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.

Files changed (59) hide show
  1. package/dist/bin/next +1 -1
  2. package/dist/build/index.js +2 -2
  3. package/dist/build/swc/index.js +1 -1
  4. package/dist/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.js +3 -3
  5. package/dist/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.js.map +1 -1
  6. package/dist/build/webpack-config.js +2 -2
  7. package/dist/client/app-bootstrap.js +1 -1
  8. package/dist/client/components/react-dev-overlay/server/{middleware.js → middleware-webpack.js} +1 -1
  9. package/dist/client/components/react-dev-overlay/server/middleware-webpack.js.map +1 -0
  10. package/dist/client/index.js +1 -1
  11. package/dist/compiled/next-server/server.runtime.prod.js.map +1 -1
  12. package/dist/esm/build/index.js +2 -2
  13. package/dist/esm/build/swc/index.js +1 -1
  14. package/dist/esm/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.js +1 -1
  15. package/dist/esm/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.js.map +1 -1
  16. package/dist/esm/build/webpack-config.js +2 -2
  17. package/dist/esm/client/app-bootstrap.js +1 -1
  18. package/dist/esm/client/components/react-dev-overlay/server/{middleware.js → middleware-webpack.js} +1 -1
  19. package/dist/esm/client/components/react-dev-overlay/server/middleware-webpack.js.map +1 -0
  20. package/dist/esm/client/index.js +1 -1
  21. package/dist/esm/server/config.js +1 -1
  22. package/dist/esm/server/dev/hot-reloader-turbopack.js +1 -1
  23. package/dist/esm/server/dev/hot-reloader-webpack.js +2 -2
  24. package/dist/esm/server/dev/hot-reloader-webpack.js.map +1 -1
  25. package/dist/esm/server/image-optimizer.js +2 -2
  26. package/dist/esm/server/image-optimizer.js.map +1 -1
  27. package/dist/esm/server/lib/app-info-log.js +1 -1
  28. package/dist/esm/server/lib/router-utils/setup-dev-bundler.js +1 -1
  29. package/dist/esm/server/lib/router-utils/setup-dev-bundler.js.map +1 -1
  30. package/dist/esm/server/lib/start-server.js +1 -1
  31. package/dist/esm/server/patch-error-inspect.js +1 -1
  32. package/dist/esm/server/patch-error-inspect.js.map +1 -1
  33. package/dist/esm/server/web/sandbox/context.js +1 -1
  34. package/dist/esm/server/web/sandbox/context.js.map +1 -1
  35. package/dist/esm/server/web/sandbox/sandbox.js +1 -1
  36. package/dist/esm/server/web/sandbox/sandbox.js.map +1 -1
  37. package/dist/server/config.js +1 -1
  38. package/dist/server/dev/hot-reloader-turbopack.js +1 -1
  39. package/dist/server/dev/hot-reloader-webpack.js +4 -4
  40. package/dist/server/dev/hot-reloader-webpack.js.map +1 -1
  41. package/dist/server/image-optimizer.js +2 -2
  42. package/dist/server/image-optimizer.js.map +1 -1
  43. package/dist/server/lib/app-info-log.js +1 -1
  44. package/dist/server/lib/router-utils/setup-dev-bundler.js +5 -5
  45. package/dist/server/lib/router-utils/setup-dev-bundler.js.map +1 -1
  46. package/dist/server/lib/start-server.js +1 -1
  47. package/dist/server/patch-error-inspect.js +2 -2
  48. package/dist/server/patch-error-inspect.js.map +1 -1
  49. package/dist/server/web/sandbox/context.js +1 -1
  50. package/dist/server/web/sandbox/context.js.map +1 -1
  51. package/dist/server/web/sandbox/sandbox.js +1 -1
  52. package/dist/server/web/sandbox/sandbox.js.map +1 -1
  53. package/dist/telemetry/anonymous-meta.js +1 -1
  54. package/dist/telemetry/events/session-stopped.js +2 -2
  55. package/dist/telemetry/events/version.js +2 -2
  56. package/package.json +15 -15
  57. package/dist/client/components/react-dev-overlay/server/middleware.js.map +0 -1
  58. package/dist/esm/client/components/react-dev-overlay/server/middleware.js.map +0 -1
  59. /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":["clearAllModuleContexts","clearModuleContext","edgeSandboxNextRequestContext","getModuleContext","requestStore","getServerError","decorateServerError","process","env","NODE_ENV","middleware","require","error","_","__","moduleContexts","Map","pendingModuleCaches","intervalsManager","removeAll","timeoutsManager","clear","path","handleContext","key","cache","context","paths","has","delete","loadWasm","wasm","modules","Promise","all","map","binding","module","WebAssembly","compile","fs","readFile","filePath","name","buildEnvironmentVariablesFrom","injectedEnvironments","pairs","Object","keys","fromEntries","NEXT_RUNTIME","throwUnsupportedAPIError","Error","COMPILER_NAMES","edgeServer","createProcessPolyfill","processPolyfill","overriddenValue","defineProperty","get","undefined","set","value","enumerable","addStub","getDecorateUnhandledError","runtime","EdgeRuntimeError","evaluate","getDecorateUnhandledRejection","rejected","reason","NativeModuleMap","mods","pick","BufferImplementation","EventsImplementation","AsyncHooksImplementation","AssertImplementation","UtilImplementation","entries","AsyncLocalStorage","createLocalRequestContext","createModuleContext","options","warnedEvals","Set","warnedWasmCodegens","edgeFunctionEntry","EdgeRuntime","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","fetchInlineAsset","assets","distDir","headers","Headers","store","getStore","prevs","split","concat","moduleName","join","response","url","String","catch","message","stack","__Request","Request","constructor","validateURL","next","__redirect","Response","redirect","bind","args","EDGE_UNSUPPORTED_NODE_APIS","assign","performance","setInterval","clearInterval","interval","remove","setTimeout","clearTimeout","timeout","NEXT_REQUEST_CONTEXT_SYMBOL","Symbol","for","decorateUnhandledError","addEventListener","decorateUnhandledRejection","getModuleContextShared","deferredModuleContext","lazyModuleContext","useCache","moduleContext","evaluateInContext","filepath","content","readFileSync","runInContext","filename"],"mappings":";;;;;;;;;;;;;;;;;;IAwDsBA,sBAAsB;eAAtBA;;IAeAC,kBAAkB;eAAlBA;;IA+KTC,6BAA6B;eAA7BA;;IAwQSC,gB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;gBACd,IAAIwE,QAAQ+E,QAAQ,EAAE;oBACpBC,iCAAAA,cAAezI,KAAK,CAACE,MAAM,CAACyI;gBAC9B;gBACA,MAAM1J;YACR;QACF;IACF;IAEA,OAAO;QAAE,GAAGwJ,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":["clearAllModuleContexts","clearModuleContext","edgeSandboxNextRequestContext","getModuleContext","requestStore","getServerError","decorateServerError","process","env","NODE_ENV","middleware","require","error","_","__","moduleContexts","Map","pendingModuleCaches","intervalsManager","removeAll","timeoutsManager","clear","path","handleContext","key","cache","context","paths","has","delete","loadWasm","wasm","modules","Promise","all","map","binding","module","WebAssembly","compile","fs","readFile","filePath","name","buildEnvironmentVariablesFrom","injectedEnvironments","pairs","Object","keys","fromEntries","NEXT_RUNTIME","throwUnsupportedAPIError","Error","COMPILER_NAMES","edgeServer","createProcessPolyfill","processPolyfill","overriddenValue","defineProperty","get","undefined","set","value","enumerable","addStub","getDecorateUnhandledError","runtime","EdgeRuntimeError","evaluate","getDecorateUnhandledRejection","rejected","reason","NativeModuleMap","mods","pick","BufferImplementation","EventsImplementation","AsyncHooksImplementation","AssertImplementation","UtilImplementation","entries","AsyncLocalStorage","createLocalRequestContext","createModuleContext","options","warnedEvals","Set","warnedWasmCodegens","edgeFunctionEntry","EdgeRuntime","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","fetchInlineAsset","assets","distDir","headers","Headers","store","getStore","prevs","split","concat","moduleName","join","response","url","String","catch","message","stack","__Request","Request","constructor","validateURL","next","__redirect","Response","redirect","bind","args","EDGE_UNSUPPORTED_NODE_APIS","assign","performance","setInterval","clearInterval","interval","remove","setTimeout","clearTimeout","timeout","NEXT_REQUEST_CONTEXT_SYMBOL","Symbol","for","decorateUnhandledError","addEventListener","decorateUnhandledRejection","getModuleContextShared","deferredModuleContext","lazyModuleContext","useCache","moduleContext","evaluateInContext","filepath","content","readFileSync","runInContext","filename"],"mappings":";;;;;;;;;;;;;;;;;;IAyDsBA,sBAAsB;eAAtBA;;IAeAC,kBAAkB;eAAlBA;;IA+KTC,6BAA6B;eAA7BA;;IAwQSC,gBAAgB;eAAhBA;;IA5QTC,YAAY;eAAZA;;;6BA7OqB;2BAI3B;6BACqB;oBACiB;uBACjB;sBACP;mCACY;oBACJ;mEACI;mEACA;mEACA;iEACF;wEACM;kCACa;uCACR;;;;;;AAQ1C,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;AAKzB,eAAehB;IACpBkB,kCAAgB,CAACC,SAAS;IAC1BC,iCAAe,CAACD,SAAS;IACzBJ,eAAeM,KAAK;IACpBJ,oBAAoBI,KAAK;AAC3B;AAUO,eAAepB,mBAAmBqB,IAAY;IACnDJ,kCAAgB,CAACC,SAAS;IAC1BC,iCAAe,CAACD,SAAS;IAEzB,MAAMI,gBAAgB,CACpBC,KACAC,OACAC;QAEA,IAAID,yBAAAA,MAAOE,KAAK,CAACC,GAAG,CAACN,OAAO;YAC1BI,QAAQG,MAAM,CAACL;QACjB;IACF;IAEA,KAAK,MAAM,CAACA,KAAKC,MAAM,IAAIV,eAAgB;QACzCQ,cAAcC,KAAKC,OAAO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IAEtB,MAAMG,oBAAoB,CAACC;QACzB,IAAI,CAACF,cAAczI,KAAK,CAACC,GAAG,CAAC0I,WAAW;YACtC,MAAMC,UAAUC,IAAAA,gBAAY,EAACF,UAAU;YACvC,IAAI;gBACFG,IAAAA,gBAAY,EAACF,SAASH,cAAclG,OAAO,CAACxC,OAAO,EAAE;oBACnDgJ,UAAUJ;gBACZ;gBACAF,cAAczI,KAAK,CAACkC,GAAG,CAACyG,UAAUC;YACpC,EAAE,OAAO3J,OAAO;gBACd,IAAIwE,QAAQ+E,QAAQ,EAAE;oBACpBC,iCAAAA,cAAezI,KAAK,CAACE,MAAM,CAACyI;gBAC9B;gBACA,MAAM1J;YACR;QACF;IACF;IAEA,OAAO;QAAE,GAAGwJ,aAAa;QAAEC;IAAkB;AAC/C"}
@@ -39,7 +39,7 @@ const FORBIDDEN_HEADERS = [
39
39
  * tagged with `edge-server` so they can properly be rendered in dev.
40
40
  */ function withTaggedErrors(fn) {
41
41
  if (process.env.NODE_ENV === 'development') {
42
- const { getServerError } = require('../../../client/components/react-dev-overlay/server/middleware');
42
+ const { getServerError } = require('../../../client/components/react-dev-overlay/server/middleware-webpack');
43
43
  return (params)=>fn(params).then((result)=>{
44
44
  var _result_waitUntil;
45
45
  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":["ErrorSource","getRuntimeContext","run","Symbol","FORBIDDEN_HEADERS","withTaggedErrors","fn","process","env","NODE_ENV","getServerError","require","params","then","result","waitUntil","catch","error","runtime","evaluateInContext","getModuleContext","moduleName","name","onWarning","onError","useCache","edgeFunctionEntry","distDir","incrementalCache","context","globalThis","__incrementalCache","serverComponentsHmrCache","__serverComponentsHmrCache","paramPath","paths","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","NEXT_RSC_UNION_QUERY","toString","Headers","key","value","Object","entries","set","builtinRequestCtx","getBuiltinRequestContext","edgeSandboxNextRequestContext","requestStore","requestToBodyStream","headerName","Error","finalize"],"mappings":";;;;;;;;;;;;;;;;IAgBaA,WAAW;eAAXA;;IAkDSC,iBAAiB;eAAjBA;;IA2BTC,GAAG;eAAHA;;;yBAtFN;6BAC6B;kCACC;uCAK9B;AAEA,MAAMF,cAAcG,OAAO;AAElC,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,+CAA+C;gBAC/C,MAAMP,eAAeO,OAAO;YAC9B;IACN;IAEA,OAAOX;AACT;AAEO,eAAeL,kBACpBW,MAAuC;IAEvC,MAAM,EAAEM,OAAO,EAAEC,iBAAiB,EAAE,GAAG,MAAMC,IAAAA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QAGF,IAAI,CAAClE,QAAQ,MAAM,IAAImE,MAAM;QAC7B,OAAOnE;IACT,SAAU;YACFF;QAAN,QAAMA,wBAAAA,OAAO0B,OAAO,CAACmB,IAAI,qBAAnB7C,sBAAqBsE,QAAQ;IACrC;AACF"}
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":["ErrorSource","getRuntimeContext","run","Symbol","FORBIDDEN_HEADERS","withTaggedErrors","fn","process","env","NODE_ENV","getServerError","require","params","then","result","waitUntil","catch","error","runtime","evaluateInContext","getModuleContext","moduleName","name","onWarning","onError","useCache","edgeFunctionEntry","distDir","incrementalCache","context","globalThis","__incrementalCache","serverComponentsHmrCache","__serverComponentsHmrCache","paramPath","paths","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","NEXT_RSC_UNION_QUERY","toString","Headers","key","value","Object","entries","set","builtinRequestCtx","getBuiltinRequestContext","edgeSandboxNextRequestContext","requestStore","requestToBodyStream","headerName","Error","finalize"],"mappings":";;;;;;;;;;;;;;;;IAgBaA,WAAW;eAAXA;;IAkDSC,iBAAiB;eAAjBA;;IA2BTC,GAAG;eAAHA;;;yBAtFN;6BAC6B;kCACC;uCAK9B;AAEA,MAAMF,cAAcG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BAAAA,MAAOH,QAAQ,OAAM;IACxC;IAEA,IAAI;QACF,IAAItD,SAAuC6C;QAC3C,MAAMgB,oBAAgD;YACpD,GAAGC,IAAAA,+CAAwB,GAAE;YAC7B,gBAAgB;YAChB,2DAA2D;YAC3D,wGAAwG;YACxG,4GAA4G;YAC5G7D,WAAWH,OAAO0B,OAAO,CAACvB,SAAS;QACrC;QACA,MAAM8D,sCAA6B,CAAC3E,GAAG,CAACyE,mBAAmB,IACzDG,qBAAY,CAAC5E,GAAG,CAAC;gBAAEqC;YAAQ,GAAG;gBAC5BzB,SAAS,MAAMqC,aAAa;oBAC1Bb,SAAS;wBACP,GAAG1B,OAAO0B,OAAO;wBACjBmB,MACEH,UACAyB,IAAAA,gCAAmB,EAAC7D,QAAQW,OAAO,EAAE+B,aAAaN;oBACtD;gBACF;gBACA,KAAK,MAAM0B,cAAc5E,kBAAmB;oBAC1CU,OAAOmC,QAAQ,CAACV,OAAO,CAAC2B,MAAM,CAACc;gBACjC;YACF;QAGF,IAAI,CAAClE,QAAQ,MAAM,IAAImE,MAAM;QAC7B,OAAOnE;IACT,SAAU;YACFF;QAAN,QAAMA,wBAAAA,OAAO0B,OAAO,CAACmB,IAAI,qBAAnB7C,sBAAqBsE,QAAQ;IACrC;AACF"}
@@ -81,7 +81,7 @@ function getAnonymousMeta() {
81
81
  isWsl: _iswsl.default,
82
82
  isCI: _ciinfo.isCI,
83
83
  ciName: _ciinfo.isCI && _ciinfo.name || null,
84
- nextVersion: "15.0.4-canary.23"
84
+ nextVersion: "15.0.4-canary.24"
85
85
  };
86
86
  return traits;
87
87
  }
@@ -11,11 +11,11 @@ Object.defineProperty(exports, "eventCliSessionStopped", {
11
11
  const EVENT_VERSION = 'NEXT_CLI_SESSION_STOPPED';
12
12
  function eventCliSessionStopped(event) {
13
13
  // This should be an invariant, if it fails our build tooling is broken.
14
- if (typeof "15.0.4-canary.23" !== 'string') {
14
+ if (typeof "15.0.4-canary.24" !== 'string') {
15
15
  return [];
16
16
  }
17
17
  const payload = {
18
- nextVersion: "15.0.4-canary.23",
18
+ nextVersion: "15.0.4-canary.24",
19
19
  nodeVersion: process.version,
20
20
  cliCommand: event.cliCommand,
21
21
  durationMilliseconds: event.durationMilliseconds,
@@ -36,12 +36,12 @@ function hasBabelConfig(dir) {
36
36
  function eventCliSession(dir, nextConfig, event) {
37
37
  var _nextConfig_experimental_staleTimes, _nextConfig_experimental_staleTimes1, _nextConfig_experimental_reactCompiler, _nextConfig_experimental_reactCompiler1;
38
38
  // This should be an invariant, if it fails our build tooling is broken.
39
- if (typeof "15.0.4-canary.23" !== 'string') {
39
+ if (typeof "15.0.4-canary.24" !== 'string') {
40
40
  return [];
41
41
  }
42
42
  const { images, i18n } = nextConfig || {};
43
43
  const payload = {
44
- nextVersion: "15.0.4-canary.23",
44
+ nextVersion: "15.0.4-canary.24",
45
45
  nodeVersion: process.version,
46
46
  cliCommand: event.cliCommand,
47
47
  isSrcDir: event.isSrcDir,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next",
3
- "version": "15.0.4-canary.23",
3
+ "version": "15.0.4-canary.24",
4
4
  "description": "The React Framework",
5
5
  "main": "./dist/server/next.js",
6
6
  "license": "MIT",
@@ -97,7 +97,7 @@
97
97
  ]
98
98
  },
99
99
  "dependencies": {
100
- "@next/env": "15.0.4-canary.23",
100
+ "@next/env": "15.0.4-canary.24",
101
101
  "@swc/counter": "0.1.3",
102
102
  "@swc/helpers": "0.5.13",
103
103
  "busboy": "1.6.0",
@@ -129,14 +129,14 @@
129
129
  },
130
130
  "optionalDependencies": {
131
131
  "sharp": "^0.33.5",
132
- "@next/swc-darwin-arm64": "15.0.4-canary.23",
133
- "@next/swc-darwin-x64": "15.0.4-canary.23",
134
- "@next/swc-linux-arm64-gnu": "15.0.4-canary.23",
135
- "@next/swc-linux-arm64-musl": "15.0.4-canary.23",
136
- "@next/swc-linux-x64-gnu": "15.0.4-canary.23",
137
- "@next/swc-linux-x64-musl": "15.0.4-canary.23",
138
- "@next/swc-win32-arm64-msvc": "15.0.4-canary.23",
139
- "@next/swc-win32-x64-msvc": "15.0.4-canary.23"
132
+ "@next/swc-darwin-arm64": "15.0.4-canary.24",
133
+ "@next/swc-darwin-x64": "15.0.4-canary.24",
134
+ "@next/swc-linux-arm64-gnu": "15.0.4-canary.24",
135
+ "@next/swc-linux-arm64-musl": "15.0.4-canary.24",
136
+ "@next/swc-linux-x64-gnu": "15.0.4-canary.24",
137
+ "@next/swc-linux-x64-musl": "15.0.4-canary.24",
138
+ "@next/swc-win32-arm64-msvc": "15.0.4-canary.24",
139
+ "@next/swc-win32-x64-msvc": "15.0.4-canary.24"
140
140
  },
141
141
  "devDependencies": {
142
142
  "@ampproject/toolbox-optimizer": "2.8.3",
@@ -169,11 +169,11 @@
169
169
  "@jest/types": "29.5.0",
170
170
  "@mswjs/interceptors": "0.23.0",
171
171
  "@napi-rs/triples": "1.2.0",
172
- "@next/font": "15.0.4-canary.23",
173
- "@next/polyfill-module": "15.0.4-canary.23",
174
- "@next/polyfill-nomodule": "15.0.4-canary.23",
175
- "@next/react-refresh-utils": "15.0.4-canary.23",
176
- "@next/swc": "15.0.4-canary.23",
172
+ "@next/font": "15.0.4-canary.24",
173
+ "@next/polyfill-module": "15.0.4-canary.24",
174
+ "@next/polyfill-nomodule": "15.0.4-canary.24",
175
+ "@next/react-refresh-utils": "15.0.4-canary.24",
176
+ "@next/swc": "15.0.4-canary.24",
177
177
  "@opentelemetry/api": "1.6.0",
178
178
  "@playwright/test": "1.41.2",
179
179
  "@swc/core": "1.9.2-nightly-20241111.1",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/server/middleware.ts"],"sourcesContent":["import { constants as FS, promises as fs } from 'fs'\nimport path from 'path'\nimport url from 'url'\nimport { SourceMapConsumer } from 'next/dist/compiled/source-map08'\nimport type { StackFrame } from 'next/dist/compiled/stacktrace-parser'\nimport { getSourceMapFromFile } from '../internal/helpers/get-source-map-from-file'\nimport { launchEditor } from '../internal/helpers/launchEditor'\nimport {\n badRequest,\n findSourcePackage,\n getOriginalCodeFrame,\n internalServerError,\n json,\n noContent,\n type OriginalStackFrameResponse,\n} from './shared'\nimport { NEXT_PROJECT_ROOT } from '../../../../build/next-dir-paths'\nexport { getServerError } from '../internal/helpers/node-stack-frames'\nexport { parseStack } from '../internal/helpers/parse-stack'\nexport { getSourceMapFromFile }\n\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type webpack from 'webpack'\nimport type {\n NullableMappedPosition,\n RawSourceMap,\n} from 'next/dist/compiled/source-map08'\nimport { formatFrameSourceFile } from '../internal/helpers/webpack-module-path'\nimport type { MappedPosition } from 'source-map'\n\nfunction shouldIgnorePath(modulePath: string): boolean {\n return (\n modulePath.includes('node_modules') ||\n // Only relevant for when Next.js is symlinked e.g. in the Next.js monorepo\n modulePath.includes('next/dist')\n )\n}\n\ntype IgnoredSources = Array<{ url: string; ignored: boolean }>\n\nexport interface IgnorableStackFrame extends StackFrame {\n ignored: boolean\n}\n\ntype SourceAttributes = {\n sourcePosition: NullableMappedPosition\n sourceContent: string | null\n}\n\ntype Source =\n | {\n type: 'file'\n sourceMap: RawSourceMap\n ignoredSources: IgnoredSources\n modulePath: string\n }\n | {\n type: 'bundle'\n sourceMap: RawSourceMap\n ignoredSources: IgnoredSources\n compilation: webpack.Compilation\n moduleId: string\n modulePath: string\n }\n\nfunction getModuleById(\n id: string | undefined,\n compilation: webpack.Compilation\n) {\n const { chunkGraph, modules } = compilation\n\n return [...modules].find((module) => chunkGraph.getModuleId(module) === id)\n}\n\nfunction findModuleNotFoundFromError(errorMessage: string | undefined) {\n return errorMessage?.match(/'([^']+)' module/)?.[1]\n}\n\nfunction getSourcePath(source: string) {\n return source.replace(/^(webpack:\\/\\/\\/|webpack:\\/\\/|webpack:\\/\\/_N_E\\/)/, '')\n}\n\nasync function findOriginalSourcePositionAndContent(\n sourceMap: RawSourceMap,\n position: { line: number; column: number | null }\n): Promise<SourceAttributes | null> {\n const consumer = await new SourceMapConsumer(sourceMap)\n try {\n const sourcePosition = consumer.originalPositionFor({\n line: position.line,\n column: position.column ?? 0,\n })\n\n if (!sourcePosition.source) {\n return null\n }\n\n const sourceContent: string | null =\n consumer.sourceContentFor(\n sourcePosition.source,\n /* returnNullOnMissing */ true\n ) ?? null\n\n return {\n sourcePosition,\n sourceContent,\n }\n } finally {\n consumer.destroy()\n }\n}\n\nexport function getIgnoredSources(sourceMap: RawSourceMap): IgnoredSources {\n const ignoreList = new Set<number>()\n const moduleFilenames = sourceMap?.sources ?? []\n\n for (let index = 0; index < moduleFilenames.length; index++) {\n // bundlerFilePath case: webpack://./app/page.tsx\n const bundlerFilePath = moduleFilenames[index]\n // Format the path to the normal file path\n const formattedFilePath = formatFrameSourceFile(bundlerFilePath)\n if (shouldIgnorePath(formattedFilePath)) {\n ignoreList.add(index)\n }\n }\n\n const ignoredSources = sourceMap.sources.map((source, index) => {\n return {\n url: source,\n ignored: ignoreList.has(sourceMap.sources.indexOf(source)),\n content: sourceMap.sourcesContent?.[index] ?? null,\n }\n })\n return ignoredSources\n}\n\nfunction isIgnoredSource(\n source: Source,\n sourcePosition: MappedPosition | NullableMappedPosition\n) {\n if (sourcePosition.source == null) {\n return true\n }\n for (const ignoredSource of source.ignoredSources) {\n if (ignoredSource.ignored && ignoredSource.url === sourcePosition.source) {\n return true\n }\n }\n\n return false\n}\n\nfunction createStackFrame(searchParams: URLSearchParams) {\n const file = searchParams.get('file') as string\n return {\n file,\n methodName: searchParams.get('methodName') as string,\n lineNumber: parseInt(searchParams.get('lineNumber') ?? '0', 10) || 0,\n column: parseInt(searchParams.get('column') ?? '0', 10) || 0,\n arguments: searchParams.getAll('arguments').filter(Boolean),\n } satisfies StackFrame\n}\n\nfunction findOriginalSourcePositionAndContentFromCompilation(\n moduleId: string | undefined,\n importedModule: string,\n compilation: webpack.Compilation\n): SourceAttributes | null {\n const module = getModuleById(moduleId, compilation)\n return module?.buildInfo?.importLocByPath?.get(importedModule) ?? null\n}\n\nexport async function createOriginalStackFrame({\n source,\n rootDirectory,\n frame,\n errorMessage,\n}: {\n source: Source\n rootDirectory: string\n frame: StackFrame\n errorMessage?: string\n}): Promise<OriginalStackFrameResponse | null> {\n const { lineNumber, column } = frame\n const moduleNotFound = findModuleNotFoundFromError(errorMessage)\n const result = await (async () => {\n if (moduleNotFound) {\n if (source.type === 'file') {\n return undefined\n }\n\n return findOriginalSourcePositionAndContentFromCompilation(\n source.moduleId,\n moduleNotFound,\n source.compilation\n )\n }\n // This returns 1-based lines and 0-based columns\n return await findOriginalSourcePositionAndContent(source.sourceMap, {\n line: lineNumber ?? 1,\n column,\n })\n })()\n\n if (!result) {\n return null\n }\n const { sourcePosition, sourceContent } = result\n\n if (!sourcePosition.source) {\n return null\n }\n\n const ignored =\n isIgnoredSource(source, sourcePosition) ||\n // If the source file is externals, should be excluded even it's not ignored source.\n // e.g. webpack://next/dist/.. needs to be ignored\n shouldIgnorePath(source.modulePath)\n\n const sourcePath = getSourcePath(\n // When sourcePosition.source is the loader path the modulePath is generally better.\n (sourcePosition.source!.includes('|')\n ? source.modulePath\n : sourcePosition.source) || source.modulePath\n )\n const filePath = path.resolve(rootDirectory, sourcePath)\n\n const resolvedFilePath = sourceContent\n ? path.relative(rootDirectory, filePath)\n : sourcePosition.source\n\n const traced: IgnorableStackFrame = {\n file: resolvedFilePath,\n lineNumber: sourcePosition.line,\n column: (sourcePosition.column ?? 0) + 1,\n methodName:\n sourcePosition.name ||\n // default is not a valid identifier in JS so webpack uses a custom variable when it's an unnamed default export\n // Resolve it back to `default` for the method name if the source position didn't have the method.\n frame.methodName\n ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n ?.replace('__webpack_exports__.', ''),\n arguments: [],\n ignored,\n }\n\n return {\n originalStackFrame: traced,\n originalCodeFrame: getOriginalCodeFrame(traced, sourceContent),\n sourcePackage: findSourcePackage(traced),\n }\n}\n\nexport async function getSourceMapFromCompilation(\n id: string,\n compilation: webpack.Compilation\n): Promise<RawSourceMap | undefined> {\n try {\n const module = getModuleById(id, compilation)\n\n if (!module) {\n return undefined\n }\n\n // @ts-expect-error The types for `CodeGenerationResults.get` require a\n // runtime to be passed as second argument, but apparently it also works\n // without it.\n const codeGenerationResult = compilation.codeGenerationResults.get(module)\n const source = codeGenerationResult?.sources.get('javascript')\n\n return source?.map() ?? undefined\n } catch (err) {\n console.error(`Failed to lookup module by ID (\"${id}\"):`, err)\n return undefined\n }\n}\n\nasync function getSource(\n filename: string,\n options: {\n getCompilations: () => webpack.Compilation[]\n }\n): Promise<Source | undefined> {\n const { getCompilations } = options\n\n if (path.isAbsolute(filename)) {\n filename = url.pathToFileURL(filename).href\n }\n\n if (filename.startsWith('file:')) {\n const sourceMap = await getSourceMapFromFile(filename)\n return sourceMap\n ? {\n type: 'file',\n sourceMap,\n ignoredSources: getIgnoredSources(sourceMap),\n modulePath: filename.replace(/^file:\\/\\//, ''),\n }\n : undefined\n }\n\n // webpack-internal:///./src/hello.tsx => ./src/hello.tsx\n // rsc://React/Server/webpack-internal:///(rsc)/./src/hello.tsx?42 => (rsc)/./src/hello.tsx\n // webpack://_N_E/./src/hello.tsx => ./src/hello.tsx\n const moduleId = filename\n .replace(\n /^(rsc:\\/\\/React\\/[^/]+\\/)?(webpack-internal:\\/\\/\\/|webpack:\\/\\/(_N_E\\/)?)/,\n ''\n )\n .replace(/\\?\\d+$/, '')\n\n // (rsc)/./src/hello.tsx => ./src/hello.tsx\n const modulePath = moduleId.replace(/^(\\(.*\\)\\/?)/, '')\n\n for (const compilation of getCompilations()) {\n // TODO: `ignoreList`\n const sourceMap = await getSourceMapFromCompilation(moduleId, compilation)\n const ignoreList = []\n const moduleFilenames = sourceMap?.sources ?? []\n\n for (let index = 0; index < moduleFilenames.length; index++) {\n // bundlerFilePath case: webpack://./app/page.tsx\n const bundlerFilePath = moduleFilenames[index]\n // Format the path to the normal file path\n const formattedFilePath = formatFrameSourceFile(bundlerFilePath)\n if (shouldIgnorePath(formattedFilePath)) {\n ignoreList.push(index)\n }\n }\n\n if (sourceMap) {\n const ignoredSources = getIgnoredSources(sourceMap)\n return {\n type: 'bundle',\n sourceMap,\n compilation,\n moduleId,\n modulePath,\n ignoredSources,\n }\n }\n }\n\n return undefined\n}\n\nexport function getOverlayMiddleware(options: {\n rootDirectory: string\n clientStats: () => webpack.Stats | null\n serverStats: () => webpack.Stats | null\n edgeServerStats: () => webpack.Stats | null\n}) {\n const { rootDirectory, clientStats, serverStats, edgeServerStats } = options\n\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(`http://n${req.url}`)\n\n if (pathname === '/__nextjs_original-stack-frame') {\n const isServer = searchParams.get('isServer') === 'true'\n const isEdgeServer = searchParams.get('isEdgeServer') === 'true'\n const isAppDirectory = searchParams.get('isAppDirectory') === 'true'\n const frame = createStackFrame(searchParams)\n const formattedFilePath = formatFrameSourceFile(frame.file)\n const filePath = path.join(rootDirectory, formattedFilePath)\n const isNextjsSource = filePath.startsWith(NEXT_PROJECT_ROOT)\n\n let sourcePackage = findSourcePackage(frame)\n let source: Source | undefined\n\n if (isNextjsSource) {\n sourcePackage = 'next'\n return json(res, { sourcePackage })\n }\n\n try {\n source = await getSource(frame.file, {\n getCompilations: () => {\n const compilations: webpack.Compilation[] = []\n\n // Try Client Compilation first. In `pages` we leverage\n // `isClientError` to check. In `app` it depends on if it's a server\n // / client component and when the code throws. E.g. during HTML\n // rendering it's the server/edge compilation.\n if ((!isEdgeServer && !isServer) || isAppDirectory) {\n const compilation = clientStats()?.compilation\n\n if (compilation) {\n compilations.push(compilation)\n }\n }\n\n // Try Server Compilation. In `pages` this could be something\n // imported in getServerSideProps/getStaticProps as the code for\n // those is tree-shaken. In `app` this finds server components and\n // code that was imported from a server component. It also covers\n // when client component code throws during HTML rendering.\n if (isServer || isAppDirectory) {\n const compilation = serverStats()?.compilation\n\n if (compilation) {\n compilations.push(compilation)\n }\n }\n\n // Try Edge Server Compilation. Both cases are the same as Server\n // Compilation, main difference is that it covers `runtime: 'edge'`\n // pages/app routes.\n if (isEdgeServer || isAppDirectory) {\n const compilation = edgeServerStats()?.compilation\n\n if (compilation) {\n compilations.push(compilation)\n }\n }\n\n return compilations\n },\n })\n } catch (err) {\n console.error('Failed to get source map:', err)\n return internalServerError(res)\n }\n\n if (!source) {\n if (sourcePackage) return json(res, { sourcePackage })\n return noContent(res)\n }\n\n try {\n const originalStackFrameResponse = await createOriginalStackFrame({\n frame,\n source,\n rootDirectory,\n })\n\n if (!originalStackFrameResponse) {\n if (sourcePackage) return json(res, { sourcePackage })\n return noContent(res)\n }\n\n return json(res, originalStackFrameResponse)\n } catch (err) {\n console.log('Failed to parse source map:', err)\n return internalServerError(res)\n }\n } else if (pathname === '/__nextjs_launch-editor') {\n const frame = createStackFrame(searchParams)\n\n if (!frame.file) return badRequest(res)\n\n // frame files may start with their webpack layer, like (middleware)/middleware.js\n const filePath = path.resolve(\n rootDirectory,\n frame.file.replace(/^\\([^)]+\\)\\//, '')\n )\n const fileExists = await fs.access(filePath, FS.F_OK).then(\n () => true,\n () => false\n )\n if (!fileExists) return noContent(res)\n\n try {\n await launchEditor(filePath, frame.lineNumber, frame.column ?? 1)\n } catch (err) {\n console.log('Failed to launch editor:', err)\n return internalServerError(res)\n }\n\n return noContent(res)\n }\n\n return next()\n }\n}\n\nexport function getSourceMapMiddleware(options: {\n clientStats: () => webpack.Stats | null\n serverStats: () => webpack.Stats | null\n edgeServerStats: () => webpack.Stats | null\n}) {\n const { clientStats, serverStats, edgeServerStats } = options\n\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(`http://n${req.url}`)\n\n if (pathname !== '/__nextjs_source-map') {\n return next()\n }\n\n const filename = searchParams.get('filename')\n\n if (!filename) {\n return badRequest(res)\n }\n\n let source: Source | undefined\n\n try {\n source = await getSource(filename, {\n getCompilations: () => {\n const compilations: webpack.Compilation[] = []\n\n for (const stats of [\n clientStats(),\n serverStats(),\n edgeServerStats(),\n ]) {\n if (stats?.compilation) {\n compilations.push(stats.compilation)\n }\n }\n\n return compilations\n },\n })\n } catch (error) {\n console.error('Failed to get source map:', error)\n\n return internalServerError(res)\n }\n\n if (!source) {\n return noContent(res)\n }\n\n return json(res, source.sourceMap)\n }\n}\n"],"names":["createOriginalStackFrame","getIgnoredSources","getOverlayMiddleware","getServerError","getSourceMapFromCompilation","getSourceMapFromFile","getSourceMapMiddleware","parseStack","shouldIgnorePath","modulePath","includes","getModuleById","id","compilation","chunkGraph","modules","find","module","getModuleId","findModuleNotFoundFromError","errorMessage","match","getSourcePath","source","replace","findOriginalSourcePositionAndContent","sourceMap","position","consumer","SourceMapConsumer","sourcePosition","originalPositionFor","line","column","sourceContent","sourceContentFor","destroy","ignoreList","Set","moduleFilenames","sources","index","length","bundlerFilePath","formattedFilePath","formatFrameSourceFile","add","ignoredSources","map","url","ignored","has","indexOf","content","sourcesContent","isIgnoredSource","ignoredSource","createStackFrame","searchParams","file","get","methodName","lineNumber","parseInt","arguments","getAll","filter","Boolean","findOriginalSourcePositionAndContentFromCompilation","moduleId","importedModule","buildInfo","importLocByPath","rootDirectory","frame","moduleNotFound","result","type","undefined","sourcePath","filePath","path","resolve","resolvedFilePath","relative","traced","name","originalStackFrame","originalCodeFrame","getOriginalCodeFrame","sourcePackage","findSourcePackage","codeGenerationResult","codeGenerationResults","err","console","error","getSource","filename","options","getCompilations","isAbsolute","pathToFileURL","href","startsWith","push","clientStats","serverStats","edgeServerStats","req","res","next","pathname","URL","isServer","isEdgeServer","isAppDirectory","join","isNextjsSource","NEXT_PROJECT_ROOT","json","compilations","internalServerError","noContent","originalStackFrameResponse","log","badRequest","fileExists","fs","access","FS","F_OK","then","launchEditor","stats"],"mappings":";;;;;;;;;;;;;;;;;;;;;IA4KsBA,wBAAwB;eAAxBA;;IA5DNC,iBAAiB;eAAjBA;;IA0OAC,oBAAoB;eA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E,OAAOzB,OAAO;YACdD,QAAQC,KAAK,CAAC,6BAA6BA;YAE3C,OAAO0B,IAAAA,2BAAmB,EAACZ;QAC7B;QAEA,IAAI,CAACvF,QAAQ;YACX,OAAOoG,IAAAA,iBAAS,EAACb;QACnB;QAEA,OAAOU,IAAAA,YAAI,EAACV,KAAKvF,OAAOG,SAAS;IACnC;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../../src/client/components/react-dev-overlay/server/middleware.ts"],"sourcesContent":["import { constants as FS, promises as fs } from 'fs'\nimport path from 'path'\nimport url from 'url'\nimport { SourceMapConsumer } from 'next/dist/compiled/source-map08'\nimport type { StackFrame } from 'next/dist/compiled/stacktrace-parser'\nimport { getSourceMapFromFile } from '../internal/helpers/get-source-map-from-file'\nimport { launchEditor } from '../internal/helpers/launchEditor'\nimport {\n badRequest,\n findSourcePackage,\n getOriginalCodeFrame,\n internalServerError,\n json,\n noContent,\n type OriginalStackFrameResponse,\n} from './shared'\nimport { NEXT_PROJECT_ROOT } from '../../../../build/next-dir-paths'\nexport { getServerError } from '../internal/helpers/node-stack-frames'\nexport { parseStack } from '../internal/helpers/parse-stack'\nexport { getSourceMapFromFile }\n\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type webpack from 'webpack'\nimport type {\n NullableMappedPosition,\n RawSourceMap,\n} from 'next/dist/compiled/source-map08'\nimport { formatFrameSourceFile } from '../internal/helpers/webpack-module-path'\nimport type { MappedPosition } from 'source-map'\n\nfunction shouldIgnorePath(modulePath: string): boolean {\n return (\n modulePath.includes('node_modules') ||\n // Only relevant for when Next.js is symlinked e.g. in the Next.js monorepo\n modulePath.includes('next/dist')\n )\n}\n\ntype IgnoredSources = Array<{ url: string; ignored: boolean }>\n\nexport interface IgnorableStackFrame extends StackFrame {\n ignored: boolean\n}\n\ntype SourceAttributes = {\n sourcePosition: NullableMappedPosition\n sourceContent: string | null\n}\n\ntype Source =\n | {\n type: 'file'\n sourceMap: RawSourceMap\n ignoredSources: IgnoredSources\n modulePath: string\n }\n | {\n type: 'bundle'\n sourceMap: RawSourceMap\n ignoredSources: IgnoredSources\n compilation: webpack.Compilation\n moduleId: string\n modulePath: string\n }\n\nfunction getModuleById(\n id: string | undefined,\n compilation: webpack.Compilation\n) {\n const { chunkGraph, modules } = compilation\n\n return [...modules].find((module) => chunkGraph.getModuleId(module) === id)\n}\n\nfunction findModuleNotFoundFromError(errorMessage: string | undefined) {\n return errorMessage?.match(/'([^']+)' module/)?.[1]\n}\n\nfunction getSourcePath(source: string) {\n return source.replace(/^(webpack:\\/\\/\\/|webpack:\\/\\/|webpack:\\/\\/_N_E\\/)/, '')\n}\n\nasync function findOriginalSourcePositionAndContent(\n sourceMap: RawSourceMap,\n position: { line: number; column: number | null }\n): Promise<SourceAttributes | null> {\n const consumer = await new SourceMapConsumer(sourceMap)\n try {\n const sourcePosition = consumer.originalPositionFor({\n line: position.line,\n column: position.column ?? 0,\n })\n\n if (!sourcePosition.source) {\n return null\n }\n\n const sourceContent: string | null =\n consumer.sourceContentFor(\n sourcePosition.source,\n /* returnNullOnMissing */ true\n ) ?? null\n\n return {\n sourcePosition,\n sourceContent,\n }\n } finally {\n consumer.destroy()\n }\n}\n\nexport function getIgnoredSources(sourceMap: RawSourceMap): IgnoredSources {\n const ignoreList = new Set<number>()\n const moduleFilenames = sourceMap?.sources ?? []\n\n for (let index = 0; index < moduleFilenames.length; index++) {\n // bundlerFilePath case: webpack://./app/page.tsx\n const bundlerFilePath = moduleFilenames[index]\n // Format the path to the normal file path\n const formattedFilePath = formatFrameSourceFile(bundlerFilePath)\n if (shouldIgnorePath(formattedFilePath)) {\n ignoreList.add(index)\n }\n }\n\n const ignoredSources = sourceMap.sources.map((source, index) => {\n return {\n url: source,\n ignored: ignoreList.has(sourceMap.sources.indexOf(source)),\n content: sourceMap.sourcesContent?.[index] ?? null,\n }\n })\n return ignoredSources\n}\n\nfunction isIgnoredSource(\n source: Source,\n sourcePosition: MappedPosition | NullableMappedPosition\n) {\n if (sourcePosition.source == null) {\n return true\n }\n for (const ignoredSource of source.ignoredSources) {\n if (ignoredSource.ignored && ignoredSource.url === sourcePosition.source) {\n return true\n }\n }\n\n return false\n}\n\nfunction createStackFrame(searchParams: URLSearchParams) {\n const file = searchParams.get('file') as string\n return {\n file,\n methodName: searchParams.get('methodName') as string,\n lineNumber: parseInt(searchParams.get('lineNumber') ?? '0', 10) || 0,\n column: parseInt(searchParams.get('column') ?? '0', 10) || 0,\n arguments: searchParams.getAll('arguments').filter(Boolean),\n } satisfies StackFrame\n}\n\nfunction findOriginalSourcePositionAndContentFromCompilation(\n moduleId: string | undefined,\n importedModule: string,\n compilation: webpack.Compilation\n): SourceAttributes | null {\n const module = getModuleById(moduleId, compilation)\n return module?.buildInfo?.importLocByPath?.get(importedModule) ?? null\n}\n\nexport async function createOriginalStackFrame({\n source,\n rootDirectory,\n frame,\n errorMessage,\n}: {\n source: Source\n rootDirectory: string\n frame: StackFrame\n errorMessage?: string\n}): Promise<OriginalStackFrameResponse | null> {\n const { lineNumber, column } = frame\n const moduleNotFound = findModuleNotFoundFromError(errorMessage)\n const result = await (async () => {\n if (moduleNotFound) {\n if (source.type === 'file') {\n return undefined\n }\n\n return findOriginalSourcePositionAndContentFromCompilation(\n source.moduleId,\n moduleNotFound,\n source.compilation\n )\n }\n // This returns 1-based lines and 0-based columns\n return await findOriginalSourcePositionAndContent(source.sourceMap, {\n line: lineNumber ?? 1,\n column,\n })\n })()\n\n if (!result) {\n return null\n }\n const { sourcePosition, sourceContent } = result\n\n if (!sourcePosition.source) {\n return null\n }\n\n const ignored =\n isIgnoredSource(source, sourcePosition) ||\n // If the source file is externals, should be excluded even it's not ignored source.\n // e.g. webpack://next/dist/.. needs to be ignored\n shouldIgnorePath(source.modulePath)\n\n const sourcePath = getSourcePath(\n // When sourcePosition.source is the loader path the modulePath is generally better.\n (sourcePosition.source!.includes('|')\n ? source.modulePath\n : sourcePosition.source) || source.modulePath\n )\n const filePath = path.resolve(rootDirectory, sourcePath)\n\n const resolvedFilePath = sourceContent\n ? path.relative(rootDirectory, filePath)\n : sourcePosition.source\n\n const traced: IgnorableStackFrame = {\n file: resolvedFilePath,\n lineNumber: sourcePosition.line,\n column: (sourcePosition.column ?? 0) + 1,\n methodName:\n sourcePosition.name ||\n // default is not a valid identifier in JS so webpack uses a custom variable when it's an unnamed default export\n // Resolve it back to `default` for the method name if the source position didn't have the method.\n frame.methodName\n ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n ?.replace('__webpack_exports__.', ''),\n arguments: [],\n ignored,\n }\n\n return {\n originalStackFrame: traced,\n originalCodeFrame: getOriginalCodeFrame(traced, sourceContent),\n sourcePackage: findSourcePackage(traced),\n }\n}\n\nexport async function getSourceMapFromCompilation(\n id: string,\n compilation: webpack.Compilation\n): Promise<RawSourceMap | undefined> {\n try {\n const module = getModuleById(id, compilation)\n\n if (!module) {\n return undefined\n }\n\n // @ts-expect-error The types for `CodeGenerationResults.get` require a\n // runtime to be passed as second argument, but apparently it also works\n // without it.\n const codeGenerationResult = compilation.codeGenerationResults.get(module)\n const source = codeGenerationResult?.sources.get('javascript')\n\n return source?.map() ?? undefined\n } catch (err) {\n console.error(`Failed to lookup module by ID (\"${id}\"):`, err)\n return undefined\n }\n}\n\nasync function getSource(\n filename: string,\n options: {\n getCompilations: () => webpack.Compilation[]\n }\n): Promise<Source | undefined> {\n const { getCompilations } = options\n\n if (path.isAbsolute(filename)) {\n filename = url.pathToFileURL(filename).href\n }\n\n if (filename.startsWith('file:')) {\n const sourceMap = await getSourceMapFromFile(filename)\n return sourceMap\n ? {\n type: 'file',\n sourceMap,\n ignoredSources: getIgnoredSources(sourceMap),\n modulePath: filename.replace(/^file:\\/\\//, ''),\n }\n : undefined\n }\n\n // webpack-internal:///./src/hello.tsx => ./src/hello.tsx\n // rsc://React/Server/webpack-internal:///(rsc)/./src/hello.tsx?42 => (rsc)/./src/hello.tsx\n // webpack://_N_E/./src/hello.tsx => ./src/hello.tsx\n const moduleId = filename\n .replace(\n /^(rsc:\\/\\/React\\/[^/]+\\/)?(webpack-internal:\\/\\/\\/|webpack:\\/\\/(_N_E\\/)?)/,\n ''\n )\n .replace(/\\?\\d+$/, '')\n\n // (rsc)/./src/hello.tsx => ./src/hello.tsx\n const modulePath = moduleId.replace(/^(\\(.*\\)\\/?)/, '')\n\n for (const compilation of getCompilations()) {\n // TODO: `ignoreList`\n const sourceMap = await getSourceMapFromCompilation(moduleId, compilation)\n const ignoreList = []\n const moduleFilenames = sourceMap?.sources ?? []\n\n for (let index = 0; index < moduleFilenames.length; index++) {\n // bundlerFilePath case: webpack://./app/page.tsx\n const bundlerFilePath = moduleFilenames[index]\n // Format the path to the normal file path\n const formattedFilePath = formatFrameSourceFile(bundlerFilePath)\n if (shouldIgnorePath(formattedFilePath)) {\n ignoreList.push(index)\n }\n }\n\n if (sourceMap) {\n const ignoredSources = getIgnoredSources(sourceMap)\n return {\n type: 'bundle',\n sourceMap,\n compilation,\n moduleId,\n modulePath,\n ignoredSources,\n }\n }\n }\n\n return undefined\n}\n\nexport function getOverlayMiddleware(options: {\n rootDirectory: string\n clientStats: () => webpack.Stats | null\n serverStats: () => webpack.Stats | null\n edgeServerStats: () => webpack.Stats | null\n}) {\n const { rootDirectory, clientStats, serverStats, edgeServerStats } = options\n\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(`http://n${req.url}`)\n\n if (pathname === '/__nextjs_original-stack-frame') {\n const isServer = searchParams.get('isServer') === 'true'\n const isEdgeServer = searchParams.get('isEdgeServer') === 'true'\n const isAppDirectory = searchParams.get('isAppDirectory') === 'true'\n const frame = createStackFrame(searchParams)\n const formattedFilePath = formatFrameSourceFile(frame.file)\n const filePath = path.join(rootDirectory, formattedFilePath)\n const isNextjsSource = filePath.startsWith(NEXT_PROJECT_ROOT)\n\n let sourcePackage = findSourcePackage(frame)\n let source: Source | undefined\n\n if (isNextjsSource) {\n sourcePackage = 'next'\n return json(res, { sourcePackage })\n }\n\n try {\n source = await getSource(frame.file, {\n getCompilations: () => {\n const compilations: webpack.Compilation[] = []\n\n // Try Client Compilation first. In `pages` we leverage\n // `isClientError` to check. In `app` it depends on if it's a server\n // / client component and when the code throws. E.g. during HTML\n // rendering it's the server/edge compilation.\n if ((!isEdgeServer && !isServer) || isAppDirectory) {\n const compilation = clientStats()?.compilation\n\n if (compilation) {\n compilations.push(compilation)\n }\n }\n\n // Try Server Compilation. In `pages` this could be something\n // imported in getServerSideProps/getStaticProps as the code for\n // those is tree-shaken. In `app` this finds server components and\n // code that was imported from a server component. It also covers\n // when client component code throws during HTML rendering.\n if (isServer || isAppDirectory) {\n const compilation = serverStats()?.compilation\n\n if (compilation) {\n compilations.push(compilation)\n }\n }\n\n // Try Edge Server Compilation. Both cases are the same as Server\n // Compilation, main difference is that it covers `runtime: 'edge'`\n // pages/app routes.\n if (isEdgeServer || isAppDirectory) {\n const compilation = edgeServerStats()?.compilation\n\n if (compilation) {\n compilations.push(compilation)\n }\n }\n\n return compilations\n },\n })\n } catch (err) {\n console.error('Failed to get source map:', err)\n return internalServerError(res)\n }\n\n if (!source) {\n if (sourcePackage) return json(res, { sourcePackage })\n return noContent(res)\n }\n\n try {\n const originalStackFrameResponse = await createOriginalStackFrame({\n frame,\n source,\n rootDirectory,\n })\n\n if (!originalStackFrameResponse) {\n if (sourcePackage) return json(res, { sourcePackage })\n return noContent(res)\n }\n\n return json(res, originalStackFrameResponse)\n } catch (err) {\n console.log('Failed to parse source map:', err)\n return internalServerError(res)\n }\n } else if (pathname === '/__nextjs_launch-editor') {\n const frame = createStackFrame(searchParams)\n\n if (!frame.file) return badRequest(res)\n\n // frame files may start with their webpack layer, like (middleware)/middleware.js\n const filePath = path.resolve(\n rootDirectory,\n frame.file.replace(/^\\([^)]+\\)\\//, '')\n )\n const fileExists = await fs.access(filePath, FS.F_OK).then(\n () => true,\n () => false\n )\n if (!fileExists) return noContent(res)\n\n try {\n await launchEditor(filePath, frame.lineNumber, frame.column ?? 1)\n } catch (err) {\n console.log('Failed to launch editor:', err)\n return internalServerError(res)\n }\n\n return noContent(res)\n }\n\n return next()\n }\n}\n\nexport function getSourceMapMiddleware(options: {\n clientStats: () => webpack.Stats | null\n serverStats: () => webpack.Stats | null\n edgeServerStats: () => webpack.Stats | null\n}) {\n const { clientStats, serverStats, edgeServerStats } = options\n\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(`http://n${req.url}`)\n\n if (pathname !== '/__nextjs_source-map') {\n return next()\n }\n\n const filename = searchParams.get('filename')\n\n if (!filename) {\n return badRequest(res)\n }\n\n let source: Source | undefined\n\n try {\n source = await getSource(filename, {\n getCompilations: () => {\n const compilations: webpack.Compilation[] = []\n\n for (const stats of [\n clientStats(),\n serverStats(),\n edgeServerStats(),\n ]) {\n if (stats?.compilation) {\n compilations.push(stats.compilation)\n }\n }\n\n return compilations\n },\n })\n } catch (error) {\n console.error('Failed to get source map:', error)\n\n return internalServerError(res)\n }\n\n if (!source) {\n return noContent(res)\n }\n\n return json(res, source.sourceMap)\n }\n}\n"],"names":["constants","FS","promises","fs","path","url","SourceMapConsumer","getSourceMapFromFile","launchEditor","badRequest","findSourcePackage","getOriginalCodeFrame","internalServerError","json","noContent","NEXT_PROJECT_ROOT","getServerError","parseStack","formatFrameSourceFile","shouldIgnorePath","modulePath","includes","getModuleById","id","compilation","chunkGraph","modules","find","module","getModuleId","findModuleNotFoundFromError","errorMessage","match","getSourcePath","source","replace","findOriginalSourcePositionAndContent","sourceMap","position","consumer","sourcePosition","originalPositionFor","line","column","sourceContent","sourceContentFor","destroy","getIgnoredSources","ignoreList","Set","moduleFilenames","sources","index","length","bundlerFilePath","formattedFilePath","add","ignoredSources","map","ignored","has","indexOf","content","sourcesContent","isIgnoredSource","ignoredSource","createStackFrame","searchParams","file","get","methodName","lineNumber","parseInt","arguments","getAll","filter","Boolean","findOriginalSourcePositionAndContentFromCompilation","moduleId","importedModule","buildInfo","importLocByPath","createOriginalStackFrame","rootDirectory","frame","moduleNotFound","result","type","undefined","sourcePath","filePath","resolve","resolvedFilePath","relative","traced","name","originalStackFrame","originalCodeFrame","sourcePackage","getSourceMapFromCompilation","codeGenerationResult","codeGenerationResults","err","console","error","getSource","filename","options","getCompilations","isAbsolute","pathToFileURL","href","startsWith","push","getOverlayMiddleware","clientStats","serverStats","edgeServerStats","req","res","next","pathname","URL","isServer","isEdgeServer","isAppDirectory","join","isNextjsSource","compilations","originalStackFrameResponse","log","fileExists","access","F_OK","then","getSourceMapMiddleware","stats"],"mappings":"AAAA,SAASA,aAAaC,EAAE,EAAEC,YAAYC,EAAE,QAAQ,KAAI;AACpD,OAAOC,UAAU,OAAM;AACvB,OAAOC,SAAS,MAAK;AACrB,SAASC,iBAAiB,QAAQ,kCAAiC;AAEnE,SAASC,oBAAoB,QAAQ,+CAA8C;AACnF,SAASC,YAAY,QAAQ,mCAAkC;AAC/D,SACEC,UAAU,EACVC,iBAAiB,EACjBC,oBAAoB,EACpBC,mBAAmB,EACnBC,IAAI,EACJC,SAAS,QAEJ,WAAU;AACjB,SAASC,iBAAiB,QAAQ,mCAAkC;AACpE,SAASC,cAAc,QAAQ,wCAAuC;AACtE,SAASC,UAAU,QAAQ,kCAAiC;AAC5D,SAASV,oBAAoB,GAAE;AAQ/B,SAASW,qBAAqB,QAAQ,0CAAyC;AAG/E,SAASC,iBAAiBC,UAAkB;IAC1C,OACEA,WAAWC,QAAQ,CAAC,mBACpB,2EAA2E;IAC3ED,WAAWC,QAAQ,CAAC;AAExB;AA6BA,SAASC,cACPC,EAAsB,EACtBC,WAAgC;IAEhC,MAAM,EAAEC,UAAU,EAAEC,OAAO,EAAE,GAAGF;IAEhC,OAAO;WAAIE;KAAQ,CAACC,IAAI,CAAC,CAACC,SAAWH,WAAWI,WAAW,CAACD,YAAYL;AAC1E;AAEA,SAASO,4BAA4BC,YAAgC;QAC5DA;IAAP,OAAOA,iCAAAA,s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