| self.__BUILD_MANIFEST = { | ||
| "__rewrites": { | ||
| "afterFiles": [], | ||
| "beforeFiles": [], | ||
| "fallback": [] | ||
| }, | ||
| "sortedPages": [ | ||
| "/_app", | ||
| "/_error" | ||
| ] | ||
| };self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB() |
| self.__MIDDLEWARE_MATCHERS = [];self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB() |
| self.__SSG_MANIFEST=new Set([]);self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB() |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| import { renderToNodeFlightStream } from './stream-ops'; | ||
| import { getClientReferenceManifest } from './manifests-singleton'; | ||
| import { extractNextErrorCode } from '../../lib/error-telemetry-utils'; | ||
| const filterStackFrame = process.env.NODE_ENV !== 'production' ? require('../lib/source-maps').filterStackFrameDEV : undefined; | ||
| /** | ||
| * Encodes dev-validation errors into the RSC Flight bytes the dev overlay | ||
| * revives. Must run in the runtime that produced the errors (the in-process | ||
| * render or the validation worker) so the encode uses the matching | ||
| * client-reference manifest and captures the live `Error` objects with their | ||
| * stacks and digests. The error codes ride along in a side-channel `Map` | ||
| * because React doesn't revive `__NEXT_ERROR_CODE` during RSC deserialization; | ||
| * RSC preserves object identity, so the revived map keys reference the same | ||
| * errors. | ||
| */ export async function serializeValidationErrorsToFlight(componentMod, errors) { | ||
| const errorCodes = new Map(); | ||
| for (const err of errors){ | ||
| const code = extractNextErrorCode(err); | ||
| if (code !== undefined) { | ||
| errorCodes.set(err, code); | ||
| } | ||
| } | ||
| const { clientModules } = getClientReferenceManifest(); | ||
| const stream = renderToNodeFlightStream(componentMod, { | ||
| errors, | ||
| errorCodes | ||
| }, clientModules, { | ||
| filterStackFrame | ||
| }); | ||
| const chunks = []; | ||
| for await (const chunk of stream){ | ||
| chunks.push(chunk); | ||
| } | ||
| return chunks; | ||
| } | ||
| //# sourceMappingURL=dev-validation-error-delivery.js.map |
| {"version":3,"sources":["../../../../src/server/app-render/dev-validation-error-delivery.ts"],"sourcesContent":["import type { AppPageModule } from '../route-modules/app-page/module'\nimport { renderToNodeFlightStream } from './stream-ops'\nimport { getClientReferenceManifest } from './manifests-singleton'\nimport { extractNextErrorCode } from '../../lib/error-telemetry-utils'\n\nconst filterStackFrame =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .filterStackFrameDEV\n : undefined\n\n/**\n * Encodes dev-validation errors into the RSC Flight bytes the dev overlay\n * revives. Must run in the runtime that produced the errors (the in-process\n * render or the validation worker) so the encode uses the matching\n * client-reference manifest and captures the live `Error` objects with their\n * stacks and digests. The error codes ride along in a side-channel `Map`\n * because React doesn't revive `__NEXT_ERROR_CODE` during RSC deserialization;\n * RSC preserves object identity, so the revived map keys reference the same\n * errors.\n */\nexport async function serializeValidationErrorsToFlight(\n componentMod: AppPageModule,\n errors: Error[]\n): Promise<Uint8Array[]> {\n const errorCodes = new Map<Error, string>()\n for (const err of errors) {\n const code = extractNextErrorCode(err)\n if (code !== undefined) {\n errorCodes.set(err, code)\n }\n }\n\n const { clientModules } = getClientReferenceManifest()\n\n const stream = renderToNodeFlightStream(\n componentMod,\n { errors, errorCodes },\n clientModules,\n { filterStackFrame }\n )\n\n const chunks: Uint8Array[] = []\n for await (const chunk of stream) {\n chunks.push(chunk)\n }\n return chunks\n}\n"],"names":["renderToNodeFlightStream","getClientReferenceManifest","extractNextErrorCode","filterStackFrame","process","env","NODE_ENV","require","filterStackFrameDEV","undefined","serializeValidationErrorsToFlight","componentMod","errors","errorCodes","Map","err","code","set","clientModules","stream","chunks","chunk","push"],"mappings":"AACA,SAASA,wBAAwB,QAAQ,eAAc;AACvD,SAASC,0BAA0B,QAAQ,wBAAuB;AAClE,SAASC,oBAAoB,QAAQ,kCAAiC;AAEtE,MAAMC,mBACJC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eACrB,AAACC,QAAQ,sBACNC,mBAAmB,GACtBC;AAEN;;;;;;;;;CASC,GACD,OAAO,eAAeC,kCACpBC,YAA2B,EAC3BC,MAAe;IAEf,MAAMC,aAAa,IAAIC;IACvB,KAAK,MAAMC,OAAOH,OAAQ;QACxB,MAAMI,OAAOd,qBAAqBa;QAClC,IAAIC,SAASP,WAAW;YACtBI,WAAWI,GAAG,CAACF,KAAKC;QACtB;IACF;IAEA,MAAM,EAAEE,aAAa,EAAE,GAAGjB;IAE1B,MAAMkB,SAASnB,yBACbW,cACA;QAAEC;QAAQC;IAAW,GACrBK,eACA;QAAEf;IAAiB;IAGrB,MAAMiB,SAAuB,EAAE;IAC/B,WAAW,MAAMC,SAASF,OAAQ;QAChCC,OAAOE,IAAI,CAACD;IACd;IACA,OAAOD;AACT","ignoreList":[0]} |
| /** | ||
| * The lifecycle events Cache Components validation emits so E2E tests can | ||
| * locate the validation window in the CLI output. Each is serialized between | ||
| * `<VALIDATION_MESSAGE>` delimiters (see `formatValidationEvent`) and parsed | ||
| * back by the test harness. Produced by the in-process validation in | ||
| * `app-render.tsx` (both dev and build) and by the validation worker, which is | ||
| * why the shape lives here rather than in a single producer. | ||
| * | ||
| * `requestId` correlates a start with its matching end/aborted. Dev and worker | ||
| * validation use the render's request id; build validation, which has no such | ||
| * id, uses a stringified timestamp instead. | ||
| */ /** | ||
| * Wraps a validation event in the `<VALIDATION_MESSAGE>` delimiters the test | ||
| * harness scans for. The caller chooses the output stream (dev validation logs | ||
| * to stdout; build validation uses stderr for deterministic ordering). | ||
| */ export function formatValidationEvent(event) { | ||
| return '<VALIDATION_MESSAGE>' + JSON.stringify(event) + '</VALIDATION_MESSAGE>'; | ||
| } | ||
| //# sourceMappingURL=dev-validation-events.js.map |
| {"version":3,"sources":["../../../../src/server/app-render/dev-validation-events.ts"],"sourcesContent":["/**\n * The lifecycle events Cache Components validation emits so E2E tests can\n * locate the validation window in the CLI output. Each is serialized between\n * `<VALIDATION_MESSAGE>` delimiters (see `formatValidationEvent`) and parsed\n * back by the test harness. Produced by the in-process validation in\n * `app-render.tsx` (both dev and build) and by the validation worker, which is\n * why the shape lives here rather than in a single producer.\n *\n * `requestId` correlates a start with its matching end/aborted. Dev and worker\n * validation use the render's request id; build validation, which has no such\n * id, uses a stringified timestamp instead.\n */\nexport type ValidationEvent =\n | ValidationStartEvent\n | ValidationEndEvent\n | ValidationAbortedEvent\n\nexport type ValidationStartEvent = {\n type: 'validation_start'\n requestId: string\n url: string\n /**\n * Only reported for development validation.\n */\n responseFinished?: boolean\n}\n\nexport type ValidationEndEvent = {\n type: 'validation_end'\n requestId: string\n url: string\n}\n\n/**\n * Emitted when detached validation is aborted. It can appear without a start\n * when cancellation happens before validation runs, or after a start instead of\n * an end when in-flight validation is cancelled.\n */\nexport type ValidationAbortedEvent = {\n type: 'validation_aborted'\n requestId: string\n url: string\n}\n\n/**\n * Wraps a validation event in the `<VALIDATION_MESSAGE>` delimiters the test\n * harness scans for. The caller chooses the output stream (dev validation logs\n * to stdout; build validation uses stderr for deterministic ordering).\n */\nexport function formatValidationEvent(event: ValidationEvent): string {\n return (\n '<VALIDATION_MESSAGE>' + JSON.stringify(event) + '</VALIDATION_MESSAGE>'\n )\n}\n"],"names":["formatValidationEvent","event","JSON","stringify"],"mappings":"AAAA;;;;;;;;;;;CAWC,GAiCD;;;;CAIC,GACD,OAAO,SAASA,sBAAsBC,KAAsB;IAC1D,OACE,yBAAyBC,KAAKC,SAAS,CAACF,SAAS;AAErD","ignoreList":[0]} |
| /** | ||
| * Cross-module handoff for the dev validation worker (client-module warmup, | ||
| * static-shell validation, and instant-config validation all run on it). A | ||
| * symbol on `globalThis` decouples the dev-server entry point (which installs | ||
| * the jest-worker pool) from the read site in `runDevValidationInBackground` | ||
| * inside `app-render.tsx`, avoiding a direct import of dev-only pool code from | ||
| * the render module. When the symbol is not set (e.g. because the feature flag | ||
| * is disabled), `getDevValidationWorker()` returns undefined and the caller | ||
| * runs validation in process instead. | ||
| */ const SYMBOL = Symbol.for('next.dev.validationWorker'); | ||
| export function setDevValidationWorker(fn) { | ||
| ; | ||
| globalThis[SYMBOL] = fn; | ||
| } | ||
| export function getDevValidationWorker() { | ||
| return globalThis[SYMBOL]; | ||
| } | ||
| //# sourceMappingURL=dev-validation-worker-globals.js.map |
| {"version":3,"sources":["../../../../src/server/app-render/dev-validation-worker-globals.ts"],"sourcesContent":["import type { Params } from '../request/params'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport type { NextParsedUrlQuery } from '../request-meta'\nimport type { PrefetchingMode } from './app-render'\nimport type { NextConfigComplete, ValidationLevel } from '../config-shared'\nimport type { ImageConfigComplete } from '../../shared/lib/image-config'\n\n/**\n * Cross-module handoff for the dev validation worker (client-module warmup,\n * static-shell validation, and instant-config validation all run on it). A\n * symbol on `globalThis` decouples the dev-server entry point (which installs\n * the jest-worker pool) from the read site in `runDevValidationInBackground`\n * inside `app-render.tsx`, avoiding a direct import of dev-only pool code from\n * the render module. When the symbol is not set (e.g. because the feature flag\n * is disabled), `getDevValidationWorker()` returns undefined and the caller\n * runs validation in process instead.\n */\nconst SYMBOL: unique symbol = Symbol.for('next.dev.validationWorker')\n\n/**\n * Per-stage RSC chunks, the serializable form of `AccumulatedStreamChunks` that\n * the worker replays. No live streams cross the boundary.\n */\nexport interface SerializedAccumulatedChunks {\n shellStaticChunks: Uint8Array[]\n staticChunks: Uint8Array[]\n shellRuntimeChunks: Uint8Array[]\n runtimeChunks: Uint8Array[]\n dynamicChunks: Uint8Array[]\n}\n\n/**\n * Serializable view of one validation input (the shape `DevValidationInputs`\n * carries), with the live streams already drained to chunks. The stage-end\n * timings are replayed into the per-depth Flight re-encodes so the worker\n * reconstructs the same partial-stage boundaries the main render observed.\n */\nexport interface SerializedValidationInputs {\n accumulatedChunks: SerializedAccumulatedChunks\n debugChunks: Uint8Array[] | null\n startTime: number\n staticStageEndTime: number\n runtimeStageEndTime: number\n}\n\n/**\n * Serializable view of the request, rebuilt into a `RequestStore` on the worker\n * so `cookies()` / `headers()` / `draftMode()` behave as in the real render.\n */\nexport interface DevValidationRequestSnapshot {\n headers: [string, string][]\n urlPathname: string\n urlSearch: string\n rootParams: Params\n isDraftMode: boolean\n isHmrRefresh: boolean\n hmrRefreshHash: string | undefined\n}\n\n/**\n * Everything the worker needs to rebuild the render context and inputs and run\n * `runValidationInDev`. Built on the main thread from the settled render; the\n * pool augments it with install-time fields (`distDir`, `buildId`, …).\n */\nexport interface DevValidationSnapshot {\n page: string\n route: string\n requestId: string\n responseFinished: boolean\n prefetchMode: PrefetchingMode\n devRenderDidError: boolean\n nonce: string | undefined\n query: NextParsedUrlQuery\n request: DevValidationRequestSnapshot\n // The interpolated route params, the routing seed the worker rebuilds\n // `getDynamicParamFromSegment` from (together with the fallback params\n // below).\n interpolatedParams: Params\n // The request's fallback params, the set `ctx.getDynamicParamFromSegment`\n // closed over. The worker rebuilds `getDynamicParamFromSegment` from these\n // (with `interpolatedParams` and `optimisticRouting`), so the depth-loop\n // segment keys match the seed render's Flight. It is null for a request whose\n // params all resolve to concrete values.\n requestFallbackRouteParams: OpaqueFallbackRouteParams | null\n // The validation fallback params, passed to `runValidationInDev` and its\n // prerender stores. They mark params unknown so that accessing one during the\n // simulated prefetch is treated as dynamic. This set may include params that\n // `requestFallbackRouteParams` does not.\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n optimisticRouting: boolean\n forceStatic: boolean | undefined\n validationLevel: ValidationLevel\n implicitTags: string[]\n /**\n * Pages whose client reference manifests supplied client references to the\n * render being validated, beyond the validated route's own manifest (see\n * `WorkStore.additionalClientReferenceManifestPages`). The worker registers\n * these so the same references resolve in its thread. Empty for all but the\n * rare renders that React's I/O tracking carries a reference into.\n */\n additionalClientReferenceManifestPages: string[]\n isDebugChannelEnabled: boolean\n renderOpts: {\n images: ImageConfigComplete\n allowEmptyStaticShell: boolean | undefined\n }\n instantInputs: SerializedValidationInputs | null\n staticInputs: SerializedValidationInputs\n}\n\n/**\n * Install-time fields the dev server's worker pool augments the snapshot with\n * so the worker can reload the route (`distDir`; `page` comes from the\n * snapshot) and rebuild the work store (`buildId`, `deploymentId`, the config\n * slice).\n */\nexport interface DevValidationInstallFields {\n distDir: string\n buildId: string\n deploymentId: string\n nextConfigSerializable: {\n httpAgentOptions: NextConfigComplete['httpAgentOptions']\n cacheLifeProfiles: NextConfigComplete['cacheLife']\n useCacheTimeout: number\n staticPageGenerationTimeout: number\n }\n}\n\n/**\n * The full message the worker receives and forwards into the in-bundle entry:\n * the main-thread snapshot plus the pool's install-time fields.\n */\nexport type DevValidationWorkerMessage = DevValidationSnapshot &\n DevValidationInstallFields\n\n/**\n * The RSC-encoded `{ errors, errorCodes }` Flight chunks for the dev overlay,\n * or null when validation produced no errors or was aborted. The worker also\n * logs the errors to its own stderr (piped to the parent) with code frames.\n */\nexport type DevValidationWorkerResult = Uint8Array[] | null\n\n/**\n * Worker hook installed by the dev server. Given the render snapshot and the\n * validation abort signal, runs validation on a worker thread and resolves to\n * the validation error Flight chunks to deliver on the main thread. On an abort\n * the pool relays the aborted signal to the worker thread through a shared\n * flag, so the in-flight run aborts mid-run; validation always runs as a thread\n * (never a child process), which is what makes that cross-thread abort\n * possible.\n */\nexport type DevValidationWorker = (\n snapshot: DevValidationSnapshot,\n validationAbortSignal: AbortSignal\n) => Promise<DevValidationWorkerResult>\n\ninterface WorkerHolder {\n [SYMBOL]?: DevValidationWorker\n}\n\nexport function setDevValidationWorker(\n fn: DevValidationWorker | undefined\n): void {\n ;(globalThis as WorkerHolder)[SYMBOL] = fn\n}\n\nexport function getDevValidationWorker(): DevValidationWorker | undefined {\n return (globalThis as WorkerHolder)[SYMBOL]\n}\n"],"names":["SYMBOL","Symbol","for","setDevValidationWorker","fn","globalThis","getDevValidationWorker"],"mappings":"AAOA;;;;;;;;;CASC,GACD,MAAMA,SAAwBC,OAAOC,GAAG,CAAC;AA+IzC,OAAO,SAASC,uBACdC,EAAmC;;IAEjCC,UAA2B,CAACL,OAAO,GAAGI;AAC1C;AAEA,OAAO,SAASE;IACd,OAAO,AAACD,UAA2B,CAACL,OAAO;AAC7C","ignoreList":[0]} |
| import { isNodeNextResponse } from '../base-http/helpers'; | ||
| /** | ||
| * Builds the serializable snapshot the dev validation worker needs to rebuild | ||
| * the render context and inputs and run `runValidationInDev` on the worker | ||
| * thread. Reads only serializable data from the settled render; the live | ||
| * objects (`componentMod`, the async-storage stores, | ||
| * `getDynamicParamFromSegment`) are reconstructed on the worker from this seed. | ||
| * Draining the debug channels is async, so this returns a promise. | ||
| */ export async function buildDevValidationSnapshot(ctx, instantInputs, staticInputs, prefetchMode, fallbackRouteParams, devRenderDidError) { | ||
| const requestStore = staticInputs.requestStore; | ||
| const responseFinished = !isNodeNextResponse(ctx.res) || ctx.res.originalResponse.writableFinished; | ||
| // The instant and static inputs may share one debug channel, so drain each | ||
| // channel only once. | ||
| const chunksByChannel = new WeakMap(); | ||
| const getDebugChunksOnce = async (channel)=>{ | ||
| if (!channel) { | ||
| return null; | ||
| } | ||
| let chunks = chunksByChannel.get(channel); | ||
| if (!chunks) { | ||
| chunks = []; | ||
| for await (const chunk of channel){ | ||
| chunks.push(chunk); | ||
| } | ||
| chunksByChannel.set(channel, chunks); | ||
| } | ||
| return chunks; | ||
| }; | ||
| const toSerializedInputs = async (inputs)=>({ | ||
| accumulatedChunks: inputs.accumulatedChunks, | ||
| debugChunks: await getDebugChunksOnce(inputs.debugChannelClient), | ||
| startTime: inputs.startTime, | ||
| staticStageEndTime: inputs.staticStageEndTime, | ||
| runtimeStageEndTime: inputs.runtimeStageEndTime | ||
| }); | ||
| return { | ||
| page: ctx.workStore.page, | ||
| route: ctx.workStore.route, | ||
| requestId: ctx.requestId, | ||
| responseFinished, | ||
| prefetchMode, | ||
| devRenderDidError, | ||
| nonce: ctx.nonce, | ||
| query: ctx.query, | ||
| request: { | ||
| headers: [ | ||
| ...requestStore.headers.entries() | ||
| ], | ||
| urlPathname: requestStore.url.pathname, | ||
| urlSearch: requestStore.url.search, | ||
| rootParams: requestStore.rootParams, | ||
| isDraftMode: requestStore.draftMode.isEnabled, | ||
| isHmrRefresh: requestStore.isHmrRefresh ?? false, | ||
| hmrRefreshHash: requestStore.hmrRefreshHash | ||
| }, | ||
| interpolatedParams: ctx.interpolatedParams, | ||
| requestFallbackRouteParams: ctx.fallbackRouteParams, | ||
| fallbackRouteParams, | ||
| optimisticRouting: ctx.renderOpts.experimental.optimisticRouting, | ||
| forceStatic: ctx.workStore.forceStatic, | ||
| validationLevel: ctx.workStore.validationLevel, | ||
| implicitTags: ctx.implicitTags.tags, | ||
| additionalClientReferenceManifestPages: ctx.workStore.additionalClientReferenceManifestPages ? [ | ||
| ...ctx.workStore.additionalClientReferenceManifestPages | ||
| ] : [], | ||
| isDebugChannelEnabled: !!ctx.renderOpts.setReactDebugChannel, | ||
| renderOpts: { | ||
| images: ctx.renderOpts.images, | ||
| allowEmptyStaticShell: ctx.renderOpts.allowEmptyStaticShell | ||
| }, | ||
| instantInputs: instantInputs ? await toSerializedInputs(instantInputs) : null, | ||
| staticInputs: await toSerializedInputs(staticInputs) | ||
| }; | ||
| } | ||
| //# sourceMappingURL=dev-validation-worker-snapshot.js.map |
| {"version":3,"sources":["../../../../src/server/app-render/dev-validation-worker-snapshot.ts"],"sourcesContent":["import type { AppRenderContext, ResolvedValidationInputs } from './app-render'\nimport type { PrefetchingMode } from './app-render'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport type { AnyStream } from './stream-ops'\nimport type {\n DevValidationSnapshot,\n SerializedValidationInputs,\n} from './dev-validation-worker-globals'\n\nimport { isNodeNextResponse } from '../base-http/helpers'\n\n/**\n * Builds the serializable snapshot the dev validation worker needs to rebuild\n * the render context and inputs and run `runValidationInDev` on the worker\n * thread. Reads only serializable data from the settled render; the live\n * objects (`componentMod`, the async-storage stores,\n * `getDynamicParamFromSegment`) are reconstructed on the worker from this seed.\n * Draining the debug channels is async, so this returns a promise.\n */\nexport async function buildDevValidationSnapshot(\n ctx: AppRenderContext,\n instantInputs: ResolvedValidationInputs | null,\n staticInputs: ResolvedValidationInputs,\n prefetchMode: PrefetchingMode,\n fallbackRouteParams: OpaqueFallbackRouteParams | null,\n devRenderDidError: boolean\n): Promise<DevValidationSnapshot> {\n const requestStore = staticInputs.requestStore\n const responseFinished =\n !isNodeNextResponse(ctx.res) || ctx.res.originalResponse.writableFinished\n\n // The instant and static inputs may share one debug channel, so drain each\n // channel only once.\n const chunksByChannel = new WeakMap<AnyStream, Uint8Array[]>()\n const getDebugChunksOnce = async (\n channel: AnyStream | undefined\n ): Promise<Uint8Array[] | null> => {\n if (!channel) {\n return null\n }\n let chunks = chunksByChannel.get(channel)\n if (!chunks) {\n chunks = []\n for await (const chunk of channel) {\n chunks.push(chunk)\n }\n chunksByChannel.set(channel, chunks)\n }\n return chunks\n }\n\n const toSerializedInputs = async (\n inputs: ResolvedValidationInputs\n ): Promise<SerializedValidationInputs> => ({\n accumulatedChunks: inputs.accumulatedChunks,\n debugChunks: await getDebugChunksOnce(inputs.debugChannelClient),\n startTime: inputs.startTime,\n staticStageEndTime: inputs.staticStageEndTime,\n runtimeStageEndTime: inputs.runtimeStageEndTime,\n })\n\n return {\n page: ctx.workStore.page,\n route: ctx.workStore.route,\n requestId: ctx.requestId,\n responseFinished,\n prefetchMode,\n devRenderDidError,\n nonce: ctx.nonce,\n query: ctx.query,\n request: {\n headers: [...requestStore.headers.entries()],\n urlPathname: requestStore.url.pathname,\n urlSearch: requestStore.url.search,\n rootParams: requestStore.rootParams,\n isDraftMode: requestStore.draftMode.isEnabled,\n isHmrRefresh: requestStore.isHmrRefresh ?? false,\n hmrRefreshHash: requestStore.hmrRefreshHash,\n },\n interpolatedParams: ctx.interpolatedParams,\n requestFallbackRouteParams: ctx.fallbackRouteParams,\n fallbackRouteParams,\n optimisticRouting: ctx.renderOpts.experimental.optimisticRouting,\n forceStatic: ctx.workStore.forceStatic,\n validationLevel: ctx.workStore.validationLevel,\n implicitTags: ctx.implicitTags.tags,\n additionalClientReferenceManifestPages: ctx.workStore\n .additionalClientReferenceManifestPages\n ? [...ctx.workStore.additionalClientReferenceManifestPages]\n : [],\n isDebugChannelEnabled: !!ctx.renderOpts.setReactDebugChannel,\n renderOpts: {\n images: ctx.renderOpts.images,\n allowEmptyStaticShell: ctx.renderOpts.allowEmptyStaticShell,\n },\n instantInputs: instantInputs\n ? await toSerializedInputs(instantInputs)\n : null,\n staticInputs: await toSerializedInputs(staticInputs),\n }\n}\n"],"names":["isNodeNextResponse","buildDevValidationSnapshot","ctx","instantInputs","staticInputs","prefetchMode","fallbackRouteParams","devRenderDidError","requestStore","responseFinished","res","originalResponse","writableFinished","chunksByChannel","WeakMap","getDebugChunksOnce","channel","chunks","get","chunk","push","set","toSerializedInputs","inputs","accumulatedChunks","debugChunks","debugChannelClient","startTime","staticStageEndTime","runtimeStageEndTime","page","workStore","route","requestId","nonce","query","request","headers","entries","urlPathname","url","pathname","urlSearch","search","rootParams","isDraftMode","draftMode","isEnabled","isHmrRefresh","hmrRefreshHash","interpolatedParams","requestFallbackRouteParams","optimisticRouting","renderOpts","experimental","forceStatic","validationLevel","implicitTags","tags","additionalClientReferenceManifestPages","isDebugChannelEnabled","setReactDebugChannel","images","allowEmptyStaticShell"],"mappings":"AASA,SAASA,kBAAkB,QAAQ,uBAAsB;AAEzD;;;;;;;CAOC,GACD,OAAO,eAAeC,2BACpBC,GAAqB,EACrBC,aAA8C,EAC9CC,YAAsC,EACtCC,YAA6B,EAC7BC,mBAAqD,EACrDC,iBAA0B;IAE1B,MAAMC,eAAeJ,aAAaI,YAAY;IAC9C,MAAMC,mBACJ,CAACT,mBAAmBE,IAAIQ,GAAG,KAAKR,IAAIQ,GAAG,CAACC,gBAAgB,CAACC,gBAAgB;IAE3E,2EAA2E;IAC3E,qBAAqB;IACrB,MAAMC,kBAAkB,IAAIC;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QAC9CC,cAAcvD,IAAIuD,YAAY,CAACC,IAAI;QACnCC,wCAAwCzD,IAAI6B,SAAS,CAClD4B,sCAAsC,GACrC;eAAIzD,IAAI6B,SAAS,CAAC4B,sCAAsC;SAAC,GACzD,EAAE;QACNC,uBAAuB,CAAC,CAAC1D,IAAImD,UAAU,CAACQ,oBAAoB;QAC5DR,YAAY;YACVS,QAAQ5D,IAAImD,UAAU,CAACS,MAAM;YAC7BC,uBAAuB7D,IAAImD,UAAU,CAACU,qBAAqB;QAC7D;QACA5D,eAAeA,gBACX,MAAMmB,mBAAmBnB,iBACzB;QACJC,cAAc,MAAMkB,mBAAmBlB;IACzC;AACF","ignoreList":[0]} |
| import { Worker } from 'next/dist/compiled/jest-worker'; | ||
| import { setDevValidationWorker } from '../app-render/dev-validation-worker-globals'; | ||
| import { onCacheInvalidation } from './require-cache'; | ||
| import { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'; | ||
| import { needsExperimentalReact } from '../../lib/needs-experimental-react'; | ||
| /** | ||
| * Wire up the dev-server's validation worker: register the HMR teardown | ||
| * listener and install the hook that `runDevValidationInBackground` calls once | ||
| * a render has settled. The worker thread is spawned lazily, so nothing is | ||
| * created until the first navigation actually validates. | ||
| */ export function installDevValidationWorker(options) { | ||
| const { distDir, buildId, deploymentId, nextConfig } = options; | ||
| // A single worker, not a pool. Validation for one navigation runs its depth | ||
| // loop sequentially, and a newer navigation supersedes the previous one | ||
| // (aborting it mid-run) rather than running concurrently, so there's no | ||
| // per-request fan-out to parallelize (unlike the `'use cache'` probe, where | ||
| // one request fans out into concurrent probes). One worker already frees the | ||
| // main thread, which is the whole point; it also keeps each request's CLI | ||
| // marker block contiguous in the piped output. Torn down on HMR (stale user | ||
| // modules) and on crash. | ||
| // | ||
| // TODO(dev-validation-worker): raise `numWorkers` if concurrent navigations | ||
| // across independent requests (e.g. multiple tabs) show a validation-latency | ||
| // tail. | ||
| let pool; | ||
| const getPool = ()=>{ | ||
| if (pool) { | ||
| return pool; | ||
| } | ||
| // Strip `--inspect` from any inherited `NODE_OPTIONS` so the worker doesn't | ||
| // fight the parent for the same debug port. | ||
| const workerNodeOptions = getFormattedNodeOptionsWithoutInspect(); | ||
| // The worker is shipped as four pre-bundled dev-only artifacts | ||
| // ({webpack,turbopack} × {stable,experimental}), one per combination of the | ||
| // user's bundler and vendored React channel. Pick the matching artifact | ||
| // from runtime env so the worker stays in lockstep with the user's app | ||
| // bundle. `needsExperimentalReact` is the same predicate `define-env.ts` | ||
| // uses to wire `__NEXT_EXPERIMENTAL_REACT`. | ||
| const turbo = process.env.TURBOPACK ? '-turbo' : ''; | ||
| const channel = needsExperimentalReact(nextConfig) ? '-experimental' : ''; | ||
| const workerPath = require.resolve(`next/dist/compiled/next-server/dev-validation-worker${turbo}${channel}.runtime.dev.js`); | ||
| const worker = new Worker(workerPath, { | ||
| maxRetries: 0, | ||
| numWorkers: 1, | ||
| // Always worker-threads, regardless of `experimental.workerThreads`. | ||
| // Unlike the `'use cache'` probe (which follows the flag), validation has | ||
| // no reason to prefer a child process: it doesn't need process-level | ||
| // isolation (a worker thread already has its own V8 heap and module | ||
| // registry, so the reloaded route is isolated from the main thread), and | ||
| // threads let a superseded validation be aborted mid-run through a shared | ||
| // `SharedArrayBuffer`, which a separate process can't receive. Threads | ||
| // also carry the transported Flight bytes as typed arrays via structured | ||
| // clone, with no JSON round-trip to corrupt them. | ||
| enableWorkerThreads: true, | ||
| // Listing the method explicitly tells jest-worker to skip the discovery | ||
| // `require()` it would otherwise do in the parent process to enumerate | ||
| // the module's exports. This worker's top-level imports (`require-hook`, | ||
| // `node-environment`) run runtime setup meant only for the isolated | ||
| // worker thread, so they must not be evaluated in the parent. | ||
| exposedMethods: [ | ||
| 'runDevValidation' | ||
| ], | ||
| forkOptions: { | ||
| env: { | ||
| ...process.env, | ||
| NODE_OPTIONS: workerNodeOptions | ||
| } | ||
| } | ||
| }); | ||
| worker.getStdout().pipe(process.stdout); | ||
| worker.getStderr().pipe(process.stderr); | ||
| pool = worker; | ||
| return worker; | ||
| }; | ||
| const tearDownPool = async ()=>{ | ||
| const current = pool; | ||
| if (!current) { | ||
| return; | ||
| } | ||
| pool = undefined; | ||
| await current.end().catch(()=>{ | ||
| // The worker thread exits on its own once its work settles; a failed | ||
| // `.end()` here just means we couldn't wait for it cleanly. | ||
| }); | ||
| }; | ||
| const runValidation = async (snapshot, validationAbortSignal)=>{ | ||
| let activePool; | ||
| try { | ||
| activePool = getPool(); | ||
| } catch { | ||
| return null; | ||
| } | ||
| const message = { | ||
| ...snapshot, | ||
| distDir, | ||
| buildId, | ||
| deploymentId, | ||
| nextConfigSerializable: { | ||
| httpAgentOptions: nextConfig.httpAgentOptions, | ||
| cacheLifeProfiles: nextConfig.cacheLife, | ||
| useCacheTimeout: nextConfig.experimental.useCacheTimeout, | ||
| staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout | ||
| } | ||
| }; | ||
| // The worker runs as a thread (see `enableWorkerThreads` above), so an | ||
| // abort reaches it through a one-slot shared flag rather than the abort | ||
| // signal directly (a signal can't cross the thread boundary). Mirror an | ||
| // abort of `validationAbortSignal` into the buffer and wake the worker's | ||
| // `Atomics.waitAsync` on it, so it aborts the in-flight run at its next | ||
| // depth boundary. | ||
| const abortBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT); | ||
| const abortFlag = new Int32Array(abortBuffer); | ||
| const propagateAbort = ()=>{ | ||
| Atomics.store(abortFlag, 0, 1); | ||
| Atomics.notify(abortFlag, 0); | ||
| }; | ||
| if (validationAbortSignal.aborted) { | ||
| propagateAbort(); | ||
| } else { | ||
| validationAbortSignal.addEventListener('abort', propagateAbort, { | ||
| once: true | ||
| }); | ||
| } | ||
| try { | ||
| return await activePool.runDevValidation(message, abortBuffer); | ||
| } catch { | ||
| // Worker crash or IPC error: tear down so the next validation starts | ||
| // fresh. The main thread treats a missing result as "nothing to deliver." | ||
| await tearDownPool(); | ||
| return null; | ||
| } finally{ | ||
| // `once` only auto-removes the listener if it fired, so remove it | ||
| // explicitly to bound its lifetime to this run when validation completed | ||
| // without being superseded. | ||
| validationAbortSignal.removeEventListener('abort', propagateAbort); | ||
| } | ||
| }; | ||
| // The dev server can't reach into the worker to clear its `require.cache` or | ||
| // manifest caches, so we drop the worker whenever the parent's caches are | ||
| // invalidated (HMR, route recompile). The next validation lazy-spawns a fresh | ||
| // worker with empty caches. | ||
| onCacheInvalidation(()=>{ | ||
| void tearDownPool(); | ||
| }); | ||
| setDevValidationWorker(runValidation); | ||
| } | ||
| //# sourceMappingURL=dev-validation-worker-pool.js.map |
| {"version":3,"sources":["../../../../src/server/dev/dev-validation-worker-pool.ts"],"sourcesContent":["import type { NextConfigComplete } from '../config-shared'\nimport type { runDevValidation } from './dev-validation-worker'\nimport type {\n DevValidationSnapshot,\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\n\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { setDevValidationWorker } from '../app-render/dev-validation-worker-globals'\nimport { onCacheInvalidation } from './require-cache'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { needsExperimentalReact } from '../../lib/needs-experimental-react'\n\ninterface InstallOptions {\n distDir: string\n buildId: string\n deploymentId: string\n nextConfig: NextConfigComplete\n}\n\ntype ValidationPool = { [key: string]: any } & {\n runDevValidation: typeof runDevValidation\n}\n\n/**\n * Wire up the dev-server's validation worker: register the HMR teardown\n * listener and install the hook that `runDevValidationInBackground` calls once\n * a render has settled. The worker thread is spawned lazily, so nothing is\n * created until the first navigation actually validates.\n */\nexport function installDevValidationWorker(options: InstallOptions): void {\n const { distDir, buildId, deploymentId, nextConfig } = options\n\n // A single worker, not a pool. Validation for one navigation runs its depth\n // loop sequentially, and a newer navigation supersedes the previous one\n // (aborting it mid-run) rather than running concurrently, so there's no\n // per-request fan-out to parallelize (unlike the `'use cache'` probe, where\n // one request fans out into concurrent probes). One worker already frees the\n // main thread, which is the whole point; it also keeps each request's CLI\n // marker block contiguous in the piped output. Torn down on HMR (stale user\n // modules) and on crash.\n //\n // TODO(dev-validation-worker): raise `numWorkers` if concurrent navigations\n // across independent requests (e.g. multiple tabs) show a validation-latency\n // tail.\n let pool: ValidationPool | undefined\n\n const getPool = (): ValidationPool => {\n if (pool) {\n return pool\n }\n // Strip `--inspect` from any inherited `NODE_OPTIONS` so the worker doesn't\n // fight the parent for the same debug port.\n const workerNodeOptions = getFormattedNodeOptionsWithoutInspect()\n\n // The worker is shipped as four pre-bundled dev-only artifacts\n // ({webpack,turbopack} × {stable,experimental}), one per combination of the\n // user's bundler and vendored React channel. Pick the matching artifact\n // from runtime env so the worker stays in lockstep with the user's app\n // bundle. `needsExperimentalReact` is the same predicate `define-env.ts`\n // uses to wire `__NEXT_EXPERIMENTAL_REACT`.\n const turbo = process.env.TURBOPACK ? '-turbo' : ''\n const channel = needsExperimentalReact(nextConfig) ? '-experimental' : ''\n const workerPath = require.resolve(\n `next/dist/compiled/next-server/dev-validation-worker${turbo}${channel}.runtime.dev.js`\n )\n\n const worker = new Worker(workerPath, {\n maxRetries: 0,\n numWorkers: 1,\n // Always worker-threads, regardless of `experimental.workerThreads`.\n // Unlike the `'use cache'` probe (which follows the flag), validation has\n // no reason to prefer a child process: it doesn't need process-level\n // isolation (a worker thread already has its own V8 heap and module\n // registry, so the reloaded route is isolated from the main thread), and\n // threads let a superseded validation be aborted mid-run through a shared\n // `SharedArrayBuffer`, which a separate process can't receive. Threads\n // also carry the transported Flight bytes as typed arrays via structured\n // clone, with no JSON round-trip to corrupt them.\n enableWorkerThreads: true,\n // Listing the method explicitly tells jest-worker to skip the discovery\n // `require()` it would otherwise do in the parent process to enumerate\n // the module's exports. This worker's top-level imports (`require-hook`,\n // `node-environment`) run runtime setup meant only for the isolated\n // worker thread, so they must not be evaluated in the parent.\n exposedMethods: ['runDevValidation'],\n forkOptions: {\n env: {\n ...process.env,\n NODE_OPTIONS: workerNodeOptions,\n },\n },\n }) as Worker & ValidationPool\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n pool = worker\n return worker\n }\n\n const tearDownPool = async (): Promise<void> => {\n const current = pool\n if (!current) {\n return\n }\n pool = undefined\n await current.end().catch(() => {\n // The worker thread exits on its own once its work settles; a failed\n // `.end()` here just means we couldn't wait for it cleanly.\n })\n }\n\n const runValidation = async (\n snapshot: DevValidationSnapshot,\n validationAbortSignal: AbortSignal\n ): Promise<DevValidationWorkerResult> => {\n let activePool: ValidationPool\n try {\n activePool = getPool()\n } catch {\n return null\n }\n\n const message: DevValidationWorkerMessage = {\n ...snapshot,\n distDir,\n buildId,\n deploymentId,\n nextConfigSerializable: {\n httpAgentOptions: nextConfig.httpAgentOptions,\n cacheLifeProfiles: nextConfig.cacheLife,\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n },\n }\n\n // The worker runs as a thread (see `enableWorkerThreads` above), so an\n // abort reaches it through a one-slot shared flag rather than the abort\n // signal directly (a signal can't cross the thread boundary). Mirror an\n // abort of `validationAbortSignal` into the buffer and wake the worker's\n // `Atomics.waitAsync` on it, so it aborts the in-flight run at its next\n // depth boundary.\n const abortBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)\n const abortFlag = new Int32Array(abortBuffer)\n const propagateAbort = () => {\n Atomics.store(abortFlag, 0, 1)\n Atomics.notify(abortFlag, 0)\n }\n if (validationAbortSignal.aborted) {\n propagateAbort()\n } else {\n validationAbortSignal.addEventListener('abort', propagateAbort, {\n once: true,\n })\n }\n\n try {\n return await activePool.runDevValidation(message, abortBuffer)\n } catch {\n // Worker crash or IPC error: tear down so the next validation starts\n // fresh. The main thread treats a missing result as \"nothing to deliver.\"\n await tearDownPool()\n return null\n } finally {\n // `once` only auto-removes the listener if it fired, so remove it\n // explicitly to bound its lifetime to this run when validation completed\n // without being superseded.\n validationAbortSignal.removeEventListener('abort', propagateAbort)\n }\n }\n\n // The dev server can't reach into the worker to clear its `require.cache` or\n // manifest caches, so we drop the worker whenever the parent's caches are\n // invalidated (HMR, route recompile). The next validation lazy-spawns a fresh\n // worker with empty caches.\n onCacheInvalidation(() => {\n void tearDownPool()\n })\n\n setDevValidationWorker(runValidation)\n}\n"],"names":["Worker","setDevValidationWorker","onCacheInvalidation","getFormattedNodeOptionsWithoutInspect","needsExperimentalReact","installDevValidationWorker","options","distDir","buildId","deploymentId","nextConfig","pool","getPool","workerNodeOptions","turbo","process","env","TURBOPACK","channel","workerPath","require","resolve","worker","maxRetries","numWorkers","enableWorkerThreads","exposedMethods","forkOptions","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","tearDownPool","current","undefined","end","catch","runValidation","snapshot","validationAbortSignal","activePool","message","nextConfigSerializable","httpAgentOptions","cacheLifeProfiles","cacheLife","useCacheTimeout","experimental","staticPageGenerationTimeout","abortBuffer","SharedArrayBuffer","Int32Array","BYTES_PER_ELEMENT","abortFlag","propagateAbort","Atomics","store","notify","aborted","addEventListener","once","runDevValidation","removeEventListener"],"mappings":"AAQA,SAASA,MAAM,QAAQ,iCAAgC;AACvD,SAASC,sBAAsB,QAAQ,8CAA6C;AACpF,SAASC,mBAAmB,QAAQ,kBAAiB;AACrD,SAASC,qCAAqC,QAAQ,eAAc;AACpE,SAASC,sBAAsB,QAAQ,qCAAoC;AAa3E;;;;;CAKC,GACD,OAAO,SAASC,2BAA2BC,OAAuB;IAChE,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAEC,YAAY,EAAEC,UAAU,EAAE,GAAGJ;IAEvD,4EAA4E;IAC5E,wEAAwE;IACxE,wEAAwE;IACxE,4EAA4E;IAC5E,6EAA6E;IAC7E,0EAA0E;IAC1E,4EAA4E;IAC5E,yBAAyB;IACzB,EAAE;IACF,4EAA4E;IAC5E,6EAA6E;IAC7E,QAAQ;IACR,IAAIK;IAEJ,MAAMC,UAAU;QACd,IAAID,MAAM;YACR,OAAOA;QACT;QACA,4EAA4E;QAC5E,4CAA4C;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AWmC,gBAAgB;gBAC7CC,mBAAmBpC,WAAWqC,SAAS;gBACvCC,iBAAiBtC,WAAWuC,YAAY,CAACD,eAAe;gBACxDE,6BAA6BxC,WAAWwC,2BAA2B;YACrE;QACF;QAEA,uEAAuE;QACvE,wEAAwE;QACxE,wEAAwE;QACxE,yEAAyE;QACzE,wEAAwE;QACxE,kBAAkB;QAClB,MAAMC,cAAc,IAAIC,kBAAkBC,WAAWC,iBAAiB;QACtE,MAAMC,YAAY,IAAIF,WAAWF;QACjC,MAAMK,iBAAiB;YACrBC,QAAQC,KAAK,CAACH,WAAW,GAAG;YAC5BE,QAAQE,MAAM,CAACJ,WAAW;QAC5B;QACA,IAAId,sBAAsBmB,OAAO,EAAE;YACjCJ;QACF,OAAO;YACLf,sBAAsBoB,gBAAgB,CAAC,SAASL,gBAAgB;gBAC9DM,MAAM;YACR;QACF;QAEA,IAAI;YACF,OAAO,MAAMpB,WAAWqB,gBAAgB,CAACpB,SAASQ;QACpD,EAAE,OAAM;YACN,qEAAqE;YACrE,0EAA0E;YAC1E,MAAMjB;YACN,OAAO;QACT,SAAU;YACR,kEAAkE;YAClE,yEAAyE;YACzE,4BAA4B;YAC5BO,sBAAsBuB,mBAAmB,CAAC,SAASR;QACrD;IACF;IAEA,6EAA6E;IAC7E,0EAA0E;IAC1E,8EAA8E;IAC9E,4BAA4B;IAC5BtD,oBAAoB;QAClB,KAAKgC;IACP;IAEAjC,uBAAuBsC;AACzB","ignoreList":[0]} |
| import '../require-hook'; | ||
| import '../node-environment'; | ||
| import { isAbsolute, relative } from 'path'; | ||
| import { readFileSync, realpathSync } from 'fs'; | ||
| import { fileURLToPath } from 'url'; | ||
| import { installBindings } from '../../build/swc/install-bindings'; | ||
| import { installCodeFrameSupport } from '../lib/install-code-frame'; | ||
| import { loadClientReferenceManifestForPage, loadComponents } from '../load-components'; | ||
| import { setHttpClientAndAgentOptions } from '../setup-http-agent-env'; | ||
| import { serializeValidationErrorsToFlight } from '../app-render/dev-validation-error-delivery'; | ||
| import { formatValidationEvent } from '../app-render/dev-validation-events'; | ||
| import { getServerActionsManifest, setManifestsSingleton } from '../app-render/manifests-singleton'; | ||
| import { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'; | ||
| /** | ||
| * Resolves a chunk's source map by reading the `.map` file the bundler emitted | ||
| * next to it, for chunks inside `distDir`. | ||
| * | ||
| * The main thread answers the same question through the Turbopack project | ||
| * handle, which cannot cross a thread boundary. Reading from disk is | ||
| * project-free and, more importantly, does not depend on the chunk having been | ||
| * evaluated in this thread: Node.js caches source maps per isolate, and the | ||
| * worker never renders server components, so it holds maps only for the chunks | ||
| * `loadComponents` pulled in. Frames arriving in the transported payload can | ||
| * point at any chunk the main render touched. | ||
| * | ||
| * This only helps Turbopack, which writes a `.map` beside every chunk. Webpack | ||
| * keeps its dev source maps in the compiler rather than on disk, so its frames | ||
| * from chunks this thread never evaluated stay unresolved, and its module URLs | ||
| * (`webpack-internal://…`) are declined below for the same reason. Frames from | ||
| * dependencies that are not bundled never reach this point, because | ||
| * `filterStackFrameDEV` drops `node_modules` and `node:` frames; bundled | ||
| * dependencies appear as chunks inside `distDir` like any other code. | ||
| */ function createDiskSourceMapLookup(distDir) { | ||
| // The frames carry resolved paths, so compare against the resolved `distDir` | ||
| // to keep the containment check meaningful when the project sits behind a | ||
| // symlink. | ||
| let canonicalDistDir = distDir; | ||
| try { | ||
| canonicalDistDir = realpathSync(distDir); | ||
| } catch {} | ||
| const payloads = new Map(); | ||
| return function findSourceMapPayloadOnDisk(sourceURL) { | ||
| let chunkPath = sourceURL; | ||
| if (chunkPath.startsWith('file://')) { | ||
| try { | ||
| chunkPath = fileURLToPath(chunkPath); | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } | ||
| if (!isAbsolute(chunkPath)) { | ||
| // Not an emitted chunk, e.g. `webpack-internal://` or `<anonymous>`. | ||
| return undefined; | ||
| } | ||
| const cached = payloads.get(chunkPath); | ||
| if (cached !== undefined || payloads.has(chunkPath)) { | ||
| return cached; | ||
| } | ||
| let payload; | ||
| const relativePath = relative(canonicalDistDir, chunkPath); | ||
| // Only chunks emitted into `distDir` have a source map to point at, and | ||
| // this keeps the lookup from reading arbitrary paths off disk. | ||
| if (!relativePath.startsWith('..') && !isAbsolute(relativePath)) { | ||
| try { | ||
| payload = JSON.parse(readFileSync(chunkPath + '.map', 'utf8')); | ||
| } catch { | ||
| payload = undefined; | ||
| } | ||
| } | ||
| payloads.set(chunkPath, payload); | ||
| return payload; | ||
| }; | ||
| } | ||
| // Match the main dev server (`next-dev-server.ts`), which raises this so the | ||
| // server captures deeper stacks. React's owner-stack capture during the | ||
| // validation prerenders depends on it, so without it the worker's errors lose | ||
| // their owner-stack source attribution. | ||
| try { | ||
| Error.stackTraceLimit = 50; | ||
| } catch {} | ||
| // The lifecycle markers E2E tests read from the CLI. Emitted on the worker's | ||
| // stdout (piped to the parent) so they interleave with the parent's captured | ||
| // output the same way the in-process `runWithDevValidationLogging` markers do. | ||
| // Gated on the same test env that path checks. | ||
| const isTestLoggingEnabled = !!(process.env.__NEXT_TEST_MODE && process.env.NEXT_TEST_LOG_VALIDATION); | ||
| /** | ||
| * Adapts the pool's supersede flag into an `AbortSignal` the validation passes | ||
| * check at their depth/yield boundaries. The pool shares an `Int32Array`-backed | ||
| * `SharedArrayBuffer` whose first slot the main thread flips to non-zero (with | ||
| * `Atomics.store` + `Atomics.notify`) when a newer navigation supersedes this | ||
| * one. We wait for that notification with `Atomics.waitAsync`, which is | ||
| * event-driven rather than polled. A validation that finishes without being | ||
| * superseded calls `cleanup()`, which wakes our own still-pending wait so it | ||
| * leaves no waiter (and no retained buffer) behind. | ||
| */ function createSupersedeSignal(abortBuffer) { | ||
| const controller = new AbortController(); | ||
| const flag = new Int32Array(abortBuffer); | ||
| if (Atomics.load(flag, 0) !== 0) { | ||
| controller.abort(); | ||
| return { | ||
| signal: controller.signal, | ||
| cleanup: ()=>{} | ||
| }; | ||
| } | ||
| let settled = false; | ||
| const wait = Atomics.waitAsync(flag, 0, 0); | ||
| if (wait.async) { | ||
| wait.value.then(()=>{ | ||
| if (settled) { | ||
| return; | ||
| } | ||
| settled = true; | ||
| // Woken either by a real supersede or by `cleanup()`; only the former | ||
| // leaves the flag set. | ||
| if (Atomics.load(flag, 0) !== 0) { | ||
| controller.abort(); | ||
| } | ||
| }); | ||
| } else if (Atomics.load(flag, 0) !== 0) { | ||
| // The flag flipped between the load above and the wait. | ||
| controller.abort(); | ||
| } | ||
| return { | ||
| signal: controller.signal, | ||
| cleanup: ()=>{ | ||
| if (!settled) { | ||
| Atomics.notify(flag, 0); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| /** | ||
| * Waits out the test-only validation delay, resolving early if the render is | ||
| * superseded. Mirrors the delay in `runWithDevValidationLogging` so scheduler | ||
| * tests observe the same in-flight window on the worker path. | ||
| */ async function applyTestValidationDelay(signal) { | ||
| const delayMs = Number(process.env.NEXT_TEST_DEV_VALIDATION_DELAY_MS); | ||
| if (!Number.isFinite(delayMs) || delayMs <= 0 || signal.aborted) { | ||
| return; | ||
| } | ||
| await new Promise((resolve)=>{ | ||
| const finishDelay = ()=>{ | ||
| clearTimeout(timeout); | ||
| signal.removeEventListener('abort', finishDelay); | ||
| resolve(); | ||
| }; | ||
| const timeout = setTimeout(finishDelay, delayMs); | ||
| signal.addEventListener('abort', finishDelay, { | ||
| once: true | ||
| }); | ||
| }); | ||
| } | ||
| /** | ||
| * Registers the client reference manifests of the pages that supplied client | ||
| * references to the render being validated, beyond the validated route's own | ||
| * manifest. This thread has its own manifests singleton, which `loadComponents` | ||
| * seeds with only the validated route, so without these the dev-only cross-page | ||
| * lookup in `createProxiedClientReferenceManifest` has no other manifest to | ||
| * search and decoding the transported payload fails. Usually a no-op, since the | ||
| * main thread only records a page when React's I/O tracking actually carried a | ||
| * reference across pages. | ||
| */ async function registerAdditionalClientReferenceManifests(distDir, pages) { | ||
| if (pages.length === 0) { | ||
| return; | ||
| } | ||
| // Set by `loadComponents`. One server actions manifest covers the whole app, | ||
| // so the pages registered here share the validated route's. | ||
| const serverActionsManifest = getServerActionsManifest(); | ||
| await Promise.all(pages.map(async (page)=>{ | ||
| const clientReferenceManifest = await loadClientReferenceManifestForPage(distDir, page); | ||
| if (clientReferenceManifest) { | ||
| setManifestsSingleton({ | ||
| page, | ||
| clientReferenceManifest, | ||
| serverActionsManifest | ||
| }); | ||
| } | ||
| })); | ||
| } | ||
| /** | ||
| * Runs the dev instant/static-shell validation passes off the main thread. | ||
| * Reloads the route's compiled module, then delegates the whole validation to | ||
| * that module via `ComponentMod.routeModule.runValidationInDev`, so every | ||
| * render (flight re-encodes and client prerenders) runs inside the app-page | ||
| * bundle's single React instance. Logs any returned errors to the worker's | ||
| * stderr with source-mapped code frames, then encodes them as RSC Flight bytes | ||
| * for the main thread to forward to the dev overlay. Returns `null` when | ||
| * validation was superseded or produced no errors. | ||
| */ export async function runDevValidation(message, abortBuffer) { | ||
| // Load the native SWC bindings and wire the code-frame renderer so the errors | ||
| // logged below render with a source-mapped code frame, matching the | ||
| // in-process dev output (the E2E tests snapshot the CLI text between the | ||
| // validation markers). The `build/swc` graph these pull in is bundled as a | ||
| // runtime external (see `next-runtime.webpack-config.js`), so it resolves | ||
| // from the installed `next/dist` tree rather than being compiled into this | ||
| // worker bundle, the same way the unbundled build worker loads it. | ||
| await installBindings(); | ||
| installCodeFrameSupport(); | ||
| setBundlerFindSourceMapImplementation(createDiskSourceMapLookup(message.distDir)); | ||
| setHttpClientAndAgentOptions({ | ||
| httpAgentOptions: message.nextConfigSerializable.httpAgentOptions | ||
| }); | ||
| // Populates the manifests singleton for the route via `setManifestsSingleton` | ||
| // inside `loadComponents`, exactly as a real request does. The pool tears the | ||
| // worker down on HMR / route recompile so the next validation reloads from a | ||
| // clean require cache. | ||
| const { ComponentMod } = await loadComponents({ | ||
| distDir: message.distDir, | ||
| page: message.page, | ||
| isAppPath: true, | ||
| isDev: true, | ||
| sriEnabled: false, | ||
| needsManifestsForLegacyReasons: true | ||
| }); | ||
| await registerAdditionalClientReferenceManifests(message.distDir, message.additionalClientReferenceManifestPages); | ||
| const { signal, cleanup } = createSupersedeSignal(abortBuffer); | ||
| if (isTestLoggingEnabled) { | ||
| console.log(formatValidationEvent({ | ||
| type: 'validation_start', | ||
| requestId: message.requestId, | ||
| url: message.request.urlPathname + message.request.urlSearch, | ||
| responseFinished: message.responseFinished | ||
| })); | ||
| } | ||
| try { | ||
| if (isTestLoggingEnabled) { | ||
| await applyTestValidationDelay(signal); | ||
| } | ||
| if (signal.aborted) { | ||
| return null; | ||
| } | ||
| // Crossing into the app-page bundle: the entire validation runs there, so | ||
| // the client prerenders use the same React the user's client components | ||
| // resolve through `ComponentMod`. | ||
| const validationErrors = await ComponentMod.routeModule.runValidationInDev(ComponentMod, message, signal); | ||
| if (validationErrors === undefined || signal.aborted) { | ||
| return null; | ||
| } | ||
| const errors = []; | ||
| for (const validationError of validationErrors){ | ||
| // Log to the worker's stderr; `node-environment` + | ||
| // `installCodeFrameSupport` render the source-mapped stack and code frame | ||
| // there, matching the in-process CLI output. | ||
| console.error(validationError); | ||
| if (validationError instanceof Error) { | ||
| errors.push(validationError); | ||
| } | ||
| } | ||
| if (errors.length === 0) { | ||
| return null; | ||
| } | ||
| return await serializeValidationErrorsToFlight(ComponentMod, errors); | ||
| } finally{ | ||
| cleanup(); | ||
| if (isTestLoggingEnabled) { | ||
| console.log(formatValidationEvent({ | ||
| type: signal.aborted ? 'validation_aborted' : 'validation_end', | ||
| requestId: message.requestId, | ||
| url: message.request.urlPathname + message.request.urlSearch | ||
| })); | ||
| } | ||
| } | ||
| } | ||
| //# sourceMappingURL=dev-validation-worker.js.map |
| {"version":3,"sources":["../../../../src/server/dev/dev-validation-worker.ts"],"sourcesContent":["import type { AppPageModule } from '../route-modules/app-page/module'\nimport type {\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\n\nimport '../require-hook'\nimport '../node-environment'\n\nimport { isAbsolute, relative } from 'path'\nimport { readFileSync, realpathSync } from 'fs'\nimport { fileURLToPath } from 'url'\nimport { installBindings } from '../../build/swc/install-bindings'\nimport { installCodeFrameSupport } from '../lib/install-code-frame'\nimport {\n loadClientReferenceManifestForPage,\n loadComponents,\n} from '../load-components'\nimport { setHttpClientAndAgentOptions } from '../setup-http-agent-env'\nimport { serializeValidationErrorsToFlight } from '../app-render/dev-validation-error-delivery'\nimport { formatValidationEvent } from '../app-render/dev-validation-events'\nimport {\n getServerActionsManifest,\n setManifestsSingleton,\n} from '../app-render/manifests-singleton'\nimport { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'\nimport type { ModernSourceMapPayload } from '../lib/source-maps'\n\n/**\n * Resolves a chunk's source map by reading the `.map` file the bundler emitted\n * next to it, for chunks inside `distDir`.\n *\n * The main thread answers the same question through the Turbopack project\n * handle, which cannot cross a thread boundary. Reading from disk is\n * project-free and, more importantly, does not depend on the chunk having been\n * evaluated in this thread: Node.js caches source maps per isolate, and the\n * worker never renders server components, so it holds maps only for the chunks\n * `loadComponents` pulled in. Frames arriving in the transported payload can\n * point at any chunk the main render touched.\n *\n * This only helps Turbopack, which writes a `.map` beside every chunk. Webpack\n * keeps its dev source maps in the compiler rather than on disk, so its frames\n * from chunks this thread never evaluated stay unresolved, and its module URLs\n * (`webpack-internal://…`) are declined below for the same reason. Frames from\n * dependencies that are not bundled never reach this point, because\n * `filterStackFrameDEV` drops `node_modules` and `node:` frames; bundled\n * dependencies appear as chunks inside `distDir` like any other code.\n */\nfunction createDiskSourceMapLookup(\n distDir: string\n): (sourceURL: string) => ModernSourceMapPayload | undefined {\n // The frames carry resolved paths, so compare against the resolved `distDir`\n // to keep the containment check meaningful when the project sits behind a\n // symlink.\n let canonicalDistDir = distDir\n try {\n canonicalDistDir = realpathSync(distDir)\n } catch {}\n\n const payloads = new Map<string, ModernSourceMapPayload | undefined>()\n\n return function findSourceMapPayloadOnDisk(sourceURL) {\n let chunkPath = sourceURL\n\n if (chunkPath.startsWith('file://')) {\n try {\n chunkPath = fileURLToPath(chunkPath)\n } catch {\n return undefined\n }\n }\n\n if (!isAbsolute(chunkPath)) {\n // Not an emitted chunk, e.g. `webpack-internal://` or `<anonymous>`.\n return undefined\n }\n\n const cached = payloads.get(chunkPath)\n if (cached !== undefined || payloads.has(chunkPath)) {\n return cached\n }\n\n let payload: ModernSourceMapPayload | undefined\n const relativePath = relative(canonicalDistDir, chunkPath)\n\n // Only chunks emitted into `distDir` have a source map to point at, and\n // this keeps the lookup from reading arbitrary paths off disk.\n if (!relativePath.startsWith('..') && !isAbsolute(relativePath)) {\n try {\n payload = JSON.parse(readFileSync(chunkPath + '.map', 'utf8'))\n } catch {\n payload = undefined\n }\n }\n\n payloads.set(chunkPath, payload)\n\n return payload\n }\n}\n\n// Match the main dev server (`next-dev-server.ts`), which raises this so the\n// server captures deeper stacks. React's owner-stack capture during the\n// validation prerenders depends on it, so without it the worker's errors lose\n// their owner-stack source attribution.\ntry {\n Error.stackTraceLimit = 50\n} catch {}\n\n// The lifecycle markers E2E tests read from the CLI. Emitted on the worker's\n// stdout (piped to the parent) so they interleave with the parent's captured\n// output the same way the in-process `runWithDevValidationLogging` markers do.\n// Gated on the same test env that path checks.\nconst isTestLoggingEnabled = !!(\n process.env.__NEXT_TEST_MODE && process.env.NEXT_TEST_LOG_VALIDATION\n)\n\n/**\n * Adapts the pool's supersede flag into an `AbortSignal` the validation passes\n * check at their depth/yield boundaries. The pool shares an `Int32Array`-backed\n * `SharedArrayBuffer` whose first slot the main thread flips to non-zero (with\n * `Atomics.store` + `Atomics.notify`) when a newer navigation supersedes this\n * one. We wait for that notification with `Atomics.waitAsync`, which is\n * event-driven rather than polled. A validation that finishes without being\n * superseded calls `cleanup()`, which wakes our own still-pending wait so it\n * leaves no waiter (and no retained buffer) behind.\n */\nfunction createSupersedeSignal(abortBuffer: SharedArrayBuffer): {\n signal: AbortSignal\n cleanup: () => void\n} {\n const controller = new AbortController()\n const flag = new Int32Array(abortBuffer)\n\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n let settled = false\n const wait = Atomics.waitAsync(flag, 0, 0)\n if (wait.async) {\n wait.value.then(() => {\n if (settled) {\n return\n }\n settled = true\n // Woken either by a real supersede or by `cleanup()`; only the former\n // leaves the flag set.\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n }\n })\n } else if (Atomics.load(flag, 0) !== 0) {\n // The flag flipped between the load above and the wait.\n controller.abort()\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (!settled) {\n Atomics.notify(flag, 0)\n }\n },\n }\n}\n\n/**\n * Waits out the test-only validation delay, resolving early if the render is\n * superseded. Mirrors the delay in `runWithDevValidationLogging` so scheduler\n * tests observe the same in-flight window on the worker path.\n */\nasync function applyTestValidationDelay(signal: AbortSignal): Promise<void> {\n const delayMs = Number(process.env.NEXT_TEST_DEV_VALIDATION_DELAY_MS)\n if (!Number.isFinite(delayMs) || delayMs <= 0 || signal.aborted) {\n return\n }\n\n await new Promise<void>((resolve) => {\n const finishDelay = () => {\n clearTimeout(timeout)\n signal.removeEventListener('abort', finishDelay)\n resolve()\n }\n const timeout = setTimeout(finishDelay, delayMs)\n signal.addEventListener('abort', finishDelay, { once: true })\n })\n}\n\n/**\n * Registers the client reference manifests of the pages that supplied client\n * references to the render being validated, beyond the validated route's own\n * manifest. This thread has its own manifests singleton, which `loadComponents`\n * seeds with only the validated route, so without these the dev-only cross-page\n * lookup in `createProxiedClientReferenceManifest` has no other manifest to\n * search and decoding the transported payload fails. Usually a no-op, since the\n * main thread only records a page when React's I/O tracking actually carried a\n * reference across pages.\n */\nasync function registerAdditionalClientReferenceManifests(\n distDir: string,\n pages: string[]\n): Promise<void> {\n if (pages.length === 0) {\n return\n }\n\n // Set by `loadComponents`. One server actions manifest covers the whole app,\n // so the pages registered here share the validated route's.\n const serverActionsManifest = getServerActionsManifest()\n\n await Promise.all(\n pages.map(async (page) => {\n const clientReferenceManifest = await loadClientReferenceManifestForPage(\n distDir,\n page\n )\n\n if (clientReferenceManifest) {\n setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n })\n )\n}\n\n/**\n * Runs the dev instant/static-shell validation passes off the main thread.\n * Reloads the route's compiled module, then delegates the whole validation to\n * that module via `ComponentMod.routeModule.runValidationInDev`, so every\n * render (flight re-encodes and client prerenders) runs inside the app-page\n * bundle's single React instance. Logs any returned errors to the worker's\n * stderr with source-mapped code frames, then encodes them as RSC Flight bytes\n * for the main thread to forward to the dev overlay. Returns `null` when\n * validation was superseded or produced no errors.\n */\nexport async function runDevValidation(\n message: DevValidationWorkerMessage,\n abortBuffer: SharedArrayBuffer\n): Promise<DevValidationWorkerResult> {\n // Load the native SWC bindings and wire the code-frame renderer so the errors\n // logged below render with a source-mapped code frame, matching the\n // in-process dev output (the E2E tests snapshot the CLI text between the\n // validation markers). The `build/swc` graph these pull in is bundled as a\n // runtime external (see `next-runtime.webpack-config.js`), so it resolves\n // from the installed `next/dist` tree rather than being compiled into this\n // worker bundle, the same way the unbundled build worker loads it.\n await installBindings()\n installCodeFrameSupport()\n setBundlerFindSourceMapImplementation(\n createDiskSourceMapLookup(message.distDir)\n )\n setHttpClientAndAgentOptions({\n httpAgentOptions: message.nextConfigSerializable.httpAgentOptions,\n })\n\n // Populates the manifests singleton for the route via `setManifestsSingleton`\n // inside `loadComponents`, exactly as a real request does. The pool tears the\n // worker down on HMR / route recompile so the next validation reloads from a\n // clean require cache.\n const { ComponentMod } = await loadComponents<AppPageModule>({\n distDir: message.distDir,\n page: message.page,\n isAppPath: true,\n isDev: true,\n sriEnabled: false,\n needsManifestsForLegacyReasons: true,\n })\n\n await registerAdditionalClientReferenceManifests(\n message.distDir,\n message.additionalClientReferenceManifestPages\n )\n\n const { signal, cleanup } = createSupersedeSignal(abortBuffer)\n\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: 'validation_start',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n responseFinished: message.responseFinished,\n })\n )\n }\n\n try {\n if (isTestLoggingEnabled) {\n await applyTestValidationDelay(signal)\n }\n\n if (signal.aborted) {\n return null\n }\n\n // Crossing into the app-page bundle: the entire validation runs there, so\n // the client prerenders use the same React the user's client components\n // resolve through `ComponentMod`.\n const validationErrors = await ComponentMod.routeModule.runValidationInDev(\n ComponentMod,\n message,\n signal\n )\n\n if (validationErrors === undefined || signal.aborted) {\n return null\n }\n\n const errors: Error[] = []\n for (const validationError of validationErrors) {\n // Log to the worker's stderr; `node-environment` +\n // `installCodeFrameSupport` render the source-mapped stack and code frame\n // there, matching the in-process CLI output.\n console.error(validationError)\n if (validationError instanceof Error) {\n errors.push(validationError)\n }\n }\n\n if (errors.length === 0) {\n return null\n }\n\n return await serializeValidationErrorsToFlight(ComponentMod, errors)\n } finally {\n cleanup()\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: signal.aborted ? 'validation_aborted' : 'validation_end',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n })\n )\n }\n }\n}\n"],"names":["isAbsolute","relative","readFileSync","realpathSync","fileURLToPath","installBindings","installCodeFrameSupport","loadClientReferenceManifestForPage","loadComponents","setHttpClientAndAgentOptions","serializeValidationErrorsToFlight","formatValidationEvent","getServerActionsManifest","setManifestsSingleton","setBundlerFindSourceMapImplementation","createDiskSourceMapLookup","distDir","canonicalDistDir","payloads","Map","findSourceMapPayloadOnDisk","sourceURL","chunkPath","startsWith","undefined","cached","get","has","payload","relativePath","JSON","parse","set","Error","stackTraceLimit","isTestLoggingEnabled","process","env","__NEXT_TEST_MODE","NEXT_TEST_LOG_VALIDATION","createSupersedeSignal","abortBuffer","controller","AbortController","flag","Int32Array","Atomics","load","abort","signal","cleanup","settled","wait","waitAsync","async","value","then","notify","applyTestValidationDelay","delayMs","Number","NEXT_TEST_DEV_VALIDATION_DELAY_MS","isFinite","aborted","Promise","resolve","finishDelay","clearTimeout","timeout","removeEventListener","setTimeout","addEventListener","once","registerAdditionalClientReferenceManifests","pages","length","serverActionsManifest","all","map","page","clientReferenceManifest","runDevValidation","message","httpAgentOptions","nextConfigSerializable","ComponentMod","isAppPath","isDev","sriEnabled","needsManifestsForLegacyReasons","additionalClientReferenceManifestPages","console","log","type","requestId","url","request","urlPathname","urlSearch","responseFinished","validationErrors","routeModule","runValidationInDev","errors","validationError","error","push"],"mappings":"AAMA,OAAO,kBAAiB;AACxB,OAAO,sBAAqB;AAE5B,SAASA,UAAU,EAAEC,QAAQ,QAAQ,OAAM;AAC3C,SAASC,YAAY,EAAEC,YAAY,QAAQ,KAAI;AAC/C,SAASC,aAAa,QAAQ,MAAK;AACnC,SAASC,eAAe,QAAQ,mCAAkC;AAClE,SAASC,uBAAuB,QAAQ,4BAA2B;AACnE,SACEC,kCAAkC,EAClCC,cAAc,QACT,qBAAoB;AAC3B,SAASC,4BAA4B,QAAQ,0BAAyB;AACtE,SAASC,iCAAiC,QAAQ,8CAA6C;AAC/F,SAASC,qBAAqB,QAAQ,sCAAqC;AAC3E,SACEC,wBAAwB,EACxBC,qBAAqB,QAChB,oCAAmC;AAC1C,SAASC,qCAAqC,QAAQ,yBAAwB;AAG9E;;;;;;;;;;;;;;;;;;;CAmBC,GACD,SAASC,0BACPC,OAAe;IAEf,6EAA6E;IAC7E,0EAA0E;IAC1E,WAAW;IACX,IAAIC,mBAAmBD;IACvB,IAAI;QACFC,mBAAmBd,aAAaa;IAClC,EAAE,OAAM,CAAC;IAET,MAAME,WAAW,IAAIC;IAErB,OAAO,SAASC,2BAA2BC,SAAS;QAClD,IAAIC,YAAYD;QAEhB,IAAIC,UAAUC,UAAU,CAAC,YAAY;YACnC,IAAI;gBACFD,YAAYlB,cAAckB;YAC5B,EAAE,OAAM;gBACN,OAAOE;YACT;QACF;QAEA,IAAI,CAACxB,WAAWsB,YAAY;YAC1B,qEAAqE;YACrE,OAAOE;QACT;QAEA,MAAMC,SAASP,SAASQ,GAAG,CAACJ;QAC5B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MjE,kCAAkC2E,cAAckB;IAC/D,SAAU;QACRrD;QACA,IAAIf,sBAAsB;YACxBwD,QAAQC,GAAG,CACTjF,sBAAsB;gBACpBkF,MAAM5C,OAAOc,OAAO,GAAG,uBAAuB;gBAC9C+B,WAAWZ,QAAQY,SAAS;gBAC5BC,KAAKb,QAAQc,OAAO,CAACC,WAAW,GAAGf,QAAQc,OAAO,CAACE,SAAS;YAC9D;QAEJ;IACF;AACF","ignoreList":[0]} |
| import { Duplex } from 'node:stream'; | ||
| const noop = ()=>{}; | ||
| /** | ||
| * Destroys the zlib stream that the `compression` middleware left open on a | ||
| * response that never finished. | ||
| * | ||
| * The middleware ends its stream only from its own `res.end()` wrapper, so a | ||
| * client disconnect leaves it open, and an open zlib stream is pinned by its | ||
| * native handle: it survives GC, permanently retaining ~256 KiB of deflate | ||
| * state. Ending it rather than destroying it does not work -- its `data` handler | ||
| * writes to the dead response, `res.write()` returns `false`, and the middleware | ||
| * pauses the stream, so it never reaches `end`. | ||
| * | ||
| * `res.on('drain', …)` is forwarded to that stream and `EventEmitter#on` returns | ||
| * the emitter, which is the only handle to it from outside. When compression is | ||
| * inactive the call returns `res` itself. | ||
| */ export function releaseCompressionStream(res) { | ||
| const maybeStream = res.on('drain', noop); | ||
| // The `Duplex` check keeps a future middleware change from turning this into a | ||
| // `destroy()` on a non-stream, which would throw from a `close` handler. | ||
| if (maybeStream === res || !(maybeStream instanceof Duplex)) { | ||
| res.off('drain', noop); | ||
| return; | ||
| } | ||
| maybeStream.destroy(); | ||
| } | ||
| //# sourceMappingURL=release-compression-stream.js.map |
| {"version":3,"sources":["../../../../src/server/lib/release-compression-stream.ts"],"sourcesContent":["import type { ServerResponse } from 'node:http'\nimport { Duplex } from 'node:stream'\n\nconst noop = () => {}\n\n/**\n * Destroys the zlib stream that the `compression` middleware left open on a\n * response that never finished.\n *\n * The middleware ends its stream only from its own `res.end()` wrapper, so a\n * client disconnect leaves it open, and an open zlib stream is pinned by its\n * native handle: it survives GC, permanently retaining ~256 KiB of deflate\n * state. Ending it rather than destroying it does not work -- its `data` handler\n * writes to the dead response, `res.write()` returns `false`, and the middleware\n * pauses the stream, so it never reaches `end`.\n *\n * `res.on('drain', …)` is forwarded to that stream and `EventEmitter#on` returns\n * the emitter, which is the only handle to it from outside. When compression is\n * inactive the call returns `res` itself.\n */\nexport function releaseCompressionStream(res: ServerResponse): void {\n const maybeStream: unknown = res.on('drain', noop)\n\n // The `Duplex` check keeps a future middleware change from turning this into a\n // `destroy()` on a non-stream, which would throw from a `close` handler.\n if (maybeStream === res || !(maybeStream instanceof Duplex)) {\n res.off('drain', noop)\n return\n }\n\n maybeStream.destroy()\n}\n"],"names":["Duplex","noop","releaseCompressionStream","res","maybeStream","on","off","destroy"],"mappings":"AACA,SAASA,MAAM,QAAQ,cAAa;AAEpC,MAAMC,OAAO,KAAO;AAEpB;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,yBAAyBC,GAAmB;IAC1D,MAAMC,cAAuBD,IAAIE,EAAE,CAAC,SAASJ;IAE7C,+EAA+E;IAC/E,yEAAyE;IACzE,IAAIG,gBAAgBD,OAAO,CAAEC,CAAAA,uBAAuBJ,MAAK,GAAI;QAC3DG,IAAIG,GAAG,CAAC,SAASL;QACjB;IACF;IAEAG,YAAYG,OAAO;AACrB","ignoreList":[0]} |
| import type { AppPageModule } from '../route-modules/app-page/module'; | ||
| /** | ||
| * Encodes dev-validation errors into the RSC Flight bytes the dev overlay | ||
| * revives. Must run in the runtime that produced the errors (the in-process | ||
| * render or the validation worker) so the encode uses the matching | ||
| * client-reference manifest and captures the live `Error` objects with their | ||
| * stacks and digests. The error codes ride along in a side-channel `Map` | ||
| * because React doesn't revive `__NEXT_ERROR_CODE` during RSC deserialization; | ||
| * RSC preserves object identity, so the revived map keys reference the same | ||
| * errors. | ||
| */ | ||
| export declare function serializeValidationErrorsToFlight(componentMod: AppPageModule, errors: Error[]): Promise<Uint8Array[]>; |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { | ||
| value: true | ||
| }); | ||
| Object.defineProperty(exports, "serializeValidationErrorsToFlight", { | ||
| enumerable: true, | ||
| get: function() { | ||
| return serializeValidationErrorsToFlight; | ||
| } | ||
| }); | ||
| const _streamops = require("./stream-ops"); | ||
| const _manifestssingleton = require("./manifests-singleton"); | ||
| const _errortelemetryutils = require("../../lib/error-telemetry-utils"); | ||
| const filterStackFrame = process.env.NODE_ENV !== 'production' ? require('../lib/source-maps').filterStackFrameDEV : undefined; | ||
| async function serializeValidationErrorsToFlight(componentMod, errors) { | ||
| const errorCodes = new Map(); | ||
| for (const err of errors){ | ||
| const code = (0, _errortelemetryutils.extractNextErrorCode)(err); | ||
| if (code !== undefined) { | ||
| errorCodes.set(err, code); | ||
| } | ||
| } | ||
| const { clientModules } = (0, _manifestssingleton.getClientReferenceManifest)(); | ||
| const stream = (0, _streamops.renderToNodeFlightStream)(componentMod, { | ||
| errors, | ||
| errorCodes | ||
| }, clientModules, { | ||
| filterStackFrame | ||
| }); | ||
| const chunks = []; | ||
| for await (const chunk of stream){ | ||
| chunks.push(chunk); | ||
| } | ||
| return chunks; | ||
| } | ||
| //# sourceMappingURL=dev-validation-error-delivery.js.map |
| {"version":3,"sources":["../../../src/server/app-render/dev-validation-error-delivery.ts"],"sourcesContent":["import type { AppPageModule } from '../route-modules/app-page/module'\nimport { renderToNodeFlightStream } from './stream-ops'\nimport { getClientReferenceManifest } from './manifests-singleton'\nimport { extractNextErrorCode } from '../../lib/error-telemetry-utils'\n\nconst filterStackFrame =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .filterStackFrameDEV\n : undefined\n\n/**\n * Encodes dev-validation errors into the RSC Flight bytes the dev overlay\n * revives. Must run in the runtime that produced the errors (the in-process\n * render or the validation worker) so the encode uses the matching\n * client-reference manifest and captures the live `Error` objects with their\n * stacks and digests. The error codes ride along in a side-channel `Map`\n * because React doesn't revive `__NEXT_ERROR_CODE` during RSC deserialization;\n * RSC preserves object identity, so the revived map keys reference the same\n * errors.\n */\nexport async function serializeValidationErrorsToFlight(\n componentMod: AppPageModule,\n errors: Error[]\n): Promise<Uint8Array[]> {\n const errorCodes = new Map<Error, string>()\n for (const err of errors) {\n const code = extractNextErrorCode(err)\n if (code !== undefined) {\n errorCodes.set(err, code)\n }\n }\n\n const { clientModules } = getClientReferenceManifest()\n\n const stream = renderToNodeFlightStream(\n componentMod,\n { errors, errorCodes },\n clientModules,\n { filterStackFrame }\n )\n\n const chunks: Uint8Array[] = []\n for await (const chunk of stream) {\n chunks.push(chunk)\n }\n return chunks\n}\n"],"names":["serializeValidationErrorsToFlight","filterStackFrame","process","env","NODE_ENV","require","filterStackFrameDEV","undefined","componentMod","errors","errorCodes","Map","err","code","extractNextErrorCode","set","clientModules","getClientReferenceManifest","stream","renderToNodeFlightStream","chunks","chunk","push"],"mappings":";;;;+BAqBsBA;;;eAAAA;;;2BApBmB;oCACE;qCACN;AAErC,MAAMC,mBACJC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eACrB,AAACC,QAAQ,sBACNC,mBAAmB,GACtBC;AAYC,eAAeP,kCACpBQ,YAA2B,EAC3BC,MAAe;IAEf,MAAMC,aAAa,IAAIC;IACvB,KAAK,MAAMC,OAAOH,OAAQ;QACxB,MAAMI,OAAOC,IAAAA,yCAAoB,EAACF;QAClC,IAAIC,SAASN,WAAW;YACtBG,WAAWK,GAAG,CAACH,KAAKC;QACtB;IACF;IAEA,MAAM,EAAEG,aAAa,EAAE,GAAGC,IAAAA,8CAA0B;IAEpD,MAAMC,SAASC,IAAAA,mCAAwB,EACrCX,cACA;QAAEC;QAAQC;IAAW,GACrBM,eACA;QAAEf;IAAiB;IAGrB,MAAMmB,SAAuB,EAAE;IAC/B,WAAW,MAAMC,SAASH,OAAQ;QAChCE,OAAOE,IAAI,CAACD;IACd;IACA,OAAOD;AACT","ignoreList":[0]} |
| /** | ||
| * The lifecycle events Cache Components validation emits so E2E tests can | ||
| * locate the validation window in the CLI output. Each is serialized between | ||
| * `<VALIDATION_MESSAGE>` delimiters (see `formatValidationEvent`) and parsed | ||
| * back by the test harness. Produced by the in-process validation in | ||
| * `app-render.tsx` (both dev and build) and by the validation worker, which is | ||
| * why the shape lives here rather than in a single producer. | ||
| * | ||
| * `requestId` correlates a start with its matching end/aborted. Dev and worker | ||
| * validation use the render's request id; build validation, which has no such | ||
| * id, uses a stringified timestamp instead. | ||
| */ | ||
| export type ValidationEvent = ValidationStartEvent | ValidationEndEvent | ValidationAbortedEvent; | ||
| export type ValidationStartEvent = { | ||
| type: 'validation_start'; | ||
| requestId: string; | ||
| url: string; | ||
| /** | ||
| * Only reported for development validation. | ||
| */ | ||
| responseFinished?: boolean; | ||
| }; | ||
| export type ValidationEndEvent = { | ||
| type: 'validation_end'; | ||
| requestId: string; | ||
| url: string; | ||
| }; | ||
| /** | ||
| * Emitted when detached validation is aborted. It can appear without a start | ||
| * when cancellation happens before validation runs, or after a start instead of | ||
| * an end when in-flight validation is cancelled. | ||
| */ | ||
| export type ValidationAbortedEvent = { | ||
| type: 'validation_aborted'; | ||
| requestId: string; | ||
| url: string; | ||
| }; | ||
| /** | ||
| * Wraps a validation event in the `<VALIDATION_MESSAGE>` delimiters the test | ||
| * harness scans for. The caller chooses the output stream (dev validation logs | ||
| * to stdout; build validation uses stderr for deterministic ordering). | ||
| */ | ||
| export declare function formatValidationEvent(event: ValidationEvent): string; |
| /** | ||
| * The lifecycle events Cache Components validation emits so E2E tests can | ||
| * locate the validation window in the CLI output. Each is serialized between | ||
| * `<VALIDATION_MESSAGE>` delimiters (see `formatValidationEvent`) and parsed | ||
| * back by the test harness. Produced by the in-process validation in | ||
| * `app-render.tsx` (both dev and build) and by the validation worker, which is | ||
| * why the shape lives here rather than in a single producer. | ||
| * | ||
| * `requestId` correlates a start with its matching end/aborted. Dev and worker | ||
| * validation use the render's request id; build validation, which has no such | ||
| * id, uses a stringified timestamp instead. | ||
| */ "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { | ||
| value: true | ||
| }); | ||
| Object.defineProperty(exports, "formatValidationEvent", { | ||
| enumerable: true, | ||
| get: function() { | ||
| return formatValidationEvent; | ||
| } | ||
| }); | ||
| function formatValidationEvent(event) { | ||
| return '<VALIDATION_MESSAGE>' + JSON.stringify(event) + '</VALIDATION_MESSAGE>'; | ||
| } | ||
| //# sourceMappingURL=dev-validation-events.js.map |
| {"version":3,"sources":["../../../src/server/app-render/dev-validation-events.ts"],"sourcesContent":["/**\n * The lifecycle events Cache Components validation emits so E2E tests can\n * locate the validation window in the CLI output. Each is serialized between\n * `<VALIDATION_MESSAGE>` delimiters (see `formatValidationEvent`) and parsed\n * back by the test harness. Produced by the in-process validation in\n * `app-render.tsx` (both dev and build) and by the validation worker, which is\n * why the shape lives here rather than in a single producer.\n *\n * `requestId` correlates a start with its matching end/aborted. Dev and worker\n * validation use the render's request id; build validation, which has no such\n * id, uses a stringified timestamp instead.\n */\nexport type ValidationEvent =\n | ValidationStartEvent\n | ValidationEndEvent\n | ValidationAbortedEvent\n\nexport type ValidationStartEvent = {\n type: 'validation_start'\n requestId: string\n url: string\n /**\n * Only reported for development validation.\n */\n responseFinished?: boolean\n}\n\nexport type ValidationEndEvent = {\n type: 'validation_end'\n requestId: string\n url: string\n}\n\n/**\n * Emitted when detached validation is aborted. It can appear without a start\n * when cancellation happens before validation runs, or after a start instead of\n * an end when in-flight validation is cancelled.\n */\nexport type ValidationAbortedEvent = {\n type: 'validation_aborted'\n requestId: string\n url: string\n}\n\n/**\n * Wraps a validation event in the `<VALIDATION_MESSAGE>` delimiters the test\n * harness scans for. The caller chooses the output stream (dev validation logs\n * to stdout; build validation uses stderr for deterministic ordering).\n */\nexport function formatValidationEvent(event: ValidationEvent): string {\n return (\n '<VALIDATION_MESSAGE>' + JSON.stringify(event) + '</VALIDATION_MESSAGE>'\n )\n}\n"],"names":["formatValidationEvent","event","JSON","stringify"],"mappings":"AAAA;;;;;;;;;;;CAWC;;;;+BAsCeA;;;eAAAA;;;AAAT,SAASA,sBAAsBC,KAAsB;IAC1D,OACE,yBAAyBC,KAAKC,SAAS,CAACF,SAAS;AAErD","ignoreList":[0]} |
| import type { Params } from '../request/params'; | ||
| import type { OpaqueFallbackRouteParams } from '../request/fallback-params'; | ||
| import type { NextParsedUrlQuery } from '../request-meta'; | ||
| import type { PrefetchingMode } from './app-render'; | ||
| import type { NextConfigComplete, ValidationLevel } from '../config-shared'; | ||
| import type { ImageConfigComplete } from '../../shared/lib/image-config'; | ||
| /** | ||
| * Per-stage RSC chunks, the serializable form of `AccumulatedStreamChunks` that | ||
| * the worker replays. No live streams cross the boundary. | ||
| */ | ||
| export interface SerializedAccumulatedChunks { | ||
| shellStaticChunks: Uint8Array[]; | ||
| staticChunks: Uint8Array[]; | ||
| shellRuntimeChunks: Uint8Array[]; | ||
| runtimeChunks: Uint8Array[]; | ||
| dynamicChunks: Uint8Array[]; | ||
| } | ||
| /** | ||
| * Serializable view of one validation input (the shape `DevValidationInputs` | ||
| * carries), with the live streams already drained to chunks. The stage-end | ||
| * timings are replayed into the per-depth Flight re-encodes so the worker | ||
| * reconstructs the same partial-stage boundaries the main render observed. | ||
| */ | ||
| export interface SerializedValidationInputs { | ||
| accumulatedChunks: SerializedAccumulatedChunks; | ||
| debugChunks: Uint8Array[] | null; | ||
| startTime: number; | ||
| staticStageEndTime: number; | ||
| runtimeStageEndTime: number; | ||
| } | ||
| /** | ||
| * Serializable view of the request, rebuilt into a `RequestStore` on the worker | ||
| * so `cookies()` / `headers()` / `draftMode()` behave as in the real render. | ||
| */ | ||
| export interface DevValidationRequestSnapshot { | ||
| headers: [string, string][]; | ||
| urlPathname: string; | ||
| urlSearch: string; | ||
| rootParams: Params; | ||
| isDraftMode: boolean; | ||
| isHmrRefresh: boolean; | ||
| hmrRefreshHash: string | undefined; | ||
| } | ||
| /** | ||
| * Everything the worker needs to rebuild the render context and inputs and run | ||
| * `runValidationInDev`. Built on the main thread from the settled render; the | ||
| * pool augments it with install-time fields (`distDir`, `buildId`, …). | ||
| */ | ||
| export interface DevValidationSnapshot { | ||
| page: string; | ||
| route: string; | ||
| requestId: string; | ||
| responseFinished: boolean; | ||
| prefetchMode: PrefetchingMode; | ||
| devRenderDidError: boolean; | ||
| nonce: string | undefined; | ||
| query: NextParsedUrlQuery; | ||
| request: DevValidationRequestSnapshot; | ||
| interpolatedParams: Params; | ||
| requestFallbackRouteParams: OpaqueFallbackRouteParams | null; | ||
| fallbackRouteParams: OpaqueFallbackRouteParams | null; | ||
| optimisticRouting: boolean; | ||
| forceStatic: boolean | undefined; | ||
| validationLevel: ValidationLevel; | ||
| implicitTags: string[]; | ||
| /** | ||
| * Pages whose client reference manifests supplied client references to the | ||
| * render being validated, beyond the validated route's own manifest (see | ||
| * `WorkStore.additionalClientReferenceManifestPages`). The worker registers | ||
| * these so the same references resolve in its thread. Empty for all but the | ||
| * rare renders that React's I/O tracking carries a reference into. | ||
| */ | ||
| additionalClientReferenceManifestPages: string[]; | ||
| isDebugChannelEnabled: boolean; | ||
| renderOpts: { | ||
| images: ImageConfigComplete; | ||
| allowEmptyStaticShell: boolean | undefined; | ||
| }; | ||
| instantInputs: SerializedValidationInputs | null; | ||
| staticInputs: SerializedValidationInputs; | ||
| } | ||
| /** | ||
| * Install-time fields the dev server's worker pool augments the snapshot with | ||
| * so the worker can reload the route (`distDir`; `page` comes from the | ||
| * snapshot) and rebuild the work store (`buildId`, `deploymentId`, the config | ||
| * slice). | ||
| */ | ||
| export interface DevValidationInstallFields { | ||
| distDir: string; | ||
| buildId: string; | ||
| deploymentId: string; | ||
| nextConfigSerializable: { | ||
| httpAgentOptions: NextConfigComplete['httpAgentOptions']; | ||
| cacheLifeProfiles: NextConfigComplete['cacheLife']; | ||
| useCacheTimeout: number; | ||
| staticPageGenerationTimeout: number; | ||
| }; | ||
| } | ||
| /** | ||
| * The full message the worker receives and forwards into the in-bundle entry: | ||
| * the main-thread snapshot plus the pool's install-time fields. | ||
| */ | ||
| export type DevValidationWorkerMessage = DevValidationSnapshot & DevValidationInstallFields; | ||
| /** | ||
| * The RSC-encoded `{ errors, errorCodes }` Flight chunks for the dev overlay, | ||
| * or null when validation produced no errors or was aborted. The worker also | ||
| * logs the errors to its own stderr (piped to the parent) with code frames. | ||
| */ | ||
| export type DevValidationWorkerResult = Uint8Array[] | null; | ||
| /** | ||
| * Worker hook installed by the dev server. Given the render snapshot and the | ||
| * validation abort signal, runs validation on a worker thread and resolves to | ||
| * the validation error Flight chunks to deliver on the main thread. On an abort | ||
| * the pool relays the aborted signal to the worker thread through a shared | ||
| * flag, so the in-flight run aborts mid-run; validation always runs as a thread | ||
| * (never a child process), which is what makes that cross-thread abort | ||
| * possible. | ||
| */ | ||
| export type DevValidationWorker = (snapshot: DevValidationSnapshot, validationAbortSignal: AbortSignal) => Promise<DevValidationWorkerResult>; | ||
| export declare function setDevValidationWorker(fn: DevValidationWorker | undefined): void; | ||
| export declare function getDevValidationWorker(): DevValidationWorker | undefined; |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { | ||
| value: true | ||
| }); | ||
| 0 && (module.exports = { | ||
| getDevValidationWorker: null, | ||
| setDevValidationWorker: null | ||
| }); | ||
| function _export(target, all) { | ||
| for(var name in all)Object.defineProperty(target, name, { | ||
| enumerable: true, | ||
| get: all[name] | ||
| }); | ||
| } | ||
| _export(exports, { | ||
| getDevValidationWorker: function() { | ||
| return getDevValidationWorker; | ||
| }, | ||
| setDevValidationWorker: function() { | ||
| return setDevValidationWorker; | ||
| } | ||
| }); | ||
| /** | ||
| * Cross-module handoff for the dev validation worker (client-module warmup, | ||
| * static-shell validation, and instant-config validation all run on it). A | ||
| * symbol on `globalThis` decouples the dev-server entry point (which installs | ||
| * the jest-worker pool) from the read site in `runDevValidationInBackground` | ||
| * inside `app-render.tsx`, avoiding a direct import of dev-only pool code from | ||
| * the render module. When the symbol is not set (e.g. because the feature flag | ||
| * is disabled), `getDevValidationWorker()` returns undefined and the caller | ||
| * runs validation in process instead. | ||
| */ const SYMBOL = Symbol.for('next.dev.validationWorker'); | ||
| function setDevValidationWorker(fn) { | ||
| ; | ||
| globalThis[SYMBOL] = fn; | ||
| } | ||
| function getDevValidationWorker() { | ||
| return globalThis[SYMBOL]; | ||
| } | ||
| //# sourceMappingURL=dev-validation-worker-globals.js.map |
| {"version":3,"sources":["../../../src/server/app-render/dev-validation-worker-globals.ts"],"sourcesContent":["import type { Params } from '../request/params'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport type { NextParsedUrlQuery } from '../request-meta'\nimport type { PrefetchingMode } from './app-render'\nimport type { NextConfigComplete, ValidationLevel } from '../config-shared'\nimport type { ImageConfigComplete } from '../../shared/lib/image-config'\n\n/**\n * Cross-module handoff for the dev validation worker (client-module warmup,\n * static-shell validation, and instant-config validation all run on it). A\n * symbol on `globalThis` decouples the dev-server entry point (which installs\n * the jest-worker pool) from the read site in `runDevValidationInBackground`\n * inside `app-render.tsx`, avoiding a direct import of dev-only pool code from\n * the render module. When the symbol is not set (e.g. because the feature flag\n * is disabled), `getDevValidationWorker()` returns undefined and the caller\n * runs validation in process instead.\n */\nconst SYMBOL: unique symbol = Symbol.for('next.dev.validationWorker')\n\n/**\n * Per-stage RSC chunks, the serializable form of `AccumulatedStreamChunks` that\n * the worker replays. No live streams cross the boundary.\n */\nexport interface SerializedAccumulatedChunks {\n shellStaticChunks: Uint8Array[]\n staticChunks: Uint8Array[]\n shellRuntimeChunks: Uint8Array[]\n runtimeChunks: Uint8Array[]\n dynamicChunks: Uint8Array[]\n}\n\n/**\n * Serializable view of one validation input (the shape `DevValidationInputs`\n * carries), with the live streams already drained to chunks. The stage-end\n * timings are replayed into the per-depth Flight re-encodes so the worker\n * reconstructs the same partial-stage boundaries the main render observed.\n */\nexport interface SerializedValidationInputs {\n accumulatedChunks: SerializedAccumulatedChunks\n debugChunks: Uint8Array[] | null\n startTime: number\n staticStageEndTime: number\n runtimeStageEndTime: number\n}\n\n/**\n * Serializable view of the request, rebuilt into a `RequestStore` on the worker\n * so `cookies()` / `headers()` / `draftMode()` behave as in the real render.\n */\nexport interface DevValidationRequestSnapshot {\n headers: [string, string][]\n urlPathname: string\n urlSearch: string\n rootParams: Params\n isDraftMode: boolean\n isHmrRefresh: boolean\n hmrRefreshHash: string | undefined\n}\n\n/**\n * Everything the worker needs to rebuild the render context and inputs and run\n * `runValidationInDev`. Built on the main thread from the settled render; the\n * pool augments it with install-time fields (`distDir`, `buildId`, …).\n */\nexport interface DevValidationSnapshot {\n page: string\n route: string\n requestId: string\n responseFinished: boolean\n prefetchMode: PrefetchingMode\n devRenderDidError: boolean\n nonce: string | undefined\n query: NextParsedUrlQuery\n request: DevValidationRequestSnapshot\n // The interpolated route params, the routing seed the worker rebuilds\n // `getDynamicParamFromSegment` from (together with the fallback params\n // below).\n interpolatedParams: Params\n // The request's fallback params, the set `ctx.getDynamicParamFromSegment`\n // closed over. The worker rebuilds `getDynamicParamFromSegment` from these\n // (with `interpolatedParams` and `optimisticRouting`), so the depth-loop\n // segment keys match the seed render's Flight. It is null for a request whose\n // params all resolve to concrete values.\n requestFallbackRouteParams: OpaqueFallbackRouteParams | null\n // The validation fallback params, passed to `runValidationInDev` and its\n // prerender stores. They mark params unknown so that accessing one during the\n // simulated prefetch is treated as dynamic. This set may include params that\n // `requestFallbackRouteParams` does not.\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n optimisticRouting: boolean\n forceStatic: boolean | undefined\n validationLevel: ValidationLevel\n implicitTags: string[]\n /**\n * Pages whose client reference manifests supplied client references to the\n * render being validated, beyond the validated route's own manifest (see\n * `WorkStore.additionalClientReferenceManifestPages`). The worker registers\n * these so the same references resolve in its thread. Empty for all but the\n * rare renders that React's I/O tracking carries a reference into.\n */\n additionalClientReferenceManifestPages: string[]\n isDebugChannelEnabled: boolean\n renderOpts: {\n images: ImageConfigComplete\n allowEmptyStaticShell: boolean | undefined\n }\n instantInputs: SerializedValidationInputs | null\n staticInputs: SerializedValidationInputs\n}\n\n/**\n * Install-time fields the dev server's worker pool augments the snapshot with\n * so the worker can reload the route (`distDir`; `page` comes from the\n * snapshot) and rebuild the work store (`buildId`, `deploymentId`, the config\n * slice).\n */\nexport interface DevValidationInstallFields {\n distDir: string\n buildId: string\n deploymentId: string\n nextConfigSerializable: {\n httpAgentOptions: NextConfigComplete['httpAgentOptions']\n cacheLifeProfiles: NextConfigComplete['cacheLife']\n useCacheTimeout: number\n staticPageGenerationTimeout: number\n }\n}\n\n/**\n * The full message the worker receives and forwards into the in-bundle entry:\n * the main-thread snapshot plus the pool's install-time fields.\n */\nexport type DevValidationWorkerMessage = DevValidationSnapshot &\n DevValidationInstallFields\n\n/**\n * The RSC-encoded `{ errors, errorCodes }` Flight chunks for the dev overlay,\n * or null when validation produced no errors or was aborted. The worker also\n * logs the errors to its own stderr (piped to the parent) with code frames.\n */\nexport type DevValidationWorkerResult = Uint8Array[] | null\n\n/**\n * Worker hook installed by the dev server. Given the render snapshot and the\n * validation abort signal, runs validation on a worker thread and resolves to\n * the validation error Flight chunks to deliver on the main thread. On an abort\n * the pool relays the aborted signal to the worker thread through a shared\n * flag, so the in-flight run aborts mid-run; validation always runs as a thread\n * (never a child process), which is what makes that cross-thread abort\n * possible.\n */\nexport type DevValidationWorker = (\n snapshot: DevValidationSnapshot,\n validationAbortSignal: AbortSignal\n) => Promise<DevValidationWorkerResult>\n\ninterface WorkerHolder {\n [SYMBOL]?: DevValidationWorker\n}\n\nexport function setDevValidationWorker(\n fn: DevValidationWorker | undefined\n): void {\n ;(globalThis as WorkerHolder)[SYMBOL] = fn\n}\n\nexport function getDevValidationWorker(): DevValidationWorker | undefined {\n return (globalThis as WorkerHolder)[SYMBOL]\n}\n"],"names":["getDevValidationWorker","setDevValidationWorker","SYMBOL","Symbol","for","fn","globalThis"],"mappings":";;;;;;;;;;;;;;;IAsKgBA,sBAAsB;eAAtBA;;IANAC,sBAAsB;eAAtBA;;;AAzJhB;;;;;;;;;CASC,GACD,MAAMC,SAAwBC,OAAOC,GAAG,CAAC;AA+IlC,SAASH,uBACdI,EAAmC;;IAEjCC,UAA2B,CAACJ,OAAO,GAAGG;AAC1C;AAEO,SAASL;IACd,OAAO,AAACM,UAA2B,CAACJ,OAAO;AAC7C","ignoreList":[0]} |
| import type { AppRenderContext, ResolvedValidationInputs } from './app-render'; | ||
| import type { PrefetchingMode } from './app-render'; | ||
| import type { OpaqueFallbackRouteParams } from '../request/fallback-params'; | ||
| import type { DevValidationSnapshot } from './dev-validation-worker-globals'; | ||
| /** | ||
| * Builds the serializable snapshot the dev validation worker needs to rebuild | ||
| * the render context and inputs and run `runValidationInDev` on the worker | ||
| * thread. Reads only serializable data from the settled render; the live | ||
| * objects (`componentMod`, the async-storage stores, | ||
| * `getDynamicParamFromSegment`) are reconstructed on the worker from this seed. | ||
| * Draining the debug channels is async, so this returns a promise. | ||
| */ | ||
| export declare function buildDevValidationSnapshot(ctx: AppRenderContext, instantInputs: ResolvedValidationInputs | null, staticInputs: ResolvedValidationInputs, prefetchMode: PrefetchingMode, fallbackRouteParams: OpaqueFallbackRouteParams | null, devRenderDidError: boolean): Promise<DevValidationSnapshot>; |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { | ||
| value: true | ||
| }); | ||
| Object.defineProperty(exports, "buildDevValidationSnapshot", { | ||
| enumerable: true, | ||
| get: function() { | ||
| return buildDevValidationSnapshot; | ||
| } | ||
| }); | ||
| const _helpers = require("../base-http/helpers"); | ||
| async function buildDevValidationSnapshot(ctx, instantInputs, staticInputs, prefetchMode, fallbackRouteParams, devRenderDidError) { | ||
| const requestStore = staticInputs.requestStore; | ||
| const responseFinished = !(0, _helpers.isNodeNextResponse)(ctx.res) || ctx.res.originalResponse.writableFinished; | ||
| // The instant and static inputs may share one debug channel, so drain each | ||
| // channel only once. | ||
| const chunksByChannel = new WeakMap(); | ||
| const getDebugChunksOnce = async (channel)=>{ | ||
| if (!channel) { | ||
| return null; | ||
| } | ||
| let chunks = chunksByChannel.get(channel); | ||
| if (!chunks) { | ||
| chunks = []; | ||
| for await (const chunk of channel){ | ||
| chunks.push(chunk); | ||
| } | ||
| chunksByChannel.set(channel, chunks); | ||
| } | ||
| return chunks; | ||
| }; | ||
| const toSerializedInputs = async (inputs)=>({ | ||
| accumulatedChunks: inputs.accumulatedChunks, | ||
| debugChunks: await getDebugChunksOnce(inputs.debugChannelClient), | ||
| startTime: inputs.startTime, | ||
| staticStageEndTime: inputs.staticStageEndTime, | ||
| runtimeStageEndTime: inputs.runtimeStageEndTime | ||
| }); | ||
| return { | ||
| page: ctx.workStore.page, | ||
| route: ctx.workStore.route, | ||
| requestId: ctx.requestId, | ||
| responseFinished, | ||
| prefetchMode, | ||
| devRenderDidError, | ||
| nonce: ctx.nonce, | ||
| query: ctx.query, | ||
| request: { | ||
| headers: [ | ||
| ...requestStore.headers.entries() | ||
| ], | ||
| urlPathname: requestStore.url.pathname, | ||
| urlSearch: requestStore.url.search, | ||
| rootParams: requestStore.rootParams, | ||
| isDraftMode: requestStore.draftMode.isEnabled, | ||
| isHmrRefresh: requestStore.isHmrRefresh ?? false, | ||
| hmrRefreshHash: requestStore.hmrRefreshHash | ||
| }, | ||
| interpolatedParams: ctx.interpolatedParams, | ||
| requestFallbackRouteParams: ctx.fallbackRouteParams, | ||
| fallbackRouteParams, | ||
| optimisticRouting: ctx.renderOpts.experimental.optimisticRouting, | ||
| forceStatic: ctx.workStore.forceStatic, | ||
| validationLevel: ctx.workStore.validationLevel, | ||
| implicitTags: ctx.implicitTags.tags, | ||
| additionalClientReferenceManifestPages: ctx.workStore.additionalClientReferenceManifestPages ? [ | ||
| ...ctx.workStore.additionalClientReferenceManifestPages | ||
| ] : [], | ||
| isDebugChannelEnabled: !!ctx.renderOpts.setReactDebugChannel, | ||
| renderOpts: { | ||
| images: ctx.renderOpts.images, | ||
| allowEmptyStaticShell: ctx.renderOpts.allowEmptyStaticShell | ||
| }, | ||
| instantInputs: instantInputs ? await toSerializedInputs(instantInputs) : null, | ||
| staticInputs: await toSerializedInputs(staticInputs) | ||
| }; | ||
| } | ||
| //# sourceMappingURL=dev-validation-worker-snapshot.js.map |
| {"version":3,"sources":["../../../src/server/app-render/dev-validation-worker-snapshot.ts"],"sourcesContent":["import type { AppRenderContext, ResolvedValidationInputs } from './app-render'\nimport type { PrefetchingMode } from './app-render'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport type { AnyStream } from './stream-ops'\nimport type {\n DevValidationSnapshot,\n SerializedValidationInputs,\n} from './dev-validation-worker-globals'\n\nimport { isNodeNextResponse } from '../base-http/helpers'\n\n/**\n * Builds the serializable snapshot the dev validation worker needs to rebuild\n * the render context and inputs and run `runValidationInDev` on the worker\n * thread. Reads only serializable data from the settled render; the live\n * objects (`componentMod`, the async-storage stores,\n * `getDynamicParamFromSegment`) are reconstructed on the worker from this seed.\n * Draining the debug channels is async, so this returns a promise.\n */\nexport async function buildDevValidationSnapshot(\n ctx: AppRenderContext,\n instantInputs: ResolvedValidationInputs | null,\n staticInputs: ResolvedValidationInputs,\n prefetchMode: PrefetchingMode,\n fallbackRouteParams: OpaqueFallbackRouteParams | null,\n devRenderDidError: boolean\n): Promise<DevValidationSnapshot> {\n const requestStore = staticInputs.requestStore\n const responseFinished =\n !isNodeNextResponse(ctx.res) || ctx.res.originalResponse.writableFinished\n\n // The instant and static inputs may share one debug channel, so drain each\n // channel only once.\n const chunksByChannel = new WeakMap<AnyStream, Uint8Array[]>()\n const getDebugChunksOnce = async (\n channel: AnyStream | undefined\n ): Promise<Uint8Array[] | null> => {\n if (!channel) {\n return null\n }\n let chunks = chunksByChannel.get(channel)\n if (!chunks) {\n chunks = []\n for await (const chunk of channel) {\n chunks.push(chunk)\n }\n chunksByChannel.set(channel, chunks)\n }\n return chunks\n }\n\n const toSerializedInputs = async (\n inputs: ResolvedValidationInputs\n ): Promise<SerializedValidationInputs> => ({\n accumulatedChunks: inputs.accumulatedChunks,\n debugChunks: await getDebugChunksOnce(inputs.debugChannelClient),\n startTime: inputs.startTime,\n staticStageEndTime: inputs.staticStageEndTime,\n runtimeStageEndTime: inputs.runtimeStageEndTime,\n })\n\n return {\n page: ctx.workStore.page,\n route: ctx.workStore.route,\n requestId: ctx.requestId,\n responseFinished,\n prefetchMode,\n devRenderDidError,\n nonce: ctx.nonce,\n query: ctx.query,\n request: {\n headers: [...requestStore.headers.entries()],\n urlPathname: requestStore.url.pathname,\n urlSearch: requestStore.url.search,\n rootParams: requestStore.rootParams,\n isDraftMode: requestStore.draftMode.isEnabled,\n isHmrRefresh: requestStore.isHmrRefresh ?? false,\n hmrRefreshHash: requestStore.hmrRefreshHash,\n },\n interpolatedParams: ctx.interpolatedParams,\n requestFallbackRouteParams: ctx.fallbackRouteParams,\n fallbackRouteParams,\n optimisticRouting: ctx.renderOpts.experimental.optimisticRouting,\n forceStatic: ctx.workStore.forceStatic,\n validationLevel: ctx.workStore.validationLevel,\n implicitTags: ctx.implicitTags.tags,\n additionalClientReferenceManifestPages: ctx.workStore\n .additionalClientReferenceManifestPages\n ? [...ctx.workStore.additionalClientReferenceManifestPages]\n : [],\n isDebugChannelEnabled: !!ctx.renderOpts.setReactDebugChannel,\n renderOpts: {\n images: ctx.renderOpts.images,\n allowEmptyStaticShell: ctx.renderOpts.allowEmptyStaticShell,\n },\n instantInputs: instantInputs\n ? await toSerializedInputs(instantInputs)\n : null,\n staticInputs: await toSerializedInputs(staticInputs),\n }\n}\n"],"names":["buildDevValidationSnapshot","ctx","instantInputs","staticInputs","prefetchMode","fallbackRouteParams","devRenderDidError","requestStore","responseFinished","isNodeNextResponse","res","originalResponse","writableFinished","chunksByChannel","WeakMap","getDebugChunksOnce","channel","chunks","get","chunk","push","set","toSerializedInputs","inputs","accumulatedChunks","debugChunks","debugChannelClient","startTime","staticStageEndTime","runtimeStageEndTime","page","workStore","route","requestId","nonce","query","request","headers","entries","urlPathname","url","pathname","urlSearch","search","rootParams","isDraftMode","draftMode","isEnabled","isHmrRefresh","hmrRefreshHash","interpolatedParams","requestFallbackRouteParams","optimisticRouting","renderOpts","experimental","forceStatic","validationLevel","implicitTags","tags","additionalClientReferenceManifestPages","isDebugChannelEnabled","setReactDebugChannel","images","allowEmptyStaticShell"],"mappings":";;;;+BAmBsBA;;;eAAAA;;;yBAVa;AAU5B,eAAeA,2BACpBC,GAAqB,EACrBC,aAA8C,EAC9CC,YAAsC,EACtCC,YAA6B,EAC7BC,mBAAqD,EACrDC,iBAA0B;IAE1B,MAAMC,eAAeJ,aAAaI,YAAY;IAC9C,MAAMC,mBACJ,CAACC,IAAAA,2BAAkB,EAACR,IAAIS,GAAG,KAAKT,IAAIS,GAAG,CAACC,gBAAgB,CAACC,gBAAgB;IAE3E,2EAA2E;IAC3E,qBAAqB;IACrB,MAAMC,kBAAkB,IAAIC;IAC5B,MAAMC,qBAAqB,OACzBC;QAEA,IAAI,CAACA,SAAS;YACZ,OAAO;QACT;QACA,IAAIC,SAASJ,gBAAgBK,GAAG,CAACF;QACjC,IAAI,CAACC,QAAQ;YACXA,SAAS,EAAE;YACX,WAAW,MAAME,SAASH,QAAS;gBACjCC,OAAOG,IAAI,CAACD;YACd;YACAN,gBAAgBQ,GAAG,CAACL,SAASC;QAC/B;QACA,OAAOA;IACT;IAEA,MAAMK,qBAAqB,OACzBC,SACyC,CAAA;YACzCC,mBAAmBD,OAAOC,iBAAiB;YAC3CC,aAAa,MAAMV,mBAAmBQ,OAAOG,kBAAkB;YAC/DC,WAAWJ,OAAOI,SAAS;YAC3BC,oBAAoBL,OAAOK,kBAAkB;YAC7CC,qBAAqBN,OAAOM,mBAAmB;QACjD,CAAA;IAEA,OAAO;QACLC,MAAM7B,IAAI8B,SAAS,CAACD,IAAI;QACxBE,OAAO/B,IAAI8B,SAAS,CAACC,KAAK;QAC1BC,WAAWhC,IAAIgC,SAAS;QACxBzB;QACAJ;QACAE;QACA4B,OAAOjC,IAAIiC,KAAK;QAChBC,OAAOlC,IAAIkC,KAAK;QAChBC,SAAS;YACPC,SAAS;mBAAI9B,aAAa8B,OAAO,CAACC,OAAO;aAAG;YAC5CC,aAAahC,aAAaiC,GAAG,CAACC,QAAQ;YACtCC,WAAWnC,aAAaiC,GAAG,CAACG,MAAM;YAClCC,YAAYrC,aAAaqC,UAAU;YACnCC,aAAatC,aAAauC,SAAS,CAACC,SAAS;YAC7CC,cAAczC,aAAayC,YAAY,IAAI;YAC3CC,gBAAgB1C,aAAa0C,cAAc;QAC7C;QACAC,oBAAoBjD,IAAIiD,kBAAkB;QAC1CC,4BAA4BlD,IAAII,mBAAmB;QACnDA;QACA+C,mBAAmBnD,IAAIoD,UAAU,CAACC,YAAY,CAACF,iBAAiB;QAChEG,aAAatD,IAAI8B,SAAS,CAACwB,WAAW;QACtCC,iBAAiBvD,IAAI8B,SAAS,CAACyB,eAAe;QAC9CC,cAAcxD,IAAIwD,YAAY,CAACC,IAAI;QACnCC,wCAAwC1D,IAAI8B,SAAS,CAClD4B,sCAAsC,GACrC;eAAI1D,IAAI8B,SAAS,CAAC4B,sCAAsC;SAAC,GACzD,EAAE;QACNC,uBAAuB,CAAC,CAAC3D,IAAIoD,UAAU,CAACQ,oBAAoB;QAC5DR,YAAY;YACVS,QAAQ7D,IAAIoD,UAAU,CAACS,MAAM;YAC7BC,uBAAuB9D,IAAIoD,UAAU,CAACU,qBAAqB;QAC7D;QACA7D,eAAeA,gBACX,MAAMoB,mBAAmBpB,iBACzB;QACJC,cAAc,MAAMmB,mBAAmBnB;IACzC;AACF","ignoreList":[0]} |
| import type { NextConfigComplete } from '../config-shared'; | ||
| interface InstallOptions { | ||
| distDir: string; | ||
| buildId: string; | ||
| deploymentId: string; | ||
| nextConfig: NextConfigComplete; | ||
| } | ||
| /** | ||
| * Wire up the dev-server's validation worker: register the HMR teardown | ||
| * listener and install the hook that `runDevValidationInBackground` calls once | ||
| * a render has settled. The worker thread is spawned lazily, so nothing is | ||
| * created until the first navigation actually validates. | ||
| */ | ||
| export declare function installDevValidationWorker(options: InstallOptions): void; | ||
| export {}; |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { | ||
| value: true | ||
| }); | ||
| Object.defineProperty(exports, "installDevValidationWorker", { | ||
| enumerable: true, | ||
| get: function() { | ||
| return installDevValidationWorker; | ||
| } | ||
| }); | ||
| const _jestworker = require("next/dist/compiled/jest-worker"); | ||
| const _devvalidationworkerglobals = require("../app-render/dev-validation-worker-globals"); | ||
| const _requirecache = require("./require-cache"); | ||
| const _utils = require("../lib/utils"); | ||
| const _needsexperimentalreact = require("../../lib/needs-experimental-react"); | ||
| function installDevValidationWorker(options) { | ||
| const { distDir, buildId, deploymentId, nextConfig } = options; | ||
| // A single worker, not a pool. Validation for one navigation runs its depth | ||
| // loop sequentially, and a newer navigation supersedes the previous one | ||
| // (aborting it mid-run) rather than running concurrently, so there's no | ||
| // per-request fan-out to parallelize (unlike the `'use cache'` probe, where | ||
| // one request fans out into concurrent probes). One worker already frees the | ||
| // main thread, which is the whole point; it also keeps each request's CLI | ||
| // marker block contiguous in the piped output. Torn down on HMR (stale user | ||
| // modules) and on crash. | ||
| // | ||
| // TODO(dev-validation-worker): raise `numWorkers` if concurrent navigations | ||
| // across independent requests (e.g. multiple tabs) show a validation-latency | ||
| // tail. | ||
| let pool; | ||
| const getPool = ()=>{ | ||
| if (pool) { | ||
| return pool; | ||
| } | ||
| // Strip `--inspect` from any inherited `NODE_OPTIONS` so the worker doesn't | ||
| // fight the parent for the same debug port. | ||
| const workerNodeOptions = (0, _utils.getFormattedNodeOptionsWithoutInspect)(); | ||
| // The worker is shipped as four pre-bundled dev-only artifacts | ||
| // ({webpack,turbopack} × {stable,experimental}), one per combination of the | ||
| // user's bundler and vendored React channel. Pick the matching artifact | ||
| // from runtime env so the worker stays in lockstep with the user's app | ||
| // bundle. `needsExperimentalReact` is the same predicate `define-env.ts` | ||
| // uses to wire `__NEXT_EXPERIMENTAL_REACT`. | ||
| const turbo = process.env.TURBOPACK ? '-turbo' : ''; | ||
| const channel = (0, _needsexperimentalreact.needsExperimentalReact)(nextConfig) ? '-experimental' : ''; | ||
| const workerPath = require.resolve(`next/dist/compiled/next-server/dev-validation-worker${turbo}${channel}.runtime.dev.js`); | ||
| const worker = new _jestworker.Worker(workerPath, { | ||
| maxRetries: 0, | ||
| numWorkers: 1, | ||
| // Always worker-threads, regardless of `experimental.workerThreads`. | ||
| // Unlike the `'use cache'` probe (which follows the flag), validation has | ||
| // no reason to prefer a child process: it doesn't need process-level | ||
| // isolation (a worker thread already has its own V8 heap and module | ||
| // registry, so the reloaded route is isolated from the main thread), and | ||
| // threads let a superseded validation be aborted mid-run through a shared | ||
| // `SharedArrayBuffer`, which a separate process can't receive. Threads | ||
| // also carry the transported Flight bytes as typed arrays via structured | ||
| // clone, with no JSON round-trip to corrupt them. | ||
| enableWorkerThreads: true, | ||
| // Listing the method explicitly tells jest-worker to skip the discovery | ||
| // `require()` it would otherwise do in the parent process to enumerate | ||
| // the module's exports. This worker's top-level imports (`require-hook`, | ||
| // `node-environment`) run runtime setup meant only for the isolated | ||
| // worker thread, so they must not be evaluated in the parent. | ||
| exposedMethods: [ | ||
| 'runDevValidation' | ||
| ], | ||
| forkOptions: { | ||
| env: { | ||
| ...process.env, | ||
| NODE_OPTIONS: workerNodeOptions | ||
| } | ||
| } | ||
| }); | ||
| worker.getStdout().pipe(process.stdout); | ||
| worker.getStderr().pipe(process.stderr); | ||
| pool = worker; | ||
| return worker; | ||
| }; | ||
| const tearDownPool = async ()=>{ | ||
| const current = pool; | ||
| if (!current) { | ||
| return; | ||
| } | ||
| pool = undefined; | ||
| await current.end().catch(()=>{ | ||
| // The worker thread exits on its own once its work settles; a failed | ||
| // `.end()` here just means we couldn't wait for it cleanly. | ||
| }); | ||
| }; | ||
| const runValidation = async (snapshot, validationAbortSignal)=>{ | ||
| let activePool; | ||
| try { | ||
| activePool = getPool(); | ||
| } catch { | ||
| return null; | ||
| } | ||
| const message = { | ||
| ...snapshot, | ||
| distDir, | ||
| buildId, | ||
| deploymentId, | ||
| nextConfigSerializable: { | ||
| httpAgentOptions: nextConfig.httpAgentOptions, | ||
| cacheLifeProfiles: nextConfig.cacheLife, | ||
| useCacheTimeout: nextConfig.experimental.useCacheTimeout, | ||
| staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout | ||
| } | ||
| }; | ||
| // The worker runs as a thread (see `enableWorkerThreads` above), so an | ||
| // abort reaches it through a one-slot shared flag rather than the abort | ||
| // signal directly (a signal can't cross the thread boundary). Mirror an | ||
| // abort of `validationAbortSignal` into the buffer and wake the worker's | ||
| // `Atomics.waitAsync` on it, so it aborts the in-flight run at its next | ||
| // depth boundary. | ||
| const abortBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT); | ||
| const abortFlag = new Int32Array(abortBuffer); | ||
| const propagateAbort = ()=>{ | ||
| Atomics.store(abortFlag, 0, 1); | ||
| Atomics.notify(abortFlag, 0); | ||
| }; | ||
| if (validationAbortSignal.aborted) { | ||
| propagateAbort(); | ||
| } else { | ||
| validationAbortSignal.addEventListener('abort', propagateAbort, { | ||
| once: true | ||
| }); | ||
| } | ||
| try { | ||
| return await activePool.runDevValidation(message, abortBuffer); | ||
| } catch { | ||
| // Worker crash or IPC error: tear down so the next validation starts | ||
| // fresh. The main thread treats a missing result as "nothing to deliver." | ||
| await tearDownPool(); | ||
| return null; | ||
| } finally{ | ||
| // `once` only auto-removes the listener if it fired, so remove it | ||
| // explicitly to bound its lifetime to this run when validation completed | ||
| // without being superseded. | ||
| validationAbortSignal.removeEventListener('abort', propagateAbort); | ||
| } | ||
| }; | ||
| // The dev server can't reach into the worker to clear its `require.cache` or | ||
| // manifest caches, so we drop the worker whenever the parent's caches are | ||
| // invalidated (HMR, route recompile). The next validation lazy-spawns a fresh | ||
| // worker with empty caches. | ||
| (0, _requirecache.onCacheInvalidation)(()=>{ | ||
| void tearDownPool(); | ||
| }); | ||
| (0, _devvalidationworkerglobals.setDevValidationWorker)(runValidation); | ||
| } | ||
| //# sourceMappingURL=dev-validation-worker-pool.js.map |
| {"version":3,"sources":["../../../src/server/dev/dev-validation-worker-pool.ts"],"sourcesContent":["import type { NextConfigComplete } from '../config-shared'\nimport type { runDevValidation } from './dev-validation-worker'\nimport type {\n DevValidationSnapshot,\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\n\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { setDevValidationWorker } from '../app-render/dev-validation-worker-globals'\nimport { onCacheInvalidation } from './require-cache'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { needsExperimentalReact } from '../../lib/needs-experimental-react'\n\ninterface InstallOptions {\n distDir: string\n buildId: string\n deploymentId: string\n nextConfig: NextConfigComplete\n}\n\ntype ValidationPool = { [key: string]: any } & {\n runDevValidation: typeof runDevValidation\n}\n\n/**\n * Wire up the dev-server's validation worker: register the HMR teardown\n * listener and install the hook that `runDevValidationInBackground` calls once\n * a render has settled. The worker thread is spawned lazily, so nothing is\n * created until the first navigation actually validates.\n */\nexport function installDevValidationWorker(options: InstallOptions): void {\n const { distDir, buildId, deploymentId, nextConfig } = options\n\n // A single worker, not a pool. Validation for one navigation runs its depth\n // loop sequentially, and a newer navigation supersedes the previous one\n // (aborting it mid-run) rather than running concurrently, so there's no\n // per-request fan-out to parallelize (unlike the `'use cache'` probe, where\n // one request fans out into concurrent probes). One worker already frees the\n // main thread, which is the whole point; it also keeps each request's CLI\n // marker block contiguous in the piped output. Torn down on HMR (stale user\n // modules) and on crash.\n //\n // TODO(dev-validation-worker): raise `numWorkers` if concurrent navigations\n // across independent requests (e.g. multiple tabs) show a validation-latency\n // tail.\n let pool: ValidationPool | undefined\n\n const getPool = (): ValidationPool => {\n if (pool) {\n return pool\n }\n // Strip `--inspect` from any inherited `NODE_OPTIONS` so the worker doesn't\n // fight the parent for the same debug port.\n const workerNodeOptions = getFormattedNodeOptionsWithoutInspect()\n\n // The worker is shipped as four pre-bundled dev-only artifacts\n // ({webpack,turbopack} × {stable,experimental}), one per combination of the\n // user's bundler and vendored React channel. Pick the matching artifact\n // from runtime env so the worker stays in lockstep with the user's app\n // bundle. `needsExperimentalReact` is the same predicate `define-env.ts`\n // uses to wire `__NEXT_EXPERIMENTAL_REACT`.\n const turbo = process.env.TURBOPACK ? '-turbo' : ''\n const channel = needsExperimentalReact(nextConfig) ? '-experimental' : ''\n const workerPath = require.resolve(\n `next/dist/compiled/next-server/dev-validation-worker${turbo}${channel}.runtime.dev.js`\n )\n\n const worker = new Worker(workerPath, {\n maxRetries: 0,\n numWorkers: 1,\n // Always worker-threads, regardless of `experimental.workerThreads`.\n // Unlike the `'use cache'` probe (which follows the flag), validation has\n // no reason to prefer a child process: it doesn't need process-level\n // isolation (a worker thread already has its own V8 heap and module\n // registry, so the reloaded route is isolated from the main thread), and\n // threads let a superseded validation be aborted mid-run through a shared\n // `SharedArrayBuffer`, which a separate process can't receive. Threads\n // also carry the transported Flight bytes as typed arrays via structured\n // clone, with no JSON round-trip to corrupt them.\n enableWorkerThreads: true,\n // Listing the method explicitly tells jest-worker to skip the discovery\n // `require()` it would otherwise do in the parent process to enumerate\n // the module's exports. This worker's top-level imports (`require-hook`,\n // `node-environment`) run runtime setup meant only for the isolated\n // worker thread, so they must not be evaluated in the parent.\n exposedMethods: ['runDevValidation'],\n forkOptions: {\n env: {\n ...process.env,\n NODE_OPTIONS: workerNodeOptions,\n },\n },\n }) as Worker & ValidationPool\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n pool = worker\n return worker\n }\n\n const tearDownPool = async (): Promise<void> => {\n const current = pool\n if (!current) {\n return\n }\n pool = undefined\n await current.end().catch(() => {\n // The worker thread exits on its own once its work settles; a failed\n // `.end()` here just means we couldn't wait for it cleanly.\n })\n }\n\n const runValidation = async (\n snapshot: DevValidationSnapshot,\n validationAbortSignal: AbortSignal\n ): Promise<DevValidationWorkerResult> => {\n let activePool: ValidationPool\n try {\n activePool = getPool()\n } catch {\n return null\n }\n\n const message: DevValidationWorkerMessage = {\n ...snapshot,\n distDir,\n buildId,\n deploymentId,\n nextConfigSerializable: {\n httpAgentOptions: nextConfig.httpAgentOptions,\n cacheLifeProfiles: nextConfig.cacheLife,\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n },\n }\n\n // The worker runs as a thread (see `enableWorkerThreads` above), so an\n // abort reaches it through a one-slot shared flag rather than the abort\n // signal directly (a signal can't cross the thread boundary). Mirror an\n // abort of `validationAbortSignal` into the buffer and wake the worker's\n // `Atomics.waitAsync` on it, so it aborts the in-flight run at its next\n // depth boundary.\n const abortBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)\n const abortFlag = new Int32Array(abortBuffer)\n const propagateAbort = () => {\n Atomics.store(abortFlag, 0, 1)\n Atomics.notify(abortFlag, 0)\n }\n if (validationAbortSignal.aborted) {\n propagateAbort()\n } else {\n validationAbortSignal.addEventListener('abort', propagateAbort, {\n once: true,\n })\n }\n\n try {\n return await activePool.runDevValidation(message, abortBuffer)\n } catch {\n // Worker crash or IPC error: tear down so the next validation starts\n // fresh. The main thread treats a missing result as \"nothing to deliver.\"\n await tearDownPool()\n return null\n } finally {\n // `once` only auto-removes the listener if it fired, so remove it\n // explicitly to bound its lifetime to this run when validation completed\n // without being superseded.\n validationAbortSignal.removeEventListener('abort', propagateAbort)\n }\n }\n\n // The dev server can't reach into the worker to clear its `require.cache` or\n // manifest caches, so we drop the worker whenever the parent's caches are\n // invalidated (HMR, route recompile). The next validation lazy-spawns a fresh\n // worker with empty caches.\n onCacheInvalidation(() => {\n void tearDownPool()\n })\n\n setDevValidationWorker(runValidation)\n}\n"],"names":["installDevValidationWorker","options","distDir","buildId","deploymentId","nextConfig","pool","getPool","workerNodeOptions","getFormattedNodeOptionsWithoutInspect","turbo","process","env","TURBOPACK","channel","needsExperimentalReact","workerPath","require","resolve","worker","Worker","maxRetries","numWorkers","enableWorkerThreads","exposedMethods","forkOptions","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","tearDownPool","current","undefined","end","catch","runValidation","snapshot","validationAbortSignal","activePool","message","nextConfigSerializable","httpAgentOptions","cacheLifeProfiles","cacheLife","useCacheTimeout","experimental","staticPageGenerationTimeout","abortBuffer","SharedArrayBuffer","Int32Array","BYTES_PER_ELEMENT","abortFlag","propagateAbort","Atomics","store","notify","aborted","addEventListener","once","runDevValidation","removeEventListener","onCacheInvalidation","setDevValidationWorker"],"mappings":";;;;+BA+BgBA;;;eAAAA;;;4BAvBO;4CACgB;8BACH;uBACkB;wCACf;AAmBhC,SAASA,2BAA2BC,OAAuB;IAChE,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAEC,YAAY,EAAEC,UAAU,EAAE,GAAGJ;IAEvD,4EAA4E;IAC5E,wEAAwE;IACxE,wEAAwE;IACxE,4EAA4E;IAC5E,6EAA6E;IAC7E,0EAA0E;IAC1E,4EAA4E;IAC5E,yBAAyB;IACzB,EAAE;IACF,4EAA4E;IAC5E,6EAA6E;IAC7E,QAAQ;IACR,IAAIK;IAEJ,MAAMC,UAAU;QACd,IAAID,MAAM;YACR,OAAOA;QACT;QACA,4EAA4E;QAC5E,4CAA4C;QAC5C,MAAME,oBAAoBC,IAAAA,4CAAqC;QAE/D,+DAA+D;QAC/D,4EAA4E;QAC5E,wEAAwE;QACxE,uEAAuE;QACvE,yEAAyE;QACzE,4CAA4C;QAC5C,MAAMC,QAAQC,QAAQC,GAAG,CAACC,SAAS,GAAG,WAAW;QACjD,MAAMC,UAAUC,IAAAA,8CAAsB,EAACV,cAAc,kBAAkB;QACvE,MAAMW,aAAaC,QAAQC,OAAO,CAChC,CAAC,oDAAoD,EAAER,QAAQI,QAAQ,eAAe,CAAC;QAGzF,MAAMK,SAAS,IAAIC,kBAAM,CAACJ,YAAY;YACpCK,YAAY;YACZC,YAAY;YACZ,qEAAqE;YACrE,0EAA0E;YAC1E,qEAAqE;YACrE,oEAAoE;YACpE,yEAAyE;YACzE,0EAA0E;YAC1E,uEAAuE;YACvE,yEAAyE;YACzE,kDAAkD;YAClDC,qBAA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B;gBAC9DM,MAAM;YACR;QACF;QAEA,IAAI;YACF,OAAO,MAAMpB,WAAWqB,gBAAgB,CAACpB,SAASQ;QACpD,EAAE,OAAM;YACN,qEAAqE;YACrE,0EAA0E;YAC1E,MAAMjB;YACN,OAAO;QACT,SAAU;YACR,kEAAkE;YAClE,yEAAyE;YACzE,4BAA4B;YAC5BO,sBAAsBuB,mBAAmB,CAAC,SAASR;QACrD;IACF;IAEA,6EAA6E;IAC7E,0EAA0E;IAC1E,8EAA8E;IAC9E,4BAA4B;IAC5BS,IAAAA,iCAAmB,EAAC;QAClB,KAAK/B;IACP;IAEAgC,IAAAA,kDAAsB,EAAC3B;AACzB","ignoreList":[0]} |
| import type { DevValidationWorkerMessage, DevValidationWorkerResult } from '../app-render/dev-validation-worker-globals'; | ||
| import '../require-hook'; | ||
| import '../node-environment'; | ||
| /** | ||
| * Runs the dev instant/static-shell validation passes off the main thread. | ||
| * Reloads the route's compiled module, then delegates the whole validation to | ||
| * that module via `ComponentMod.routeModule.runValidationInDev`, so every | ||
| * render (flight re-encodes and client prerenders) runs inside the app-page | ||
| * bundle's single React instance. Logs any returned errors to the worker's | ||
| * stderr with source-mapped code frames, then encodes them as RSC Flight bytes | ||
| * for the main thread to forward to the dev overlay. Returns `null` when | ||
| * validation was superseded or produced no errors. | ||
| */ | ||
| export declare function runDevValidation(message: DevValidationWorkerMessage, abortBuffer: SharedArrayBuffer): Promise<DevValidationWorkerResult>; |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { | ||
| value: true | ||
| }); | ||
| Object.defineProperty(exports, "runDevValidation", { | ||
| enumerable: true, | ||
| get: function() { | ||
| return runDevValidation; | ||
| } | ||
| }); | ||
| require("../require-hook"); | ||
| require("../node-environment"); | ||
| const _path = require("path"); | ||
| const _fs = require("fs"); | ||
| const _url = require("url"); | ||
| const _installbindings = require("../../build/swc/install-bindings"); | ||
| const _installcodeframe = require("../lib/install-code-frame"); | ||
| const _loadcomponents = require("../load-components"); | ||
| const _setuphttpagentenv = require("../setup-http-agent-env"); | ||
| const _devvalidationerrordelivery = require("../app-render/dev-validation-error-delivery"); | ||
| const _devvalidationevents = require("../app-render/dev-validation-events"); | ||
| const _manifestssingleton = require("../app-render/manifests-singleton"); | ||
| const _patcherrorinspect = require("../patch-error-inspect"); | ||
| /** | ||
| * Resolves a chunk's source map by reading the `.map` file the bundler emitted | ||
| * next to it, for chunks inside `distDir`. | ||
| * | ||
| * The main thread answers the same question through the Turbopack project | ||
| * handle, which cannot cross a thread boundary. Reading from disk is | ||
| * project-free and, more importantly, does not depend on the chunk having been | ||
| * evaluated in this thread: Node.js caches source maps per isolate, and the | ||
| * worker never renders server components, so it holds maps only for the chunks | ||
| * `loadComponents` pulled in. Frames arriving in the transported payload can | ||
| * point at any chunk the main render touched. | ||
| * | ||
| * This only helps Turbopack, which writes a `.map` beside every chunk. Webpack | ||
| * keeps its dev source maps in the compiler rather than on disk, so its frames | ||
| * from chunks this thread never evaluated stay unresolved, and its module URLs | ||
| * (`webpack-internal://…`) are declined below for the same reason. Frames from | ||
| * dependencies that are not bundled never reach this point, because | ||
| * `filterStackFrameDEV` drops `node_modules` and `node:` frames; bundled | ||
| * dependencies appear as chunks inside `distDir` like any other code. | ||
| */ function createDiskSourceMapLookup(distDir) { | ||
| // The frames carry resolved paths, so compare against the resolved `distDir` | ||
| // to keep the containment check meaningful when the project sits behind a | ||
| // symlink. | ||
| let canonicalDistDir = distDir; | ||
| try { | ||
| canonicalDistDir = (0, _fs.realpathSync)(distDir); | ||
| } catch {} | ||
| const payloads = new Map(); | ||
| return function findSourceMapPayloadOnDisk(sourceURL) { | ||
| let chunkPath = sourceURL; | ||
| if (chunkPath.startsWith('file://')) { | ||
| try { | ||
| chunkPath = (0, _url.fileURLToPath)(chunkPath); | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } | ||
| if (!(0, _path.isAbsolute)(chunkPath)) { | ||
| // Not an emitted chunk, e.g. `webpack-internal://` or `<anonymous>`. | ||
| return undefined; | ||
| } | ||
| const cached = payloads.get(chunkPath); | ||
| if (cached !== undefined || payloads.has(chunkPath)) { | ||
| return cached; | ||
| } | ||
| let payload; | ||
| const relativePath = (0, _path.relative)(canonicalDistDir, chunkPath); | ||
| // Only chunks emitted into `distDir` have a source map to point at, and | ||
| // this keeps the lookup from reading arbitrary paths off disk. | ||
| if (!relativePath.startsWith('..') && !(0, _path.isAbsolute)(relativePath)) { | ||
| try { | ||
| payload = JSON.parse((0, _fs.readFileSync)(chunkPath + '.map', 'utf8')); | ||
| } catch { | ||
| payload = undefined; | ||
| } | ||
| } | ||
| payloads.set(chunkPath, payload); | ||
| return payload; | ||
| }; | ||
| } | ||
| // Match the main dev server (`next-dev-server.ts`), which raises this so the | ||
| // server captures deeper stacks. React's owner-stack capture during the | ||
| // validation prerenders depends on it, so without it the worker's errors lose | ||
| // their owner-stack source attribution. | ||
| try { | ||
| Error.stackTraceLimit = 50; | ||
| } catch {} | ||
| // The lifecycle markers E2E tests read from the CLI. Emitted on the worker's | ||
| // stdout (piped to the parent) so they interleave with the parent's captured | ||
| // output the same way the in-process `runWithDevValidationLogging` markers do. | ||
| // Gated on the same test env that path checks. | ||
| const isTestLoggingEnabled = !!(process.env.__NEXT_TEST_MODE && process.env.NEXT_TEST_LOG_VALIDATION); | ||
| /** | ||
| * Adapts the pool's supersede flag into an `AbortSignal` the validation passes | ||
| * check at their depth/yield boundaries. The pool shares an `Int32Array`-backed | ||
| * `SharedArrayBuffer` whose first slot the main thread flips to non-zero (with | ||
| * `Atomics.store` + `Atomics.notify`) when a newer navigation supersedes this | ||
| * one. We wait for that notification with `Atomics.waitAsync`, which is | ||
| * event-driven rather than polled. A validation that finishes without being | ||
| * superseded calls `cleanup()`, which wakes our own still-pending wait so it | ||
| * leaves no waiter (and no retained buffer) behind. | ||
| */ function createSupersedeSignal(abortBuffer) { | ||
| const controller = new AbortController(); | ||
| const flag = new Int32Array(abortBuffer); | ||
| if (Atomics.load(flag, 0) !== 0) { | ||
| controller.abort(); | ||
| return { | ||
| signal: controller.signal, | ||
| cleanup: ()=>{} | ||
| }; | ||
| } | ||
| let settled = false; | ||
| const wait = Atomics.waitAsync(flag, 0, 0); | ||
| if (wait.async) { | ||
| wait.value.then(()=>{ | ||
| if (settled) { | ||
| return; | ||
| } | ||
| settled = true; | ||
| // Woken either by a real supersede or by `cleanup()`; only the former | ||
| // leaves the flag set. | ||
| if (Atomics.load(flag, 0) !== 0) { | ||
| controller.abort(); | ||
| } | ||
| }); | ||
| } else if (Atomics.load(flag, 0) !== 0) { | ||
| // The flag flipped between the load above and the wait. | ||
| controller.abort(); | ||
| } | ||
| return { | ||
| signal: controller.signal, | ||
| cleanup: ()=>{ | ||
| if (!settled) { | ||
| Atomics.notify(flag, 0); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| /** | ||
| * Waits out the test-only validation delay, resolving early if the render is | ||
| * superseded. Mirrors the delay in `runWithDevValidationLogging` so scheduler | ||
| * tests observe the same in-flight window on the worker path. | ||
| */ async function applyTestValidationDelay(signal) { | ||
| const delayMs = Number(process.env.NEXT_TEST_DEV_VALIDATION_DELAY_MS); | ||
| if (!Number.isFinite(delayMs) || delayMs <= 0 || signal.aborted) { | ||
| return; | ||
| } | ||
| await new Promise((resolve)=>{ | ||
| const finishDelay = ()=>{ | ||
| clearTimeout(timeout); | ||
| signal.removeEventListener('abort', finishDelay); | ||
| resolve(); | ||
| }; | ||
| const timeout = setTimeout(finishDelay, delayMs); | ||
| signal.addEventListener('abort', finishDelay, { | ||
| once: true | ||
| }); | ||
| }); | ||
| } | ||
| /** | ||
| * Registers the client reference manifests of the pages that supplied client | ||
| * references to the render being validated, beyond the validated route's own | ||
| * manifest. This thread has its own manifests singleton, which `loadComponents` | ||
| * seeds with only the validated route, so without these the dev-only cross-page | ||
| * lookup in `createProxiedClientReferenceManifest` has no other manifest to | ||
| * search and decoding the transported payload fails. Usually a no-op, since the | ||
| * main thread only records a page when React's I/O tracking actually carried a | ||
| * reference across pages. | ||
| */ async function registerAdditionalClientReferenceManifests(distDir, pages) { | ||
| if (pages.length === 0) { | ||
| return; | ||
| } | ||
| // Set by `loadComponents`. One server actions manifest covers the whole app, | ||
| // so the pages registered here share the validated route's. | ||
| const serverActionsManifest = (0, _manifestssingleton.getServerActionsManifest)(); | ||
| await Promise.all(pages.map(async (page)=>{ | ||
| const clientReferenceManifest = await (0, _loadcomponents.loadClientReferenceManifestForPage)(distDir, page); | ||
| if (clientReferenceManifest) { | ||
| (0, _manifestssingleton.setManifestsSingleton)({ | ||
| page, | ||
| clientReferenceManifest, | ||
| serverActionsManifest | ||
| }); | ||
| } | ||
| })); | ||
| } | ||
| async function runDevValidation(message, abortBuffer) { | ||
| // Load the native SWC bindings and wire the code-frame renderer so the errors | ||
| // logged below render with a source-mapped code frame, matching the | ||
| // in-process dev output (the E2E tests snapshot the CLI text between the | ||
| // validation markers). The `build/swc` graph these pull in is bundled as a | ||
| // runtime external (see `next-runtime.webpack-config.js`), so it resolves | ||
| // from the installed `next/dist` tree rather than being compiled into this | ||
| // worker bundle, the same way the unbundled build worker loads it. | ||
| await (0, _installbindings.installBindings)(); | ||
| (0, _installcodeframe.installCodeFrameSupport)(); | ||
| (0, _patcherrorinspect.setBundlerFindSourceMapImplementation)(createDiskSourceMapLookup(message.distDir)); | ||
| (0, _setuphttpagentenv.setHttpClientAndAgentOptions)({ | ||
| httpAgentOptions: message.nextConfigSerializable.httpAgentOptions | ||
| }); | ||
| // Populates the manifests singleton for the route via `setManifestsSingleton` | ||
| // inside `loadComponents`, exactly as a real request does. The pool tears the | ||
| // worker down on HMR / route recompile so the next validation reloads from a | ||
| // clean require cache. | ||
| const { ComponentMod } = await (0, _loadcomponents.loadComponents)({ | ||
| distDir: message.distDir, | ||
| page: message.page, | ||
| isAppPath: true, | ||
| isDev: true, | ||
| sriEnabled: false, | ||
| needsManifestsForLegacyReasons: true | ||
| }); | ||
| await registerAdditionalClientReferenceManifests(message.distDir, message.additionalClientReferenceManifestPages); | ||
| const { signal, cleanup } = createSupersedeSignal(abortBuffer); | ||
| if (isTestLoggingEnabled) { | ||
| console.log((0, _devvalidationevents.formatValidationEvent)({ | ||
| type: 'validation_start', | ||
| requestId: message.requestId, | ||
| url: message.request.urlPathname + message.request.urlSearch, | ||
| responseFinished: message.responseFinished | ||
| })); | ||
| } | ||
| try { | ||
| if (isTestLoggingEnabled) { | ||
| await applyTestValidationDelay(signal); | ||
| } | ||
| if (signal.aborted) { | ||
| return null; | ||
| } | ||
| // Crossing into the app-page bundle: the entire validation runs there, so | ||
| // the client prerenders use the same React the user's client components | ||
| // resolve through `ComponentMod`. | ||
| const validationErrors = await ComponentMod.routeModule.runValidationInDev(ComponentMod, message, signal); | ||
| if (validationErrors === undefined || signal.aborted) { | ||
| return null; | ||
| } | ||
| const errors = []; | ||
| for (const validationError of validationErrors){ | ||
| // Log to the worker's stderr; `node-environment` + | ||
| // `installCodeFrameSupport` render the source-mapped stack and code frame | ||
| // there, matching the in-process CLI output. | ||
| console.error(validationError); | ||
| if (validationError instanceof Error) { | ||
| errors.push(validationError); | ||
| } | ||
| } | ||
| if (errors.length === 0) { | ||
| return null; | ||
| } | ||
| return await (0, _devvalidationerrordelivery.serializeValidationErrorsToFlight)(ComponentMod, errors); | ||
| } finally{ | ||
| cleanup(); | ||
| if (isTestLoggingEnabled) { | ||
| console.log((0, _devvalidationevents.formatValidationEvent)({ | ||
| type: signal.aborted ? 'validation_aborted' : 'validation_end', | ||
| requestId: message.requestId, | ||
| url: message.request.urlPathname + message.request.urlSearch | ||
| })); | ||
| } | ||
| } | ||
| } | ||
| //# sourceMappingURL=dev-validation-worker.js.map |
| {"version":3,"sources":["../../../src/server/dev/dev-validation-worker.ts"],"sourcesContent":["import type { AppPageModule } from '../route-modules/app-page/module'\nimport type {\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\n\nimport '../require-hook'\nimport '../node-environment'\n\nimport { isAbsolute, relative } from 'path'\nimport { readFileSync, realpathSync } from 'fs'\nimport { fileURLToPath } from 'url'\nimport { installBindings } from '../../build/swc/install-bindings'\nimport { installCodeFrameSupport } from '../lib/install-code-frame'\nimport {\n loadClientReferenceManifestForPage,\n loadComponents,\n} from '../load-components'\nimport { setHttpClientAndAgentOptions } from '../setup-http-agent-env'\nimport { serializeValidationErrorsToFlight } from '../app-render/dev-validation-error-delivery'\nimport { formatValidationEvent } from '../app-render/dev-validation-events'\nimport {\n getServerActionsManifest,\n setManifestsSingleton,\n} from '../app-render/manifests-singleton'\nimport { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'\nimport type { ModernSourceMapPayload } from '../lib/source-maps'\n\n/**\n * Resolves a chunk's source map by reading the `.map` file the bundler emitted\n * next to it, for chunks inside `distDir`.\n *\n * The main thread answers the same question through the Turbopack project\n * handle, which cannot cross a thread boundary. Reading from disk is\n * project-free and, more importantly, does not depend on the chunk having been\n * evaluated in this thread: Node.js caches source maps per isolate, and the\n * worker never renders server components, so it holds maps only for the chunks\n * `loadComponents` pulled in. Frames arriving in the transported payload can\n * point at any chunk the main render touched.\n *\n * This only helps Turbopack, which writes a `.map` beside every chunk. Webpack\n * keeps its dev source maps in the compiler rather than on disk, so its frames\n * from chunks this thread never evaluated stay unresolved, and its module URLs\n * (`webpack-internal://…`) are declined below for the same reason. Frames from\n * dependencies that are not bundled never reach this point, because\n * `filterStackFrameDEV` drops `node_modules` and `node:` frames; bundled\n * dependencies appear as chunks inside `distDir` like any other code.\n */\nfunction createDiskSourceMapLookup(\n distDir: string\n): (sourceURL: string) => ModernSourceMapPayload | undefined {\n // The frames carry resolved paths, so compare against the resolved `distDir`\n // to keep the containment check meaningful when the project sits behind a\n // symlink.\n let canonicalDistDir = distDir\n try {\n canonicalDistDir = realpathSync(distDir)\n } catch {}\n\n const payloads = new Map<string, ModernSourceMapPayload | undefined>()\n\n return function findSourceMapPayloadOnDisk(sourceURL) {\n let chunkPath = sourceURL\n\n if (chunkPath.startsWith('file://')) {\n try {\n chunkPath = fileURLToPath(chunkPath)\n } catch {\n return undefined\n }\n }\n\n if (!isAbsolute(chunkPath)) {\n // Not an emitted chunk, e.g. `webpack-internal://` or `<anonymous>`.\n return undefined\n }\n\n const cached = payloads.get(chunkPath)\n if (cached !== undefined || payloads.has(chunkPath)) {\n return cached\n }\n\n let payload: ModernSourceMapPayload | undefined\n const relativePath = relative(canonicalDistDir, chunkPath)\n\n // Only chunks emitted into `distDir` have a source map to point at, and\n // this keeps the lookup from reading arbitrary paths off disk.\n if (!relativePath.startsWith('..') && !isAbsolute(relativePath)) {\n try {\n payload = JSON.parse(readFileSync(chunkPath + '.map', 'utf8'))\n } catch {\n payload = undefined\n }\n }\n\n payloads.set(chunkPath, payload)\n\n return payload\n }\n}\n\n// Match the main dev server (`next-dev-server.ts`), which raises this so the\n// server captures deeper stacks. React's owner-stack capture during the\n// validation prerenders depends on it, so without it the worker's errors lose\n// their owner-stack source attribution.\ntry {\n Error.stackTraceLimit = 50\n} catch {}\n\n// The lifecycle markers E2E tests read from the CLI. Emitted on the worker's\n// stdout (piped to the parent) so they interleave with the parent's captured\n// output the same way the in-process `runWithDevValidationLogging` markers do.\n// Gated on the same test env that path checks.\nconst isTestLoggingEnabled = !!(\n process.env.__NEXT_TEST_MODE && process.env.NEXT_TEST_LOG_VALIDATION\n)\n\n/**\n * Adapts the pool's supersede flag into an `AbortSignal` the validation passes\n * check at their depth/yield boundaries. The pool shares an `Int32Array`-backed\n * `SharedArrayBuffer` whose first slot the main thread flips to non-zero (with\n * `Atomics.store` + `Atomics.notify`) when a newer navigation supersedes this\n * one. We wait for that notification with `Atomics.waitAsync`, which is\n * event-driven rather than polled. A validation that finishes without being\n * superseded calls `cleanup()`, which wakes our own still-pending wait so it\n * leaves no waiter (and no retained buffer) behind.\n */\nfunction createSupersedeSignal(abortBuffer: SharedArrayBuffer): {\n signal: AbortSignal\n cleanup: () => void\n} {\n const controller = new AbortController()\n const flag = new Int32Array(abortBuffer)\n\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n let settled = false\n const wait = Atomics.waitAsync(flag, 0, 0)\n if (wait.async) {\n wait.value.then(() => {\n if (settled) {\n return\n }\n settled = true\n // Woken either by a real supersede or by `cleanup()`; only the former\n // leaves the flag set.\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n }\n })\n } else if (Atomics.load(flag, 0) !== 0) {\n // The flag flipped between the load above and the wait.\n controller.abort()\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (!settled) {\n Atomics.notify(flag, 0)\n }\n },\n }\n}\n\n/**\n * Waits out the test-only validation delay, resolving early if the render is\n * superseded. Mirrors the delay in `runWithDevValidationLogging` so scheduler\n * tests observe the same in-flight window on the worker path.\n */\nasync function applyTestValidationDelay(signal: AbortSignal): Promise<void> {\n const delayMs = Number(process.env.NEXT_TEST_DEV_VALIDATION_DELAY_MS)\n if (!Number.isFinite(delayMs) || delayMs <= 0 || signal.aborted) {\n return\n }\n\n await new Promise<void>((resolve) => {\n const finishDelay = () => {\n clearTimeout(timeout)\n signal.removeEventListener('abort', finishDelay)\n resolve()\n }\n const timeout = setTimeout(finishDelay, delayMs)\n signal.addEventListener('abort', finishDelay, { once: true })\n })\n}\n\n/**\n * Registers the client reference manifests of the pages that supplied client\n * references to the render being validated, beyond the validated route's own\n * manifest. This thread has its own manifests singleton, which `loadComponents`\n * seeds with only the validated route, so without these the dev-only cross-page\n * lookup in `createProxiedClientReferenceManifest` has no other manifest to\n * search and decoding the transported payload fails. Usually a no-op, since the\n * main thread only records a page when React's I/O tracking actually carried a\n * reference across pages.\n */\nasync function registerAdditionalClientReferenceManifests(\n distDir: string,\n pages: string[]\n): Promise<void> {\n if (pages.length === 0) {\n return\n }\n\n // Set by `loadComponents`. One server actions manifest covers the whole app,\n // so the pages registered here share the validated route's.\n const serverActionsManifest = getServerActionsManifest()\n\n await Promise.all(\n pages.map(async (page) => {\n const clientReferenceManifest = await loadClientReferenceManifestForPage(\n distDir,\n page\n )\n\n if (clientReferenceManifest) {\n setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n })\n )\n}\n\n/**\n * Runs the dev instant/static-shell validation passes off the main thread.\n * Reloads the route's compiled module, then delegates the whole validation to\n * that module via `ComponentMod.routeModule.runValidationInDev`, so every\n * render (flight re-encodes and client prerenders) runs inside the app-page\n * bundle's single React instance. Logs any returned errors to the worker's\n * stderr with source-mapped code frames, then encodes them as RSC Flight bytes\n * for the main thread to forward to the dev overlay. Returns `null` when\n * validation was superseded or produced no errors.\n */\nexport async function runDevValidation(\n message: DevValidationWorkerMessage,\n abortBuffer: SharedArrayBuffer\n): Promise<DevValidationWorkerResult> {\n // Load the native SWC bindings and wire the code-frame renderer so the errors\n // logged below render with a source-mapped code frame, matching the\n // in-process dev output (the E2E tests snapshot the CLI text between the\n // validation markers). The `build/swc` graph these pull in is bundled as a\n // runtime external (see `next-runtime.webpack-config.js`), so it resolves\n // from the installed `next/dist` tree rather than being compiled into this\n // worker bundle, the same way the unbundled build worker loads it.\n await installBindings()\n installCodeFrameSupport()\n setBundlerFindSourceMapImplementation(\n createDiskSourceMapLookup(message.distDir)\n )\n setHttpClientAndAgentOptions({\n httpAgentOptions: message.nextConfigSerializable.httpAgentOptions,\n })\n\n // Populates the manifests singleton for the route via `setManifestsSingleton`\n // inside `loadComponents`, exactly as a real request does. The pool tears the\n // worker down on HMR / route recompile so the next validation reloads from a\n // clean require cache.\n const { ComponentMod } = await loadComponents<AppPageModule>({\n distDir: message.distDir,\n page: message.page,\n isAppPath: true,\n isDev: true,\n sriEnabled: false,\n needsManifestsForLegacyReasons: true,\n })\n\n await registerAdditionalClientReferenceManifests(\n message.distDir,\n message.additionalClientReferenceManifestPages\n )\n\n const { signal, cleanup } = createSupersedeSignal(abortBuffer)\n\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: 'validation_start',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n responseFinished: message.responseFinished,\n })\n )\n }\n\n try {\n if (isTestLoggingEnabled) {\n await applyTestValidationDelay(signal)\n }\n\n if (signal.aborted) {\n return null\n }\n\n // Crossing into the app-page bundle: the entire validation runs there, so\n // the client prerenders use the same React the user's client components\n // resolve through `ComponentMod`.\n const validationErrors = await ComponentMod.routeModule.runValidationInDev(\n ComponentMod,\n message,\n signal\n )\n\n if (validationErrors === undefined || signal.aborted) {\n return null\n }\n\n const errors: Error[] = []\n for (const validationError of validationErrors) {\n // Log to the worker's stderr; `node-environment` +\n // `installCodeFrameSupport` render the source-mapped stack and code frame\n // there, matching the in-process CLI output.\n console.error(validationError)\n if (validationError instanceof Error) {\n errors.push(validationError)\n }\n }\n\n if (errors.length === 0) {\n return null\n }\n\n return await serializeValidationErrorsToFlight(ComponentMod, errors)\n } finally {\n cleanup()\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: signal.aborted ? 'validation_aborted' : 'validation_end',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n })\n )\n }\n }\n}\n"],"names":["runDevValidation","createDiskSourceMapLookup","distDir","canonicalDistDir","realpathSync","payloads","Map","findSourceMapPayloadOnDisk","sourceURL","chunkPath","startsWith","fileURLToPath","undefined","isAbsolute","cached","get","has","payload","relativePath","relative","JSON","parse","readFileSync","set","Error","stackTraceLimit","isTestLoggingEnabled","process","env","__NEXT_TEST_MODE","NEXT_TEST_LOG_VALIDATION","createSupersedeSignal","abortBuffer","controller","AbortController","flag","Int32Array","Atomics","load","abort","signal","cleanup","settled","wait","waitAsync","async","value","then","notify","applyTestValidationDelay","delayMs","Number","NEXT_TEST_DEV_VALIDATION_DELAY_MS","isFinite","aborted","Promise","resolve","finishDelay","clearTimeout","timeout","removeEventListener","setTimeout","addEventListener","once","registerAdditionalClientReferenceManifests","pages","length","serverActionsManifest","getServerActionsManifest","all","map","page","clientReferenceManifest","loadClientReferenceManifestForPage","setManifestsSingleton","message","installBindings","installCodeFrameSupport","setBundlerFindSourceMapImplementation","setHttpClientAndAgentOptions","httpAgentOptions","nextConfigSerializable","ComponentMod","loadComponents","isAppPath","isDev","sriEnabled","needsManifestsForLegacyReasons","additionalClientReferenceManifestPages","console","log","formatValidationEvent","type","requestId","url","request","urlPathname","urlSearch","responseFinished","validationErrors","routeModule","runValidationInDev","errors","validationError","error","push","serializeValidationErrorsToFlight"],"mappings":";;;;+BAgPsBA;;;eAAAA;;;QA1Of;QACA;sBAE8B;oBACM;qBACb;iCACE;kCACQ;gCAIjC;mCACsC;4CACK;qCACZ;oCAI/B;mCAC+C;AAGtD;;;;;;;;;;;;;;;;;;;CAmBC,GACD,SAASC,0BACPC,OAAe;IAEf,6EAA6E;IAC7E,0EAA0E;IAC1E,WAAW;IACX,IAAIC,mBAAmBD;IACvB,IAAI;QACFC,mBAAmBC,IAAAA,gBAAY,EAACF;IAClC,EAAE,OAAM,CAAC;IAET,MAAMG,WAAW,IAAIC;IAErB,OAAO,SAASC,2BAA2BC,SAAS;QAClD,IAAIC,YAAYD;QAEhB,IAAIC,UAAUC,UAAU,CAAC,YAAY;YACnC,IAAI;gBACFD,YAAYE,IAAAA,kBAAa,EAACF;YAC5B,EAAE,OAAM;gBACN,OAAOG;YACT;QACF;QAEA,IAAI,CAACC,IAAAA,gBAAU,EAACJ,YAAY;YAC1B,qEAAqE;YACrE,OAAOG;QACT;QAEA,MAAME,SAAST,SAASU,GAAG,CAACN;QAC5B,IAAIK,WAAWF,aAAaP,SAASW,GAAG,CAACP,YAAY;YACnD,OAAOK;QACT;QAEA,IAAIG;QACJ,MAAMC,eAAeC,IAAAA,cAAQ,EAAChB,kBAAkBM;QAEhD,wEAAwE;QACxE,+DAA+D;QAC/D,IAAI,CAACS,aAAaR,UAAU,CAAC,SAAS,CAACG,IAAAA,gBAAU,EAACK,eAAe;YAC/D,IAAI;gBACFD,UAAUG,KAAKC,KAAK,CAACC,IAAAA,gBAAY,EAACb,YAAY,QAAQ;YACxD,EAAE,OAAM;gBACNQ,UAAUL;YACZ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5BC,KAAKnB,QAAQoB,OAAO,CAACC,WAAW,GAAGrB,QAAQoB,OAAO,CAACE,SAAS;YAC9D;QAEJ;IACF;AACF","ignoreList":[0]} |
| import type { ServerResponse } from 'node:http'; | ||
| /** | ||
| * Destroys the zlib stream that the `compression` middleware left open on a | ||
| * response that never finished. | ||
| * | ||
| * The middleware ends its stream only from its own `res.end()` wrapper, so a | ||
| * client disconnect leaves it open, and an open zlib stream is pinned by its | ||
| * native handle: it survives GC, permanently retaining ~256 KiB of deflate | ||
| * state. Ending it rather than destroying it does not work -- its `data` handler | ||
| * writes to the dead response, `res.write()` returns `false`, and the middleware | ||
| * pauses the stream, so it never reaches `end`. | ||
| * | ||
| * `res.on('drain', …)` is forwarded to that stream and `EventEmitter#on` returns | ||
| * the emitter, which is the only handle to it from outside. When compression is | ||
| * inactive the call returns `res` itself. | ||
| */ | ||
| export declare function releaseCompressionStream(res: ServerResponse): void; |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { | ||
| value: true | ||
| }); | ||
| Object.defineProperty(exports, "releaseCompressionStream", { | ||
| enumerable: true, | ||
| get: function() { | ||
| return releaseCompressionStream; | ||
| } | ||
| }); | ||
| const _nodestream = require("node:stream"); | ||
| const noop = ()=>{}; | ||
| function releaseCompressionStream(res) { | ||
| const maybeStream = res.on('drain', noop); | ||
| // The `Duplex` check keeps a future middleware change from turning this into a | ||
| // `destroy()` on a non-stream, which would throw from a `close` handler. | ||
| if (maybeStream === res || !(maybeStream instanceof _nodestream.Duplex)) { | ||
| res.off('drain', noop); | ||
| return; | ||
| } | ||
| maybeStream.destroy(); | ||
| } | ||
| //# sourceMappingURL=release-compression-stream.js.map |
| {"version":3,"sources":["../../../src/server/lib/release-compression-stream.ts"],"sourcesContent":["import type { ServerResponse } from 'node:http'\nimport { Duplex } from 'node:stream'\n\nconst noop = () => {}\n\n/**\n * Destroys the zlib stream that the `compression` middleware left open on a\n * response that never finished.\n *\n * The middleware ends its stream only from its own `res.end()` wrapper, so a\n * client disconnect leaves it open, and an open zlib stream is pinned by its\n * native handle: it survives GC, permanently retaining ~256 KiB of deflate\n * state. Ending it rather than destroying it does not work -- its `data` handler\n * writes to the dead response, `res.write()` returns `false`, and the middleware\n * pauses the stream, so it never reaches `end`.\n *\n * `res.on('drain', …)` is forwarded to that stream and `EventEmitter#on` returns\n * the emitter, which is the only handle to it from outside. When compression is\n * inactive the call returns `res` itself.\n */\nexport function releaseCompressionStream(res: ServerResponse): void {\n const maybeStream: unknown = res.on('drain', noop)\n\n // The `Duplex` check keeps a future middleware change from turning this into a\n // `destroy()` on a non-stream, which would throw from a `close` handler.\n if (maybeStream === res || !(maybeStream instanceof Duplex)) {\n res.off('drain', noop)\n return\n }\n\n maybeStream.destroy()\n}\n"],"names":["releaseCompressionStream","noop","res","maybeStream","on","Duplex","off","destroy"],"mappings":";;;;+BAoBgBA;;;eAAAA;;;4BAnBO;AAEvB,MAAMC,OAAO,KAAO;AAiBb,SAASD,yBAAyBE,GAAmB;IAC1D,MAAMC,cAAuBD,IAAIE,EAAE,CAAC,SAASH;IAE7C,+EAA+E;IAC/E,yEAAyE;IACzE,IAAIE,gBAAgBD,OAAO,CAAEC,CAAAA,uBAAuBE,kBAAM,AAAD,GAAI;QAC3DH,IAAII,GAAG,CAAC,SAASL;QACjB;IACF;IAEAE,YAAYI,OAAO;AACrB","ignoreList":[0]} |
@@ -138,3 +138,3 @@ "use strict"; | ||
| }({}); | ||
| const nextVersion = "16.3.0-canary.96"; | ||
| const nextVersion = "16.3.0-canary.97"; | ||
| const ArchName = (0, _os.arch)(); | ||
@@ -141,0 +141,0 @@ const PlatformName = (0, _os.platform)(); |
@@ -96,3 +96,3 @@ "use strict"; | ||
| isPersistentCachingEnabled: persistentCaching, | ||
| nextVersion: "16.3.0-canary.96" | ||
| nextVersion: "16.3.0-canary.97" | ||
| }, { | ||
@@ -99,0 +99,0 @@ turbopackMemoryEviction: config.experimental.turbopackMemoryEvictionMode, |
@@ -118,3 +118,3 @@ // Import cpu-profile first to start profiling early if enabled | ||
| deferredEntries: config.experimental.deferredEntries, | ||
| nextVersion: "16.3.0-canary.96" | ||
| nextVersion: "16.3.0-canary.97" | ||
| }; | ||
@@ -121,0 +121,0 @@ const sharedTurboOptions = { |
@@ -6,5 +6,5 @@ 1:"$Sreact.fragment" | ||
| 7:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/0umcxbkfjfq.0.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/0umcxbkfjfq.0.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 4:{} | ||
| 5:"$0:rsc:props:children:0:props:serverProvidedParams:params" | ||
| 8:null |
@@ -12,3 +12,3 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/0umcxbkfjfq.0.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/0umcxbkfjfq.0.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 6:{} | ||
@@ -15,0 +15,0 @@ 7:"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params" |
@@ -5,2 +5,2 @@ 1:"$Sreact.fragment" | ||
| 4:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} |
@@ -5,2 +5,2 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} |
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}},"staleTime":300,"buildId":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}},"staleTime":300,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} |
@@ -10,2 +10,2 @@ <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kp3gz-tar6qr.js"/><script src="/_next/static/chunks/0o8czoqls7u7z.js" async=""></script><script src="/_next/static/chunks/0x_ezzus9zvio.js" async=""></script><script src="/_next/static/chunks/turbopack-0htcm_o68u32o.js" async=""></script><script src="/_next/static/chunks/00qfakp0bmxst.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| })(); | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kp3gz-tar6qr.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[32816,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n3:I[78470,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n4:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ViewportBoundary\"]\na:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"MetadataBoundary\"]\nc:I[43334,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/00qfakp0bmxst.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"n-bNe3k7fxKlqnoBT5_ZT\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kp3gz-tar6qr.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[32816,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n3:I[78470,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n4:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ViewportBoundary\"]\na:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"MetadataBoundary\"]\nc:I[43334,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/00qfakp0bmxst.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"ssoYuJB_kT5Zgw5eY8qfb\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> |
@@ -10,3 +10,3 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| d:[] | ||
@@ -13,0 +13,0 @@ 7:"$Wd" |
@@ -10,3 +10,3 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| d:[] | ||
@@ -13,0 +13,0 @@ 7:"$Wd" |
@@ -5,2 +5,2 @@ 1:"$Sreact.fragment" | ||
| 4:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"rsc":["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} |
@@ -5,2 +5,2 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} |
| 1:"$Sreact.fragment" | ||
| 2:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"OutletBoundary"] | ||
| 3:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],null,["$","$L2",null,{"children":["$","$3",null,{"name":"Next.MetadataOutlet","children":"$@4"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],null,["$","$L2",null,{"children":["$","$3",null,{"name":"Next.MetadataOutlet","children":"$@4"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 4:null |
@@ -5,2 +5,2 @@ 1:"$Sreact.fragment" | ||
| 4:[] | ||
| 0:{"rsc":["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}]}]]}],"isPartial":false,"staleTime":300,"varyParams":"$W4","buildId":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"rsc":["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}]}]]}],"isPartial":false,"staleTime":300,"varyParams":"$W4","buildId":"ssoYuJB_kT5Zgw5eY8qfb"} |
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"/_not-found","param":null,"prefetchHints":0,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}}}},"staleTime":300,"buildId":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"/_not-found","param":null,"prefetchHints":0,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}}}},"staleTime":300,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} |
@@ -10,2 +10,2 @@ <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kp3gz-tar6qr.js"/><script src="/_next/static/chunks/0o8czoqls7u7z.js" async=""></script><script src="/_next/static/chunks/0x_ezzus9zvio.js" async=""></script><script src="/_next/static/chunks/turbopack-0htcm_o68u32o.js" async=""></script><script src="/_next/static/chunks/00qfakp0bmxst.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| })(); | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kp3gz-tar6qr.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[32816,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n3:I[78470,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n4:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ViewportBoundary\"]\na:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"MetadataBoundary\"]\nc:I[43334,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/00qfakp0bmxst.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"n-bNe3k7fxKlqnoBT5_ZT\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kp3gz-tar6qr.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[32816,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n3:I[78470,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n4:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ViewportBoundary\"]\na:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"MetadataBoundary\"]\nc:I[43334,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/00qfakp0bmxst.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"ssoYuJB_kT5Zgw5eY8qfb\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> |
@@ -10,2 +10,2 @@ <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kp3gz-tar6qr.js"/><script src="/_next/static/chunks/0o8czoqls7u7z.js" async=""></script><script src="/_next/static/chunks/0x_ezzus9zvio.js" async=""></script><script src="/_next/static/chunks/turbopack-0htcm_o68u32o.js" async=""></script><script src="/_next/static/chunks/00qfakp0bmxst.js" async=""></script><script src="/_next/static/chunks/0umcxbkfjfq.0.js" async=""></script><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| })(); | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><main class="h-screen flex flex-col bg-background"><div class="flex-none px-4 py-2 border-b border-border flex items-center gap-3"><div class="flex-1 flex"><div class="flex items-center gap-2 min-w-64 max-w-full"><button class="inline-flex items-center gap-2 whitespace-nowrap rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 flex-grow-1 w-full justify-between font-mono text-sm" role="combobox" aria-expanded="false" disabled="" type="button" aria-haspopup="dialog" aria-controls="radix-_R_lbtb_" data-state="closed"><div class="flex items-center"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader mr-2 inline animate-spin" aria-hidden="true"><path d="M12 2v4"></path><path d="m16.2 7.8 2.9-2.9"></path><path d="M18 12h4"></path><path d="m16.2 16.2 2.9 2.9"></path><path d="M12 18v4"></path><path d="m4.9 19.1 2.9-2.9"></path><path d="M2 12h4"></path><path d="m4.9 4.9 2.9 2.9"></path></svg>Loading routes...</div><div class="flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down h-4 w-4 shrink-0 opacity-50" aria-hidden="true"><path d="m7 15 5 5 5-5"></path><path d="m7 9 5-5 5 5"></path></svg></div></button></div></div><div class="flex items-center gap-2"></div></div><div class="flex-1 flex min-h-0"><div class="flex-1 min-w-0 p-4 bg-background"><div class="h-full w-full grid grid-cols-12 grid-rows-8 gap-2"><div class="animate-pulse rounded-md bg-muted col-span-5 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-1"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div></div></div><button type="button" class="flex-none w-1 bg-border cursor-col-resize transition-colors" disabled="" aria-label="Resize sidebar"></button><div class="flex-none bg-muted border-l border-border overflow-y-auto" style="width:20%"><div class="flex-1 p-3 space-y-4 overflow-y-auto"><div class="animate-pulse rounded-md bg-muted h-4 w-3/4"></div><div class="animate-pulse rounded-md bg-muted h-4 w-full"></div><div class="animate-pulse rounded-md bg-muted h-4 w-5/6"></div><div class="mt-4 space-y-2"><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-4/5"></div></div></div></div></div></main><!--$--><!--/$--><script src="/_next/static/chunks/0kp3gz-tar6qr.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[32816,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n3:I[78470,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n4:I[87181,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ClientPageRoot\"]\n5:I[79331,[\"/_next/static/chunks/00qfakp0bmxst.js\",\"/_next/static/chunks/0umcxbkfjfq.0.js\"],\"default\"]\n8:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"OutletBoundary\"]\n9:\"$Sreact.suspense\"\nb:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ViewportBoundary\"]\nd:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"MetadataBoundary\"]\nf:I[43334,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"__PAGE__\",{}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/00qfakp0bmxst.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"$L4\",null,{\"Component\":\"$5\",\"serverProvidedParams\":{\"searchParams\":{},\"params\":{},\"promises\":[\"$@6\",\"$@7\"]}}],[[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/0umcxbkfjfq.0.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"$L8\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@a\"}]}]]}],{},null,false,null]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$Lb\",null,{\"children\":\"$Lc\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$Ld\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Le\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$f\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"n-bNe3k7fxKlqnoBT5_ZT\"}\n"])</script><script>self.__next_f.push([1,"6:{}\n7:\"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params\"\n"])</script><script>self.__next_f.push([1,"c:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"a:null\ne:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><main class="h-screen flex flex-col bg-background"><div class="flex-none px-4 py-2 border-b border-border flex items-center gap-3"><div class="flex-1 flex"><div class="flex items-center gap-2 min-w-64 max-w-full"><button class="inline-flex items-center gap-2 whitespace-nowrap rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 flex-grow-1 w-full justify-between font-mono text-sm" role="combobox" aria-expanded="false" disabled="" type="button" aria-haspopup="dialog" aria-controls="radix-_R_lbtb_" data-state="closed"><div class="flex items-center"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader mr-2 inline animate-spin" aria-hidden="true"><path d="M12 2v4"></path><path d="m16.2 7.8 2.9-2.9"></path><path d="M18 12h4"></path><path d="m16.2 16.2 2.9 2.9"></path><path d="M12 18v4"></path><path d="m4.9 19.1 2.9-2.9"></path><path d="M2 12h4"></path><path d="m4.9 4.9 2.9 2.9"></path></svg>Loading routes...</div><div class="flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down h-4 w-4 shrink-0 opacity-50" aria-hidden="true"><path d="m7 15 5 5 5-5"></path><path d="m7 9 5-5 5 5"></path></svg></div></button></div></div><div class="flex items-center gap-2"></div></div><div class="flex-1 flex min-h-0"><div class="flex-1 min-w-0 p-4 bg-background"><div class="h-full w-full grid grid-cols-12 grid-rows-8 gap-2"><div class="animate-pulse rounded-md bg-muted col-span-5 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-1"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div></div></div><button type="button" class="flex-none w-1 bg-border cursor-col-resize transition-colors" disabled="" aria-label="Resize sidebar"></button><div class="flex-none bg-muted border-l border-border overflow-y-auto" style="width:20%"><div class="flex-1 p-3 space-y-4 overflow-y-auto"><div class="animate-pulse rounded-md bg-muted h-4 w-3/4"></div><div class="animate-pulse rounded-md bg-muted h-4 w-full"></div><div class="animate-pulse rounded-md bg-muted h-4 w-5/6"></div><div class="mt-4 space-y-2"><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-4/5"></div></div></div></div></div></main><!--$--><!--/$--><script src="/_next/static/chunks/0kp3gz-tar6qr.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[32816,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n3:I[78470,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n4:I[87181,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ClientPageRoot\"]\n5:I[79331,[\"/_next/static/chunks/00qfakp0bmxst.js\",\"/_next/static/chunks/0umcxbkfjfq.0.js\"],\"default\"]\n8:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"OutletBoundary\"]\n9:\"$Sreact.suspense\"\nb:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ViewportBoundary\"]\nd:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"MetadataBoundary\"]\nf:I[43334,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"__PAGE__\",{}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/00qfakp0bmxst.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"$L4\",null,{\"Component\":\"$5\",\"serverProvidedParams\":{\"searchParams\":{},\"params\":{},\"promises\":[\"$@6\",\"$@7\"]}}],[[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/0umcxbkfjfq.0.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"$L8\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@a\"}]}]]}],{},null,false,null]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$Lb\",null,{\"children\":\"$Lc\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$Ld\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Le\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$f\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"ssoYuJB_kT5Zgw5eY8qfb\"}\n"])</script><script>self.__next_f.push([1,"6:{}\n7:\"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params\"\n"])</script><script>self.__next_f.push([1,"c:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"a:null\ne:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> |
@@ -12,3 +12,3 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/0umcxbkfjfq.0.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"n-bNe3k7fxKlqnoBT5_ZT"} | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/0umcxbkfjfq.0.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 6:{} | ||
@@ -15,0 +15,0 @@ 7:"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params" |
@@ -42,3 +42,3 @@ #!/usr/bin/env node | ||
| const nextBuild = async (options, directory)=>{ | ||
| process.title = `next-build (v${"16.3.0-canary.96"})`; | ||
| process.title = `next-build (v${"16.3.0-canary.97"})`; | ||
| process.on('SIGTERM', ()=>{ | ||
@@ -45,0 +45,0 @@ (0, _cpuprofile.saveCpuProfile)(); |
@@ -43,3 +43,3 @@ #!/usr/bin/env node | ||
| const bindings = await (0, _swc.loadBindings)((_config_experimental1 = config.experimental) == null ? void 0 : _config_experimental1.useWasmBinary); | ||
| await bindings.turbo.databaseCompact(cachePath, "16.3.0-canary.96"); | ||
| await bindings.turbo.databaseCompact(cachePath, "16.3.0-canary.97"); | ||
| console.log('Turbopack database compaction complete.'); | ||
@@ -46,0 +46,0 @@ }; |
@@ -18,3 +18,3 @@ /** | ||
| const _setattributesfromprops = require("./set-attributes-from-props"); | ||
| const version = "16.3.0-canary.96"; | ||
| const version = "16.3.0-canary.97"; | ||
| window.next = { | ||
@@ -21,0 +21,0 @@ version, |
@@ -63,3 +63,3 @@ /* global location */ // imports polyfill from `@next/polyfill-module` after build. | ||
| const _isnextroutererror = require("./components/is-next-router-error"); | ||
| const version = "16.3.0-canary.96"; | ||
| const version = "16.3.0-canary.97"; | ||
| let router; | ||
@@ -66,0 +66,0 @@ const emitter = (0, _mitt.default)(); |
@@ -14,3 +14,3 @@ import path from 'path'; | ||
| }({}); | ||
| const nextVersion = "16.3.0-canary.96"; | ||
| const nextVersion = "16.3.0-canary.97"; | ||
| const ArchName = arch(); | ||
@@ -17,0 +17,0 @@ const PlatformName = platform(); |
@@ -69,3 +69,3 @@ import path from 'path'; | ||
| isPersistentCachingEnabled: persistentCaching, | ||
| nextVersion: "16.3.0-canary.96" | ||
| nextVersion: "16.3.0-canary.97" | ||
| }, { | ||
@@ -72,0 +72,0 @@ turbopackMemoryEviction: config.experimental.turbopackMemoryEvictionMode, |
@@ -87,3 +87,3 @@ // Import cpu-profile first to start profiling early if enabled | ||
| deferredEntries: config.experimental.deferredEntries, | ||
| nextVersion: "16.3.0-canary.96" | ||
| nextVersion: "16.3.0-canary.97" | ||
| }; | ||
@@ -90,0 +90,0 @@ const sharedTurboOptions = { |
@@ -8,3 +8,3 @@ /** | ||
| import { setAttributesFromProps } from './set-attributes-from-props'; | ||
| const version = "16.3.0-canary.96"; | ||
| const version = "16.3.0-canary.97"; | ||
| window.next = { | ||
@@ -11,0 +11,0 @@ version, |
@@ -28,3 +28,3 @@ /* global location */ // imports polyfill from `@next/polyfill-module` after build. | ||
| import { isNextRouterError } from './components/is-next-router-error'; | ||
| export const version = "16.3.0-canary.96"; | ||
| export const version = "16.3.0-canary.97"; | ||
| export let router; | ||
@@ -31,0 +31,0 @@ export const emitter = mitt(); |
@@ -20,3 +20,3 @@ import { readFileSync, writeFileSync } from 'fs'; | ||
| const data = await res.json(); | ||
| const versionData = data.versions["16.3.0-canary.96"]; | ||
| const versionData = data.versions["16.3.0-canary.97"]; | ||
| return { | ||
@@ -54,3 +54,3 @@ os: versionData.os, | ||
| lockfileParsed.dependencies[pkg] = { | ||
| version: "16.3.0-canary.96", | ||
| version: "16.3.0-canary.97", | ||
| resolved: pkgData.tarball, | ||
@@ -63,3 +63,3 @@ integrity: pkgData.integrity, | ||
| lockfileParsed.packages[pkg] = { | ||
| version: "16.3.0-canary.96", | ||
| version: "16.3.0-canary.97", | ||
| resolved: pkgData.tarball, | ||
@@ -66,0 +66,0 @@ integrity: pkgData.integrity, |
@@ -46,3 +46,4 @@ import { InvariantError } from '../../shared/lib/invariant-error'; | ||
| if (workStore) { | ||
| const currentManifest = clientReferenceManifestsPerRoute.get(workStore.route); | ||
| var _clientReferenceManifestsPerRoute_get; | ||
| const currentManifest = (_clientReferenceManifestsPerRoute_get = clientReferenceManifestsPerRoute.get(workStore.route)) == null ? void 0 : _clientReferenceManifestsPerRoute_get.clientReferenceManifest; | ||
| if (currentManifest == null ? void 0 : currentManifest[prop][id]) { | ||
@@ -62,8 +63,15 @@ return currentManifest[prop][id]; | ||
| if (process.env.NODE_ENV !== 'production') { | ||
| for (const [route, manifest] of clientReferenceManifestsPerRoute){ | ||
| for (const [route, { page, clientReferenceManifest }] of clientReferenceManifestsPerRoute){ | ||
| if (route === workStore.route) { | ||
| continue; | ||
| } | ||
| const entry = manifest[prop][id]; | ||
| const entry = clientReferenceManifest[prop][id]; | ||
| if (entry !== undefined) { | ||
| if (process.env.__NEXT_DEV_SERVER) { | ||
| // The dev validation worker rebuilds this registry in its | ||
| // own thread, seeded with only the route it validates, so | ||
| // it has to be told which other manifests it needs. | ||
| workStore.additionalClientReferenceManifestPages ??= new Set(); | ||
| workStore.additionalClientReferenceManifestPages.add(page); | ||
| } | ||
| return entry; | ||
@@ -80,4 +88,4 @@ } | ||
| // that case we search all page manifests to find the module. | ||
| for (const manifest of clientReferenceManifestsPerRoute.values()){ | ||
| const entry = manifest[prop][id]; | ||
| for (const { clientReferenceManifest } of clientReferenceManifestsPerRoute.values()){ | ||
| const entry = clientReferenceManifest[prop][id]; | ||
| if (entry !== undefined) { | ||
@@ -108,4 +116,4 @@ return entry; | ||
| } | ||
| const currentManifest = clientReferenceManifestsPerRoute.get(workStore.route); | ||
| if (!currentManifest) { | ||
| const registeredManifest = clientReferenceManifestsPerRoute.get(workStore.route); | ||
| if (!registeredManifest) { | ||
| throw Object.defineProperty(new InvariantError(`The client reference manifest for route "${workStore.route}" does not exist.`), "__NEXT_ERROR_CODE", { | ||
@@ -117,3 +125,3 @@ value: "E951", | ||
| } | ||
| return currentManifest[prop]; | ||
| return registeredManifest.clientReferenceManifest[prop]; | ||
| } | ||
@@ -231,2 +239,3 @@ case 'clientModules': | ||
| const existingSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]; | ||
| const route = normalizeAppPath(page); | ||
| const serverActionsManifest = { | ||
@@ -240,3 +249,6 @@ encryptionKey: rawServerActionsManifest.encryptionKey, | ||
| if (existingSingleton) { | ||
| existingSingleton.clientReferenceManifestsPerRoute.set(normalizeAppPath(page), clientReferenceManifest); | ||
| existingSingleton.clientReferenceManifestsPerRoute.set(route, { | ||
| page, | ||
| clientReferenceManifest | ||
| }); | ||
| existingSingleton.serverActionsManifest = serverActionsManifest; | ||
@@ -246,4 +258,7 @@ } else { | ||
| [ | ||
| normalizeAppPath(page), | ||
| clientReferenceManifest | ||
| route, | ||
| { | ||
| page, | ||
| clientReferenceManifest | ||
| } | ||
| ] | ||
@@ -250,0 +265,0 @@ ]); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/app-render/manifests-singleton.ts"],"sourcesContent":["import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'\nimport type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { mightBeServerReferenceId } from '../../shared/lib/server-reference-info'\nimport { wellKnownProperties } from '../../shared/lib/utils/reflect-utils'\nimport { workAsyncStorage } from './work-async-storage.external'\n\nexport interface ServerModuleMap {\n readonly [name: string]: {\n readonly id: string | number\n readonly name: string\n readonly chunks: Readonly<Array<string>> // currently not used\n readonly async?: boolean\n }\n}\n\nexport function getActionNotFoundError(actionId: string | null): Error {\n return new Error(\n `Failed to find Server Action${actionId ? ` \"${actionId}\"` : ''}. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n )\n}\n\nexport function getInvalidServerReferenceIdError(id: string): Error {\n // `id` is arbitrary client-provided input. Unlike the not-found case, it has\n // not passed the length gate and can reach this error via a malformed server\n // reference in an action payload, so it may be of any length and contain\n // control characters. `JSON.stringify` escapes newlines and quotes so it\n // can't forge log lines, and truncating overly long ids prevents log\n // flooding. Ids at or below the cap are logged in full so that we only add an\n // ellipsis to ids that are meaningfully longer than the truncated length.\n const encoded = JSON.stringify(\n id.length > MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH\n ? id.slice(0, TRUNCATED_SERVER_REFERENCE_ID_LENGTH) + '…'\n : id\n )\n\n return new Error(\n `The Server Reference ID did not match the expected format. Received ${encoded}.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n )\n}\n\n// Ids at or below the cap are logged in full. Longer ids are truncated to the\n// shorter length and marked with an ellipsis, so the cap leaves headroom over\n// the truncated length rather than ellipsizing ids that are barely too long.\nconst MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH = 100\nconst TRUNCATED_SERVER_REFERENCE_ID_LENGTH = 90\n\n// This is a global singleton that is, among other things, also used to\n// encode/decode bound args of server function closures. This can't be using a\n// AsyncLocalStorage as it might happen at the module level.\nconst MANIFESTS_SINGLETON = Symbol.for('next.server.manifests')\n\ninterface ManifestsSingleton {\n readonly clientReferenceManifestsPerRoute: Map<\n string,\n DeepReadonly<ClientReferenceManifest>\n >\n readonly proxiedClientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n serverActionsManifest: DeepReadonly<ActionManifest>\n serverModuleMap: ServerModuleMap\n}\n\ntype GlobalThisWithManifests = typeof globalThis & {\n [MANIFESTS_SINGLETON]?: ManifestsSingleton\n}\n\ntype ClientReferenceManifestMappingProp =\n | 'clientModules'\n | 'rscModuleMapping'\n | 'edgeRscModuleMapping'\n | 'ssrModuleMapping'\n | 'edgeSSRModuleMapping'\n\nconst globalThisWithManifests = globalThis as GlobalThisWithManifests\n\nfunction createProxiedClientReferenceManifest(\n clientReferenceManifestsPerRoute: Map<\n string,\n DeepReadonly<ClientReferenceManifest>\n >\n): DeepReadonly<ClientReferenceManifest> {\n const createMappingProxy = (prop: ClientReferenceManifestMappingProp) => {\n return new Proxy(\n {},\n {\n get(_, id: string) {\n const workStore = workAsyncStorage.getStore()\n\n if (workStore) {\n const currentManifest = clientReferenceManifestsPerRoute.get(\n workStore.route\n )\n\n if (currentManifest?.[prop][id]) {\n return currentManifest[prop][id]\n }\n\n // In development, we also check all other manifests to see if the\n // module exists there. This is to support a scenario where React's\n // I/O tracking (dev-only) creates a connection from one page to\n // another through an emitted async I/O node that references client\n // components from the other page, e.g. in owner props.\n // TODO: Maybe we need to add a `debugBundlerConfig` option to React\n // to avoid this workaround. The current workaround has the\n // disadvantage that one might accidentally or intentionally share\n // client references across pages (e.g. by storing them in a global\n // variable), which would then only be caught in production.\n if (process.env.NODE_ENV !== 'production') {\n for (const [\n route,\n manifest,\n ] of clientReferenceManifestsPerRoute) {\n if (route === workStore.route) {\n continue\n }\n\n const entry = manifest[prop][id]\n\n if (entry !== undefined) {\n return entry\n }\n }\n }\n } else {\n // If there's no work store defined, we can assume that a client\n // reference manifest is needed during module evaluation, e.g. to\n // create a server function using a higher-order function. This\n // might also use client components which need to be serialized by\n // Flight, and therefore client references need to be resolvable. In\n // that case we search all page manifests to find the module.\n for (const manifest of clientReferenceManifestsPerRoute.values()) {\n const entry = manifest[prop][id]\n\n if (entry !== undefined) {\n return entry\n }\n }\n }\n\n return undefined\n },\n }\n )\n }\n\n const mappingProxies = new Map<\n ClientReferenceManifestMappingProp,\n ReturnType<typeof createMappingProxy>\n >()\n\n return new Proxy(\n {},\n {\n get(_, prop) {\n const workStore = workAsyncStorage.getStore()\n\n switch (prop) {\n case 'moduleLoading':\n case 'entryCSSFiles':\n case 'entryJSFiles': {\n if (!workStore) {\n throw new InvariantError(\n `Cannot access \"${prop}\" without a work store.`\n )\n }\n\n const currentManifest = clientReferenceManifestsPerRoute.get(\n workStore.route\n )\n\n if (!currentManifest) {\n throw new InvariantError(\n `The client reference manifest for route \"${workStore.route}\" does not exist.`\n )\n }\n\n return currentManifest[prop]\n }\n case 'clientModules':\n case 'rscModuleMapping':\n case 'edgeRscModuleMapping':\n case 'ssrModuleMapping':\n case 'edgeSSRModuleMapping': {\n let proxy = mappingProxies.get(prop)\n\n if (!proxy) {\n proxy = createMappingProxy(prop)\n mappingProxies.set(prop, proxy)\n }\n\n return proxy\n }\n default: {\n throw new InvariantError(\n `This is a proxied client reference manifest. The property \"${String(prop)}\" is not handled.`\n )\n }\n }\n },\n }\n ) as DeepReadonly<ClientReferenceManifest>\n}\n\n/**\n * This function creates a Flight-acceptable server module map proxy from our\n * Server Reference Manifest similar to our client module map. This is because\n * our manifest contains a lot of internal Next.js data that are relevant to the\n * runtime, workers, etc. that React doesn't need to know.\n */\nfunction createServerModuleMap(): ServerModuleMap {\n return new Proxy(Object.create(null) as ServerModuleMap, {\n get: (target, id: string | symbol, receiver) => {\n // React's debug serialization can probe the module map like a plain object.\n // These probes are not server reference lookups.\n if (typeof id !== 'string') {\n return Reflect.get(target, id, receiver)\n }\n\n if (wellKnownProperties.has(id)) {\n return Reflect.get(target, id, receiver)\n }\n\n if (!mightBeServerReferenceId(id)) {\n throw getInvalidServerReferenceIdError(id)\n }\n\n const workers =\n getServerActionsManifest()[\n process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n ]?.[id]?.workers\n\n if (!workers) {\n throw getActionNotFoundError(id)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n let workerEntry: { moduleId: string | number; async: boolean } | undefined\n\n if (workStore) {\n workerEntry = workers[normalizeWorkerPageName(workStore.page)]\n } else {\n // If there's no work store defined, we can assume that a server\n // module map is needed during module evaluation, e.g. to create a\n // server action using a higher-order function. Therefore it should be\n // safe to return any entry from the manifest that matches the action\n // ID. They all refer to the same module ID, which must also exist in\n // the current page bundle. TODO: This is currently not guaranteed in\n // Turbopack, and needs to be fixed.\n workerEntry = Object.values(workers).at(0)\n }\n\n if (!workerEntry) {\n throw getActionNotFoundError(id)\n }\n\n const { moduleId, async } = workerEntry\n\n return { id: moduleId, name: id, chunks: [], async }\n },\n })\n}\n\n/**\n * The flight entry loader keys actions by bundlePath. bundlePath corresponds\n * with the relative path (including 'app') to the page entrypoint.\n */\nfunction normalizeWorkerPageName(pageName: string) {\n if (pathHasPrefix(pageName, 'app')) {\n return pageName\n }\n\n return 'app' + pageName\n}\n\n/**\n * Converts a bundlePath (relative path to the entrypoint) to a routable page\n * name.\n */\nfunction denormalizeWorkerPageName(bundlePath: string) {\n return normalizeAppPath(removePathPrefix(bundlePath, 'app'))\n}\n\n/**\n * Checks if the requested action has a worker for the current page.\n * If not, it returns the first worker that has a handler for the action.\n */\nexport function selectWorkerForForwarding(\n actionId: string,\n pageName: string\n): string | undefined {\n const serverActionsManifest = getServerActionsManifest()\n const workers =\n serverActionsManifest[\n process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n ][actionId]?.workers\n\n // There are no workers to handle this action, nothing to forward to.\n if (!workers) {\n return\n }\n\n // If there is an entry for the current page, we don't need to forward.\n if (workers[normalizeWorkerPageName(pageName)]) {\n return\n }\n\n // Otherwise, grab the first worker that has a handler for this action id.\n return denormalizeWorkerPageName(Object.keys(workers)[0])\n}\n\nexport function setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest: rawServerActionsManifest,\n}: {\n page: string\n clientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n serverActionsManifest: DeepReadonly<ActionManifest>\n}) {\n const existingSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]\n\n const serverActionsManifest: DeepReadonly<ActionManifest> = {\n encryptionKey: rawServerActionsManifest.encryptionKey,\n // Use null-prototypes for the action objects to prevent prototype pollution\n // from affecting action ID lookups.\n node: Object.assign(Object.create(null), rawServerActionsManifest.node),\n edge: Object.assign(Object.create(null), rawServerActionsManifest.edge),\n }\n\n if (existingSingleton) {\n existingSingleton.clientReferenceManifestsPerRoute.set(\n normalizeAppPath(page),\n clientReferenceManifest\n )\n\n existingSingleton.serverActionsManifest = serverActionsManifest\n } else {\n const clientReferenceManifestsPerRoute = new Map<\n string,\n DeepReadonly<ClientReferenceManifest>\n >([[normalizeAppPath(page), clientReferenceManifest]])\n\n const proxiedClientReferenceManifest = createProxiedClientReferenceManifest(\n clientReferenceManifestsPerRoute\n )\n\n globalThisWithManifests[MANIFESTS_SINGLETON] = {\n clientReferenceManifestsPerRoute,\n proxiedClientReferenceManifest,\n serverActionsManifest,\n serverModuleMap: createServerModuleMap(),\n }\n }\n}\n\nfunction getManifestsSingleton(): ManifestsSingleton {\n const manifestSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]\n\n if (!manifestSingleton) {\n throw new InvariantError('The manifests singleton was not initialized.')\n }\n\n return manifestSingleton\n}\n\nexport function getClientReferenceManifest(): DeepReadonly<ClientReferenceManifest> {\n return getManifestsSingleton().proxiedClientReferenceManifest\n}\n\nexport function getServerActionsManifest(): DeepReadonly<ActionManifest> {\n return getManifestsSingleton().serverActionsManifest\n}\n\nexport function getServerModuleMap() {\n return getManifestsSingleton().serverModuleMap\n}\n"],"names":["InvariantError","normalizeAppPath","pathHasPrefix","removePathPrefix","mightBeServerReferenceId","wellKnownProperties","workAsyncStorage","getActionNotFoundError","actionId","Error","getInvalidServerReferenceIdError","id","encoded","JSON","stringify","length","MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH","slice","TRUNCATED_SERVER_REFERENCE_ID_LENGTH","MANIFESTS_SINGLETON","Symbol","for","globalThisWithManifests","globalThis","createProxiedClientReferenceManifest","clientReferenceManifestsPerRoute","createMappingProxy","prop","Proxy","get","_","workStore","getStore","currentManifest","route","process","env","NODE_ENV","manifest","entry","undefined","values","mappingProxies","Map","proxy","set","String","createServerModuleMap","Object","create","target","receiver","getServerActionsManifest","Reflect","has","workers","NEXT_RUNTIME","workerEntry","normalizeWorkerPageName","page","at","moduleId","async","name","chunks","pageName","denormalizeWorkerPageName","bundlePath","selectWorkerForForwarding","serverActionsManifest","keys","setManifestsSingleton","clientReferenceManifest","rawServerActionsManifest","existingSingleton","encryptionKey","node","assign","edge","proxiedClientReferenceManifest","serverModuleMap","getManifestsSingleton","manifestSingleton","getClientReferenceManifest","getServerModuleMap"],"mappings":"AAGA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SAASC,gBAAgB,QAAQ,0CAAyC;AAC1E,SAASC,aAAa,QAAQ,gDAA+C;AAC7E,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,wBAAwB,QAAQ,yCAAwC;AACjF,SAASC,mBAAmB,QAAQ,uCAAsC;AAC1E,SAASC,gBAAgB,QAAQ,gCAA+B;AAWhE,OAAO,SAASC,uBAAuBC,QAAuB;IAC5D,OAAO,qBAEN,CAFM,IAAIC,MACT,CAAC,4BAA4B,EAAED,WAAW,CAAC,EAAE,EAAEA,SAAS,CAAC,CAAC,GAAG,GAAG,oIAAoI,C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AAC7B,OAAOC,MAAM,CAAC,OAAOwB,yBAAyBK,IAAI;IACxE;IAEA,IAAIJ,mBAAmB;QACrBA,kBAAkBjD,gCAAgC,CAACoB,GAAG,CACpD5C,iBAAiB0D,OACjBa;QAGFE,kBAAkBL,qBAAqB,GAAGA;IAC5C,OAAO;QACL,MAAM5C,mCAAmC,IAAIkB,IAG3C;YAAC;gBAAC1C,iBAAiB0D;gBAAOa;aAAwB;SAAC;QAErD,MAAMO,iCAAiCvD,qCACrCC;QAGFH,uBAAuB,CAACH,oBAAoB,GAAG;YAC7CM;YACAsD;YACAV;YACAW,iBAAiBjC;QACnB;IACF;AACF;AAEA,SAASkC;IACP,MAAMC,oBAAoB5D,uBAAuB,CAACH,oBAAoB;IAEtE,IAAI,CAAC+D,mBAAmB;QACtB,MAAM,qBAAkE,CAAlE,IAAIlF,eAAe,iDAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAiE;IACzE;IAEA,OAAOkF;AACT;AAEA,OAAO,SAASC;IACd,OAAOF,wBAAwBF,8BAA8B;AAC/D;AAEA,OAAO,SAAS3B;IACd,OAAO6B,wBAAwBZ,qBAAqB;AACtD;AAEA,OAAO,SAASe;IACd,OAAOH,wBAAwBD,eAAe;AAChD","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/app-render/manifests-singleton.ts"],"sourcesContent":["import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'\nimport type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { mightBeServerReferenceId } from '../../shared/lib/server-reference-info'\nimport { wellKnownProperties } from '../../shared/lib/utils/reflect-utils'\nimport { workAsyncStorage } from './work-async-storage.external'\n\nexport interface ServerModuleMap {\n readonly [name: string]: {\n readonly id: string | number\n readonly name: string\n readonly chunks: Readonly<Array<string>> // currently not used\n readonly async?: boolean\n }\n}\n\nexport function getActionNotFoundError(actionId: string | null): Error {\n return new Error(\n `Failed to find Server Action${actionId ? ` \"${actionId}\"` : ''}. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n )\n}\n\nexport function getInvalidServerReferenceIdError(id: string): Error {\n // `id` is arbitrary client-provided input. Unlike the not-found case, it has\n // not passed the length gate and can reach this error via a malformed server\n // reference in an action payload, so it may be of any length and contain\n // control characters. `JSON.stringify` escapes newlines and quotes so it\n // can't forge log lines, and truncating overly long ids prevents log\n // flooding. Ids at or below the cap are logged in full so that we only add an\n // ellipsis to ids that are meaningfully longer than the truncated length.\n const encoded = JSON.stringify(\n id.length > MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH\n ? id.slice(0, TRUNCATED_SERVER_REFERENCE_ID_LENGTH) + '…'\n : id\n )\n\n return new Error(\n `The Server Reference ID did not match the expected format. Received ${encoded}.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n )\n}\n\n// Ids at or below the cap are logged in full. Longer ids are truncated to the\n// shorter length and marked with an ellipsis, so the cap leaves headroom over\n// the truncated length rather than ellipsizing ids that are barely too long.\nconst MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH = 100\nconst TRUNCATED_SERVER_REFERENCE_ID_LENGTH = 90\n\n// This is a global singleton that is, among other things, also used to\n// encode/decode bound args of server function closures. This can't be using a\n// AsyncLocalStorage as it might happen at the module level.\nconst MANIFESTS_SINGLETON = Symbol.for('next.server.manifests')\n\ninterface RegisteredClientReferenceManifest {\n /**\n * The page the manifest was registered with. Routes are normalized app paths,\n * which is lossy (route groups, parallel slots and the trailing `/page` are\n * stripped), so this is kept alongside for consumers that need to address the\n * manifest on disk again rather than reversing the normalization.\n */\n readonly page: string\n readonly clientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n}\n\ninterface ManifestsSingleton {\n readonly clientReferenceManifestsPerRoute: Map<\n string,\n RegisteredClientReferenceManifest\n >\n readonly proxiedClientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n serverActionsManifest: DeepReadonly<ActionManifest>\n serverModuleMap: ServerModuleMap\n}\n\ntype GlobalThisWithManifests = typeof globalThis & {\n [MANIFESTS_SINGLETON]?: ManifestsSingleton\n}\n\ntype ClientReferenceManifestMappingProp =\n | 'clientModules'\n | 'rscModuleMapping'\n | 'edgeRscModuleMapping'\n | 'ssrModuleMapping'\n | 'edgeSSRModuleMapping'\n\nconst globalThisWithManifests = globalThis as GlobalThisWithManifests\n\nfunction createProxiedClientReferenceManifest(\n clientReferenceManifestsPerRoute: Map<\n string,\n RegisteredClientReferenceManifest\n >\n): DeepReadonly<ClientReferenceManifest> {\n const createMappingProxy = (prop: ClientReferenceManifestMappingProp) => {\n return new Proxy(\n {},\n {\n get(_, id: string) {\n const workStore = workAsyncStorage.getStore()\n\n if (workStore) {\n const currentManifest = clientReferenceManifestsPerRoute.get(\n workStore.route\n )?.clientReferenceManifest\n\n if (currentManifest?.[prop][id]) {\n return currentManifest[prop][id]\n }\n\n // In development, we also check all other manifests to see if the\n // module exists there. This is to support a scenario where React's\n // I/O tracking (dev-only) creates a connection from one page to\n // another through an emitted async I/O node that references client\n // components from the other page, e.g. in owner props.\n // TODO: Maybe we need to add a `debugBundlerConfig` option to React\n // to avoid this workaround. The current workaround has the\n // disadvantage that one might accidentally or intentionally share\n // client references across pages (e.g. by storing them in a global\n // variable), which would then only be caught in production.\n if (process.env.NODE_ENV !== 'production') {\n for (const [\n route,\n { page, clientReferenceManifest },\n ] of clientReferenceManifestsPerRoute) {\n if (route === workStore.route) {\n continue\n }\n\n const entry = clientReferenceManifest[prop][id]\n\n if (entry !== undefined) {\n if (process.env.__NEXT_DEV_SERVER) {\n // The dev validation worker rebuilds this registry in its\n // own thread, seeded with only the route it validates, so\n // it has to be told which other manifests it needs.\n workStore.additionalClientReferenceManifestPages ??=\n new Set()\n workStore.additionalClientReferenceManifestPages.add(page)\n }\n\n return entry\n }\n }\n }\n } else {\n // If there's no work store defined, we can assume that a client\n // reference manifest is needed during module evaluation, e.g. to\n // create a server function using a higher-order function. This\n // might also use client components which need to be serialized by\n // Flight, and therefore client references need to be resolvable. In\n // that case we search all page manifests to find the module.\n for (const {\n clientReferenceManifest,\n } of clientReferenceManifestsPerRoute.values()) {\n const entry = clientReferenceManifest[prop][id]\n\n if (entry !== undefined) {\n return entry\n }\n }\n }\n\n return undefined\n },\n }\n )\n }\n\n const mappingProxies = new Map<\n ClientReferenceManifestMappingProp,\n ReturnType<typeof createMappingProxy>\n >()\n\n return new Proxy(\n {},\n {\n get(_, prop) {\n const workStore = workAsyncStorage.getStore()\n\n switch (prop) {\n case 'moduleLoading':\n case 'entryCSSFiles':\n case 'entryJSFiles': {\n if (!workStore) {\n throw new InvariantError(\n `Cannot access \"${prop}\" without a work store.`\n )\n }\n\n const registeredManifest = clientReferenceManifestsPerRoute.get(\n workStore.route\n )\n\n if (!registeredManifest) {\n throw new InvariantError(\n `The client reference manifest for route \"${workStore.route}\" does not exist.`\n )\n }\n\n return registeredManifest.clientReferenceManifest[prop]\n }\n case 'clientModules':\n case 'rscModuleMapping':\n case 'edgeRscModuleMapping':\n case 'ssrModuleMapping':\n case 'edgeSSRModuleMapping': {\n let proxy = mappingProxies.get(prop)\n\n if (!proxy) {\n proxy = createMappingProxy(prop)\n mappingProxies.set(prop, proxy)\n }\n\n return proxy\n }\n default: {\n throw new InvariantError(\n `This is a proxied client reference manifest. The property \"${String(prop)}\" is not handled.`\n )\n }\n }\n },\n }\n ) as DeepReadonly<ClientReferenceManifest>\n}\n\n/**\n * This function creates a Flight-acceptable server module map proxy from our\n * Server Reference Manifest similar to our client module map. This is because\n * our manifest contains a lot of internal Next.js data that are relevant to the\n * runtime, workers, etc. that React doesn't need to know.\n */\nfunction createServerModuleMap(): ServerModuleMap {\n return new Proxy(Object.create(null) as ServerModuleMap, {\n get: (target, id: string | symbol, receiver) => {\n // React's debug serialization can probe the module map like a plain object.\n // These probes are not server reference lookups.\n if (typeof id !== 'string') {\n return Reflect.get(target, id, receiver)\n }\n\n if (wellKnownProperties.has(id)) {\n return Reflect.get(target, id, receiver)\n }\n\n if (!mightBeServerReferenceId(id)) {\n throw getInvalidServerReferenceIdError(id)\n }\n\n const workers =\n getServerActionsManifest()[\n process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n ]?.[id]?.workers\n\n if (!workers) {\n throw getActionNotFoundError(id)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n let workerEntry: { moduleId: string | number; async: boolean } | undefined\n\n if (workStore) {\n workerEntry = workers[normalizeWorkerPageName(workStore.page)]\n } else {\n // If there's no work store defined, we can assume that a server\n // module map is needed during module evaluation, e.g. to create a\n // server action using a higher-order function. Therefore it should be\n // safe to return any entry from the manifest that matches the action\n // ID. They all refer to the same module ID, which must also exist in\n // the current page bundle. TODO: This is currently not guaranteed in\n // Turbopack, and needs to be fixed.\n workerEntry = Object.values(workers).at(0)\n }\n\n if (!workerEntry) {\n throw getActionNotFoundError(id)\n }\n\n const { moduleId, async } = workerEntry\n\n return { id: moduleId, name: id, chunks: [], async }\n },\n })\n}\n\n/**\n * The flight entry loader keys actions by bundlePath. bundlePath corresponds\n * with the relative path (including 'app') to the page entrypoint.\n */\nfunction normalizeWorkerPageName(pageName: string) {\n if (pathHasPrefix(pageName, 'app')) {\n return pageName\n }\n\n return 'app' + pageName\n}\n\n/**\n * Converts a bundlePath (relative path to the entrypoint) to a routable page\n * name.\n */\nfunction denormalizeWorkerPageName(bundlePath: string) {\n return normalizeAppPath(removePathPrefix(bundlePath, 'app'))\n}\n\n/**\n * Checks if the requested action has a worker for the current page.\n * If not, it returns the first worker that has a handler for the action.\n */\nexport function selectWorkerForForwarding(\n actionId: string,\n pageName: string\n): string | undefined {\n const serverActionsManifest = getServerActionsManifest()\n const workers =\n serverActionsManifest[\n process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n ][actionId]?.workers\n\n // There are no workers to handle this action, nothing to forward to.\n if (!workers) {\n return\n }\n\n // If there is an entry for the current page, we don't need to forward.\n if (workers[normalizeWorkerPageName(pageName)]) {\n return\n }\n\n // Otherwise, grab the first worker that has a handler for this action id.\n return denormalizeWorkerPageName(Object.keys(workers)[0])\n}\n\nexport function setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest: rawServerActionsManifest,\n}: {\n page: string\n clientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n serverActionsManifest: DeepReadonly<ActionManifest>\n}) {\n const existingSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]\n const route = normalizeAppPath(page)\n\n const serverActionsManifest: DeepReadonly<ActionManifest> = {\n encryptionKey: rawServerActionsManifest.encryptionKey,\n // Use null-prototypes for the action objects to prevent prototype pollution\n // from affecting action ID lookups.\n node: Object.assign(Object.create(null), rawServerActionsManifest.node),\n edge: Object.assign(Object.create(null), rawServerActionsManifest.edge),\n }\n\n if (existingSingleton) {\n existingSingleton.clientReferenceManifestsPerRoute.set(route, {\n page,\n clientReferenceManifest,\n })\n\n existingSingleton.serverActionsManifest = serverActionsManifest\n } else {\n const clientReferenceManifestsPerRoute = new Map<\n string,\n RegisteredClientReferenceManifest\n >([[route, { page, clientReferenceManifest }]])\n\n const proxiedClientReferenceManifest = createProxiedClientReferenceManifest(\n clientReferenceManifestsPerRoute\n )\n\n globalThisWithManifests[MANIFESTS_SINGLETON] = {\n clientReferenceManifestsPerRoute,\n proxiedClientReferenceManifest,\n serverActionsManifest,\n serverModuleMap: createServerModuleMap(),\n }\n }\n}\n\nfunction getManifestsSingleton(): ManifestsSingleton {\n const manifestSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]\n\n if (!manifestSingleton) {\n throw new InvariantError('The manifests singleton was not initialized.')\n }\n\n return manifestSingleton\n}\n\nexport function getClientReferenceManifest(): DeepReadonly<ClientReferenceManifest> {\n return getManifestsSingleton().proxiedClientReferenceManifest\n}\n\nexport function getServerActionsManifest(): DeepReadonly<ActionManifest> {\n return getManifestsSingleton().serverActionsManifest\n}\n\nexport function getServerModuleMap() {\n return getManifestsSingleton().serverModuleMap\n}\n"],"names":["InvariantError","normalizeAppPath","pathHasPrefix","removePathPrefix","mightBeServerReferenceId","wellKnownProperties","workAsyncStorage","getActionNotFoundError","actionId","Error","getInvalidServerReferenceIdError","id","encoded","JSON","stringify","length","MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH","slice","TRUNCATED_SERVER_REFERENCE_ID_LENGTH","MANIFESTS_SINGLETON","Symbol","for","globalThisWithManifests","globalThis","createProxiedClientReferenceManifest","clientReferenceManifestsPerRoute","createMappingProxy","prop","Proxy","get","_","workStore","getStore","currentManifest","route","clientReferenceManifest","process","env","NODE_ENV","page","entry","undefined","__NEXT_DEV_SERVER","additionalClientReferenceManifestPages","Set","add","values","mappingProxies","Map","registeredManifest","proxy","set","String","createServerModuleMap","Object","create","target","receiver","getServerActionsManifest","Reflect","has","workers","NEXT_RUNTIME","workerEntry","normalizeWorkerPageName","at","moduleId","async","name","chunks","pageName","denormalizeWorkerPageName","bundlePath","selectWorkerForForwarding","serverActionsManifest","keys","setManifestsSingleton","rawServerActionsManifest","existingSingleton","encryptionKey","node","assign","edge","proxiedClientReferenceManifest","serverModuleMap","getManifestsSingleton","manifestSingleton","getClientReferenceManifest","getServerModuleMap"],"mappings":"AAGA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SAASC,gBAAgB,QAAQ,0CAAyC;AAC1E,SAASC,aAAa,QAAQ,gDAA+C;AAC7E,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,wBAAwB,QAAQ,yCAAwC;AACjF,SAASC,mBAAmB,QAAQ,uCAAsC;AAC1E,SAASC,gBAAgB,QAAQ,gCAA+B;AAWhE,OAAO,SAASC,uBAAuBC,QAAuB;IAC5D,OAAO,qBAEN,CAFM,IAAIC,MACT,CAA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} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/app-render/work-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { FetchMetrics } from '../base-http'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'\nimport type { AfterContext } from '../after/after-context'\nimport type { ResolvedCacheLifeProfiles } from '../config-shared'\nimport type { SharedCacheResult } from '../use-cache/use-cache-wrapper'\nimport type { ValidationLevel } from '../config-shared'\n\n// Share the instance module in the next-shared layer\nimport { workAsyncStorageInstance } from './work-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { LazyResult } from '../lib/lazy-result'\nimport type { DigestedError } from './create-error-handler'\nimport type { ActionRevalidationKind } from '../../shared/lib/action-revalidation-kind'\n\nexport interface WorkStore {\n readonly isStaticGeneration: boolean\n\n /**\n * The page that is being rendered. This relates to the path to the page file.\n */\n readonly page: string\n\n /**\n * The route that is being rendered. This is the page property without the\n * trailing `/page` or `/route` suffix.\n */\n readonly route: string\n\n readonly incrementalCache?: IncrementalCache\n readonly cacheLifeProfiles: ResolvedCacheLifeProfiles\n readonly useCacheTimeout: number\n readonly staticPageGenerationTimeout: number\n\n readonly isOnDemandRevalidate?: boolean\n readonly isBuildTimePrerendering?: boolean\n\n forceDynamic?: boolean\n fetchCache?: AppSegmentConfig['fetchCache']\n\n forceStatic?: boolean\n dynamicShouldError?: boolean\n pendingRevalidates?: Record<string, Promise<any>>\n pendingRevalidateWrites?: Array<Promise<void>> // This is like pendingRevalidates but isn't used for deduping.\n readonly afterContext: AfterContext\n\n dynamicUsageDescription?: string\n dynamicUsageStack?: string\n\n /**\n * Invalid dynamic usage errors might be caught in userland. We attach them to\n * the work store to ensure we can still fail the build, or show en error in\n * dev mode.\n */\n // TODO: Collect an array of errors, and throw as AggregateError when\n // `serializeError` and the Dev Overlay support it.\n invalidDynamicUsageError?: Error\n\n nextFetchId?: number\n pathWasRevalidated?: ActionRevalidationKind\n\n /**\n * Tags that were revalidated during the current request. They need to be sent\n * to cache handlers to propagate their revalidation.\n */\n pendingRevalidatedTags?: Array<{\n tag: string\n profile?: string | { stale?: number; revalidate?: number; expire?: number }\n }>\n\n /**\n * Tags that were previously revalidated (e.g. by a redirecting server action)\n * and have already been sent to cache handlers. Retrieved cache entries that\n * include any of these tags must be discarded.\n */\n readonly previouslyRevalidatedTags: readonly string[]\n\n /**\n * This map contains lazy results so that we can evaluate them when the first\n * cache entry is read. It allows us to skip refreshing tags if no caches are\n * read at all.\n */\n readonly refreshTagsByCacheKind: Map<string, LazyResult<void>>\n\n fetchMetrics?: FetchMetrics\n shouldTrackFetchMetrics: boolean\n\n /**\n * Tracks pending `\"use cache\"` invocations within the current request scope,\n * keyed by the serialized cache key (coarse key). Used for intra-request\n * deduplication: when multiple components call the same cache function within\n * a single request, only the first one runs (cache handler lookup +\n * generation), and joiners tee its result stream.\n * Root params are identical within a request, so the coarse key is sufficient.\n */\n pendingCacheInvocations?: Map<string, Promise<SharedCacheResult>>\n\n /**\n * Set by the dev-server's hang-detection probe worker (see\n * `use-cache-probe-worker.ts`) to switch `cache()` into a one-shot fill\n * path: run `generateCacheEntry` as for a cold fill, drain the resulting\n * stream, return. No cache-handler or resume-data-cache I/O, no\n * intra-request leader election — the probe just needs to learn whether\n * the body completes in module-scope isolation.\n */\n readonly useCacheProbeMode?: {\n /**\n * Max wall time the probe fill may take. `cache()` enforces this with\n * `UseCacheTimeoutError`, which the probe worker translates to\n * `{ outcome: 'hung' }` for the parent process.\n */\n readonly timeoutMs: number\n }\n\n isDraftMode?: boolean\n isUnstableNoStore?: boolean\n isPrefetchRequest?: boolean\n\n /**\n * Dev-only request identity used by local request insights. requestId\n * identifies one server request, while htmlRequestId groups requests that\n * originated from the same browser page.\n */\n requestId?: string\n htmlRequestId?: string\n\n /**\n * This only exists because it's needed in use-cache-wrapper\n */\n deploymentId: string\n /**\n * Prefer `sharedContext.buildId` instead. This only exists because it's needed in use-cache-wrapper\n */\n buildId: string\n\n readonly reactLoadableManifest?: DeepReadonly<\n Record<string, { files: string[] }>\n >\n readonly assetPrefix?: string\n readonly nonce?: string\n\n cacheComponentsEnabled: boolean\n validationLevel: ValidationLevel\n\n /**\n * Run the given function inside a clean AsyncLocalStorage snapshot. This is\n * useful when generating cache entries, to ensure that the cache generation\n * cannot read anything from the context we're currently executing in, which\n * might include request-specific things like `cookies()` inside a\n * `React.cache()`.\n */\n runInCleanSnapshot: <R, TArgs extends any[]>(\n fn: (...args: TArgs) => R,\n ...args: TArgs\n ) => R\n\n reactServerErrorsByDigest: Map<string, DigestedError>\n}\n\nexport type WorkAsyncStorage = AsyncLocalStorage<WorkStore>\n\nexport { workAsyncStorageInstance as workAsyncStorage }\n"],"names":["workAsyncStorageInstance","workAsyncStorage"],"mappings":"AAUA,qDAAqD;AACrD,SAASA,wBAAwB,QAAQ,qCAAqC;IAAE,wBAAwB;AAAc,EAAC;AAuJvH,SAASA,4BAA4BC,gBAAgB,GAAE","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/app-render/work-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { FetchMetrics } from '../base-http'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'\nimport type { AfterContext } from '../after/after-context'\nimport type { ResolvedCacheLifeProfiles } from '../config-shared'\nimport type { SharedCacheResult } from '../use-cache/use-cache-wrapper'\nimport type { ValidationLevel } from '../config-shared'\n\n// Share the instance module in the next-shared layer\nimport { workAsyncStorageInstance } from './work-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { LazyResult } from '../lib/lazy-result'\nimport type { DigestedError } from './create-error-handler'\nimport type { ActionRevalidationKind } from '../../shared/lib/action-revalidation-kind'\n\nexport interface WorkStore {\n readonly isStaticGeneration: boolean\n\n /**\n * The page that is being rendered. This relates to the path to the page file.\n */\n readonly page: string\n\n /**\n * The route that is being rendered. This is the page property without the\n * trailing `/page` or `/route` suffix.\n */\n readonly route: string\n\n readonly incrementalCache?: IncrementalCache\n readonly cacheLifeProfiles: ResolvedCacheLifeProfiles\n readonly useCacheTimeout: number\n readonly staticPageGenerationTimeout: number\n\n readonly isOnDemandRevalidate?: boolean\n readonly isBuildTimePrerendering?: boolean\n\n forceDynamic?: boolean\n fetchCache?: AppSegmentConfig['fetchCache']\n\n forceStatic?: boolean\n dynamicShouldError?: boolean\n pendingRevalidates?: Record<string, Promise<any>>\n pendingRevalidateWrites?: Array<Promise<void>> // This is like pendingRevalidates but isn't used for deduping.\n readonly afterContext: AfterContext\n\n dynamicUsageDescription?: string\n dynamicUsageStack?: string\n\n /**\n * Invalid dynamic usage errors might be caught in userland. We attach them to\n * the work store to ensure we can still fail the build, or show en error in\n * dev mode.\n */\n // TODO: Collect an array of errors, and throw as AggregateError when\n // `serializeError` and the Dev Overlay support it.\n invalidDynamicUsageError?: Error\n\n nextFetchId?: number\n pathWasRevalidated?: ActionRevalidationKind\n\n /**\n * Tags that were revalidated during the current request. They need to be sent\n * to cache handlers to propagate their revalidation.\n */\n pendingRevalidatedTags?: Array<{\n tag: string\n profile?: string | { stale?: number; revalidate?: number; expire?: number }\n }>\n\n /**\n * Tags that were previously revalidated (e.g. by a redirecting server action)\n * and have already been sent to cache handlers. Retrieved cache entries that\n * include any of these tags must be discarded.\n */\n readonly previouslyRevalidatedTags: readonly string[]\n\n /**\n * This map contains lazy results so that we can evaluate them when the first\n * cache entry is read. It allows us to skip refreshing tags if no caches are\n * read at all.\n */\n readonly refreshTagsByCacheKind: Map<string, LazyResult<void>>\n\n fetchMetrics?: FetchMetrics\n shouldTrackFetchMetrics: boolean\n\n /**\n * Tracks pending `\"use cache\"` invocations within the current request scope,\n * keyed by the serialized cache key (coarse key). Used for intra-request\n * deduplication: when multiple components call the same cache function within\n * a single request, only the first one runs (cache handler lookup +\n * generation), and joiners tee its result stream.\n * Root params are identical within a request, so the coarse key is sufficient.\n */\n pendingCacheInvocations?: Map<string, Promise<SharedCacheResult>>\n\n /**\n * Set by the dev-server's hang-detection probe worker (see\n * `use-cache-probe-worker.ts`) to switch `cache()` into a one-shot fill\n * path: run `generateCacheEntry` as for a cold fill, drain the resulting\n * stream, return. No cache-handler or resume-data-cache I/O, no\n * intra-request leader election — the probe just needs to learn whether\n * the body completes in module-scope isolation.\n */\n readonly useCacheProbeMode?: {\n /**\n * Max wall time the probe fill may take. `cache()` enforces this with\n * `UseCacheTimeoutError`, which the probe worker translates to\n * `{ outcome: 'hung' }` for the parent process.\n */\n readonly timeoutMs: number\n }\n\n isDraftMode?: boolean\n isUnstableNoStore?: boolean\n isPrefetchRequest?: boolean\n\n /**\n * Dev-only request identity used by local request insights. requestId\n * identifies one server request, while htmlRequestId groups requests that\n * originated from the same browser page.\n */\n requestId?: string\n htmlRequestId?: string\n\n /**\n * This only exists because it's needed in use-cache-wrapper\n */\n deploymentId: string\n /**\n * Prefer `sharedContext.buildId` instead. This only exists because it's needed in use-cache-wrapper\n */\n buildId: string\n\n readonly reactLoadableManifest?: DeepReadonly<\n Record<string, { files: string[] }>\n >\n readonly assetPrefix?: string\n readonly nonce?: string\n\n cacheComponentsEnabled: boolean\n validationLevel: ValidationLevel\n\n /**\n * Pages, other than the one being rendered, whose client reference manifest\n * supplied a client reference for this render. Only populated by the dev\n * server, where React's I/O tracking can carry a reference from another page\n * into this render, which `createProxiedClientReferenceManifest` resolves by\n * searching the other pages' manifests. The dev validation worker rebuilds\n * that registry in its own thread from the route it validates, so it relies\n * on this to know which other manifests to register.\n */\n additionalClientReferenceManifestPages?: Set<string>\n\n /**\n * Run the given function inside a clean AsyncLocalStorage snapshot. This is\n * useful when generating cache entries, to ensure that the cache generation\n * cannot read anything from the context we're currently executing in, which\n * might include request-specific things like `cookies()` inside a\n * `React.cache()`.\n */\n runInCleanSnapshot: <R, TArgs extends any[]>(\n fn: (...args: TArgs) => R,\n ...args: TArgs\n ) => R\n\n reactServerErrorsByDigest: Map<string, DigestedError>\n}\n\nexport type WorkAsyncStorage = AsyncLocalStorage<WorkStore>\n\nexport { workAsyncStorageInstance as workAsyncStorage }\n"],"names":["workAsyncStorageInstance","workAsyncStorage"],"mappings":"AAUA,qDAAqD;AACrD,SAASA,wBAAwB,QAAQ,qCAAqC;IAAE,wBAAwB;AAAc,EAAC;AAkKvH,SAASA,4BAA4BC,gBAAgB,GAAE","ignoreList":[0]} |
@@ -424,2 +424,3 @@ import { VALID_LOADERS } from '../shared/lib/image-config'; | ||
| }).optional(), | ||
| devValidationWorker: z.boolean().optional(), | ||
| staticGenerationRetryCount: z.number().int().optional(), | ||
@@ -426,0 +427,0 @@ staticGenerationMaxConcurrency: z.number().int().optional(), |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/config-schema.ts"],"sourcesContent":["import type { NextConfig } from './config'\nimport { VALID_LOADERS } from '../shared/lib/image-config'\n\nimport { z } from 'next/dist/compiled/zod'\nimport type zod from 'next/dist/compiled/zod'\n\nimport type { SizeLimit } from '../types'\nimport {\n LIGHTNINGCSS_FEATURE_NAMES,\n type ExportPathMap,\n type TurbopackLoaderItem,\n type TurbopackOptions,\n type TurbopackRuleConfigItem,\n type TurbopackRuleConfigCollection,\n type TurbopackRuleCondition,\n type TurbopackLoaderBuiltinCondition,\n} from './config-shared'\nimport type {\n Header,\n Rewrite,\n RouteHas,\n Redirect,\n} from '../lib/load-custom-routes'\nimport { SUPPORTED_TEST_RUNNERS_LIST } from '../cli/next-test'\n\n// A custom zod schema for the SizeLimit type\nconst zSizeLimit = z.custom<SizeLimit>((val) => {\n if (typeof val === 'number' || typeof val === 'string') {\n return true\n }\n return false\n})\n\nconst zExportMap: zod.ZodType<ExportPathMap> = z.record(\n z.string(),\n z.object({\n page: z.string(),\n query: z.any(), // NextParsedUrlQuery\n\n // private optional properties\n _fallbackRouteParams: z.array(z.any()).optional(),\n _isAppDir: z.boolean().optional(),\n _isDynamicError: z.boolean().optional(),\n _isRoutePPREnabled: z.boolean().optional(),\n _allowEmptyStaticShell: z.boolean().optional(),\n _isFallbackUpgradeable: z.boolean().optional(),\n })\n)\n\nconst zRouteHas: zod.ZodType<RouteHas> = z.union([\n z.object({\n type: z.enum(['header', 'query', 'cookie']),\n key: z.string(),\n value: z.string().optional(),\n }),\n z.object({\n type: z.literal('host'),\n key: z.undefined().optional(),\n value: z.string(),\n }),\n])\n\nconst zRewrite: zod.ZodType<Rewrite> = z.object({\n source: z.string(),\n destination: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n internal: z.boolean().optional(),\n})\n\nconst zRedirect: zod.ZodType<Redirect> = z\n .object({\n source: z.string(),\n destination: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n internal: z.boolean().optional(),\n })\n .and(\n z.union([\n z.object({\n statusCode: z.never().optional(),\n permanent: z.boolean(),\n }),\n z.object({\n statusCode: z.number(),\n permanent: z.never().optional(),\n }),\n ])\n )\n\nconst zHeader: zod.ZodType<Header> = z.object({\n source: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n headers: z.array(z.object({ key: z.string(), value: z.string() })),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n\n internal: z.boolean().optional(),\n})\n\nconst zTurbopackLoaderItem: zod.ZodType<TurbopackLoaderItem> = z.union([\n z.string(),\n z.strictObject({\n loader: z.string(),\n // Any JSON value can be used as turbo loader options, so use z.any() here\n options: z.record(z.string(), z.any()).optional(),\n }),\n])\n\nconst zTurbopackLoaderBuiltinCondition: zod.ZodType<TurbopackLoaderBuiltinCondition> =\n z.union([\n z.literal('browser'),\n z.literal('foreign'),\n z.literal('development'),\n z.literal('production'),\n z.literal('node'),\n z.literal('edge-light'),\n ])\n\nconst zTurbopackCondition: zod.ZodType<TurbopackRuleCondition> = z.union([\n z.strictObject({ all: z.lazy(() => z.array(zTurbopackCondition)) }),\n z.strictObject({ any: z.lazy(() => z.array(zTurbopackCondition)) }),\n z.strictObject({ not: z.lazy(() => zTurbopackCondition) }),\n zTurbopackLoaderBuiltinCondition,\n z.strictObject({\n path: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n content: z.instanceof(RegExp).optional(),\n query: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n contentType: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n }),\n])\n\nconst zTurbopackModuleType = z.enum([\n 'asset',\n 'ecmascript',\n 'typescript',\n 'css',\n 'css-module',\n 'wasm',\n 'raw',\n 'node',\n 'bytes',\n])\n\nconst zTurbopackRuleConfigItem: zod.ZodType<TurbopackRuleConfigItem> =\n z.strictObject({\n loaders: z.array(zTurbopackLoaderItem).optional(),\n as: z.string().optional(),\n condition: zTurbopackCondition.optional(),\n type: zTurbopackModuleType.optional(),\n })\n\nconst zTurbopackRuleConfigCollection: zod.ZodType<TurbopackRuleConfigCollection> =\n z.union([\n zTurbopackRuleConfigItem,\n z.array(z.union([zTurbopackLoaderItem, zTurbopackRuleConfigItem])),\n ])\n\nconst zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({\n rules: z.record(z.string(), zTurbopackRuleConfigCollection).optional(),\n resolveAlias: z\n .record(\n z.string(),\n z.union([\n z.string(),\n z.array(z.string()),\n z.record(z.string(), z.union([z.string(), z.array(z.string())])),\n ])\n )\n .optional(),\n resolveExtensions: z.array(z.string()).optional(),\n root: z.string().optional(),\n debugIds: z.boolean().optional(),\n chunkLoadingGlobal: z.string().optional(),\n ignoreIssue: z\n .array(\n z.object({\n path: z.union([z.string(), z.instanceof(RegExp)]),\n title: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n description: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n })\n )\n .optional(),\n})\n\nexport const experimentalSchema = {\n outputHashSalt: z.string().optional(),\n useSkewCookie: z.boolean().optional(),\n after: z.boolean().optional(),\n appNavFailHandling: z.boolean().optional(),\n appNewScrollHandler: z.boolean().optional(),\n coldCacheBadge: z.boolean().optional(),\n preloadEntriesOnStart: z.boolean().optional(),\n allowedRevalidateHeaderKeys: z.array(z.string()).optional(),\n staleTimes: z\n .object({\n dynamic: z.number().optional(),\n static: z.number().gte(30).optional(),\n })\n .optional(),\n cacheLife: z\n .record(\n z.object({\n stale: z.number().optional(),\n revalidate: z.number().optional(),\n expire: z.number().optional(),\n })\n )\n .optional(),\n cacheHandlers: z.record(z.string(), z.string().optional()).optional(),\n clientRouterFilter: z.boolean().optional(),\n clientRouterFilterRedirects: z.boolean().optional(),\n clientRouterFilterAllowedRate: z.number().optional(),\n cpus: z.number().optional(),\n memoryBasedWorkersCount: z.boolean().optional(),\n craCompat: z.boolean().optional(),\n caseSensitiveRoutes: z.boolean().optional(),\n clientParamParsingOrigins: z.array(z.string()).optional(),\n cachedNavigations: z\n .union([z.boolean(), z.literal('allow-runtime')])\n .optional(),\n dynamicOnHover: z.boolean().optional(),\n useOffline: z.boolean().optional(),\n optimisticRouting: z.boolean().optional(),\n instrumentationClientRouterTransitionEvents: z.boolean().optional(),\n varyParams: z.boolean().optional(),\n prefetchInlining: z\n .union([\n z.boolean(),\n z.object({\n maxSize: z.number().optional(),\n maxBundleSize: z.number().optional(),\n }),\n ])\n .optional(),\n disableOptimizedLoading: z.boolean().optional(),\n disablePostcssPresetEnv: z.boolean().optional(),\n cacheComponents: z.boolean().optional(),\n inlineCss: z.boolean().optional(),\n esmExternals: z.union([z.boolean(), z.literal('loose')]).optional(),\n serverActions: z\n .object({\n bodySizeLimit: zSizeLimit.optional(),\n allowedOrigins: z.array(z.string()).optional(),\n })\n .optional(),\n maxPostponedStateSize: zSizeLimit.optional(),\n // The original type was Record<string, any>\n extensionAlias: z.record(z.string(), z.any()).optional(),\n externalDir: z.boolean().optional(),\n externalMiddlewareRewritesResolve: z.boolean().optional(),\n externalProxyRewritesResolve: z.boolean().optional(),\n exposeTestingApiInProductionBuild: z.boolean().optional(),\n requestInsights: z.boolean().optional(),\n fallbackNodePolyfills: z.literal(false).optional(),\n fetchCacheKeyPrefix: z.string().optional(),\n forceSwcTransforms: z.boolean().optional(),\n fullySpecified: z.boolean().optional(),\n gzipSize: z.boolean().optional(),\n imgOptConcurrency: z.number().int().optional().nullable(),\n imgOptOperationCache: z.boolean().optional().nullable(),\n imgOptTimeoutInSeconds: z.number().int().optional(),\n imgOptMaxInputPixels: z.number().int().optional(),\n imgOptSequentialRead: z.boolean().optional().nullable(),\n isrFlushToDisk: z.boolean().optional(),\n largePageDataBytes: z.number().optional(),\n linkNoTouchStart: z.boolean().optional(),\n manualClientBasePath: z.boolean().optional(),\n middlewarePrefetch: z.enum(['strict', 'flexible']).optional(),\n proxyPrefetch: z.enum(['strict', 'flexible']).optional(),\n middlewareClientMaxBodySize: zSizeLimit.optional(),\n proxyClientMaxBodySize: zSizeLimit.optional(),\n multiZoneDraftMode: z.boolean().optional(),\n cssChunking: z\n .union([\n z.boolean(),\n z.literal('strict'),\n z.literal('loose'),\n z.literal('graph'),\n z.strictObject({ type: z.literal('strict') }),\n z.strictObject({ type: z.literal('loose') }),\n z.strictObject({\n type: z.literal('graph'),\n requestCost: z.number().nonnegative().finite().optional(),\n weightDistribution: z.number().nonnegative().finite().optional(),\n }),\n ])\n .optional(),\n nextScriptWorkers: z.boolean().optional(),\n // The critter option is unknown, use z.any() here\n optimizeCss: z.union([z.boolean(), z.any()]).optional(),\n optimisticClientCache: z.boolean().optional(),\n parallelServerCompiles: z.boolean().optional(),\n parallelServerBuildTraces: z.boolean().optional(),\n ppr: z\n .union([z.boolean(), z.literal('incremental')])\n .readonly()\n .optional(),\n taint: z.boolean().optional(),\n blockingSSR: z.boolean().optional(),\n prerenderEarlyExit: z.boolean().optional(),\n proxyTimeout: z.number().gte(0).optional(),\n rootParams: z.boolean().optional(),\n mcpServer: z.boolean().optional(),\n removeUncaughtErrorAndRejectionListeners: z.boolean().optional(),\n validateRSCRequestHeaders: z.boolean().optional(),\n scrollRestoration: z.boolean().optional(),\n sri: z\n .object({\n algorithm: z.enum(['sha256', 'sha384', 'sha512']).optional(),\n })\n .optional(),\n swcPlugins: z\n // The specific swc plugin's option is unknown, use z.any() here\n .array(z.tuple([z.string(), z.record(z.string(), z.any())]))\n .optional(),\n swcEnvOptions: z\n .object({\n mode: z.enum(['usage', 'entry']).optional(),\n coreJs: z.string().optional(),\n skip: z.array(z.string()).optional(),\n include: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n shippedProposals: z.boolean().optional(),\n forceAllTransforms: z.boolean().optional(),\n debug: z.boolean().optional(),\n loose: z.boolean().optional(),\n })\n .optional(),\n swcTraceProfiling: z.boolean().optional(),\n // NonNullable<webpack.Configuration['experiments']>['buildHttp']\n urlImports: z.any().optional(),\n workerThreads: z.boolean().optional(),\n webVitalsAttribution: z\n .array(\n z.union([\n z.literal('CLS'),\n z.literal('FCP'),\n z.literal('FID'),\n z.literal('INP'),\n z.literal('LCP'),\n z.literal('TTFB'),\n ])\n )\n .optional(),\n // This is partial set of mdx-rs transform options we support, aligned\n // with next_core::next_config::MdxRsOptions. Ensure both types are kept in sync.\n mdxRs: z\n .union([\n z.boolean(),\n z.object({\n development: z.boolean().optional(),\n jsxRuntime: z.string().optional(),\n jsxImportSource: z.string().optional(),\n providerImportSource: z.string().optional(),\n mdxType: z.enum(['gfm', 'commonmark']).optional(),\n }),\n ])\n .optional(),\n transitionIndicator: z.boolean().optional(),\n gestureTransition: z.boolean().optional(),\n typedRoutes: z.boolean().optional(),\n webpackBuildWorker: z.boolean().optional(),\n webpackMemoryOptimizations: z.boolean().optional(),\n turbopackMemoryEviction: z\n .union([z.literal(false), z.literal('full'), z.literal('auto')])\n .optional(),\n turbopackPluginRuntimeStrategy: z\n .enum(['workerThreads', 'childProcesses'])\n .optional(),\n turbopackMinify: z.boolean().optional(),\n turbopackFileSystemCacheForDev: z.boolean().optional(),\n turbopackFileSystemCacheForBuild: z.boolean().optional(),\n turbopackSourceMaps: z.boolean().optional(),\n turbopackInputSourceMaps: z.boolean().optional(),\n turbopackModuleFragments: z.boolean().optional(),\n turbopackRemoveUnusedImports: z.boolean().optional(),\n turbopackRemoveUnusedExports: z.boolean().optional(),\n turbopackScopeHoisting: z.boolean().optional(),\n turbopackGenerateComponentChunks: z.boolean().optional(),\n turbopackSharedRuntime: z.boolean().optional(),\n turbopackChunkingHeuristics: z\n .object({\n firstPageLoadPriority: z.number().min(0).max(1).optional(),\n priorityRoutes: z.array(z.instanceof(RegExp)).optional(),\n priorityBoost: z.number().min(1).optional(),\n requestCost: z.number().min(0).max(1_000_000).optional(),\n })\n .optional(),\n turbopackWorkerAssetPrefix: z.string().optional(),\n turbopackClientSideNestedAsyncChunking: z.boolean().optional(),\n turbopackServerSideNestedAsyncChunking: z.boolean().optional(),\n turbopackImportTypeBytes: z.boolean().optional(),\n turbopackUseBuiltinBabel: z.boolean().optional(),\n turbopackUseBuiltinSass: z.boolean().optional(),\n turbopackLocalPostcssConfig: z.boolean().optional(),\n turbopackModuleIds: z.enum(['named', 'deterministic']).optional(),\n turbopackInferModuleSideEffects: z.boolean().optional(),\n turbopackCjsTreeShaking: z.boolean().optional(),\n turbopackServerFastRefresh: z.boolean().optional(),\n optimizePackageImports: z.array(z.string()).optional(),\n optimizeServerReact: z.boolean().optional(),\n strictRouteTypes: z.boolean().optional(),\n useTypeScriptCli: z.boolean().optional(),\n clientTraceMetadata: z.array(z.string()).optional(),\n serverMinification: z.boolean().optional(),\n serverSourceMaps: z.boolean().optional(),\n useWasmBinary: z.boolean().optional(),\n useLightningcss: z.boolean().optional(),\n lightningCssFeatures: z\n .object({\n include: z.array(z.enum(LIGHTNINGCSS_FEATURE_NAMES)).optional(),\n exclude: z.array(z.enum(LIGHTNINGCSS_FEATURE_NAMES)).optional(),\n })\n .optional(),\n testProxy: z.boolean().optional(),\n defaultTestRunner: z.enum(SUPPORTED_TEST_RUNNERS_LIST).optional(),\n allowDevelopmentBuild: z.literal(true).optional(),\n\n reactDebugChannel: z.boolean().optional(),\n instantInsights: z\n .object({\n validationLevel: z\n .enum([\n 'warning',\n 'manual-warning',\n 'experimental-error',\n 'experimental-manual-error',\n ])\n .optional(),\n })\n .optional(),\n staticGenerationRetryCount: z.number().int().optional(),\n staticGenerationMaxConcurrency: z.number().int().optional(),\n staticGenerationMinPagesPerWorker: z.number().int().optional(),\n typedEnv: z.boolean().optional(),\n serverComponentsHmrCache: z.boolean().optional(),\n serverComponentsHmrCancellation: z.boolean().optional(),\n authInterrupts: z.boolean().optional(),\n useCache: z.boolean().optional(),\n durableUseCacheEntries: z.boolean().optional(),\n useCacheTimeout: z.number().positive().optional(),\n slowModuleDetection: z\n .object({\n buildTimeThresholdMs: z.number().int(),\n })\n .optional(),\n globalNotFound: z.boolean().optional(),\n turbopackRustReactCompiler: z.boolean().optional(),\n browserDebugInfoInTerminal: z\n .union([\n z.boolean(),\n z.enum(['error', 'warn', 'verbose']),\n z.object({\n level: z.enum(['error', 'warn', 'verbose']).optional(),\n depthLimit: z.number().int().positive().optional(),\n edgeLimit: z.number().int().positive().optional(),\n showSourceLocation: z.boolean().optional(),\n }),\n ])\n .optional(),\n lockDistDir: z.boolean().optional(),\n hideLogsAfterAbort: z.boolean().optional(),\n runtimeServerDeploymentId: z.boolean().optional(),\n supportsImmutableAssets: z.boolean().optional(),\n deferredEntries: z.array(z.string()).optional(),\n onBeforeDeferredEntries: z.function().returns(z.promise(z.void())).optional(),\n reportSystemEnvInlining: z.enum(['warn', 'error']).optional(),\n}\n\nexport const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>\n z.strictObject({\n adapterPath: z.string().optional(),\n agentRules: z.boolean().optional(),\n allowedDevOrigins: z.array(z.string()).optional(),\n assetPrefix: z.string().optional(),\n basePath: z.string().optional(),\n bundlePagesRouterDependencies: z.boolean().optional(),\n cacheComponents: z.boolean().optional(),\n cacheHandler: z.string().min(1).optional(),\n cacheHandlers: z.record(z.string(), z.string().optional()).optional(),\n cacheLife: z\n .record(\n z.object({\n stale: z.number().optional(),\n revalidate: z.number().optional(),\n expire: z.number().optional(),\n })\n )\n .optional(),\n cacheMaxMemorySize: z.number().optional(),\n cleanDistDir: z.boolean().optional(),\n compiler: z\n .strictObject({\n emotion: z\n .union([\n z.boolean(),\n z.object({\n sourceMap: z.boolean().optional(),\n autoLabel: z\n .union([\n z.literal('always'),\n z.literal('dev-only'),\n z.literal('never'),\n ])\n .optional(),\n labelFormat: z.string().min(1).optional(),\n importMap: z\n .record(\n z.string(),\n z.record(\n z.string(),\n z.object({\n canonicalImport: z\n .tuple([z.string(), z.string()])\n .optional(),\n styledBaseImport: z\n .tuple([z.string(), z.string()])\n .optional(),\n })\n )\n )\n .optional(),\n }),\n ])\n .optional(),\n reactRemoveProperties: z\n .union([\n z.boolean().optional(),\n z.object({\n properties: z.array(z.string()).optional(),\n }),\n ])\n .optional(),\n relay: z\n .object({\n src: z.string(),\n artifactDirectory: z.string().optional(),\n language: z.enum(['javascript', 'typescript', 'flow']).optional(),\n eagerEsModules: z.boolean().optional(),\n })\n .optional(),\n removeConsole: z\n .union([\n z.boolean().optional(),\n z.object({\n exclude: z.array(z.string()).min(1).optional(),\n }),\n ])\n .optional(),\n styledComponents: z.union([\n z.boolean().optional(),\n z.object({\n displayName: z.boolean().optional(),\n topLevelImportPaths: z.array(z.string()).optional(),\n ssr: z.boolean().optional(),\n fileName: z.boolean().optional(),\n meaninglessFileNames: z.array(z.string()).optional(),\n minify: z.boolean().optional(),\n transpileTemplateLiterals: z.boolean().optional(),\n namespace: z.string().min(1).optional(),\n pure: z.boolean().optional(),\n cssProp: z.boolean().optional(),\n }),\n ]),\n styledJsx: z.union([\n z.boolean().optional(),\n z.object({\n useLightningcss: z.boolean().optional(),\n }),\n ]),\n define: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional(),\n defineServer: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional(),\n runAfterProductionCompile: z\n .function()\n .returns(z.promise(z.void()))\n .optional(),\n })\n .optional(),\n compress: z.boolean().optional(),\n configOrigin: z.string().optional(),\n crossOrigin: z\n .union([z.literal('anonymous'), z.literal('use-credentials')])\n .optional(),\n deploymentId: z.string().optional(),\n supportsImmutableAssets: z.boolean().optional(),\n outputHashSalt: z.string().optional(),\n devIndicators: z\n .union([\n z.object({\n position: z\n .union([\n z.literal('bottom-left'),\n z.literal('bottom-right'),\n z.literal('top-left'),\n z.literal('top-right'),\n ])\n .optional(),\n }),\n z.literal(false),\n ])\n .optional(),\n distDir: z.string().min(1).optional(),\n env: z.record(z.string(), z.union([z.string(), z.undefined()])).optional(),\n enablePrerenderSourceMaps: z.boolean().optional(),\n excludeDefaultMomentLocales: z.boolean().optional(),\n experimental: z.strictObject(experimentalSchema).optional(),\n exportPathMap: z\n .function()\n .args(\n zExportMap,\n z.object({\n dev: z.boolean(),\n dir: z.string(),\n outDir: z.string().nullable(),\n distDir: z.string(),\n buildId: z.string(),\n })\n )\n .returns(z.union([zExportMap, z.promise(zExportMap)]))\n .optional(),\n generateBuildId: z\n .function()\n .args()\n .returns(\n z.union([\n z.string(),\n z.null(),\n z.promise(z.union([z.string(), z.null()])),\n ])\n )\n .optional(),\n generateEtags: z.boolean().optional(),\n headers: z\n .function()\n .args()\n .returns(z.promise(z.array(zHeader)))\n .optional(),\n htmlLimitedBots: z.instanceof(RegExp).optional(),\n httpAgentOptions: z\n .strictObject({ keepAlive: z.boolean().optional() })\n .optional(),\n i18n: z\n .strictObject({\n defaultLocale: z.string().min(1),\n domains: z\n .array(\n z.strictObject({\n defaultLocale: z.string().min(1),\n domain: z.string().min(1),\n http: z.literal(true).optional(),\n locales: z.array(z.string().min(1)).optional(),\n })\n )\n .optional(),\n localeDetection: z.literal(false).optional(),\n locales: z.array(z.string().min(1)),\n })\n .nullable()\n .optional(),\n images: z\n .strictObject({\n localPatterns: z\n .array(\n z.strictObject({\n pathname: z.string().optional(),\n search: z.string().optional(),\n })\n )\n .max(25)\n .optional(),\n remotePatterns: z\n .array(\n z.union([\n z.instanceof(URL),\n z.strictObject({\n hostname: z.string(),\n pathname: z.string().optional(),\n port: z.string().max(5).optional(),\n protocol: z.enum(['http', 'https']).optional(),\n search: z.string().optional(),\n }),\n ])\n )\n .max(50)\n .optional(),\n unoptimized: z.boolean().optional(),\n customCacheHandler: z.boolean().optional(),\n contentSecurityPolicy: z.string().optional(),\n contentDispositionType: z.enum(['inline', 'attachment']).optional(),\n dangerouslyAllowSVG: z.boolean().optional(),\n dangerouslyAllowLocalIP: z.boolean().optional(),\n deviceSizes: z\n .array(z.number().int().gte(1).lte(10000))\n .max(25)\n .optional(),\n disableStaticImages: z.boolean().optional(),\n domains: z.array(z.string()).max(50).optional(),\n formats: z\n .array(z.enum(['image/avif', 'image/webp']))\n .max(4)\n .optional(),\n imageSizes: z\n .array(z.number().int().gte(1).lte(10000))\n .min(0)\n .max(25)\n .optional(),\n loader: z.enum(VALID_LOADERS).optional(),\n loaderFile: z.string().optional(),\n maximumDiskCacheSize: z.number().int().min(0).optional(),\n maximumRedirects: z.number().int().min(0).max(20).optional(),\n maximumResponseBody: z\n .number()\n .int()\n .min(1)\n .max(Number.MAX_SAFE_INTEGER)\n .optional(),\n minimumCacheTTL: z.number().int().gte(0).optional(),\n path: z.string().optional(),\n qualities: z\n .array(z.number().int().gte(1).lte(100))\n .min(1)\n .max(20)\n .optional(),\n })\n .optional(),\n logging: z\n .union([\n z.object({\n fetches: z\n .object({\n fullUrl: z.boolean().optional(),\n hmrRefreshes: z.boolean().optional(),\n })\n .optional(),\n incomingRequests: z\n .union([\n z.boolean(),\n z.object({\n ignore: z.array(z.instanceof(RegExp)),\n }),\n ])\n .optional(),\n serverFunctions: z.boolean().optional(),\n browserToTerminal: z\n .union([z.boolean(), z.enum(['error', 'warn'])])\n .optional(),\n }),\n z.literal(false),\n ])\n .optional(),\n modularizeImports: z\n .record(\n z.string(),\n z.object({\n transform: z.union([z.string(), z.record(z.string(), z.string())]),\n preventFullImport: z.boolean().optional(),\n skipDefaultConversion: z.boolean().optional(),\n })\n )\n .optional(),\n onDemandEntries: z\n .strictObject({\n maxInactiveAge: z.number().optional(),\n pagesBufferLength: z.number().optional(),\n })\n .optional(),\n output: z.enum(['standalone', 'export']).optional(),\n outputFileTracingRoot: z.string().optional(),\n outputFileTracingExcludes: z\n .record(z.string(), z.array(z.string()))\n .optional(),\n outputFileTracingIncludes: z\n .record(z.string(), z.array(z.string()))\n .optional(),\n pageExtensions: z.array(z.string()).min(1).optional(),\n instrumentationClientInject: z.array(z.string()).optional(),\n partialPrefetching: z\n .union([z.boolean(), z.literal('unstable_eager')])\n .optional(),\n poweredByHeader: z.boolean().optional(),\n productionBrowserSourceMaps: z.boolean().optional(),\n reactCompiler: z.union([\n z.boolean(),\n z\n .object({\n compilationMode: z.enum(['infer', 'annotation', 'all']).optional(),\n panicThreshold: z\n .enum(['none', 'critical_errors', 'all_errors'])\n .optional(),\n })\n .optional(),\n ]),\n reactProductionProfiling: z.boolean().optional(),\n reactStrictMode: z.boolean().nullable().optional(),\n reactMaxHeadersLength: z.number().nonnegative().int().optional(),\n redirects: z\n .function()\n .args()\n .returns(z.promise(z.array(zRedirect)))\n .optional(),\n rewrites: z\n .function()\n .args()\n .returns(\n z.promise(\n z.union([\n z.array(zRewrite),\n z.object({\n beforeFiles: z.array(zRewrite),\n afterFiles: z.array(zRewrite),\n fallback: z.array(zRewrite),\n }),\n ])\n )\n )\n .optional(),\n // sassOptions properties are unknown besides implementation, use z.any() here\n sassOptions: z\n .object({\n implementation: z.string().optional(),\n })\n .catchall(z.any())\n .optional(),\n serverExternalPackages: z.array(z.string()).optional(),\n skipMiddlewareUrlNormalize: z.boolean().optional(),\n skipProxyUrlNormalize: z.boolean().optional(),\n skipTrailingSlashRedirect: z.boolean().optional(),\n staticPageGenerationTimeout: z.number().optional(),\n expireTime: z.number().optional(),\n target: z.string().optional(),\n trailingSlash: z.boolean().optional(),\n transpilePackages: z.array(z.string()).optional(),\n turbopack: zTurbopackConfig.optional(),\n typescript: z\n .strictObject({\n ignoreBuildErrors: z.boolean().optional(),\n tsconfigPath: z.string().min(1).optional(),\n })\n .optional(),\n typedRoutes: z.boolean().optional(),\n useFileSystemPublicRoutes: z.boolean().optional(),\n // The webpack config type is unknown, use z.any() here\n webpack: z.any().nullable().optional(),\n watchOptions: z\n .strictObject({\n pollIntervalMs: z.number().positive().finite().optional(),\n })\n .optional(),\n })\n)\n"],"names":["VALID_LOADERS","z","LIGHTNINGCSS_FEATURE_NAMES","SUPPORTED_TEST_RUNNERS_LIST","zSizeLimit","custom","val","zExportMap","record","string","object","page","query","any","_fallbackRouteParams","array","optional","_isAppDir","boolean","_isDynamicError","_isRoutePPREnabled","_allowEmptyStaticShell","_isFallbackUpgradeable","zRouteHas","union","type","enum","key","value","literal","undefined","zRewrite","source","destination","basePath","locale","has","missing","internal","zRedirect","and","statusCode","never","permanent","number","zHeader","headers","zTurbopackLoaderItem","strictObject","loader","options","zTurbopackLoaderBuiltinCondition","zTurbopackCondition","all","lazy","not","path","instanceof","RegExp","content","contentType","zTurbopackModuleType","zTurbopackRuleConfigItem","loaders","as","condition","zTurbopackRuleConfigCollection","zTurbopackConfig","rules","resolveAlias","resolveExtensions","root","debugIds","chunkLoadingGlobal","ignoreIssue","title","description","experimentalSchema","outputHashSalt","useSkewCookie","after","appNavFailHandling","appNewScrollHandler","coldCacheBadge","preloadEntriesOnStart","allowedRevalidateHeaderKeys","staleTimes","dynamic","static","gte","cacheLife","stale","revalidate","expire","cacheHandlers","clientRouterFilter","clientRouterFilterRedirects","clientRouterFilterAllowedRate","cpus","memoryBasedWorkersCount","craCompat","caseSensitiveRoutes","clientParamParsingOrigins","cachedNavigations","dynamicOnHover","useOffline","optimisticRouting","instrumentationClientRouterTransitionEvents","varyParams","prefetchInlining","maxSize","maxBundleSize","disableOptimizedLoading","disablePostcssPresetEnv","cacheComponents","inlineCss","esmExternals","serverActions","bodySizeLimit","allowedOrigins","maxPostponedStateSize","extensionAlias","externalDir","externalMiddlewareRewritesResolve","externalProxyRewritesResolve","exposeTestingApiInProductionBuild","requestInsights","fallbackNodePolyfills","fetchCacheKeyPrefix","forceSwcTransforms","fullySpecified","gzipSize","imgOptConcurrency","int","nullable","imgOptOperationCache","imgOptTimeoutInSeconds","imgOptMaxInputPixels","imgOptSequentialRead","isrFlushToDisk","largePageDataBytes","linkNoTouchStart","manualClientBasePath","middlewarePrefetch","proxyPrefetch","middlewareClientMaxBodySize","proxyClientMaxBodySize","multiZoneDraftMode","cssChunking","requestCost","nonnegative","finite","weightDistribution","nextScriptWorkers","optimizeCss","optimisticClientCache","parallelServerCompiles","parallelServerBuildTraces","ppr","readonly","taint","blockingSSR","prerenderEarlyExit","proxyTimeout","rootParams","mcpServer","removeUncaughtErrorAndRejectionListeners","validateRSCRequestHeaders","scrollRestoration","sri","algorithm","swcPlugins","tuple","swcEnvOptions","mode","coreJs","skip","include","exclude","shippedProposals","forceAllTransforms","debug","loose","swcTraceProfiling","urlImports","workerThreads","webVitalsAttribution","mdxRs","development","jsxRuntime","jsxImportSource","providerImportSource","mdxType","transitionIndicator","gestureTransition","typedRoutes","webpackBuildWorker","webpackMemoryOptimizations","turbopackMemoryEviction","turbopackPluginRuntimeStrategy","turbopackMinify","turbopackFileSystemCacheForDev","turbopackFileSystemCacheForBuild","turbopackSourceMaps","turbopackInputSourceMaps","turbopackModuleFragments","turbopackRemoveUnusedImports","turbopackRemoveUnusedExports","turbopackScopeHoisting","turbopackGenerateComponentChunks","turbopackSharedRuntime","turbopackChunkingHeuristics","firstPageLoadPriority","min","max","priorityRoutes","priorityBoost","turbopackWorkerAssetPrefix","turbopackClientSideNestedAsyncChunking","turbopackServerSideNestedAsyncChunking","turbopackImportTypeBytes","turbopackUseBuiltinBabel","turbopackUseBuiltinSass","turbopackLocalPostcssConfig","turbopackModuleIds","turbopackInferModuleSideEffects","turbopackCjsTreeShaking","turbopackServerFastRefresh","optimizePackageImports","optimizeServerReact","strictRouteTypes","useTypeScriptCli","clientTraceMetadata","serverMinification","serverSourceMaps","useWasmBinary","useLightningcss","lightningCssFeatures","testProxy","defaultTestRunner","allowDevelopmentBuild","reactDebugChannel","instantInsights","validationLevel","staticGenerationRetryCount","staticGenerationMaxConcurrency","staticGenerationMinPagesPerWorker","typedEnv","serverComponentsHmrCache","serverComponentsHmrCancellation","authInterrupts","useCache","durableUseCacheEntries","useCacheTimeout","positive","slowModuleDetection","buildTimeThresholdMs","globalNotFound","turbopackRustReactCompiler","browserDebugInfoInTerminal","level","depthLimit","edgeLimit","showSourceLocation","lockDistDir","hideLogsAfterAbort","runtimeServerDeploymentId","supportsImmutableAssets","deferredEntries","onBeforeDeferredEntries","function","returns","promise","void","reportSystemEnvInlining","configSchema","adapterPath","agentRules","allowedDevOrigins","assetPrefix","bundlePagesRouterDependencies","cacheHandler","cacheMaxMemorySize","cleanDistDir","compiler","emotion","sourceMap","autoLabel","labelFormat","importMap","canonicalImport","styledBaseImport","reactRemoveProperties","properties","relay","src","artifactDirectory","language","eagerEsModules","removeConsole","styledComponents","displayName","topLevelImportPaths","ssr","fileName","meaninglessFileNames","minify","transpileTemplateLiterals","namespace","pure","cssProp","styledJsx","define","defineServer","runAfterProductionCompile","compress","configOrigin","crossOrigin","deploymentId","devIndicators","position","distDir","env","enablePrerenderSourceMaps","excludeDefaultMomentLocales","experimental","exportPathMap","args","dev","dir","outDir","buildId","generateBuildId","null","generateEtags","htmlLimitedBots","httpAgentOptions","keepAlive","i18n","defaultLocale","domains","domain","http","locales","localeDetection","images","localPatterns","pathname","search","remotePatterns","URL","hostname","port","protocol","unoptimized","customCacheHandler","contentSecurityPolicy","contentDispositionType","dangerouslyAllowSVG","dangerouslyAllowLocalIP","deviceSizes","lte","disableStaticImages","formats","imageSizes","loaderFile","maximumDiskCacheSize","maximumRedirects","maximumResponseBody","Number","MAX_SAFE_INTEGER","minimumCacheTTL","qualities","logging","fetches","fullUrl","hmrRefreshes","incomingRequests","ignore","serverFunctions","browserToTerminal","modularizeImports","transform","preventFullImport","skipDefaultConversion","onDemandEntries","maxInactiveAge","pagesBufferLength","output","outputFileTracingRoot","outputFileTracingExcludes","outputFileTracingIncludes","pageExtensions","instrumentationClientInject","partialPrefetching","poweredByHeader","productionBrowserSourceMaps","reactCompiler","compilationMode","panicThreshold","reactProductionProfiling","reactStrictMode","reactMaxHeadersLength","redirects","rewrites","beforeFiles","afterFiles","fallback","sassOptions","implementation","catchall","serverExternalPackages","skipMiddlewareUrlNormalize","skipProxyUrlNormalize","skipTrailingSlashRedirect","staticPageGenerationTimeout","expireTime","target","trailingSlash","transpilePackages","turbopack","typescript","ignoreBuildErrors","tsconfigPath","useFileSystemPublicRoutes","webpack","watchOptions","pollIntervalMs"],"mappings":"AACA,SAASA,aAAa,QAAQ,6BAA4B;AAE1D,SAASC,CAAC,QAAQ,yBAAwB;AAI1C,SACEC,0BAA0B,QAQrB,kBAAiB;AAOxB,SAASC,2BAA2B,QAAQ,mBAAkB;AAE9D,6CAA6C;AAC7C,MAAMC,aAAaH,EAAEI,MAAM,CAAY,CAACC;IACtC,IAAI,OAAOA,QAAQ,YAAY,OAAOA,QAAQ,UAAU;QACtD,OAAO;IACT;IACA,OAAO;AACT;AAEA,MAAMC,aAAyCN,EAAEO,MAAM,CACrDP,EAAEQ,MAAM,IACRR,EAAES,MAAM,CAAC;IACPC,MAAMV,EAAEQ,MAAM;IACdG,OAAOX,EAAEY,GAAG;IAEZ,8BAA8B;IAC9BC,sBAAsBb,EAAEc,KAAK,CAACd,EAAEY,GAAG,IAAIG,QAAQ;IAC/CC,WAAWhB,EAAEiB,OAAO,GAAGF,QAAQ;IAC/BG,iBAAiBlB,EAAEiB,OAAO,GAAGF,QAAQ;IACrCI,oBAAoBnB,EAAEiB,OAAO,GAAGF,QAAQ;IACxCK,wBAAwBpB,EAAEiB,OAAO,GAAGF,Q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,GACC0Y,QAAQ,CAACzZ,EAAEY,GAAG,IACdG,QAAQ;QACX2Y,wBAAwB1Z,EAAEc,KAAK,CAACd,EAAEQ,MAAM,IAAIO,QAAQ;QACpD4Y,4BAA4B3Z,EAAEiB,OAAO,GAAGF,QAAQ;QAChD6Y,uBAAuB5Z,EAAEiB,OAAO,GAAGF,QAAQ;QAC3C8Y,2BAA2B7Z,EAAEiB,OAAO,GAAGF,QAAQ;QAC/C+Y,6BAA6B9Z,EAAE2C,MAAM,GAAG5B,QAAQ;QAChDgZ,YAAY/Z,EAAE2C,MAAM,GAAG5B,QAAQ;QAC/BiZ,QAAQha,EAAEQ,MAAM,GAAGO,QAAQ;QAC3BkZ,eAAeja,EAAEiB,OAAO,GAAGF,QAAQ;QACnCmZ,mBAAmBla,EAAEc,KAAK,CAACd,EAAEQ,MAAM,IAAIO,QAAQ;QAC/CoZ,WAAWjW,iBAAiBnD,QAAQ;QACpCqZ,YAAYpa,EACT+C,YAAY,CAAC;YACZsX,mBAAmBra,EAAEiB,OAAO,GAAGF,QAAQ;YACvCuZ,cAActa,EAAEQ,MAAM,GAAG4M,GAAG,CAAC,GAAGrM,QAAQ;QAC1C,GACCA,QAAQ;QACXmL,aAAalM,EAAEiB,OAAO,GAAGF,QAAQ;QACjCwZ,2BAA2Bva,EAAEiB,OAAO,GAAGF,QAAQ;QAC/C,uDAAuD;QACvDyZ,SAASxa,EAAEY,GAAG,GAAGyH,QAAQ,GAAGtH,QAAQ;QACpC0Z,cAAcza,EACX+C,YAAY,CAAC;YACZ2X,gBAAgB1a,EAAE2C,MAAM,GAAGkN,QAAQ,GAAGvG,MAAM,GAAGvI,QAAQ;QACzD,GACCA,QAAQ;IACb,IACD","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/config-schema.ts"],"sourcesContent":["import type { NextConfig } from './config'\nimport { VALID_LOADERS } from '../shared/lib/image-config'\n\nimport { z } from 'next/dist/compiled/zod'\nimport type zod from 'next/dist/compiled/zod'\n\nimport type { SizeLimit } from '../types'\nimport {\n LIGHTNINGCSS_FEATURE_NAMES,\n type ExportPathMap,\n type TurbopackLoaderItem,\n type TurbopackOptions,\n type TurbopackRuleConfigItem,\n type TurbopackRuleConfigCollection,\n type TurbopackRuleCondition,\n type TurbopackLoaderBuiltinCondition,\n} from './config-shared'\nimport type {\n Header,\n Rewrite,\n RouteHas,\n Redirect,\n} from '../lib/load-custom-routes'\nimport { SUPPORTED_TEST_RUNNERS_LIST } from '../cli/next-test'\n\n// A custom zod schema for the SizeLimit type\nconst zSizeLimit = z.custom<SizeLimit>((val) => {\n if (typeof val === 'number' || typeof val === 'string') {\n return true\n }\n return false\n})\n\nconst zExportMap: zod.ZodType<ExportPathMap> = z.record(\n z.string(),\n z.object({\n page: z.string(),\n query: z.any(), // NextParsedUrlQuery\n\n // private optional properties\n _fallbackRouteParams: z.array(z.any()).optional(),\n _isAppDir: z.boolean().optional(),\n _isDynamicError: z.boolean().optional(),\n _isRoutePPREnabled: z.boolean().optional(),\n _allowEmptyStaticShell: z.boolean().optional(),\n _isFallbackUpgradeable: z.boolean().optional(),\n })\n)\n\nconst zRouteHas: zod.ZodType<RouteHas> = z.union([\n z.object({\n type: z.enum(['header', 'query', 'cookie']),\n key: z.string(),\n value: z.string().optional(),\n }),\n z.object({\n type: z.literal('host'),\n key: z.undefined().optional(),\n value: z.string(),\n }),\n])\n\nconst zRewrite: zod.ZodType<Rewrite> = z.object({\n source: z.string(),\n destination: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n internal: z.boolean().optional(),\n})\n\nconst zRedirect: zod.ZodType<Redirect> = z\n .object({\n source: z.string(),\n destination: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n internal: z.boolean().optional(),\n })\n .and(\n z.union([\n z.object({\n statusCode: z.never().optional(),\n permanent: z.boolean(),\n }),\n z.object({\n statusCode: z.number(),\n permanent: z.never().optional(),\n }),\n ])\n )\n\nconst zHeader: zod.ZodType<Header> = z.object({\n source: z.string(),\n basePath: z.literal(false).optional(),\n locale: z.literal(false).optional(),\n headers: z.array(z.object({ key: z.string(), value: z.string() })),\n has: z.array(zRouteHas).optional(),\n missing: z.array(zRouteHas).optional(),\n\n internal: z.boolean().optional(),\n})\n\nconst zTurbopackLoaderItem: zod.ZodType<TurbopackLoaderItem> = z.union([\n z.string(),\n z.strictObject({\n loader: z.string(),\n // Any JSON value can be used as turbo loader options, so use z.any() here\n options: z.record(z.string(), z.any()).optional(),\n }),\n])\n\nconst zTurbopackLoaderBuiltinCondition: zod.ZodType<TurbopackLoaderBuiltinCondition> =\n z.union([\n z.literal('browser'),\n z.literal('foreign'),\n z.literal('development'),\n z.literal('production'),\n z.literal('node'),\n z.literal('edge-light'),\n ])\n\nconst zTurbopackCondition: zod.ZodType<TurbopackRuleCondition> = z.union([\n z.strictObject({ all: z.lazy(() => z.array(zTurbopackCondition)) }),\n z.strictObject({ any: z.lazy(() => z.array(zTurbopackCondition)) }),\n z.strictObject({ not: z.lazy(() => zTurbopackCondition) }),\n zTurbopackLoaderBuiltinCondition,\n z.strictObject({\n path: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n content: z.instanceof(RegExp).optional(),\n query: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n contentType: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n }),\n])\n\nconst zTurbopackModuleType = z.enum([\n 'asset',\n 'ecmascript',\n 'typescript',\n 'css',\n 'css-module',\n 'wasm',\n 'raw',\n 'node',\n 'bytes',\n])\n\nconst zTurbopackRuleConfigItem: zod.ZodType<TurbopackRuleConfigItem> =\n z.strictObject({\n loaders: z.array(zTurbopackLoaderItem).optional(),\n as: z.string().optional(),\n condition: zTurbopackCondition.optional(),\n type: zTurbopackModuleType.optional(),\n })\n\nconst zTurbopackRuleConfigCollection: zod.ZodType<TurbopackRuleConfigCollection> =\n z.union([\n zTurbopackRuleConfigItem,\n z.array(z.union([zTurbopackLoaderItem, zTurbopackRuleConfigItem])),\n ])\n\nconst zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({\n rules: z.record(z.string(), zTurbopackRuleConfigCollection).optional(),\n resolveAlias: z\n .record(\n z.string(),\n z.union([\n z.string(),\n z.array(z.string()),\n z.record(z.string(), z.union([z.string(), z.array(z.string())])),\n ])\n )\n .optional(),\n resolveExtensions: z.array(z.string()).optional(),\n root: z.string().optional(),\n debugIds: z.boolean().optional(),\n chunkLoadingGlobal: z.string().optional(),\n ignoreIssue: z\n .array(\n z.object({\n path: z.union([z.string(), z.instanceof(RegExp)]),\n title: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n description: z.union([z.string(), z.instanceof(RegExp)]).optional(),\n })\n )\n .optional(),\n})\n\nexport const experimentalSchema = {\n outputHashSalt: z.string().optional(),\n useSkewCookie: z.boolean().optional(),\n after: z.boolean().optional(),\n appNavFailHandling: z.boolean().optional(),\n appNewScrollHandler: z.boolean().optional(),\n coldCacheBadge: z.boolean().optional(),\n preloadEntriesOnStart: z.boolean().optional(),\n allowedRevalidateHeaderKeys: z.array(z.string()).optional(),\n staleTimes: z\n .object({\n dynamic: z.number().optional(),\n static: z.number().gte(30).optional(),\n })\n .optional(),\n cacheLife: z\n .record(\n z.object({\n stale: z.number().optional(),\n revalidate: z.number().optional(),\n expire: z.number().optional(),\n })\n )\n .optional(),\n cacheHandlers: z.record(z.string(), z.string().optional()).optional(),\n clientRouterFilter: z.boolean().optional(),\n clientRouterFilterRedirects: z.boolean().optional(),\n clientRouterFilterAllowedRate: z.number().optional(),\n cpus: z.number().optional(),\n memoryBasedWorkersCount: z.boolean().optional(),\n craCompat: z.boolean().optional(),\n caseSensitiveRoutes: z.boolean().optional(),\n clientParamParsingOrigins: z.array(z.string()).optional(),\n cachedNavigations: z\n .union([z.boolean(), z.literal('allow-runtime')])\n .optional(),\n dynamicOnHover: z.boolean().optional(),\n useOffline: z.boolean().optional(),\n optimisticRouting: z.boolean().optional(),\n instrumentationClientRouterTransitionEvents: z.boolean().optional(),\n varyParams: z.boolean().optional(),\n prefetchInlining: z\n .union([\n z.boolean(),\n z.object({\n maxSize: z.number().optional(),\n maxBundleSize: z.number().optional(),\n }),\n ])\n .optional(),\n disableOptimizedLoading: z.boolean().optional(),\n disablePostcssPresetEnv: z.boolean().optional(),\n cacheComponents: z.boolean().optional(),\n inlineCss: z.boolean().optional(),\n esmExternals: z.union([z.boolean(), z.literal('loose')]).optional(),\n serverActions: z\n .object({\n bodySizeLimit: zSizeLimit.optional(),\n allowedOrigins: z.array(z.string()).optional(),\n })\n .optional(),\n maxPostponedStateSize: zSizeLimit.optional(),\n // The original type was Record<string, any>\n extensionAlias: z.record(z.string(), z.any()).optional(),\n externalDir: z.boolean().optional(),\n externalMiddlewareRewritesResolve: z.boolean().optional(),\n externalProxyRewritesResolve: z.boolean().optional(),\n exposeTestingApiInProductionBuild: z.boolean().optional(),\n requestInsights: z.boolean().optional(),\n fallbackNodePolyfills: z.literal(false).optional(),\n fetchCacheKeyPrefix: z.string().optional(),\n forceSwcTransforms: z.boolean().optional(),\n fullySpecified: z.boolean().optional(),\n gzipSize: z.boolean().optional(),\n imgOptConcurrency: z.number().int().optional().nullable(),\n imgOptOperationCache: z.boolean().optional().nullable(),\n imgOptTimeoutInSeconds: z.number().int().optional(),\n imgOptMaxInputPixels: z.number().int().optional(),\n imgOptSequentialRead: z.boolean().optional().nullable(),\n isrFlushToDisk: z.boolean().optional(),\n largePageDataBytes: z.number().optional(),\n linkNoTouchStart: z.boolean().optional(),\n manualClientBasePath: z.boolean().optional(),\n middlewarePrefetch: z.enum(['strict', 'flexible']).optional(),\n proxyPrefetch: z.enum(['strict', 'flexible']).optional(),\n middlewareClientMaxBodySize: zSizeLimit.optional(),\n proxyClientMaxBodySize: zSizeLimit.optional(),\n multiZoneDraftMode: z.boolean().optional(),\n cssChunking: z\n .union([\n z.boolean(),\n z.literal('strict'),\n z.literal('loose'),\n z.literal('graph'),\n z.strictObject({ type: z.literal('strict') }),\n z.strictObject({ type: z.literal('loose') }),\n z.strictObject({\n type: z.literal('graph'),\n requestCost: z.number().nonnegative().finite().optional(),\n weightDistribution: z.number().nonnegative().finite().optional(),\n }),\n ])\n .optional(),\n nextScriptWorkers: z.boolean().optional(),\n // The critter option is unknown, use z.any() here\n optimizeCss: z.union([z.boolean(), z.any()]).optional(),\n optimisticClientCache: z.boolean().optional(),\n parallelServerCompiles: z.boolean().optional(),\n parallelServerBuildTraces: z.boolean().optional(),\n ppr: z\n .union([z.boolean(), z.literal('incremental')])\n .readonly()\n .optional(),\n taint: z.boolean().optional(),\n blockingSSR: z.boolean().optional(),\n prerenderEarlyExit: z.boolean().optional(),\n proxyTimeout: z.number().gte(0).optional(),\n rootParams: z.boolean().optional(),\n mcpServer: z.boolean().optional(),\n removeUncaughtErrorAndRejectionListeners: z.boolean().optional(),\n validateRSCRequestHeaders: z.boolean().optional(),\n scrollRestoration: z.boolean().optional(),\n sri: z\n .object({\n algorithm: z.enum(['sha256', 'sha384', 'sha512']).optional(),\n })\n .optional(),\n swcPlugins: z\n // The specific swc plugin's option is unknown, use z.any() here\n .array(z.tuple([z.string(), z.record(z.string(), z.any())]))\n .optional(),\n swcEnvOptions: z\n .object({\n mode: z.enum(['usage', 'entry']).optional(),\n coreJs: z.string().optional(),\n skip: z.array(z.string()).optional(),\n include: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n shippedProposals: z.boolean().optional(),\n forceAllTransforms: z.boolean().optional(),\n debug: z.boolean().optional(),\n loose: z.boolean().optional(),\n })\n .optional(),\n swcTraceProfiling: z.boolean().optional(),\n // NonNullable<webpack.Configuration['experiments']>['buildHttp']\n urlImports: z.any().optional(),\n workerThreads: z.boolean().optional(),\n webVitalsAttribution: z\n .array(\n z.union([\n z.literal('CLS'),\n z.literal('FCP'),\n z.literal('FID'),\n z.literal('INP'),\n z.literal('LCP'),\n z.literal('TTFB'),\n ])\n )\n .optional(),\n // This is partial set of mdx-rs transform options we support, aligned\n // with next_core::next_config::MdxRsOptions. Ensure both types are kept in sync.\n mdxRs: z\n .union([\n z.boolean(),\n z.object({\n development: z.boolean().optional(),\n jsxRuntime: z.string().optional(),\n jsxImportSource: z.string().optional(),\n providerImportSource: z.string().optional(),\n mdxType: z.enum(['gfm', 'commonmark']).optional(),\n }),\n ])\n .optional(),\n transitionIndicator: z.boolean().optional(),\n gestureTransition: z.boolean().optional(),\n typedRoutes: z.boolean().optional(),\n webpackBuildWorker: z.boolean().optional(),\n webpackMemoryOptimizations: z.boolean().optional(),\n turbopackMemoryEviction: z\n .union([z.literal(false), z.literal('full'), z.literal('auto')])\n .optional(),\n turbopackPluginRuntimeStrategy: z\n .enum(['workerThreads', 'childProcesses'])\n .optional(),\n turbopackMinify: z.boolean().optional(),\n turbopackFileSystemCacheForDev: z.boolean().optional(),\n turbopackFileSystemCacheForBuild: z.boolean().optional(),\n turbopackSourceMaps: z.boolean().optional(),\n turbopackInputSourceMaps: z.boolean().optional(),\n turbopackModuleFragments: z.boolean().optional(),\n turbopackRemoveUnusedImports: z.boolean().optional(),\n turbopackRemoveUnusedExports: z.boolean().optional(),\n turbopackScopeHoisting: z.boolean().optional(),\n turbopackGenerateComponentChunks: z.boolean().optional(),\n turbopackSharedRuntime: z.boolean().optional(),\n turbopackChunkingHeuristics: z\n .object({\n firstPageLoadPriority: z.number().min(0).max(1).optional(),\n priorityRoutes: z.array(z.instanceof(RegExp)).optional(),\n priorityBoost: z.number().min(1).optional(),\n requestCost: z.number().min(0).max(1_000_000).optional(),\n })\n .optional(),\n turbopackWorkerAssetPrefix: z.string().optional(),\n turbopackClientSideNestedAsyncChunking: z.boolean().optional(),\n turbopackServerSideNestedAsyncChunking: z.boolean().optional(),\n turbopackImportTypeBytes: z.boolean().optional(),\n turbopackUseBuiltinBabel: z.boolean().optional(),\n turbopackUseBuiltinSass: z.boolean().optional(),\n turbopackLocalPostcssConfig: z.boolean().optional(),\n turbopackModuleIds: z.enum(['named', 'deterministic']).optional(),\n turbopackInferModuleSideEffects: z.boolean().optional(),\n turbopackCjsTreeShaking: z.boolean().optional(),\n turbopackServerFastRefresh: z.boolean().optional(),\n optimizePackageImports: z.array(z.string()).optional(),\n optimizeServerReact: z.boolean().optional(),\n strictRouteTypes: z.boolean().optional(),\n useTypeScriptCli: z.boolean().optional(),\n clientTraceMetadata: z.array(z.string()).optional(),\n serverMinification: z.boolean().optional(),\n serverSourceMaps: z.boolean().optional(),\n useWasmBinary: z.boolean().optional(),\n useLightningcss: z.boolean().optional(),\n lightningCssFeatures: z\n .object({\n include: z.array(z.enum(LIGHTNINGCSS_FEATURE_NAMES)).optional(),\n exclude: z.array(z.enum(LIGHTNINGCSS_FEATURE_NAMES)).optional(),\n })\n .optional(),\n testProxy: z.boolean().optional(),\n defaultTestRunner: z.enum(SUPPORTED_TEST_RUNNERS_LIST).optional(),\n allowDevelopmentBuild: z.literal(true).optional(),\n\n reactDebugChannel: z.boolean().optional(),\n instantInsights: z\n .object({\n validationLevel: z\n .enum([\n 'warning',\n 'manual-warning',\n 'experimental-error',\n 'experimental-manual-error',\n ])\n .optional(),\n })\n .optional(),\n devValidationWorker: z.boolean().optional(),\n staticGenerationRetryCount: z.number().int().optional(),\n staticGenerationMaxConcurrency: z.number().int().optional(),\n staticGenerationMinPagesPerWorker: z.number().int().optional(),\n typedEnv: z.boolean().optional(),\n serverComponentsHmrCache: z.boolean().optional(),\n serverComponentsHmrCancellation: z.boolean().optional(),\n authInterrupts: z.boolean().optional(),\n useCache: z.boolean().optional(),\n durableUseCacheEntries: z.boolean().optional(),\n useCacheTimeout: z.number().positive().optional(),\n slowModuleDetection: z\n .object({\n buildTimeThresholdMs: z.number().int(),\n })\n .optional(),\n globalNotFound: z.boolean().optional(),\n turbopackRustReactCompiler: z.boolean().optional(),\n browserDebugInfoInTerminal: z\n .union([\n z.boolean(),\n z.enum(['error', 'warn', 'verbose']),\n z.object({\n level: z.enum(['error', 'warn', 'verbose']).optional(),\n depthLimit: z.number().int().positive().optional(),\n edgeLimit: z.number().int().positive().optional(),\n showSourceLocation: z.boolean().optional(),\n }),\n ])\n .optional(),\n lockDistDir: z.boolean().optional(),\n hideLogsAfterAbort: z.boolean().optional(),\n runtimeServerDeploymentId: z.boolean().optional(),\n supportsImmutableAssets: z.boolean().optional(),\n deferredEntries: z.array(z.string()).optional(),\n onBeforeDeferredEntries: z.function().returns(z.promise(z.void())).optional(),\n reportSystemEnvInlining: z.enum(['warn', 'error']).optional(),\n}\n\nexport const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>\n z.strictObject({\n adapterPath: z.string().optional(),\n agentRules: z.boolean().optional(),\n allowedDevOrigins: z.array(z.string()).optional(),\n assetPrefix: z.string().optional(),\n basePath: z.string().optional(),\n bundlePagesRouterDependencies: z.boolean().optional(),\n cacheComponents: z.boolean().optional(),\n cacheHandler: z.string().min(1).optional(),\n cacheHandlers: z.record(z.string(), z.string().optional()).optional(),\n cacheLife: z\n .record(\n z.object({\n stale: z.number().optional(),\n revalidate: z.number().optional(),\n expire: z.number().optional(),\n })\n )\n .optional(),\n cacheMaxMemorySize: z.number().optional(),\n cleanDistDir: z.boolean().optional(),\n compiler: z\n .strictObject({\n emotion: z\n .union([\n z.boolean(),\n z.object({\n sourceMap: z.boolean().optional(),\n autoLabel: z\n .union([\n z.literal('always'),\n z.literal('dev-only'),\n z.literal('never'),\n ])\n .optional(),\n labelFormat: z.string().min(1).optional(),\n importMap: z\n .record(\n z.string(),\n z.record(\n z.string(),\n z.object({\n canonicalImport: z\n .tuple([z.string(), z.string()])\n .optional(),\n styledBaseImport: z\n .tuple([z.string(), z.string()])\n .optional(),\n })\n )\n )\n .optional(),\n }),\n ])\n .optional(),\n reactRemoveProperties: z\n .union([\n z.boolean().optional(),\n z.object({\n properties: z.array(z.string()).optional(),\n }),\n ])\n .optional(),\n relay: z\n .object({\n src: z.string(),\n artifactDirectory: z.string().optional(),\n language: z.enum(['javascript', 'typescript', 'flow']).optional(),\n eagerEsModules: z.boolean().optional(),\n })\n .optional(),\n removeConsole: z\n .union([\n z.boolean().optional(),\n z.object({\n exclude: z.array(z.string()).min(1).optional(),\n }),\n ])\n .optional(),\n styledComponents: z.union([\n z.boolean().optional(),\n z.object({\n displayName: z.boolean().optional(),\n topLevelImportPaths: z.array(z.string()).optional(),\n ssr: z.boolean().optional(),\n fileName: z.boolean().optional(),\n meaninglessFileNames: z.array(z.string()).optional(),\n minify: z.boolean().optional(),\n transpileTemplateLiterals: z.boolean().optional(),\n namespace: z.string().min(1).optional(),\n pure: z.boolean().optional(),\n cssProp: z.boolean().optional(),\n }),\n ]),\n styledJsx: z.union([\n z.boolean().optional(),\n z.object({\n useLightningcss: z.boolean().optional(),\n }),\n ]),\n define: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional(),\n defineServer: z\n .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))\n .optional(),\n runAfterProductionCompile: z\n .function()\n .returns(z.promise(z.void()))\n .optional(),\n })\n .optional(),\n compress: z.boolean().optional(),\n configOrigin: z.string().optional(),\n crossOrigin: z\n .union([z.literal('anonymous'), z.literal('use-credentials')])\n .optional(),\n deploymentId: z.string().optional(),\n supportsImmutableAssets: z.boolean().optional(),\n outputHashSalt: z.string().optional(),\n devIndicators: z\n .union([\n z.object({\n position: z\n .union([\n z.literal('bottom-left'),\n z.literal('bottom-right'),\n z.literal('top-left'),\n z.literal('top-right'),\n ])\n .optional(),\n }),\n z.literal(false),\n ])\n .optional(),\n distDir: z.string().min(1).optional(),\n env: z.record(z.string(), z.union([z.string(), z.undefined()])).optional(),\n enablePrerenderSourceMaps: z.boolean().optional(),\n excludeDefaultMomentLocales: z.boolean().optional(),\n experimental: z.strictObject(experimentalSchema).optional(),\n exportPathMap: z\n .function()\n .args(\n zExportMap,\n z.object({\n dev: z.boolean(),\n dir: z.string(),\n outDir: z.string().nullable(),\n distDir: z.string(),\n buildId: z.string(),\n })\n )\n .returns(z.union([zExportMap, z.promise(zExportMap)]))\n .optional(),\n generateBuildId: z\n .function()\n .args()\n .returns(\n z.union([\n z.string(),\n z.null(),\n z.promise(z.union([z.string(), z.null()])),\n ])\n )\n .optional(),\n generateEtags: z.boolean().optional(),\n headers: z\n .function()\n .args()\n .returns(z.promise(z.array(zHeader)))\n .optional(),\n htmlLimitedBots: z.instanceof(RegExp).optional(),\n httpAgentOptions: z\n .strictObject({ keepAlive: z.boolean().optional() })\n .optional(),\n i18n: z\n .strictObject({\n defaultLocale: z.string().min(1),\n domains: z\n .array(\n z.strictObject({\n defaultLocale: z.string().min(1),\n domain: z.string().min(1),\n http: z.literal(true).optional(),\n locales: z.array(z.string().min(1)).optional(),\n })\n )\n .optional(),\n localeDetection: z.literal(false).optional(),\n locales: z.array(z.string().min(1)),\n })\n .nullable()\n .optional(),\n images: z\n .strictObject({\n localPatterns: z\n .array(\n z.strictObject({\n pathname: z.string().optional(),\n search: z.string().optional(),\n })\n )\n .max(25)\n .optional(),\n remotePatterns: z\n .array(\n z.union([\n z.instanceof(URL),\n z.strictObject({\n hostname: z.string(),\n pathname: z.string().optional(),\n port: z.string().max(5).optional(),\n protocol: z.enum(['http', 'https']).optional(),\n search: z.string().optional(),\n }),\n ])\n )\n .max(50)\n .optional(),\n unoptimized: z.boolean().optional(),\n customCacheHandler: z.boolean().optional(),\n contentSecurityPolicy: z.string().optional(),\n contentDispositionType: z.enum(['inline', 'attachment']).optional(),\n dangerouslyAllowSVG: z.boolean().optional(),\n dangerouslyAllowLocalIP: z.boolean().optional(),\n deviceSizes: z\n .array(z.number().int().gte(1).lte(10000))\n .max(25)\n .optional(),\n disableStaticImages: z.boolean().optional(),\n domains: z.array(z.string()).max(50).optional(),\n formats: z\n .array(z.enum(['image/avif', 'image/webp']))\n .max(4)\n .optional(),\n imageSizes: z\n .array(z.number().int().gte(1).lte(10000))\n .min(0)\n .max(25)\n .optional(),\n loader: z.enum(VALID_LOADERS).optional(),\n loaderFile: z.string().optional(),\n maximumDiskCacheSize: z.number().int().min(0).optional(),\n maximumRedirects: z.number().int().min(0).max(20).optional(),\n maximumResponseBody: z\n .number()\n .int()\n .min(1)\n .max(Number.MAX_SAFE_INTEGER)\n .optional(),\n minimumCacheTTL: z.number().int().gte(0).optional(),\n path: z.string().optional(),\n qualities: z\n .array(z.number().int().gte(1).lte(100))\n .min(1)\n .max(20)\n .optional(),\n })\n .optional(),\n logging: z\n .union([\n z.object({\n fetches: z\n .object({\n fullUrl: z.boolean().optional(),\n hmrRefreshes: z.boolean().optional(),\n })\n .optional(),\n incomingRequests: z\n .union([\n z.boolean(),\n z.object({\n ignore: z.array(z.instanceof(RegExp)),\n }),\n ])\n .optional(),\n serverFunctions: z.boolean().optional(),\n browserToTerminal: z\n .union([z.boolean(), z.enum(['error', 'warn'])])\n .optional(),\n }),\n z.literal(false),\n ])\n .optional(),\n modularizeImports: z\n .record(\n z.string(),\n z.object({\n transform: z.union([z.string(), z.record(z.string(), z.string())]),\n preventFullImport: z.boolean().optional(),\n skipDefaultConversion: z.boolean().optional(),\n })\n )\n .optional(),\n onDemandEntries: z\n .strictObject({\n maxInactiveAge: z.number().optional(),\n pagesBufferLength: z.number().optional(),\n })\n .optional(),\n output: z.enum(['standalone', 'export']).optional(),\n outputFileTracingRoot: z.string().optional(),\n outputFileTracingExcludes: z\n .record(z.string(), z.array(z.string()))\n .optional(),\n outputFileTracingIncludes: z\n .record(z.string(), z.array(z.string()))\n .optional(),\n pageExtensions: z.array(z.string()).min(1).optional(),\n instrumentationClientInject: z.array(z.string()).optional(),\n partialPrefetching: z\n .union([z.boolean(), z.literal('unstable_eager')])\n .optional(),\n poweredByHeader: z.boolean().optional(),\n productionBrowserSourceMaps: z.boolean().optional(),\n reactCompiler: z.union([\n z.boolean(),\n z\n .object({\n compilationMode: z.enum(['infer', 'annotation', 'all']).optional(),\n panicThreshold: z\n .enum(['none', 'critical_errors', 'all_errors'])\n .optional(),\n })\n .optional(),\n ]),\n reactProductionProfiling: z.boolean().optional(),\n reactStrictMode: z.boolean().nullable().optional(),\n reactMaxHeadersLength: z.number().nonnegative().int().optional(),\n redirects: z\n .function()\n .args()\n .returns(z.promise(z.array(zRedirect)))\n .optional(),\n rewrites: z\n .function()\n .args()\n .returns(\n z.promise(\n z.union([\n z.array(zRewrite),\n z.object({\n beforeFiles: z.array(zRewrite),\n afterFiles: z.array(zRewrite),\n fallback: z.array(zRewrite),\n }),\n ])\n )\n )\n .optional(),\n // sassOptions properties are unknown besides implementation, use z.any() here\n sassOptions: z\n .object({\n implementation: z.string().optional(),\n })\n .catchall(z.any())\n .optional(),\n serverExternalPackages: z.array(z.string()).optional(),\n skipMiddlewareUrlNormalize: z.boolean().optional(),\n skipProxyUrlNormalize: z.boolean().optional(),\n skipTrailingSlashRedirect: z.boolean().optional(),\n staticPageGenerationTimeout: z.number().optional(),\n expireTime: z.number().optional(),\n target: z.string().optional(),\n trailingSlash: z.boolean().optional(),\n transpilePackages: z.array(z.string()).optional(),\n turbopack: zTurbopackConfig.optional(),\n typescript: z\n .strictObject({\n ignoreBuildErrors: z.boolean().optional(),\n tsconfigPath: z.string().min(1).optional(),\n })\n .optional(),\n typedRoutes: z.boolean().optional(),\n useFileSystemPublicRoutes: z.boolean().optional(),\n // The webpack config type is unknown, use z.any() here\n webpack: z.any().nullable().optional(),\n watchOptions: z\n .strictObject({\n pollIntervalMs: z.number().positive().finite().optional(),\n })\n .optional(),\n })\n)\n"],"names":["VALID_LOADERS","z","LIGHTNINGCSS_FEATURE_NAMES","SUPPORTED_TEST_RUNNERS_LIST","zSizeLimit","custom","val","zExportMap","record","string","object","page","query","any","_fallbackRouteParams","array","optional","_isAppDir","boolean","_isDynamicError","_isRoutePPREnabled","_allowEmptyStaticShell","_isFallbackUpgradeable","zRouteHas","union","type","enum","key","value","literal","undefined","zRewrite","source","destination","basePath","locale","has","missing","internal","zRedirect","and","statusCode","never","permanent","number","zHeader","headers","zTurbopackLoaderItem","strictObject","loader","options","zTurbopackLoaderBuiltinCondition","zTurbopackCondition","all","lazy","not","path","instanceof","RegExp","content","contentType","zTurbopackModuleType","zTurbopackRuleConfigItem","loaders","as","condition","zTurbopackRuleConfigCollection","zTurbopackConfig","rules","resolveAlias","resolveExtensions","root","debugIds","chunkLoadingGlobal","ignoreIssue","title","description","experimentalSchema","outputHashSalt","useSkewCookie","after","appNavFailHandling","appNewScrollHandler","coldCacheBadge","preloadEntriesOnStart","allowedRevalidateHeaderKeys","staleTimes","dynamic","static","gte","cacheLife","stale","revalidate","expire","cacheHandlers","clientRouterFilter","clientRouterFilterRedirects","clientRouterFilterAllowedRate","cpus","memoryBasedWorkersCount","craCompat","caseSensitiveRoutes","clientParamParsingOrigins","cachedNavigations","dynamicOnHover","useOffline","optimisticRouting","instrumentationClientRouterTransitionEvents","varyParams","prefetchInlining","maxSize","maxBundleSize","disableOptimizedLoading","disablePostcssPresetEnv","cacheComponents","inlineCss","esmExternals","serverActions","bodySizeLimit","allowedOrigins","maxPostponedStateSize","extensionAlias","externalDir","externalMiddlewareRewritesResolve","externalProxyRewritesResolve","exposeTestingApiInProductionBuild","requestInsights","fallbackNodePolyfills","fetchCacheKeyPrefix","forceSwcTransforms","fullySpecified","gzipSize","imgOptConcurrency","int","nullable","imgOptOperationCache","imgOptTimeoutInSeconds","imgOptMaxInputPixels","imgOptSequentialRead","isrFlushToDisk","largePageDataBytes","linkNoTouchStart","manualClientBasePath","middlewarePrefetch","proxyPrefetch","middlewareClientMaxBodySize","proxyClientMaxBodySize","multiZoneDraftMode","cssChunking","requestCost","nonnegative","finite","weightDistribution","nextScriptWorkers","optimizeCss","optimisticClientCache","parallelServerCompiles","parallelServerBuildTraces","ppr","readonly","taint","blockingSSR","prerenderEarlyExit","proxyTimeout","rootParams","mcpServer","removeUncaughtErrorAndRejectionListeners","validateRSCRequestHeaders","scrollRestoration","sri","algorithm","swcPlugins","tuple","swcEnvOptions","mode","coreJs","skip","include","exclude","shippedProposals","forceAllTransforms","debug","loose","swcTraceProfiling","urlImports","workerThreads","webVitalsAttribution","mdxRs","development","jsxRuntime","jsxImportSource","providerImportSource","mdxType","transitionIndicator","gestureTransition","typedRoutes","webpackBuildWorker","webpackMemoryOptimizations","turbopackMemoryEviction","turbopackPluginRuntimeStrategy","turbopackMinify","turbopackFileSystemCacheForDev","turbopackFileSystemCacheForBuild","turbopackSourceMaps","turbopackInputSourceMaps","turbopackModuleFragments","turbopackRemoveUnusedImports","turbopackRemoveUnusedExports","turbopackScopeHoisting","turbopackGenerateComponentChunks","turbopackSharedRuntime","turbopackChunkingHeuristics","firstPageLoadPriority","min","max","priorityRoutes","priorityBoost","turbopackWorkerAssetPrefix","turbopackClientSideNestedAsyncChunking","turbopackServerSideNestedAsyncChunking","turbopackImportTypeBytes","turbopackUseBuiltinBabel","turbopackUseBuiltinSass","turbopackLocalPostcssConfig","turbopackModuleIds","turbopackInferModuleSideEffects","turbopackCjsTreeShaking","turbopackServerFastRefresh","optimizePackageImports","optimizeServerReact","strictRouteTypes","useTypeScriptCli","clientTraceMetadata","serverMinification","serverSourceMaps","useWasmBinary","useLightningcss","lightningCssFeatures","testProxy","defaultTestRunner","allowDevelopmentBuild","reactDebugChannel","instantInsights","validationLevel","devValidationWorker","staticGenerationRetryCount","staticGenerationMaxConcurrency","staticGenerationMinPagesPerWorker","typedEnv","serverComponentsHmrCache","serverComponentsHmrCancellation","authInterrupts","useCache","durableUseCacheEntries","useCacheTimeout","positive","slowModuleDetection","buildTimeThresholdMs","globalNotFound","turbopackRustReactCompiler","browserDebugInfoInTerminal","level","depthLimit","edgeLimit","showSourceLocation","lockDistDir","hideLogsAfterAbort","runtimeServerDeploymentId","supportsImmutableAssets","deferredEntries","onBeforeDeferredEntries","function","returns","promise","void","reportSystemEnvInlining","configSchema","adapterPath","agentRules","allowedDevOrigins","assetPrefix","bundlePagesRouterDependencies","cacheHandler","cacheMaxMemorySize","cleanDistDir","compiler","emotion","sourceMap","autoLabel","labelFormat","importMap","canonicalImport","styledBaseImport","reactRemoveProperties","properties","relay","src","artifactDirectory","language","eagerEsModules","removeConsole","styledComponents","displayName","topLevelImportPaths","ssr","fileName","meaninglessFileNames","minify","transpileTemplateLiterals","namespace","pure","cssProp","styledJsx","define","defineServer","runAfterProductionCompile","compress","configOrigin","crossOrigin","deploymentId","devIndicators","position","distDir","env","enablePrerenderSourceMaps","excludeDefaultMomentLocales","experimental","exportPathMap","args","dev","dir","outDir","buildId","generateBuildId","null","generateEtags","htmlLimitedBots","httpAgentOptions","keepAlive","i18n","defaultLocale","domains","domain","http","locales","localeDetection","images","localPatterns","pathname","search","remotePatterns","URL","hostname","port","protocol","unoptimized","customCacheHandler","contentSecurityPolicy","contentDispositionType","dangerouslyAllowSVG","dangerouslyAllowLocalIP","deviceSizes","lte","disableStaticImages","formats","imageSizes","loaderFile","maximumDiskCacheSize","maximumRedirects","maximumResponseBody","Number","MAX_SAFE_INTEGER","minimumCacheTTL","qualities","logging","fetches","fullUrl","hmrRefreshes","incomingRequests","ignore","serverFunctions","browserToTerminal","modularizeImports","transform","preventFullImport","skipDefaultConversion","onDemandEntries","maxInactiveAge","pagesBufferLength","output","outputFileTracingRoot","outputFileTracingExcludes","outputFileTracingIncludes","pageExtensions","instrumentationClientInject","partialPrefetching","poweredByHeader","productionBrowserSourceMaps","reactCompiler","compilationMode","panicThreshold","reactProductionProfiling","reactStrictMode","reactMaxHeadersLength","redirects","rewrites","beforeFiles","afterFiles","fallback","sassOptions","implementation","catchall","serverExternalPackages","skipMiddlewareUrlNormalize","skipProxyUrlNormalize","skipTrailingSlashRedirect","staticPageGenerationTimeout","expireTime","target","trailingSlash","transpilePackages","turbopack","typescript","ignoreBuildErrors","tsconfigPath","useFileSystemPublicRoutes","webpack","watchOptions","pollIntervalMs"],"mappings":"AACA,SAASA,aAAa,QAAQ,6BAA4B;AAE1D,SAASC,CAAC,QAAQ,yBAAwB;AAI1C,SACEC,0BAA0B,QAQrB,kBAAiB;AAOxB,SAASC,2BAA2B,QAAQ,mBAA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Q;YACvCwZ,cAAcva,EAAEQ,MAAM,GAAG4M,GAAG,CAAC,GAAGrM,QAAQ;QAC1C,GACCA,QAAQ;QACXmL,aAAalM,EAAEiB,OAAO,GAAGF,QAAQ;QACjCyZ,2BAA2Bxa,EAAEiB,OAAO,GAAGF,QAAQ;QAC/C,uDAAuD;QACvD0Z,SAASza,EAAEY,GAAG,GAAGyH,QAAQ,GAAGtH,QAAQ;QACpC2Z,cAAc1a,EACX+C,YAAY,CAAC;YACZ4X,gBAAgB3a,EAAE2C,MAAM,GAAGmN,QAAQ,GAAGxG,MAAM,GAAGvI,QAAQ;QACzD,GACCA,QAAQ;IACb,IACD","ignoreList":[0]} |
@@ -165,2 +165,3 @@ import os from 'os'; | ||
| coldCacheBadge: false, | ||
| devValidationWorker: true, | ||
| useSkewCookie: false, | ||
@@ -167,0 +168,0 @@ cssChunking: true, |
@@ -89,3 +89,12 @@ import { DEVTOOLS_CODE_FRAME_MAX_WIDTH, getOriginalCodeFrame, ignoreListAnonymousStackFramesIfSandwiched } from '../../next-devtools/server/shared'; | ||
| } | ||
| return devirtualizeReactServerURL(fileParam); | ||
| const file = devirtualizeReactServerURL(fileParam); | ||
| // React virtualizes filenames as `'file://' + path`, which is malformed | ||
| // for paths that need percent-encoding (e.g. a space in the project path) | ||
| // and then fails both Turbopack's `traceSource` and Node.js' source map | ||
| // cache lookups. Re-encode through WHATWG URL parsing. | ||
| // TODO(veil): Revisit if React's virtualization round-trips losslessly. | ||
| if (file.startsWith('file://') && URL.canParse(file)) { | ||
| return new URL(file).href; | ||
| } | ||
| return file; | ||
| } | ||
@@ -92,0 +101,0 @@ function createStackFrames(body) { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/dev/middleware-turbopack.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport {\n DEVTOOLS_CODE_FRAME_MAX_WIDTH,\n getOriginalCodeFrame,\n ignoreListAnonymousStackFramesIfSandwiched,\n type IgnorableStackFrame,\n type OriginalStackFrameResponse,\n type OriginalStackFramesRequest,\n type OriginalStackFramesResponse,\n type StackFrame,\n} from '../../next-devtools/server/shared'\nimport { middlewareResponse } from '../../next-devtools/server/middleware-response'\nimport path from 'path'\nimport { openFileInEditor } from '../../next-devtools/server/launch-editor'\nimport {\n SourceMapConsumer,\n type NullableMappedPosition,\n} from 'next/dist/compiled/source-map08'\nimport type { Project, TurbopackStackFrame } from '../../build/swc/types'\nimport {\n type ModernSourceMapPayload,\n devirtualizeReactServerURL,\n findApplicableSourceMapPayload,\n} from '../lib/source-maps'\nimport { findSourceMap, type SourceMap } from 'node:module'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { inspect } from 'node:util'\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 modulePath.startsWith('node:')\n )\n}\n\nconst currentSourcesByFile: Map<string, Promise<string | null>> = new Map()\n/**\n * @returns 1-based lines and 1-based columns\n */\nasync function batchedTraceSource(\n project: Project,\n frame: TurbopackStackFrame\n): Promise<{ frame: IgnorableStackFrame; source: string | null } | undefined> {\n const file = frame.file\n ? // TODO(veil): Why are the frames sent encoded?\n decodeURIComponent(frame.file)\n : undefined\n\n if (!file) return\n\n // For node internals they cannot traced the actual source code with project.traceSource,\n // we need an early return to indicate it's ignored to avoid the unknown scheme error from `project.traceSource`.\n if (file.startsWith('node:')) {\n return {\n frame: {\n file,\n line1: frame.line ?? null,\n column1: frame.column ?? null,\n methodName: frame.methodName ?? '<unknown>',\n ignored: true,\n arguments: [],\n },\n source: null,\n }\n }\n\n const currentDirectoryFileUrl = pathToFileURL(process.cwd()).href\n\n const sourceFrame = await project.traceSource(frame, currentDirectoryFileUrl)\n if (!sourceFrame) {\n return {\n frame: {\n file,\n line1: frame.line ?? null,\n column1: frame.column ?? null,\n methodName: frame.methodName ?? '<unknown>',\n ignored: shouldIgnorePath(file),\n arguments: [],\n },\n source: null,\n }\n }\n\n let source = null\n const originalFile = sourceFrame.originalFile\n\n // Don't look up source for node_modules or internals. These can often be large bundled files.\n const ignored =\n // Check the sourcemap's ignoreList (e.g. from 3rd party packages)\n !!sourceFrame.isIgnored ||\n shouldIgnorePath(originalFile ?? sourceFrame.file)\n if (originalFile && !ignored) {\n let sourcePromise = currentSourcesByFile.get(originalFile)\n if (!sourcePromise) {\n sourcePromise = project.getSourceForAsset(originalFile)\n currentSourcesByFile.set(originalFile, sourcePromise)\n setTimeout(() => {\n // Cache file reads for 100ms, as frames will often reference the same\n // files and can be large.\n currentSourcesByFile.delete(originalFile!)\n }, 100)\n }\n source = await sourcePromise\n }\n\n const ignorableFrame: IgnorableStackFrame = {\n file: sourceFrame.file,\n line1: sourceFrame.line ?? null,\n column1: sourceFrame.column ?? null,\n methodName:\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n frame.methodName ?? '<unknown>',\n ignored,\n arguments: [],\n }\n\n return {\n frame: ignorableFrame,\n source,\n }\n}\n\nfunction parseFile(fileParam: string | null): string | undefined {\n if (!fileParam) {\n return undefined\n }\n\n return devirtualizeReactServerURL(fileParam)\n}\n\nfunction createStackFrames(\n body: OriginalStackFramesRequest\n): TurbopackStackFrame[] {\n const { frames, isServer } = body\n\n return frames\n .map((frame): TurbopackStackFrame | undefined => {\n const file = parseFile(frame.file)\n\n if (!file) {\n return undefined\n }\n\n return {\n file,\n methodName: frame.methodName ?? '<unknown>',\n line: frame.line1 ?? undefined,\n column: frame.column1 ?? undefined,\n isServer,\n }\n })\n .filter((f): f is TurbopackStackFrame => f !== undefined)\n}\n\nfunction createStackFrame(\n searchParams: URLSearchParams\n): TurbopackStackFrame | undefined {\n const file = parseFile(searchParams.get('file'))\n\n if (!file) {\n return undefined\n }\n\n return {\n file,\n methodName: searchParams.get('methodName') ?? '<unknown>',\n line: parseInt(searchParams.get('line1') ?? '0', 10) || undefined,\n column: parseInt(searchParams.get('column1') ?? '0', 10) || undefined,\n isServer: searchParams.get('isServer') === 'true',\n }\n}\n\n/**\n * @returns 1-based lines and 1-based columns\n */\nasync function nativeTraceSource(\n frame: TurbopackStackFrame\n): Promise<{ frame: IgnorableStackFrame; source: string | null } | undefined> {\n const sourceURL = frame.file\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMap(sourceURL)?.payload\n } catch (cause) {\n throw new Error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n }\n\n if (sourceMapPayload !== undefined) {\n let consumer: SourceMapConsumer\n try {\n consumer = await new SourceMapConsumer(sourceMapPayload)\n } catch (cause) {\n throw new Error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n }\n let traced: {\n originalPosition: NullableMappedPosition\n sourceContent: string | null\n } | null\n try {\n const originalPosition = consumer.originalPositionFor({\n line: frame.line ?? 1,\n // 0-based columns out requires 0-based columns in.\n column: (frame.column ?? 1) - 1,\n })\n\n if (originalPosition.source === null) {\n traced = null\n } else {\n const sourceContent: string | null =\n consumer.sourceContentFor(\n originalPosition.source,\n /* returnNullOnMissing */ true\n ) ?? null\n\n traced = { originalPosition, sourceContent }\n }\n } finally {\n consumer.destroy()\n }\n\n if (traced !== null) {\n const { originalPosition, sourceContent } = traced\n const applicableSourceMap = findApplicableSourceMapPayload(\n (frame.line ?? 1) - 1,\n (frame.column ?? 1) - 1,\n sourceMapPayload\n )\n\n // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.\n let ignored = false\n if (applicableSourceMap === undefined) {\n console.error(\n 'No applicable source map found in sections for frame',\n frame\n )\n } else {\n // TODO: O(n^2). Consider moving `ignoreList` into a Set\n const sourceIndex = applicableSourceMap.sources.indexOf(\n originalPosition.source!\n )\n ignored =\n applicableSourceMap.ignoreList?.includes(sourceIndex) ??\n // When sourcemap is not available, fallback to checking `frame.file`.\n // e.g. In pages router, nextjs server code is not bundled into the page.\n shouldIgnorePath(frame.file)\n }\n\n const originalStackFrame: IgnorableStackFrame = {\n methodName:\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n frame.methodName\n ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n ?.replace('__webpack_exports__.', '') || '<unknown>',\n file: originalPosition.source,\n line1: originalPosition.line,\n column1:\n originalPosition.column === null ? null : originalPosition.column + 1,\n // TODO: c&p from async createOriginalStackFrame but why not frame.arguments?\n arguments: [],\n ignored,\n }\n\n return {\n frame: originalStackFrame,\n source: sourceContent,\n }\n }\n }\n\n return undefined\n}\n\n/**\n * Code frame rendering options. The defaults match terminal consumers; only\n * the overlay HTTP path opts in to always-on colors and the wide max width.\n */\ntype CodeFrameOptions = {\n /** Defaults to `process.stdout.isTTY`. */\n colors?: boolean\n /** Defaults to the dev server's terminal width. */\n maxWidth?: number\n}\n\nasync function createOriginalStackFrame(\n project: Project,\n projectPath: string,\n frame: TurbopackStackFrame,\n codeFrameOptions?: CodeFrameOptions\n): Promise<OriginalStackFrameResponse | null> {\n const traced =\n (await nativeTraceSource(frame)) ??\n // TODO(veil): When would the bundler know more than native?\n // If it's faster, try the bundler first and fall back to native later.\n (await batchedTraceSource(project, frame))\n if (!traced) {\n return null\n }\n\n let normalizedStackFrameLocation = traced.frame.file\n if (\n normalizedStackFrameLocation !== null &&\n normalizedStackFrameLocation.startsWith('file://')\n ) {\n normalizedStackFrameLocation = path.relative(\n projectPath,\n fileURLToPath(normalizedStackFrameLocation)\n )\n }\n\n /** undefined = not yet computed */\n let originalCodeFrame: string | null | undefined\n\n const tracedFrame = traced.frame\n return {\n originalStackFrame: {\n arguments: tracedFrame.arguments,\n file: normalizedStackFrameLocation,\n line1: tracedFrame.line1,\n column1: tracedFrame.column1,\n ignored: tracedFrame.ignored,\n methodName: tracedFrame.methodName,\n },\n get originalCodeFrame() {\n if (originalCodeFrame === undefined) {\n originalCodeFrame = getOriginalCodeFrame(tracedFrame, traced.source, {\n colors: codeFrameOptions?.colors,\n maxWidth: codeFrameOptions?.maxWidth,\n })\n }\n return originalCodeFrame\n },\n }\n}\n\nexport function getOverlayMiddleware({\n project,\n projectPath,\n isSrcDir,\n}: {\n project: Project\n projectPath: string\n isSrcDir: boolean\n}) {\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(req.url!, 'http://n')\n\n if (pathname === '/__nextjs_original-stack-frames') {\n if (req.method !== 'POST') {\n return middlewareResponse.badRequest(res)\n }\n\n const body = await new Promise<string>((resolve, reject) => {\n let data = ''\n req.on('data', (chunk) => {\n data += chunk\n })\n req.on('end', () => resolve(data))\n req.on('error', reject)\n })\n\n const request = JSON.parse(body) as OriginalStackFramesRequest\n const result = await getOriginalStackFrames({\n project,\n projectPath,\n frames: request.frames,\n isServer: request.isServer,\n isEdgeServer: request.isEdgeServer,\n isAppDirectory: request.isAppDirectory,\n codeFrameOptions: {\n // Overlay parses ANSI in JS and renders in a scrollable\n // `<pre>`, so colors are always wanted and terminal width is\n // irrelevant.\n colors: true,\n maxWidth: DEVTOOLS_CODE_FRAME_MAX_WIDTH,\n },\n })\n\n ignoreListAnonymousStackFramesIfSandwiched(result)\n\n return middlewareResponse.json(res, result)\n } else if (pathname === '/__nextjs_launch-editor') {\n const isAppRelativePath = searchParams.get('isAppRelativePath') === '1'\n\n let openEditorResult\n if (isAppRelativePath) {\n const relativeFilePath = searchParams.get('file') || ''\n const appPath = path.join(\n isSrcDir ? 'src' : '',\n 'app',\n relativeFilePath\n )\n openEditorResult = await openFileInEditor(appPath, 1, 1, projectPath)\n } else {\n const frame = createStackFrame(searchParams)\n if (!frame) return middlewareResponse.badRequest(res)\n openEditorResult = await openFileInEditor(\n frame.file,\n frame.line ?? 1,\n frame.column ?? 1,\n projectPath\n )\n }\n\n if (openEditorResult.error) {\n return middlewareResponse.internalServerError(\n res,\n openEditorResult.error\n )\n }\n if (!openEditorResult.found) {\n return middlewareResponse.notFound(res)\n }\n return middlewareResponse.noContent(res)\n }\n\n return next()\n }\n}\n\nexport function getSourceMapMiddleware(project: Project) {\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(req.url!, 'http://n')\n\n if (pathname !== '/__nextjs_source-map') {\n return next()\n }\n\n let filename = searchParams.get('filename')\n\n if (!filename) {\n return middlewareResponse.badRequest(res)\n }\n\n let nativeSourceMap: SourceMap | undefined\n try {\n nativeSourceMap = findSourceMap(filename)\n } catch (cause) {\n return middlewareResponse.internalServerError(\n res,\n new Error(\n `${filename}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n )\n }\n\n if (nativeSourceMap !== undefined) {\n const sourceMapPayload = nativeSourceMap.payload\n return middlewareResponse.json(res, sourceMapPayload)\n }\n\n try {\n // Turbopack chunk filenames might be URL-encoded.\n filename = decodeURI(filename)\n } catch {\n return middlewareResponse.badRequest(res)\n }\n\n if (path.isAbsolute(filename)) {\n filename = pathToFileURL(filename).href\n }\n\n try {\n const sourceMapString = await project.getSourceMap(filename)\n\n if (sourceMapString) {\n return middlewareResponse.jsonString(res, sourceMapString)\n }\n } catch (cause) {\n return middlewareResponse.internalServerError(\n res,\n new Error(\n `Failed to get source map for '${filename}'. This is a bug in Next.js`,\n {\n cause,\n }\n )\n )\n }\n\n middlewareResponse.noContent(res)\n }\n}\n\nexport async function getOriginalStackFrames({\n project,\n projectPath,\n frames,\n isServer,\n isEdgeServer,\n isAppDirectory,\n codeFrameOptions,\n}: {\n project: Project\n projectPath: string\n frames: readonly StackFrame[]\n isServer: boolean\n isEdgeServer: boolean\n isAppDirectory: boolean\n codeFrameOptions?: CodeFrameOptions\n}): Promise<OriginalStackFramesResponse> {\n const stackFrames = createStackFrames({\n frames,\n isServer,\n isEdgeServer,\n isAppDirectory,\n })\n\n return Promise.all(\n stackFrames.map(async (frame) => {\n try {\n const stackFrame = await createOriginalStackFrame(\n project,\n projectPath,\n frame,\n codeFrameOptions\n )\n if (stackFrame === null) {\n return {\n status: 'rejected',\n reason: 'Failed to create original stack frame',\n }\n }\n const originalStackFrame = stackFrame.originalStackFrame\n return {\n status: 'fulfilled',\n value: {\n originalStackFrame,\n originalCodeFrame:\n (originalStackFrame?.ignored ?? true)\n ? null\n : // TODO: Don't get all codeframes of non-ignored frames eagerly.\n stackFrame.originalCodeFrame,\n },\n }\n } catch (error) {\n return {\n status: 'rejected',\n reason: inspect(error, { colors: false }),\n }\n }\n })\n )\n}\n"],"names":["DEVTOOLS_CODE_FRAME_MAX_WIDTH","getOriginalCodeFrame","ignoreListAnonymousStackFramesIfSandwiched","middlewareResponse","path","openFileInEditor","SourceMapConsumer","devirtualizeReactServerURL","findApplicableSourceMapPayload","findSourceMap","fileURLToPath","pathToFileURL","inspect","shouldIgnorePath","modulePath","includes","startsWith","currentSourcesByFile","Map","batchedTraceSource","project","frame","file","decodeURIComponent","undefined","line1","line","column1","column","methodName","ignored","arguments","source","currentDirectoryFileUrl","process","cwd","href","sourceFrame","traceSource","originalFile","isIgnored","sourcePromise","get","getSourceForAsset","set","setTimeout","delete","ignorableFrame","parseFile","fileParam","createStackFrames","body","frames","isServer","map","filter","f","createStackFrame","searchParams","parseInt","nativeTraceSource","sourceURL","sourceMapPayload","payload","cause","Error","consumer","traced","originalPosition","originalPositionFor","sourceContent","sourceContentFor","destroy","applicableSourceMap","console","error","sourceIndex","sources","indexOf","ignoreList","originalStackFrame","replace","createOriginalStackFrame","projectPath","codeFrameOptions","normalizedStackFrameLocation","relative","originalCodeFrame","tracedFrame","colors","maxWidth","getOverlayMiddleware","isSrcDir","req","res","next","pathname","URL","url","method","badRequest","Promise","resolve","reject","data","on","chunk","request","JSON","parse","result","getOriginalStackFrames","isEdgeServer","isAppDirectory","json","isAppRelativePath","openEditorResult","relativeFilePath","appPath","join","internalServerError","found","notFound","noContent","getSourceMapMiddleware","filename","nativeSourceMap","decodeURI","isAbsolute","sourceMapString","getSourceMap","jsonString","stackFrames","all","stackFrame","status","reason","value"],"mappings":"AACA,SACEA,6BAA6B,EAC7BC,oBAAoB,EACpBC,0CAA0C,QAMrC,oCAAmC;AAC1C,SAASC,kBAAkB,QAAQ,iDAAgD;AACnF,OAAOC,UAAU,OAAM;AACvB,SAASC,gBAAgB,QAAQ,2CAA0C;AAC3E,SACEC,iBAAiB,QAEZ,kCAAiC;AAExC,SAEEC,0BAA0B,EAC1BC,8BAA8B,QACzB,qBAAoB;AAC3B,SAASC,aAAa,QAAwB,cAAa;AAC3D,SAASC,aAAa,EAAEC,aAAa,QAAQ,WAAU;AACvD,SAASC,OAAO,QAAQ,YAAW;AAEnC,SAASC,iBAAiBC,UAAkB;IAC1C,OACEA,WAAWC,QAAQ,CAAC,mBACpB,2EAA2E;IAC3ED,WAAWC,QAAQ,CAAC,gBACpBD,WAAWE,UAAU,CAAC;AAE1B;AAEA,MAAMC,uBAA4D,IAAIC;AACtE;;CAEC,GACD,eAAeC,mBACbC,OAAgB,EAChBC,KAA0B;IAE1B,MAAMC,OAAOD,MAAMC,IAAI,GAEnBC,mBAAmBF,MAAMC,IAAI,IAC7BE;IAEJ,IAAI,CAACF,MAAM;IAEX,yFAAyF;IACzF,iHAAiH;IACjH,IAAIA,KAAKN,UAAU,CAAC,UAAU;QAC5B,OAAO;YACLK,OAAO;gBACLC;gBACAG,OAAOJ,MAAMK,IAAI,IAAI;gBACrBC,SAASN,MAAMO,MAAM,IAAI;gBACzBC,YAAYR,MAAMQ,UAAU,IAAI;gBAChCC,SAAS;gBACTC,WAAW,EAAE;YACf;YACAC,QAAQ;QACV;IACF;IAEA,MAAMC,0BAA0BtB,cAAcuB,QAAQC,GAAG,IAAIC,IAAI;IAEjE,MAAMC,cAAc,MAAMjB,QAAQkB,W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+D,OAAO;oBAAEc,QAAQ;gBAAM;YACzC;QACF;IACF;AAEJ","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/dev/middleware-turbopack.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport {\n DEVTOOLS_CODE_FRAME_MAX_WIDTH,\n getOriginalCodeFrame,\n ignoreListAnonymousStackFramesIfSandwiched,\n type IgnorableStackFrame,\n type OriginalStackFrameResponse,\n type OriginalStackFramesRequest,\n type OriginalStackFramesResponse,\n type StackFrame,\n} from '../../next-devtools/server/shared'\nimport { middlewareResponse } from '../../next-devtools/server/middleware-response'\nimport path from 'path'\nimport { openFileInEditor } from '../../next-devtools/server/launch-editor'\nimport {\n SourceMapConsumer,\n type NullableMappedPosition,\n} from 'next/dist/compiled/source-map08'\nimport type { Project, TurbopackStackFrame } from '../../build/swc/types'\nimport {\n type ModernSourceMapPayload,\n devirtualizeReactServerURL,\n findApplicableSourceMapPayload,\n} from '../lib/source-maps'\nimport { findSourceMap, type SourceMap } from 'node:module'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { inspect } from 'node:util'\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 modulePath.startsWith('node:')\n )\n}\n\nconst currentSourcesByFile: Map<string, Promise<string | null>> = new Map()\n/**\n * @returns 1-based lines and 1-based columns\n */\nasync function batchedTraceSource(\n project: Project,\n frame: TurbopackStackFrame\n): Promise<{ frame: IgnorableStackFrame; source: string | null } | undefined> {\n const file = frame.file\n ? // TODO(veil): Why are the frames sent encoded?\n decodeURIComponent(frame.file)\n : undefined\n\n if (!file) return\n\n // For node internals they cannot traced the actual source code with project.traceSource,\n // we need an early return to indicate it's ignored to avoid the unknown scheme error from `project.traceSource`.\n if (file.startsWith('node:')) {\n return {\n frame: {\n file,\n line1: frame.line ?? null,\n column1: frame.column ?? null,\n methodName: frame.methodName ?? '<unknown>',\n ignored: true,\n arguments: [],\n },\n source: null,\n }\n }\n\n const currentDirectoryFileUrl = pathToFileURL(process.cwd()).href\n\n const sourceFrame = await project.traceSource(frame, currentDirectoryFileUrl)\n if (!sourceFrame) {\n return {\n frame: {\n file,\n line1: frame.line ?? null,\n column1: frame.column ?? null,\n methodName: frame.methodName ?? '<unknown>',\n ignored: shouldIgnorePath(file),\n arguments: [],\n },\n source: null,\n }\n }\n\n let source = null\n const originalFile = sourceFrame.originalFile\n\n // Don't look up source for node_modules or internals. These can often be large bundled files.\n const ignored =\n // Check the sourcemap's ignoreList (e.g. from 3rd party packages)\n !!sourceFrame.isIgnored ||\n shouldIgnorePath(originalFile ?? sourceFrame.file)\n if (originalFile && !ignored) {\n let sourcePromise = currentSourcesByFile.get(originalFile)\n if (!sourcePromise) {\n sourcePromise = project.getSourceForAsset(originalFile)\n currentSourcesByFile.set(originalFile, sourcePromise)\n setTimeout(() => {\n // Cache file reads for 100ms, as frames will often reference the same\n // files and can be large.\n currentSourcesByFile.delete(originalFile!)\n }, 100)\n }\n source = await sourcePromise\n }\n\n const ignorableFrame: IgnorableStackFrame = {\n file: sourceFrame.file,\n line1: sourceFrame.line ?? null,\n column1: sourceFrame.column ?? null,\n methodName:\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n frame.methodName ?? '<unknown>',\n ignored,\n arguments: [],\n }\n\n return {\n frame: ignorableFrame,\n source,\n }\n}\n\nfunction parseFile(fileParam: string | null): string | undefined {\n if (!fileParam) {\n return undefined\n }\n\n const file = devirtualizeReactServerURL(fileParam)\n // React virtualizes filenames as `'file://' + path`, which is malformed\n // for paths that need percent-encoding (e.g. a space in the project path)\n // and then fails both Turbopack's `traceSource` and Node.js' source map\n // cache lookups. Re-encode through WHATWG URL parsing.\n // TODO(veil): Revisit if React's virtualization round-trips losslessly.\n if (file.startsWith('file://') && URL.canParse(file)) {\n return new URL(file).href\n }\n return file\n}\n\nfunction createStackFrames(\n body: OriginalStackFramesRequest\n): TurbopackStackFrame[] {\n const { frames, isServer } = body\n\n return frames\n .map((frame): TurbopackStackFrame | undefined => {\n const file = parseFile(frame.file)\n\n if (!file) {\n return undefined\n }\n\n return {\n file,\n methodName: frame.methodName ?? '<unknown>',\n line: frame.line1 ?? undefined,\n column: frame.column1 ?? undefined,\n isServer,\n }\n })\n .filter((f): f is TurbopackStackFrame => f !== undefined)\n}\n\nfunction createStackFrame(\n searchParams: URLSearchParams\n): TurbopackStackFrame | undefined {\n const file = parseFile(searchParams.get('file'))\n\n if (!file) {\n return undefined\n }\n\n return {\n file,\n methodName: searchParams.get('methodName') ?? '<unknown>',\n line: parseInt(searchParams.get('line1') ?? '0', 10) || undefined,\n column: parseInt(searchParams.get('column1') ?? '0', 10) || undefined,\n isServer: searchParams.get('isServer') === 'true',\n }\n}\n\n/**\n * @returns 1-based lines and 1-based columns\n */\nasync function nativeTraceSource(\n frame: TurbopackStackFrame\n): Promise<{ frame: IgnorableStackFrame; source: string | null } | undefined> {\n const sourceURL = frame.file\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMap(sourceURL)?.payload\n } catch (cause) {\n throw new Error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n }\n\n if (sourceMapPayload !== undefined) {\n let consumer: SourceMapConsumer\n try {\n consumer = await new SourceMapConsumer(sourceMapPayload)\n } catch (cause) {\n throw new Error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n }\n let traced: {\n originalPosition: NullableMappedPosition\n sourceContent: string | null\n } | null\n try {\n const originalPosition = consumer.originalPositionFor({\n line: frame.line ?? 1,\n // 0-based columns out requires 0-based columns in.\n column: (frame.column ?? 1) - 1,\n })\n\n if (originalPosition.source === null) {\n traced = null\n } else {\n const sourceContent: string | null =\n consumer.sourceContentFor(\n originalPosition.source,\n /* returnNullOnMissing */ true\n ) ?? null\n\n traced = { originalPosition, sourceContent }\n }\n } finally {\n consumer.destroy()\n }\n\n if (traced !== null) {\n const { originalPosition, sourceContent } = traced\n const applicableSourceMap = findApplicableSourceMapPayload(\n (frame.line ?? 1) - 1,\n (frame.column ?? 1) - 1,\n sourceMapPayload\n )\n\n // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.\n let ignored = false\n if (applicableSourceMap === undefined) {\n console.error(\n 'No applicable source map found in sections for frame',\n frame\n )\n } else {\n // TODO: O(n^2). Consider moving `ignoreList` into a Set\n const sourceIndex = applicableSourceMap.sources.indexOf(\n originalPosition.source!\n )\n ignored =\n applicableSourceMap.ignoreList?.includes(sourceIndex) ??\n // When sourcemap is not available, fallback to checking `frame.file`.\n // e.g. In pages router, nextjs server code is not bundled into the page.\n shouldIgnorePath(frame.file)\n }\n\n const originalStackFrame: IgnorableStackFrame = {\n methodName:\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n frame.methodName\n ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n ?.replace('__webpack_exports__.', '') || '<unknown>',\n file: originalPosition.source,\n line1: originalPosition.line,\n column1:\n originalPosition.column === null ? null : originalPosition.column + 1,\n // TODO: c&p from async createOriginalStackFrame but why not frame.arguments?\n arguments: [],\n ignored,\n }\n\n return {\n frame: originalStackFrame,\n source: sourceContent,\n }\n }\n }\n\n return undefined\n}\n\n/**\n * Code frame rendering options. The defaults match terminal consumers; only\n * the overlay HTTP path opts in to always-on colors and the wide max width.\n */\ntype CodeFrameOptions = {\n /** Defaults to `process.stdout.isTTY`. */\n colors?: boolean\n /** Defaults to the dev server's terminal width. */\n maxWidth?: number\n}\n\nasync function createOriginalStackFrame(\n project: Project,\n projectPath: string,\n frame: TurbopackStackFrame,\n codeFrameOptions?: CodeFrameOptions\n): Promise<OriginalStackFrameResponse | null> {\n const traced =\n (await nativeTraceSource(frame)) ??\n // TODO(veil): When would the bundler know more than native?\n // If it's faster, try the bundler first and fall back to native later.\n (await batchedTraceSource(project, frame))\n if (!traced) {\n return null\n }\n\n let normalizedStackFrameLocation = traced.frame.file\n if (\n normalizedStackFrameLocation !== null &&\n normalizedStackFrameLocation.startsWith('file://')\n ) {\n normalizedStackFrameLocation = path.relative(\n projectPath,\n fileURLToPath(normalizedStackFrameLocation)\n )\n }\n\n /** undefined = not yet computed */\n let originalCodeFrame: string | null | undefined\n\n const tracedFrame = traced.frame\n return {\n originalStackFrame: {\n arguments: tracedFrame.arguments,\n file: normalizedStackFrameLocation,\n line1: tracedFrame.line1,\n column1: tracedFrame.column1,\n ignored: tracedFrame.ignored,\n methodName: tracedFrame.methodName,\n },\n get originalCodeFrame() {\n if (originalCodeFrame === undefined) {\n originalCodeFrame = getOriginalCodeFrame(tracedFrame, traced.source, {\n colors: codeFrameOptions?.colors,\n maxWidth: codeFrameOptions?.maxWidth,\n })\n }\n return originalCodeFrame\n },\n }\n}\n\nexport function getOverlayMiddleware({\n project,\n projectPath,\n isSrcDir,\n}: {\n project: Project\n projectPath: string\n isSrcDir: boolean\n}) {\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(req.url!, 'http://n')\n\n if (pathname === '/__nextjs_original-stack-frames') {\n if (req.method !== 'POST') {\n return middlewareResponse.badRequest(res)\n }\n\n const body = await new Promise<string>((resolve, reject) => {\n let data = ''\n req.on('data', (chunk) => {\n data += chunk\n })\n req.on('end', () => resolve(data))\n req.on('error', reject)\n })\n\n const request = JSON.parse(body) as OriginalStackFramesRequest\n const result = await getOriginalStackFrames({\n project,\n projectPath,\n frames: request.frames,\n isServer: request.isServer,\n isEdgeServer: request.isEdgeServer,\n isAppDirectory: request.isAppDirectory,\n codeFrameOptions: {\n // Overlay parses ANSI in JS and renders in a scrollable\n // `<pre>`, so colors are always wanted and terminal width is\n // irrelevant.\n colors: true,\n maxWidth: DEVTOOLS_CODE_FRAME_MAX_WIDTH,\n },\n })\n\n ignoreListAnonymousStackFramesIfSandwiched(result)\n\n return middlewareResponse.json(res, result)\n } else if (pathname === '/__nextjs_launch-editor') {\n const isAppRelativePath = searchParams.get('isAppRelativePath') === '1'\n\n let openEditorResult\n if (isAppRelativePath) {\n const relativeFilePath = searchParams.get('file') || ''\n const appPath = path.join(\n isSrcDir ? 'src' : '',\n 'app',\n relativeFilePath\n )\n openEditorResult = await openFileInEditor(appPath, 1, 1, projectPath)\n } else {\n const frame = createStackFrame(searchParams)\n if (!frame) return middlewareResponse.badRequest(res)\n openEditorResult = await openFileInEditor(\n frame.file,\n frame.line ?? 1,\n frame.column ?? 1,\n projectPath\n )\n }\n\n if (openEditorResult.error) {\n return middlewareResponse.internalServerError(\n res,\n openEditorResult.error\n )\n }\n if (!openEditorResult.found) {\n return middlewareResponse.notFound(res)\n }\n return middlewareResponse.noContent(res)\n }\n\n return next()\n }\n}\n\nexport function getSourceMapMiddleware(project: Project) {\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(req.url!, 'http://n')\n\n if (pathname !== '/__nextjs_source-map') {\n return next()\n }\n\n let filename = searchParams.get('filename')\n\n if (!filename) {\n return middlewareResponse.badRequest(res)\n }\n\n let nativeSourceMap: SourceMap | undefined\n try {\n nativeSourceMap = findSourceMap(filename)\n } catch (cause) {\n return middlewareResponse.internalServerError(\n res,\n new Error(\n `${filename}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n )\n }\n\n if (nativeSourceMap !== undefined) {\n const sourceMapPayload = nativeSourceMap.payload\n return middlewareResponse.json(res, sourceMapPayload)\n }\n\n try {\n // Turbopack chunk filenames might be URL-encoded.\n filename = decodeURI(filename)\n } catch {\n return middlewareResponse.badRequest(res)\n }\n\n if (path.isAbsolute(filename)) {\n filename = pathToFileURL(filename).href\n }\n\n try {\n const sourceMapString = await project.getSourceMap(filename)\n\n if (sourceMapString) {\n return middlewareResponse.jsonString(res, sourceMapString)\n }\n } catch (cause) {\n return middlewareResponse.internalServerError(\n res,\n new Error(\n `Failed to get source map for '${filename}'. This is a bug in Next.js`,\n {\n cause,\n }\n )\n )\n }\n\n middlewareResponse.noContent(res)\n }\n}\n\nexport async function getOriginalStackFrames({\n project,\n projectPath,\n frames,\n isServer,\n isEdgeServer,\n isAppDirectory,\n codeFrameOptions,\n}: {\n project: Project\n projectPath: string\n frames: readonly StackFrame[]\n isServer: boolean\n isEdgeServer: boolean\n isAppDirectory: boolean\n codeFrameOptions?: CodeFrameOptions\n}): Promise<OriginalStackFramesResponse> {\n const stackFrames = createStackFrames({\n frames,\n isServer,\n isEdgeServer,\n isAppDirectory,\n })\n\n return Promise.all(\n stackFrames.map(async (frame) => {\n try {\n const stackFrame = await createOriginalStackFrame(\n project,\n projectPath,\n frame,\n codeFrameOptions\n )\n if (stackFrame === null) {\n return {\n status: 'rejected',\n reason: 'Failed to create original stack frame',\n }\n }\n const originalStackFrame = stackFrame.originalStackFrame\n return {\n status: 'fulfilled',\n value: {\n originalStackFrame,\n originalCodeFrame:\n (originalStackFrame?.ignored ?? true)\n ? null\n : // TODO: Don't get all codeframes of non-ignored frames eagerly.\n stackFrame.originalCodeFrame,\n },\n }\n } catch (error) {\n return {\n status: 'rejected',\n reason: inspect(error, { colors: false }),\n }\n }\n })\n )\n}\n"],"names":["DEVTOOLS_CODE_FRAME_MAX_WIDTH","getOriginalCodeFrame","ignoreListAnonymousStackFramesIfSandwiched","middlewareResponse","path","openFileInEditor","SourceMapConsumer","devirtualizeReactServerURL","findApplicableSourceMapPayload","findSourceMap","fileURLToPath","pathToFileURL","inspect","shouldIgnorePath","modulePath","includes","startsWith","currentSourcesByFile","Map","batchedTraceSource","project","frame","file","decodeURIComponent","undefined","line1","line","column1","column","methodName","ignored","arguments","source","currentDirectoryFileUrl","process","cwd","href","sourceFrame","traceSource","originalFile","isIgnored","sourcePromise","get","getSourceForAsset","set","setTimeout","delete","ignorableFrame","parseFile","fileParam","URL","canParse","createStackFrames","body","frames","isServer","map","filter","f","createStackFrame","searchParams","parseInt","nativeTraceSource","sourceURL","sourceMapPayload","payload","cause","Error","consumer","traced","originalPosition","originalPositionFor","sourceContent","sourceContentFor","destroy","applicableSourceMap","console","error","sourceIndex","sources","indexOf","ignoreList","originalStackFrame","replace","createOriginalStackFrame","projectPath","codeFrameOptions","normalizedStackFrameLocation","relative","originalCodeFrame","tracedFrame","colors","maxWidth","getOverlayMiddleware","isSrcDir","req","res","next","pathname","url","method","badRequest","Promise","resolve","reject","data","on","chunk","request","JSON","parse","result","getOriginalStackFrames","isEdgeServer","isAppDirectory","json","isAppRelativePath","openEditorResult","relativeFilePath","appPath","join","internalServerError","found","notFound","noContent","getSourceMapMiddleware","filename","nativeSourceMap","decodeURI","isAbsolute","sourceMapString","getSourceMap","jsonString","stackFrames","all","stackFrame","status","reason","value"],"mappings":"AACA,SACEA,6BAA6B,EAC7BC,oBAAoB,EACpBC,0CAA0C,QAMrC,oCAAmC;AAC1C,SAASC,kBAAkB,QAAQ,iDAAgD;AACnF,OAAOC,UAAU,OAAM;AACvB,SAASC,gBAAgB,QAAQ,2CAA0C;AAC3E,SACEC,iBAAiB,QAEZ,kCAAiC;AAExC,SAEEC,0BAA0B,EAC1BC,8BAA8B,QACzB,qBAAoB;AAC3B,SAASC,aAAa,QAAwB,cAAa;AAC3D,SAASC,aAAa,EAAEC,aAAa,QAAQ,WAAU;AACvD,SAASC,OAAO,QAAQ,YAAW;AAEnC,SAASC,iBAAiBC,UAAkB;IAC1C,OACEA,WAAWC,QAAQ,CAAC,mBACpB,2EAA2E;IAC3ED,WAAWC,QAAQ,CAAC,gBACpBD,WAAWE,UAAU,CAAC;AAE1B;AAEA,MAAMC,uBAA4D,IAAIC;AACtE;;CAEC,GACD,eAAeC,mBACbC,OAAg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;AACF;AAEA,OAAO,eAAegB,uBAAuB,EAC3C5F,OAAO,EACPiE,WAAW,EACX/B,MAAM,EACNC,QAAQ,EACR0D,YAAY,EACZC,cAAc,EACd5B,gBAAgB,EASjB;IACC,MAAM+C,cAAcjF,kBAAkB;QACpCE;QACAC;QACA0D;QACAC;IACF;IAEA,OAAOZ,QAAQgC,GAAG,CAChBD,YAAY7E,GAAG,CAAC,OAAOnC;QACrB,IAAI;YACF,MAAMkH,aAAa,MAAMnD,yBACvBhE,SACAiE,aACAhE,OACAiE;YAEF,IAAIiD,eAAe,MAAM;gBACvB,OAAO;oBACLC,QAAQ;oBACRC,QAAQ;gBACV;YACF;YACA,MAAMvD,qBAAqBqD,WAAWrD,kBAAkB;YACxD,OAAO;gBACLsD,QAAQ;gBACRE,OAAO;oBACLxD;oBACAO,mBACE,AAACP,CAAAA,sCAAAA,mBAAoBpD,OAAO,KAAI,OAC5B,OAEAyG,WAAW9C,iBAAiB;gBACpC;YACF;QACF,EAAE,OAAOZ,OAAO;YACd,OAAO;gBACL2D,QAAQ;gBACRC,QAAQ7H,QAAQiE,OAAO;oBAAEc,QAAQ;gBAAM;YACzC;QACF;IACF;AAEJ","ignoreList":[0]} |
@@ -6,2 +6,3 @@ import { addRequestMeta, getRequestMeta } from '../request-meta'; | ||
| import { installUseCacheProbe } from './use-cache-probe-pool'; | ||
| import { installDevValidationWorker } from './dev-validation-worker-pool'; | ||
| import { join as pathJoin } from 'path'; | ||
@@ -120,2 +121,22 @@ import { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'; | ||
| }); | ||
| // Runs Cache Components dev validation on a worker thread, off the main | ||
| // thread, so validation renders don't block the event loop during rapid | ||
| // navigation. Gated by `experimental.devValidationWorker`. The worker is | ||
| // spawned lazily on the first navigation that validates, so this install is | ||
| // free when a project doesn't use Cache Components. | ||
| // | ||
| // Turbopack only, because the worker's thread has source maps just for the | ||
| // chunks it loaded itself, and resolves the rest by reading the `.map` | ||
| // Turbopack writes next to each chunk. Webpack keeps its dev source maps in | ||
| // the compiler, which the worker's thread cannot reach, so validation | ||
| // errors would be reported without a source location. Running validation on | ||
| // the main thread costs dev performance but keeps those frames intact. | ||
| if (process.env.TURBOPACK && this.nextConfig.experimental.devValidationWorker !== false) { | ||
| installDevValidationWorker({ | ||
| distDir: this.distDir, | ||
| buildId: this.buildId, | ||
| deploymentId: this.deploymentId, | ||
| nextConfig: this.nextConfig | ||
| }); | ||
| } | ||
| } | ||
@@ -122,0 +143,0 @@ getServerComponentsHmrCache() { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { DetachedPromise } from '../../lib/detached-promise'\nimport { isPostpone } from '../lib/router-utils/is-postpone'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = new DetachedPromise<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return JSON.stringify(value.staticPaths)?.length || 1\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value) {\n return JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n process.on('unhandledRejection', (reason) => {\n if (isPostpone(reason)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n this.logErrorWithOriginalStack(reason, 'unhandledRejection')\n })\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n pprConfig: this.nextConfig.experimental.ppr,\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["addRequestMeta","getRequestMeta","React","fs","Worker","installUseCacheProbe","join","pathJoin","PUBLIC_DIR_MIDDLEWARE_CONFLICT","findPagesDir","PHASE_DEVELOPMENT_SERVER","PAGES_MANIFEST","APP_PATHS_MANIFEST","COMPILER_NAMES","PRERENDER_MANIFEST","Server","WrappedBuildError","normalizePagePath","pathHasPrefix","removePathPrefix","Telemetry","hrtimeToEpochNanoseconds","setGlobal","trace","traceGlobals","findPageFile","getFormattedNodeOptionsWithoutInspect","withCoalescedInvoke","loadDefaultErrorComponents","DecodeError","MiddlewareNotFoundError","Log","isError","getProperError","defaultConfig","isMiddlewareFile","formatServerError","DevRouteMatcherManager","DevPagesRouteMatcherProvider","DevPagesAPIRouteMatcherProvider","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","NodeManifestLoader","BatchedFileReader","DefaultFileReader","LRUCache","getMiddlewareRouteMatcher","DetachedPromise","isPostpone","generateInterceptionRoutesRewrites","buildCustomRoute","decorateServerError","logRequests","FallbackMode","fallbackModeToFallbackField","ensureInstrumentationRegistered","getInstrumentationModule","getRouteRegex","HMR_MESSAGE_SENT_TO_BROWSER","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","createElement","DevServer","getStaticPathsWorker","worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","conf","bundlerService","startServerSpan","renderOpts","ErrorDebug","staticPathsCache","length","value","JSON","stringify","staticPaths","pagesDir","appDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","distDir","buildId","deploymentId","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","extensions","pageExtensions","extensionsExpression","RegExp","fileReader","pathnameFilter","test","push","localeNormalizer","ignorePartFilter","part","startsWith","isTurbopack","TURBOPACK","getBuildId","prepareImpl","existingTelemetry","get","telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","on","reason","logErrorWithOriginalStack","err","hasPage","normalizedPath","console","error","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","requestStart","hrtime","bigint","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","devRequestTimingInternalsEnd","manualTraceChild","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","existsSync","publicDir","sent","__NEXT_PAGE","internalErr","body","send","type","getPagesManifest","serverDistDir","getAppPathsManifest","enabledDirectories","app","rewrites","Object","keys","appPathRoutes","map","route","regex","output","exit","getMiddleware","middleware","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","message","runInstrumentationHookIfAvailable","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","pprConfig","ppr","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","instrumentationOnRequestError","args","silenceLog"],"mappings":"AAWA,SACEA,cAAc,EACdC,cAAc,QAGT,kBAAiB;AAQxB,YAAYC,WAAW,QAAO;AAC9B,OAAOC,QAAQ,KAAI;AACnB,SAASC,MAAM,QAAQ,iCAAgC;AACvD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,QAAQC,QAAQ,QAAQ,OAAM;AACvC,SAASC,8BAA8B,QAAQ,sBAAqB;AACpE,SAASC,YAAY,QAAQ,2BAA0B;AACvD,SACEC,wBAAwB,EACxBC,cAAc,EACdC,kBAAkB,EAClBC,cAAc,EACdC,kBAAkB,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,CAACtL,yBAAyB,CAACC,KAAK;QACtC;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { installDevValidationWorker } from './dev-validation-worker-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { DetachedPromise } from '../../lib/detached-promise'\nimport { isPostpone } from '../lib/router-utils/is-postpone'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = new DetachedPromise<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return JSON.stringify(value.staticPaths)?.length || 1\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value) {\n return JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n\n // Runs Cache Components dev validation on a worker thread, off the main\n // thread, so validation renders don't block the event loop during rapid\n // navigation. Gated by `experimental.devValidationWorker`. The worker is\n // spawned lazily on the first navigation that validates, so this install is\n // free when a project doesn't use Cache Components.\n //\n // Turbopack only, because the worker's thread has source maps just for the\n // chunks it loaded itself, and resolves the rest by reading the `.map`\n // Turbopack writes next to each chunk. Webpack keeps its dev source maps in\n // the compiler, which the worker's thread cannot reach, so validation\n // errors would be reported without a source location. Running validation on\n // the main thread costs dev performance but keeps those frames intact.\n if (\n process.env.TURBOPACK &&\n this.nextConfig.experimental.devValidationWorker !== false\n ) {\n installDevValidationWorker({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n process.on('unhandledRejection', (reason) => {\n if (isPostpone(reason)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n this.logErrorWithOriginalStack(reason, 'unhandledRejection')\n })\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n pprConfig: this.nextConfig.experimental.ppr,\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["addRequestMeta","getRequestMeta","React","fs","Worker","installUseCacheProbe","installDevValidationWorker","join","pathJoin","PUBLIC_DIR_MIDDLEWARE_CONFLICT","findPagesDir","PHASE_DEVELOPMENT_SERVER","PAGES_MANIFEST","APP_PATHS_MANIFEST","COMPILER_NAMES","PRERENDER_MANIFEST","Server","WrappedBuildError","normalizePagePath","pathHasPrefix","removePathPrefix","Telemetry","hrtimeToEpochNanoseconds","setGlobal","trace","traceGlobals","findPageFile","getFormattedNodeOptionsWithoutInspect","withCoalescedInvoke","loadDefaultErrorComponents","DecodeError","MiddlewareNotFoundError","Log","isError","getProperError","defaultConfig","isMiddlewareFile","formatServerError","DevRouteMatcherManager","DevPagesRouteMatcherProvider","DevPagesAPIRouteMatcherProvider","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","NodeManifestLoader","BatchedFileReader","DefaultFileReader","LRUCache","getMiddlewareRouteMatcher","DetachedPromise","isPostpone","generateInterceptionRoutesRewrites","buildCustomRoute","decorateServerError","logRequests","FallbackMode","fallbackModeToFallbackField","ensureInstrumentationRegistered","getInstrumentationModule","getRouteRegex","HMR_MESSAGE_SENT_TO_BROWSER","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","createElement","DevServer","getStaticPathsWorker","worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","conf","bundlerService","startServerSpan","renderOpts","ErrorDebug","staticPathsCache","length","value","JSON","stringify","staticPaths","pagesDir","appDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","distDir","buildId","deploymentId","TURBOPACK","devValidationWorker","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","extensions","pageExtensions","extensionsExpression","RegExp","fileReader","pathnameFilter","test","push","localeNormalizer","ignorePartFilter","part","startsWith","isTurbopack","getBuildId","prepareImpl","existingTelemetry","get","telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","on","reason","logErrorWithOriginalStack","err","hasPage","normalizedPath","console","error","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","requestStart","hrtime","bigint","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","devRequestTimingInternalsEnd","manualTraceChild","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","existsSync","publicDir","sent","__NEXT_PAGE","internalErr","body","send","type","getPagesManifest","serverDistDir","getAppPathsManifest","enabledDirectories","app","rewrites","Object","keys","appPathRoutes","map","route","regex","output","exit","getMiddleware","middleware","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","message","runInstrumentationHookIfAvailable","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","pprConfig","ppr","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","instrumentationOnRequestError","args","silenceLog"],"mappings":"AAWA,SACEA,cAAc,EACdC,cAAc,QAGT,kBAAiB;AAQxB,YAAYC,WAAW,QAAO;AAC9B,OAAOC,QAAQ,KAAI;AACnB,SAASC,MAAM,QAAQ,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aAAa,CAACC,YAAY,EAAE;YACnD,MAAM,IAAI,CAAC9M,UAAU,CAAC;gBACpBE;gBACAyH;gBACAxH,YAAY;gBACZF,YAAY7D;gBACZgE;YACF;QACF;QAEA,IAAI,CAAC2M,gBAAgB,GAAG,KAAK,CAAC9F;QAE9B,OAAO,MAAM,KAAK,CAACsF,mBAAmB;YACpCrM;YACAuM;YACAjK;YACAgK;YACAvE;YACAyE;YACAtM;QACF;IACF;IAEA,MAAgB4M,2BACd5M,GAAY,EAC2C;QACvD,MAAM,IAAI,CAAClC,cAAc,CAAC8O,0BAA0B,CAAC5M;QACrD,OAAO,MAAMnG,2BAA2B,IAAI,CAACmF,OAAO;IACtD;IAEA,MAAMwN,oBAAoB1M,IAAY,EAAgB;QACpD,OAAO,MAAM,IAAI,CAAChC,cAAc,CAAC0O,mBAAmB,CAAC1M;IACvD;IAEA,MAAgB+M,8BACd,GAAGC,IAAqD,EACxD;QACA,MAAM,KAAK,CAACD,iCAAiCC;QAE7C,MAAM,CAACpL,SAASqL,WAAW,GAAGD;QAC9B,IAAI,CAACC,YAAY;YACf,IAAI,CAACtL,yBAAyB,CAACC,KAAK;QACtC;IACF;AACF","ignoreList":[0]} |
@@ -14,3 +14,3 @@ import { loadEnvConfig } from '@next/env'; | ||
| const versionSuffix = logBundler ? ` (${bundlerName(getBundlerFromEnv())})` : ''; | ||
| Log.bootstrap(`${bold(purple(`${Log.prefixes.ready} Next.js ${"16.3.0-canary.96"}`))}${versionSuffix}`); | ||
| Log.bootstrap(`${bold(purple(`${Log.prefixes.ready} Next.js ${"16.3.0-canary.97"}`))}${versionSuffix}`); | ||
| if (appUrl) { | ||
@@ -17,0 +17,0 @@ Log.bootstrap(`- Local: ${appUrl}`); |
@@ -12,5 +12,8 @@ import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'; | ||
| if (pathname.startsWith('/')) { | ||
| const pathnameParts = pathname.split('/'); | ||
| for(let i = 1; i < pathnameParts.length + 1; i++){ | ||
| let curPathname = pathnameParts.slice(0, i).join('/'); | ||
| let end = pathname.indexOf('/', 1); | ||
| while(true){ | ||
| if (end === -1) { | ||
| end = pathname.length; | ||
| } | ||
| let curPathname = pathname.slice(0, end); | ||
| if (curPathname) { | ||
@@ -23,2 +26,6 @@ // all derived tags other than the page are layout tags | ||
| } | ||
| if (end === pathname.length) { | ||
| break; | ||
| } | ||
| end = pathname.indexOf('/', end + 1); | ||
| } | ||
@@ -25,0 +32,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/implicit-tags.ts"],"sourcesContent":["import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport { getCacheHandlerEntries } from '../use-cache/handlers'\nimport { encodeCacheTag } from './encode-cache-tag'\nimport { createLazyResult, type LazyResult } from './lazy-result'\n\nexport interface ImplicitTags {\n /**\n * For legacy usage, the implicit tags are passed to the incremental cache\n * handler in `get` calls.\n */\n readonly tags: string[]\n\n /**\n * Modern cache handlers don't receive implicit tags. Instead, the implicit\n * tags' expirations are stored in the work unit store, and used to compare\n * with a cache entry's timestamp.\n *\n * Note: This map contains lazy results so that we can evaluate them when the\n * first cache entry is read. It allows us to skip fetching the expiration\n * values if no caches are read at all.\n */\n readonly expirationsByCacheKind: Map<string, LazyResult<number>>\n}\n\nconst getDerivedTags = (pathname: string): string[] => {\n const derivedTags: string[] = [`/layout`]\n\n // we automatically add the current path segments as tags\n // for revalidatePath handling\n if (pathname.startsWith('/')) {\n const pathnameParts = pathname.split('/')\n\n for (let i = 1; i < pathnameParts.length + 1; i++) {\n let curPathname = pathnameParts.slice(0, i).join('/')\n\n if (curPathname) {\n // all derived tags other than the page are layout tags\n if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {\n curPathname = `${curPathname}${\n !curPathname.endsWith('/') ? '/' : ''\n }layout`\n }\n derivedTags.push(curPathname)\n }\n }\n }\n return derivedTags\n}\n\n/**\n * Creates a map with lazy results that fetch the expiration value for the given\n * tags and respective cache kind when they're awaited for the first time.\n */\nfunction createTagsExpirationsByCacheKind(\n tags: string[]\n): Map<string, LazyResult<number>> {\n const expirationsByCacheKind = new Map<string, LazyResult<number>>()\n const cacheHandlers = getCacheHandlerEntries()\n\n if (cacheHandlers) {\n for (const [kind, cacheHandler] of cacheHandlers) {\n if ('getExpiration' in cacheHandler) {\n expirationsByCacheKind.set(\n kind,\n createLazyResult(async () => cacheHandler.getExpiration(tags))\n )\n }\n }\n }\n\n return expirationsByCacheKind\n}\n\nexport async function getImplicitTags(\n page: string,\n pathname: string,\n fallbackRouteParams: null | OpaqueFallbackRouteParams\n): Promise<ImplicitTags> {\n const tags = new Set<string>()\n\n // Add the derived tags from the page. Encode each tag so a non-ASCII\n // pathname doesn't trip header validation when written to\n // `x-next-cache-tags`. Idempotent on already-ASCII input.\n const derivedTags = getDerivedTags(page)\n for (let tag of derivedTags) {\n tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`)\n tags.add(tag)\n }\n\n // Add the tags from the pathname. If the route has unknown params, we don't\n // want to add the pathname as a tag, as it will be invalid.\n if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {\n const tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`)\n tags.add(tag)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n const tagsArray = Array.from(tags)\n return {\n tags: tagsArray,\n expirationsByCacheKind: createTagsExpirationsByCacheKind(tagsArray),\n }\n}\n"],"names":["NEXT_CACHE_IMPLICIT_TAG_ID","getCacheHandlerEntries","encodeCacheTag","createLazyResult","getDerivedTags","pathname","derivedTags","startsWith","pathnameParts","split","i","length","curPathname","slice","join","endsWith","push","createTagsExpirationsByCacheKind","tags","expirationsByCacheKind","Map","cacheHandlers","kind","cacheHandler","set","getExpiration","getImplicitTags","page","fallbackRouteParams","Set","tag","add","size","has","tagsArray","Array","from"],"mappings":"AAAA,SAASA,0BAA0B,QAAQ,sBAAqB;AAEhE,SAASC,sBAAsB,QAAQ,wBAAuB;AAC9D,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,gBAAgB,QAAyB,gBAAe;AAqBjE,MAAMC,iBAAiB,CAACC;IACtB,MAAMC,cAAwB;QAAC,CAAC,OAAO,CAAC;KAAC;IAEzC,yDAAyD;IACzD,8BAA8B;IAC9B,IAAID,SAASE,UAAU,CAAC,MAAM;QAC5B,MAAMC,gBAAgBH,SAASI,KAAK,CAAC;QAErC,IAAK,IAAIC,IAAI,GAAGA,IAAIF,cAAcG,MAAM,GAAG,GAAGD,IAAK;YACjD,IAAIE,cAAcJ,cAAcK,KAAK,CAAC,GAAGH,GAAGI,IAAI,CAAC;YAEjD,IAAIF,aAAa;gBACf,uDAAuD;gBACvD,IAAI,CAACA,YAAYG,QAAQ,CAAC,YAAY,CAACH,YAAYG,QAAQ,CAAC,WAAW;oBACrEH,cAAc,GAAGA,cACf,CAACA,YAAYG,QAAQ,CAAC,OAAO,MAAM,GACpC,MAAM,CAAC;gBACV;gBACAT,YAAYU,IAAI,CAACJ;YACnB;QACF;IACF;IACA,OAAON;AACT;AAEA;;;CAGC,GACD,SAASW,iCACPC,IAAc;IAEd,MAAMC,yBAAyB,IAAIC;IACnC,MAAMC,gBAAgBpB;IAEtB,IAAIoB,eAAe;QACjB,KAAK,MAAM,CAACC,MAAMC,aAAa,IAAIF,cAAe;YAChD,IAAI,mBAAmBE,cAAc;gBACnCJ,uBAAuBK,GAAG,CACxBF,MACAnB,iBAAiB,UAAYoB,aAAaE,aAAa,CAACP;YAE5D;QACF;IACF;IAEA,OAAOC;AACT;AAEA,OAAO,eAAeO,gBACpBC,IAAY,EACZtB,QAAgB,EAChBuB,mBAAqD;IAErD,MAAMV,OAAO,IAAIW;IAEjB,qEAAqE;IACrE,0DAA0D;IAC1D,0DAA0D;IAC1D,MAAMvB,cAAcF,eAAeuB;IACnC,KAAK,IAAIG,OAAOxB,YAAa;QAC3BwB,MAAM5B,eAAe,GAAGF,6BAA6B8B,KAAK;QAC1DZ,KAAKa,GAAG,CAACD;IACX;IAEA,4EAA4E;IAC5E,4DAA4D;IAC5D,IAAIzB,YAAa,CAAA,CAACuB,uBAAuBA,oBAAoBI,IAAI,KAAK,CAAA,GAAI;QACxE,MAAMF,MAAM5B,eAAe,GAAGF,6BAA6BK,UAAU;QACrEa,KAAKa,GAAG,CAACD;IACX;IAEA,IAAIZ,KAAKe,GAAG,CAAC,GAAGjC,2BAA2B,CAAC,CAAC,GAAG;QAC9CkB,KAAKa,GAAG,CAAC,GAAG/B,2BAA2B,MAAM,CAAC;IAChD;IAEA,IAAIkB,KAAKe,GAAG,CAAC,GAAGjC,2BAA2B,MAAM,CAAC,GAAG;QACnDkB,KAAKa,GAAG,CAAC,GAAG/B,2BAA2B,CAAC,CAAC;IAC3C;IAEA,MAAMkC,YAAYC,MAAMC,IAAI,CAAClB;IAC7B,OAAO;QACLA,MAAMgB;QACNf,wBAAwBF,iCAAiCiB;IAC3D;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/implicit-tags.ts"],"sourcesContent":["import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport { getCacheHandlerEntries } from '../use-cache/handlers'\nimport { encodeCacheTag } from './encode-cache-tag'\nimport { createLazyResult, type LazyResult } from './lazy-result'\n\nexport interface ImplicitTags {\n /**\n * For legacy usage, the implicit tags are passed to the incremental cache\n * handler in `get` calls.\n */\n readonly tags: string[]\n\n /**\n * Modern cache handlers don't receive implicit tags. Instead, the implicit\n * tags' expirations are stored in the work unit store, and used to compare\n * with a cache entry's timestamp.\n *\n * Note: This map contains lazy results so that we can evaluate them when the\n * first cache entry is read. It allows us to skip fetching the expiration\n * values if no caches are read at all.\n */\n readonly expirationsByCacheKind: Map<string, LazyResult<number>>\n}\n\nconst getDerivedTags = (pathname: string): string[] => {\n const derivedTags: string[] = [`/layout`]\n\n // we automatically add the current path segments as tags\n // for revalidatePath handling\n if (pathname.startsWith('/')) {\n let end = pathname.indexOf('/', 1)\n\n while (true) {\n if (end === -1) {\n end = pathname.length\n }\n\n let curPathname = pathname.slice(0, end)\n if (curPathname) {\n // all derived tags other than the page are layout tags\n if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {\n curPathname = `${curPathname}${\n !curPathname.endsWith('/') ? '/' : ''\n }layout`\n }\n derivedTags.push(curPathname)\n }\n\n if (end === pathname.length) {\n break\n }\n end = pathname.indexOf('/', end + 1)\n }\n }\n return derivedTags\n}\n\n/**\n * Creates a map with lazy results that fetch the expiration value for the given\n * tags and respective cache kind when they're awaited for the first time.\n */\nfunction createTagsExpirationsByCacheKind(\n tags: string[]\n): Map<string, LazyResult<number>> {\n const expirationsByCacheKind = new Map<string, LazyResult<number>>()\n const cacheHandlers = getCacheHandlerEntries()\n\n if (cacheHandlers) {\n for (const [kind, cacheHandler] of cacheHandlers) {\n if ('getExpiration' in cacheHandler) {\n expirationsByCacheKind.set(\n kind,\n createLazyResult(async () => cacheHandler.getExpiration(tags))\n )\n }\n }\n }\n\n return expirationsByCacheKind\n}\n\nexport async function getImplicitTags(\n page: string,\n pathname: string,\n fallbackRouteParams: null | OpaqueFallbackRouteParams\n): Promise<ImplicitTags> {\n const tags = new Set<string>()\n\n // Add the derived tags from the page. Encode each tag so a non-ASCII\n // pathname doesn't trip header validation when written to\n // `x-next-cache-tags`. Idempotent on already-ASCII input.\n const derivedTags = getDerivedTags(page)\n for (let tag of derivedTags) {\n tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`)\n tags.add(tag)\n }\n\n // Add the tags from the pathname. If the route has unknown params, we don't\n // want to add the pathname as a tag, as it will be invalid.\n if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {\n const tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`)\n tags.add(tag)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n const tagsArray = Array.from(tags)\n return {\n tags: tagsArray,\n expirationsByCacheKind: createTagsExpirationsByCacheKind(tagsArray),\n }\n}\n"],"names":["NEXT_CACHE_IMPLICIT_TAG_ID","getCacheHandlerEntries","encodeCacheTag","createLazyResult","getDerivedTags","pathname","derivedTags","startsWith","end","indexOf","length","curPathname","slice","endsWith","push","createTagsExpirationsByCacheKind","tags","expirationsByCacheKind","Map","cacheHandlers","kind","cacheHandler","set","getExpiration","getImplicitTags","page","fallbackRouteParams","Set","tag","add","size","has","tagsArray","Array","from"],"mappings":"AAAA,SAASA,0BAA0B,QAAQ,sBAAqB;AAEhE,SAASC,sBAAsB,QAAQ,wBAAuB;AAC9D,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,gBAAgB,QAAyB,gBAAe;AAqBjE,MAAMC,iBAAiB,CAACC;IACtB,MAAMC,cAAwB;QAAC,CAAC,OAAO,CAAC;KAAC;IAEzC,yDAAyD;IACzD,8BAA8B;IAC9B,IAAID,SAASE,UAAU,CAAC,MAAM;QAC5B,IAAIC,MAAMH,SAASI,OAAO,CAAC,KAAK;QAEhC,MAAO,KAAM;YACX,IAAID,QAAQ,CAAC,GAAG;gBACdA,MAAMH,SAASK,MAAM;YACvB;YAEA,IAAIC,cAAcN,SAASO,KAAK,CAAC,GAAGJ;YACpC,IAAIG,aAAa;gBACf,uDAAuD;gBACvD,I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AAIgB,KAAKe,GAAG,CAAC,GAAG/B,2BAA2B,MAAM,CAAC,GAAG;QACnDgB,KAAKa,GAAG,CAAC,GAAG7B,2BAA2B,CAAC,CAAC;IAC3C;IAEA,MAAMgC,YAAYC,MAAMC,IAAI,CAAClB;IAC7B,OAAO;QACLA,MAAMgB;QACNf,wBAAwBF,iCAAiCiB;IAC3D;AACF","ignoreList":[0]} |
@@ -22,2 +22,3 @@ // this must come first as it includes require hooks | ||
| import setupCompression from 'next/dist/compiled/compression'; | ||
| import { releaseCompressionStream } from './release-compression-stream'; | ||
| import { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'; | ||
@@ -203,2 +204,8 @@ import { isPostpone } from './router-utils/is-postpone'; | ||
| compress(req, res, ()=>{}); | ||
| // On client disconnect the middleware never ends its zlib stream, which | ||
| // then leaks past GC. See `releaseCompressionStream`. | ||
| res.once('close', ()=>{ | ||
| if (res.writableFinished) return; | ||
| releaseCompressionStream(res); | ||
| }); | ||
| } | ||
@@ -205,0 +212,0 @@ req.on('error', (_err)=>{ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/router-server.ts"],"sourcesContent":["// this must come first as it includes require hooks\nimport type { WorkerRequestHandler, WorkerUpgradeHandler } from './types'\nimport type { DevBundler, ServerFields } from './router-utils/setup-dev-bundler'\nimport type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta'\n\n// This is required before other imports to ensure the require hook is setup.\nimport '../node-environment'\nimport '../require-hook'\n\nimport url from 'url'\nimport path from 'path'\nimport loadConfig, { type ConfiguredExperimentalFeature } from '../config'\nimport { finalizeBundlerFromConfig, getBundlerFromEnv } from '../../lib/bundler'\nimport { serveStatic } from '../serve-static'\nimport setupDebug from 'next/dist/compiled/debug'\nimport * as Log from '../../build/output/log'\nimport { DecodeError } from '../../shared/lib/utils'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport { setupFsCheck } from './router-utils/filesystem'\nimport { proxyRequest } from './router-utils/proxy-request'\nimport { isAbortError, pipeToNodeResponse } from '../pipe-readable'\nimport { getResolveRoutes } from './router-utils/resolve-routes'\nimport { addRequestMeta, getRequestMeta } from '../request-meta'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport setupCompression from 'next/dist/compiled/compression'\nimport { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'\nimport { isPostpone } from './router-utils/is-postpone'\nimport { isNonHtmlSecFetchDest } from './is-non-html-sec-fetch-dest'\nimport { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url'\n\nimport {\n PHASE_PRODUCTION_SERVER,\n PHASE_DEVELOPMENT_SERVER,\n REQUEST_INSIGHTS_DEV_ENDPOINT,\n UNDERSCORE_NOT_FOUND_ROUTE,\n} from '../../shared/lib/constants'\nimport { RedirectStatusCode } from '../../client/components/redirect-status-code'\nimport { DevBundlerService } from './dev-bundler-service'\nimport { type Span, trace } from '../../trace'\nimport { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'\nimport { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { MockedResponse } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type AppIsrManifestMessage,\n} from '../dev/hot-reloader-types'\nimport { normalizedAssetPrefix } from '../../shared/lib/normalized-asset-prefix'\nimport { NEXT_PATCH_SYMBOL } from './patch-fetch'\nimport type { ServerInitResult } from './render-server'\nimport { filterInternalHeaders } from './server-ipc/utils'\nimport { blockCrossSiteDEV } from './router-utils/block-cross-site-dev'\nimport { traceGlobals } from '../../trace/shared'\nimport { NoFallbackError } from '../../shared/lib/no-fallback-error.external'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n} from './router-utils/router-server-context'\nimport {\n handleChromeDevtoolsWorkspaceRequest,\n isChromeDevtoolsWorkspaceUrl,\n} from './chrome-devtools-workspace'\nimport { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'\nimport {\n getRequestInsightsSnapshot,\n isRequestInsightsEnabled,\n} from './trace/request-insights'\n\nconst debug = setupDebug('next:router-server:main')\nconst isNextFont = (pathname: string | null) =>\n pathname && /\\/media\\/[^/]+\\.(woff|woff2|eot|ttf|otf)$/.test(pathname)\n\nexport type RenderServer = Pick<\n typeof import('./render-server'),\n | 'initialize'\n | 'clearModuleContext'\n | 'propagateServerField'\n | 'getServerField'\n>\n\nexport interface LazyRenderServerInstance {\n instance?: RenderServer\n}\n\nconst requestHandlers: Record<string, WorkerRequestHandler> = {}\n\nexport async function initialize(opts: {\n dir: string\n port: number\n dev: boolean\n onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined\n server?: import('http').Server\n minimalMode?: boolean\n hostname?: string\n keepAliveTimeout?: number\n customServer?: boolean\n experimentalHttpsServer?: boolean\n serverFastRefresh?: boolean\n startServerSpan?: Span\n quiet?: boolean\n}): Promise<ServerInitResult> {\n if (!process.env.NODE_ENV) {\n // @ts-ignore not readonly\n process.env.NODE_ENV = opts.dev ? 'development' : 'production'\n }\n\n // Capture the bundler before loading the config\n const bundlerBeforeConfig = opts.dev ? getBundlerFromEnv() : undefined\n\n let experimentalFeatures: ConfiguredExperimentalFeature[] = []\n const config = await loadConfig(\n opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,\n opts.dir,\n {\n silent: false,\n reportExperimentalFeatures(features) {\n experimentalFeatures = features.toSorted(({ key: a }, { key: b }) =>\n a.localeCompare(b)\n )\n },\n }\n )\n\n if (bundlerBeforeConfig !== undefined) {\n finalizeBundlerFromConfig(bundlerBeforeConfig)\n }\n\n let compress: ReturnType<typeof setupCompression> | undefined\n\n if (config?.compress !== false) {\n compress = setupCompression()\n }\n\n const fsChecker = await setupFsCheck({\n dev: opts.dev,\n dir: opts.dir,\n config,\n minimalMode: opts.minimalMode,\n })\n\n const renderServer: LazyRenderServerInstance = {}\n\n let development:\n | {\n bundler: DevBundler\n service: DevBundlerService\n config: NextConfigComplete\n }\n | undefined = undefined\n\n let originalFetch = globalThis.fetch\n\n if (opts.dev) {\n const { Telemetry } =\n require('../../telemetry/storage') as typeof import('../../telemetry/storage')\n\n const telemetry = new Telemetry({\n distDir: path.join(opts.dir, config.distDir),\n })\n traceGlobals.set('telemetry', telemetry)\n\n const { pagesDir, appDir } = findPagesDir(opts.dir)\n\n const { setupDevBundler } =\n require('./router-utils/setup-dev-bundler') as typeof import('./router-utils/setup-dev-bundler')\n\n const resetFetch = () => {\n globalThis.fetch = originalFetch\n ;(globalThis as Record<symbol, unknown>)[NEXT_PATCH_SYMBOL] = false\n }\n\n const setupDevBundlerSpan = opts.startServerSpan\n ? opts.startServerSpan.traceChild('setup-dev-bundler')\n : trace('setup-dev-bundler')\n\n // In development, it's always the complete config.\n let developmentConfig = config as NextConfigComplete\n\n // Resolve the effective serverFastRefresh value.\n // Both default to enabled (true). CLI takes precedence over config.\n const cliServerFastRefresh = opts.serverFastRefresh\n const configServerFastRefresh =\n developmentConfig.experimental?.turbopackServerFastRefresh\n let effectiveServerFastRefresh: boolean | undefined\n if (\n cliServerFastRefresh !== undefined &&\n configServerFastRefresh !== undefined &&\n cliServerFastRefresh !== configServerFastRefresh\n ) {\n Log.warn(\n `The CLI flag \"${cliServerFastRefresh === false ? '--no-server-fast-refresh' : '--server-fast-refresh'}\" conflicts with \"experimental.turbopackServerFastRefresh: ${configServerFastRefresh}\" in your Next.js config. The CLI flag will take precedence.`\n )\n effectiveServerFastRefresh = cliServerFastRefresh\n } else {\n // Default to true when neither CLI nor config specifies a value.\n effectiveServerFastRefresh =\n cliServerFastRefresh ?? configServerFastRefresh ?? true\n }\n\n let developmentBundler = await setupDevBundlerSpan.traceAsyncFn(() =>\n setupDevBundler({\n // Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks.\n renderServer,\n appDir,\n pagesDir,\n telemetry,\n fsChecker,\n dir: opts.dir,\n nextConfig: developmentConfig,\n isCustomServer: opts.customServer,\n turbo: !!process.env.TURBOPACK,\n port: opts.port,\n onDevServerCleanup: opts.onDevServerCleanup,\n resetFetch,\n serverFastRefresh: effectiveServerFastRefresh,\n })\n )\n\n let devBundlerService = new DevBundlerService(\n developmentBundler,\n // The request handler is assigned below, this allows us to create a lazy\n // reference to it.\n (req, res) => {\n return requestHandlers[opts.dir](req, res)\n },\n Boolean(developmentConfig.experimental.requestInsights)\n )\n\n development = {\n bundler: developmentBundler,\n service: devBundlerService,\n config: developmentConfig,\n }\n }\n\n renderServer.instance =\n require('./render-server') as typeof import('./render-server')\n\n const requestHandlerImpl: WorkerRequestHandler = async (req, res) => {\n addRequestMeta(req, 'relativeProjectDir', relativeProjectDir)\n\n // internal headers should not be honored by the request handler\n if (!process.env.NEXT_PRIVATE_TEST_HEADERS) {\n filterInternalHeaders(req.headers)\n }\n\n if (opts.dev && req.url) {\n if (config.experimental.requestInsights) {\n process.env.__NEXT_REQUEST_INSIGHTS = 'true'\n }\n\n const urlParts = req.url.split('?', 1)\n const pathname = removePathPrefix(urlParts[0] || '', config.basePath)\n\n if (pathname === REQUEST_INSIGHTS_DEV_ENDPOINT) {\n if (\n development &&\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n if (\n !config.experimental.requestInsights &&\n !isRequestInsightsEnabled()\n ) {\n res.statusCode = 404\n res.end(\n JSON.stringify({\n error:\n 'Request Insights is not enabled. Set experimental.requestInsights = true and restart next dev.',\n })\n )\n return\n }\n\n res.statusCode = 200\n res.end(JSON.stringify(getRequestInsightsSnapshot()))\n return\n }\n }\n\n if (\n !opts.minimalMode &&\n config.i18n &&\n config.i18n.localeDetection !== false\n ) {\n const urlParts = (req.url || '').split('?', 1)\n let urlNoQuery = urlParts[0] || ''\n\n if (config.basePath) {\n urlNoQuery = removePathPrefix(urlNoQuery, config.basePath)\n }\n\n const pathnameInfo = getNextPathnameInfo(urlNoQuery, {\n nextConfig: config,\n })\n\n const domainLocale = detectDomainLocale(\n config.i18n.domains,\n getHostname({ hostname: urlNoQuery }, req.headers)\n )\n\n const defaultLocale =\n domainLocale?.defaultLocale || config.i18n.defaultLocale\n\n const { getLocaleRedirect } =\n require('../../shared/lib/i18n/get-locale-redirect') as typeof import('../../shared/lib/i18n/get-locale-redirect')\n\n const parsedUrl = parseUrlUtil((req.url || '')?.replace(/^\\/+/, '/'))\n\n const redirect = getLocaleRedirect({\n defaultLocale,\n domainLocale,\n headers: req.headers,\n nextConfig: config,\n pathLocale: pathnameInfo.locale,\n urlParsed: {\n ...parsedUrl,\n pathname: pathnameInfo.locale\n ? `/${pathnameInfo.locale}${urlNoQuery}`\n : urlNoQuery,\n },\n })\n\n if (redirect) {\n res.setHeader('Location', redirect)\n res.statusCode = RedirectStatusCode.TemporaryRedirect\n res.end(redirect)\n return\n }\n }\n\n if (compress) {\n // @ts-expect-error not express req/res\n compress(req, res, () => {})\n }\n req.on('error', (_err) => {\n // TODO: log socket errors?\n })\n res.on('error', (_err) => {\n // TODO: log socket errors?\n })\n\n const invokedOutputs = new Set<string>()\n\n async function invokeRender(\n parsedUrl: NextUrlWithParsedQuery,\n invokePath: string,\n handleIndex: number,\n additionalRequestMeta?: RequestMeta\n ) {\n // invokeRender expects /api routes to not be locale prefixed\n // so normalize here before continuing\n if (\n config.i18n &&\n removePathPrefix(invokePath, config.basePath).startsWith(\n `/${getRequestMeta(req, 'locale')}/api`\n )\n ) {\n invokePath = fsChecker.handleLocale(\n removePathPrefix(invokePath, config.basePath)\n ).pathname\n }\n\n if (\n req.headers['x-nextjs-data'] &&\n fsChecker.getMiddlewareMatchers()?.length &&\n removePathPrefix(invokePath, config.basePath) === '/404'\n ) {\n res.setHeader('x-nextjs-matched-path', parsedUrl.pathname || '')\n res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end('{}')\n return null\n }\n\n if (!handlers) {\n throw new Error('Failed to initialize render server')\n }\n\n addRequestMeta(req, 'invokePath', invokePath)\n addRequestMeta(req, 'invokeQuery', parsedUrl.query)\n addRequestMeta(req, 'middlewareInvoke', false)\n\n for (const key in additionalRequestMeta || {}) {\n addRequestMeta(\n req,\n key as keyof RequestMeta,\n additionalRequestMeta![key as keyof RequestMeta]\n )\n }\n\n debug('invokeRender', req.url, req.headers)\n\n try {\n const initResult =\n await renderServer?.instance?.initialize(renderServerOpts)\n try {\n await initResult?.requestHandler(req, res)\n } catch (err) {\n if (err instanceof NoFallbackError) {\n await handleRequest(handleIndex + 1)\n return\n }\n throw err\n }\n return\n } catch (e) {\n // If the client aborts before we can receive a response object (when\n // the headers are flushed), then we can early exit without further\n // processing.\n if (isAbortError(e)) {\n return\n }\n throw e\n }\n }\n\n const handleRequest = async (handleIndex: number) => {\n if (handleIndex > 5) {\n throw new Error(`Attempted to handle request too many times ${req.url}`)\n }\n\n // handle hot-reloader first\n if (development) {\n if (\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n const origUrl = req.url || '/'\n\n // both the basePath and assetPrefix need to be stripped from the URL\n // so that the development bundler can find the correct file\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n const parsedUrl = parseUrlUtil(req.url || '/')\n\n const hotReloaderResult = await development.bundler.hotReloader.run(\n req,\n res,\n parsedUrl\n )\n\n if (hotReloaderResult.finished) {\n return hotReloaderResult\n }\n\n req.url = origUrl\n }\n\n const {\n finished,\n parsedUrl,\n statusCode,\n resHeaders,\n bodyStream,\n matchedOutput,\n } = await resolveRoutes({\n req,\n res,\n isUpgradeReq: false,\n signal: signalFromNodeResponse(res),\n invokedOutputs,\n })\n\n if (res.closed || res.finished) {\n return\n }\n\n if (development && matchedOutput?.type === 'devVirtualFsItem') {\n const origUrl = req.url || '/'\n\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n const result = await development.bundler.requestHandler(req, res)\n\n if (result.finished) {\n return\n }\n // TODO: throw invariant if we resolved to this but it wasn't handled?\n req.url = origUrl\n }\n\n debug('requestHandler!', req.url, {\n matchedOutput,\n statusCode,\n resHeaders,\n bodyStream: !!bodyStream,\n parsedUrl: {\n pathname: parsedUrl.pathname,\n query: parsedUrl.query,\n },\n finished,\n })\n\n // apply any response headers from routing\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n\n // handle redirect\n if (!bodyStream && statusCode && statusCode > 300 && statusCode < 400) {\n const destination = url.format(parsedUrl)\n res.statusCode = statusCode\n res.setHeader('location', destination)\n\n if (statusCode === RedirectStatusCode.PermanentRedirect) {\n res.setHeader('Refresh', `0;url=${destination}`)\n }\n return res.end(destination)\n }\n\n // handle middleware body response\n if (bodyStream) {\n res.statusCode = statusCode || 200\n return await pipeToNodeResponse(bodyStream, res)\n }\n\n if (finished && parsedUrl.protocol) {\n return await proxyRequest(\n req,\n res,\n parsedUrl,\n undefined,\n getRequestMeta(req, 'clonableBody')?.cloneBodyStream(),\n config.experimental.proxyTimeout\n )\n }\n\n if (matchedOutput?.fsPath && matchedOutput.itemPath) {\n if (\n opts.dev &&\n (fsChecker.appFiles.has(matchedOutput.itemPath) ||\n fsChecker.pageFiles.has(matchedOutput.itemPath))\n ) {\n res.statusCode = 500\n const message = `A conflicting public file and page file was found for path ${matchedOutput.itemPath} https://nextjs.org/docs/messages/conflicting-public-file-page`\n await invokeRender(parsedUrl, '/_error', handleIndex, {\n invokeStatus: 500,\n invokeError: new Error(message),\n })\n Log.error(message)\n return\n }\n\n if (\n !res.getHeader('cache-control') &&\n matchedOutput.type === 'nextStaticFolder'\n ) {\n if (matchedOutput.itemPath.startsWith('/service-worker/')) {\n res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate')\n res.setHeader('Service-Worker-Allowed', config.basePath || '/')\n } else if (opts.dev && !isNextFont(parsedUrl.pathname)) {\n res.setHeader('Cache-Control', 'no-cache, must-revalidate')\n } else {\n res.setHeader(\n 'Cache-Control',\n 'public, max-age=31536000, immutable'\n )\n }\n }\n if (!(req.method === 'GET' || req.method === 'HEAD')) {\n res.setHeader('Allow', ['GET', 'HEAD'])\n res.statusCode = 405\n return await invokeRender(parseUrlUtil('/405'), '/405', handleIndex, {\n invokeStatus: 405,\n })\n }\n\n try {\n return await serveStatic(req, res, matchedOutput.itemPath, {\n root: matchedOutput.itemsRoot,\n // Ensures that etags are not generated for static files when disabled.\n etag: config.generateEtags,\n })\n } catch (err: any) {\n /**\n * Hardcoded every possible error status code that could be thrown by \"serveStatic\" method\n * This is done by searching \"this.error\" inside \"send\" module's source code:\n * https://github.com/pillarjs/send/blob/master/index.js\n * https://github.com/pillarjs/send/blob/develop/index.js\n */\n const POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC = new Set([\n // send module will throw 500 when header is already sent or fs.stat error happens\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L392\n // Note: we will use Next.js built-in 500 page to handle 500 errors\n // 500,\n\n // send module will throw 404 when file is missing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L421\n // Note: we will use Next.js built-in 404 page to handle 404 errors\n // 404,\n\n // send module will throw 403 when redirecting to a directory without enabling directory listing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L484\n // Note: Next.js throws a different error (without status code) for directory listing\n // 403,\n\n // send module will throw 400 when fails to normalize the path\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L520\n 400,\n\n // send module will throw 412 with conditional GET request\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L632\n 412,\n\n // send module will throw 416 when range is not satisfiable\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L669\n 416,\n ])\n\n let validErrorStatus = POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC.has(\n err.statusCode\n )\n\n // normalize non-allowed status codes\n if (!validErrorStatus) {\n ;(err as any).statusCode = 400\n }\n\n if (typeof err.statusCode === 'number') {\n const invokePath = `/${err.statusCode}`\n const invokeStatus = err.statusCode\n res.statusCode = err.statusCode\n return await invokeRender(\n parseUrlUtil(invokePath),\n invokePath,\n handleIndex,\n {\n invokeStatus,\n }\n )\n }\n throw err\n }\n }\n\n if (matchedOutput) {\n invokedOutputs.add(matchedOutput.itemPath)\n\n return await invokeRender(\n parsedUrl,\n parsedUrl.pathname || '/',\n handleIndex,\n {\n invokeOutput: matchedOutput.itemPath,\n }\n )\n }\n\n // We want the original pathname without any basePath or proxy rewrites.\n if (development && isChromeDevtoolsWorkspaceUrl(req.url)) {\n await handleChromeDevtoolsWorkspaceRequest(res, opts, config)\n return\n }\n\n // 404 case\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n\n let realRequestPathname = parsedUrl.pathname ?? ''\n if (realRequestPathname) {\n if (config.basePath) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.basePath\n )\n }\n if (config.assetPrefix) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.assetPrefix\n )\n }\n if (config.i18n) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n '/' + (getRequestMeta(req, 'locale') ?? '')\n )\n }\n }\n // For not found static assets, return plain text 404 instead of\n // full HTML 404 pages to save bandwidth.\n if (realRequestPathname.startsWith('/_next/static/')) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // For subresource requests (e.g. images or fonts), return plain text\n // 404 instead of rendering the not-found route.\n if (\n (req.method === 'GET' || req.method === 'HEAD') &&\n isNonHtmlSecFetchDest(req.headers['sec-fetch-dest'])\n ) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // Short-circuit favicon.ico serving so that the 404 page doesn't get built as favicon is requested by the browser when loading any route.\n if (opts.dev && !matchedOutput && parsedUrl.pathname === '/favicon.ico') {\n res.statusCode = 404\n res.end('')\n return null\n }\n\n const appNotFound = opts.dev\n ? development?.bundler?.serverFields.hasAppNotFound\n : await fsChecker.getItem(UNDERSCORE_NOT_FOUND_ROUTE)\n\n res.statusCode = 404\n\n if (appNotFound) {\n return await invokeRender(\n parsedUrl,\n UNDERSCORE_NOT_FOUND_ROUTE,\n handleIndex,\n {\n invokeStatus: 404,\n }\n )\n }\n\n await invokeRender(parsedUrl, '/404', handleIndex, {\n invokeStatus: 404,\n })\n }\n\n try {\n await handleRequest(0)\n } catch (err) {\n try {\n let invokePath = '/500'\n let invokeStatus = '500'\n\n if (err instanceof DecodeError) {\n invokePath = '/400'\n invokeStatus = '400'\n } else {\n console.error(err)\n }\n res.statusCode = Number(invokeStatus)\n return await invokeRender(parseUrlUtil(invokePath), invokePath, 0, {\n invokeStatus: res.statusCode,\n })\n } catch (err2) {\n console.error(err2)\n }\n res.statusCode = 500\n res.end('Internal Server Error')\n }\n }\n\n let requestHandler: WorkerRequestHandler = requestHandlerImpl\n if (config.experimental.testProxy) {\n // Intercept fetch and other testmode apis.\n const { wrapRequestHandlerWorker, interceptTestApis } =\n // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n require('next/dist/experimental/testmode/server') as typeof import('../../experimental/testmode/server')\n requestHandler = wrapRequestHandlerWorker(requestHandler)\n interceptTestApis()\n // We treat the intercepted fetch as \"original\" fetch that should be reset to during HMR.\n originalFetch = globalThis.fetch\n }\n requestHandlers[opts.dir] = requestHandler\n\n const renderServerOpts: Parameters<RenderServer['initialize']>[0] = {\n port: opts.port,\n dir: opts.dir,\n hostname: opts.hostname,\n minimalMode: opts.minimalMode,\n dev: !!opts.dev,\n server: opts.server,\n serverFields: {\n ...(development?.bundler?.serverFields || {}),\n setIsrStatus: development?.service?.setIsrStatus.bind(\n development?.service\n ),\n } satisfies ServerFields,\n experimentalTestProxy: !!config.experimental.testProxy,\n experimentalHttpsServer: !!opts.experimentalHttpsServer,\n bundlerService: development?.service,\n startServerSpan: opts.startServerSpan,\n quiet: opts.quiet,\n onDevServerCleanup: opts.onDevServerCleanup,\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n }\n renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl\n\n // pre-initialize workers\n const handlers = await renderServer.instance.initialize(renderServerOpts)\n\n // this must come after initialize of render server since it's\n // using initialized methods\n if (!routerServerGlobal[RouterServerContextSymbol]) {\n routerServerGlobal[RouterServerContextSymbol] = {}\n }\n const relativeProjectDir = path.relative(process.cwd(), opts.dir)\n\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {\n nextConfig: getNextConfigRuntime(config),\n hostname: handlers.server.hostname,\n revalidate: handlers.server.revalidate.bind(handlers.server),\n render404: handlers.server.render404.bind(handlers.server),\n experimentalTestProxy: renderServerOpts.experimentalTestProxy,\n logErrorWithOriginalStack: opts.dev\n ? handlers.server.logErrorWithOriginalStack.bind(handlers.server)\n : (err: unknown) => !opts.quiet && Log.error(err),\n setCacheStatus: config.cacheComponents\n ? development?.service?.setCacheStatus.bind(development?.service)\n : undefined,\n setIsrStatus: development?.service?.setIsrStatus.bind(development?.service),\n setReactDebugChannel: development?.config.experimental.reactDebugChannel\n ? development?.service?.setReactDebugChannel.bind(development?.service)\n : undefined,\n sendErrorsToBrowser: development?.service?.sendErrorsToBrowser.bind(\n development?.service\n ),\n }\n\n const logError = async (\n type: 'uncaughtException' | 'unhandledRejection',\n err: Error | undefined\n ) => {\n if (isPostpone(err)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n if (type === 'unhandledRejection') {\n Log.error('unhandledRejection: ', err)\n } else if (type === 'uncaughtException') {\n Log.error('uncaughtException: ', err)\n }\n }\n\n process.on('uncaughtException', logError.bind(null, 'uncaughtException'))\n process.on('unhandledRejection', logError.bind(null, 'unhandledRejection'))\n\n const resolveRoutes = getResolveRoutes(\n fsChecker,\n config,\n opts,\n renderServer.instance,\n renderServerOpts,\n development?.bundler?.ensureMiddleware\n )\n\n const upgradeHandler: WorkerUpgradeHandler = async (req, socket, head) => {\n try {\n req.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n socket.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n\n if (opts.dev && development && req.url) {\n if (\n blockCrossSiteDEV(\n req,\n socket,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n const { basePath, assetPrefix } = config\n\n let hmrPrefix = basePath\n\n // assetPrefix overrides basePath for HMR path\n if (assetPrefix) {\n hmrPrefix = normalizedAssetPrefix(assetPrefix)\n\n if (URL.canParse(hmrPrefix)) {\n // remove trailing slash from pathname\n // return empty string if pathname is '/'\n // to avoid conflicts with '/_next' below\n hmrPrefix = new URL(hmrPrefix).pathname.replace(/\\/$/, '')\n }\n }\n\n const isHMRRequest = req.url.startsWith(\n ensureLeadingSlash(`${hmrPrefix}/_next/hmr`)\n )\n\n // only handle HMR requests if the basePath in the request\n // matches the basePath for the handler responding to the request\n if (isHMRRequest) {\n return development.bundler.hotReloader.onHMR(\n req,\n socket,\n head,\n (client, { isLegacyClient }) => {\n if (isLegacyClient) {\n // Only send the ISR manifest to legacy clients, i.e. Pages\n // Router clients, or App Router clients that have Cache\n // Components disabled. The ISR manifest is only used to inform\n // the static indicator, which currently does not provide useful\n // information if Cache Components is enabled due to its binary\n // nature (i.e. it does not support showing info for partially\n // static pages).\n client.send(\n JSON.stringify({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: development.service?.appIsrManifest || {},\n } satisfies AppIsrManifestMessage)\n )\n }\n }\n )\n }\n }\n\n const res = new MockedResponse({\n resWriter: () => {\n throw new Error(\n 'Invariant: did not expect response writer to be written to for upgrade request'\n )\n },\n })\n const { finished, matchedOutput, parsedUrl, statusCode } =\n await resolveRoutes({\n req,\n res,\n isUpgradeReq: true,\n signal: signalFromNodeResponse(socket),\n })\n\n // TODO: allow upgrade requests to pages/app paths?\n // this was not previously supported\n if (matchedOutput) {\n return socket.end()\n }\n\n if (finished && parsedUrl.protocol) {\n if (!statusCode) {\n return await proxyRequest(req, socket, parsedUrl, head)\n }\n\n return socket.end()\n }\n\n // If there's no matched output, we don't handle the request as user's\n // custom WS server may be listening on the same path.\n } catch (err) {\n console.error('Error handling upgrade request', err)\n socket.end()\n }\n }\n\n return {\n requestHandler,\n upgradeHandler,\n server: handlers.server,\n closeUpgraded() {\n development?.bundler?.hotReloader?.close()\n },\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n agentRules: config.agentRules,\n }\n}\n"],"names":["url","path","loadConfig","finalizeBundlerFromConfig","getBundlerFromEnv","serveStatic","setupDebug","Log","DecodeError","findPagesDir","setupFsCheck","proxyRequest","isAbortError","pipeToNodeResponse","getResolveRoutes","addRequestMeta","getRequestMeta","pathHasPrefix","removePathPrefix","setupCompression","signalFromNodeResponse","isPostpone","isNonHtmlSecFetchDest","parseUrl","parseUrlUtil","PHASE_PRODUCTION_SERVER","PHASE_DEVELOPMENT_SERVER","REQUEST_INSIGHTS_DEV_ENDPOINT","UNDERSCORE_NOT_FOUND_ROUTE","RedirectStatusCode","DevBundlerService","trace","ensureLeadingSlash","getNextPathnameInfo","getHostname","detectDomainLocale","MockedResponse","HMR_MESSAGE_SENT_TO_BROWSER","normalizedAssetPrefix","NEXT_PATCH_SYMBOL","filterInternalHeaders","blockCrossSiteDEV","traceGlobals","NoFallbackError","RouterServerContextSymbol","routerServerGlobal","handleChromeDevtoolsWorkspaceRequest","isChromeDevtoolsWorkspaceUrl","getNextConfigRuntime","getRequestInsightsSnapshot","isRequestInsightsEnabled","debug","isNextFont","pathname","test","requestHandlers","initialize","opts","development","process","env","NODE_ENV","dev","bundlerBeforeConfig","undefined","experimentalFeatures","config","dir","silent","reportExperimentalFeatures","features","toSorted","key","a","b","localeCompare","compress","fsChecker","minimalMode","renderServer","originalFetch","globalThis","fetch","developmentConfig","Telemetry","require","telemetry","distDir","join","set","pagesDir","appDir","setupDevBundler","resetFetch","setupDevBundlerSpan","startServerSpan","traceChild","cliServerFastRefresh","serverFastRefresh","configServerFastRefresh","experimental","turbopackServerFastRefresh","effectiveServerFastRefresh","warn","developmentBundler","traceAsyncFn","nextConfig","isCustomServer","customServer","turbo","TURBOPACK","port","onDevServerCleanup","devBundlerService","req","res","Boolean","requestInsights","bundler","service","instance","requestHandlerImpl","relativeProjectDir","NEXT_PRIVATE_TEST_HEADERS","headers","__NEXT_REQUEST_INSIGHTS","urlParts","split","basePath","allowedDevOrigins","hostname","setHeader","statusCode","end","JSON","stringify","error","i18n","localeDetection","urlNoQuery","pathnameInfo","domainLocale","domains","defaultLocale","getLocaleRedirect","parsedUrl","replace","redirect","pathLocale","locale","urlParsed","TemporaryRedirect","on","_err","invokedOutputs","Set","invokeRender","invokePath","handleIndex","additionalRequestMeta","startsWith","handleLocale","getMiddlewareMatchers","length","handlers","Error","query","initResult","renderServerOpts","requestHandler","err","handleRequest","e","origUrl","assetPrefix","hotReloaderResult","hotReloader","run","finished","resHeaders","bodyStream","matchedOutput","resolveRoutes","isUpgradeReq","signal","closed","type","Object","keys","result","destination","format","PermanentRedirect","protocol","cloneBodyStream","proxyTimeout","fsPath","itemPath","appFiles","has","pageFiles","message","invokeStatus","invokeError","getHeader","method","root","itemsRoot","etag","generateEtags","POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC","validErrorStatus","add","invokeOutput","realRequestPathname","appNotFound","serverFields","hasAppNotFound","getItem","console","Number","err2","testProxy","wrapRequestHandlerWorker","interceptTestApis","server","setIsrStatus","bind","experimentalTestProxy","experimentalHttpsServer","bundlerService","quiet","cacheComponents","partialPrefetching","routerServerHandler","relative","cwd","revalidate","render404","logErrorWithOriginalStack","setCacheStatus","setReactDebugChannel","reactDebugChannel","sendErrorsToBrowser","logError","ensureMiddleware","upgradeHandler","socket","head","hmrPrefix","URL","canParse","isHMRRequest","onHMR","client","isLegacyClient","send","ISR_MANIFEST","data","appIsrManifest","resWriter","closeUpgraded","close","agentRules"],"mappings":"AAAA,oDAAoD;AAKpD,6EAA6E;AAC7E,OAAO,sBAAqB;AAC5B,OAAO,kBAAiB;AAExB,OAAOA,SAAS,MAAK;AACrB,OAAOC,UAAU,OAAM;AACvB,OAAOC,gBAAwD,YAAW;AAC1E,SAASC,yBAAyB,EAAEC,iBAAiB,QAAQ,oBAAmB;AAChF,SAASC,WAAW,QAAQ,kBAAiB;AAC7C,OAAOC,gBAAgB,2BAA0B;AACjD,YAAYC,SAAS,yBAAwB;AAC7C,SAASC,WAAW,QAAQ,yBAAwB;AACpD,SAASC,YAAY,QAAQ,2BAA0B;AACvD,SAASC,YAAY,QAAQ,4BAA2B;AACxD,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,YAAY,EAAEC,kBAAkB,QAAQ,mBAAkB;AACnE,SAASC,gBAAgB,QAAQ,gCAA+B;AAChE,SAASC,cAAc,EAAEC,cAAc,QAAQ,kBAAiB;AAChE,SAASC,aAAa,QAAQ,gDAA+C;AAC7E,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,OAAOC,sBAAsB,iCA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kD,cAAc;gBAClBpE;gBACAC;gBACAoE,cAAc;gBACdC,QAAQpK,uBAAuBmO;YACjC;YAEF,mDAAmD;YACnD,oCAAoC;YACpC,IAAIlE,eAAe;gBACjB,OAAOkE,OAAOlH,GAAG;YACnB;YAEA,IAAI6C,YAAYjC,UAAUgD,QAAQ,EAAE;gBAClC,IAAI,CAAC7D,YAAY;oBACf,OAAO,MAAMzH,aAAauG,KAAKqI,QAAQtG,WAAWuG;gBACpD;gBAEA,OAAOD,OAAOlH,GAAG;YACnB;QAEA,sEAAsE;QACtE,sDAAsD;QACxD,EAAE,OAAOqC,KAAK;YACZiD,QAAQnF,KAAK,CAAC,kCAAkCkC;YAChD6E,OAAOlH,GAAG;QACZ;IACF;IAEA,OAAO;QACLoC;QACA6E;QACArB,QAAQ7D,SAAS6D,MAAM;QACvBoC;gBACE3M,kCAAAA;YAAAA,gCAAAA,uBAAAA,YAAa4D,OAAO,sBAApB5D,mCAAAA,qBAAsBsH,WAAW,qBAAjCtH,iCAAmC4M,KAAK;QAC1C;QACA/K,SAASrB,OAAOqB,OAAO;QACvBtB;QACAuK,iBAAiBtK,OAAOsK,eAAe;QACvCC,oBAAoBvK,OAAOuK,kBAAkB;QAC7C8B,YAAYrM,OAAOqM,UAAU;IAC/B;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/router-server.ts"],"sourcesContent":["// this must come first as it includes require hooks\nimport type { WorkerRequestHandler, WorkerUpgradeHandler } from './types'\nimport type { DevBundler, ServerFields } from './router-utils/setup-dev-bundler'\nimport type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta'\n\n// This is required before other imports to ensure the require hook is setup.\nimport '../node-environment'\nimport '../require-hook'\n\nimport url from 'url'\nimport path from 'path'\nimport loadConfig, { type ConfiguredExperimentalFeature } from '../config'\nimport { finalizeBundlerFromConfig, getBundlerFromEnv } from '../../lib/bundler'\nimport { serveStatic } from '../serve-static'\nimport setupDebug from 'next/dist/compiled/debug'\nimport * as Log from '../../build/output/log'\nimport { DecodeError } from '../../shared/lib/utils'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport { setupFsCheck } from './router-utils/filesystem'\nimport { proxyRequest } from './router-utils/proxy-request'\nimport { isAbortError, pipeToNodeResponse } from '../pipe-readable'\nimport { getResolveRoutes } from './router-utils/resolve-routes'\nimport { addRequestMeta, getRequestMeta } from '../request-meta'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport setupCompression from 'next/dist/compiled/compression'\nimport { releaseCompressionStream } from './release-compression-stream'\nimport { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'\nimport { isPostpone } from './router-utils/is-postpone'\nimport { isNonHtmlSecFetchDest } from './is-non-html-sec-fetch-dest'\nimport { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url'\n\nimport {\n PHASE_PRODUCTION_SERVER,\n PHASE_DEVELOPMENT_SERVER,\n REQUEST_INSIGHTS_DEV_ENDPOINT,\n UNDERSCORE_NOT_FOUND_ROUTE,\n} from '../../shared/lib/constants'\nimport { RedirectStatusCode } from '../../client/components/redirect-status-code'\nimport { DevBundlerService } from './dev-bundler-service'\nimport { type Span, trace } from '../../trace'\nimport { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'\nimport { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { MockedResponse } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type AppIsrManifestMessage,\n} from '../dev/hot-reloader-types'\nimport { normalizedAssetPrefix } from '../../shared/lib/normalized-asset-prefix'\nimport { NEXT_PATCH_SYMBOL } from './patch-fetch'\nimport type { ServerInitResult } from './render-server'\nimport { filterInternalHeaders } from './server-ipc/utils'\nimport { blockCrossSiteDEV } from './router-utils/block-cross-site-dev'\nimport { traceGlobals } from '../../trace/shared'\nimport { NoFallbackError } from '../../shared/lib/no-fallback-error.external'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n} from './router-utils/router-server-context'\nimport {\n handleChromeDevtoolsWorkspaceRequest,\n isChromeDevtoolsWorkspaceUrl,\n} from './chrome-devtools-workspace'\nimport { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'\nimport {\n getRequestInsightsSnapshot,\n isRequestInsightsEnabled,\n} from './trace/request-insights'\n\nconst debug = setupDebug('next:router-server:main')\nconst isNextFont = (pathname: string | null) =>\n pathname && /\\/media\\/[^/]+\\.(woff|woff2|eot|ttf|otf)$/.test(pathname)\n\nexport type RenderServer = Pick<\n typeof import('./render-server'),\n | 'initialize'\n | 'clearModuleContext'\n | 'propagateServerField'\n | 'getServerField'\n>\n\nexport interface LazyRenderServerInstance {\n instance?: RenderServer\n}\n\nconst requestHandlers: Record<string, WorkerRequestHandler> = {}\n\nexport async function initialize(opts: {\n dir: string\n port: number\n dev: boolean\n onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined\n server?: import('http').Server\n minimalMode?: boolean\n hostname?: string\n keepAliveTimeout?: number\n customServer?: boolean\n experimentalHttpsServer?: boolean\n serverFastRefresh?: boolean\n startServerSpan?: Span\n quiet?: boolean\n}): Promise<ServerInitResult> {\n if (!process.env.NODE_ENV) {\n // @ts-ignore not readonly\n process.env.NODE_ENV = opts.dev ? 'development' : 'production'\n }\n\n // Capture the bundler before loading the config\n const bundlerBeforeConfig = opts.dev ? getBundlerFromEnv() : undefined\n\n let experimentalFeatures: ConfiguredExperimentalFeature[] = []\n const config = await loadConfig(\n opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,\n opts.dir,\n {\n silent: false,\n reportExperimentalFeatures(features) {\n experimentalFeatures = features.toSorted(({ key: a }, { key: b }) =>\n a.localeCompare(b)\n )\n },\n }\n )\n\n if (bundlerBeforeConfig !== undefined) {\n finalizeBundlerFromConfig(bundlerBeforeConfig)\n }\n\n let compress: ReturnType<typeof setupCompression> | undefined\n\n if (config?.compress !== false) {\n compress = setupCompression()\n }\n\n const fsChecker = await setupFsCheck({\n dev: opts.dev,\n dir: opts.dir,\n config,\n minimalMode: opts.minimalMode,\n })\n\n const renderServer: LazyRenderServerInstance = {}\n\n let development:\n | {\n bundler: DevBundler\n service: DevBundlerService\n config: NextConfigComplete\n }\n | undefined = undefined\n\n let originalFetch = globalThis.fetch\n\n if (opts.dev) {\n const { Telemetry } =\n require('../../telemetry/storage') as typeof import('../../telemetry/storage')\n\n const telemetry = new Telemetry({\n distDir: path.join(opts.dir, config.distDir),\n })\n traceGlobals.set('telemetry', telemetry)\n\n const { pagesDir, appDir } = findPagesDir(opts.dir)\n\n const { setupDevBundler } =\n require('./router-utils/setup-dev-bundler') as typeof import('./router-utils/setup-dev-bundler')\n\n const resetFetch = () => {\n globalThis.fetch = originalFetch\n ;(globalThis as Record<symbol, unknown>)[NEXT_PATCH_SYMBOL] = false\n }\n\n const setupDevBundlerSpan = opts.startServerSpan\n ? opts.startServerSpan.traceChild('setup-dev-bundler')\n : trace('setup-dev-bundler')\n\n // In development, it's always the complete config.\n let developmentConfig = config as NextConfigComplete\n\n // Resolve the effective serverFastRefresh value.\n // Both default to enabled (true). CLI takes precedence over config.\n const cliServerFastRefresh = opts.serverFastRefresh\n const configServerFastRefresh =\n developmentConfig.experimental?.turbopackServerFastRefresh\n let effectiveServerFastRefresh: boolean | undefined\n if (\n cliServerFastRefresh !== undefined &&\n configServerFastRefresh !== undefined &&\n cliServerFastRefresh !== configServerFastRefresh\n ) {\n Log.warn(\n `The CLI flag \"${cliServerFastRefresh === false ? '--no-server-fast-refresh' : '--server-fast-refresh'}\" conflicts with \"experimental.turbopackServerFastRefresh: ${configServerFastRefresh}\" in your Next.js config. The CLI flag will take precedence.`\n )\n effectiveServerFastRefresh = cliServerFastRefresh\n } else {\n // Default to true when neither CLI nor config specifies a value.\n effectiveServerFastRefresh =\n cliServerFastRefresh ?? configServerFastRefresh ?? true\n }\n\n let developmentBundler = await setupDevBundlerSpan.traceAsyncFn(() =>\n setupDevBundler({\n // Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks.\n renderServer,\n appDir,\n pagesDir,\n telemetry,\n fsChecker,\n dir: opts.dir,\n nextConfig: developmentConfig,\n isCustomServer: opts.customServer,\n turbo: !!process.env.TURBOPACK,\n port: opts.port,\n onDevServerCleanup: opts.onDevServerCleanup,\n resetFetch,\n serverFastRefresh: effectiveServerFastRefresh,\n })\n )\n\n let devBundlerService = new DevBundlerService(\n developmentBundler,\n // The request handler is assigned below, this allows us to create a lazy\n // reference to it.\n (req, res) => {\n return requestHandlers[opts.dir](req, res)\n },\n Boolean(developmentConfig.experimental.requestInsights)\n )\n\n development = {\n bundler: developmentBundler,\n service: devBundlerService,\n config: developmentConfig,\n }\n }\n\n renderServer.instance =\n require('./render-server') as typeof import('./render-server')\n\n const requestHandlerImpl: WorkerRequestHandler = async (req, res) => {\n addRequestMeta(req, 'relativeProjectDir', relativeProjectDir)\n\n // internal headers should not be honored by the request handler\n if (!process.env.NEXT_PRIVATE_TEST_HEADERS) {\n filterInternalHeaders(req.headers)\n }\n\n if (opts.dev && req.url) {\n if (config.experimental.requestInsights) {\n process.env.__NEXT_REQUEST_INSIGHTS = 'true'\n }\n\n const urlParts = req.url.split('?', 1)\n const pathname = removePathPrefix(urlParts[0] || '', config.basePath)\n\n if (pathname === REQUEST_INSIGHTS_DEV_ENDPOINT) {\n if (\n development &&\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n if (\n !config.experimental.requestInsights &&\n !isRequestInsightsEnabled()\n ) {\n res.statusCode = 404\n res.end(\n JSON.stringify({\n error:\n 'Request Insights is not enabled. Set experimental.requestInsights = true and restart next dev.',\n })\n )\n return\n }\n\n res.statusCode = 200\n res.end(JSON.stringify(getRequestInsightsSnapshot()))\n return\n }\n }\n\n if (\n !opts.minimalMode &&\n config.i18n &&\n config.i18n.localeDetection !== false\n ) {\n const urlParts = (req.url || '').split('?', 1)\n let urlNoQuery = urlParts[0] || ''\n\n if (config.basePath) {\n urlNoQuery = removePathPrefix(urlNoQuery, config.basePath)\n }\n\n const pathnameInfo = getNextPathnameInfo(urlNoQuery, {\n nextConfig: config,\n })\n\n const domainLocale = detectDomainLocale(\n config.i18n.domains,\n getHostname({ hostname: urlNoQuery }, req.headers)\n )\n\n const defaultLocale =\n domainLocale?.defaultLocale || config.i18n.defaultLocale\n\n const { getLocaleRedirect } =\n require('../../shared/lib/i18n/get-locale-redirect') as typeof import('../../shared/lib/i18n/get-locale-redirect')\n\n const parsedUrl = parseUrlUtil((req.url || '')?.replace(/^\\/+/, '/'))\n\n const redirect = getLocaleRedirect({\n defaultLocale,\n domainLocale,\n headers: req.headers,\n nextConfig: config,\n pathLocale: pathnameInfo.locale,\n urlParsed: {\n ...parsedUrl,\n pathname: pathnameInfo.locale\n ? `/${pathnameInfo.locale}${urlNoQuery}`\n : urlNoQuery,\n },\n })\n\n if (redirect) {\n res.setHeader('Location', redirect)\n res.statusCode = RedirectStatusCode.TemporaryRedirect\n res.end(redirect)\n return\n }\n }\n\n if (compress) {\n // @ts-expect-error not express req/res\n compress(req, res, () => {})\n\n // On client disconnect the middleware never ends its zlib stream, which\n // then leaks past GC. See `releaseCompressionStream`.\n res.once('close', () => {\n if (res.writableFinished) return\n\n releaseCompressionStream(res)\n })\n }\n req.on('error', (_err) => {\n // TODO: log socket errors?\n })\n res.on('error', (_err) => {\n // TODO: log socket errors?\n })\n\n const invokedOutputs = new Set<string>()\n\n async function invokeRender(\n parsedUrl: NextUrlWithParsedQuery,\n invokePath: string,\n handleIndex: number,\n additionalRequestMeta?: RequestMeta\n ) {\n // invokeRender expects /api routes to not be locale prefixed\n // so normalize here before continuing\n if (\n config.i18n &&\n removePathPrefix(invokePath, config.basePath).startsWith(\n `/${getRequestMeta(req, 'locale')}/api`\n )\n ) {\n invokePath = fsChecker.handleLocale(\n removePathPrefix(invokePath, config.basePath)\n ).pathname\n }\n\n if (\n req.headers['x-nextjs-data'] &&\n fsChecker.getMiddlewareMatchers()?.length &&\n removePathPrefix(invokePath, config.basePath) === '/404'\n ) {\n res.setHeader('x-nextjs-matched-path', parsedUrl.pathname || '')\n res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end('{}')\n return null\n }\n\n if (!handlers) {\n throw new Error('Failed to initialize render server')\n }\n\n addRequestMeta(req, 'invokePath', invokePath)\n addRequestMeta(req, 'invokeQuery', parsedUrl.query)\n addRequestMeta(req, 'middlewareInvoke', false)\n\n for (const key in additionalRequestMeta || {}) {\n addRequestMeta(\n req,\n key as keyof RequestMeta,\n additionalRequestMeta![key as keyof RequestMeta]\n )\n }\n\n debug('invokeRender', req.url, req.headers)\n\n try {\n const initResult =\n await renderServer?.instance?.initialize(renderServerOpts)\n try {\n await initResult?.requestHandler(req, res)\n } catch (err) {\n if (err instanceof NoFallbackError) {\n await handleRequest(handleIndex + 1)\n return\n }\n throw err\n }\n return\n } catch (e) {\n // If the client aborts before we can receive a response object (when\n // the headers are flushed), then we can early exit without further\n // processing.\n if (isAbortError(e)) {\n return\n }\n throw e\n }\n }\n\n const handleRequest = async (handleIndex: number) => {\n if (handleIndex > 5) {\n throw new Error(`Attempted to handle request too many times ${req.url}`)\n }\n\n // handle hot-reloader first\n if (development) {\n if (\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n const origUrl = req.url || '/'\n\n // both the basePath and assetPrefix need to be stripped from the URL\n // so that the development bundler can find the correct file\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n const parsedUrl = parseUrlUtil(req.url || '/')\n\n const hotReloaderResult = await development.bundler.hotReloader.run(\n req,\n res,\n parsedUrl\n )\n\n if (hotReloaderResult.finished) {\n return hotReloaderResult\n }\n\n req.url = origUrl\n }\n\n const {\n finished,\n parsedUrl,\n statusCode,\n resHeaders,\n bodyStream,\n matchedOutput,\n } = await resolveRoutes({\n req,\n res,\n isUpgradeReq: false,\n signal: signalFromNodeResponse(res),\n invokedOutputs,\n })\n\n if (res.closed || res.finished) {\n return\n }\n\n if (development && matchedOutput?.type === 'devVirtualFsItem') {\n const origUrl = req.url || '/'\n\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n const result = await development.bundler.requestHandler(req, res)\n\n if (result.finished) {\n return\n }\n // TODO: throw invariant if we resolved to this but it wasn't handled?\n req.url = origUrl\n }\n\n debug('requestHandler!', req.url, {\n matchedOutput,\n statusCode,\n resHeaders,\n bodyStream: !!bodyStream,\n parsedUrl: {\n pathname: parsedUrl.pathname,\n query: parsedUrl.query,\n },\n finished,\n })\n\n // apply any response headers from routing\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n\n // handle redirect\n if (!bodyStream && statusCode && statusCode > 300 && statusCode < 400) {\n const destination = url.format(parsedUrl)\n res.statusCode = statusCode\n res.setHeader('location', destination)\n\n if (statusCode === RedirectStatusCode.PermanentRedirect) {\n res.setHeader('Refresh', `0;url=${destination}`)\n }\n return res.end(destination)\n }\n\n // handle middleware body response\n if (bodyStream) {\n res.statusCode = statusCode || 200\n return await pipeToNodeResponse(bodyStream, res)\n }\n\n if (finished && parsedUrl.protocol) {\n return await proxyRequest(\n req,\n res,\n parsedUrl,\n undefined,\n getRequestMeta(req, 'clonableBody')?.cloneBodyStream(),\n config.experimental.proxyTimeout\n )\n }\n\n if (matchedOutput?.fsPath && matchedOutput.itemPath) {\n if (\n opts.dev &&\n (fsChecker.appFiles.has(matchedOutput.itemPath) ||\n fsChecker.pageFiles.has(matchedOutput.itemPath))\n ) {\n res.statusCode = 500\n const message = `A conflicting public file and page file was found for path ${matchedOutput.itemPath} https://nextjs.org/docs/messages/conflicting-public-file-page`\n await invokeRender(parsedUrl, '/_error', handleIndex, {\n invokeStatus: 500,\n invokeError: new Error(message),\n })\n Log.error(message)\n return\n }\n\n if (\n !res.getHeader('cache-control') &&\n matchedOutput.type === 'nextStaticFolder'\n ) {\n if (matchedOutput.itemPath.startsWith('/service-worker/')) {\n res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate')\n res.setHeader('Service-Worker-Allowed', config.basePath || '/')\n } else if (opts.dev && !isNextFont(parsedUrl.pathname)) {\n res.setHeader('Cache-Control', 'no-cache, must-revalidate')\n } else {\n res.setHeader(\n 'Cache-Control',\n 'public, max-age=31536000, immutable'\n )\n }\n }\n if (!(req.method === 'GET' || req.method === 'HEAD')) {\n res.setHeader('Allow', ['GET', 'HEAD'])\n res.statusCode = 405\n return await invokeRender(parseUrlUtil('/405'), '/405', handleIndex, {\n invokeStatus: 405,\n })\n }\n\n try {\n return await serveStatic(req, res, matchedOutput.itemPath, {\n root: matchedOutput.itemsRoot,\n // Ensures that etags are not generated for static files when disabled.\n etag: config.generateEtags,\n })\n } catch (err: any) {\n /**\n * Hardcoded every possible error status code that could be thrown by \"serveStatic\" method\n * This is done by searching \"this.error\" inside \"send\" module's source code:\n * https://github.com/pillarjs/send/blob/master/index.js\n * https://github.com/pillarjs/send/blob/develop/index.js\n */\n const POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC = new Set([\n // send module will throw 500 when header is already sent or fs.stat error happens\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L392\n // Note: we will use Next.js built-in 500 page to handle 500 errors\n // 500,\n\n // send module will throw 404 when file is missing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L421\n // Note: we will use Next.js built-in 404 page to handle 404 errors\n // 404,\n\n // send module will throw 403 when redirecting to a directory without enabling directory listing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L484\n // Note: Next.js throws a different error (without status code) for directory listing\n // 403,\n\n // send module will throw 400 when fails to normalize the path\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L520\n 400,\n\n // send module will throw 412 with conditional GET request\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L632\n 412,\n\n // send module will throw 416 when range is not satisfiable\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L669\n 416,\n ])\n\n let validErrorStatus = POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC.has(\n err.statusCode\n )\n\n // normalize non-allowed status codes\n if (!validErrorStatus) {\n ;(err as any).statusCode = 400\n }\n\n if (typeof err.statusCode === 'number') {\n const invokePath = `/${err.statusCode}`\n const invokeStatus = err.statusCode\n res.statusCode = err.statusCode\n return await invokeRender(\n parseUrlUtil(invokePath),\n invokePath,\n handleIndex,\n {\n invokeStatus,\n }\n )\n }\n throw err\n }\n }\n\n if (matchedOutput) {\n invokedOutputs.add(matchedOutput.itemPath)\n\n return await invokeRender(\n parsedUrl,\n parsedUrl.pathname || '/',\n handleIndex,\n {\n invokeOutput: matchedOutput.itemPath,\n }\n )\n }\n\n // We want the original pathname without any basePath or proxy rewrites.\n if (development && isChromeDevtoolsWorkspaceUrl(req.url)) {\n await handleChromeDevtoolsWorkspaceRequest(res, opts, config)\n return\n }\n\n // 404 case\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n\n let realRequestPathname = parsedUrl.pathname ?? ''\n if (realRequestPathname) {\n if (config.basePath) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.basePath\n )\n }\n if (config.assetPrefix) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.assetPrefix\n )\n }\n if (config.i18n) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n '/' + (getRequestMeta(req, 'locale') ?? '')\n )\n }\n }\n // For not found static assets, return plain text 404 instead of\n // full HTML 404 pages to save bandwidth.\n if (realRequestPathname.startsWith('/_next/static/')) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // For subresource requests (e.g. images or fonts), return plain text\n // 404 instead of rendering the not-found route.\n if (\n (req.method === 'GET' || req.method === 'HEAD') &&\n isNonHtmlSecFetchDest(req.headers['sec-fetch-dest'])\n ) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // Short-circuit favicon.ico serving so that the 404 page doesn't get built as favicon is requested by the browser when loading any route.\n if (opts.dev && !matchedOutput && parsedUrl.pathname === '/favicon.ico') {\n res.statusCode = 404\n res.end('')\n return null\n }\n\n const appNotFound = opts.dev\n ? development?.bundler?.serverFields.hasAppNotFound\n : await fsChecker.getItem(UNDERSCORE_NOT_FOUND_ROUTE)\n\n res.statusCode = 404\n\n if (appNotFound) {\n return await invokeRender(\n parsedUrl,\n UNDERSCORE_NOT_FOUND_ROUTE,\n handleIndex,\n {\n invokeStatus: 404,\n }\n )\n }\n\n await invokeRender(parsedUrl, '/404', handleIndex, {\n invokeStatus: 404,\n })\n }\n\n try {\n await handleRequest(0)\n } catch (err) {\n try {\n let invokePath = '/500'\n let invokeStatus = '500'\n\n if (err instanceof DecodeError) {\n invokePath = '/400'\n invokeStatus = '400'\n } else {\n console.error(err)\n }\n res.statusCode = Number(invokeStatus)\n return await invokeRender(parseUrlUtil(invokePath), invokePath, 0, {\n invokeStatus: res.statusCode,\n })\n } catch (err2) {\n console.error(err2)\n }\n res.statusCode = 500\n res.end('Internal Server Error')\n }\n }\n\n let requestHandler: WorkerRequestHandler = requestHandlerImpl\n if (config.experimental.testProxy) {\n // Intercept fetch and other testmode apis.\n const { wrapRequestHandlerWorker, interceptTestApis } =\n // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n require('next/dist/experimental/testmode/server') as typeof import('../../experimental/testmode/server')\n requestHandler = wrapRequestHandlerWorker(requestHandler)\n interceptTestApis()\n // We treat the intercepted fetch as \"original\" fetch that should be reset to during HMR.\n originalFetch = globalThis.fetch\n }\n requestHandlers[opts.dir] = requestHandler\n\n const renderServerOpts: Parameters<RenderServer['initialize']>[0] = {\n port: opts.port,\n dir: opts.dir,\n hostname: opts.hostname,\n minimalMode: opts.minimalMode,\n dev: !!opts.dev,\n server: opts.server,\n serverFields: {\n ...(development?.bundler?.serverFields || {}),\n setIsrStatus: development?.service?.setIsrStatus.bind(\n development?.service\n ),\n } satisfies ServerFields,\n experimentalTestProxy: !!config.experimental.testProxy,\n experimentalHttpsServer: !!opts.experimentalHttpsServer,\n bundlerService: development?.service,\n startServerSpan: opts.startServerSpan,\n quiet: opts.quiet,\n onDevServerCleanup: opts.onDevServerCleanup,\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n }\n renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl\n\n // pre-initialize workers\n const handlers = await renderServer.instance.initialize(renderServerOpts)\n\n // this must come after initialize of render server since it's\n // using initialized methods\n if (!routerServerGlobal[RouterServerContextSymbol]) {\n routerServerGlobal[RouterServerContextSymbol] = {}\n }\n const relativeProjectDir = path.relative(process.cwd(), opts.dir)\n\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {\n nextConfig: getNextConfigRuntime(config),\n hostname: handlers.server.hostname,\n revalidate: handlers.server.revalidate.bind(handlers.server),\n render404: handlers.server.render404.bind(handlers.server),\n experimentalTestProxy: renderServerOpts.experimentalTestProxy,\n logErrorWithOriginalStack: opts.dev\n ? handlers.server.logErrorWithOriginalStack.bind(handlers.server)\n : (err: unknown) => !opts.quiet && Log.error(err),\n setCacheStatus: config.cacheComponents\n ? development?.service?.setCacheStatus.bind(development?.service)\n : undefined,\n setIsrStatus: development?.service?.setIsrStatus.bind(development?.service),\n setReactDebugChannel: development?.config.experimental.reactDebugChannel\n ? development?.service?.setReactDebugChannel.bind(development?.service)\n : undefined,\n sendErrorsToBrowser: development?.service?.sendErrorsToBrowser.bind(\n development?.service\n ),\n }\n\n const logError = async (\n type: 'uncaughtException' | 'unhandledRejection',\n err: Error | undefined\n ) => {\n if (isPostpone(err)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n if (type === 'unhandledRejection') {\n Log.error('unhandledRejection: ', err)\n } else if (type === 'uncaughtException') {\n Log.error('uncaughtException: ', err)\n }\n }\n\n process.on('uncaughtException', logError.bind(null, 'uncaughtException'))\n process.on('unhandledRejection', logError.bind(null, 'unhandledRejection'))\n\n const resolveRoutes = getResolveRoutes(\n fsChecker,\n config,\n opts,\n renderServer.instance,\n renderServerOpts,\n development?.bundler?.ensureMiddleware\n )\n\n const upgradeHandler: WorkerUpgradeHandler = async (req, socket, head) => {\n try {\n req.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n socket.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n\n if (opts.dev && development && req.url) {\n if (\n blockCrossSiteDEV(\n req,\n socket,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n const { basePath, assetPrefix } = config\n\n let hmrPrefix = basePath\n\n // assetPrefix overrides basePath for HMR path\n if (assetPrefix) {\n hmrPrefix = normalizedAssetPrefix(assetPrefix)\n\n if (URL.canParse(hmrPrefix)) {\n // remove trailing slash from pathname\n // return empty string if pathname is '/'\n // to avoid conflicts with '/_next' below\n hmrPrefix = new URL(hmrPrefix).pathname.replace(/\\/$/, '')\n }\n }\n\n const isHMRRequest = req.url.startsWith(\n ensureLeadingSlash(`${hmrPrefix}/_next/hmr`)\n )\n\n // only handle HMR requests if the basePath in the request\n // matches the basePath for the handler responding to the request\n if (isHMRRequest) {\n return development.bundler.hotReloader.onHMR(\n req,\n socket,\n head,\n (client, { isLegacyClient }) => {\n if (isLegacyClient) {\n // Only send the ISR manifest to legacy clients, i.e. Pages\n // Router clients, or App Router clients that have Cache\n // Components disabled. The ISR manifest is only used to inform\n // the static indicator, which currently does not provide useful\n // information if Cache Components is enabled due to its binary\n // nature (i.e. it does not support showing info for partially\n // static pages).\n client.send(\n JSON.stringify({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: development.service?.appIsrManifest || {},\n } satisfies AppIsrManifestMessage)\n )\n }\n }\n )\n }\n }\n\n const res = new MockedResponse({\n resWriter: () => {\n throw new Error(\n 'Invariant: did not expect response writer to be written to for upgrade request'\n )\n },\n })\n const { finished, matchedOutput, parsedUrl, statusCode } =\n await resolveRoutes({\n req,\n res,\n isUpgradeReq: true,\n signal: signalFromNodeResponse(socket),\n })\n\n // TODO: allow upgrade requests to pages/app paths?\n // this was not previously supported\n if (matchedOutput) {\n return socket.end()\n }\n\n if (finished && parsedUrl.protocol) {\n if (!statusCode) {\n return await proxyRequest(req, socket, parsedUrl, head)\n }\n\n return socket.end()\n }\n\n // If there's no matched output, we don't handle the request as user's\n // custom WS server may be listening on the same path.\n } catch (err) {\n console.error('Error handling upgrade request', err)\n socket.end()\n }\n }\n\n return {\n requestHandler,\n upgradeHandler,\n server: handlers.server,\n closeUpgraded() {\n development?.bundler?.hotReloader?.close()\n },\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n agentRules: config.agentRules,\n }\n}\n"],"names":["url","path","loadConfig","finalizeBundlerFromConfig","getBundlerFromEnv","serveStatic","setupDebug","Log","DecodeError","findPagesDir","setupFsCheck","proxyRequest","isAbortError","pipeToNodeResponse","getResolveRoutes","addRequestMeta","getRequestMeta","pathHasPrefix","removePathPrefix","setupCompression","releaseCompressionStream","signalFromNodeResponse","isPostpone","isNonHtmlSecFetchDest","parseUrl","parseUrlUtil","PHASE_PRODUCTION_SERVER","PHASE_DEVELOPMENT_SERVER","REQUEST_INSIGHTS_DEV_ENDPOINT","UNDERSCORE_NOT_FOUND_ROUTE","RedirectStatusCode","DevBundlerService","trace","ensureLeadingSlash","getNextPathnameInfo","getHostname","detectDomainLocale","MockedResponse","HMR_MESSAGE_SENT_TO_BROWSER","normalizedAssetPrefix","NEXT_PATCH_SYMBOL","filterInternalHeaders","blockCrossSiteDEV","traceGlobals","NoFallbackError","RouterServerContextSymbol","routerServerGlobal","handleChromeDevtoolsWorkspaceRequest","isChromeDevtoolsWorkspaceUrl","getNextConfigRuntime","getRequestInsightsSnapshot","isRequestInsightsEnabled","debug","isNextFont","pathname","test","requestHandlers","initialize","opts","development","process","env","NODE_ENV","dev","bundlerBeforeConfig","undefined","experimentalFeatures","config","dir","silent","reportExperimentalFeatures","features","toSorted","key","a","b","localeCompare","compress","fsChecker","minimalMode","renderServer","originalFetch","globalThis","fetch","developmentConfig","Telemetry","require","telemetry","distDir","join","set","pagesDir","appDir","setupDevBundler","resetFetch","setupDevBundlerSpan","startServerSpan","traceChild","cliServerFastRefresh","serverFastRefresh","configServerFastRefresh","experimental","turbopackServerFastRefresh","effectiveServerFastRefresh","warn","developmentBundler","traceAsyncFn","nextConfig","isCustomServer","customServer","turbo","TURBOPACK","port","onDevServerCleanup","devBundlerService","req","res","Boolean","requestInsights","bundler","service","instance","requestHandlerImpl","relativeProjectDir","NEXT_PRIVATE_TEST_HEADERS","headers","__NEXT_REQUEST_INSIGHTS","urlParts","split","basePath","allowedDevOrigins","hostname","setHeader","statusCode","end","JSON","stringify","error","i18n","localeDetection","urlNoQuery","pathnameInfo","domainLocale","domains","defaultLocale","getLocaleRedirect","parsedUrl","replace","redirect","pathLocale","locale","urlParsed","TemporaryRedirect","once","writableFinished","on","_err","invokedOutputs","Set","invokeRender","invokePath","handleIndex","additionalRequestMeta","startsWith","handleLocale","getMiddlewareMatchers","length","handlers","Error","query","initResult","renderServerOpts","requestHandler","err","handleRequest","e","origUrl","assetPrefix","hotReloaderResult","hotReloader","run","finished","resHeaders","bodyStream","matchedOutput","resolveRoutes","isUpgradeReq","signal","closed","type","Object","keys","result","destination","format","PermanentRedirect","protocol","cloneBodyStream","proxyTimeout","fsPath","itemPath","appFiles","has","pageFiles","message","invokeStatus","invokeError","getHeader","method","root","itemsRoot","etag","generateEtags","POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC","validErrorStatus","add","invokeOutput","realRequestPathname","appNotFound","serverFields","hasAppNotFound","getItem","console","Number","err2","testProxy","wrapRequestHandlerWorker","interceptTestApis","server","setIsrStatus","bind","experimentalTestProxy","experimentalHttpsServer","bundlerService","quiet","cacheComponents","partialPrefetching","routerServerHandler","relative","cwd","revalidate","render404","logErrorWithOriginalStack","setCacheStatus","setReactDebugChannel","reactDebugChannel","sendErrorsToBrowser","logError","ensureMiddleware","upgradeHandler","socket","head","hmrPrefix","URL","canParse","isHMRRequest","onHMR","client","isLegacyClient","send","ISR_MANIFEST","data","appIsrManifest","resWriter","closeUpgraded","close","agentRules"],"mappings":"AAAA,oDAAoD;AAKpD,6EAA6E;AAC7E,OAAO,sBAAqB;AAC5B,OAAO,kBAAiB;AAExB,OAAOA,SAAS,MAAK;AACrB,OAAOC,UAAU,OAAM;AACvB,OAAOC,gBAAwD,YAAW;AAC1E,SAASC,yBAAyB,EAAEC,iBAAiB,QAAQ,oBAAmB;AAChF,SAASC,WAAW,QAAQ,kBAAiB;AAC7C,OAAOC,gBAAgB,2BAA0B;AACjD,YAAYC,SAAS,yBAAwB;AAC7C,SAASC,WAAW,QAAQ,yBAAwB;AACpD,SAASC,YAAY,QAAQ,2BAA0B;A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F","ignoreList":[0]} |
@@ -7,2 +7,22 @@ import { LRUCache } from './lru-cache'; | ||
| const findSourceMap = process.env.NEXT_RUNTIME === 'edge' ? noSourceMap : require('module').findSourceMap; | ||
| // `SourceMap#payload` deep-clones the payload on every access — expensive | ||
| // for large chunk maps — so the clone is shared per `SourceMap` instance, | ||
| // which Node.js memoizes per script. | ||
| const sourceMapPayloads = new WeakMap(); | ||
| /** | ||
| * Like `module.findSourceMap`, but returns the source map's payload without | ||
| * cloning it on every call. Callers must not mutate the returned payload. | ||
| * Throws like `module.findSourceMap` does on invalid source maps. | ||
| */ export function findSourceMapPayload(sourceURL) { | ||
| const sourceMap = findSourceMap(sourceURL); | ||
| if (sourceMap === undefined) { | ||
| return undefined; | ||
| } | ||
| let payload = sourceMapPayloads.get(sourceMap); | ||
| if (payload === undefined) { | ||
| payload = sourceMap.payload; | ||
| sourceMapPayloads.set(sourceMap, payload); | ||
| } | ||
| return payload; | ||
| } | ||
| export function sourceMapIgnoreListsEverything(sourceMap) { | ||
@@ -61,9 +81,8 @@ return sourceMap.ignoreList !== undefined && sourceMap.sources.length === sourceMap.ignoreList.length; | ||
| // Make sure this doesn't adversely affect performance when CJS is used by Next.js. | ||
| const sourceMap = findSourceMap(sourceURL); | ||
| if (sourceMap === undefined) { | ||
| // No source map assoicated. | ||
| // TODO: Node.js types should reflect that `findSourceMap` can return `undefined`. | ||
| const payload = findSourceMapPayload(sourceURL); | ||
| if (payload === undefined) { | ||
| // No source map associated. | ||
| return true; | ||
| } | ||
| const sourceMapPayload = findApplicableSourceMapPayload(line1 - 1, column1 - 1, sourceMap.payload); | ||
| const sourceMapPayload = findApplicableSourceMapPayload(line1 - 1, column1 - 1, payload); | ||
| if (sourceMapPayload === undefined) { | ||
@@ -119,4 +138,3 @@ // No source map section applicable to the frame. | ||
| try { | ||
| var _findSourceMap; | ||
| sourceMapPayload = (_findSourceMap = findSourceMap(scriptNameOrSourceURL)) == null ? void 0 : _findSourceMap.payload; | ||
| sourceMapPayload = findSourceMapPayload(scriptNameOrSourceURL); | ||
| } catch (cause) { | ||
@@ -123,0 +141,0 @@ console.error(`${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/source-maps.ts"],"sourcesContent":["import type { SourceMap } from 'module'\nimport { LRUCache } from './lru-cache'\n\nfunction noSourceMap(): SourceMap | undefined {\n return undefined\n}\n\n// Edge runtime does not implement `module`\nconst findSourceMap =\n process.env.NEXT_RUNTIME === 'edge'\n ? noSourceMap\n : (require('module') as typeof import('module')).findSourceMap\n\n/**\n * https://tc39.es/source-map/#index-map\n */\ninterface IndexSourceMapSection {\n offset: {\n line: number\n column: number\n }\n map: BasicSourceMapPayload\n}\n\n// TODO(veil): Upstream types\n/** https://tc39.es/ecma426/#sec-index-source-map */\ninterface IndexSourceMap {\n version: number\n file: string\n sections: IndexSourceMapSection[]\n}\n\n/** https://tc39.es/ecma426/#sec-source-map-format */\nexport interface BasicSourceMapPayload {\n version: number\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `file` is optional. */\n file: string\n sourceRoot?: string\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `sources[number]` can be `null`. */\n sources: Array<string>\n names: Array<string>\n mappings: string\n ignoreList?: number[]\n}\n\nexport type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap\n\nexport function sourceMapIgnoreListsEverything(\n sourceMap: BasicSourceMapPayload\n): boolean {\n return (\n sourceMap.ignoreList !== undefined &&\n sourceMap.sources.length === sourceMap.ignoreList.length\n )\n}\n\n/**\n * Finds the sourcemap payload applicable to a given frame.\n * Equal to the input unless an Index Source Map is used.\n * @param line0 - The line number of the frame, 0-based.\n * @param column0 - The column number of the frame, 0-based.\n */\nexport function findApplicableSourceMapPayload(\n line0: number,\n column0: number,\n payload: ModernSourceMapPayload\n): BasicSourceMapPayload | undefined {\n if ('sections' in payload) {\n if (payload.sections.length === 0) {\n return undefined\n }\n\n // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object\n // Therefore the last section that has an offset less than or equal to the frame is the applicable one.\n const sections = payload.sections\n let left = 0\n let right = sections.length - 1\n let result: IndexSourceMapSection | null = null\n\n while (left <= right) {\n // fast Math.floor\n const middle = ~~((left + right) / 2)\n const section = sections[middle]\n const offset = section.offset\n\n if (\n offset.line < line0 ||\n (offset.line === line0 && offset.column <= column0)\n ) {\n result = section\n left = middle + 1\n } else {\n right = middle - 1\n }\n }\n\n return result === null ? undefined : result.map\n } else {\n return payload\n }\n}\n\nconst didWarnAboutInvalidSourceMapDEV = new Set<string>()\n\nexport function filterStackFrameDEV(\n sourceURL: string,\n functionName: string,\n line1: number,\n column1: number\n): boolean {\n if (sourceURL === '') {\n // The default implementation filters out <anonymous> stack frames\n // but we want to retain them because current Server Components and\n // built-in Components in parent stacks don't have source location.\n // Filter out frames that show up in Promises to get good names in React's\n // Server Request track until we come up with a better heuristic.\n return functionName !== 'new Promise'\n }\n if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) {\n return false\n }\n try {\n // Node.js loads source maps eagerly so this call is cheap.\n // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules).\n // Make sure this doesn't adversely affect performance when CJS is used by Next.js.\n const sourceMap = findSourceMap(sourceURL)\n if (sourceMap === undefined) {\n // No source map assoicated.\n // TODO: Node.js types should reflect that `findSourceMap` can return `undefined`.\n return true\n }\n const sourceMapPayload = findApplicableSourceMapPayload(\n line1 - 1,\n column1 - 1,\n sourceMap.payload\n )\n if (sourceMapPayload === undefined) {\n // No source map section applicable to the frame.\n return true\n }\n return !sourceMapIgnoreListsEverything(sourceMapPayload)\n } catch (cause) {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: Share cache with patch-error-inspect\n if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) {\n didWarnAboutInvalidSourceMapDEV.add(sourceURL)\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`\n )\n }\n }\n\n return true\n }\n}\n\n// `scriptNameOrSourceURL` is what React forwards from the stack frame: the\n// script's `getScriptNameOrSourceURL()`, which for the server chunks we can\n// map is an absolute filesystem path, not a URL. The returned value is the\n// source map's URL (`file:` or `data:`).\ntype FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null\n// Find the URL of a source map using the bundler's API.\n// Shared via `globalThis` because this module is compiled both into the server\n// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`\n// (where the dev server registers the implementation), and each copy has its own\n// module state.\nconst bundlerFindSourceMapURLSymbol = Symbol.for(\n 'next.server.bundlerFindSourceMapURL'\n)\n\nexport function setBundlerFindSourceMapURLImplementation(\n findSourceMapURLImplementation: FindSourceMapURL\n): void {\n ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =\n findSourceMapURLImplementation\n}\n\nfunction bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {\n const implementation: FindSourceMapURL | undefined = (globalThis as any)[\n bundlerFindSourceMapURLSymbol\n ]\n return implementation === undefined\n ? null\n : implementation(scriptNameOrSourceURL)\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(\n 512 * 1024 * 1024,\n (url) =>\n url === invalidSourceMap\n ? // Ideally we'd account for key length. So we just guestimate a small source map\n // so that we don't create a huge cache with empty source maps.\n 8 * 1024\n : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength\n url.length\n)\nexport function findSourceMapURLDEV(\n scriptNameOrSourceURL: string\n): string | null {\n try {\n const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)\n if (bundlerSourceMapURL !== null) {\n return bundlerSourceMapURL\n }\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`\n )\n }\n\n // No bundler implementation (e.g. Webpack): inline the source map Node.js\n // knows as a `data:` URL.\n let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n if (sourceMapURL === undefined) {\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMap(scriptNameOrSourceURL)?.payload\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n }\n\n if (sourceMapPayload === undefined) {\n sourceMapURL = invalidSourceMap\n } else {\n // TODO: Might be more efficient to extract the relevant section from Index Maps.\n // Unclear if that search is worth the smaller payload we have to stringify.\n const sourceMapJSON = JSON.stringify(sourceMapPayload)\n const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString(\n 'base64'\n )\n sourceMapURL = `data:application/json;base64,${sourceMapURLData}`\n }\n\n sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL)\n }\n\n return sourceMapURL === invalidSourceMap ? null : sourceMapURL\n}\n\nexport function devirtualizeReactServerURL(sourceURL: string): string {\n if (sourceURL.startsWith('about://React/')) {\n // about://React/Server/file://<filename>?42 => file://<filename>\n const envIdx = sourceURL.indexOf('/', 'about://React/'.length)\n const suffixIdx = sourceURL.lastIndexOf('?')\n if (envIdx > -1 && suffixIdx > -1) {\n return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx))\n }\n }\n return sourceURL\n}\n\nfunction isAnonymousFrameLikelyJSNative(methodName: string): boolean {\n // Anonymous frames can also be produced in React parent stacks either from\n // host components or Server Components. We don't want to ignore those.\n // This could hide user-space methods that are named like native JS methods but\n // should you really do that?\n return (\n // e.g. JSON.parse\n methodName.startsWith('JSON.') ||\n // E.g. Promise.withResolves\n methodName.startsWith('Function.') ||\n // various JS built-ins\n methodName.startsWith('Promise.') ||\n methodName.startsWith('Array.') ||\n methodName.startsWith('Set.') ||\n methodName.startsWith('Map.')\n )\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched<Frame>(\n frames: Frame[],\n isAnonymousFrame: (frame: Frame) => boolean,\n isIgnoredFrame: (frame: Frame) => boolean,\n getMethodName: (frame: Frame) => string,\n /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */\n ignoreFrame: (frame: Frame) => void\n): void {\n for (let i = 1; i < frames.length; i++) {\n const currentFrame = frames[i]\n if (\n !(\n isAnonymousFrame(currentFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(currentFrame))\n )\n ) {\n continue\n }\n\n const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1])\n if (previousFrameIsIgnored && i < frames.length - 1) {\n let ignoreSandwich = false\n let j = i + 1\n for (j; j < frames.length; j++) {\n const nextFrame = frames[j]\n const nextFrameIsAnonymous =\n isAnonymousFrame(nextFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(nextFrame))\n if (nextFrameIsAnonymous) {\n continue\n }\n\n const nextFrameIsIgnored = isIgnoredFrame(nextFrame)\n if (nextFrameIsIgnored) {\n ignoreSandwich = true\n break\n }\n }\n\n if (ignoreSandwich) {\n for (i; i < j; i++) {\n ignoreFrame(frames[i])\n }\n }\n }\n }\n}\n"],"names":["LRUCache","noSourceMap","undefined","findSourceMap","process","env","NEXT_RUNTIME","require","sourceMapIgnoreListsEverything","sourceMap","ignoreList","sources","length","findApplicableSourceMapPayload","line0","column0","payload","sections","left","right","result","middle","section","offset","line","column","map","didWarnAboutInvalidSourceMapDEV","Set","filterStackFrameDEV","sourceURL","functionName","line1","column1","startsWith","includes","sourceMapPayload","cause","NODE_ENV","has","add","console","error","bundlerFindSourceMapURLSymbol","Symbol","for","setBundlerFindSourceMapURLImplementation","findSourceMapURLImplementation","globalThis","bundlerFindSourceMapURL","scriptNameOrSourceURL","implementation","invalidSourceMap","sourceMapURLs","url","findSourceMapURLDEV","bundlerSourceMapURL","sourceMapURL","get","sourceMapJSON","JSON","stringify","sourceMapURLData","Buffer","from","toString","set","devirtualizeReactServerURL","envIdx","indexOf","suffixIdx","lastIndexOf","decodeURI","slice","isAnonymousFrameLikelyJSNative","methodName","ignoreListAnonymousStackFramesIfSandwiched","frames","isAnonymousFrame","isIgnoredFrame","getMethodName","ignoreFrame","i","currentFrame","previousFrameIsIgnored","ignoreSandwich","j","nextFrame","nextFrameIsAnonymous","nextFrameIsIgnored"],"mappings":"AACA,SAASA,QAAQ,QAAQ,cAAa;AAEtC,SAASC;IACP,OAAOC;AACT;AAEA,2CAA2C;AAC3C,MAAMC,gBACJC,QAAQC,GAAG,CAACC,YAAY,KAAK,SACzBL,cACA,AAACM,QAAQ,UAAsCJ,aAAa;AAsClE,OAAO,SAASK,+BACdC,SAAgC;IAEhC,OACEA,UAAUC,UAAU,KAAKR,aACzBO,UAAUE,OAAO,CAACC,MAAM,KAAKH,UAAUC,UAAU,CAACE,MAAM;AAE5D;AAEA;;;;;CAKC,GACD,OAAO,SAASC,+BACdC,KAAa,EACbC,OAAe,EACfC,OAA+B;IAE/B,IAAI,cAAcA,SAAS;QACzB,IAAIA,QAAQC,QAAQ,CAACL,MAAM,KAAK,GAAG;YACjC,OAAOV;QACT;QAEA,2FAA2F;QAC3F,uGAAuG;QACvG,MAAMe,WAAWD,QAAQC,QAAQ;QACjC,IAAIC,OAAO;QACX,IAAIC,QAAQF,SAASL,MAAM,GAAG;QAC9B,IAAIQ,SAAuC;QAE3C,MAAOF,QAAQC,MAAO;YACpB,kBAAkB;YAClB,MAAME,SAAS,CAAC,CAAE,CAAA,AAACH,CAAAA,OAAOC,KAAI,IAAK,CAAA;YACnC,MAAMG,UAAUL,QAAQ,CAACI,OAAO;YAChC,MAAME,SAASD,QAAQC,MAAM;YAE7B,IACEA,OAAOC,IAAI,GAAGV,SACbS,OAAOC,IAAI,KAAKV,SAASS,OAAOE,MAAM,IAAIV,SAC3C;gBACAK,SAASE;gBACTJ,OAAOG,SAAS;YAClB,OAAO;gBACLF,QAAQE,SAAS;YACnB;QACF;QAEA,OAAOD,WAAW,O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oB;oBACtBJ,iBAAiB;oBACjB;gBACF;YACF;YAEA,IAAIA,gBAAgB;gBAClB,IAAKH,GAAGA,IAAII,GAAGJ,IAAK;oBAClBD,YAAYJ,MAAM,CAACK,EAAE;gBACvB;YACF;QACF;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/source-maps.ts"],"sourcesContent":["import type { SourceMap } from 'module'\nimport { LRUCache } from './lru-cache'\n\nfunction noSourceMap(): SourceMap | undefined {\n return undefined\n}\n\n// Edge runtime does not implement `module`\nconst findSourceMap =\n process.env.NEXT_RUNTIME === 'edge'\n ? noSourceMap\n : (require('module') as typeof import('module')).findSourceMap\n\n/**\n * https://tc39.es/source-map/#index-map\n */\ninterface IndexSourceMapSection {\n offset: {\n line: number\n column: number\n }\n map: BasicSourceMapPayload\n}\n\n// TODO(veil): Upstream types\n/** https://tc39.es/ecma426/#sec-index-source-map */\ninterface IndexSourceMap {\n version: number\n file: string\n sections: IndexSourceMapSection[]\n}\n\n/** https://tc39.es/ecma426/#sec-source-map-format */\nexport interface BasicSourceMapPayload {\n version: number\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `file` is optional. */\n file: string\n sourceRoot?: string\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `sources[number]` can be `null`. */\n sources: Array<string>\n names: Array<string>\n mappings: string\n ignoreList?: number[]\n}\n\nexport type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap\n\n// `SourceMap#payload` deep-clones the payload on every access — expensive\n// for large chunk maps — so the clone is shared per `SourceMap` instance,\n// which Node.js memoizes per script.\nconst sourceMapPayloads = new WeakMap<SourceMap, ModernSourceMapPayload>()\n\n/**\n * Like `module.findSourceMap`, but returns the source map's payload without\n * cloning it on every call. Callers must not mutate the returned payload.\n * Throws like `module.findSourceMap` does on invalid source maps.\n */\nexport function findSourceMapPayload(\n sourceURL: string\n): ModernSourceMapPayload | undefined {\n const sourceMap = findSourceMap(sourceURL)\n if (sourceMap === undefined) {\n return undefined\n }\n let payload = sourceMapPayloads.get(sourceMap)\n if (payload === undefined) {\n payload = sourceMap.payload as ModernSourceMapPayload\n sourceMapPayloads.set(sourceMap, payload)\n }\n return payload\n}\n\nexport function sourceMapIgnoreListsEverything(\n sourceMap: BasicSourceMapPayload\n): boolean {\n return (\n sourceMap.ignoreList !== undefined &&\n sourceMap.sources.length === sourceMap.ignoreList.length\n )\n}\n\n/**\n * Finds the sourcemap payload applicable to a given frame.\n * Equal to the input unless an Index Source Map is used.\n * @param line0 - The line number of the frame, 0-based.\n * @param column0 - The column number of the frame, 0-based.\n */\nexport function findApplicableSourceMapPayload(\n line0: number,\n column0: number,\n payload: ModernSourceMapPayload\n): BasicSourceMapPayload | undefined {\n if ('sections' in payload) {\n if (payload.sections.length === 0) {\n return undefined\n }\n\n // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object\n // Therefore the last section that has an offset less than or equal to the frame is the applicable one.\n const sections = payload.sections\n let left = 0\n let right = sections.length - 1\n let result: IndexSourceMapSection | null = null\n\n while (left <= right) {\n // fast Math.floor\n const middle = ~~((left + right) / 2)\n const section = sections[middle]\n const offset = section.offset\n\n if (\n offset.line < line0 ||\n (offset.line === line0 && offset.column <= column0)\n ) {\n result = section\n left = middle + 1\n } else {\n right = middle - 1\n }\n }\n\n return result === null ? undefined : result.map\n } else {\n return payload\n }\n}\n\nconst didWarnAboutInvalidSourceMapDEV = new Set<string>()\n\nexport function filterStackFrameDEV(\n sourceURL: string,\n functionName: string,\n line1: number,\n column1: number\n): boolean {\n if (sourceURL === '') {\n // The default implementation filters out <anonymous> stack frames\n // but we want to retain them because current Server Components and\n // built-in Components in parent stacks don't have source location.\n // Filter out frames that show up in Promises to get good names in React's\n // Server Request track until we come up with a better heuristic.\n return functionName !== 'new Promise'\n }\n if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) {\n return false\n }\n try {\n // Node.js loads source maps eagerly so this call is cheap.\n // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules).\n // Make sure this doesn't adversely affect performance when CJS is used by Next.js.\n const payload = findSourceMapPayload(sourceURL)\n if (payload === undefined) {\n // No source map associated.\n return true\n }\n const sourceMapPayload = findApplicableSourceMapPayload(\n line1 - 1,\n column1 - 1,\n payload\n )\n if (sourceMapPayload === undefined) {\n // No source map section applicable to the frame.\n return true\n }\n return !sourceMapIgnoreListsEverything(sourceMapPayload)\n } catch (cause) {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: Share cache with patch-error-inspect\n if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) {\n didWarnAboutInvalidSourceMapDEV.add(sourceURL)\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`\n )\n }\n }\n\n return true\n }\n}\n\n// `scriptNameOrSourceURL` is what React forwards from the stack frame: the\n// script's `getScriptNameOrSourceURL()`, which for the server chunks we can\n// map is an absolute filesystem path, not a URL. The returned value is the\n// source map's URL (`file:` or `data:`).\ntype FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null\n// Find the URL of a source map using the bundler's API.\n// Shared via `globalThis` because this module is compiled both into the server\n// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`\n// (where the dev server registers the implementation), and each copy has its own\n// module state.\nconst bundlerFindSourceMapURLSymbol = Symbol.for(\n 'next.server.bundlerFindSourceMapURL'\n)\n\nexport function setBundlerFindSourceMapURLImplementation(\n findSourceMapURLImplementation: FindSourceMapURL\n): void {\n ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =\n findSourceMapURLImplementation\n}\n\nfunction bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {\n const implementation: FindSourceMapURL | undefined = (globalThis as any)[\n bundlerFindSourceMapURLSymbol\n ]\n return implementation === undefined\n ? null\n : implementation(scriptNameOrSourceURL)\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(\n 512 * 1024 * 1024,\n (url) =>\n url === invalidSourceMap\n ? // Ideally we'd account for key length. So we just guestimate a small source map\n // so that we don't create a huge cache with empty source maps.\n 8 * 1024\n : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength\n url.length\n)\nexport function findSourceMapURLDEV(\n scriptNameOrSourceURL: string\n): string | null {\n try {\n const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)\n if (bundlerSourceMapURL !== null) {\n return bundlerSourceMapURL\n }\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`\n )\n }\n\n // No bundler implementation (e.g. Webpack): inline the source map Node.js\n // knows as a `data:` URL.\n let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n if (sourceMapURL === undefined) {\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMapPayload(scriptNameOrSourceURL)\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n }\n\n if (sourceMapPayload === undefined) {\n sourceMapURL = invalidSourceMap\n } else {\n // TODO: Might be more efficient to extract the relevant section from Index Maps.\n // Unclear if that search is worth the smaller payload we have to stringify.\n const sourceMapJSON = JSON.stringify(sourceMapPayload)\n const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString(\n 'base64'\n )\n sourceMapURL = `data:application/json;base64,${sourceMapURLData}`\n }\n\n sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL)\n }\n\n return sourceMapURL === invalidSourceMap ? null : sourceMapURL\n}\n\nexport function devirtualizeReactServerURL(sourceURL: string): string {\n if (sourceURL.startsWith('about://React/')) {\n // about://React/Server/file://<filename>?42 => file://<filename>\n const envIdx = sourceURL.indexOf('/', 'about://React/'.length)\n const suffixIdx = sourceURL.lastIndexOf('?')\n if (envIdx > -1 && suffixIdx > -1) {\n return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx))\n }\n }\n return sourceURL\n}\n\nfunction isAnonymousFrameLikelyJSNative(methodName: string): boolean {\n // Anonymous frames can also be produced in React parent stacks either from\n // host components or Server Components. We don't want to ignore those.\n // This could hide user-space methods that are named like native JS methods but\n // should you really do that?\n return (\n // e.g. JSON.parse\n methodName.startsWith('JSON.') ||\n // E.g. Promise.withResolves\n methodName.startsWith('Function.') ||\n // various JS built-ins\n methodName.startsWith('Promise.') ||\n methodName.startsWith('Array.') ||\n methodName.startsWith('Set.') ||\n methodName.startsWith('Map.')\n )\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched<Frame>(\n frames: Frame[],\n isAnonymousFrame: (frame: Frame) => boolean,\n isIgnoredFrame: (frame: Frame) => boolean,\n getMethodName: (frame: Frame) => string,\n /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */\n ignoreFrame: (frame: Frame) => void\n): void {\n for (let i = 1; i < frames.length; i++) {\n const currentFrame = frames[i]\n if (\n !(\n isAnonymousFrame(currentFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(currentFrame))\n )\n ) {\n continue\n }\n\n const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1])\n if (previousFrameIsIgnored && i < frames.length - 1) {\n let ignoreSandwich = false\n let j = i + 1\n for (j; j < frames.length; j++) {\n const nextFrame = frames[j]\n const nextFrameIsAnonymous =\n isAnonymousFrame(nextFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(nextFrame))\n if (nextFrameIsAnonymous) {\n continue\n }\n\n const nextFrameIsIgnored = isIgnoredFrame(nextFrame)\n if (nextFrameIsIgnored) {\n ignoreSandwich = true\n break\n }\n }\n\n if (ignoreSandwich) {\n for (i; i < j; i++) {\n ignoreFrame(frames[i])\n }\n }\n }\n }\n}\n"],"names":["LRUCache","noSourceMap","undefined","findSourceMap","process","env","NEXT_RUNTIME","require","sourceMapPayloads","WeakMap","findSourceMapPayload","sourceURL","sourceMap","payload","get","set","sourceMapIgnoreListsEverything","ignoreList","sources","length","findApplicableSourceMapPayload","line0","column0","sections","left","right","result","middle","section","offset","line","column","map","didWarnAboutInvalidSourceMapDEV","Set","filterStackFrameDEV","functionName","line1","column1","startsWith","includes","sourceMapPayload","cause","NODE_ENV","has","add","console","error","bundlerFindSourceMapURLSymbol","Symbol","for","setBundlerFindSourceMapURLImplementation","findSourceMapURLImplementation","globalThis","bundlerFindSourceMapURL","scriptNameOrSourceURL","implementation","invalidSourceMap","sourceMapURLs","url","findSourceMapURLDEV","bundlerSourceMapURL","sourceMapURL","sourceMapJSON","JSON","stringify","sourceMapURLData","Buffer","from","toString","devirtualizeReactServerURL","envIdx","indexOf","suffixIdx","lastIndexOf","decodeURI","slice","isAnonymousFrameLikelyJSNative","methodName","ignoreListAnonymousStackFramesIfSandwiched","frames","isAnonymousFrame","isIgnoredFrame","getMethodName","ignoreFrame","i","currentFrame","previousFrameIsIgnored","ignoreSandwich","j","nextFrame","nextFrameIsAnonymous","nextFrameIsIgnored"],"mappings":"AACA,SAASA,QAAQ,QAAQ,cAAa;AAEtC,SAASC;IACP,OAAOC;AACT;AAEA,2CAA2C;AAC3C,MAAMC,gBACJC,QAAQC,GAAG,CAACC,YAAY,KAAK,SACzBL,cACA,AAACM,QAAQ,UAAsCJ,aAAa;AAsClE,0EAA0E;AAC1E,0EAA0E;AAC1E,qCAAqC;AACrC,MAAMK,oBAAoB,IAAIC;AAE9B;;;;CAIC,GACD,OAAO,SAASC,qBACdC,SAAiB;IAEjB,MAAMC,YAAYT,cAAcQ;IAChC,IAAIC,cAAcV,WAAW;QAC3B,OAAOA;IACT;IACA,IAAIW,UAAUL,kBAAkBM,GAAG,CAACF;IACpC,IAAIC,YAAYX,WAAW;QACzBW,UAAUD,UAAUC,OAAO;QAC3BL,kBAAkBO,GAAG,CAACH,WAAWC;IACnC;IACA,OAAOA;AACT;AAEA,OAAO,SAASG,+B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,aACtBuC,WAAWvC,UAAU,CAAC,WACtBuC,WAAWvC,UAAU,CAAC;AAE1B;AAEA,OAAO,SAASwC,2CACdC,MAAe,EACfC,gBAA2C,EAC3CC,cAAyC,EACzCC,aAAuC,EACvC,2HAA2H,GAC3HC,WAAmC;IAEnC,IAAK,IAAIC,IAAI,GAAGA,IAAIL,OAAO7D,MAAM,EAAEkE,IAAK;QACtC,MAAMC,eAAeN,MAAM,CAACK,EAAE;QAC9B,IACE,CACEJ,CAAAA,iBAAiBK,iBACjBT,+BAA+BM,cAAcG,cAAa,GAE5D;YACA;QACF;QAEA,MAAMC,yBAAyBL,eAAeF,MAAM,CAACK,IAAI,EAAE;QAC3D,IAAIE,0BAA0BF,IAAIL,OAAO7D,MAAM,GAAG,GAAG;YACnD,IAAIqE,iBAAiB;YACrB,IAAIC,IAAIJ,IAAI;YACZ,IAAKI,GAAGA,IAAIT,OAAO7D,MAAM,EAAEsE,IAAK;gBAC9B,MAAMC,YAAYV,MAAM,CAACS,EAAE;gBAC3B,MAAME,uBACJV,iBAAiBS,cACjBb,+BAA+BM,cAAcO;gBAC/C,IAAIC,sBAAsB;oBACxB;gBACF;gBAEA,MAAMC,qBAAqBV,eAAeQ;gBAC1C,IAAIE,oBAAoB;oBACtBJ,iBAAiB;oBACjB;gBACF;YACF;YAEA,IAAIA,gBAAgB;gBAClB,IAAKH,GAAGA,IAAII,GAAGJ,IAAK;oBAClBD,YAAYJ,MAAM,CAACK,EAAE;gBACvB;YACF;QACF;IACF;AACF","ignoreList":[0]} |
@@ -112,3 +112,3 @@ // Start CPU profile if it wasn't already started. | ||
| let { port } = serverOptions; | ||
| process.title = `next-server (v${"16.3.0-canary.96"})`; | ||
| process.title = `next-server (v${"16.3.0-canary.97"})`; | ||
| let handlersReady = ()=>{}; | ||
@@ -115,0 +115,0 @@ let handlersError = ()=>{}; |
@@ -47,3 +47,10 @@ import { BUILD_MANIFEST, REACT_LOADABLE_MANIFEST, CLIENT_REFERENCE_MANIFEST, SERVER_REFERENCE_MANIFEST, DYNAMIC_CSS_MANIFEST, SUBRESOURCE_INTEGRITY_MANIFEST } from '../shared/lib/constants'; | ||
| } | ||
| async function tryLoadClientReferenceManifest(manifestPath, entryName, attempts) { | ||
| /** | ||
| * Loads the client reference manifest that the bundler emitted for an app page, | ||
| * or returns undefined if there is none. Both the manifest file and the entry | ||
| * inside it are addressed by the page with `%5F` decoded back to `_`, so | ||
| * callers pass the page as-is and this resolves both. | ||
| */ export async function loadClientReferenceManifestForPage(distDir, page, attempts) { | ||
| const entryName = page.replace(/%5F/g, '_'); | ||
| const manifestPath = join(/* turbopackIgnore: true */ distDir, 'server', 'app', entryName + '_' + CLIENT_REFERENCE_MANIFEST + '.js'); | ||
| try { | ||
@@ -95,3 +102,3 @@ const context = await evalManifestWithRetries(manifestPath, attempts); | ||
| isAppPath || process.env.TURBOPACK ? undefined : loadManifestWithRetries(join(/* turbopackIgnore: true */ distDir, `${DYNAMIC_CSS_MANIFEST}.json`), manifestLoadAttempts).catch(()=>undefined), | ||
| isAppPath && hasClientManifest ? tryLoadClientReferenceManifest(join(/* turbopackIgnore: true */ distDir, 'server', 'app', page.replace(/%5F/g, '_') + '_' + CLIENT_REFERENCE_MANIFEST + '.js'), page.replace(/%5F/g, '_'), manifestLoadAttempts) : undefined, | ||
| isAppPath && hasClientManifest ? loadClientReferenceManifestForPage(distDir, page, manifestLoadAttempts) : undefined, | ||
| isAppPath ? loadManifestWithRetries(join(/* turbopackIgnore: true */ distDir, 'server', SERVER_REFERENCE_MANIFEST + '.json'), manifestLoadAttempts).catch(()=>null) : null, | ||
@@ -98,0 +105,0 @@ sriEnabled ? loadManifestWithRetries(join(/* turbopackIgnore: true */ distDir, 'server', SUBRESOURCE_INTEGRITY_MANIFEST + '.json')).catch(()=>undefined) : undefined |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/load-components.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type {\n AppType,\n DocumentType,\n NextComponentType,\n} from '../shared/lib/utils'\nimport type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'\nimport type {\n PageConfig,\n GetStaticPaths,\n GetServerSideProps,\n GetStaticProps,\n} from '../types'\nimport type { RouteModule } from './route-modules/route-module'\nimport type { BuildManifest } from './get-page-files'\nimport type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin'\n\nimport {\n BUILD_MANIFEST,\n REACT_LOADABLE_MANIFEST,\n CLIENT_REFERENCE_MANIFEST,\n SERVER_REFERENCE_MANIFEST,\n DYNAMIC_CSS_MANIFEST,\n SUBRESOURCE_INTEGRITY_MANIFEST,\n} from '../shared/lib/constants'\nimport { join } from 'path'\nimport { requirePage } from './require'\nimport { interopDefault } from '../lib/interop-default'\nimport { getTracer } from './lib/trace/tracer'\nimport { LoadComponentsSpan } from './lib/trace/constants'\nimport { evalManifest, loadManifest } from './load-manifest.external'\nimport { wait } from '../lib/wait'\nimport { setManifestsSingleton } from './app-render/manifests-singleton'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { isStaticMetadataRoute } from '../lib/metadata/is-metadata-route'\n\nexport type ManifestItem = {\n id: number | string\n files: string[]\n}\n\nexport type ReactLoadableManifest = { [moduleId: string]: ManifestItem }\n/**\n * This manifest prevents removing server rendered <link> tags after client\n * navigation. This is only needed under `Pages dir && Production && Webpack`.\n * @see https://github.com/vercel/next.js/pull/72959\n */\nexport type DynamicCssManifest = string[]\n\n/**\n * A manifest entry type for the react-loadable-manifest.json.\n *\n * The whole manifest.json is a type of `Record<pathname, LoadableManifest>`\n * where pathname is a string-based key points to the path of the page contains\n * each dynamic imports.\n */\nexport interface LoadableManifest {\n [k: string]: { id: string | number; files: string[] }\n}\n\nexport type GenericComponentMod = {\n handler(\n req: IncomingMessage,\n res: ServerResponse,\n ctx: {\n waitUntil?: (prom: Promise<void>) => void\n }\n ): Promise<void | null>\n}\n\nexport type LoadComponentsReturnType<\n NextModule extends GenericComponentMod = GenericComponentMod,\n> = {\n Component: NextComponentType\n pageConfig: PageConfig\n buildManifest: DeepReadonly<BuildManifest>\n subresourceIntegrityManifest?: DeepReadonly<Record<string, string>>\n reactLoadableManifest: DeepReadonly<ReactLoadableManifest>\n dynamicCssManifest?: DeepReadonly<DynamicCssManifest>\n Document: DocumentType\n App: AppType\n getStaticProps?: GetStaticProps\n getStaticPaths?: GetStaticPaths\n getServerSideProps?: GetServerSideProps\n ComponentMod: NextModule\n routeModule: RouteModule\n isAppPath?: boolean\n page: string\n multiZoneDraftMode?: boolean\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function loadManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return loadManifest<T>(manifestPath)\n } catch (err) {\n attempts--\n if (attempts <= 0) throw err\n\n await wait(100)\n }\n }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts, or return undefined.\n */\nexport async function tryLoadManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n try {\n return await loadManifestWithRetries<T>(manifestPath, attempts)\n } catch (err) {\n return undefined\n }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function evalManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return evalManifest<T>(manifestPath)\n } catch (err) {\n attempts--\n if (attempts <= 0) throw err\n\n await wait(100)\n }\n }\n}\n\nasync function tryLoadClientReferenceManifest(\n manifestPath: string,\n entryName: string,\n attempts?: number\n): Promise<DeepReadonly<ClientReferenceManifest> | undefined> {\n try {\n const context = await evalManifestWithRetries<{\n __RSC_MANIFEST: { [key: string]: ClientReferenceManifest }\n }>(manifestPath, attempts)\n return context.__RSC_MANIFEST[entryName]\n } catch (err) {\n return undefined\n }\n}\n\nasync function loadComponentsImpl<\n N extends GenericComponentMod = GenericComponentMod,\n>({\n distDir,\n page,\n isAppPath,\n isDev,\n sriEnabled,\n // When route modules are used, which is the case for the server calls to loadComponents, it no longer needs manifest to be loaded here.\n // Static generation still needs the manifests to be loaded here.\n // In the future static generation will also use route modules, and we will remove this flag.\n needsManifestsForLegacyReasons,\n}: {\n distDir: string\n page: string\n isAppPath: boolean\n isDev: boolean\n sriEnabled: boolean\n needsManifestsForLegacyReasons: boolean\n}): Promise<LoadComponentsReturnType<N>> {\n let DocumentMod = {}\n let AppMod = {}\n if (!isAppPath) {\n ;[DocumentMod, AppMod] = await Promise.all([\n requirePage('/_document', distDir, false),\n requirePage('/_app', distDir, false),\n ])\n }\n\n if (needsManifestsForLegacyReasons) {\n // In dev mode we retry loading a manifest file to handle a race condition\n // that can occur while app and pages are compiling at the same time, and the\n // build-manifest is still being written to disk while an app path is\n // attempting to load.\n const manifestLoadAttempts = isDev ? 3 : 1\n\n let reactLoadableManifestPath: string\n if (!process.env.TURBOPACK) {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n REACT_LOADABLE_MANIFEST\n )\n } else if (isAppPath) {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'app',\n page,\n REACT_LOADABLE_MANIFEST\n )\n } else {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'pages',\n normalizePagePath(page),\n REACT_LOADABLE_MANIFEST\n )\n }\n\n // Make sure to avoid loading the manifest for static metadata routes for better performance.\n const hasClientManifest = !isStaticMetadataRoute(page)\n\n // Load the manifest files first\n //\n // Loading page-specific manifests shouldn't throw an error if the manifest couldn't be found, so\n // that the `requirePage` call below will throw the correct error in that case\n // (a `PageNotFoundError`).\n const [\n buildManifest,\n reactLoadableManifest,\n dynamicCssManifest,\n clientReferenceManifest,\n serverActionsManifest,\n subresourceIntegrityManifest,\n ] = await Promise.all([\n loadManifestWithRetries<BuildManifest>(\n join(/* turbopackIgnore: true */ distDir, BUILD_MANIFEST),\n manifestLoadAttempts\n ),\n tryLoadManifestWithRetries<ReactLoadableManifest>(\n reactLoadableManifestPath,\n manifestLoadAttempts\n ),\n // This manifest will only exist in Pages dir && Production && Webpack.\n isAppPath || process.env.TURBOPACK\n ? undefined\n : loadManifestWithRetries<DynamicCssManifest>(\n join(\n /* turbopackIgnore: true */ distDir,\n `${DYNAMIC_CSS_MANIFEST}.json`\n ),\n manifestLoadAttempts\n ).catch(() => undefined),\n isAppPath && hasClientManifest\n ? tryLoadClientReferenceManifest(\n join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'app',\n page.replace(/%5F/g, '_') +\n '_' +\n CLIENT_REFERENCE_MANIFEST +\n '.js'\n ),\n page.replace(/%5F/g, '_'),\n manifestLoadAttempts\n )\n : undefined,\n isAppPath\n ? loadManifestWithRetries<ActionManifest>(\n join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n SERVER_REFERENCE_MANIFEST + '.json'\n ),\n manifestLoadAttempts\n ).catch(() => null)\n : null,\n sriEnabled\n ? loadManifestWithRetries<DeepReadonly<Record<string, string>>>(\n join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n SUBRESOURCE_INTEGRITY_MANIFEST + '.json'\n )\n ).catch(() => undefined)\n : undefined,\n ])\n\n // Before requiring the actual page module, we have to set the reference\n // manifests to our global store so Server Action's encryption util can access\n // to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n\n const ComponentMod = await requirePage(page, distDir, isAppPath)\n\n const Component = interopDefault(ComponentMod)\n const Document = interopDefault(DocumentMod)\n const App = interopDefault(AppMod)\n\n const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =\n ComponentMod\n\n return {\n // @ts-expect-error this is indeed `{} || AppType` and not always `AppType`\n App,\n // @ts-expect-error this is indeed `{} || DocumentType` and not always `DocumentType`\n Document,\n Component,\n buildManifest,\n subresourceIntegrityManifest,\n reactLoadableManifest: reactLoadableManifest || {},\n dynamicCssManifest,\n pageConfig: ComponentMod.config || {},\n ComponentMod,\n getServerSideProps,\n getStaticProps,\n getStaticPaths,\n isAppPath,\n page,\n routeModule,\n }\n } else {\n const ComponentMod = await requirePage(page, distDir, isAppPath)\n\n const Component = interopDefault(ComponentMod)\n const Document = interopDefault(DocumentMod)\n const App = interopDefault(AppMod)\n\n const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =\n ComponentMod\n\n return {\n App,\n Document,\n Component,\n pageConfig: ComponentMod.config || {},\n ComponentMod,\n getServerSideProps,\n getStaticProps,\n getStaticPaths,\n isAppPath,\n page,\n routeModule,\n } as any // temporary `as any` to make TypeScript not fail so that the tests will run on the PR.\n }\n}\n\nexport const loadComponents = getTracer().wrap(\n LoadComponentsSpan.loadComponents,\n loadComponentsImpl\n)\n"],"names":["BUILD_MANIFEST","REACT_LOADABLE_MANIFEST","CLIENT_REFERENCE_MANIFEST","SERVER_REFERENCE_MANIFEST","DYNAMIC_CSS_MANIFEST","SUBRESOURCE_INTEGRITY_MANIFEST","join","requirePage","interopDefault","getTracer","LoadComponentsSpan","evalManifest","loadManifest","wait","setManifestsSingleton","normalizePagePath","isStaticMetadataRoute","loadManifestWithRetries","manifestPath","attempts","err","tryLoadManifestWithRetries","undefined","evalManifestWithRetries","tryLoadClientReferenceManifest","entryName","context","__RSC_MANIFEST","loadComponentsImpl","distDir","page","isAppPath","isDev","sriEnabled","needsManifestsForLegacyReasons","DocumentMod","AppMod","Promise","all","manifestLoadAttempts","reactLoadableManifestPath","process","env","TURBOPACK","hasClientManifest","buildManifest","reactLoadableManifest","dynamicCssManifest","clientReferenceManifest","serverActionsManifest","subresourceIntegrityManifest","catch","replace","ComponentMod","Component","Document","App","getServerSideProps","getStaticProps","getStaticPaths","routeModule","pageConfig","config","loadComponents","wrap"],"mappings":"AAiBA,SACEA,cAAc,EACdC,uBAAuB,EACvBC,yBAAyB,EACzBC,yBAAyB,EACzBC,oBAAoB,EACpBC,8BAA8B,QACzB,0BAAyB;AAChC,SAASC,I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ACF;AAEA,OAAO,MAAMG,iBAAiBtD,YAAYuD,IAAI,CAC5CtD,mBAAmBqD,cAAc,EACjCnC,oBACD","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/load-components.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type {\n AppType,\n DocumentType,\n NextComponentType,\n} from '../shared/lib/utils'\nimport type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'\nimport type {\n PageConfig,\n GetStaticPaths,\n GetServerSideProps,\n GetStaticProps,\n} from '../types'\nimport type { RouteModule } from './route-modules/route-module'\nimport type { BuildManifest } from './get-page-files'\nimport type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin'\n\nimport {\n BUILD_MANIFEST,\n REACT_LOADABLE_MANIFEST,\n CLIENT_REFERENCE_MANIFEST,\n SERVER_REFERENCE_MANIFEST,\n DYNAMIC_CSS_MANIFEST,\n SUBRESOURCE_INTEGRITY_MANIFEST,\n} from '../shared/lib/constants'\nimport { join } from 'path'\nimport { requirePage } from './require'\nimport { interopDefault } from '../lib/interop-default'\nimport { getTracer } from './lib/trace/tracer'\nimport { LoadComponentsSpan } from './lib/trace/constants'\nimport { evalManifest, loadManifest } from './load-manifest.external'\nimport { wait } from '../lib/wait'\nimport { setManifestsSingleton } from './app-render/manifests-singleton'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { isStaticMetadataRoute } from '../lib/metadata/is-metadata-route'\n\nexport type ManifestItem = {\n id: number | string\n files: string[]\n}\n\nexport type ReactLoadableManifest = { [moduleId: string]: ManifestItem }\n/**\n * This manifest prevents removing server rendered <link> tags after client\n * navigation. This is only needed under `Pages dir && Production && Webpack`.\n * @see https://github.com/vercel/next.js/pull/72959\n */\nexport type DynamicCssManifest = string[]\n\n/**\n * A manifest entry type for the react-loadable-manifest.json.\n *\n * The whole manifest.json is a type of `Record<pathname, LoadableManifest>`\n * where pathname is a string-based key points to the path of the page contains\n * each dynamic imports.\n */\nexport interface LoadableManifest {\n [k: string]: { id: string | number; files: string[] }\n}\n\nexport type GenericComponentMod = {\n handler(\n req: IncomingMessage,\n res: ServerResponse,\n ctx: {\n waitUntil?: (prom: Promise<void>) => void\n }\n ): Promise<void | null>\n}\n\nexport type LoadComponentsReturnType<\n NextModule extends GenericComponentMod = GenericComponentMod,\n> = {\n Component: NextComponentType\n pageConfig: PageConfig\n buildManifest: DeepReadonly<BuildManifest>\n subresourceIntegrityManifest?: DeepReadonly<Record<string, string>>\n reactLoadableManifest: DeepReadonly<ReactLoadableManifest>\n dynamicCssManifest?: DeepReadonly<DynamicCssManifest>\n Document: DocumentType\n App: AppType\n getStaticProps?: GetStaticProps\n getStaticPaths?: GetStaticPaths\n getServerSideProps?: GetServerSideProps\n ComponentMod: NextModule\n routeModule: RouteModule\n isAppPath?: boolean\n page: string\n multiZoneDraftMode?: boolean\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function loadManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return loadManifest<T>(manifestPath)\n } catch (err) {\n attempts--\n if (attempts <= 0) throw err\n\n await wait(100)\n }\n }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts, or return undefined.\n */\nexport async function tryLoadManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n try {\n return await loadManifestWithRetries<T>(manifestPath, attempts)\n } catch (err) {\n return undefined\n }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function evalManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return evalManifest<T>(manifestPath)\n } catch (err) {\n attempts--\n if (attempts <= 0) throw err\n\n await wait(100)\n }\n }\n}\n\n/**\n * Loads the client reference manifest that the bundler emitted for an app page,\n * or returns undefined if there is none. Both the manifest file and the entry\n * inside it are addressed by the page with `%5F` decoded back to `_`, so\n * callers pass the page as-is and this resolves both.\n */\nexport async function loadClientReferenceManifestForPage(\n distDir: string,\n page: string,\n attempts?: number\n): Promise<DeepReadonly<ClientReferenceManifest> | undefined> {\n const entryName = page.replace(/%5F/g, '_')\n\n const manifestPath = join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'app',\n entryName + '_' + CLIENT_REFERENCE_MANIFEST + '.js'\n )\n\n try {\n const context = await evalManifestWithRetries<{\n __RSC_MANIFEST: { [key: string]: ClientReferenceManifest }\n }>(manifestPath, attempts)\n return context.__RSC_MANIFEST[entryName]\n } catch (err) {\n return undefined\n }\n}\n\nasync function loadComponentsImpl<\n N extends GenericComponentMod = GenericComponentMod,\n>({\n distDir,\n page,\n isAppPath,\n isDev,\n sriEnabled,\n // When route modules are used, which is the case for the server calls to loadComponents, it no longer needs manifest to be loaded here.\n // Static generation still needs the manifests to be loaded here.\n // In the future static generation will also use route modules, and we will remove this flag.\n needsManifestsForLegacyReasons,\n}: {\n distDir: string\n page: string\n isAppPath: boolean\n isDev: boolean\n sriEnabled: boolean\n needsManifestsForLegacyReasons: boolean\n}): Promise<LoadComponentsReturnType<N>> {\n let DocumentMod = {}\n let AppMod = {}\n if (!isAppPath) {\n ;[DocumentMod, AppMod] = await Promise.all([\n requirePage('/_document', distDir, false),\n requirePage('/_app', distDir, false),\n ])\n }\n\n if (needsManifestsForLegacyReasons) {\n // In dev mode we retry loading a manifest file to handle a race condition\n // that can occur while app and pages are compiling at the same time, and the\n // build-manifest is still being written to disk while an app path is\n // attempting to load.\n const manifestLoadAttempts = isDev ? 3 : 1\n\n let reactLoadableManifestPath: string\n if (!process.env.TURBOPACK) {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n REACT_LOADABLE_MANIFEST\n )\n } else if (isAppPath) {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'app',\n page,\n REACT_LOADABLE_MANIFEST\n )\n } else {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'pages',\n normalizePagePath(page),\n REACT_LOADABLE_MANIFEST\n )\n }\n\n // Make sure to avoid loading the manifest for static metadata routes for better performance.\n const hasClientManifest = !isStaticMetadataRoute(page)\n\n // Load the manifest files first\n //\n // Loading page-specific manifests shouldn't throw an error if the manifest couldn't be found, so\n // that the `requirePage` call below will throw the correct error in that case\n // (a `PageNotFoundError`).\n const [\n buildManifest,\n reactLoadableManifest,\n dynamicCssManifest,\n clientReferenceManifest,\n serverActionsManifest,\n subresourceIntegrityManifest,\n ] = await Promise.all([\n loadManifestWithRetries<BuildManifest>(\n join(/* turbopackIgnore: true */ distDir, BUILD_MANIFEST),\n manifestLoadAttempts\n ),\n tryLoadManifestWithRetries<ReactLoadableManifest>(\n reactLoadableManifestPath,\n manifestLoadAttempts\n ),\n // This manifest will only exist in Pages dir && Production && Webpack.\n isAppPath || process.env.TURBOPACK\n ? undefined\n : loadManifestWithRetries<DynamicCssManifest>(\n join(\n /* turbopackIgnore: true */ distDir,\n `${DYNAMIC_CSS_MANIFEST}.json`\n ),\n manifestLoadAttempts\n ).catch(() => undefined),\n isAppPath && hasClientManifest\n ? loadClientReferenceManifestForPage(\n distDir,\n page,\n manifestLoadAttempts\n )\n : undefined,\n isAppPath\n ? loadManifestWithRetries<ActionManifest>(\n join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n SERVER_REFERENCE_MANIFEST + '.json'\n ),\n manifestLoadAttempts\n ).catch(() => null)\n : null,\n sriEnabled\n ? loadManifestWithRetries<DeepReadonly<Record<string, string>>>(\n join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n SUBRESOURCE_INTEGRITY_MANIFEST + '.json'\n )\n ).catch(() => undefined)\n : undefined,\n ])\n\n // Before requiring the actual page module, we have to set the reference\n // manifests to our global store so Server Action's encryption util can access\n // to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n\n const ComponentMod = await requirePage(page, distDir, isAppPath)\n\n const Component = interopDefault(ComponentMod)\n const Document = interopDefault(DocumentMod)\n const App = interopDefault(AppMod)\n\n const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =\n ComponentMod\n\n return {\n // @ts-expect-error this is indeed `{} || AppType` and not always `AppType`\n App,\n // @ts-expect-error this is indeed `{} || DocumentType` and not always `DocumentType`\n Document,\n Component,\n buildManifest,\n subresourceIntegrityManifest,\n reactLoadableManifest: reactLoadableManifest || {},\n dynamicCssManifest,\n pageConfig: ComponentMod.config || {},\n ComponentMod,\n getServerSideProps,\n getStaticProps,\n getStaticPaths,\n isAppPath,\n page,\n routeModule,\n }\n } else {\n const ComponentMod = await requirePage(page, distDir, isAppPath)\n\n const Component = interopDefault(ComponentMod)\n const Document = interopDefault(DocumentMod)\n const App = interopDefault(AppMod)\n\n const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =\n ComponentMod\n\n return {\n App,\n Document,\n Component,\n pageConfig: ComponentMod.config || {},\n ComponentMod,\n getServerSideProps,\n getStaticProps,\n getStaticPaths,\n isAppPath,\n page,\n routeModule,\n } as any // temporary `as any` to make TypeScript not fail so that the tests will run on the PR.\n }\n}\n\nexport const loadComponents = getTracer().wrap(\n LoadComponentsSpan.loadComponents,\n loadComponentsImpl\n)\n"],"names":["BUILD_MANIFEST","REACT_LOADABLE_MANIFEST","CLIENT_REFERENCE_MANIFEST","SERVER_REFERENCE_MANIFEST","DYNAMIC_CSS_MANIFEST","SUBRESOURCE_INTEGRITY_MANIFEST","join","requirePage","interopDefault","getTracer","LoadComponentsSpan","evalManifest","loadManifest","wait","setManifestsSingleton","normalizePagePath","isStaticMetadataRoute","loadManifestWithRetries","manifestPath","attempts","err","tryLoadManifestWithRetries","undefined","evalManifestWithRetries","loadClientReferenceManifestForPage","distDir","page","entryName","replace","context","__RSC_MANIFEST","loadComponentsImpl","isAppPath","isDev","sriEnabled","needsManifestsForLegacyReasons","DocumentMod","AppMod","Promise","all","manifestLoadAttempts","reactLoadableManifestPath","process","env","TURBOPACK","hasClientManifest","buildManifest","reactLoadableManifest","dynamicCssManifest","clientReferenceManifest","serverActionsManifest","subresourceIntegrityManifest","catch","ComponentMod","Component","Document","App","getServerSideProps","getStaticProps","getStaticPaths","routeModule","pageConfig","config","loadComponents","wrap"],"mappings":"AAiBA,SACEA,cAAc,EACdC,uBAAuB,EACvBC,yBAAyB,EACzBC,yBAAyB,EACzBC,oBAAoB,EACpBC,8BAA8B,QACzB,0BAAyB;AAChC,SAASC,IAAI,QAAQ,OAAM;AAC3B,SAASC,WAAW,QAAQ,YAAW;AACvC,SAASC,cAAc,QAAQ,yBAAwB;AACvD,SAASC,SAAS,QAAQ,qBAAoB;AAC9C,SAASC,kBAAkB,QAAQ,wBAAuB;AAC1D,SAASC,YAAY,EAAEC,YAAY,QAAQ,2BAA0B;AACrE,SAASC,IAAI,QAAQ,cAAa;AAClC,SAASC,qBAAqB,QAAQ,mCAAkC;AAExE,SAASC,iBAAiB,QAAQ,8CAA6C;AAC/E,SAASC,qBAAqB,QAAQ,oCAAmC;AAyDzE;;CAEC,GACD,OAAO,eAAeC,wBACpBC,YAAoB,EACpBC,WAAW,CAAC;IAEZ,MAAO,KAAM;QACX,IAAI;YACF,OAAOP,aAAgBM;QACzB,EAAE,OAAOE,KAAK;YACZD;YACA,IAAIA,YAAY,GAAG,MAAMC;YAEzB,MAAMP,KAAK;QACb;IACF;AACF;AAEA;;CAEC,GACD,OAAO,eAAeQ,2BACpBH,YAAoB,EACpBC,WAAW,CAAC;IAEZ,IAAI;QACF,OAAO,MAAMF,wBAA2BC,cAAcC;IACxD,EAAE,OAAOC,KAAK;QACZ,OAAOE;IACT;AACF;AAEA;;CAEC,GACD,OAAO,eAAeC,wBACpBL,YAAoB,EACpBC,WAAW,CAAC;IAEZ,MAAO,KAAM;QACX,IAAI;YACF,OAAOR,aAAgBO;QACzB,EAAE,OAAOE,KAAK;YACZD;YACA,IAAIA,YAAY,GAAG,MAAMC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,MAAMP,eAAe,MAAM9C,YAAYmB,MAAMD,SAASO;QAEtD,MAAMsB,YAAY9C,eAAe6C;QACjC,MAAME,WAAW/C,eAAe4B;QAChC,MAAMoB,MAAMhD,eAAe6B;QAE3B,MAAM,EAAEoB,kBAAkB,EAAEC,cAAc,EAAEC,cAAc,EAAEC,WAAW,EAAE,GACvEP;QAEF,OAAO;YACLG;YACAD;YACAD;YACAO,YAAYR,aAAaS,MAAM,IAAI,CAAC;YACpCT;YACAI;YACAC;YACAC;YACA3B;YACAN;YACAkC;QACF,GAAS,uFAAuF;IAClG;AACF;AAEA,OAAO,MAAMG,iBAAiBtD,YAAYuD,IAAI,CAC5CtD,mBAAmBqD,cAAc,EACjChC,oBACD","ignoreList":[0]} |
@@ -1,6 +0,5 @@ | ||
| import { findSourceMap as nativeFindSourceMap } from 'module'; | ||
| import * as path from 'path'; | ||
| import * as url from 'url'; | ||
| import { SourceMapConsumer as SyncSourceMapConsumer } from 'next/dist/compiled/source-map'; | ||
| import { devirtualizeReactServerURL, findApplicableSourceMapPayload, ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric, sourceMapIgnoreListsEverything } from './lib/source-maps'; | ||
| import { devirtualizeReactServerURL, findApplicableSourceMapPayload, findSourceMapPayload, ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric, sourceMapIgnoreListsEverything } from './lib/source-maps'; | ||
| import { parseStack } from './lib/parse-stack'; | ||
@@ -13,11 +12,32 @@ import { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'; | ||
| // TODO(veil): Set from Webpack as well | ||
| let bundlerFindSourceMapPayload = ()=>undefined; | ||
| // | ||
| // Stored on `globalThis` for the same reason as the code frame renderer below: | ||
| // this module is bundled into several runtimes that each get their own copy, | ||
| // and the copy that installs the implementation is not necessarily the one that | ||
| // symbolicates a frame. The dev validation worker depends on that, because it | ||
| // installs its implementation from the worker bundle while the frames are | ||
| // symbolicated by the app-page bundle's copy. | ||
| const BUNDLER_FIND_SOURCE_MAP = Symbol.for('next.dev.bundlerFindSourceMap'); | ||
| export function setBundlerFindSourceMapImplementation(findSourceMapImplementation) { | ||
| bundlerFindSourceMapPayload = findSourceMapImplementation; | ||
| ; | ||
| globalThis[BUNDLER_FIND_SOURCE_MAP] = findSourceMapImplementation; | ||
| } | ||
| let codeFrameRenderer; | ||
| function bundlerFindSourceMapPayload(sourceURL) { | ||
| var _globalThis_BUNDLER_FIND_SOURCE_MAP; | ||
| return (_globalThis_BUNDLER_FIND_SOURCE_MAP = globalThis[BUNDLER_FIND_SOURCE_MAP]) == null ? void 0 : _globalThis_BUNDLER_FIND_SOURCE_MAP.call(globalThis, sourceURL); | ||
| } | ||
| // The code-frame renderer is stored on `globalThis` rather than in a module | ||
| // variable because this module is bundled into several runtimes (the dev | ||
| // server, the app-page runtime bundle, and the dev worker bundles) that each | ||
| // get their own copy. `Error.prepareStackTrace` is a single process-global, so | ||
| // whichever copy patched it last is the one that renders errors, which may not | ||
| // be the copy `setCodeFrameRenderer` was called on. Sharing the renderer | ||
| // through a `globalThis` symbol lets any copy install it and any copy read it. | ||
| const CODE_FRAME_RENDERER = Symbol.for('next.dev.codeFrameRenderer'); | ||
| export function setCodeFrameRenderer(renderer) { | ||
| codeFrameRenderer = renderer; | ||
| ; | ||
| globalThis[CODE_FRAME_RENDERER] = renderer; | ||
| } | ||
| function getOriginalCodeFrame(frame, source, colors = process.stdout.isTTY) { | ||
| const codeFrameRenderer = globalThis[CODE_FRAME_RENDERER]; | ||
| if (!codeFrameRenderer) { | ||
@@ -29,2 +49,23 @@ // No renderer available - gracefully degrade | ||
| } | ||
| // Constructing a consumer indexes the whole payload — expensive for large | ||
| // chunk maps and previously paid per frame — so consumers are shared across | ||
| // all frames and errors whose lookups returned the same payload. The inner | ||
| // key is the URL the consumer resolves relative `sources` against. | ||
| const sourceMapConsumers = new WeakMap(); | ||
| function getOrCreateSourceMapConsumer(payload, sourceMapURL) { | ||
| let consumersByURL = sourceMapConsumers.get(payload); | ||
| let consumer = consumersByURL == null ? void 0 : consumersByURL.get(sourceMapURL); | ||
| if (consumer === undefined) { | ||
| consumer = new SyncSourceMapConsumer(payload, // @ts-expect-error: our typings don't include this parameter but it is here. | ||
| sourceMapURL); | ||
| if (consumersByURL === undefined) { | ||
| consumersByURL = new Map(); | ||
| // Throws for payloads that aren't objects; those are invalid source | ||
| // maps anyway, and the caller reports them. | ||
| sourceMapConsumers.set(payload, consumersByURL); | ||
| } | ||
| consumersByURL.set(sourceMapURL, consumer); | ||
| } | ||
| return consumer; | ||
| } | ||
| function frameToString(methodName, sourceURL, line1, column1) { | ||
@@ -114,4 +155,16 @@ let sourceLocation = line1 !== null ? `:${line1}` : ''; | ||
| try { | ||
| const sourceMap = nativeFindSourceMap(sourceURL); | ||
| maybeSourceMapPayload = sourceMap == null ? void 0 : sourceMap.payload; | ||
| maybeSourceMapPayload = findSourceMapPayload(sourceURL); | ||
| if (maybeSourceMapPayload === undefined && sourceURL.startsWith('file://')) { | ||
| // Devirtualizing React's fake frame URL decodes the path, while Node.js | ||
| // keys its source map cache by the `pathToFileURL` encoding of the same | ||
| // path, so a path containing characters that encoding escapes (such as | ||
| // the brackets in Turbopack's `[root-of-the-server]` chunks) misses | ||
| // above. Node.js also accepts the plain path, which is unambiguous for | ||
| // both interpretations, so retry with that before giving up. | ||
| // | ||
| // TODO(veil): Making React's fake frame URLs reversible, as proposed in | ||
| // https://github.com/react/react/pull/37105, would let the first lookup | ||
| // succeed on its own and retire this retry. | ||
| maybeSourceMapPayload = findSourceMapPayload(url.fileURLToPath(sourceURL)); | ||
| } | ||
| } catch (cause) { | ||
@@ -149,4 +202,3 @@ // We should not log an actual error instance here because that will re-enter | ||
| const sourceMapURL = sourceURL + '.map'; | ||
| sourceMapConsumer = new SyncSourceMapConsumer(sourceMapPayload, // @ts-expect-error: our typings don't include this parameter but it is here. | ||
| sourceMapURL); | ||
| sourceMapConsumer = getOrCreateSourceMapConsumer(sourceMapPayload, sourceMapURL); | ||
| } catch (cause) { | ||
@@ -153,0 +205,0 @@ // We should not log an actual error instance here because that will re-enter |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/patch-error-inspect.ts"],"sourcesContent":["import { findSourceMap as nativeFindSourceMap } from 'module'\nimport * as path from 'path'\nimport * as url from 'url'\nimport type * as util from 'util'\nimport { SourceMapConsumer as SyncSourceMapConsumer } from 'next/dist/compiled/source-map'\nimport {\n type ModernSourceMapPayload,\n devirtualizeReactServerURL,\n findApplicableSourceMapPayload,\n ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric,\n sourceMapIgnoreListsEverything,\n} from './lib/source-maps'\nimport { parseStack, type StackFrame } from './lib/parse-stack'\nimport type { IgnorableStackFrame } from '../next-devtools/server/shared'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { dim, italic } from '../lib/picocolors'\n\ntype FindSourceMapPayload = (\n sourceURL: string\n) => ModernSourceMapPayload | undefined\n// Find a source map using the bundler's API.\n// This is only a fallback for when Node.js fails to due to bugs e.g. https://github.com/nodejs/node/issues/52102\n// TODO: Remove once all supported Node.js versions are fixed.\n// TODO(veil): Set from Webpack as well\nlet bundlerFindSourceMapPayload: FindSourceMapPayload = () => undefined\n\nexport function setBundlerFindSourceMapImplementation(\n findSourceMapImplementation: FindSourceMapPayload\n): void {\n bundlerFindSourceMapPayload = findSourceMapImplementation\n}\n\n// Code frame renderer - injected by dev/build to avoid hard dependency on native bindings\ntype CodeFrameRenderer = (\n frame: IgnorableStackFrame,\n source: string | null,\n colors: boolean\n) => string | null\n\nlet codeFrameRenderer: CodeFrameRenderer | undefined\n\nexport function setCodeFrameRenderer(renderer: CodeFrameRenderer): void {\n codeFrameRenderer = renderer\n}\n\nfunction getOriginalCodeFrame(\n frame: IgnorableStackFrame,\n source: string | null,\n colors: boolean = process.stdout.isTTY\n): string | null {\n if (!codeFrameRenderer) {\n // No renderer available - gracefully degrade\n return null\n }\n return codeFrameRenderer(frame, source, colors)\n}\n\ntype SourceMapCache = Map<\n string,\n null | { map: SyncSourceMapConsumer; payload: ModernSourceMapPayload }\n>\n\nfunction frameToString(\n methodName: string | null,\n sourceURL: string | null,\n line1: number | null,\n column1: number | null\n): string {\n let sourceLocation = line1 !== null ? `:${line1}` : ''\n if (column1 !== null && sourceLocation !== '') {\n sourceLocation += `:${column1}`\n }\n\n let fileLocation: string | null\n if (\n sourceURL !== null &&\n sourceURL.startsWith('file://') &&\n URL.canParse(sourceURL)\n ) {\n // If not relative to CWD, the path is ambiguous to IDEs and clicking will prompt to select the file first.\n // In a multi-app repo, this leads to potentially larger file names but will make clicking snappy.\n // There's no tradeoff for the cases where `dir` in `next dev [dir]` is omitted\n // since relative to cwd is both the shortest and snappiest.\n fileLocation = path.relative(process.cwd(), url.fileURLToPath(sourceURL))\n } else if (sourceURL !== null && sourceURL.startsWith('/')) {\n fileLocation = path.relative(process.cwd(), sourceURL)\n } else {\n fileLocation = sourceURL\n }\n\n return methodName\n ? ` at ${methodName} (${fileLocation}${sourceLocation})`\n : ` at ${fileLocation}${sourceLocation}`\n}\n\nfunction computeErrorName(error: Error): string {\n // TODO: Node.js seems to use a different algorithm\n // class ReadonlyRequestCookiesError extends Error {}` would read `ReadonlyRequestCookiesError: [...]`\n // in the stack i.e. seems like under certain conditions it favors the constructor name.\n return error.name || 'Error'\n}\n\nfunction prepareUnsourcemappedStackTrace(\n error: Error,\n structuredStackTrace: any[]\n): string {\n const name = computeErrorName(error)\n const message = error.message || ''\n let stack = name + ': ' + message\n for (let i = 0; i < structuredStackTrace.length; i++) {\n stack += '\\n at ' + structuredStackTrace[i].toString()\n }\n return stack\n}\n\nfunction shouldIgnoreListGeneratedFrame(file: string): boolean {\n return file.startsWith('node:') || file.includes('node_modules')\n}\n\nfunction shouldIgnoreListOriginalFrame(file: string): boolean {\n return file.includes('node_modules')\n}\n\ninterface SourcemappableStackFrame extends StackFrame {\n file: NonNullable<StackFrame['file']>\n}\n\ninterface SourceMappedFrame {\n stack: IgnorableStackFrame\n // DEV only\n code: string | null\n}\n\nfunction createUnsourcemappedFrame(\n frame: SourcemappableStackFrame\n): SourceMappedFrame {\n return {\n stack: {\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n arguments: frame.arguments,\n ignored: shouldIgnoreListGeneratedFrame(frame.file),\n },\n code: null,\n }\n}\n\nfunction ignoreListAnonymousStackFramesIfSandwiched(\n sourceMappedFrames: Array<{\n stack: IgnorableStackFrame\n code: string | null\n }>\n) {\n return ignoreListAnonymousStackFramesIfSandwichedGeneric(\n sourceMappedFrames,\n (frame) => frame.stack.file === '<anonymous>',\n (frame) => frame.stack.ignored,\n (frame) => frame.stack.methodName,\n (frame) => {\n frame.stack.ignored = true\n }\n )\n}\n\n/**\n * @param frame\n * @param sourceMapCache\n * @returns The original frame if not sourcemapped.\n */\nfunction getSourcemappedFrameIfPossible(\n frame: SourcemappableStackFrame,\n sourceMapCache: SourceMapCache,\n inspectOptions: util.InspectOptions\n): {\n stack: IgnorableStackFrame\n code: string | null\n} {\n const sourceMapCacheEntry = sourceMapCache.get(frame.file)\n let sourceMapConsumer: SyncSourceMapConsumer\n let sourceMapPayload: ModernSourceMapPayload\n if (sourceMapCacheEntry === undefined) {\n // Fake frame scripts (`about://React/Server/file:///path/to/chunk.js?42`)\n // have their positions padded to match the underlying chunk, so they\n // resolve via the chunk's source map.\n let sourceURL = devirtualizeReactServerURL(frame.file)\n // e.g. \"/Users/foo/APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\"\n // or \"C:\\Users\\foo\\APP\\.next\\server\\chunks\\ssr\\[root-of-the-server]__2934a0._.js\"\n // will be keyed by Node.js as \"file:///APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\".\n // This is likely caused by `callsite.toString()` in `Error.prepareStackTrace converting file URLs to paths.\n //\n // But frame.file might also be \"webpack-internal:///(rsc)/./app/bad-sourcemap/page.js\" or\n // \"<anonymous>\" or \"node:internal/process/task_queues\" here\n if (path.isAbsolute(sourceURL)) {\n sourceURL = url.pathToFileURL(sourceURL).toString()\n }\n let maybeSourceMapPayload: ModernSourceMapPayload | undefined\n try {\n const sourceMap = nativeFindSourceMap(sourceURL)\n maybeSourceMapPayload = sourceMap?.payload\n } catch (cause) {\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n // If loading fails once, it'll fail every time.\n // So set the cache to avoid duplicate errors.\n sourceMapCache.set(frame.file, null)\n // Don't even fall back to the bundler because it might be not as strict\n // with regards to parsing and then we fail later once we consume the\n // source map payload.\n // This essentially avoids a redundant error where we fail here and then\n // later on consumption because the bundler just handed back an invalid\n // source map.\n return createUnsourcemappedFrame(frame)\n }\n if (maybeSourceMapPayload === undefined) {\n maybeSourceMapPayload = bundlerFindSourceMapPayload(sourceURL)\n }\n\n if (maybeSourceMapPayload === undefined) {\n return createUnsourcemappedFrame(frame)\n }\n sourceMapPayload = maybeSourceMapPayload\n try {\n // Pass the source map URL as the second parameter so that the consumer\n // can resolve relative paths in the source map's `sources` array. This is\n // a guess! Turbopack places .map files as siblings to the chunks so this\n // is sufficient to compute relative paths but is actually wrong (the\n // chunk and sourcemap have different content hashes). We are using the\n // node API to read the sourcemap and it doesn't give us access to the\n // URI. `sourceURL` is already devirtualized so that relative `sources`\n // resolve against the real chunk URL, not React's virtual one.\n const sourceMapURL = sourceURL + '.map'\n sourceMapConsumer = new SyncSourceMapConsumer(\n sourceMapPayload,\n // @ts-expect-error: our typings don't include this parameter but it is here.\n sourceMapURL\n )\n } catch (cause) {\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n // If creating the consumer fails once, it'll fail every time.\n // So set the cache to avoid duplicate errors.\n sourceMapCache.set(frame.file, null)\n return createUnsourcemappedFrame(frame)\n }\n sourceMapCache.set(frame.file, {\n map: sourceMapConsumer,\n payload: sourceMapPayload,\n })\n } else if (sourceMapCacheEntry === null) {\n // We failed earlier getting the payload or consumer.\n // Just return an unsourcemapped frame.\n // Errors will already be logged.\n return createUnsourcemappedFrame(frame)\n } else {\n sourceMapConsumer = sourceMapCacheEntry.map\n sourceMapPayload = sourceMapCacheEntry.payload\n }\n\n const sourcePosition = sourceMapConsumer.originalPositionFor({\n column: (frame.column1 ?? 1) - 1,\n line: frame.line1 ?? 1,\n })\n\n const applicableSourceMap = findApplicableSourceMapPayload(\n (frame.line1 ?? 1) - 1,\n (frame.column1 ?? 1) - 1,\n sourceMapPayload\n )\n let ignored =\n applicableSourceMap !== undefined &&\n sourceMapIgnoreListsEverything(applicableSourceMap)\n if (sourcePosition.source === null) {\n return {\n stack: {\n arguments: frame.arguments,\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n ignored: ignored || shouldIgnoreListGeneratedFrame(frame.file),\n },\n code: null,\n }\n }\n\n // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.\n if (applicableSourceMap === undefined) {\n console.error('No applicable source map found in sections for frame', frame)\n } else if (!ignored && shouldIgnoreListOriginalFrame(sourcePosition.source)) {\n // Externals may be libraries that don't ship ignoreLists.\n // This is really taking control away from libraries.\n // They should still ship `ignoreList` so that attached debuggers ignore-list their frames.\n // TODO: Maybe only ignore library sourcemaps if `ignoreList` is absent?\n // Though keep in mind that Turbopack omits empty `ignoreList`.\n // So if we establish this convention, we should communicate it to the ecosystem.\n ignored = true\n } else if (!ignored) {\n // TODO: O(n^2). Consider moving `ignoreList` into a Set\n const sourceIndex = applicableSourceMap.sources.indexOf(\n sourcePosition.source\n )\n ignored = applicableSourceMap.ignoreList?.includes(sourceIndex) ?? false\n }\n\n const originalFrame: IgnorableStackFrame = {\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n methodName: frame.methodName\n ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n ?.replace('__webpack_exports__.', ''),\n file: sourcePosition.source,\n line1: sourcePosition.line,\n column1: sourcePosition.column + 1,\n // TODO: c&p from async createOriginalStackFrame but why not frame.arguments?\n arguments: [],\n ignored,\n }\n\n /** undefined = not yet computed */\n let codeFrame: string | null | undefined\n\n return {\n stack: originalFrame,\n get code() {\n if (codeFrame === undefined) {\n const sourceContent: string | null =\n sourceMapConsumer.sourceContentFor(\n sourcePosition.source,\n /* returnNullOnMissing */ true\n ) ?? null\n codeFrame = getOriginalCodeFrame(\n originalFrame,\n sourceContent,\n inspectOptions.colors\n )\n }\n return codeFrame\n },\n }\n}\n\nfunction parseAndSourceMap(\n error: Error,\n inspectOptions: util.InspectOptions\n): string {\n const showIgnoreListed = process.env.__NEXT_SHOW_IGNORE_LISTED === 'true'\n // We overwrote Error.prepareStackTrace earlier so error.stack is not sourcemapped.\n let unparsedStack = String(error.stack)\n // We could just read it from `error.stack`.\n // This works around cases where a 3rd party `Error.prepareStackTrace` implementation\n // doesn't implement the name computation correctly.\n const errorName = computeErrorName(error)\n\n let idx = unparsedStack.indexOf('react_stack_bottom_frame')\n if (idx !== -1) {\n idx = unparsedStack.lastIndexOf('\\n', idx)\n } else {\n idx = unparsedStack.indexOf('react-stack-bottom-frame')\n if (idx !== -1) {\n idx = unparsedStack.lastIndexOf('\\n', idx)\n }\n }\n if (idx !== -1 && !showIgnoreListed) {\n // Cut off everything after the bottom frame since it'll be React internals.\n unparsedStack = unparsedStack.slice(0, idx)\n }\n\n const unsourcemappedStack = parseStack(unparsedStack)\n const sourceMapCache: SourceMapCache = new Map()\n\n const sourceMappedFrames: Array<{\n stack: IgnorableStackFrame\n code: string | null\n }> = []\n let sourceFrame: null | string = null\n for (const frame of unsourcemappedStack) {\n if (frame.file === null) {\n sourceMappedFrames.push({\n code: null,\n stack: {\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n arguments: frame.arguments,\n ignored: false,\n },\n })\n } else {\n const sourcemappedFrame = getSourcemappedFrameIfPossible(\n // We narrowed this earlier by bailing if `frame.file` is null.\n frame as SourcemappableStackFrame,\n sourceMapCache,\n inspectOptions\n )\n sourceMappedFrames.push(sourcemappedFrame)\n\n // We can determine the sourceframe here.\n // anonymous frames won't have a sourceframe so we don't need to scan\n // all stacks again to check if they are sandwiched between ignored frames.\n if (\n sourceFrame === null &&\n // TODO: Is this the right choice?\n !sourcemappedFrame.stack.ignored &&\n sourcemappedFrame.code !== null\n ) {\n sourceFrame = sourcemappedFrame.code\n }\n }\n }\n\n ignoreListAnonymousStackFramesIfSandwiched(sourceMappedFrames)\n\n let sourceMappedStack = ''\n for (let i = 0; i < sourceMappedFrames.length; i++) {\n const frame = sourceMappedFrames[i]\n\n if (!frame.stack.ignored) {\n sourceMappedStack +=\n '\\n' +\n frameToString(\n frame.stack.methodName,\n frame.stack.file,\n frame.stack.line1,\n frame.stack.column1\n )\n } else if (showIgnoreListed) {\n sourceMappedStack +=\n '\\n' +\n dim(\n frameToString(\n frame.stack.methodName,\n frame.stack.file,\n frame.stack.line1,\n frame.stack.column1\n )\n )\n }\n }\n\n if (sourceMappedStack === '' && sourceMappedFrames.length > 0) {\n // The `at` marker is important so that Node.js doesn't add square brackets\n // around the stringified error i.e. this results in\n // Error: message\n // at <ignore-listed frames>\n // instead of\n // [Error: message\n // at <ignore-listed frames>]\n sourceMappedStack = '\\n at ' + italic('ignore-listed frames')\n }\n\n return (\n errorName +\n ': ' +\n error.message +\n sourceMappedStack +\n (sourceFrame !== null ? '\\n' + sourceFrame : '')\n )\n}\n\nfunction sourceMapError(\n this: void,\n error: Error,\n inspectOptions: util.InspectOptions\n): Error {\n // Setting an undefined `cause` would print `[cause]: undefined`\n const options = error.cause !== undefined ? { cause: error.cause } : undefined\n\n // Create a new Error object with the source mapping applied and then use native\n // Node.js formatting on the result.\n const newError =\n error instanceof AggregateError\n ? // Preserve AggregateError's `errors` instance property\n new AggregateError(error.errors, error.message, options)\n : new Error(error.message, options)\n\n // TODO: Ensure `class MyError extends Error {}` prints `MyError` as the name\n newError.stack = parseAndSourceMap(error, inspectOptions)\n\n for (const key in error) {\n if (!Object.prototype.hasOwnProperty.call(newError, key)) {\n // @ts-expect-error -- We're copying all enumerable properties.\n // So they definitely exist on `this` and obviously have no type on `newError` (yet)\n newError[key] = error[key]\n }\n }\n\n return newError\n}\n\nexport function patchErrorInspectNodeJS(\n errorConstructor: ErrorConstructor\n): void {\n const inspectSymbol = Symbol.for('nodejs.util.inspect.custom')\n\n errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n // @ts-expect-error -- TODO upstream types\n errorConstructor.prototype[inspectSymbol] = function (\n depth: number,\n inspectOptions: util.InspectOptions,\n inspect: typeof util.inspect\n ): string {\n // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n return workUnitAsyncStorage.exit(() => {\n const newError = sourceMapError(this, inspectOptions)\n\n const originalCustomInspect = (newError as any)[inspectSymbol]\n // Prevent infinite recursion.\n // { customInspect: false } would result in `error.cause` not using our inspect.\n Object.defineProperty(newError, inspectSymbol, {\n value: undefined,\n enumerable: false,\n writable: true,\n })\n try {\n return inspect(newError, {\n ...inspectOptions,\n depth,\n })\n } finally {\n ;(newError as any)[inspectSymbol] = originalCustomInspect\n }\n })\n }\n}\n\nexport function patchErrorInspectEdgeLite(\n errorConstructor: ErrorConstructor\n): void {\n const inspectSymbol = Symbol.for('edge-runtime.inspect.custom')\n\n errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n // @ts-expect-error -- TODO upstream types\n errorConstructor.prototype[inspectSymbol] = function ({\n format,\n }: {\n format: (...args: unknown[]) => string\n }): string {\n // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n return workUnitAsyncStorage.exit(() => {\n const newError = sourceMapError(this, {})\n\n const originalCustomInspect = (newError as any)[inspectSymbol]\n // Prevent infinite recursion.\n Object.defineProperty(newError, inspectSymbol, {\n value: undefined,\n enumerable: false,\n writable: true,\n })\n try {\n return format(newError)\n } finally {\n ;(newError as any)[inspectSymbol] = originalCustomInspect\n }\n })\n }\n}\n"],"names":["findSourceMap","nativeFindSourceMap","path","url","SourceMapConsumer","SyncSourceMapConsumer","devirtualizeReactServerURL","findApplicableSourceMapPayload","ignoreListAnonymousStackFramesIfSandwiched","ignoreListAnonymousStackFramesIfSandwichedGeneric","sourceMapIgnoreListsEverything","parseStack","workUnitAsyncStorage","dim","italic","bundlerFindSourceMapPayload","undefined","setBundlerFindSourceMapImplementation","findSourceMapImplementation","codeFrameRenderer","setCodeFrameRenderer","renderer","getOriginalCodeFrame","frame","source","colors","process","stdout","isTTY","frameToString","methodName","sourceURL","line1","column1","sourceLocation","fileLocation","startsWith","URL","canParse","relative","cwd","fileURLToPath","computeErrorName","error","name","prepareUnsourcemappedStackTrace","structuredStackTrace","message","stack","i","length","toString","shouldIgnoreListGeneratedFrame","file","includes","shouldIgnoreListOriginalFrame","createUnsourcemappedFrame","arguments","ignored","code","sourceMappedFrames","getSourcemappedFrameIfPossible","sourceMapCache","inspectOptions","sourceMapCacheEntry","get","sourceMapConsumer","sourceMapPayload","isAbsolute","pathToFileURL","maybeSourceMapPayload","sourceMap","payload","cause","console","set","sourceMapURL","map","sourcePosition","originalPositionFor","column","line","applicableSourceMap","sourceIndex","sources","indexOf","ignoreList","originalFrame","replace","codeFrame","sourceContent","sourceContentFor","parseAndSourceMap","showIgnoreListed","env","__NEXT_SHOW_IGNORE_LISTED","unparsedStack","String","errorName","idx","lastIndexOf","slice","unsourcemappedStack","Map","sourceFrame","push","sourcemappedFrame","sourceMappedStack","sourceMapError","options","newError","AggregateError","errors","Error","key","Object","prototype","hasOwnProperty","call","patchErrorInspectNodeJS","errorConstructor","inspectSymbol","Symbol","for","prepareStackTrace","depth","inspect","exit","originalCustomInspect","defineProperty","value","enumerable","writable","patchErrorInspectEdgeLite","format"],"mappings":"AAAA,SAASA,iBAAiBC,mBAAmB,QAAQ,SAAQ;AAC7D,YAAYC,UAAU,OAAM;AAC5B,YAAYC,SAAS,MAAK;AAE1B,SAASC,qBAAqBC,qBAAqB,QAAQ,gCAA+B;AAC1F,SAEEC,0BAA0B,EAC1BC,8BAA8B,EAC9BC,8CAA8CC,iDAAiD,EAC/FC,8BAA8B,QACzB,oBAAmB;AAC1B,SAASC,UAAU,QAAyB,oBAAmB;AAE/D,SAASC,oBAAoB,QAAQ,gDAA+C;AACpF,SAASC,GAAG,EAAEC,MAAM,QAAQ,oBAAmB;AAK/C,6CAA6C;AAC7C,iHAAiH;AACjH,8DAA8D;AAC9D,uCAAuC;AACvC,IAAIC,8BAAoD,IAAMC;AAE9D,OAAO,SAASC,sCACdC,2BAAiD;IAEjDH,8BAA8BG;AAChC;AASA,IAAIC;AAEJ,OAAO,SAASC,qBAAqBC,QAA2B;IAC9DF,oBAAoBE;AACtB;AAEA,SAASC,qBACPC,KAA0B,EAC1BC,MAAqB,EACrBC,SAAkBC,QAAQC,MAAM,CAACC,KAAK;IAEtC,IAAI,CAACT,mBAAmB;QACtB,6CAA6C;QAC7C,OAAO;IACT;IACA,OAAOA,kBAAkBI,OAAOC,QAAQC;AAC1C;AAOA,SAASI,cACPC,UAAyB,EACzBC,SAAwB,EACxBC,KAAoB,EACpBC,OAAsB;IAEtB,IAAIC,iBAAiBF,UAAU,OAAO,CAAC,CAAC,EAAEA,OAAO,GAAG;IACpD,IAAIC,YAAY,QAAQC,mBAAmB,IAAI;QAC7CA,kBAAkB,CAAC,CAAC,EAAED,SAAS;IACjC;IAEA,IAAIE;IACJ,IACEJ,cAAc,QACdA,UAAUK,UAAU,CAAC,cACrBC,IAAIC,QAAQ,CAACP,YACb;QACA,2GAA2G;QAC3G,kGAAkG;QAClG,+EAA+E;QAC/E,4DAA4D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CH,iBAAiBI,iBAAiB,GAAG/E;IAErC,0CAA0C;IAC1C2E,iBAAiBJ,SAAS,CAACK,cAAc,GAAG,SAAU,EACpDa,MAAM,EAGP;QACC,gGAAgG;QAChG,OAAO1H,qBAAqBmH,IAAI,CAAC;YAC/B,MAAMjB,WAAWF,eAAe,IAAI,EAAE,CAAC;YAEvC,MAAMoB,wBAAwB,AAAClB,QAAgB,CAACW,cAAc;YAC9D,8BAA8B;YAC9BN,OAAOc,cAAc,CAACnB,UAAUW,eAAe;gBAC7CS,OAAOlH;gBACPmH,YAAY;gBACZC,UAAU;YACZ;YACA,IAAI;gBACF,OAAOE,OAAOxB;YAChB,SAAU;;gBACNA,QAAgB,CAACW,cAAc,GAAGO;YACtC;QACF;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/patch-error-inspect.ts"],"sourcesContent":["import * as path from 'path'\nimport * as url from 'url'\nimport type * as util from 'util'\nimport { SourceMapConsumer as SyncSourceMapConsumer } from 'next/dist/compiled/source-map'\nimport {\n type ModernSourceMapPayload,\n devirtualizeReactServerURL,\n findApplicableSourceMapPayload,\n findSourceMapPayload,\n ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric,\n sourceMapIgnoreListsEverything,\n} from './lib/source-maps'\nimport { parseStack, type StackFrame } from './lib/parse-stack'\nimport type { IgnorableStackFrame } from '../next-devtools/server/shared'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { dim, italic } from '../lib/picocolors'\n\ntype FindSourceMapPayload = (\n sourceURL: string\n) => ModernSourceMapPayload | undefined\n// Find a source map using the bundler's API.\n// This is only a fallback for when Node.js fails to due to bugs e.g. https://github.com/nodejs/node/issues/52102\n// TODO: Remove once all supported Node.js versions are fixed.\n// TODO(veil): Set from Webpack as well\n//\n// Stored on `globalThis` for the same reason as the code frame renderer below:\n// this module is bundled into several runtimes that each get their own copy,\n// and the copy that installs the implementation is not necessarily the one that\n// symbolicates a frame. The dev validation worker depends on that, because it\n// installs its implementation from the worker bundle while the frames are\n// symbolicated by the app-page bundle's copy.\nconst BUNDLER_FIND_SOURCE_MAP = Symbol.for('next.dev.bundlerFindSourceMap')\ntype GlobalWithBundlerFindSourceMap = typeof globalThis & {\n [BUNDLER_FIND_SOURCE_MAP]?: FindSourceMapPayload\n}\n\nexport function setBundlerFindSourceMapImplementation(\n findSourceMapImplementation: FindSourceMapPayload\n): void {\n ;(globalThis as GlobalWithBundlerFindSourceMap)[BUNDLER_FIND_SOURCE_MAP] =\n findSourceMapImplementation\n}\n\nfunction bundlerFindSourceMapPayload(\n sourceURL: string\n): ModernSourceMapPayload | undefined {\n return (globalThis as GlobalWithBundlerFindSourceMap)[\n BUNDLER_FIND_SOURCE_MAP\n ]?.(sourceURL)\n}\n\n// Code frame renderer - injected by dev/build to avoid hard dependency on native bindings\ntype CodeFrameRenderer = (\n frame: IgnorableStackFrame,\n source: string | null,\n colors: boolean\n) => string | null\n\n// The code-frame renderer is stored on `globalThis` rather than in a module\n// variable because this module is bundled into several runtimes (the dev\n// server, the app-page runtime bundle, and the dev worker bundles) that each\n// get their own copy. `Error.prepareStackTrace` is a single process-global, so\n// whichever copy patched it last is the one that renders errors, which may not\n// be the copy `setCodeFrameRenderer` was called on. Sharing the renderer\n// through a `globalThis` symbol lets any copy install it and any copy read it.\nconst CODE_FRAME_RENDERER = Symbol.for('next.dev.codeFrameRenderer')\ntype GlobalWithCodeFrameRenderer = typeof globalThis & {\n [CODE_FRAME_RENDERER]?: CodeFrameRenderer\n}\n\nexport function setCodeFrameRenderer(renderer: CodeFrameRenderer): void {\n ;(globalThis as GlobalWithCodeFrameRenderer)[CODE_FRAME_RENDERER] = renderer\n}\n\nfunction getOriginalCodeFrame(\n frame: IgnorableStackFrame,\n source: string | null,\n colors: boolean = process.stdout.isTTY\n): string | null {\n const codeFrameRenderer = (globalThis as GlobalWithCodeFrameRenderer)[\n CODE_FRAME_RENDERER\n ]\n if (!codeFrameRenderer) {\n // No renderer available - gracefully degrade\n return null\n }\n return codeFrameRenderer(frame, source, colors)\n}\n\ntype SourceMapCache = Map<\n string,\n null | { map: SyncSourceMapConsumer; payload: ModernSourceMapPayload }\n>\n\n// Constructing a consumer indexes the whole payload — expensive for large\n// chunk maps and previously paid per frame — so consumers are shared across\n// all frames and errors whose lookups returned the same payload. The inner\n// key is the URL the consumer resolves relative `sources` against.\nconst sourceMapConsumers = new WeakMap<\n ModernSourceMapPayload,\n Map<string, SyncSourceMapConsumer>\n>()\n\nfunction getOrCreateSourceMapConsumer(\n payload: ModernSourceMapPayload,\n sourceMapURL: string\n): SyncSourceMapConsumer {\n let consumersByURL = sourceMapConsumers.get(payload)\n let consumer = consumersByURL?.get(sourceMapURL)\n if (consumer === undefined) {\n consumer = new SyncSourceMapConsumer(\n payload,\n // @ts-expect-error: our typings don't include this parameter but it is here.\n sourceMapURL\n )\n if (consumersByURL === undefined) {\n consumersByURL = new Map()\n // Throws for payloads that aren't objects; those are invalid source\n // maps anyway, and the caller reports them.\n sourceMapConsumers.set(payload, consumersByURL)\n }\n consumersByURL.set(sourceMapURL, consumer)\n }\n return consumer\n}\n\nfunction frameToString(\n methodName: string | null,\n sourceURL: string | null,\n line1: number | null,\n column1: number | null\n): string {\n let sourceLocation = line1 !== null ? `:${line1}` : ''\n if (column1 !== null && sourceLocation !== '') {\n sourceLocation += `:${column1}`\n }\n\n let fileLocation: string | null\n if (\n sourceURL !== null &&\n sourceURL.startsWith('file://') &&\n URL.canParse(sourceURL)\n ) {\n // If not relative to CWD, the path is ambiguous to IDEs and clicking will prompt to select the file first.\n // In a multi-app repo, this leads to potentially larger file names but will make clicking snappy.\n // There's no tradeoff for the cases where `dir` in `next dev [dir]` is omitted\n // since relative to cwd is both the shortest and snappiest.\n fileLocation = path.relative(process.cwd(), url.fileURLToPath(sourceURL))\n } else if (sourceURL !== null && sourceURL.startsWith('/')) {\n fileLocation = path.relative(process.cwd(), sourceURL)\n } else {\n fileLocation = sourceURL\n }\n\n return methodName\n ? ` at ${methodName} (${fileLocation}${sourceLocation})`\n : ` at ${fileLocation}${sourceLocation}`\n}\n\nfunction computeErrorName(error: Error): string {\n // TODO: Node.js seems to use a different algorithm\n // class ReadonlyRequestCookiesError extends Error {}` would read `ReadonlyRequestCookiesError: [...]`\n // in the stack i.e. seems like under certain conditions it favors the constructor name.\n return error.name || 'Error'\n}\n\nfunction prepareUnsourcemappedStackTrace(\n error: Error,\n structuredStackTrace: any[]\n): string {\n const name = computeErrorName(error)\n const message = error.message || ''\n let stack = name + ': ' + message\n for (let i = 0; i < structuredStackTrace.length; i++) {\n stack += '\\n at ' + structuredStackTrace[i].toString()\n }\n return stack\n}\n\nfunction shouldIgnoreListGeneratedFrame(file: string): boolean {\n return file.startsWith('node:') || file.includes('node_modules')\n}\n\nfunction shouldIgnoreListOriginalFrame(file: string): boolean {\n return file.includes('node_modules')\n}\n\ninterface SourcemappableStackFrame extends StackFrame {\n file: NonNullable<StackFrame['file']>\n}\n\ninterface SourceMappedFrame {\n stack: IgnorableStackFrame\n // DEV only\n code: string | null\n}\n\nfunction createUnsourcemappedFrame(\n frame: SourcemappableStackFrame\n): SourceMappedFrame {\n return {\n stack: {\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n arguments: frame.arguments,\n ignored: shouldIgnoreListGeneratedFrame(frame.file),\n },\n code: null,\n }\n}\n\nfunction ignoreListAnonymousStackFramesIfSandwiched(\n sourceMappedFrames: Array<{\n stack: IgnorableStackFrame\n code: string | null\n }>\n) {\n return ignoreListAnonymousStackFramesIfSandwichedGeneric(\n sourceMappedFrames,\n (frame) => frame.stack.file === '<anonymous>',\n (frame) => frame.stack.ignored,\n (frame) => frame.stack.methodName,\n (frame) => {\n frame.stack.ignored = true\n }\n )\n}\n\n/**\n * @param frame\n * @param sourceMapCache\n * @returns The original frame if not sourcemapped.\n */\nfunction getSourcemappedFrameIfPossible(\n frame: SourcemappableStackFrame,\n sourceMapCache: SourceMapCache,\n inspectOptions: util.InspectOptions\n): {\n stack: IgnorableStackFrame\n code: string | null\n} {\n const sourceMapCacheEntry = sourceMapCache.get(frame.file)\n let sourceMapConsumer: SyncSourceMapConsumer\n let sourceMapPayload: ModernSourceMapPayload\n if (sourceMapCacheEntry === undefined) {\n // Fake frame scripts (`about://React/Server/file:///path/to/chunk.js?42`)\n // have their positions padded to match the underlying chunk, so they\n // resolve via the chunk's source map.\n let sourceURL = devirtualizeReactServerURL(frame.file)\n // e.g. \"/Users/foo/APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\"\n // or \"C:\\Users\\foo\\APP\\.next\\server\\chunks\\ssr\\[root-of-the-server]__2934a0._.js\"\n // will be keyed by Node.js as \"file:///APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\".\n // This is likely caused by `callsite.toString()` in `Error.prepareStackTrace converting file URLs to paths.\n //\n // But frame.file might also be \"webpack-internal:///(rsc)/./app/bad-sourcemap/page.js\" or\n // \"<anonymous>\" or \"node:internal/process/task_queues\" here\n if (path.isAbsolute(sourceURL)) {\n sourceURL = url.pathToFileURL(sourceURL).toString()\n }\n let maybeSourceMapPayload: ModernSourceMapPayload | undefined\n try {\n maybeSourceMapPayload = findSourceMapPayload(sourceURL)\n\n if (\n maybeSourceMapPayload === undefined &&\n sourceURL.startsWith('file://')\n ) {\n // Devirtualizing React's fake frame URL decodes the path, while Node.js\n // keys its source map cache by the `pathToFileURL` encoding of the same\n // path, so a path containing characters that encoding escapes (such as\n // the brackets in Turbopack's `[root-of-the-server]` chunks) misses\n // above. Node.js also accepts the plain path, which is unambiguous for\n // both interpretations, so retry with that before giving up.\n //\n // TODO(veil): Making React's fake frame URLs reversible, as proposed in\n // https://github.com/react/react/pull/37105, would let the first lookup\n // succeed on its own and retire this retry.\n maybeSourceMapPayload = findSourceMapPayload(\n url.fileURLToPath(sourceURL)\n )\n }\n } catch (cause) {\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n // If loading fails once, it'll fail every time.\n // So set the cache to avoid duplicate errors.\n sourceMapCache.set(frame.file, null)\n // Don't even fall back to the bundler because it might be not as strict\n // with regards to parsing and then we fail later once we consume the\n // source map payload.\n // This essentially avoids a redundant error where we fail here and then\n // later on consumption because the bundler just handed back an invalid\n // source map.\n return createUnsourcemappedFrame(frame)\n }\n if (maybeSourceMapPayload === undefined) {\n maybeSourceMapPayload = bundlerFindSourceMapPayload(sourceURL)\n }\n\n if (maybeSourceMapPayload === undefined) {\n return createUnsourcemappedFrame(frame)\n }\n sourceMapPayload = maybeSourceMapPayload\n try {\n // Pass the source map URL as the second parameter so that the consumer\n // can resolve relative paths in the source map's `sources` array. This is\n // a guess! Turbopack places .map files as siblings to the chunks so this\n // is sufficient to compute relative paths but is actually wrong (the\n // chunk and sourcemap have different content hashes). We are using the\n // node API to read the sourcemap and it doesn't give us access to the\n // URI. `sourceURL` is already devirtualized so that relative `sources`\n // resolve against the real chunk URL, not React's virtual one.\n const sourceMapURL = sourceURL + '.map'\n sourceMapConsumer = getOrCreateSourceMapConsumer(\n sourceMapPayload,\n sourceMapURL\n )\n } catch (cause) {\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n // If creating the consumer fails once, it'll fail every time.\n // So set the cache to avoid duplicate errors.\n sourceMapCache.set(frame.file, null)\n return createUnsourcemappedFrame(frame)\n }\n sourceMapCache.set(frame.file, {\n map: sourceMapConsumer,\n payload: sourceMapPayload,\n })\n } else if (sourceMapCacheEntry === null) {\n // We failed earlier getting the payload or consumer.\n // Just return an unsourcemapped frame.\n // Errors will already be logged.\n return createUnsourcemappedFrame(frame)\n } else {\n sourceMapConsumer = sourceMapCacheEntry.map\n sourceMapPayload = sourceMapCacheEntry.payload\n }\n\n const sourcePosition = sourceMapConsumer.originalPositionFor({\n column: (frame.column1 ?? 1) - 1,\n line: frame.line1 ?? 1,\n })\n\n const applicableSourceMap = findApplicableSourceMapPayload(\n (frame.line1 ?? 1) - 1,\n (frame.column1 ?? 1) - 1,\n sourceMapPayload\n )\n let ignored =\n applicableSourceMap !== undefined &&\n sourceMapIgnoreListsEverything(applicableSourceMap)\n if (sourcePosition.source === null) {\n return {\n stack: {\n arguments: frame.arguments,\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n ignored: ignored || shouldIgnoreListGeneratedFrame(frame.file),\n },\n code: null,\n }\n }\n\n // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.\n if (applicableSourceMap === undefined) {\n console.error('No applicable source map found in sections for frame', frame)\n } else if (!ignored && shouldIgnoreListOriginalFrame(sourcePosition.source)) {\n // Externals may be libraries that don't ship ignoreLists.\n // This is really taking control away from libraries.\n // They should still ship `ignoreList` so that attached debuggers ignore-list their frames.\n // TODO: Maybe only ignore library sourcemaps if `ignoreList` is absent?\n // Though keep in mind that Turbopack omits empty `ignoreList`.\n // So if we establish this convention, we should communicate it to the ecosystem.\n ignored = true\n } else if (!ignored) {\n // TODO: O(n^2). Consider moving `ignoreList` into a Set\n const sourceIndex = applicableSourceMap.sources.indexOf(\n sourcePosition.source\n )\n ignored = applicableSourceMap.ignoreList?.includes(sourceIndex) ?? false\n }\n\n const originalFrame: IgnorableStackFrame = {\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n methodName: frame.methodName\n ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n ?.replace('__webpack_exports__.', ''),\n file: sourcePosition.source,\n line1: sourcePosition.line,\n column1: sourcePosition.column + 1,\n // TODO: c&p from async createOriginalStackFrame but why not frame.arguments?\n arguments: [],\n ignored,\n }\n\n /** undefined = not yet computed */\n let codeFrame: string | null | undefined\n\n return {\n stack: originalFrame,\n get code() {\n if (codeFrame === undefined) {\n const sourceContent: string | null =\n sourceMapConsumer.sourceContentFor(\n sourcePosition.source,\n /* returnNullOnMissing */ true\n ) ?? null\n codeFrame = getOriginalCodeFrame(\n originalFrame,\n sourceContent,\n inspectOptions.colors\n )\n }\n return codeFrame\n },\n }\n}\n\nfunction parseAndSourceMap(\n error: Error,\n inspectOptions: util.InspectOptions\n): string {\n const showIgnoreListed = process.env.__NEXT_SHOW_IGNORE_LISTED === 'true'\n // We overwrote Error.prepareStackTrace earlier so error.stack is not sourcemapped.\n let unparsedStack = String(error.stack)\n // We could just read it from `error.stack`.\n // This works around cases where a 3rd party `Error.prepareStackTrace` implementation\n // doesn't implement the name computation correctly.\n const errorName = computeErrorName(error)\n\n let idx = unparsedStack.indexOf('react_stack_bottom_frame')\n if (idx !== -1) {\n idx = unparsedStack.lastIndexOf('\\n', idx)\n } else {\n idx = unparsedStack.indexOf('react-stack-bottom-frame')\n if (idx !== -1) {\n idx = unparsedStack.lastIndexOf('\\n', idx)\n }\n }\n if (idx !== -1 && !showIgnoreListed) {\n // Cut off everything after the bottom frame since it'll be React internals.\n unparsedStack = unparsedStack.slice(0, idx)\n }\n\n const unsourcemappedStack = parseStack(unparsedStack)\n const sourceMapCache: SourceMapCache = new Map()\n\n const sourceMappedFrames: Array<{\n stack: IgnorableStackFrame\n code: string | null\n }> = []\n let sourceFrame: null | string = null\n for (const frame of unsourcemappedStack) {\n if (frame.file === null) {\n sourceMappedFrames.push({\n code: null,\n stack: {\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n arguments: frame.arguments,\n ignored: false,\n },\n })\n } else {\n const sourcemappedFrame = getSourcemappedFrameIfPossible(\n // We narrowed this earlier by bailing if `frame.file` is null.\n frame as SourcemappableStackFrame,\n sourceMapCache,\n inspectOptions\n )\n sourceMappedFrames.push(sourcemappedFrame)\n\n // We can determine the sourceframe here.\n // anonymous frames won't have a sourceframe so we don't need to scan\n // all stacks again to check if they are sandwiched between ignored frames.\n if (\n sourceFrame === null &&\n // TODO: Is this the right choice?\n !sourcemappedFrame.stack.ignored &&\n sourcemappedFrame.code !== null\n ) {\n sourceFrame = sourcemappedFrame.code\n }\n }\n }\n\n ignoreListAnonymousStackFramesIfSandwiched(sourceMappedFrames)\n\n let sourceMappedStack = ''\n for (let i = 0; i < sourceMappedFrames.length; i++) {\n const frame = sourceMappedFrames[i]\n\n if (!frame.stack.ignored) {\n sourceMappedStack +=\n '\\n' +\n frameToString(\n frame.stack.methodName,\n frame.stack.file,\n frame.stack.line1,\n frame.stack.column1\n )\n } else if (showIgnoreListed) {\n sourceMappedStack +=\n '\\n' +\n dim(\n frameToString(\n frame.stack.methodName,\n frame.stack.file,\n frame.stack.line1,\n frame.stack.column1\n )\n )\n }\n }\n\n if (sourceMappedStack === '' && sourceMappedFrames.length > 0) {\n // The `at` marker is important so that Node.js doesn't add square brackets\n // around the stringified error i.e. this results in\n // Error: message\n // at <ignore-listed frames>\n // instead of\n // [Error: message\n // at <ignore-listed frames>]\n sourceMappedStack = '\\n at ' + italic('ignore-listed frames')\n }\n\n return (\n errorName +\n ': ' +\n error.message +\n sourceMappedStack +\n (sourceFrame !== null ? '\\n' + sourceFrame : '')\n )\n}\n\nfunction sourceMapError(\n this: void,\n error: Error,\n inspectOptions: util.InspectOptions\n): Error {\n // Setting an undefined `cause` would print `[cause]: undefined`\n const options = error.cause !== undefined ? { cause: error.cause } : undefined\n\n // Create a new Error object with the source mapping applied and then use native\n // Node.js formatting on the result.\n const newError =\n error instanceof AggregateError\n ? // Preserve AggregateError's `errors` instance property\n new AggregateError(error.errors, error.message, options)\n : new Error(error.message, options)\n\n // TODO: Ensure `class MyError extends Error {}` prints `MyError` as the name\n newError.stack = parseAndSourceMap(error, inspectOptions)\n\n for (const key in error) {\n if (!Object.prototype.hasOwnProperty.call(newError, key)) {\n // @ts-expect-error -- We're copying all enumerable properties.\n // So they definitely exist on `this` and obviously have no type on `newError` (yet)\n newError[key] = error[key]\n }\n }\n\n return newError\n}\n\nexport function patchErrorInspectNodeJS(\n errorConstructor: ErrorConstructor\n): void {\n const inspectSymbol = Symbol.for('nodejs.util.inspect.custom')\n\n errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n // @ts-expect-error -- TODO upstream types\n errorConstructor.prototype[inspectSymbol] = function (\n depth: number,\n inspectOptions: util.InspectOptions,\n inspect: typeof util.inspect\n ): string {\n // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n return workUnitAsyncStorage.exit(() => {\n const newError = sourceMapError(this, inspectOptions)\n\n const originalCustomInspect = (newError as any)[inspectSymbol]\n // Prevent infinite recursion.\n // { customInspect: false } would result in `error.cause` not using our inspect.\n Object.defineProperty(newError, inspectSymbol, {\n value: undefined,\n enumerable: false,\n writable: true,\n })\n try {\n return inspect(newError, {\n ...inspectOptions,\n depth,\n })\n } finally {\n ;(newError as any)[inspectSymbol] = originalCustomInspect\n }\n })\n }\n}\n\nexport function patchErrorInspectEdgeLite(\n errorConstructor: ErrorConstructor\n): void {\n const inspectSymbol = Symbol.for('edge-runtime.inspect.custom')\n\n errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n // @ts-expect-error -- TODO upstream types\n errorConstructor.prototype[inspectSymbol] = function ({\n format,\n }: {\n format: (...args: unknown[]) => string\n }): string {\n // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n return workUnitAsyncStorage.exit(() => {\n const newError = sourceMapError(this, {})\n\n const originalCustomInspect = (newError as any)[inspectSymbol]\n // Prevent infinite recursion.\n Object.defineProperty(newError, inspectSymbol, {\n value: undefined,\n enumerable: false,\n writable: true,\n })\n try {\n return format(newError)\n } finally {\n ;(newError as any)[inspectSymbol] = originalCustomInspect\n }\n })\n }\n}\n"],"names":["path","url","SourceMapConsumer","SyncSourceMapConsumer","devirtualizeReactServerURL","findApplicableSourceMapPayload","findSourceMapPayload","ignoreListAnonymousStackFramesIfSandwiched","ignoreListAnonymousStackFramesIfSandwichedGeneric","sourceMapIgnoreListsEverything","parseStack","workUnitAsyncStorage","dim","italic","BUNDLER_FIND_SOURCE_MAP","Symbol","for","setBundlerFindSourceMapImplementation","findSourceMapImplementation","globalThis","bundlerFindSourceMapPayload","sourceURL","CODE_FRAME_RENDERER","setCodeFrameRenderer","renderer","getOriginalCodeFrame","frame","source","colors","process","stdout","isTTY","codeFrameRenderer","sourceMapConsumers","WeakMap","getOrCreateSourceMapConsumer","payload","sourceMapURL","consumersByURL","get","consumer","undefined","Map","set","frameToString","methodName","line1","column1","sourceLocation","fileLocation","startsWith","URL","canParse","relative","cwd","fileURLToPath","computeErrorName","error","name","prepareUnsourcemappedStackTrace","structuredStackTrace","message","stack","i","length","toString","shouldIgnoreListGeneratedFrame","file","includes","shouldIgnoreListOriginalFrame","createUnsourcemappedFrame","arguments","ignored","code","sourceMappedFrames","getSourcemappedFrameIfPossible","sourceMapCache","inspectOptions","sourceMapCacheEntry","sourceMapConsumer","sourceMapPayload","isAbsolute","pathToFileURL","maybeSourceMapPayload","cause","console","map","sourcePosition","originalPositionFor","column","line","applicableSourceMap","sourceIndex","sources","indexOf","ignoreList","originalFrame","replace","codeFrame","sourceContent","sourceContentFor","parseAndSourceMap","showIgnoreListed","env","__NEXT_SHOW_IGNORE_LISTED","unparsedStack","String","errorName","idx","lastIndexOf","slice","unsourcemappedStack","sourceFrame","push","sourcemappedFrame","sourceMappedStack","sourceMapError","options","newError","AggregateError","errors","Error","key","Object","prototype","hasOwnProperty","call","patchErrorInspectNodeJS","errorConstructor","inspectSymbol","prepareStackTrace","depth","inspect","exit","originalCustomInspect","defineProperty","value","enumerable","writable","patchErrorInspectEdgeLite","format"],"mappings":"AAAA,YAAYA,UAAU,OAAM;AAC5B,YAAYC,SAAS,MAAK;AAE1B,SAASC,qBAAqBC,qBAAqB,QAAQ,gCAA+B;AAC1F,SAEEC,0BAA0B,EAC1BC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BAA8B;YAC9BN,OAAOY,cAAc,CAACjB,UAAUW,eAAe;gBAC7CO,OAAO/F;gBACPgG,YAAY;gBACZC,UAAU;YACZ;YACA,IAAI;gBACF,OAAOE,OAAOtB;YAChB,SAAU;;gBACNA,QAAgB,CAACW,cAAc,GAAGK;YACtC;QACF;IACF;AACF","ignoreList":[0]} |
| import { addRequestMeta } from '../../request-meta'; | ||
| import { renderToHTMLOrFlight } from '../../app-render/app-render'; | ||
| import { renderToHTMLOrFlight, runValidationInDevFromSnapshot } from '../../app-render/app-render'; | ||
| import { RouteModule } from '../route-module'; | ||
@@ -62,2 +62,14 @@ import * as vendoredContexts from './vendored/contexts/entrypoints'; | ||
| } | ||
| /** | ||
| * Worker entry point for dev Cache Components dev validation. The dev | ||
| * validation worker reloads this route's module and calls this so the whole | ||
| * validation runs inside the app-page bundle's React instance (the same one | ||
| * the user's client components resolve through `componentMod`), rebuilding | ||
| * the render context from the transported `message`. `componentMod` is the | ||
| * reloaded module the worker holds; it's passed in because the route module | ||
| * has no back-reference to it. Returns the validation errors for the worker | ||
| * to serialize and the main thread to deliver to the dev overlay. | ||
| */ runValidationInDev(componentMod, message, abortSignal) { | ||
| return runValidationInDevFromSnapshot(message, componentMod, abortSignal); | ||
| } | ||
| pathCouldBeIntercepted(resolvedPathname, interceptionRoutePatterns) { | ||
@@ -64,0 +76,0 @@ return isInterceptionRouteAppPath(resolvedPathname) || interceptionRoutePatterns.some((regexp)=>{ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/route-modules/app-page/module.ts"],"sourcesContent":["import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition'\nimport type RenderResult from '../../render-result'\nimport type { RenderOpts } from '../../app-render/types'\nimport { addRequestMeta, type NextParsedUrlQuery } from '../../request-meta'\nimport type { LoaderTree } from '../../lib/app-dir-module'\nimport type { PrerenderManifest } from '../../../build'\n\nimport {\n renderToHTMLOrFlight,\n type AppSharedContext,\n} from '../../app-render/app-render'\nimport {\n RouteModule,\n type RouteModuleOptions,\n type RouteModuleHandleContext,\n} from '../route-module'\nimport * as vendoredContexts from './vendored/contexts/entrypoints'\nimport type { BaseNextRequest, BaseNextResponse } from '../../base-http'\nimport type { ServerComponentsHmrCache } from '../../response-cache'\nimport type { OpaqueFallbackRouteParams } from '../../request/fallback-params'\nimport { PrerenderManifestMatcher } from './helpers/prerender-manifest-matcher'\nimport type { DeepReadonly } from '../../../shared/lib/deep-readonly'\nimport {\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n RSC_HEADER,\n} from '../../../client/components/app-router-headers'\nimport { isInterceptionRouteAppPath } from '../../../shared/lib/router/utils/interception-routes'\nimport { RSCPathnameNormalizer } from '../../normalizers/request/rsc'\nimport { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { IncomingMessage } from 'http'\nimport {\n applyAppPageRscRequestMetaFromHeaders,\n normalizeAppPageRequestUrl,\n} from './normalize-request-url'\n\nlet vendoredReactRSC\nlet vendoredReactSSR\n\n// the vendored Reacts are loaded from their original source in the edge runtime\nif (process.env.NEXT_RUNTIME !== 'edge') {\n vendoredReactRSC =\n require('./vendored/rsc/entrypoints') as typeof import('./vendored/rsc/entrypoints')\n vendoredReactSSR =\n require('./vendored/ssr/entrypoints') as typeof import('./vendored/ssr/entrypoints')\n\n // In Node environments we need to access the correct React instance from external modules such\n // as global patches. We register the loaded React instances here.\n const { registerServerReact, registerClientReact } =\n require('../../runtime-reacts.external') as typeof import('../../runtime-reacts.external')\n registerServerReact(vendoredReactRSC.React)\n registerClientReact(vendoredReactSSR.React)\n}\n\n/**\n * The AppPageModule is the type of the module exported by the bundled app page\n * module.\n */\nexport type AppPageModule = typeof import('../../../build/templates/app-page')\n\ntype AppPageUserlandModule = {\n /**\n * The tree created in next-app-loader that holds component segments and modules\n */\n loaderTree: LoaderTree\n}\n\nexport interface AppPageRouteHandlerContext extends RouteModuleHandleContext {\n page: string\n query: NextParsedUrlQuery\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n renderOpts: RenderOpts\n serverComponentsHmrCache?: ServerComponentsHmrCache\n sharedContext: AppSharedContext\n}\n\nexport type AppPageRouteModuleOptions = RouteModuleOptions<\n AppPageRouteDefinition,\n AppPageUserlandModule\n>\n\nexport class AppPageRouteModule extends RouteModule<\n AppPageRouteDefinition,\n AppPageUserlandModule\n> {\n private matchers = new WeakMap<\n DeepReadonly<PrerenderManifest>,\n PrerenderManifestMatcher\n >()\n public match(\n pathname: string,\n prerenderManifest: DeepReadonly<PrerenderManifest>\n ) {\n // Lazily create the matcher based on the provided prerender manifest.\n let matcher = this.matchers.get(prerenderManifest)\n if (!matcher) {\n matcher = new PrerenderManifestMatcher(\n this.definition.pathname,\n prerenderManifest\n )\n this.matchers.set(prerenderManifest, matcher)\n }\n\n // Match the pathname to the dynamic route.\n return matcher.match(pathname)\n }\n\n private normalizers = {\n rsc: new RSCPathnameNormalizer(),\n segmentPrefetchRSC: new SegmentPrefixRSCPathnameNormalizer(),\n }\n\n public normalizeUrl(\n req: IncomingMessage | BaseNextRequest,\n parsedUrl: UrlWithParsedQuery\n ) {\n if (this.normalizers.segmentPrefetchRSC.match(parsedUrl.pathname || '/')) {\n const result = this.normalizers.segmentPrefetchRSC.extract(\n parsedUrl.pathname || '/'\n )\n if (!result) return false\n\n const { originalPathname, segmentPath } = result\n parsedUrl.pathname = originalPathname\n\n // Mark the request as a router prefetch request.\n req.headers[RSC_HEADER] = '1'\n req.headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath\n\n addRequestMeta(req, 'isRSCRequest', true)\n addRequestMeta(req, 'isPrefetchRSCRequest', true)\n addRequestMeta(req, 'segmentPrefetchRSCRequest', segmentPath)\n } else if (this.normalizers.rsc.match(parsedUrl.pathname || '/')) {\n parsedUrl.pathname = this.normalizers.rsc.normalize(\n parsedUrl.pathname || '/',\n true\n )\n\n // Mark the request as a RSC request.\n req.headers[RSC_HEADER] = '1'\n } else {\n super.normalizeUrl(req, parsedUrl)\n }\n\n // Minimal adapters can bypass base-server request normalization and invoke\n // route modules directly, so derive RSC/prefetch metadata from headers.\n applyAppPageRscRequestMetaFromHeaders(req)\n normalizeAppPageRequestUrl(req, parsedUrl.pathname || '/')\n }\n\n public render(\n req: BaseNextRequest,\n res: BaseNextResponse,\n context: AppPageRouteHandlerContext\n ): Promise<RenderResult> {\n return renderToHTMLOrFlight(\n req,\n res,\n context.page,\n context.query,\n context.fallbackRouteParams,\n context.renderOpts,\n context.serverComponentsHmrCache,\n context.sharedContext\n )\n }\n\n private pathCouldBeIntercepted(\n resolvedPathname: string,\n interceptionRoutePatterns: RegExp[]\n ): boolean {\n return (\n isInterceptionRouteAppPath(resolvedPathname) ||\n interceptionRoutePatterns.some((regexp) => {\n return regexp.test(resolvedPathname)\n })\n )\n }\n\n public getVaryHeader(\n resolvedPathname: string,\n interceptionRoutePatterns: RegExp[]\n ): string {\n const baseVaryHeader = `${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE_HEADER}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`\n\n if (\n this.pathCouldBeIntercepted(resolvedPathname, interceptionRoutePatterns)\n ) {\n // Interception route responses can vary based on the `Next-URL` header.\n // We use the Vary header to signal this behavior to the client to properly cache the response.\n return `${baseVaryHeader}, ${NEXT_URL}`\n } else {\n // We don't need to include `Next-URL` in the Vary header for non-interception routes since it won't affect the response.\n // We also set this header for pages to avoid caching issues when navigating between pages and app.\n return baseVaryHeader\n }\n }\n}\n\nconst vendored = {\n 'react-rsc': vendoredReactRSC,\n 'react-ssr': vendoredReactSSR,\n contexts: vendoredContexts,\n}\n\nexport { renderToHTMLOrFlight, vendored }\n\nexport default AppPageRouteModule\n"],"names":["addRequestMeta","renderToHTMLOrFlight","RouteModule","vendoredContexts","PrerenderManifestMatcher","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_URL","RSC_HEADER","isInterceptionRouteAppPath","RSCPathnameNormalizer","SegmentPrefixRSCPathnameNormalizer","applyAppPageRscRequestMetaFromHeaders","normalizeAppPageRequestUrl","vendoredReactRSC","vendoredReactSSR","process","env","NEXT_RUNTIME","require","registerServerReact","registerClientReact","React","AppPageRouteModule","match","pathname","prerenderManifest","matcher","matchers","get","definition","set","normalizeUrl","req","parsedUrl","normalizers","segmentPrefetchRSC","result","extract","originalPathname","segmentPath","headers","rsc","normalize","render","res","context","page","query","fallbackRouteParams","renderOpts","serverComponentsHmrCache","sharedContext","pathCouldBeIntercepted","resolvedPathname","interceptionRoutePatterns","some","regexp","test","getVaryHeader","baseVaryHeader","WeakMap","vendored","contexts"],"mappings":"AAGA,SAASA,cAAc,QAAiC,qBAAoB;AAI5E,SACEC,oBAAoB,QAEf,8BAA6B;AACpC,SACEC,WAAW,QAGN,kBAAiB;AACxB,YAAYC,sBAAsB,kCAAiC;AAInE,SAASC,wBAAwB,QAAQ,uCAAsC;AAE/E,SACEC,2BAA2B,EAC3BC,mCAAmC,EACnCC,6BAA6B,EAC7BC,QAAQ,EACRC,UAAU,QACL,gDAA+C;AACtD,SAASC,0BAA0B,QAAQ,uDAAsD;AACjG,SAASC,qBAAqB,QAAQ,gCAA+B;AACrE,SAASC,kCAAkC,QAAQ,+CAA8C;AAGjG,SACEC,qCAAqC,EACrCC,0BAA0B,QACrB,0BAAyB;AAEhC,IAAIC;AACJ,IAAIC;AAEJ,gFAAgF;AAChF,IAAIC,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCJ,mBACEK,QAAQ;IACVJ,mBACEI,QAAQ;IAEV,+FAA+F;IAC/F,kEAAkE;IAClE,MAAM,E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-modules/app-page/module.ts"],"sourcesContent":["import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition'\nimport type RenderResult from '../../render-result'\nimport type { RenderOpts } from '../../app-render/types'\nimport { addRequestMeta, type NextParsedUrlQuery } from '../../request-meta'\nimport type { LoaderTree } from '../../lib/app-dir-module'\nimport type { PrerenderManifest } from '../../../build'\n\nimport {\n renderToHTMLOrFlight,\n runValidationInDevFromSnapshot,\n type AppSharedContext,\n} from '../../app-render/app-render'\nimport type { DevValidationWorkerMessage } from '../../app-render/dev-validation-worker-globals'\nimport {\n RouteModule,\n type RouteModuleOptions,\n type RouteModuleHandleContext,\n} from '../route-module'\nimport * as vendoredContexts from './vendored/contexts/entrypoints'\nimport type { BaseNextRequest, BaseNextResponse } from '../../base-http'\nimport type { ServerComponentsHmrCache } from '../../response-cache'\nimport type { OpaqueFallbackRouteParams } from '../../request/fallback-params'\nimport { PrerenderManifestMatcher } from './helpers/prerender-manifest-matcher'\nimport type { DeepReadonly } from '../../../shared/lib/deep-readonly'\nimport {\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n RSC_HEADER,\n} from '../../../client/components/app-router-headers'\nimport { isInterceptionRouteAppPath } from '../../../shared/lib/router/utils/interception-routes'\nimport { RSCPathnameNormalizer } from '../../normalizers/request/rsc'\nimport { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { IncomingMessage } from 'http'\nimport {\n applyAppPageRscRequestMetaFromHeaders,\n normalizeAppPageRequestUrl,\n} from './normalize-request-url'\n\nlet vendoredReactRSC\nlet vendoredReactSSR\n\n// the vendored Reacts are loaded from their original source in the edge runtime\nif (process.env.NEXT_RUNTIME !== 'edge') {\n vendoredReactRSC =\n require('./vendored/rsc/entrypoints') as typeof import('./vendored/rsc/entrypoints')\n vendoredReactSSR =\n require('./vendored/ssr/entrypoints') as typeof import('./vendored/ssr/entrypoints')\n\n // In Node environments we need to access the correct React instance from external modules such\n // as global patches. We register the loaded React instances here.\n const { registerServerReact, registerClientReact } =\n require('../../runtime-reacts.external') as typeof import('../../runtime-reacts.external')\n registerServerReact(vendoredReactRSC.React)\n registerClientReact(vendoredReactSSR.React)\n}\n\n/**\n * The AppPageModule is the type of the module exported by the bundled app page\n * module.\n */\nexport type AppPageModule = typeof import('../../../build/templates/app-page')\n\ntype AppPageUserlandModule = {\n /**\n * The tree created in next-app-loader that holds component segments and modules\n */\n loaderTree: LoaderTree\n}\n\nexport interface AppPageRouteHandlerContext extends RouteModuleHandleContext {\n page: string\n query: NextParsedUrlQuery\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n renderOpts: RenderOpts\n serverComponentsHmrCache?: ServerComponentsHmrCache\n sharedContext: AppSharedContext\n}\n\nexport type AppPageRouteModuleOptions = RouteModuleOptions<\n AppPageRouteDefinition,\n AppPageUserlandModule\n>\n\nexport class AppPageRouteModule extends RouteModule<\n AppPageRouteDefinition,\n AppPageUserlandModule\n> {\n private matchers = new WeakMap<\n DeepReadonly<PrerenderManifest>,\n PrerenderManifestMatcher\n >()\n public match(\n pathname: string,\n prerenderManifest: DeepReadonly<PrerenderManifest>\n ) {\n // Lazily create the matcher based on the provided prerender manifest.\n let matcher = this.matchers.get(prerenderManifest)\n if (!matcher) {\n matcher = new PrerenderManifestMatcher(\n this.definition.pathname,\n prerenderManifest\n )\n this.matchers.set(prerenderManifest, matcher)\n }\n\n // Match the pathname to the dynamic route.\n return matcher.match(pathname)\n }\n\n private normalizers = {\n rsc: new RSCPathnameNormalizer(),\n segmentPrefetchRSC: new SegmentPrefixRSCPathnameNormalizer(),\n }\n\n public normalizeUrl(\n req: IncomingMessage | BaseNextRequest,\n parsedUrl: UrlWithParsedQuery\n ) {\n if (this.normalizers.segmentPrefetchRSC.match(parsedUrl.pathname || '/')) {\n const result = this.normalizers.segmentPrefetchRSC.extract(\n parsedUrl.pathname || '/'\n )\n if (!result) return false\n\n const { originalPathname, segmentPath } = result\n parsedUrl.pathname = originalPathname\n\n // Mark the request as a router prefetch request.\n req.headers[RSC_HEADER] = '1'\n req.headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath\n\n addRequestMeta(req, 'isRSCRequest', true)\n addRequestMeta(req, 'isPrefetchRSCRequest', true)\n addRequestMeta(req, 'segmentPrefetchRSCRequest', segmentPath)\n } else if (this.normalizers.rsc.match(parsedUrl.pathname || '/')) {\n parsedUrl.pathname = this.normalizers.rsc.normalize(\n parsedUrl.pathname || '/',\n true\n )\n\n // Mark the request as a RSC request.\n req.headers[RSC_HEADER] = '1'\n } else {\n super.normalizeUrl(req, parsedUrl)\n }\n\n // Minimal adapters can bypass base-server request normalization and invoke\n // route modules directly, so derive RSC/prefetch metadata from headers.\n applyAppPageRscRequestMetaFromHeaders(req)\n normalizeAppPageRequestUrl(req, parsedUrl.pathname || '/')\n }\n\n public render(\n req: BaseNextRequest,\n res: BaseNextResponse,\n context: AppPageRouteHandlerContext\n ): Promise<RenderResult> {\n return renderToHTMLOrFlight(\n req,\n res,\n context.page,\n context.query,\n context.fallbackRouteParams,\n context.renderOpts,\n context.serverComponentsHmrCache,\n context.sharedContext\n )\n }\n\n /**\n * Worker entry point for dev Cache Components dev validation. The dev\n * validation worker reloads this route's module and calls this so the whole\n * validation runs inside the app-page bundle's React instance (the same one\n * the user's client components resolve through `componentMod`), rebuilding\n * the render context from the transported `message`. `componentMod` is the\n * reloaded module the worker holds; it's passed in because the route module\n * has no back-reference to it. Returns the validation errors for the worker\n * to serialize and the main thread to deliver to the dev overlay.\n */\n public runValidationInDev(\n componentMod: AppPageModule,\n message: DevValidationWorkerMessage,\n abortSignal: AbortSignal\n ): Promise<Array<unknown> | undefined> {\n return runValidationInDevFromSnapshot(message, componentMod, abortSignal)\n }\n\n private pathCouldBeIntercepted(\n resolvedPathname: string,\n interceptionRoutePatterns: RegExp[]\n ): boolean {\n return (\n isInterceptionRouteAppPath(resolvedPathname) ||\n interceptionRoutePatterns.some((regexp) => {\n return regexp.test(resolvedPathname)\n })\n )\n }\n\n public getVaryHeader(\n resolvedPathname: string,\n interceptionRoutePatterns: RegExp[]\n ): string {\n const baseVaryHeader = `${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE_HEADER}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`\n\n if (\n this.pathCouldBeIntercepted(resolvedPathname, interceptionRoutePatterns)\n ) {\n // Interception route responses can vary based on the `Next-URL` header.\n // We use the Vary header to signal this behavior to the client to properly cache the response.\n return `${baseVaryHeader}, ${NEXT_URL}`\n } else {\n // We don't need to include `Next-URL` in the Vary header for non-interception routes since it won't affect the response.\n // We also set this header for pages to avoid caching issues when navigating between pages and app.\n return baseVaryHeader\n }\n }\n}\n\nconst vendored = {\n 'react-rsc': vendoredReactRSC,\n 'react-ssr': vendoredReactSSR,\n contexts: vendoredContexts,\n}\n\nexport { renderToHTMLOrFlight, vendored }\n\nexport default AppPageRouteModule\n"],"names":["addRequestMeta","renderToHTMLOrFlight","runValidationInDevFromSnapshot","RouteModule","vendoredContexts","PrerenderManifestMatcher","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_URL","RSC_HEADER","isInterceptionRouteAppPath","RSCPathnameNormalizer","SegmentPrefixRSCPathnameNormalizer","applyAppPageRscRequestMetaFromHeaders","normalizeAppPageRequestUrl","vendoredReactRSC","vendoredReactSSR","process","env","NEXT_RUNTIME","require","registerServerReact","registerClientReact","React","AppPageRouteModule","match","pathname","prerenderManifest","matcher","matchers","get","definition","set","normalizeUrl","req","parsedUrl","normalizers","segmentPrefetchRSC","result","extract","originalPathname","segmentPath","headers","rsc","normalize","render","res","context","page","query","fallbackRouteParams","renderOpts","serverComponentsHmrCache","sharedContext","runValidationInDev","componentMod","message","abortSignal","pathCouldBeIntercepted","resolvedPathname","interceptionRoutePatterns","some","regexp","test","getVaryHeader","baseVaryHeader","WeakMap","vendored","contexts"],"mappings":"AAGA,SAASA,cAAc,QAAiC,qBAAoB;AAI5E,SACEC,oBAAoB,EACpBC,8BAA8B,QAEzB,8BAA6B;AAEpC,SACEC,WAAW,QAGN,kBAAiB;AACxB,YAAYC,sBAAsB,kCAAiC;AAInE,SAASC,wBAAwB,QAAQ,uCAAsC;AAE/E,SACEC,2BAA2B,EAC3BC,mCAAmC,EACnCC,6BAA6B,EAC7BC,QAAQ,EACRC,UAAU,QACL,gDAA+C;AACtD,SAASC,0BAA0B,QAAQ,uDAAsD;AACjG,SAASC,qBAAqB,QAAQ,gCAA+B;AACrE,SAASC,kCAAkC,QAAQ,+CAA8C;AAGjG,SACEC,qCAAqC,EACrCC,0BAA0B,QACrB,0BAAyB;AAEhC,IAAIC;AACJ,IAAIC;AAEJ,gFAAgF;AAChF,IAAIC,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCJ,mBACEK,QAAQ;IACVJ,mBACEI,QAAQ;IAEV,+FAA+F;IAC/F,kEAAkE;IAClE,MAAM,EAAEC,mBAAmB,EAAEC,mBAAmB,EAAE,GAChDF,QAAQ;IACVC,oBAAoBN,iBAAiBQ,KAAK;IAC1CD,oBAAoBN,iBAAiBO,KAAK;AAC5C;AA6BA,OAAO,MAAMC,2BAA2BtB;IAQ/BuB,MACLC,QAAgB,EAChBC,iBAAkD,EAClD;QACA,sEAAsE;QACtE,IAAIC,UAAU,IAAI,CAACC,QAAQ,CAACC,GAAG,CAACH;QAChC,IAAI,CAACC,SAAS;YACZA,UAAU,IAAIxB,yBACZ,IAAI,CAAC2B,UAAU,CAACL,QAAQ,EACxBC;YAEF,IAAI,CAACE,QAAQ,CAACG,GAAG,CAACL,mBAAmBC;QACvC;QAEA,2CAA2C;QAC3C,OAAOA,QA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;IAEA;;;;;;;;;GASC,GACD,AAAOC,mBACLC,YAA2B,EAC3BC,OAAmC,EACnCC,WAAwB,EACa;QACrC,OAAOxD,+BAA+BuD,SAASD,cAAcE;IAC/D;IAEQC,uBACNC,gBAAwB,EACxBC,yBAAmC,EAC1B;QACT,OACElD,2BAA2BiD,qBAC3BC,0BAA0BC,IAAI,CAAC,CAACC;YAC9B,OAAOA,OAAOC,IAAI,CAACJ;QACrB;IAEJ;IAEOK,cACLL,gBAAwB,EACxBC,yBAAmC,EAC3B;QACR,MAAMK,iBAAiB,GAAGxD,WAAW,EAAE,EAAEF,8BAA8B,EAAE,EAAEF,4BAA4B,EAAE,EAAEC,qCAAqC;QAEhJ,IACE,IAAI,CAACoD,sBAAsB,CAACC,kBAAkBC,4BAC9C;YACA,wEAAwE;YACxE,+FAA+F;YAC/F,OAAO,GAAGK,eAAe,EAAE,EAAEzD,UAAU;QACzC,OAAO;YACL,yHAAyH;YACzH,mGAAmG;YACnG,OAAOyD;QACT;IACF;;QAtIK,qBAIGpC,WAAW,IAAIqC,gBAsBf9B,cAAc;YACpBO,KAAK,IAAIhC;YACT0B,oBAAoB,IAAIzB;QAC1B;;AA0GF;AAEA,MAAMuD,WAAW;IACf,aAAapD;IACb,aAAaC;IACboD,UAAUjE;AACZ;AAEA,SAASH,oBAAoB,EAAEmE,QAAQ,GAAE;AAEzC,eAAe3C,mBAAkB","ignoreList":[0]} |
| class ResourceManager { | ||
| add(resourceArgs) { | ||
| const resource = this.create(resourceArgs); | ||
| this.resources.push(resource); | ||
| this.resources.add(resource); | ||
| return resource; | ||
| } | ||
| remove(resource) { | ||
| this.resources = this.resources.filter((r)=>r !== resource); | ||
| this.untrack(resource); | ||
| this.destroy(resource); | ||
| } | ||
| /** | ||
| * Stop tracking a resource without destroying it. Used when a resource has | ||
| * already been released by other means (e.g. a one-shot timeout that ran to | ||
| * completion) so it should no longer be retained by this manager. | ||
| */ untrack(resource) { | ||
| this.resources.delete(resource); | ||
| } | ||
| removeAll() { | ||
| this.resources.forEach(this.destroy); | ||
| this.resources = []; | ||
| for (const resource of this.resources){ | ||
| this.destroy(resource); | ||
| } | ||
| this.resources.clear(); | ||
| } | ||
| /** Number of resources currently tracked. Exposed for observability/tests. */ get size() { | ||
| return this.resources.size; | ||
| } | ||
| constructor(){ | ||
| this.resources = []; | ||
| this.resources = new Set(); | ||
| } | ||
| } | ||
| class IntervalsManager extends ResourceManager { | ||
| export class IntervalsManager extends ResourceManager { | ||
| create(args) { | ||
@@ -28,6 +40,21 @@ // TODO: use the edge runtime provided `setInterval` instead | ||
| } | ||
| class TimeoutsManager extends ResourceManager { | ||
| export class TimeoutsManager extends ResourceManager { | ||
| create(args) { | ||
| // TODO: use the edge runtime provided `setTimeout` instead | ||
| return webSetTimeoutPolyfill(...args); | ||
| const [globalObject, callback, ms, ...rest] = args; | ||
| // A one-shot timeout releases itself from tracking once its callback has | ||
| // run. Otherwise fire-and-forget timeouts (whose ids user code never | ||
| // passes to `clearTimeout`) would accumulate for the lifetime of the | ||
| // module context and leak memory in long-lived server processes. | ||
| // See: https://github.com/vercel/next.js/issues/95094 | ||
| let timeoutId; | ||
| const callbackWithRelease = (...callbackArgs)=>{ | ||
| try { | ||
| return callback.apply(globalObject, callbackArgs); | ||
| } finally{ | ||
| this.untrack(timeoutId); | ||
| } | ||
| }; | ||
| timeoutId = webSetTimeoutPolyfill(globalObject, callbackWithRelease, ms, ...rest); | ||
| return timeoutId; | ||
| } | ||
@@ -34,0 +61,0 @@ destroy(timeout) { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/web/sandbox/resource-managers.ts"],"sourcesContent":["abstract class ResourceManager<T, Args> {\n private resources: T[] = []\n\n abstract create(resourceArgs: Args): T\n abstract destroy(resource: T): void\n\n add(resourceArgs: Args) {\n const resource = this.create(resourceArgs)\n this.resources.push(resource)\n return resource\n }\n\n remove(resource: T) {\n this.resources = this.resources.filter((r) => r !== resource)\n this.destroy(resource)\n }\n\n removeAll() {\n this.resources.forEach(this.destroy)\n this.resources = []\n }\n}\n\nclass IntervalsManager extends ResourceManager<\n number,\n Parameters<typeof webSetIntervalPolyfill>\n> {\n create(args: Parameters<typeof webSetIntervalPolyfill>) {\n // TODO: use the edge runtime provided `setInterval` instead\n return webSetIntervalPolyfill(...args)\n }\n\n destroy(interval: number) {\n clearInterval(interval)\n }\n}\n\nclass TimeoutsManager extends ResourceManager<\n number,\n Parameters<typeof webSetTimeoutPolyfill>\n> {\n create(args: Parameters<typeof webSetTimeoutPolyfill>) {\n // TODO: use the edge runtime provided `setTimeout` instead\n return webSetTimeoutPolyfill(...args)\n }\n\n destroy(timeout: number) {\n clearTimeout(timeout)\n }\n}\n\nexport type GlobalObject = import('edge-runtime').EdgeRuntime['context']\n\nfunction webSetIntervalPolyfill<TArgs extends any[]>(\n globalObject: GlobalObject,\n callback: (...args: TArgs) => void,\n ms?: number,\n ...args: TArgs\n): number {\n return setInterval(() => {\n // node's `setInterval` sets `this` to the `Timeout` instance it returned,\n // but web `setInterval` always sets `this` to `window`\n // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval#the_this_problem\n return callback.apply(globalObject, args)\n }, ms)[Symbol.toPrimitive]()\n}\n\nfunction webSetTimeoutPolyfill<TArgs extends any[]>(\n globalObject: GlobalObject,\n callback: (...args: TArgs) => void,\n ms?: number,\n ...args: TArgs\n): number {\n const wrappedCallback = () => {\n try {\n // node's `setTimeout` sets `this` to the `Timeout` instance it returned,\n // but web `setTimeout` always sets `this` to `window`\n // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#the_this_problem\n return callback.apply(globalObject, args)\n } finally {\n // On certain older node versions (<20.16.0, <22.4.0),\n // a `setTimeout` whose Timeout was converted to a primitive will leak.\n // See: https://github.com/nodejs/node/issues/53335\n // We can work around this by explicitly calling `clearTimeout` after the callback runs.\n clearTimeout(timeout)\n }\n }\n const timeout = setTimeout(wrappedCallback, ms)\n return timeout[Symbol.toPrimitive]()\n}\n\nexport const intervalsManager = new IntervalsManager()\nexport const timeoutsManager = new TimeoutsManager()\n"],"names":["ResourceManager","add","resourceArgs","resource","create","resources","push","remove","filter","r","destroy","removeAll","forEach","IntervalsManager","args","webSetIntervalPolyfill","interval","clearInterval","TimeoutsManager","webSetTimeoutPolyfill","timeout","clearTimeout","globalObject","callback","ms","setInterval","apply","Symbol","toPrimitive","wrappedCallback","setTimeout","intervalsManager","timeoutsManager"],"mappings":"AAAA,MAAeA;IAMbC,IAAIC,YAAkB,EAAE;QACtB,MAAMC,WAAW,IAAI,CAACC,MAAM,CAACF;QAC7B,IAAI,CAACG,SAAS,CAACC,IAAI,CAACH;QACpB,OAAOA;IACT;IAEAI,OAAOJ,QAAW,EAAE;QAClB,IAAI,CAACE,SAAS,GAAG,IAAI,CAACA,SAAS,CAACG,MAAM,CAAC,CAACC,IAAMA,MAAMN;QACpD,IAAI,CAACO,OAAO,CAACP;IACf;IAEAQ,YAAY;QACV,IAAI,CAACN,SAAS,CAACO,OAAO,CAAC,IAAI,CAACF,OAAO;QACnC,IAAI,CAACL,SAAS,GAAG,EAAE;IACrB;;aAnBQA,YAAiB,EAAE;;AAoB7B;AAEA,MAAMQ,yBAAyBb;IAI7BI,OAAOU,IAA+C,EAAE;QACtD,4DAA4D;QAC5D,OAAOC,0BAA0BD;IACnC;IAEAJ,QAAQM,QAAgB,EAAE;QACxBC,cAAcD;IAChB;AACF;AAEA,MAAME,wBAAwBlB;IAI5BI,OAAOU,IAA8C,EAAE;QACrD,2DAA2D;QAC3D,OAAOK,yBAAyBL;IAClC;IAEAJ,QAAQU,OAAe,EAAE;QACvBC,aAAaD;IACf;AACF;AAIA,SAASL,uBACPO,YAA0B,EAC1BC,QAAkC,EAClCC,EAAW,EACX,GAAGV,IAAW;IAEd,OAAOW,YAAY;QACjB,0EAA0E;QAC1E,uDAAuD;QACvD,4FAA4F;QAC5F,OAAOF,SAASG,KAAK,CAACJ,cAAcR;IACtC,GAAGU,GAAG,CAACG,OAAOC,WAAW,CAAC;AAC5B;AAEA,SAAST,sBACPG,YAA0B,EAC1BC,QAAkC,EAClCC,EAAW,EACX,GAAGV,IAAW;IAEd,MAAMe,kBAAkB;QACtB,IAAI;YACF,yEAAyE;YACzE,sDAAsD;YACtD,2FAA2F;YAC3F,OAAON,SAASG,KAAK,CAACJ,cAAcR;QACtC,SAAU;YACR,sDAAsD;YACtD,uEAAuE;YACvE,mDAAmD;YACnD,wFAAwF;YACxFO,aAAaD;QACf;IACF;IACA,MAAMA,UAAUU,WAAWD,iBAAiBL;IAC5C,OAAOJ,OAAO,CAACO,OAAOC,WAAW,CAAC;AACpC;AAEA,OAAO,MAAMG,mBAAmB,IAAIlB,mBAAkB;AACtD,OAAO,MAAMmB,kBAAkB,IAAId,kBAAiB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/web/sandbox/resource-managers.ts"],"sourcesContent":["abstract class ResourceManager<T, Args> {\n private resources = new Set<T>()\n\n abstract create(resourceArgs: Args): T\n abstract destroy(resource: T): void\n\n add(resourceArgs: Args) {\n const resource = this.create(resourceArgs)\n this.resources.add(resource)\n return resource\n }\n\n remove(resource: T) {\n this.untrack(resource)\n this.destroy(resource)\n }\n\n /**\n * Stop tracking a resource without destroying it. Used when a resource has\n * already been released by other means (e.g. a one-shot timeout that ran to\n * completion) so it should no longer be retained by this manager.\n */\n protected untrack(resource: T) {\n this.resources.delete(resource)\n }\n\n removeAll() {\n for (const resource of this.resources) {\n this.destroy(resource)\n }\n this.resources.clear()\n }\n\n /** Number of resources currently tracked. Exposed for observability/tests. */\n get size() {\n return this.resources.size\n }\n}\n\nexport class IntervalsManager extends ResourceManager<\n number,\n Parameters<typeof webSetIntervalPolyfill>\n> {\n create(args: Parameters<typeof webSetIntervalPolyfill>) {\n // TODO: use the edge runtime provided `setInterval` instead\n return webSetIntervalPolyfill(...args)\n }\n\n destroy(interval: number) {\n clearInterval(interval)\n }\n}\n\nexport class TimeoutsManager extends ResourceManager<\n number,\n Parameters<typeof webSetTimeoutPolyfill>\n> {\n create(args: Parameters<typeof webSetTimeoutPolyfill>) {\n // TODO: use the edge runtime provided `setTimeout` instead\n const [globalObject, callback, ms, ...rest] = args\n\n // A one-shot timeout releases itself from tracking once its callback has\n // run. Otherwise fire-and-forget timeouts (whose ids user code never\n // passes to `clearTimeout`) would accumulate for the lifetime of the\n // module context and leak memory in long-lived server processes.\n // See: https://github.com/vercel/next.js/issues/95094\n let timeoutId: number\n const callbackWithRelease = (...callbackArgs: typeof rest) => {\n try {\n return callback.apply(globalObject, callbackArgs)\n } finally {\n this.untrack(timeoutId)\n }\n }\n\n timeoutId = webSetTimeoutPolyfill(\n globalObject,\n callbackWithRelease,\n ms,\n ...rest\n )\n return timeoutId\n }\n\n destroy(timeout: number) {\n clearTimeout(timeout)\n }\n}\n\nexport type GlobalObject = import('edge-runtime').EdgeRuntime['context']\n\nfunction webSetIntervalPolyfill<TArgs extends any[]>(\n globalObject: GlobalObject,\n callback: (...args: TArgs) => void,\n ms?: number,\n ...args: TArgs\n): number {\n return setInterval(() => {\n // node's `setInterval` sets `this` to the `Timeout` instance it returned,\n // but web `setInterval` always sets `this` to `window`\n // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval#the_this_problem\n return callback.apply(globalObject, args)\n }, ms)[Symbol.toPrimitive]()\n}\n\nfunction webSetTimeoutPolyfill<TArgs extends any[]>(\n globalObject: GlobalObject,\n callback: (...args: TArgs) => void,\n ms?: number,\n ...args: TArgs\n): number {\n const wrappedCallback = () => {\n try {\n // node's `setTimeout` sets `this` to the `Timeout` instance it returned,\n // but web `setTimeout` always sets `this` to `window`\n // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#the_this_problem\n return callback.apply(globalObject, args)\n } finally {\n // On certain older node versions (<20.16.0, <22.4.0),\n // a `setTimeout` whose Timeout was converted to a primitive will leak.\n // See: https://github.com/nodejs/node/issues/53335\n // We can work around this by explicitly calling `clearTimeout` after the callback runs.\n clearTimeout(timeout)\n }\n }\n const timeout = setTimeout(wrappedCallback, ms)\n return timeout[Symbol.toPrimitive]()\n}\n\nexport const intervalsManager = new IntervalsManager()\nexport const timeoutsManager = new TimeoutsManager()\n"],"names":["ResourceManager","add","resourceArgs","resource","create","resources","remove","untrack","destroy","delete","removeAll","clear","size","Set","IntervalsManager","args","webSetIntervalPolyfill","interval","clearInterval","TimeoutsManager","globalObject","callback","ms","rest","timeoutId","callbackWithRelease","callbackArgs","apply","webSetTimeoutPolyfill","timeout","clearTimeout","setInterval","Symbol","toPrimitive","wrappedCallback","setTimeout","intervalsManager","timeoutsManager"],"mappings":"AAAA,MAAeA;IAMbC,IAAIC,YAAkB,EAAE;QACtB,MAAMC,WAAW,IAAI,CAACC,MAAM,CAACF;QAC7B,IAAI,CAACG,SAAS,CAACJ,GAAG,CAACE;QACnB,OAAOA;IACT;IAEAG,OAAOH,QAAW,EAAE;QAClB,IAAI,CAACI,OAAO,CAACJ;QACb,IAAI,CAACK,OAAO,CAACL;IACf;IAEA;;;;GAIC,GACD,AAAUI,QAAQJ,QAAW,EAAE;QAC7B,IAAI,CAACE,SAAS,CAACI,MAAM,CAACN;IACxB;IAEAO,YAAY;QACV,KAAK,MAAMP,YAAY,IAAI,CAACE,SAAS,CAAE;YACrC,IAAI,CAACG,OAAO,CAACL;QACf;QACA,IAAI,CAACE,SAAS,CAACM,KAAK;IACtB;IAEA,4EAA4E,GAC5E,IAAIC,OAAO;QACT,OAAO,IAAI,CAACP,SAAS,CAACO,IAAI;IAC5B;;aAnCQP,YAAY,IAAIQ;;AAoC1B;AAEA,OAAO,MAAMC,yBAAyBd;IAIpCI,OAAOW,IAA+C,EAAE;QACtD,4DAA4D;QAC5D,OAAOC,0BAA0BD;IACnC;IAEAP,QAAQS,QAAgB,EAAE;QACxBC,cAAcD;IAChB;AACF;AAEA,OAAO,MAAME,wBAAwBnB;IAInCI,OAAOW,IAA8C,EAAE;QACrD,2DAA2D;QAC3D,MAAM,CAACK,cAAcC,UAAUC,IAAI,GAAGC,KAAK,GAAGR;QAE9C,yEAAyE;QACzE,qEAAqE;QACrE,qEAAqE;QACrE,iEAAiE;QACjE,sDAAsD;QACtD,IAAIS;QACJ,MAAMC,sBAAsB,CAAC,GAAGC;YAC9B,IAAI;gBACF,OAAOL,SAASM,KAAK,CAACP,cAAcM;YACtC,SAAU;gBACR,IAAI,CAACnB,OAAO,CAACiB;YACf;QACF;QAEAA,YAAYI,sBACVR,cACAK,qBACAH,OACGC;QAEL,OAAOC;IACT;IAEAhB,QAAQqB,OAAe,EAAE;QACvBC,aAAaD;IACf;AACF;AAIA,SAASb,uBACPI,YAA0B,EAC1BC,QAAkC,EAClCC,EAAW,EACX,GAAGP,IAAW;IAEd,OAAOgB,YAAY;QACjB,0EAA0E;QAC1E,uDAAuD;QACvD,4FAA4F;QAC5F,OAAOV,SAASM,KAAK,CAACP,cAAcL;IACtC,GAAGO,GAAG,CAACU,OAAOC,WAAW,CAAC;AAC5B;AAEA,SAASL,sBACPR,YAA0B,EAC1BC,QAAkC,EAClCC,EAAW,EACX,GAAGP,IAAW;IAEd,MAAMmB,kBAAkB;QACtB,IAAI;YACF,yEAAyE;YACzE,sDAAsD;YACtD,2FAA2F;YAC3F,OAAOb,SAASM,KAAK,CAACP,cAAcL;QACtC,SAAU;YACR,sDAAsD;YACtD,uEAAuE;YACvE,mDAAmD;YACnD,wFAAwF;YACxFe,aAAaD;QACf;IACF;IACA,MAAMA,UAAUM,WAAWD,iBAAiBZ;IAC5C,OAAOO,OAAO,CAACG,OAAOC,WAAW,CAAC;AACpC;AAEA,OAAO,MAAMG,mBAAmB,IAAItB,mBAAkB;AACtD,OAAO,MAAMuB,kBAAkB,IAAIlB,kBAAiB","ignoreList":[0]} |
| export function isStableBuild() { | ||
| return !"16.3.0-canary.96"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| return !"16.3.0-canary.97"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| } | ||
@@ -4,0 +4,0 @@ export class CanaryOnlyConfigError extends Error { |
@@ -75,3 +75,3 @@ "use strict"; | ||
| const data = await res.json(); | ||
| const versionData = data.versions["16.3.0-canary.96"]; | ||
| const versionData = data.versions["16.3.0-canary.97"]; | ||
| return { | ||
@@ -104,3 +104,3 @@ os: versionData.os, | ||
| lockfileParsed.dependencies[pkg] = { | ||
| version: "16.3.0-canary.96", | ||
| version: "16.3.0-canary.97", | ||
| resolved: pkgData.tarball, | ||
@@ -113,3 +113,3 @@ integrity: pkgData.integrity, | ||
| lockfileParsed.packages[pkg] = { | ||
| version: "16.3.0-canary.96", | ||
| version: "16.3.0-canary.97", | ||
| resolved: pkgData.tarball, | ||
@@ -116,0 +116,0 @@ integrity: pkgData.integrity, |
@@ -11,2 +11,3 @@ import type { RenderOpts, PreloadCallbacks } from './types'; | ||
| import type { AnyStream } from './stream-ops'; | ||
| import { type DevValidationWorkerMessage } from './dev-validation-worker-globals'; | ||
| import { type ImplicitTags } from '../lib/implicit-tags'; | ||
@@ -39,2 +40,11 @@ import { parseRelativeUrl } from '../../shared/lib/router/utils/parse-relative-url'; | ||
| interpolatedParams: Params; | ||
| /** | ||
| * The request's fallback route params (the same ones | ||
| * `getDynamicParamFromSegment` closes over). Kept on the context so the dev | ||
| * validation worker can rebuild an identical `getDynamicParamFromSegment`; | ||
| * the depth-loop segment keys are derived from it, so it must match what | ||
| * produced the seed render's Flight, not the separate fallback set validation | ||
| * uses to mark params unknown in its stores. | ||
| */ | ||
| fallbackRouteParams: OpaqueFallbackRouteParams | null; | ||
| query: NextParsedUrlQuery; | ||
@@ -99,2 +109,83 @@ isPrefetch: boolean; | ||
| export declare const renderToHTMLOrFlight: AppPageRender; | ||
| /** | ||
| * A staged dev render interrupted by sync IO. It has no artifacts that could be | ||
| * used as validation inputs, only the reason it was interrupted. | ||
| */ | ||
| interface SyncInterruptedStagedDevRender { | ||
| readonly syncInterruptReason: Error; | ||
| } | ||
| /** | ||
| * The chunks and per-stage timings a staged dev render accumulates once its | ||
| * stream finishes. A render only produces them when it runs to the end without | ||
| * a sync-IO interrupt, so they back both a render's uninterrupted outcome and | ||
| * the validation inputs. | ||
| */ | ||
| interface StagedDevRenderArtifacts { | ||
| readonly accumulatedChunks: AccumulatedStreamChunks; | ||
| readonly startTime: number; | ||
| readonly staticStageEndTime: number; | ||
| readonly runtimeStageEndTime: number; | ||
| } | ||
| /** | ||
| * What `runValidationInDev` consumes: an uninterrupted render's artifacts plus | ||
| * the request store and the debug channel. Carries no `syncInterruptReason`: | ||
| * the resolution step has already surfaced and bailed on any sync interrupt. | ||
| */ | ||
| export interface ResolvedValidationInputs extends StagedDevRenderArtifacts { | ||
| readonly requestStore: RequestStore; | ||
| readonly debugChannelClient: AnyStream | undefined; | ||
| } | ||
| /** | ||
| * The inputs produced for validation, before resolution: either an | ||
| * uninterrupted render's artifacts (`ResolvedValidationInputs`) or, for a | ||
| * render interrupted by sync IO, only the interrupt reason. An interrupted | ||
| * render is never validated, so it carries nothing else: its debug channel is | ||
| * dropped at construction. Discriminate with `'syncInterruptReason' in x`; the | ||
| * resolution step surfaces and bails on the interrupted case, so the depth loop | ||
| * only ever sees `ResolvedValidationInputs`. | ||
| */ | ||
| export type DevValidationInputs = ResolvedValidationInputs | SyncInterruptedStagedDevRender; | ||
| export declare enum PrefetchingMode { | ||
| LegacySpeculative = 1, | ||
| Partial = 2 | ||
| } | ||
| interface AccumulatedStreamChunks { | ||
| readonly shellStaticChunks: Array<Uint8Array>; | ||
| readonly staticChunks: Array<Uint8Array>; | ||
| readonly shellRuntimeChunks: Array<Uint8Array>; | ||
| readonly runtimeChunks: Array<Uint8Array>; | ||
| readonly dynamicChunks: Array<Uint8Array>; | ||
| } | ||
| /** | ||
| * The slice of the render context the dev/build validation passes read. Both | ||
| * the in-process callers and the validation worker build one of these, so it | ||
| * names exactly what validation depends on and nothing else: no live | ||
| * request/response objects that can't be rebuilt off the main thread. | ||
| * `isDebugChannelEnabled` is the derived flag validation uses in place of the | ||
| * main render's `setReactDebugChannel` callback (validation only ever read that | ||
| * callback's presence as a boolean). | ||
| */ | ||
| export type ValidationRenderContext = Pick<AppRenderContext, 'componentMod' | 'getDynamicParamFromSegment' | 'query' | 'implicitTags' | 'nonce' | 'workStore'> & { | ||
| renderOpts: Pick<RenderOpts, 'images' | 'allowEmptyStaticShell'>; | ||
| isDebugChannelEnabled: boolean; | ||
| }; | ||
| /** | ||
| * Projects a full app render context down to the slice validation reads. The | ||
| * in-process dev and build callers hold an `AppRenderContext` and use this to | ||
| * hand validation exactly what it needs; the worker builds the same shape from | ||
| * its snapshot instead. | ||
| */ | ||
| export declare function toValidationRenderContext(ctx: AppRenderContext): ValidationRenderContext; | ||
| /** | ||
| * Worker entry point for Cached Components dev validation, reached from the | ||
| * validation worker via `ComponentMod.routeModule.runValidationInDev`. The | ||
| * worker reloads the route's compiled module and calls this so the entire | ||
| * validation (Flight re-encodes and the client prerenders) runs inside the | ||
| * app-page bundle's single React instance, alongside the user's client | ||
| * components. It rebuilds the render context, work store, and request store | ||
| * from the transported snapshot (the live objects can't cross a thread) and | ||
| * returns the validation errors for the worker to serialize and the main thread | ||
| * to deliver. | ||
| */ | ||
| export declare function runValidationInDevFromSnapshot(message: DevValidationWorkerMessage, componentMod: AppPageModule, abortSignal: AbortSignal): Promise<Array<unknown> | undefined>; | ||
| export {}; |
@@ -88,3 +88,4 @@ "use strict"; | ||
| if (workStore) { | ||
| const currentManifest = clientReferenceManifestsPerRoute.get(workStore.route); | ||
| var _clientReferenceManifestsPerRoute_get; | ||
| const currentManifest = (_clientReferenceManifestsPerRoute_get = clientReferenceManifestsPerRoute.get(workStore.route)) == null ? void 0 : _clientReferenceManifestsPerRoute_get.clientReferenceManifest; | ||
| if (currentManifest == null ? void 0 : currentManifest[prop][id]) { | ||
@@ -104,8 +105,15 @@ return currentManifest[prop][id]; | ||
| if (process.env.NODE_ENV !== 'production') { | ||
| for (const [route, manifest] of clientReferenceManifestsPerRoute){ | ||
| for (const [route, { page, clientReferenceManifest }] of clientReferenceManifestsPerRoute){ | ||
| if (route === workStore.route) { | ||
| continue; | ||
| } | ||
| const entry = manifest[prop][id]; | ||
| const entry = clientReferenceManifest[prop][id]; | ||
| if (entry !== undefined) { | ||
| if (process.env.__NEXT_DEV_SERVER) { | ||
| // The dev validation worker rebuilds this registry in its | ||
| // own thread, seeded with only the route it validates, so | ||
| // it has to be told which other manifests it needs. | ||
| workStore.additionalClientReferenceManifestPages ??= new Set(); | ||
| workStore.additionalClientReferenceManifestPages.add(page); | ||
| } | ||
| return entry; | ||
@@ -122,4 +130,4 @@ } | ||
| // that case we search all page manifests to find the module. | ||
| for (const manifest of clientReferenceManifestsPerRoute.values()){ | ||
| const entry = manifest[prop][id]; | ||
| for (const { clientReferenceManifest } of clientReferenceManifestsPerRoute.values()){ | ||
| const entry = clientReferenceManifest[prop][id]; | ||
| if (entry !== undefined) { | ||
@@ -150,4 +158,4 @@ return entry; | ||
| } | ||
| const currentManifest = clientReferenceManifestsPerRoute.get(workStore.route); | ||
| if (!currentManifest) { | ||
| const registeredManifest = clientReferenceManifestsPerRoute.get(workStore.route); | ||
| if (!registeredManifest) { | ||
| throw Object.defineProperty(new _invarianterror.InvariantError(`The client reference manifest for route "${workStore.route}" does not exist.`), "__NEXT_ERROR_CODE", { | ||
@@ -159,3 +167,3 @@ value: "E951", | ||
| } | ||
| return currentManifest[prop]; | ||
| return registeredManifest.clientReferenceManifest[prop]; | ||
| } | ||
@@ -270,2 +278,3 @@ case 'clientModules': | ||
| const existingSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]; | ||
| const route = (0, _apppaths.normalizeAppPath)(page); | ||
| const serverActionsManifest = { | ||
@@ -279,3 +288,6 @@ encryptionKey: rawServerActionsManifest.encryptionKey, | ||
| if (existingSingleton) { | ||
| existingSingleton.clientReferenceManifestsPerRoute.set((0, _apppaths.normalizeAppPath)(page), clientReferenceManifest); | ||
| existingSingleton.clientReferenceManifestsPerRoute.set(route, { | ||
| page, | ||
| clientReferenceManifest | ||
| }); | ||
| existingSingleton.serverActionsManifest = serverActionsManifest; | ||
@@ -285,4 +297,7 @@ } else { | ||
| [ | ||
| (0, _apppaths.normalizeAppPath)(page), | ||
| clientReferenceManifest | ||
| route, | ||
| { | ||
| page, | ||
| clientReferenceManifest | ||
| } | ||
| ] | ||
@@ -289,0 +304,0 @@ ]); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/app-render/manifests-singleton.ts"],"sourcesContent":["import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'\nimport type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { mightBeServerReferenceId } from '../../shared/lib/server-reference-info'\nimport { wellKnownProperties } from '../../shared/lib/utils/reflect-utils'\nimport { workAsyncStorage } from './work-async-storage.external'\n\nexport interface ServerModuleMap {\n readonly [name: string]: {\n readonly id: string | number\n readonly name: string\n readonly chunks: Readonly<Array<string>> // currently not used\n readonly async?: boolean\n }\n}\n\nexport function getActionNotFoundError(actionId: string | null): Error {\n return new Error(\n `Failed to find Server Action${actionId ? ` \"${actionId}\"` : ''}. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n )\n}\n\nexport function getInvalidServerReferenceIdError(id: string): Error {\n // `id` is arbitrary client-provided input. Unlike the not-found case, it has\n // not passed the length gate and can reach this error via a malformed server\n // reference in an action payload, so it may be of any length and contain\n // control characters. `JSON.stringify` escapes newlines and quotes so it\n // can't forge log lines, and truncating overly long ids prevents log\n // flooding. Ids at or below the cap are logged in full so that we only add an\n // ellipsis to ids that are meaningfully longer than the truncated length.\n const encoded = JSON.stringify(\n id.length > MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH\n ? id.slice(0, TRUNCATED_SERVER_REFERENCE_ID_LENGTH) + '…'\n : id\n )\n\n return new Error(\n `The Server Reference ID did not match the expected format. Received ${encoded}.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n )\n}\n\n// Ids at or below the cap are logged in full. Longer ids are truncated to the\n// shorter length and marked with an ellipsis, so the cap leaves headroom over\n// the truncated length rather than ellipsizing ids that are barely too long.\nconst MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH = 100\nconst TRUNCATED_SERVER_REFERENCE_ID_LENGTH = 90\n\n// This is a global singleton that is, among other things, also used to\n// encode/decode bound args of server function closures. This can't be using a\n// AsyncLocalStorage as it might happen at the module level.\nconst MANIFESTS_SINGLETON = Symbol.for('next.server.manifests')\n\ninterface ManifestsSingleton {\n readonly clientReferenceManifestsPerRoute: Map<\n string,\n DeepReadonly<ClientReferenceManifest>\n >\n readonly proxiedClientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n serverActionsManifest: DeepReadonly<ActionManifest>\n serverModuleMap: ServerModuleMap\n}\n\ntype GlobalThisWithManifests = typeof globalThis & {\n [MANIFESTS_SINGLETON]?: ManifestsSingleton\n}\n\ntype ClientReferenceManifestMappingProp =\n | 'clientModules'\n | 'rscModuleMapping'\n | 'edgeRscModuleMapping'\n | 'ssrModuleMapping'\n | 'edgeSSRModuleMapping'\n\nconst globalThisWithManifests = globalThis as GlobalThisWithManifests\n\nfunction createProxiedClientReferenceManifest(\n clientReferenceManifestsPerRoute: Map<\n string,\n DeepReadonly<ClientReferenceManifest>\n >\n): DeepReadonly<ClientReferenceManifest> {\n const createMappingProxy = (prop: ClientReferenceManifestMappingProp) => {\n return new Proxy(\n {},\n {\n get(_, id: string) {\n const workStore = workAsyncStorage.getStore()\n\n if (workStore) {\n const currentManifest = clientReferenceManifestsPerRoute.get(\n workStore.route\n )\n\n if (currentManifest?.[prop][id]) {\n return currentManifest[prop][id]\n }\n\n // In development, we also check all other manifests to see if the\n // module exists there. This is to support a scenario where React's\n // I/O tracking (dev-only) creates a connection from one page to\n // another through an emitted async I/O node that references client\n // components from the other page, e.g. in owner props.\n // TODO: Maybe we need to add a `debugBundlerConfig` option to React\n // to avoid this workaround. The current workaround has the\n // disadvantage that one might accidentally or intentionally share\n // client references across pages (e.g. by storing them in a global\n // variable), which would then only be caught in production.\n if (process.env.NODE_ENV !== 'production') {\n for (const [\n route,\n manifest,\n ] of clientReferenceManifestsPerRoute) {\n if (route === workStore.route) {\n continue\n }\n\n const entry = manifest[prop][id]\n\n if (entry !== undefined) {\n return entry\n }\n }\n }\n } else {\n // If there's no work store defined, we can assume that a client\n // reference manifest is needed during module evaluation, e.g. to\n // create a server function using a higher-order function. This\n // might also use client components which need to be serialized by\n // Flight, and therefore client references need to be resolvable. In\n // that case we search all page manifests to find the module.\n for (const manifest of clientReferenceManifestsPerRoute.values()) {\n const entry = manifest[prop][id]\n\n if (entry !== undefined) {\n return entry\n }\n }\n }\n\n return undefined\n },\n }\n )\n }\n\n const mappingProxies = new Map<\n ClientReferenceManifestMappingProp,\n ReturnType<typeof createMappingProxy>\n >()\n\n return new Proxy(\n {},\n {\n get(_, prop) {\n const workStore = workAsyncStorage.getStore()\n\n switch (prop) {\n case 'moduleLoading':\n case 'entryCSSFiles':\n case 'entryJSFiles': {\n if (!workStore) {\n throw new InvariantError(\n `Cannot access \"${prop}\" without a work store.`\n )\n }\n\n const currentManifest = clientReferenceManifestsPerRoute.get(\n workStore.route\n )\n\n if (!currentManifest) {\n throw new InvariantError(\n `The client reference manifest for route \"${workStore.route}\" does not exist.`\n )\n }\n\n return currentManifest[prop]\n }\n case 'clientModules':\n case 'rscModuleMapping':\n case 'edgeRscModuleMapping':\n case 'ssrModuleMapping':\n case 'edgeSSRModuleMapping': {\n let proxy = mappingProxies.get(prop)\n\n if (!proxy) {\n proxy = createMappingProxy(prop)\n mappingProxies.set(prop, proxy)\n }\n\n return proxy\n }\n default: {\n throw new InvariantError(\n `This is a proxied client reference manifest. The property \"${String(prop)}\" is not handled.`\n )\n }\n }\n },\n }\n ) as DeepReadonly<ClientReferenceManifest>\n}\n\n/**\n * This function creates a Flight-acceptable server module map proxy from our\n * Server Reference Manifest similar to our client module map. This is because\n * our manifest contains a lot of internal Next.js data that are relevant to the\n * runtime, workers, etc. that React doesn't need to know.\n */\nfunction createServerModuleMap(): ServerModuleMap {\n return new Proxy(Object.create(null) as ServerModuleMap, {\n get: (target, id: string | symbol, receiver) => {\n // React's debug serialization can probe the module map like a plain object.\n // These probes are not server reference lookups.\n if (typeof id !== 'string') {\n return Reflect.get(target, id, receiver)\n }\n\n if (wellKnownProperties.has(id)) {\n return Reflect.get(target, id, receiver)\n }\n\n if (!mightBeServerReferenceId(id)) {\n throw getInvalidServerReferenceIdError(id)\n }\n\n const workers =\n getServerActionsManifest()[\n process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n ]?.[id]?.workers\n\n if (!workers) {\n throw getActionNotFoundError(id)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n let workerEntry: { moduleId: string | number; async: boolean } | undefined\n\n if (workStore) {\n workerEntry = workers[normalizeWorkerPageName(workStore.page)]\n } else {\n // If there's no work store defined, we can assume that a server\n // module map is needed during module evaluation, e.g. to create a\n // server action using a higher-order function. Therefore it should be\n // safe to return any entry from the manifest that matches the action\n // ID. They all refer to the same module ID, which must also exist in\n // the current page bundle. TODO: This is currently not guaranteed in\n // Turbopack, and needs to be fixed.\n workerEntry = Object.values(workers).at(0)\n }\n\n if (!workerEntry) {\n throw getActionNotFoundError(id)\n }\n\n const { moduleId, async } = workerEntry\n\n return { id: moduleId, name: id, chunks: [], async }\n },\n })\n}\n\n/**\n * The flight entry loader keys actions by bundlePath. bundlePath corresponds\n * with the relative path (including 'app') to the page entrypoint.\n */\nfunction normalizeWorkerPageName(pageName: string) {\n if (pathHasPrefix(pageName, 'app')) {\n return pageName\n }\n\n return 'app' + pageName\n}\n\n/**\n * Converts a bundlePath (relative path to the entrypoint) to a routable page\n * name.\n */\nfunction denormalizeWorkerPageName(bundlePath: string) {\n return normalizeAppPath(removePathPrefix(bundlePath, 'app'))\n}\n\n/**\n * Checks if the requested action has a worker for the current page.\n * If not, it returns the first worker that has a handler for the action.\n */\nexport function selectWorkerForForwarding(\n actionId: string,\n pageName: string\n): string | undefined {\n const serverActionsManifest = getServerActionsManifest()\n const workers =\n serverActionsManifest[\n process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n ][actionId]?.workers\n\n // There are no workers to handle this action, nothing to forward to.\n if (!workers) {\n return\n }\n\n // If there is an entry for the current page, we don't need to forward.\n if (workers[normalizeWorkerPageName(pageName)]) {\n return\n }\n\n // Otherwise, grab the first worker that has a handler for this action id.\n return denormalizeWorkerPageName(Object.keys(workers)[0])\n}\n\nexport function setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest: rawServerActionsManifest,\n}: {\n page: string\n clientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n serverActionsManifest: DeepReadonly<ActionManifest>\n}) {\n const existingSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]\n\n const serverActionsManifest: DeepReadonly<ActionManifest> = {\n encryptionKey: rawServerActionsManifest.encryptionKey,\n // Use null-prototypes for the action objects to prevent prototype pollution\n // from affecting action ID lookups.\n node: Object.assign(Object.create(null), rawServerActionsManifest.node),\n edge: Object.assign(Object.create(null), rawServerActionsManifest.edge),\n }\n\n if (existingSingleton) {\n existingSingleton.clientReferenceManifestsPerRoute.set(\n normalizeAppPath(page),\n clientReferenceManifest\n )\n\n existingSingleton.serverActionsManifest = serverActionsManifest\n } else {\n const clientReferenceManifestsPerRoute = new Map<\n string,\n DeepReadonly<ClientReferenceManifest>\n >([[normalizeAppPath(page), clientReferenceManifest]])\n\n const proxiedClientReferenceManifest = createProxiedClientReferenceManifest(\n clientReferenceManifestsPerRoute\n )\n\n globalThisWithManifests[MANIFESTS_SINGLETON] = {\n clientReferenceManifestsPerRoute,\n proxiedClientReferenceManifest,\n serverActionsManifest,\n serverModuleMap: createServerModuleMap(),\n }\n }\n}\n\nfunction getManifestsSingleton(): ManifestsSingleton {\n const manifestSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]\n\n if (!manifestSingleton) {\n throw new InvariantError('The manifests singleton was not initialized.')\n }\n\n return manifestSingleton\n}\n\nexport function getClientReferenceManifest(): DeepReadonly<ClientReferenceManifest> {\n return getManifestsSingleton().proxiedClientReferenceManifest\n}\n\nexport function getServerActionsManifest(): DeepReadonly<ActionManifest> {\n return getManifestsSingleton().serverActionsManifest\n}\n\nexport function getServerModuleMap() {\n return getManifestsSingleton().serverModuleMap\n}\n"],"names":["getActionNotFoundError","getClientReferenceManifest","getInvalidServerReferenceIdError","getServerActionsManifest","getServerModuleMap","selectWorkerForForwarding","setManifestsSingleton","actionId","Error","id","encoded","JSON","stringify","length","MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH","slice","TRUNCATED_SERVER_REFERENCE_ID_LENGTH","MANIFESTS_SINGLETON","Symbol","for","globalThisWithManifests","globalThis","createProxiedClientReferenceManifest","clientReferenceManifestsPerRoute","createMappingProxy","prop","Proxy","get","_","workStore","workAsyncStorage","getStore","currentManifest","route","process","env","NODE_ENV","manifest","entry","undefined","values","mappingProxies","Map","InvariantError","proxy","set","String","createServerModuleMap","Object","create","target","receiver","Reflect","wellKnownProperties","has","mightBeServerReferenceId","workers","NEXT_RUNTIME","workerEntry","normalizeWorkerPageName","page","at","moduleId","async","name","chunks","pageName","pathHasPrefix","denormalizeWorkerPageName","bundlePath","normalizeAppPath","removePathPrefix","serverActionsManifest","keys","clientReferenceManifest","rawServerActionsManifest","existingSingleton","encryptionKey","node","assign","edge","proxiedClientReferenceManifest","serverModuleMap","getManifestsSingleton","manifestSingleton"],"mappings":";;;;;;;;;;;;;;;;;;;;IAoBgBA,sBAAsB;eAAtBA;;IA8VAC,0BAA0B;eAA1BA;;IAx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pB,OAAOyB,IAAI,CAACjB,QAAQ,CAAC,EAAE;AAC1D;AAEO,SAASlD,sBAAsB,EACpCsD,IAAI,EACJc,uBAAuB,EACvBF,uBAAuBG,wBAAwB,EAKhD;IACC,MAAMC,oBAAoBxD,uBAAuB,CAACH,oBAAoB;IAEtE,MAAMuD,wBAAsD;QAC1DK,eAAeF,yBAAyBE,aAAa;QACrD,4EAA4E;QAC5E,oCAAoC;QACpCC,MAAM9B,OAAO+B,MAAM,CAAC/B,OAAOC,MAAM,CAAC,OAAO0B,yBAAyBG,IAAI;QACtEE,MAAMhC,OAAO+B,MAAM,CAAC/B,OAAOC,MAAM,CAAC,OAAO0B,yBAAyBK,IAAI;IACxE;IAEA,IAAIJ,mBAAmB;QACrBA,kBAAkBrD,gCAAgC,CAACsB,GAAG,CACpDyB,IAAAA,0BAAgB,EAACV,OACjBc;QAGFE,kBAAkBJ,qBAAqB,GAAGA;IAC5C,OAAO;QACL,MAAMjD,mCAAmC,IAAImB,IAG3C;YAAC;gBAAC4B,IAAAA,0BAAgB,EAACV;gBAAOc;aAAwB;SAAC;QAErD,MAAMO,iCAAiC3D,qCACrCC;QAGFH,uBAAuB,CAACH,oBAAoB,GAAG;YAC7CM;YACA0D;YACAT;YACAU,iBAAiBnC;QACnB;IACF;AACF;AAEA,SAASoC;IACP,MAAMC,oBAAoBhE,uBAAuB,CAACH,oBAAoB;IAEtE,IAAI,CAACmE,mBAAmB;QACtB,MAAM,qBAAkE,CAAlE,IAAIzC,8BAAc,CAAC,iDAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAiE;IACzE;IAEA,OAAOyC;AACT;AAEO,SAASnF;IACd,OAAOkF,wBAAwBF,8BAA8B;AAC/D;AAEO,SAAS9E;IACd,OAAOgF,wBAAwBX,qBAAqB;AACtD;AAEO,SAASpE;IACd,OAAO+E,wBAAwBD,eAAe;AAChD","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/app-render/manifests-singleton.ts"],"sourcesContent":["import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'\nimport type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { mightBeServerReferenceId } from '../../shared/lib/server-reference-info'\nimport { wellKnownProperties } from '../../shared/lib/utils/reflect-utils'\nimport { workAsyncStorage } from './work-async-storage.external'\n\nexport interface ServerModuleMap {\n readonly [name: string]: {\n readonly id: string | number\n readonly name: string\n readonly chunks: Readonly<Array<string>> // currently not used\n readonly async?: boolean\n }\n}\n\nexport function getActionNotFoundError(actionId: string | null): Error {\n return new Error(\n `Failed to find Server Action${actionId ? ` \"${actionId}\"` : ''}. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n )\n}\n\nexport function getInvalidServerReferenceIdError(id: string): Error {\n // `id` is arbitrary client-provided input. Unlike the not-found case, it has\n // not passed the length gate and can reach this error via a malformed server\n // reference in an action payload, so it may be of any length and contain\n // control characters. `JSON.stringify` escapes newlines and quotes so it\n // can't forge log lines, and truncating overly long ids prevents log\n // flooding. Ids at or below the cap are logged in full so that we only add an\n // ellipsis to ids that are meaningfully longer than the truncated length.\n const encoded = JSON.stringify(\n id.length > MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH\n ? id.slice(0, TRUNCATED_SERVER_REFERENCE_ID_LENGTH) + '…'\n : id\n )\n\n return new Error(\n `The Server Reference ID did not match the expected format. Received ${encoded}.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n )\n}\n\n// Ids at or below the cap are logged in full. Longer ids are truncated to the\n// shorter length and marked with an ellipsis, so the cap leaves headroom over\n// the truncated length rather than ellipsizing ids that are barely too long.\nconst MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH = 100\nconst TRUNCATED_SERVER_REFERENCE_ID_LENGTH = 90\n\n// This is a global singleton that is, among other things, also used to\n// encode/decode bound args of server function closures. This can't be using a\n// AsyncLocalStorage as it might happen at the module level.\nconst MANIFESTS_SINGLETON = Symbol.for('next.server.manifests')\n\ninterface RegisteredClientReferenceManifest {\n /**\n * The page the manifest was registered with. Routes are normalized app paths,\n * which is lossy (route groups, parallel slots and the trailing `/page` are\n * stripped), so this is kept alongside for consumers that need to address the\n * manifest on disk again rather than reversing the normalization.\n */\n readonly page: string\n readonly clientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n}\n\ninterface ManifestsSingleton {\n readonly clientReferenceManifestsPerRoute: Map<\n string,\n RegisteredClientReferenceManifest\n >\n readonly proxiedClientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n serverActionsManifest: DeepReadonly<ActionManifest>\n serverModuleMap: ServerModuleMap\n}\n\ntype GlobalThisWithManifests = typeof globalThis & {\n [MANIFESTS_SINGLETON]?: ManifestsSingleton\n}\n\ntype ClientReferenceManifestMappingProp =\n | 'clientModules'\n | 'rscModuleMapping'\n | 'edgeRscModuleMapping'\n | 'ssrModuleMapping'\n | 'edgeSSRModuleMapping'\n\nconst globalThisWithManifests = globalThis as GlobalThisWithManifests\n\nfunction createProxiedClientReferenceManifest(\n clientReferenceManifestsPerRoute: Map<\n string,\n RegisteredClientReferenceManifest\n >\n): DeepReadonly<ClientReferenceManifest> {\n const createMappingProxy = (prop: ClientReferenceManifestMappingProp) => {\n return new Proxy(\n {},\n {\n get(_, id: string) {\n const workStore = workAsyncStorage.getStore()\n\n if (workStore) {\n const currentManifest = clientReferenceManifestsPerRoute.get(\n workStore.route\n )?.clientReferenceManifest\n\n if (currentManifest?.[prop][id]) {\n return currentManifest[prop][id]\n }\n\n // In development, we also check all other manifests to see if the\n // module exists there. This is to support a scenario where React's\n // I/O tracking (dev-only) creates a connection from one page to\n // another through an emitted async I/O node that references client\n // components from the other page, e.g. in owner props.\n // TODO: Maybe we need to add a `debugBundlerConfig` option to React\n // to avoid this workaround. The current workaround has the\n // disadvantage that one might accidentally or intentionally share\n // client references across pages (e.g. by storing them in a global\n // variable), which would then only be caught in production.\n if (process.env.NODE_ENV !== 'production') {\n for (const [\n route,\n { page, clientReferenceManifest },\n ] of clientReferenceManifestsPerRoute) {\n if (route === workStore.route) {\n continue\n }\n\n const entry = clientReferenceManifest[prop][id]\n\n if (entry !== undefined) {\n if (process.env.__NEXT_DEV_SERVER) {\n // The dev validation worker rebuilds this registry in its\n // own thread, seeded with only the route it validates, so\n // it has to be told which other manifests it needs.\n workStore.additionalClientReferenceManifestPages ??=\n new Set()\n workStore.additionalClientReferenceManifestPages.add(page)\n }\n\n return entry\n }\n }\n }\n } else {\n // If there's no work store defined, we can assume that a client\n // reference manifest is needed during module evaluation, e.g. to\n // create a server function using a higher-order function. This\n // might also use client components which need to be serialized by\n // Flight, and therefore client references need to be resolvable. In\n // that case we search all page manifests to find the module.\n for (const {\n clientReferenceManifest,\n } of clientReferenceManifestsPerRoute.values()) {\n const entry = clientReferenceManifest[prop][id]\n\n if (entry !== undefined) {\n return entry\n }\n }\n }\n\n return undefined\n },\n }\n )\n }\n\n const mappingProxies = new Map<\n ClientReferenceManifestMappingProp,\n ReturnType<typeof createMappingProxy>\n >()\n\n return new Proxy(\n {},\n {\n get(_, prop) {\n const workStore = workAsyncStorage.getStore()\n\n switch (prop) {\n case 'moduleLoading':\n case 'entryCSSFiles':\n case 'entryJSFiles': {\n if (!workStore) {\n throw new InvariantError(\n `Cannot access \"${prop}\" without a work store.`\n )\n }\n\n const registeredManifest = clientReferenceManifestsPerRoute.get(\n workStore.route\n )\n\n if (!registeredManifest) {\n throw new InvariantError(\n `The client reference manifest for route \"${workStore.route}\" does not exist.`\n )\n }\n\n return registeredManifest.clientReferenceManifest[prop]\n }\n case 'clientModules':\n case 'rscModuleMapping':\n case 'edgeRscModuleMapping':\n case 'ssrModuleMapping':\n case 'edgeSSRModuleMapping': {\n let proxy = mappingProxies.get(prop)\n\n if (!proxy) {\n proxy = createMappingProxy(prop)\n mappingProxies.set(prop, proxy)\n }\n\n return proxy\n }\n default: {\n throw new InvariantError(\n `This is a proxied client reference manifest. The property \"${String(prop)}\" is not handled.`\n )\n }\n }\n },\n }\n ) as DeepReadonly<ClientReferenceManifest>\n}\n\n/**\n * This function creates a Flight-acceptable server module map proxy from our\n * Server Reference Manifest similar to our client module map. This is because\n * our manifest contains a lot of internal Next.js data that are relevant to the\n * runtime, workers, etc. that React doesn't need to know.\n */\nfunction createServerModuleMap(): ServerModuleMap {\n return new Proxy(Object.create(null) as ServerModuleMap, {\n get: (target, id: string | symbol, receiver) => {\n // React's debug serialization can probe the module map like a plain object.\n // These probes are not server reference lookups.\n if (typeof id !== 'string') {\n return Reflect.get(target, id, receiver)\n }\n\n if (wellKnownProperties.has(id)) {\n return Reflect.get(target, id, receiver)\n }\n\n if (!mightBeServerReferenceId(id)) {\n throw getInvalidServerReferenceIdError(id)\n }\n\n const workers =\n getServerActionsManifest()[\n process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n ]?.[id]?.workers\n\n if (!workers) {\n throw getActionNotFoundError(id)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n let workerEntry: { moduleId: string | number; async: boolean } | undefined\n\n if (workStore) {\n workerEntry = workers[normalizeWorkerPageName(workStore.page)]\n } else {\n // If there's no work store defined, we can assume that a server\n // module map is needed during module evaluation, e.g. to create a\n // server action using a higher-order function. Therefore it should be\n // safe to return any entry from the manifest that matches the action\n // ID. They all refer to the same module ID, which must also exist in\n // the current page bundle. TODO: This is currently not guaranteed in\n // Turbopack, and needs to be fixed.\n workerEntry = Object.values(workers).at(0)\n }\n\n if (!workerEntry) {\n throw getActionNotFoundError(id)\n }\n\n const { moduleId, async } = workerEntry\n\n return { id: moduleId, name: id, chunks: [], async }\n },\n })\n}\n\n/**\n * The flight entry loader keys actions by bundlePath. bundlePath corresponds\n * with the relative path (including 'app') to the page entrypoint.\n */\nfunction normalizeWorkerPageName(pageName: string) {\n if (pathHasPrefix(pageName, 'app')) {\n return pageName\n }\n\n return 'app' + pageName\n}\n\n/**\n * Converts a bundlePath (relative path to the entrypoint) to a routable page\n * name.\n */\nfunction denormalizeWorkerPageName(bundlePath: string) {\n return normalizeAppPath(removePathPrefix(bundlePath, 'app'))\n}\n\n/**\n * Checks if the requested action has a worker for the current page.\n * If not, it returns the first worker that has a handler for the action.\n */\nexport function selectWorkerForForwarding(\n actionId: string,\n pageName: string\n): string | undefined {\n const serverActionsManifest = getServerActionsManifest()\n const workers =\n serverActionsManifest[\n process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'\n ][actionId]?.workers\n\n // There are no workers to handle this action, nothing to forward to.\n if (!workers) {\n return\n }\n\n // If there is an entry for the current page, we don't need to forward.\n if (workers[normalizeWorkerPageName(pageName)]) {\n return\n }\n\n // Otherwise, grab the first worker that has a handler for this action id.\n return denormalizeWorkerPageName(Object.keys(workers)[0])\n}\n\nexport function setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest: rawServerActionsManifest,\n}: {\n page: string\n clientReferenceManifest: DeepReadonly<ClientReferenceManifest>\n serverActionsManifest: DeepReadonly<ActionManifest>\n}) {\n const existingSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]\n const route = normalizeAppPath(page)\n\n const serverActionsManifest: DeepReadonly<ActionManifest> = {\n encryptionKey: rawServerActionsManifest.encryptionKey,\n // Use null-prototypes for the action objects to prevent prototype pollution\n // from affecting action ID lookups.\n node: Object.assign(Object.create(null), rawServerActionsManifest.node),\n edge: Object.assign(Object.create(null), rawServerActionsManifest.edge),\n }\n\n if (existingSingleton) {\n existingSingleton.clientReferenceManifestsPerRoute.set(route, {\n page,\n clientReferenceManifest,\n })\n\n existingSingleton.serverActionsManifest = serverActionsManifest\n } else {\n const clientReferenceManifestsPerRoute = new Map<\n string,\n RegisteredClientReferenceManifest\n >([[route, { page, clientReferenceManifest }]])\n\n const proxiedClientReferenceManifest = createProxiedClientReferenceManifest(\n clientReferenceManifestsPerRoute\n )\n\n globalThisWithManifests[MANIFESTS_SINGLETON] = {\n clientReferenceManifestsPerRoute,\n proxiedClientReferenceManifest,\n serverActionsManifest,\n serverModuleMap: createServerModuleMap(),\n }\n }\n}\n\nfunction getManifestsSingleton(): ManifestsSingleton {\n const manifestSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]\n\n if (!manifestSingleton) {\n throw new InvariantError('The manifests singleton was not initialized.')\n }\n\n return manifestSingleton\n}\n\nexport function getClientReferenceManifest(): DeepReadonly<ClientReferenceManifest> {\n return getManifestsSingleton().proxiedClientReferenceManifest\n}\n\nexport function getServerActionsManifest(): DeepReadonly<ActionManifest> {\n return getManifestsSingleton().serverActionsManifest\n}\n\nexport function getServerModuleMap() {\n return getManifestsSingleton().serverModuleMap\n}\n"],"names":["getActionNotFoundError","getClientReferenceManifest","getInvalidServerReferenceIdError","getServerActionsManifest","getServerModuleMap","selectWorkerForForwarding","setManifestsSingleton","actionId","Error","id","encoded","JSON","stringify","length","MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH","slice","TRUNCATED_SERVER_REFERENCE_ID_LENGTH","MANIFESTS_SINGLETON","Symbol","for","globalThisWithManifests","globalThis","createProxiedClientReferenceManifest","clientReferenceManifestsPerRoute","createMappingProxy","prop","Proxy","get","_","workStore","workAsyncStorage","getStore","currentManifest","route","clientReferenceManifest","process","env","NODE_ENV","page","entry","undefined","__NEXT_DEV_SERVER","additionalClientReferenceManifestPages","Set","add","values","mappingProxies","Map","InvariantError","registeredManifest","proxy","set","String","createServerModuleMap","Object","create","target","receiver","Reflect","wellKnownProperties","has","mightBeServerReferenceId","workers","NEXT_RUNTIME","workerEntry","normalizeWorkerPageName","at","moduleId","async","name","chunks","pageName","pathHasPrefix","denormalizeWorkerPageName","bundlePath","normalizeAppPath","removePathPrefix","serverActionsManifest","keys","rawServerActionsManifest","existingSingleton","encryptionKey","node","assign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,uBAAuB,CAACH,oBAAoB,GAAG;YAC7CM;YACA8D;YACAR;YACAS,iBAAiBjC;QACnB;IACF;AACF;AAEA,SAASkC;IACP,MAAMC,oBAAoBpE,uBAAuB,CAACH,oBAAoB;IAEtE,IAAI,CAACuE,mBAAmB;QACtB,MAAM,qBAAkE,CAAlE,IAAIxC,8BAAc,CAAC,iDAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAiE;IACzE;IAEA,OAAOwC;AACT;AAEO,SAASvF;IACd,OAAOsF,wBAAwBF,8BAA8B;AAC/D;AAEO,SAASlF;IACd,OAAOoF,wBAAwBV,qBAAqB;AACtD;AAEO,SAASzE;IACd,OAAOmF,wBAAwBD,eAAe;AAChD","ignoreList":[0]} |
@@ -125,2 +125,12 @@ import type { AsyncLocalStorage } from 'async_hooks'; | ||
| /** | ||
| * Pages, other than the one being rendered, whose client reference manifest | ||
| * supplied a client reference for this render. Only populated by the dev | ||
| * server, where React's I/O tracking can carry a reference from another page | ||
| * into this render, which `createProxiedClientReferenceManifest` resolves by | ||
| * searching the other pages' manifests. The dev validation worker rebuilds | ||
| * that registry in its own thread from the route it validates, so it relies | ||
| * on this to know which other manifests to register. | ||
| */ | ||
| additionalClientReferenceManifestPages?: Set<string>; | ||
| /** | ||
| * Run the given function inside a clean AsyncLocalStorage snapshot. This is | ||
@@ -127,0 +137,0 @@ * useful when generating cache entries, to ensure that the cache generation |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/app-render/work-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { FetchMetrics } from '../base-http'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'\nimport type { AfterContext } from '../after/after-context'\nimport type { ResolvedCacheLifeProfiles } from '../config-shared'\nimport type { SharedCacheResult } from '../use-cache/use-cache-wrapper'\nimport type { ValidationLevel } from '../config-shared'\n\n// Share the instance module in the next-shared layer\nimport { workAsyncStorageInstance } from './work-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { LazyResult } from '../lib/lazy-result'\nimport type { DigestedError } from './create-error-handler'\nimport type { ActionRevalidationKind } from '../../shared/lib/action-revalidation-kind'\n\nexport interface WorkStore {\n readonly isStaticGeneration: boolean\n\n /**\n * The page that is being rendered. This relates to the path to the page file.\n */\n readonly page: string\n\n /**\n * The route that is being rendered. This is the page property without the\n * trailing `/page` or `/route` suffix.\n */\n readonly route: string\n\n readonly incrementalCache?: IncrementalCache\n readonly cacheLifeProfiles: ResolvedCacheLifeProfiles\n readonly useCacheTimeout: number\n readonly staticPageGenerationTimeout: number\n\n readonly isOnDemandRevalidate?: boolean\n readonly isBuildTimePrerendering?: boolean\n\n forceDynamic?: boolean\n fetchCache?: AppSegmentConfig['fetchCache']\n\n forceStatic?: boolean\n dynamicShouldError?: boolean\n pendingRevalidates?: Record<string, Promise<any>>\n pendingRevalidateWrites?: Array<Promise<void>> // This is like pendingRevalidates but isn't used for deduping.\n readonly afterContext: AfterContext\n\n dynamicUsageDescription?: string\n dynamicUsageStack?: string\n\n /**\n * Invalid dynamic usage errors might be caught in userland. We attach them to\n * the work store to ensure we can still fail the build, or show en error in\n * dev mode.\n */\n // TODO: Collect an array of errors, and throw as AggregateError when\n // `serializeError` and the Dev Overlay support it.\n invalidDynamicUsageError?: Error\n\n nextFetchId?: number\n pathWasRevalidated?: ActionRevalidationKind\n\n /**\n * Tags that were revalidated during the current request. They need to be sent\n * to cache handlers to propagate their revalidation.\n */\n pendingRevalidatedTags?: Array<{\n tag: string\n profile?: string | { stale?: number; revalidate?: number; expire?: number }\n }>\n\n /**\n * Tags that were previously revalidated (e.g. by a redirecting server action)\n * and have already been sent to cache handlers. Retrieved cache entries that\n * include any of these tags must be discarded.\n */\n readonly previouslyRevalidatedTags: readonly string[]\n\n /**\n * This map contains lazy results so that we can evaluate them when the first\n * cache entry is read. It allows us to skip refreshing tags if no caches are\n * read at all.\n */\n readonly refreshTagsByCacheKind: Map<string, LazyResult<void>>\n\n fetchMetrics?: FetchMetrics\n shouldTrackFetchMetrics: boolean\n\n /**\n * Tracks pending `\"use cache\"` invocations within the current request scope,\n * keyed by the serialized cache key (coarse key). Used for intra-request\n * deduplication: when multiple components call the same cache function within\n * a single request, only the first one runs (cache handler lookup +\n * generation), and joiners tee its result stream.\n * Root params are identical within a request, so the coarse key is sufficient.\n */\n pendingCacheInvocations?: Map<string, Promise<SharedCacheResult>>\n\n /**\n * Set by the dev-server's hang-detection probe worker (see\n * `use-cache-probe-worker.ts`) to switch `cache()` into a one-shot fill\n * path: run `generateCacheEntry` as for a cold fill, drain the resulting\n * stream, return. No cache-handler or resume-data-cache I/O, no\n * intra-request leader election — the probe just needs to learn whether\n * the body completes in module-scope isolation.\n */\n readonly useCacheProbeMode?: {\n /**\n * Max wall time the probe fill may take. `cache()` enforces this with\n * `UseCacheTimeoutError`, which the probe worker translates to\n * `{ outcome: 'hung' }` for the parent process.\n */\n readonly timeoutMs: number\n }\n\n isDraftMode?: boolean\n isUnstableNoStore?: boolean\n isPrefetchRequest?: boolean\n\n /**\n * Dev-only request identity used by local request insights. requestId\n * identifies one server request, while htmlRequestId groups requests that\n * originated from the same browser page.\n */\n requestId?: string\n htmlRequestId?: string\n\n /**\n * This only exists because it's needed in use-cache-wrapper\n */\n deploymentId: string\n /**\n * Prefer `sharedContext.buildId` instead. This only exists because it's needed in use-cache-wrapper\n */\n buildId: string\n\n readonly reactLoadableManifest?: DeepReadonly<\n Record<string, { files: string[] }>\n >\n readonly assetPrefix?: string\n readonly nonce?: string\n\n cacheComponentsEnabled: boolean\n validationLevel: ValidationLevel\n\n /**\n * Run the given function inside a clean AsyncLocalStorage snapshot. This is\n * useful when generating cache entries, to ensure that the cache generation\n * cannot read anything from the context we're currently executing in, which\n * might include request-specific things like `cookies()` inside a\n * `React.cache()`.\n */\n runInCleanSnapshot: <R, TArgs extends any[]>(\n fn: (...args: TArgs) => R,\n ...args: TArgs\n ) => R\n\n reactServerErrorsByDigest: Map<string, DigestedError>\n}\n\nexport type WorkAsyncStorage = AsyncLocalStorage<WorkStore>\n\nexport { workAsyncStorageInstance as workAsyncStorage }\n"],"names":["workAsyncStorage","workAsyncStorageInstance"],"mappings":";;;;+BAkKqCA;;;eAA5BC,kDAAwB;;;0CAvJQ","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/app-render/work-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { FetchMetrics } from '../base-http'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'\nimport type { AfterContext } from '../after/after-context'\nimport type { ResolvedCacheLifeProfiles } from '../config-shared'\nimport type { SharedCacheResult } from '../use-cache/use-cache-wrapper'\nimport type { ValidationLevel } from '../config-shared'\n\n// Share the instance module in the next-shared layer\nimport { workAsyncStorageInstance } from './work-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { LazyResult } from '../lib/lazy-result'\nimport type { DigestedError } from './create-error-handler'\nimport type { ActionRevalidationKind } from '../../shared/lib/action-revalidation-kind'\n\nexport interface WorkStore {\n readonly isStaticGeneration: boolean\n\n /**\n * The page that is being rendered. This relates to the path to the page file.\n */\n readonly page: string\n\n /**\n * The route that is being rendered. This is the page property without the\n * trailing `/page` or `/route` suffix.\n */\n readonly route: string\n\n readonly incrementalCache?: IncrementalCache\n readonly cacheLifeProfiles: ResolvedCacheLifeProfiles\n readonly useCacheTimeout: number\n readonly staticPageGenerationTimeout: number\n\n readonly isOnDemandRevalidate?: boolean\n readonly isBuildTimePrerendering?: boolean\n\n forceDynamic?: boolean\n fetchCache?: AppSegmentConfig['fetchCache']\n\n forceStatic?: boolean\n dynamicShouldError?: boolean\n pendingRevalidates?: Record<string, Promise<any>>\n pendingRevalidateWrites?: Array<Promise<void>> // This is like pendingRevalidates but isn't used for deduping.\n readonly afterContext: AfterContext\n\n dynamicUsageDescription?: string\n dynamicUsageStack?: string\n\n /**\n * Invalid dynamic usage errors might be caught in userland. We attach them to\n * the work store to ensure we can still fail the build, or show en error in\n * dev mode.\n */\n // TODO: Collect an array of errors, and throw as AggregateError when\n // `serializeError` and the Dev Overlay support it.\n invalidDynamicUsageError?: Error\n\n nextFetchId?: number\n pathWasRevalidated?: ActionRevalidationKind\n\n /**\n * Tags that were revalidated during the current request. They need to be sent\n * to cache handlers to propagate their revalidation.\n */\n pendingRevalidatedTags?: Array<{\n tag: string\n profile?: string | { stale?: number; revalidate?: number; expire?: number }\n }>\n\n /**\n * Tags that were previously revalidated (e.g. by a redirecting server action)\n * and have already been sent to cache handlers. Retrieved cache entries that\n * include any of these tags must be discarded.\n */\n readonly previouslyRevalidatedTags: readonly string[]\n\n /**\n * This map contains lazy results so that we can evaluate them when the first\n * cache entry is read. It allows us to skip refreshing tags if no caches are\n * read at all.\n */\n readonly refreshTagsByCacheKind: Map<string, LazyResult<void>>\n\n fetchMetrics?: FetchMetrics\n shouldTrackFetchMetrics: boolean\n\n /**\n * Tracks pending `\"use cache\"` invocations within the current request scope,\n * keyed by the serialized cache key (coarse key). Used for intra-request\n * deduplication: when multiple components call the same cache function within\n * a single request, only the first one runs (cache handler lookup +\n * generation), and joiners tee its result stream.\n * Root params are identical within a request, so the coarse key is sufficient.\n */\n pendingCacheInvocations?: Map<string, Promise<SharedCacheResult>>\n\n /**\n * Set by the dev-server's hang-detection probe worker (see\n * `use-cache-probe-worker.ts`) to switch `cache()` into a one-shot fill\n * path: run `generateCacheEntry` as for a cold fill, drain the resulting\n * stream, return. No cache-handler or resume-data-cache I/O, no\n * intra-request leader election — the probe just needs to learn whether\n * the body completes in module-scope isolation.\n */\n readonly useCacheProbeMode?: {\n /**\n * Max wall time the probe fill may take. `cache()` enforces this with\n * `UseCacheTimeoutError`, which the probe worker translates to\n * `{ outcome: 'hung' }` for the parent process.\n */\n readonly timeoutMs: number\n }\n\n isDraftMode?: boolean\n isUnstableNoStore?: boolean\n isPrefetchRequest?: boolean\n\n /**\n * Dev-only request identity used by local request insights. requestId\n * identifies one server request, while htmlRequestId groups requests that\n * originated from the same browser page.\n */\n requestId?: string\n htmlRequestId?: string\n\n /**\n * This only exists because it's needed in use-cache-wrapper\n */\n deploymentId: string\n /**\n * Prefer `sharedContext.buildId` instead. This only exists because it's needed in use-cache-wrapper\n */\n buildId: string\n\n readonly reactLoadableManifest?: DeepReadonly<\n Record<string, { files: string[] }>\n >\n readonly assetPrefix?: string\n readonly nonce?: string\n\n cacheComponentsEnabled: boolean\n validationLevel: ValidationLevel\n\n /**\n * Pages, other than the one being rendered, whose client reference manifest\n * supplied a client reference for this render. Only populated by the dev\n * server, where React's I/O tracking can carry a reference from another page\n * into this render, which `createProxiedClientReferenceManifest` resolves by\n * searching the other pages' manifests. The dev validation worker rebuilds\n * that registry in its own thread from the route it validates, so it relies\n * on this to know which other manifests to register.\n */\n additionalClientReferenceManifestPages?: Set<string>\n\n /**\n * Run the given function inside a clean AsyncLocalStorage snapshot. This is\n * useful when generating cache entries, to ensure that the cache generation\n * cannot read anything from the context we're currently executing in, which\n * might include request-specific things like `cookies()` inside a\n * `React.cache()`.\n */\n runInCleanSnapshot: <R, TArgs extends any[]>(\n fn: (...args: TArgs) => R,\n ...args: TArgs\n ) => R\n\n reactServerErrorsByDigest: Map<string, DigestedError>\n}\n\nexport type WorkAsyncStorage = AsyncLocalStorage<WorkStore>\n\nexport { workAsyncStorageInstance as workAsyncStorage }\n"],"names":["workAsyncStorage","workAsyncStorageInstance"],"mappings":";;;;+BA6KqCA;;;eAA5BC,kDAAwB;;;0CAlKQ","ignoreList":[0]} |
@@ -280,2 +280,3 @@ import type { NextConfig } from './config'; | ||
| }>>; | ||
| devValidationWorker: z.ZodOptional<z.ZodBoolean>; | ||
| staticGenerationRetryCount: z.ZodOptional<z.ZodNumber>; | ||
@@ -282,0 +283,0 @@ staticGenerationMaxConcurrency: z.ZodOptional<z.ZodNumber>; |
@@ -446,2 +446,3 @@ "use strict"; | ||
| }).optional(), | ||
| devValidationWorker: _zod.z.boolean().optional(), | ||
| staticGenerationRetryCount: _zod.z.number().int().optional(), | ||
@@ -448,0 +449,0 @@ staticGenerationMaxConcurrency: _zod.z.number().int().optional(), |
@@ -196,2 +196,3 @@ "use strict"; | ||
| coldCacheBadge: false, | ||
| devValidationWorker: true, | ||
| useSkewCookie: false, | ||
@@ -198,0 +199,0 @@ cssChunking: true, |
@@ -120,3 +120,12 @@ "use strict"; | ||
| } | ||
| return (0, _sourcemaps.devirtualizeReactServerURL)(fileParam); | ||
| const file = (0, _sourcemaps.devirtualizeReactServerURL)(fileParam); | ||
| // React virtualizes filenames as `'file://' + path`, which is malformed | ||
| // for paths that need percent-encoding (e.g. a space in the project path) | ||
| // and then fails both Turbopack's `traceSource` and Node.js' source map | ||
| // cache lookups. Re-encode through WHATWG URL parsing. | ||
| // TODO(veil): Revisit if React's virtualization round-trips losslessly. | ||
| if (file.startsWith('file://') && URL.canParse(file)) { | ||
| return new URL(file).href; | ||
| } | ||
| return file; | ||
| } | ||
@@ -123,0 +132,0 @@ function createStackFrames(body) { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/dev/middleware-turbopack.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport {\n DEVTOOLS_CODE_FRAME_MAX_WIDTH,\n getOriginalCodeFrame,\n ignoreListAnonymousStackFramesIfSandwiched,\n type IgnorableStackFrame,\n type OriginalStackFrameResponse,\n type OriginalStackFramesRequest,\n type OriginalStackFramesResponse,\n type StackFrame,\n} from '../../next-devtools/server/shared'\nimport { middlewareResponse } from '../../next-devtools/server/middleware-response'\nimport path from 'path'\nimport { openFileInEditor } from '../../next-devtools/server/launch-editor'\nimport {\n SourceMapConsumer,\n type NullableMappedPosition,\n} from 'next/dist/compiled/source-map08'\nimport type { Project, TurbopackStackFrame } from '../../build/swc/types'\nimport {\n type ModernSourceMapPayload,\n devirtualizeReactServerURL,\n findApplicableSourceMapPayload,\n} from '../lib/source-maps'\nimport { findSourceMap, type SourceMap } from 'node:module'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { inspect } from 'node:util'\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 modulePath.startsWith('node:')\n )\n}\n\nconst currentSourcesByFile: Map<string, Promise<string | null>> = new Map()\n/**\n * @returns 1-based lines and 1-based columns\n */\nasync function batchedTraceSource(\n project: Project,\n frame: TurbopackStackFrame\n): Promise<{ frame: IgnorableStackFrame; source: string | null } | undefined> {\n const file = frame.file\n ? // TODO(veil): Why are the frames sent encoded?\n decodeURIComponent(frame.file)\n : undefined\n\n if (!file) return\n\n // For node internals they cannot traced the actual source code with project.traceSource,\n // we need an early return to indicate it's ignored to avoid the unknown scheme error from `project.traceSource`.\n if (file.startsWith('node:')) {\n return {\n frame: {\n file,\n line1: frame.line ?? null,\n column1: frame.column ?? null,\n methodName: frame.methodName ?? '<unknown>',\n ignored: true,\n arguments: [],\n },\n source: null,\n }\n }\n\n const currentDirectoryFileUrl = pathToFileURL(process.cwd()).href\n\n const sourceFrame = await project.traceSource(frame, currentDirectoryFileUrl)\n if (!sourceFrame) {\n return {\n frame: {\n file,\n line1: frame.line ?? null,\n column1: frame.column ?? null,\n methodName: frame.methodName ?? '<unknown>',\n ignored: shouldIgnorePath(file),\n arguments: [],\n },\n source: null,\n }\n }\n\n let source = null\n const originalFile = sourceFrame.originalFile\n\n // Don't look up source for node_modules or internals. These can often be large bundled files.\n const ignored =\n // Check the sourcemap's ignoreList (e.g. from 3rd party packages)\n !!sourceFrame.isIgnored ||\n shouldIgnorePath(originalFile ?? sourceFrame.file)\n if (originalFile && !ignored) {\n let sourcePromise = currentSourcesByFile.get(originalFile)\n if (!sourcePromise) {\n sourcePromise = project.getSourceForAsset(originalFile)\n currentSourcesByFile.set(originalFile, sourcePromise)\n setTimeout(() => {\n // Cache file reads for 100ms, as frames will often reference the same\n // files and can be large.\n currentSourcesByFile.delete(originalFile!)\n }, 100)\n }\n source = await sourcePromise\n }\n\n const ignorableFrame: IgnorableStackFrame = {\n file: sourceFrame.file,\n line1: sourceFrame.line ?? null,\n column1: sourceFrame.column ?? null,\n methodName:\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n frame.methodName ?? '<unknown>',\n ignored,\n arguments: [],\n }\n\n return {\n frame: ignorableFrame,\n source,\n }\n}\n\nfunction parseFile(fileParam: string | null): string | undefined {\n if (!fileParam) {\n return undefined\n }\n\n return devirtualizeReactServerURL(fileParam)\n}\n\nfunction createStackFrames(\n body: OriginalStackFramesRequest\n): TurbopackStackFrame[] {\n const { frames, isServer } = body\n\n return frames\n .map((frame): TurbopackStackFrame | undefined => {\n const file = parseFile(frame.file)\n\n if (!file) {\n return undefined\n }\n\n return {\n file,\n methodName: frame.methodName ?? '<unknown>',\n line: frame.line1 ?? undefined,\n column: frame.column1 ?? undefined,\n isServer,\n }\n })\n .filter((f): f is TurbopackStackFrame => f !== undefined)\n}\n\nfunction createStackFrame(\n searchParams: URLSearchParams\n): TurbopackStackFrame | undefined {\n const file = parseFile(searchParams.get('file'))\n\n if (!file) {\n return undefined\n }\n\n return {\n file,\n methodName: searchParams.get('methodName') ?? '<unknown>',\n line: parseInt(searchParams.get('line1') ?? '0', 10) || undefined,\n column: parseInt(searchParams.get('column1') ?? '0', 10) || undefined,\n isServer: searchParams.get('isServer') === 'true',\n }\n}\n\n/**\n * @returns 1-based lines and 1-based columns\n */\nasync function nativeTraceSource(\n frame: TurbopackStackFrame\n): Promise<{ frame: IgnorableStackFrame; source: string | null } | undefined> {\n const sourceURL = frame.file\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMap(sourceURL)?.payload\n } catch (cause) {\n throw new Error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n }\n\n if (sourceMapPayload !== undefined) {\n let consumer: SourceMapConsumer\n try {\n consumer = await new SourceMapConsumer(sourceMapPayload)\n } catch (cause) {\n throw new Error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n }\n let traced: {\n originalPosition: NullableMappedPosition\n sourceContent: string | null\n } | null\n try {\n const originalPosition = consumer.originalPositionFor({\n line: frame.line ?? 1,\n // 0-based columns out requires 0-based columns in.\n column: (frame.column ?? 1) - 1,\n })\n\n if (originalPosition.source === null) {\n traced = null\n } else {\n const sourceContent: string | null =\n consumer.sourceContentFor(\n originalPosition.source,\n /* returnNullOnMissing */ true\n ) ?? null\n\n traced = { originalPosition, sourceContent }\n }\n } finally {\n consumer.destroy()\n }\n\n if (traced !== null) {\n const { originalPosition, sourceContent } = traced\n const applicableSourceMap = findApplicableSourceMapPayload(\n (frame.line ?? 1) - 1,\n (frame.column ?? 1) - 1,\n sourceMapPayload\n )\n\n // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.\n let ignored = false\n if (applicableSourceMap === undefined) {\n console.error(\n 'No applicable source map found in sections for frame',\n frame\n )\n } else {\n // TODO: O(n^2). Consider moving `ignoreList` into a Set\n const sourceIndex = applicableSourceMap.sources.indexOf(\n originalPosition.source!\n )\n ignored =\n applicableSourceMap.ignoreList?.includes(sourceIndex) ??\n // When sourcemap is not available, fallback to checking `frame.file`.\n // e.g. In pages router, nextjs server code is not bundled into the page.\n shouldIgnorePath(frame.file)\n }\n\n const originalStackFrame: IgnorableStackFrame = {\n methodName:\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n frame.methodName\n ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n ?.replace('__webpack_exports__.', '') || '<unknown>',\n file: originalPosition.source,\n line1: originalPosition.line,\n column1:\n originalPosition.column === null ? null : originalPosition.column + 1,\n // TODO: c&p from async createOriginalStackFrame but why not frame.arguments?\n arguments: [],\n ignored,\n }\n\n return {\n frame: originalStackFrame,\n source: sourceContent,\n }\n }\n }\n\n return undefined\n}\n\n/**\n * Code frame rendering options. The defaults match terminal consumers; only\n * the overlay HTTP path opts in to always-on colors and the wide max width.\n */\ntype CodeFrameOptions = {\n /** Defaults to `process.stdout.isTTY`. */\n colors?: boolean\n /** Defaults to the dev server's terminal width. */\n maxWidth?: number\n}\n\nasync function createOriginalStackFrame(\n project: Project,\n projectPath: string,\n frame: TurbopackStackFrame,\n codeFrameOptions?: CodeFrameOptions\n): Promise<OriginalStackFrameResponse | null> {\n const traced =\n (await nativeTraceSource(frame)) ??\n // TODO(veil): When would the bundler know more than native?\n // If it's faster, try the bundler first and fall back to native later.\n (await batchedTraceSource(project, frame))\n if (!traced) {\n return null\n }\n\n let normalizedStackFrameLocation = traced.frame.file\n if (\n normalizedStackFrameLocation !== null &&\n normalizedStackFrameLocation.startsWith('file://')\n ) {\n normalizedStackFrameLocation = path.relative(\n projectPath,\n fileURLToPath(normalizedStackFrameLocation)\n )\n }\n\n /** undefined = not yet computed */\n let originalCodeFrame: string | null | undefined\n\n const tracedFrame = traced.frame\n return {\n originalStackFrame: {\n arguments: tracedFrame.arguments,\n file: normalizedStackFrameLocation,\n line1: tracedFrame.line1,\n column1: tracedFrame.column1,\n ignored: tracedFrame.ignored,\n methodName: tracedFrame.methodName,\n },\n get originalCodeFrame() {\n if (originalCodeFrame === undefined) {\n originalCodeFrame = getOriginalCodeFrame(tracedFrame, traced.source, {\n colors: codeFrameOptions?.colors,\n maxWidth: codeFrameOptions?.maxWidth,\n })\n }\n return originalCodeFrame\n },\n }\n}\n\nexport function getOverlayMiddleware({\n project,\n projectPath,\n isSrcDir,\n}: {\n project: Project\n projectPath: string\n isSrcDir: boolean\n}) {\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(req.url!, 'http://n')\n\n if (pathname === '/__nextjs_original-stack-frames') {\n if (req.method !== 'POST') {\n return middlewareResponse.badRequest(res)\n }\n\n const body = await new Promise<string>((resolve, reject) => {\n let data = ''\n req.on('data', (chunk) => {\n data += chunk\n })\n req.on('end', () => resolve(data))\n req.on('error', reject)\n })\n\n const request = JSON.parse(body) as OriginalStackFramesRequest\n const result = await getOriginalStackFrames({\n project,\n projectPath,\n frames: request.frames,\n isServer: request.isServer,\n isEdgeServer: request.isEdgeServer,\n isAppDirectory: request.isAppDirectory,\n codeFrameOptions: {\n // Overlay parses ANSI in JS and renders in a scrollable\n // `<pre>`, so colors are always wanted and terminal width is\n // irrelevant.\n colors: true,\n maxWidth: DEVTOOLS_CODE_FRAME_MAX_WIDTH,\n },\n })\n\n ignoreListAnonymousStackFramesIfSandwiched(result)\n\n return middlewareResponse.json(res, result)\n } else if (pathname === '/__nextjs_launch-editor') {\n const isAppRelativePath = searchParams.get('isAppRelativePath') === '1'\n\n let openEditorResult\n if (isAppRelativePath) {\n const relativeFilePath = searchParams.get('file') || ''\n const appPath = path.join(\n isSrcDir ? 'src' : '',\n 'app',\n relativeFilePath\n )\n openEditorResult = await openFileInEditor(appPath, 1, 1, projectPath)\n } else {\n const frame = createStackFrame(searchParams)\n if (!frame) return middlewareResponse.badRequest(res)\n openEditorResult = await openFileInEditor(\n frame.file,\n frame.line ?? 1,\n frame.column ?? 1,\n projectPath\n )\n }\n\n if (openEditorResult.error) {\n return middlewareResponse.internalServerError(\n res,\n openEditorResult.error\n )\n }\n if (!openEditorResult.found) {\n return middlewareResponse.notFound(res)\n }\n return middlewareResponse.noContent(res)\n }\n\n return next()\n }\n}\n\nexport function getSourceMapMiddleware(project: Project) {\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(req.url!, 'http://n')\n\n if (pathname !== '/__nextjs_source-map') {\n return next()\n }\n\n let filename = searchParams.get('filename')\n\n if (!filename) {\n return middlewareResponse.badRequest(res)\n }\n\n let nativeSourceMap: SourceMap | undefined\n try {\n nativeSourceMap = findSourceMap(filename)\n } catch (cause) {\n return middlewareResponse.internalServerError(\n res,\n new Error(\n `${filename}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n )\n }\n\n if (nativeSourceMap !== undefined) {\n const sourceMapPayload = nativeSourceMap.payload\n return middlewareResponse.json(res, sourceMapPayload)\n }\n\n try {\n // Turbopack chunk filenames might be URL-encoded.\n filename = decodeURI(filename)\n } catch {\n return middlewareResponse.badRequest(res)\n }\n\n if (path.isAbsolute(filename)) {\n filename = pathToFileURL(filename).href\n }\n\n try {\n const sourceMapString = await project.getSourceMap(filename)\n\n if (sourceMapString) {\n return middlewareResponse.jsonString(res, sourceMapString)\n }\n } catch (cause) {\n return middlewareResponse.internalServerError(\n res,\n new Error(\n `Failed to get source map for '${filename}'. This is a bug in Next.js`,\n {\n cause,\n }\n )\n )\n }\n\n middlewareResponse.noContent(res)\n }\n}\n\nexport async function getOriginalStackFrames({\n project,\n projectPath,\n frames,\n isServer,\n isEdgeServer,\n isAppDirectory,\n codeFrameOptions,\n}: {\n project: Project\n projectPath: string\n frames: readonly StackFrame[]\n isServer: boolean\n isEdgeServer: boolean\n isAppDirectory: boolean\n codeFrameOptions?: CodeFrameOptions\n}): Promise<OriginalStackFramesResponse> {\n const stackFrames = createStackFrames({\n frames,\n isServer,\n isEdgeServer,\n isAppDirectory,\n })\n\n return Promise.all(\n stackFrames.map(async (frame) => {\n try {\n const stackFrame = await createOriginalStackFrame(\n project,\n projectPath,\n frame,\n codeFrameOptions\n )\n if (stackFrame === null) {\n return {\n status: 'rejected',\n reason: 'Failed to create original stack frame',\n }\n }\n const originalStackFrame = stackFrame.originalStackFrame\n return {\n status: 'fulfilled',\n value: {\n originalStackFrame,\n originalCodeFrame:\n (originalStackFrame?.ignored ?? true)\n ? null\n : // TODO: Don't get all codeframes of non-ignored frames eagerly.\n stackFrame.originalCodeFrame,\n },\n }\n } catch (error) {\n return {\n status: 'rejected',\n reason: inspect(error, { colors: false }),\n }\n }\n })\n )\n}\n"],"names":["getOriginalStackFrames","getOverlayMiddleware","getSourceMapMiddleware","shouldIgnorePath","modulePath","includes","startsWith","currentSourcesByFile","Map","batchedTraceSource","project","frame","file","decodeURIComponent","undefined","line1","line","column1","column","methodName","ignored","arguments","source","currentDirectoryFileUrl","pathToFileURL","process","cwd","href","sourceFrame","traceSource","originalFile","isIgnored","sourcePromise","get","getSourceForAsset","set","setTimeout","delete","ignorableFrame","parseFile","fileParam","devirtualizeReactServerURL","createStackFrames","body","frames","isServer","map","filter","f","createStackFrame","searchParams","parseInt","nativeTraceSource","sourceURL","sourceMapPayload","findSourceMap","payload","cause","Error","consumer","SourceMapConsumer","traced","originalPosition","originalPositionFor","sourceContent","sourceContentFor","destroy","applicableSourceMap","findApplicableSourceMapPayload","console","error","sourceIndex","sources","indexOf","ignoreList","originalStackFrame","replace","createOriginalStackFrame","projectPath","codeFrameOptions","normalizedStackFrameLocation","path","relative","fileURLToPath","originalCodeFrame","tracedFrame","getOriginalCodeFrame","colors","maxWidth","isSrcDir","req","res","next","pathname","URL","url","method","middlewareResponse","badRequest","Promise","resolve","reject","data","on","chunk","request","JSON","parse","result","isEdgeServer","isAppDirectory","DEVTOOLS_CODE_FRAME_MAX_WIDTH","ignoreListAnonymousStackFramesIfSandwiched","json","isAppRelativePath","openEditorResult","relativeFilePath","appPath","join","openFileInEditor","internalServerError","found","notFound","noContent","filename","nativeSourceMap","decodeURI","isAbsolute","sourceMapString","getSourceMap","jsonString","stackFrames","all","stackFrame","status","reason","value","inspect"],"mappings":";;;;;;;;;;;;;;;;IAyfsBA,sBAAsB;eAAtBA;;IA9JNC,oBAAoB;eAApBA;;IAyFAC,sBAAsB;eAAt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UAAU,CAACvC,KAAKqC;YAC5C;QACF,EAAE,OAAOvE,OAAO;YACd,OAAOwC,sCAAkB,CAACuB,mBAAmB,CAC3C7B,KACA,qBAKC,CALD,IAAIjC,MACF,CAAC,8BAA8B,EAAEkE,SAAS,2BAA2B,CAAC,EACtE;gBACEnE;YACF,IAJF,qBAAA;uBAAA;4BAAA;8BAAA;YAKA;QAEJ;QAEAwC,sCAAkB,CAAC0B,SAAS,CAAChC;IAC/B;AACF;AAEO,eAAe3F,uBAAuB,EAC3CU,OAAO,EACPoE,WAAW,EACXlC,MAAM,EACNC,QAAQ,EACRgE,YAAY,EACZC,cAAc,EACd/B,gBAAgB,EASjB;IACC,MAAMoD,cAAczF,kBAAkB;QACpCE;QACAC;QACAgE;QACAC;IACF;IAEA,OAAOX,QAAQiC,GAAG,CAChBD,YAAYrF,GAAG,CAAC,OAAOnC;QACrB,IAAI;YACF,MAAM0H,aAAa,MAAMxD,yBACvBnE,SACAoE,aACAnE,OACAoE;YAEF,IAAIsD,eAAe,MAAM;gBACvB,OAAO;oBACLC,QAAQ;oBACRC,QAAQ;gBACV;YACF;YACA,MAAM5D,qBAAqB0D,WAAW1D,kBAAkB;YACxD,OAAO;gBACL2D,QAAQ;gBACRE,OAAO;oBACL7D;oBACAS,mBACE,AAACT,CAAAA,sCAAAA,mBAAoBvD,OAAO,KAAI,OAC5B,OAEAiH,WAAWjD,iBAAiB;gBACpC;YACF;QACF,EAAE,OAAOd,OAAO;YACd,OAAO;gBACLgE,QAAQ;gBACRC,QAAQE,IAAAA,iBAAO,EAACnE,OAAO;oBAAEiB,QAAQ;gBAAM;YACzC;QACF;IACF;AAEJ","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/dev/middleware-turbopack.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport {\n DEVTOOLS_CODE_FRAME_MAX_WIDTH,\n getOriginalCodeFrame,\n ignoreListAnonymousStackFramesIfSandwiched,\n type IgnorableStackFrame,\n type OriginalStackFrameResponse,\n type OriginalStackFramesRequest,\n type OriginalStackFramesResponse,\n type StackFrame,\n} from '../../next-devtools/server/shared'\nimport { middlewareResponse } from '../../next-devtools/server/middleware-response'\nimport path from 'path'\nimport { openFileInEditor } from '../../next-devtools/server/launch-editor'\nimport {\n SourceMapConsumer,\n type NullableMappedPosition,\n} from 'next/dist/compiled/source-map08'\nimport type { Project, TurbopackStackFrame } from '../../build/swc/types'\nimport {\n type ModernSourceMapPayload,\n devirtualizeReactServerURL,\n findApplicableSourceMapPayload,\n} from '../lib/source-maps'\nimport { findSourceMap, type SourceMap } from 'node:module'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { inspect } from 'node:util'\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 modulePath.startsWith('node:')\n )\n}\n\nconst currentSourcesByFile: Map<string, Promise<string | null>> = new Map()\n/**\n * @returns 1-based lines and 1-based columns\n */\nasync function batchedTraceSource(\n project: Project,\n frame: TurbopackStackFrame\n): Promise<{ frame: IgnorableStackFrame; source: string | null } | undefined> {\n const file = frame.file\n ? // TODO(veil): Why are the frames sent encoded?\n decodeURIComponent(frame.file)\n : undefined\n\n if (!file) return\n\n // For node internals they cannot traced the actual source code with project.traceSource,\n // we need an early return to indicate it's ignored to avoid the unknown scheme error from `project.traceSource`.\n if (file.startsWith('node:')) {\n return {\n frame: {\n file,\n line1: frame.line ?? null,\n column1: frame.column ?? null,\n methodName: frame.methodName ?? '<unknown>',\n ignored: true,\n arguments: [],\n },\n source: null,\n }\n }\n\n const currentDirectoryFileUrl = pathToFileURL(process.cwd()).href\n\n const sourceFrame = await project.traceSource(frame, currentDirectoryFileUrl)\n if (!sourceFrame) {\n return {\n frame: {\n file,\n line1: frame.line ?? null,\n column1: frame.column ?? null,\n methodName: frame.methodName ?? '<unknown>',\n ignored: shouldIgnorePath(file),\n arguments: [],\n },\n source: null,\n }\n }\n\n let source = null\n const originalFile = sourceFrame.originalFile\n\n // Don't look up source for node_modules or internals. These can often be large bundled files.\n const ignored =\n // Check the sourcemap's ignoreList (e.g. from 3rd party packages)\n !!sourceFrame.isIgnored ||\n shouldIgnorePath(originalFile ?? sourceFrame.file)\n if (originalFile && !ignored) {\n let sourcePromise = currentSourcesByFile.get(originalFile)\n if (!sourcePromise) {\n sourcePromise = project.getSourceForAsset(originalFile)\n currentSourcesByFile.set(originalFile, sourcePromise)\n setTimeout(() => {\n // Cache file reads for 100ms, as frames will often reference the same\n // files and can be large.\n currentSourcesByFile.delete(originalFile!)\n }, 100)\n }\n source = await sourcePromise\n }\n\n const ignorableFrame: IgnorableStackFrame = {\n file: sourceFrame.file,\n line1: sourceFrame.line ?? null,\n column1: sourceFrame.column ?? null,\n methodName:\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n frame.methodName ?? '<unknown>',\n ignored,\n arguments: [],\n }\n\n return {\n frame: ignorableFrame,\n source,\n }\n}\n\nfunction parseFile(fileParam: string | null): string | undefined {\n if (!fileParam) {\n return undefined\n }\n\n const file = devirtualizeReactServerURL(fileParam)\n // React virtualizes filenames as `'file://' + path`, which is malformed\n // for paths that need percent-encoding (e.g. a space in the project path)\n // and then fails both Turbopack's `traceSource` and Node.js' source map\n // cache lookups. Re-encode through WHATWG URL parsing.\n // TODO(veil): Revisit if React's virtualization round-trips losslessly.\n if (file.startsWith('file://') && URL.canParse(file)) {\n return new URL(file).href\n }\n return file\n}\n\nfunction createStackFrames(\n body: OriginalStackFramesRequest\n): TurbopackStackFrame[] {\n const { frames, isServer } = body\n\n return frames\n .map((frame): TurbopackStackFrame | undefined => {\n const file = parseFile(frame.file)\n\n if (!file) {\n return undefined\n }\n\n return {\n file,\n methodName: frame.methodName ?? '<unknown>',\n line: frame.line1 ?? undefined,\n column: frame.column1 ?? undefined,\n isServer,\n }\n })\n .filter((f): f is TurbopackStackFrame => f !== undefined)\n}\n\nfunction createStackFrame(\n searchParams: URLSearchParams\n): TurbopackStackFrame | undefined {\n const file = parseFile(searchParams.get('file'))\n\n if (!file) {\n return undefined\n }\n\n return {\n file,\n methodName: searchParams.get('methodName') ?? '<unknown>',\n line: parseInt(searchParams.get('line1') ?? '0', 10) || undefined,\n column: parseInt(searchParams.get('column1') ?? '0', 10) || undefined,\n isServer: searchParams.get('isServer') === 'true',\n }\n}\n\n/**\n * @returns 1-based lines and 1-based columns\n */\nasync function nativeTraceSource(\n frame: TurbopackStackFrame\n): Promise<{ frame: IgnorableStackFrame; source: string | null } | undefined> {\n const sourceURL = frame.file\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMap(sourceURL)?.payload\n } catch (cause) {\n throw new Error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n }\n\n if (sourceMapPayload !== undefined) {\n let consumer: SourceMapConsumer\n try {\n consumer = await new SourceMapConsumer(sourceMapPayload)\n } catch (cause) {\n throw new Error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n }\n let traced: {\n originalPosition: NullableMappedPosition\n sourceContent: string | null\n } | null\n try {\n const originalPosition = consumer.originalPositionFor({\n line: frame.line ?? 1,\n // 0-based columns out requires 0-based columns in.\n column: (frame.column ?? 1) - 1,\n })\n\n if (originalPosition.source === null) {\n traced = null\n } else {\n const sourceContent: string | null =\n consumer.sourceContentFor(\n originalPosition.source,\n /* returnNullOnMissing */ true\n ) ?? null\n\n traced = { originalPosition, sourceContent }\n }\n } finally {\n consumer.destroy()\n }\n\n if (traced !== null) {\n const { originalPosition, sourceContent } = traced\n const applicableSourceMap = findApplicableSourceMapPayload(\n (frame.line ?? 1) - 1,\n (frame.column ?? 1) - 1,\n sourceMapPayload\n )\n\n // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.\n let ignored = false\n if (applicableSourceMap === undefined) {\n console.error(\n 'No applicable source map found in sections for frame',\n frame\n )\n } else {\n // TODO: O(n^2). Consider moving `ignoreList` into a Set\n const sourceIndex = applicableSourceMap.sources.indexOf(\n originalPosition.source!\n )\n ignored =\n applicableSourceMap.ignoreList?.includes(sourceIndex) ??\n // When sourcemap is not available, fallback to checking `frame.file`.\n // e.g. In pages router, nextjs server code is not bundled into the page.\n shouldIgnorePath(frame.file)\n }\n\n const originalStackFrame: IgnorableStackFrame = {\n methodName:\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n frame.methodName\n ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n ?.replace('__webpack_exports__.', '') || '<unknown>',\n file: originalPosition.source,\n line1: originalPosition.line,\n column1:\n originalPosition.column === null ? null : originalPosition.column + 1,\n // TODO: c&p from async createOriginalStackFrame but why not frame.arguments?\n arguments: [],\n ignored,\n }\n\n return {\n frame: originalStackFrame,\n source: sourceContent,\n }\n }\n }\n\n return undefined\n}\n\n/**\n * Code frame rendering options. The defaults match terminal consumers; only\n * the overlay HTTP path opts in to always-on colors and the wide max width.\n */\ntype CodeFrameOptions = {\n /** Defaults to `process.stdout.isTTY`. */\n colors?: boolean\n /** Defaults to the dev server's terminal width. */\n maxWidth?: number\n}\n\nasync function createOriginalStackFrame(\n project: Project,\n projectPath: string,\n frame: TurbopackStackFrame,\n codeFrameOptions?: CodeFrameOptions\n): Promise<OriginalStackFrameResponse | null> {\n const traced =\n (await nativeTraceSource(frame)) ??\n // TODO(veil): When would the bundler know more than native?\n // If it's faster, try the bundler first and fall back to native later.\n (await batchedTraceSource(project, frame))\n if (!traced) {\n return null\n }\n\n let normalizedStackFrameLocation = traced.frame.file\n if (\n normalizedStackFrameLocation !== null &&\n normalizedStackFrameLocation.startsWith('file://')\n ) {\n normalizedStackFrameLocation = path.relative(\n projectPath,\n fileURLToPath(normalizedStackFrameLocation)\n )\n }\n\n /** undefined = not yet computed */\n let originalCodeFrame: string | null | undefined\n\n const tracedFrame = traced.frame\n return {\n originalStackFrame: {\n arguments: tracedFrame.arguments,\n file: normalizedStackFrameLocation,\n line1: tracedFrame.line1,\n column1: tracedFrame.column1,\n ignored: tracedFrame.ignored,\n methodName: tracedFrame.methodName,\n },\n get originalCodeFrame() {\n if (originalCodeFrame === undefined) {\n originalCodeFrame = getOriginalCodeFrame(tracedFrame, traced.source, {\n colors: codeFrameOptions?.colors,\n maxWidth: codeFrameOptions?.maxWidth,\n })\n }\n return originalCodeFrame\n },\n }\n}\n\nexport function getOverlayMiddleware({\n project,\n projectPath,\n isSrcDir,\n}: {\n project: Project\n projectPath: string\n isSrcDir: boolean\n}) {\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(req.url!, 'http://n')\n\n if (pathname === '/__nextjs_original-stack-frames') {\n if (req.method !== 'POST') {\n return middlewareResponse.badRequest(res)\n }\n\n const body = await new Promise<string>((resolve, reject) => {\n let data = ''\n req.on('data', (chunk) => {\n data += chunk\n })\n req.on('end', () => resolve(data))\n req.on('error', reject)\n })\n\n const request = JSON.parse(body) as OriginalStackFramesRequest\n const result = await getOriginalStackFrames({\n project,\n projectPath,\n frames: request.frames,\n isServer: request.isServer,\n isEdgeServer: request.isEdgeServer,\n isAppDirectory: request.isAppDirectory,\n codeFrameOptions: {\n // Overlay parses ANSI in JS and renders in a scrollable\n // `<pre>`, so colors are always wanted and terminal width is\n // irrelevant.\n colors: true,\n maxWidth: DEVTOOLS_CODE_FRAME_MAX_WIDTH,\n },\n })\n\n ignoreListAnonymousStackFramesIfSandwiched(result)\n\n return middlewareResponse.json(res, result)\n } else if (pathname === '/__nextjs_launch-editor') {\n const isAppRelativePath = searchParams.get('isAppRelativePath') === '1'\n\n let openEditorResult\n if (isAppRelativePath) {\n const relativeFilePath = searchParams.get('file') || ''\n const appPath = path.join(\n isSrcDir ? 'src' : '',\n 'app',\n relativeFilePath\n )\n openEditorResult = await openFileInEditor(appPath, 1, 1, projectPath)\n } else {\n const frame = createStackFrame(searchParams)\n if (!frame) return middlewareResponse.badRequest(res)\n openEditorResult = await openFileInEditor(\n frame.file,\n frame.line ?? 1,\n frame.column ?? 1,\n projectPath\n )\n }\n\n if (openEditorResult.error) {\n return middlewareResponse.internalServerError(\n res,\n openEditorResult.error\n )\n }\n if (!openEditorResult.found) {\n return middlewareResponse.notFound(res)\n }\n return middlewareResponse.noContent(res)\n }\n\n return next()\n }\n}\n\nexport function getSourceMapMiddleware(project: Project) {\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise<void> {\n const { pathname, searchParams } = new URL(req.url!, 'http://n')\n\n if (pathname !== '/__nextjs_source-map') {\n return next()\n }\n\n let filename = searchParams.get('filename')\n\n if (!filename) {\n return middlewareResponse.badRequest(res)\n }\n\n let nativeSourceMap: SourceMap | undefined\n try {\n nativeSourceMap = findSourceMap(filename)\n } catch (cause) {\n return middlewareResponse.internalServerError(\n res,\n new Error(\n `${filename}: Invalid source map. Only conformant source maps can be used to find the original code.`,\n { cause }\n )\n )\n }\n\n if (nativeSourceMap !== undefined) {\n const sourceMapPayload = nativeSourceMap.payload\n return middlewareResponse.json(res, sourceMapPayload)\n }\n\n try {\n // Turbopack chunk filenames might be URL-encoded.\n filename = decodeURI(filename)\n } catch {\n return middlewareResponse.badRequest(res)\n }\n\n if (path.isAbsolute(filename)) {\n filename = pathToFileURL(filename).href\n }\n\n try {\n const sourceMapString = await project.getSourceMap(filename)\n\n if (sourceMapString) {\n return middlewareResponse.jsonString(res, sourceMapString)\n }\n } catch (cause) {\n return middlewareResponse.internalServerError(\n res,\n new Error(\n `Failed to get source map for '${filename}'. This is a bug in Next.js`,\n {\n cause,\n }\n )\n )\n }\n\n middlewareResponse.noContent(res)\n }\n}\n\nexport async function getOriginalStackFrames({\n project,\n projectPath,\n frames,\n isServer,\n isEdgeServer,\n isAppDirectory,\n codeFrameOptions,\n}: {\n project: Project\n projectPath: string\n frames: readonly StackFrame[]\n isServer: boolean\n isEdgeServer: boolean\n isAppDirectory: boolean\n codeFrameOptions?: CodeFrameOptions\n}): Promise<OriginalStackFramesResponse> {\n const stackFrames = createStackFrames({\n frames,\n isServer,\n isEdgeServer,\n isAppDirectory,\n })\n\n return Promise.all(\n stackFrames.map(async (frame) => {\n try {\n const stackFrame = await createOriginalStackFrame(\n project,\n projectPath,\n frame,\n codeFrameOptions\n )\n if (stackFrame === null) {\n return {\n status: 'rejected',\n reason: 'Failed to create original stack frame',\n }\n }\n const originalStackFrame = stackFrame.originalStackFrame\n return {\n status: 'fulfilled',\n value: {\n originalStackFrame,\n originalCodeFrame:\n (originalStackFrame?.ignored ?? true)\n ? null\n : // TODO: Don't get all codeframes of non-ignored frames eagerly.\n stackFrame.originalCodeFrame,\n },\n }\n } catch (error) {\n return {\n status: 'rejected',\n reason: inspect(error, { colors: false }),\n }\n }\n })\n )\n}\n"],"names":["getOriginalStackFrames","getOverlayMiddleware","getSourceMapMiddleware","shouldIgnorePath","modulePath","includes","startsWith","currentSourcesByFile","Map","batchedTraceSource","project","frame","file","decodeURIComponent","undefined","line1","line","column1","column","methodName","ignored","arguments","source","currentDirectoryFileUrl","pathToFileURL","process","cwd","href","sourceFrame","traceSource","originalFile","isIgnored","sourcePromise","get","getSourceForAsset","set","setTimeout","delete","ignorableFrame","parseFile","fileParam","devirtualizeReactServerURL","URL","canParse","createStackFrames","body","frames","isServer","map","filter","f","createStackFrame","searchParams","parseInt","nativeTraceSource","sourceURL","sourceMapPayload","findSourceMap","payload","cause","Error","consumer","SourceMapConsumer","traced","originalPosition","originalPositionFor","sourceContent","sourceContentFor","destroy","applicableSourceMap","findApplicableSourceMapPayload","console","error","sourceIndex","sources","indexOf","ignoreList","originalStackFrame","replace","createOriginalStackFrame","projectPath","codeFrameOptions","normalizedStackFrameLocation","path","relative","fileURLToPath","originalCodeFrame","tracedFrame","getOriginalCodeFrame","colors","maxWidth","isSrcDir","req","res","next","pathname","url","method","middlewareResponse","badRequest","Promise","resolve","reject","data","on","chunk","request","JSON","parse","result","isEdgeServer","isAppDirectory","DEVTOOLS_CODE_FRAME_MAX_WIDTH","ignoreListAnonymousStackFramesIfSandwiched","json","isAppRelativePath","openEditorResult","relativeFilePath","appPath","join","openFileInEditor","internalServerError","found","notFound","noContent","filename","nativeSourceMap","decodeURI","isAbsolute","sourceMapString","getSourceMap","jsonString","stackFrames","all","stackFrame","status","reason","value","inspect"],"mappings":";;;;;;;;;;;;;;;;IAkgBsBA,sBAAsB;eAAtBA;;IA9JNC,oBAAoB;eAApBA;;IAyFAC,sBAAsB;eAAtBA;;;wBAnbT;oCAC4B;6DAClB;8BACgB;6BAI1B;4BAMA;4BACuC;yBACD;0BACrB;;;;;;AAExB,SAASC,iBAAiBC,UAAkB;IAC1C,OACEA,WAAWC,QAAQ,CAAC,mBACpB,2EAA2E;IAC3ED,WAAWC,QAAQ,CAAC,gBACpBD,WAAWE,UAAU,CAAC;AAE1B;AAEA,MAAMC,uBAA4D,IAAIC;AACtE;;CAEC,GACD,eAAeC,mBACbC,OAAgB,EAChBC,KAA0B;IAE1B,MAAMC,OAAOD,MAAMC,IAAI,GAEnBC,mBAAmBF,MAAMC,IAAI,IAC7BE;IAEJ,IAAI,CAACF,MAAM;IAEX,yFAAyF;IACzF,iHAAiH;IACjH,IAAIA,KAAKN,UAAU,CAAC,UAAU;QAC5B,OAAO;YACLK,OAAO;gBACLC;gBACAG,OAAOJ,MAAMK,IAAI,IAAI;gBACrBC,SAASN,MAAMO,MAAM,IAAI;gBACzBC,YAAYR,MAAMQ,UAAU,IAAI;gBAChCC,SAAS;gBACTC,WAAW,EAAE;YACf;YACAC,QAAQ;QACV;IACF;IAEA,MAAMC,0BAA0BC,IAAAA,sBAAa,EAACC,QAAQC,GAAG,IAAIC,IAAI;IAEjE,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AAI;YACF,MAAM2H,aAAa,MAAMvD,yBACvBrE,SACAsE,aACArE,OACAsE;YAEF,IAAIqD,eAAe,MAAM;gBACvB,OAAO;oBACLC,QAAQ;oBACRC,QAAQ;gBACV;YACF;YACA,MAAM3D,qBAAqByD,WAAWzD,kBAAkB;YACxD,OAAO;gBACL0D,QAAQ;gBACRE,OAAO;oBACL5D;oBACAS,mBACE,AAACT,CAAAA,sCAAAA,mBAAoBzD,OAAO,KAAI,OAC5B,OAEAkH,WAAWhD,iBAAiB;gBACpC;YACF;QACF,EAAE,OAAOd,OAAO;YACd,OAAO;gBACL+D,QAAQ;gBACRC,QAAQE,IAAAA,iBAAO,EAAClE,OAAO;oBAAEiB,QAAQ;gBAAM;YACzC;QACF;IACF;AAEJ","ignoreList":[0]} |
@@ -16,2 +16,3 @@ "use strict"; | ||
| const _usecacheprobepool = require("./use-cache-probe-pool"); | ||
| const _devvalidationworkerpool = require("./dev-validation-worker-pool"); | ||
| const _path = require("path"); | ||
@@ -176,2 +177,22 @@ const _constants = require("../../lib/constants"); | ||
| }); | ||
| // Runs Cache Components dev validation on a worker thread, off the main | ||
| // thread, so validation renders don't block the event loop during rapid | ||
| // navigation. Gated by `experimental.devValidationWorker`. The worker is | ||
| // spawned lazily on the first navigation that validates, so this install is | ||
| // free when a project doesn't use Cache Components. | ||
| // | ||
| // Turbopack only, because the worker's thread has source maps just for the | ||
| // chunks it loaded itself, and resolves the rest by reading the `.map` | ||
| // Turbopack writes next to each chunk. Webpack keeps its dev source maps in | ||
| // the compiler, which the worker's thread cannot reach, so validation | ||
| // errors would be reported without a source location. Running validation on | ||
| // the main thread costs dev performance but keeps those frames intact. | ||
| if (process.env.TURBOPACK && this.nextConfig.experimental.devValidationWorker !== false) { | ||
| (0, _devvalidationworkerpool.installDevValidationWorker)({ | ||
| distDir: this.distDir, | ||
| buildId: this.buildId, | ||
| deploymentId: this.deploymentId, | ||
| nextConfig: this.nextConfig | ||
| }); | ||
| } | ||
| } | ||
@@ -178,0 +199,0 @@ getServerComponentsHmrCache() { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { DetachedPromise } from '../../lib/detached-promise'\nimport { isPostpone } from '../lib/router-utils/is-postpone'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = new DetachedPromise<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return JSON.stringify(value.staticPaths)?.length || 1\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value) {\n return JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n process.on('unhandledRejection', (reason) => {\n if (isPostpone(reason)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n this.logErrorWithOriginalStack(reason, 'unhandledRejection')\n })\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n pprConfig: this.nextConfig.experimental.ppr,\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["DevServer","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","React","createElement","Server","getStaticPathsWorker","worker","Worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getFormattedNodeOptionsWithoutInspect","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","DetachedPromise","conf","bundlerService","startServerSpan","trace","renderOpts","ErrorDebug","staticPathsCache","LRUCache","length","value","JSON","stringify","staticPaths","pagesDir","appDir","findPagesDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","defaultConfig","installUseCacheProbe","distDir","buildId","deploymentId","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","DevRouteMatcherManager","extensions","pageExtensions","extensionsExpression","RegExp","join","fileReader","BatchedFileReader","DefaultFileReader","pathnameFilter","test","push","DevPagesRouteMatcherProvider","localeNormalizer","DevPagesAPIRouteMatcherProvider","ignorePartFilter","part","startsWith","isTurbopack","TURBOPACK","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","getBuildId","prepareImpl","setGlobal","PHASE_DEVELOPMENT_SERVER","existingTelemetry","traceGlobals","get","telemetry","Telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","on","reason","isPostpone","logErrorWithOriginalStack","err","hasPage","normalizedPath","normalizePagePath","console","error","isMiddlewareFile","findPageFile","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","DecodeError","MiddlewareNotFoundError","getProperError","decorateServerError","COMPILER_NAMES","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","getRequestMeta","requestStart","hrtime","bigint","addRequestMeta","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","logRequests","devRequestTimingInternalsEnd","manualTraceChild","hrtimeToEpochNanoseconds","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","pathHasPrefix","removePathPrefix","fs","existsSync","pathJoin","publicDir","PUBLIC_DIR_MIDDLEWARE_CONFLICT","formatServerError","sent","__NEXT_PAGE","isError","internalErr","body","send","type","getPagesManifest","NodeManifestLoader","serverDistDir","PAGES_MANIFEST","getAppPathsManifest","enabledDirectories","app","APP_PATHS_MANIFEST","rewrites","generateInterceptionRoutesRewrites","Object","keys","appPathRoutes","map","route","buildCustomRoute","regex","output","Log","exit","getMiddleware","middleware","getMiddlewareRouteMatcher","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","getInstrumentationModule","message","runInstrumentationHookIfAvailable","ensureInstrumentationRegistered","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","pprConfig","ppr","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","withCoalescedInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","FallbackMode","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","PRERENDER_MANIFEST","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackModeToFallbackField","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","getRouteRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","HMR_MESSAGE_SENT_TO_BROWSER","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","WrappedBuildError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","loadDefaultErrorComponents","instrumentationOnRequestError","args","silenceLog"],"mappings":";;;;+BA6HA;;;eAAqBA;;;6BA7Gd;+DAQgB;2DACR;4BACQ;mCACc;sBACJ;2BACc;8BAClB;4BAOtB;oEACmC;mCACR;+BACJ;kCACG;yBACP;uBAMnB;wBACsB;8BACA;uBACyB;mCAClB;4CAI7B;wBAC8C;6DAChC;iEACmB;8BACe;wBACtB;mCACC;wCACK;8CACM;iDACG;gDACD;iDACC;oCACb;mCACD;mCACA;0BACT;wCACiB;iCACV;4BACL;oDACwB;kCAClB;6BACG;6BAGR;0BAC8B;gDAKnD;4BAEuB;kCAEc;mCACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE1CC,IAAAA,4CAAyB;AAEzB,wCAAwC;AACxC,IAAIC;AACJ,MAAMC,kBAA6C,CAACC;IAClD,IAAIF,8BAA8BG,WAAW;QAC3CH,4BAA4B,AAC1BI,QAAQ,+DACRC,qBAAqB;IACzB;IACA,OAAOC,OAAMC,aAAa,CAACP,2BAA2BE;AACxD;AAqBe,MAAMJ,kBAAkBU,mBAAM;IA4BnCC,u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AY,EAC2C;QACvD,MAAM,IAAI,CAACrC,cAAc,CAACkS,0BAA0B,CAAC7P;QACrD,OAAO,MAAM8P,IAAAA,sDAA0B,EAAC,IAAI,CAAC5Q,OAAO;IACtD;IAEA,MAAMsQ,oBAAoB1P,IAAY,EAAgB;QACpD,OAAO,MAAM,IAAI,CAACnC,cAAc,CAAC6R,mBAAmB,CAAC1P;IACvD;IAEA,MAAgBiQ,8BACd,GAAGC,IAAqD,EACxD;QACA,MAAM,KAAK,CAACD,iCAAiCC;QAE7C,MAAM,CAACxN,SAASyN,WAAW,GAAGD;QAC9B,IAAI,CAACC,YAAY;YACf,IAAI,CAAC1N,yBAAyB,CAACC,KAAK;QACtC;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { installDevValidationWorker } from './dev-validation-worker-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { DetachedPromise } from '../../lib/detached-promise'\nimport { isPostpone } from '../lib/router-utils/is-postpone'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = new DetachedPromise<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return JSON.stringify(value.staticPaths)?.length || 1\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value) {\n return JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n\n // Runs Cache Components dev validation on a worker thread, off the main\n // thread, so validation renders don't block the event loop during rapid\n // navigation. Gated by `experimental.devValidationWorker`. The worker is\n // spawned lazily on the first navigation that validates, so this install is\n // free when a project doesn't use Cache Components.\n //\n // Turbopack only, because the worker's thread has source maps just for the\n // chunks it loaded itself, and resolves the rest by reading the `.map`\n // Turbopack writes next to each chunk. Webpack keeps its dev source maps in\n // the compiler, which the worker's thread cannot reach, so validation\n // errors would be reported without a source location. Running validation on\n // the main thread costs dev performance but keeps those frames intact.\n if (\n process.env.TURBOPACK &&\n this.nextConfig.experimental.devValidationWorker !== false\n ) {\n installDevValidationWorker({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n process.on('unhandledRejection', (reason) => {\n if (isPostpone(reason)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n this.logErrorWithOriginalStack(reason, 'unhandledRejection')\n })\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n pprConfig: this.nextConfig.experimental.ppr,\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["DevServer","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","React","createElement","Server","getStaticPathsWorker","worker","Worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getFormattedNodeOptionsWithoutInspect","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","DetachedPromise","conf","bundlerService","startServerSpan","trace","renderOpts","ErrorDebug","staticPathsCache","LRUCache","length","value","JSON","stringify","staticPaths","pagesDir","appDir","findPagesDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","defaultConfig","installUseCacheProbe","distDir","buildId","deploymentId","TURBOPACK","devValidationWorker","installDevValidationWorker","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","DevRouteMatcherManager","extensions","pageExtensions","extensionsExpression","RegExp","join","fileReader","BatchedFileReader","DefaultFileReader","pathnameFilter","test","push","DevPagesRouteMatcherProvider","localeNormalizer","DevPagesAPIRouteMatcherProvider","ignorePartFilter","part","startsWith","isTurbopack","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","getBuildId","prepareImpl","setGlobal","PHASE_DEVELOPMENT_SERVER","existingTelemetry","traceGlobals","get","telemetry","Telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","on","reason","isPostpone","logErrorWithOriginalStack","err","hasPage","normalizedPath","normalizePagePath","console","error","isMiddlewareFile","findPageFile","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","DecodeError","MiddlewareNotFoundError","getProperError","decorateServerError","COMPILER_NAMES","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","getRequestMeta","requestStart","hrtime","bigint","addRequestMeta","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","logRequests","devRequestTimingInternalsEnd","manualTraceChild","hrtimeToEpochNanoseconds","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","pathHasPrefix","removePathPrefix","fs","existsSync","pathJoin","publicDir","PUBLIC_DIR_MIDDLEWARE_CONFLICT","formatServerError","sent","__NEXT_PAGE","isError","internalErr","body","send","type","getPagesManifest","NodeManifestLoader","serverDistDir","PAGES_MANIFEST","getAppPathsManifest","enabledDirectories","app","APP_PATHS_MANIFEST","rewrites","generateInterceptionRoutesRewrites","Object","keys","appPathRoutes","map","route","buildCustomRoute","regex","output","Log","exit","getMiddleware","middleware","getMiddlewareRouteMatcher","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","getInstrumentationModule","message","runInstrumentationHookIfAvailable","ensureInstrumentationRegistered","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","pprConfig","ppr","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","withCoalescedInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","FallbackMode","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","PRERENDER_MANIFEST","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackModeToFallbackField","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","getRouteRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","HMR_MESSAGE_SENT_TO_BROWSER","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","WrappedBuildError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","loadDefaultErrorComponents","instrumentationOnRequestError","args","silenceLog"],"mappings":";;;;+BA8HA;;;eAAqBA;;;6BA9Gd;+DAQgB;2DACR;4BACQ;mCACc;yCACM;sBACV;2BACc;8BAClB;4BAOtB;oEACmC;mCACR;+BACJ;kCACG;yBACP;uBAMnB;wBACsB;8BACA;uBACyB;mCAClB;4CAI7B;wBAC8C;6DAChC;iEACmB;8BACe;wBACtB;mCACC;wCACK;8CACM;iDACG;gDACD;iDACC;oCACb;mCACD;mCACA;0BACT;wCACiB;iCACV;4BACL;oDACwB;kCAClB;6BACG;6BAGR;0BAC8B;gDAKnD;4BAEuB;kCAEc;mCACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE1CC,IAAAA,4CAAyB;AAEzB,wCAAwC;AACxC,IAAIC;AACJ,MAAMC,kBAA6C,CAACC;IAClD,IAAIF,8BAA8BG,WAAW;QAC3CH,4BAA4B,AAC1BI,QAAQ,+DACRC,qBAAqB;IACzB;IACA,OAAOC,OAAMC,aAAa,CAACP,2BAA2BE;AACxD;AAqBe,MAAMJ,kBAAkBU,mBAAM;IA4BnCC,uBAEN;QACA,MAAMC,SAAS,IAAIC,kBAAM,CAACP,QAAQQ,OAAO,CAAC,0BAA0B;YAClEC,YAAY;YACZ,2GAA2G;YAC3G,uCAAuC;YACvCC,YAAY;YACZC,qBAAqB,IAAI,CAACC,UAAU,CAACC,YAAY,CAACC,aAAa;YAC/DC,aAAa;gBACXC,KAAK;oBACH,GAAGC,QAAQD,GAAG;oBACd,4GAA4G;oBAC5G,kGAAkG;oBAClG,mGAAmG;oBACnG,0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ACF;QACF;QAEA,IAAI,CAAC2P,gBAAgB,GAAG,KAAK,CAACvG;QAE9B,OAAO,MAAM,KAAK,CAAC8F,mBAAmB;YACpCpP;YACAsP;YACAhM;YACA+L;YACA7E;YACA+E;YACArP;QACF;IACF;IAEA,MAAgB4P,2BACd5P,GAAY,EAC2C;QACvD,MAAM,IAAI,CAACxC,cAAc,CAACoS,0BAA0B,CAAC5P;QACrD,OAAO,MAAM6P,IAAAA,sDAA0B,EAAC,IAAI,CAAC9Q,OAAO;IACtD;IAEA,MAAMwQ,oBAAoBzP,IAAY,EAAgB;QACpD,OAAO,MAAM,IAAI,CAACtC,cAAc,CAAC+R,mBAAmB,CAACzP;IACvD;IAEA,MAAgBgQ,8BACd,GAAGC,IAAqD,EACxD;QACA,MAAM,KAAK,CAACD,iCAAiCC;QAE7C,MAAM,CAACxN,SAASyN,WAAW,GAAGD;QAC9B,IAAI,CAACC,YAAY;YACf,IAAI,CAAC1N,yBAAyB,CAACC,KAAK;QACtC;IACF;AACF","ignoreList":[0]} |
@@ -82,3 +82,3 @@ "use strict"; | ||
| const versionSuffix = logBundler ? ` (${(0, _bundler.bundlerName)((0, _bundler.getBundlerFromEnv)())})` : ''; | ||
| _log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"16.3.0-canary.96"}`))}${versionSuffix}`); | ||
| _log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"16.3.0-canary.97"}`))}${versionSuffix}`); | ||
| if (appUrl) { | ||
@@ -85,0 +85,0 @@ _log.bootstrap(`- Local: ${appUrl}`); |
@@ -22,5 +22,8 @@ "use strict"; | ||
| if (pathname.startsWith('/')) { | ||
| const pathnameParts = pathname.split('/'); | ||
| for(let i = 1; i < pathnameParts.length + 1; i++){ | ||
| let curPathname = pathnameParts.slice(0, i).join('/'); | ||
| let end = pathname.indexOf('/', 1); | ||
| while(true){ | ||
| if (end === -1) { | ||
| end = pathname.length; | ||
| } | ||
| let curPathname = pathname.slice(0, end); | ||
| if (curPathname) { | ||
@@ -33,2 +36,6 @@ // all derived tags other than the page are layout tags | ||
| } | ||
| if (end === pathname.length) { | ||
| break; | ||
| } | ||
| end = pathname.indexOf('/', end + 1); | ||
| } | ||
@@ -35,0 +42,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/lib/implicit-tags.ts"],"sourcesContent":["import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport { getCacheHandlerEntries } from '../use-cache/handlers'\nimport { encodeCacheTag } from './encode-cache-tag'\nimport { createLazyResult, type LazyResult } from './lazy-result'\n\nexport interface ImplicitTags {\n /**\n * For legacy usage, the implicit tags are passed to the incremental cache\n * handler in `get` calls.\n */\n readonly tags: string[]\n\n /**\n * Modern cache handlers don't receive implicit tags. Instead, the implicit\n * tags' expirations are stored in the work unit store, and used to compare\n * with a cache entry's timestamp.\n *\n * Note: This map contains lazy results so that we can evaluate them when the\n * first cache entry is read. It allows us to skip fetching the expiration\n * values if no caches are read at all.\n */\n readonly expirationsByCacheKind: Map<string, LazyResult<number>>\n}\n\nconst getDerivedTags = (pathname: string): string[] => {\n const derivedTags: string[] = [`/layout`]\n\n // we automatically add the current path segments as tags\n // for revalidatePath handling\n if (pathname.startsWith('/')) {\n const pathnameParts = pathname.split('/')\n\n for (let i = 1; i < pathnameParts.length + 1; i++) {\n let curPathname = pathnameParts.slice(0, i).join('/')\n\n if (curPathname) {\n // all derived tags other than the page are layout tags\n if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {\n curPathname = `${curPathname}${\n !curPathname.endsWith('/') ? '/' : ''\n }layout`\n }\n derivedTags.push(curPathname)\n }\n }\n }\n return derivedTags\n}\n\n/**\n * Creates a map with lazy results that fetch the expiration value for the given\n * tags and respective cache kind when they're awaited for the first time.\n */\nfunction createTagsExpirationsByCacheKind(\n tags: string[]\n): Map<string, LazyResult<number>> {\n const expirationsByCacheKind = new Map<string, LazyResult<number>>()\n const cacheHandlers = getCacheHandlerEntries()\n\n if (cacheHandlers) {\n for (const [kind, cacheHandler] of cacheHandlers) {\n if ('getExpiration' in cacheHandler) {\n expirationsByCacheKind.set(\n kind,\n createLazyResult(async () => cacheHandler.getExpiration(tags))\n )\n }\n }\n }\n\n return expirationsByCacheKind\n}\n\nexport async function getImplicitTags(\n page: string,\n pathname: string,\n fallbackRouteParams: null | OpaqueFallbackRouteParams\n): Promise<ImplicitTags> {\n const tags = new Set<string>()\n\n // Add the derived tags from the page. Encode each tag so a non-ASCII\n // pathname doesn't trip header validation when written to\n // `x-next-cache-tags`. Idempotent on already-ASCII input.\n const derivedTags = getDerivedTags(page)\n for (let tag of derivedTags) {\n tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`)\n tags.add(tag)\n }\n\n // Add the tags from the pathname. If the route has unknown params, we don't\n // want to add the pathname as a tag, as it will be invalid.\n if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {\n const tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`)\n tags.add(tag)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n const tagsArray = Array.from(tags)\n return {\n tags: tagsArray,\n expirationsByCacheKind: createTagsExpirationsByCacheKind(tagsArray),\n }\n}\n"],"names":["getImplicitTags","getDerivedTags","pathname","derivedTags","startsWith","pathnameParts","split","i","length","curPathname","slice","join","endsWith","push","createTagsExpirationsByCacheKind","tags","expirationsByCacheKind","Map","cacheHandlers","getCacheHandlerEntries","kind","cacheHandler","set","createLazyResult","getExpiration","page","fallbackRouteParams","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AOzB,YAAa;QAC3ByB,MAAMC,IAAAA,8BAAc,EAAC,GAAGC,qCAA0B,GAAGF,KAAK;QAC1Db,KAAKgB,GAAG,CAACH;IACX;IAEA,4EAA4E;IAC5E,4DAA4D;IAC5D,IAAI1B,YAAa,CAAA,CAACwB,uBAAuBA,oBAAoBM,IAAI,KAAK,CAAA,GAAI;QACxE,MAAMJ,MAAMC,IAAAA,8BAAc,EAAC,GAAGC,qCAA0B,GAAG5B,UAAU;QACrEa,KAAKgB,GAAG,CAACH;IACX;IAEA,IAAIb,KAAKkB,GAAG,CAAC,GAAGH,qCAA0B,CAAC,CAAC,CAAC,GAAG;QAC9Cf,KAAKgB,GAAG,CAAC,GAAGD,qCAA0B,CAAC,MAAM,CAAC;IAChD;IAEA,IAAIf,KAAKkB,GAAG,CAAC,GAAGH,qCAA0B,CAAC,MAAM,CAAC,GAAG;QACnDf,KAAKgB,GAAG,CAAC,GAAGD,qCAA0B,CAAC,CAAC,CAAC;IAC3C;IAEA,MAAMI,YAAYC,MAAMC,IAAI,CAACrB;IAC7B,OAAO;QACLA,MAAMmB;QACNlB,wBAAwBF,iCAAiCoB;IAC3D;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/lib/implicit-tags.ts"],"sourcesContent":["import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport { getCacheHandlerEntries } from '../use-cache/handlers'\nimport { encodeCacheTag } from './encode-cache-tag'\nimport { createLazyResult, type LazyResult } from './lazy-result'\n\nexport interface ImplicitTags {\n /**\n * For legacy usage, the implicit tags are passed to the incremental cache\n * handler in `get` calls.\n */\n readonly tags: string[]\n\n /**\n * Modern cache handlers don't receive implicit tags. Instead, the implicit\n * tags' expirations are stored in the work unit store, and used to compare\n * with a cache entry's timestamp.\n *\n * Note: This map contains lazy results so that we can evaluate them when the\n * first cache entry is read. It allows us to skip fetching the expiration\n * values if no caches are read at all.\n */\n readonly expirationsByCacheKind: Map<string, LazyResult<number>>\n}\n\nconst getDerivedTags = (pathname: string): string[] => {\n const derivedTags: string[] = [`/layout`]\n\n // we automatically add the current path segments as tags\n // for revalidatePath handling\n if (pathname.startsWith('/')) {\n let end = pathname.indexOf('/', 1)\n\n while (true) {\n if (end === -1) {\n end = pathname.length\n }\n\n let curPathname = pathname.slice(0, end)\n if (curPathname) {\n // all derived tags other than the page are layout tags\n if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {\n curPathname = `${curPathname}${\n !curPathname.endsWith('/') ? '/' : ''\n }layout`\n }\n derivedTags.push(curPathname)\n }\n\n if (end === pathname.length) {\n break\n }\n end = pathname.indexOf('/', end + 1)\n }\n }\n return derivedTags\n}\n\n/**\n * Creates a map with lazy results that fetch the expiration value for the given\n * tags and respective cache kind when they're awaited for the first time.\n */\nfunction createTagsExpirationsByCacheKind(\n tags: string[]\n): Map<string, LazyResult<number>> {\n const expirationsByCacheKind = new Map<string, LazyResult<number>>()\n const cacheHandlers = getCacheHandlerEntries()\n\n if (cacheHandlers) {\n for (const [kind, cacheHandler] of cacheHandlers) {\n if ('getExpiration' in cacheHandler) {\n expirationsByCacheKind.set(\n kind,\n createLazyResult(async () => cacheHandler.getExpiration(tags))\n )\n }\n }\n }\n\n return expirationsByCacheKind\n}\n\nexport async function getImplicitTags(\n page: string,\n pathname: string,\n fallbackRouteParams: null | OpaqueFallbackRouteParams\n): Promise<ImplicitTags> {\n const tags = new Set<string>()\n\n // Add the derived tags from the page. Encode each tag so a non-ASCII\n // pathname doesn't trip header validation when written to\n // `x-next-cache-tags`. Idempotent on already-ASCII input.\n const derivedTags = getDerivedTags(page)\n for (let tag of derivedTags) {\n tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`)\n tags.add(tag)\n }\n\n // Add the tags from the pathname. If the route has unknown params, we don't\n // want to add the pathname as a tag, as it will be invalid.\n if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {\n const tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`)\n tags.add(tag)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n const tagsArray = Array.from(tags)\n return {\n tags: tagsArray,\n expirationsByCacheKind: createTagsExpirationsByCacheKind(tagsArray),\n }\n}\n"],"names":["getImplicitTags","getDerivedTags","pathname","derivedTags","startsWith","end","indexOf","length","curPathname","slice","endsWith","push","createTagsExpirationsByCacheKind","tags","expirationsByCacheKind","Map","cacheHandlers","getCacheHandlerEntries","kind","cacheHandler","set","createLazyResult","getExpiration","page","fallbackRouteParams","Set","tag","encodeCacheTag","NEXT_CACHE_IMPLICIT_TAG_ID","add","size","has","tagsArray","Array","from"],"mappings":";;;;+BAkFsBA;;;eAAAA;;;2BAlFqB;0BAEJ;gCACR;4BACmB;AAqBlD,MAAMC,iBAAiB,CAACC;IACtB,MAAMC,cAAwB;QAAC,CAAC,OAAO,CAAC;KAAC;IAEzC,yDAAyD;IACzD,8BAA8B;IAC9B,IAAID,SAASE,UAAU,CAAC,MAAM;QAC5B,IAAIC,MAAMH,SAASI,OAAO,CAAC,KAAK;QAEhC,MAAO,KAAM;YACX,IAAID,QAAQ,CAAC,GAAG;gBACdA,MAAMH,SAASK,MAAM;YACvB;YAEA,IAAIC,cAAcN,SAASO,KAAK,CAAC,GAAGJ;YACpC,IAAIG,aAAa;gBACf,uDAAuD;gBACvD,IAAI,CAACA,YAAYE,QAAQ,CAAC,YAAY,CAACF,YAAYE,QAAQ,CAAC,WAAW;oBACrEF,cAAc,GAAGA,cACf,CAACA,YAAYE,QAAQ,CAAC,OAAO,MAAM,GACpC,MAAM,CAAC;gBACV;gBACAP,YAAYQ,IAAI,CAACH;YAC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AAC;IAC3C;IAEA,MAAMI,YAAYC,MAAMC,IAAI,CAACrB;IAC7B,OAAO;QACLA,MAAMmB;QACNlB,wBAAwBF,iCAAiCoB;IAC3D;AACF","ignoreList":[0]} |
@@ -31,2 +31,3 @@ // this must come first as it includes require hooks | ||
| const _compression = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/compression")); | ||
| const _releasecompressionstream = require("./release-compression-stream"); | ||
| const _nextrequest = require("../web/spec-extension/adapters/next-request"); | ||
@@ -258,2 +259,8 @@ const _ispostpone = require("./router-utils/is-postpone"); | ||
| compress(req, res, ()=>{}); | ||
| // On client disconnect the middleware never ends its zlib stream, which | ||
| // then leaks past GC. See `releaseCompressionStream`. | ||
| res.once('close', ()=>{ | ||
| if (res.writableFinished) return; | ||
| (0, _releasecompressionstream.releaseCompressionStream)(res); | ||
| }); | ||
| } | ||
@@ -260,0 +267,0 @@ req.on('error', (_err)=>{ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/lib/router-server.ts"],"sourcesContent":["// this must come first as it includes require hooks\nimport type { WorkerRequestHandler, WorkerUpgradeHandler } from './types'\nimport type { DevBundler, ServerFields } from './router-utils/setup-dev-bundler'\nimport type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta'\n\n// This is required before other imports to ensure the require hook is setup.\nimport '../node-environment'\nimport '../require-hook'\n\nimport url from 'url'\nimport path from 'path'\nimport loadConfig, { type ConfiguredExperimentalFeature } from '../config'\nimport { finalizeBundlerFromConfig, getBundlerFromEnv } from '../../lib/bundler'\nimport { serveStatic } from '../serve-static'\nimport setupDebug from 'next/dist/compiled/debug'\nimport * as Log from '../../build/output/log'\nimport { DecodeError } from '../../shared/lib/utils'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport { setupFsCheck } from './router-utils/filesystem'\nimport { proxyRequest } from './router-utils/proxy-request'\nimport { isAbortError, pipeToNodeResponse } from '../pipe-readable'\nimport { getResolveRoutes } from './router-utils/resolve-routes'\nimport { addRequestMeta, getRequestMeta } from '../request-meta'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport setupCompression from 'next/dist/compiled/compression'\nimport { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'\nimport { isPostpone } from './router-utils/is-postpone'\nimport { isNonHtmlSecFetchDest } from './is-non-html-sec-fetch-dest'\nimport { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url'\n\nimport {\n PHASE_PRODUCTION_SERVER,\n PHASE_DEVELOPMENT_SERVER,\n REQUEST_INSIGHTS_DEV_ENDPOINT,\n UNDERSCORE_NOT_FOUND_ROUTE,\n} from '../../shared/lib/constants'\nimport { RedirectStatusCode } from '../../client/components/redirect-status-code'\nimport { DevBundlerService } from './dev-bundler-service'\nimport { type Span, trace } from '../../trace'\nimport { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'\nimport { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { MockedResponse } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type AppIsrManifestMessage,\n} from '../dev/hot-reloader-types'\nimport { normalizedAssetPrefix } from '../../shared/lib/normalized-asset-prefix'\nimport { NEXT_PATCH_SYMBOL } from './patch-fetch'\nimport type { ServerInitResult } from './render-server'\nimport { filterInternalHeaders } from './server-ipc/utils'\nimport { blockCrossSiteDEV } from './router-utils/block-cross-site-dev'\nimport { traceGlobals } from '../../trace/shared'\nimport { NoFallbackError } from '../../shared/lib/no-fallback-error.external'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n} from './router-utils/router-server-context'\nimport {\n handleChromeDevtoolsWorkspaceRequest,\n isChromeDevtoolsWorkspaceUrl,\n} from './chrome-devtools-workspace'\nimport { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'\nimport {\n getRequestInsightsSnapshot,\n isRequestInsightsEnabled,\n} from './trace/request-insights'\n\nconst debug = setupDebug('next:router-server:main')\nconst isNextFont = (pathname: string | null) =>\n pathname && /\\/media\\/[^/]+\\.(woff|woff2|eot|ttf|otf)$/.test(pathname)\n\nexport type RenderServer = Pick<\n typeof import('./render-server'),\n | 'initialize'\n | 'clearModuleContext'\n | 'propagateServerField'\n | 'getServerField'\n>\n\nexport interface LazyRenderServerInstance {\n instance?: RenderServer\n}\n\nconst requestHandlers: Record<string, WorkerRequestHandler> = {}\n\nexport async function initialize(opts: {\n dir: string\n port: number\n dev: boolean\n onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined\n server?: import('http').Server\n minimalMode?: boolean\n hostname?: string\n keepAliveTimeout?: number\n customServer?: boolean\n experimentalHttpsServer?: boolean\n serverFastRefresh?: boolean\n startServerSpan?: Span\n quiet?: boolean\n}): Promise<ServerInitResult> {\n if (!process.env.NODE_ENV) {\n // @ts-ignore not readonly\n process.env.NODE_ENV = opts.dev ? 'development' : 'production'\n }\n\n // Capture the bundler before loading the config\n const bundlerBeforeConfig = opts.dev ? getBundlerFromEnv() : undefined\n\n let experimentalFeatures: ConfiguredExperimentalFeature[] = []\n const config = await loadConfig(\n opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,\n opts.dir,\n {\n silent: false,\n reportExperimentalFeatures(features) {\n experimentalFeatures = features.toSorted(({ key: a }, { key: b }) =>\n a.localeCompare(b)\n )\n },\n }\n )\n\n if (bundlerBeforeConfig !== undefined) {\n finalizeBundlerFromConfig(bundlerBeforeConfig)\n }\n\n let compress: ReturnType<typeof setupCompression> | undefined\n\n if (config?.compress !== false) {\n compress = setupCompression()\n }\n\n const fsChecker = await setupFsCheck({\n dev: opts.dev,\n dir: opts.dir,\n config,\n minimalMode: opts.minimalMode,\n })\n\n const renderServer: LazyRenderServerInstance = {}\n\n let development:\n | {\n bundler: DevBundler\n service: DevBundlerService\n config: NextConfigComplete\n }\n | undefined = undefined\n\n let originalFetch = globalThis.fetch\n\n if (opts.dev) {\n const { Telemetry } =\n require('../../telemetry/storage') as typeof import('../../telemetry/storage')\n\n const telemetry = new Telemetry({\n distDir: path.join(opts.dir, config.distDir),\n })\n traceGlobals.set('telemetry', telemetry)\n\n const { pagesDir, appDir } = findPagesDir(opts.dir)\n\n const { setupDevBundler } =\n require('./router-utils/setup-dev-bundler') as typeof import('./router-utils/setup-dev-bundler')\n\n const resetFetch = () => {\n globalThis.fetch = originalFetch\n ;(globalThis as Record<symbol, unknown>)[NEXT_PATCH_SYMBOL] = false\n }\n\n const setupDevBundlerSpan = opts.startServerSpan\n ? opts.startServerSpan.traceChild('setup-dev-bundler')\n : trace('setup-dev-bundler')\n\n // In development, it's always the complete config.\n let developmentConfig = config as NextConfigComplete\n\n // Resolve the effective serverFastRefresh value.\n // Both default to enabled (true). CLI takes precedence over config.\n const cliServerFastRefresh = opts.serverFastRefresh\n const configServerFastRefresh =\n developmentConfig.experimental?.turbopackServerFastRefresh\n let effectiveServerFastRefresh: boolean | undefined\n if (\n cliServerFastRefresh !== undefined &&\n configServerFastRefresh !== undefined &&\n cliServerFastRefresh !== configServerFastRefresh\n ) {\n Log.warn(\n `The CLI flag \"${cliServerFastRefresh === false ? '--no-server-fast-refresh' : '--server-fast-refresh'}\" conflicts with \"experimental.turbopackServerFastRefresh: ${configServerFastRefresh}\" in your Next.js config. The CLI flag will take precedence.`\n )\n effectiveServerFastRefresh = cliServerFastRefresh\n } else {\n // Default to true when neither CLI nor config specifies a value.\n effectiveServerFastRefresh =\n cliServerFastRefresh ?? configServerFastRefresh ?? true\n }\n\n let developmentBundler = await setupDevBundlerSpan.traceAsyncFn(() =>\n setupDevBundler({\n // Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks.\n renderServer,\n appDir,\n pagesDir,\n telemetry,\n fsChecker,\n dir: opts.dir,\n nextConfig: developmentConfig,\n isCustomServer: opts.customServer,\n turbo: !!process.env.TURBOPACK,\n port: opts.port,\n onDevServerCleanup: opts.onDevServerCleanup,\n resetFetch,\n serverFastRefresh: effectiveServerFastRefresh,\n })\n )\n\n let devBundlerService = new DevBundlerService(\n developmentBundler,\n // The request handler is assigned below, this allows us to create a lazy\n // reference to it.\n (req, res) => {\n return requestHandlers[opts.dir](req, res)\n },\n Boolean(developmentConfig.experimental.requestInsights)\n )\n\n development = {\n bundler: developmentBundler,\n service: devBundlerService,\n config: developmentConfig,\n }\n }\n\n renderServer.instance =\n require('./render-server') as typeof import('./render-server')\n\n const requestHandlerImpl: WorkerRequestHandler = async (req, res) => {\n addRequestMeta(req, 'relativeProjectDir', relativeProjectDir)\n\n // internal headers should not be honored by the request handler\n if (!process.env.NEXT_PRIVATE_TEST_HEADERS) {\n filterInternalHeaders(req.headers)\n }\n\n if (opts.dev && req.url) {\n if (config.experimental.requestInsights) {\n process.env.__NEXT_REQUEST_INSIGHTS = 'true'\n }\n\n const urlParts = req.url.split('?', 1)\n const pathname = removePathPrefix(urlParts[0] || '', config.basePath)\n\n if (pathname === REQUEST_INSIGHTS_DEV_ENDPOINT) {\n if (\n development &&\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n if (\n !config.experimental.requestInsights &&\n !isRequestInsightsEnabled()\n ) {\n res.statusCode = 404\n res.end(\n JSON.stringify({\n error:\n 'Request Insights is not enabled. Set experimental.requestInsights = true and restart next dev.',\n })\n )\n return\n }\n\n res.statusCode = 200\n res.end(JSON.stringify(getRequestInsightsSnapshot()))\n return\n }\n }\n\n if (\n !opts.minimalMode &&\n config.i18n &&\n config.i18n.localeDetection !== false\n ) {\n const urlParts = (req.url || '').split('?', 1)\n let urlNoQuery = urlParts[0] || ''\n\n if (config.basePath) {\n urlNoQuery = removePathPrefix(urlNoQuery, config.basePath)\n }\n\n const pathnameInfo = getNextPathnameInfo(urlNoQuery, {\n nextConfig: config,\n })\n\n const domainLocale = detectDomainLocale(\n config.i18n.domains,\n getHostname({ hostname: urlNoQuery }, req.headers)\n )\n\n const defaultLocale =\n domainLocale?.defaultLocale || config.i18n.defaultLocale\n\n const { getLocaleRedirect } =\n require('../../shared/lib/i18n/get-locale-redirect') as typeof import('../../shared/lib/i18n/get-locale-redirect')\n\n const parsedUrl = parseUrlUtil((req.url || '')?.replace(/^\\/+/, '/'))\n\n const redirect = getLocaleRedirect({\n defaultLocale,\n domainLocale,\n headers: req.headers,\n nextConfig: config,\n pathLocale: pathnameInfo.locale,\n urlParsed: {\n ...parsedUrl,\n pathname: pathnameInfo.locale\n ? `/${pathnameInfo.locale}${urlNoQuery}`\n : urlNoQuery,\n },\n })\n\n if (redirect) {\n res.setHeader('Location', redirect)\n res.statusCode = RedirectStatusCode.TemporaryRedirect\n res.end(redirect)\n return\n }\n }\n\n if (compress) {\n // @ts-expect-error not express req/res\n compress(req, res, () => {})\n }\n req.on('error', (_err) => {\n // TODO: log socket errors?\n })\n res.on('error', (_err) => {\n // TODO: log socket errors?\n })\n\n const invokedOutputs = new Set<string>()\n\n async function invokeRender(\n parsedUrl: NextUrlWithParsedQuery,\n invokePath: string,\n handleIndex: number,\n additionalRequestMeta?: RequestMeta\n ) {\n // invokeRender expects /api routes to not be locale prefixed\n // so normalize here before continuing\n if (\n config.i18n &&\n removePathPrefix(invokePath, config.basePath).startsWith(\n `/${getRequestMeta(req, 'locale')}/api`\n )\n ) {\n invokePath = fsChecker.handleLocale(\n removePathPrefix(invokePath, config.basePath)\n ).pathname\n }\n\n if (\n req.headers['x-nextjs-data'] &&\n fsChecker.getMiddlewareMatchers()?.length &&\n removePathPrefix(invokePath, config.basePath) === '/404'\n ) {\n res.setHeader('x-nextjs-matched-path', parsedUrl.pathname || '')\n res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end('{}')\n return null\n }\n\n if (!handlers) {\n throw new Error('Failed to initialize render server')\n }\n\n addRequestMeta(req, 'invokePath', invokePath)\n addRequestMeta(req, 'invokeQuery', parsedUrl.query)\n addRequestMeta(req, 'middlewareInvoke', false)\n\n for (const key in additionalRequestMeta || {}) {\n addRequestMeta(\n req,\n key as keyof RequestMeta,\n additionalRequestMeta![key as keyof RequestMeta]\n )\n }\n\n debug('invokeRender', req.url, req.headers)\n\n try {\n const initResult =\n await renderServer?.instance?.initialize(renderServerOpts)\n try {\n await initResult?.requestHandler(req, res)\n } catch (err) {\n if (err instanceof NoFallbackError) {\n await handleRequest(handleIndex + 1)\n return\n }\n throw err\n }\n return\n } catch (e) {\n // If the client aborts before we can receive a response object (when\n // the headers are flushed), then we can early exit without further\n // processing.\n if (isAbortError(e)) {\n return\n }\n throw e\n }\n }\n\n const handleRequest = async (handleIndex: number) => {\n if (handleIndex > 5) {\n throw new Error(`Attempted to handle request too many times ${req.url}`)\n }\n\n // handle hot-reloader first\n if (development) {\n if (\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n const origUrl = req.url || '/'\n\n // both the basePath and assetPrefix need to be stripped from the URL\n // so that the development bundler can find the correct file\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n const parsedUrl = parseUrlUtil(req.url || '/')\n\n const hotReloaderResult = await development.bundler.hotReloader.run(\n req,\n res,\n parsedUrl\n )\n\n if (hotReloaderResult.finished) {\n return hotReloaderResult\n }\n\n req.url = origUrl\n }\n\n const {\n finished,\n parsedUrl,\n statusCode,\n resHeaders,\n bodyStream,\n matchedOutput,\n } = await resolveRoutes({\n req,\n res,\n isUpgradeReq: false,\n signal: signalFromNodeResponse(res),\n invokedOutputs,\n })\n\n if (res.closed || res.finished) {\n return\n }\n\n if (development && matchedOutput?.type === 'devVirtualFsItem') {\n const origUrl = req.url || '/'\n\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n const result = await development.bundler.requestHandler(req, res)\n\n if (result.finished) {\n return\n }\n // TODO: throw invariant if we resolved to this but it wasn't handled?\n req.url = origUrl\n }\n\n debug('requestHandler!', req.url, {\n matchedOutput,\n statusCode,\n resHeaders,\n bodyStream: !!bodyStream,\n parsedUrl: {\n pathname: parsedUrl.pathname,\n query: parsedUrl.query,\n },\n finished,\n })\n\n // apply any response headers from routing\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n\n // handle redirect\n if (!bodyStream && statusCode && statusCode > 300 && statusCode < 400) {\n const destination = url.format(parsedUrl)\n res.statusCode = statusCode\n res.setHeader('location', destination)\n\n if (statusCode === RedirectStatusCode.PermanentRedirect) {\n res.setHeader('Refresh', `0;url=${destination}`)\n }\n return res.end(destination)\n }\n\n // handle middleware body response\n if (bodyStream) {\n res.statusCode = statusCode || 200\n return await pipeToNodeResponse(bodyStream, res)\n }\n\n if (finished && parsedUrl.protocol) {\n return await proxyRequest(\n req,\n res,\n parsedUrl,\n undefined,\n getRequestMeta(req, 'clonableBody')?.cloneBodyStream(),\n config.experimental.proxyTimeout\n )\n }\n\n if (matchedOutput?.fsPath && matchedOutput.itemPath) {\n if (\n opts.dev &&\n (fsChecker.appFiles.has(matchedOutput.itemPath) ||\n fsChecker.pageFiles.has(matchedOutput.itemPath))\n ) {\n res.statusCode = 500\n const message = `A conflicting public file and page file was found for path ${matchedOutput.itemPath} https://nextjs.org/docs/messages/conflicting-public-file-page`\n await invokeRender(parsedUrl, '/_error', handleIndex, {\n invokeStatus: 500,\n invokeError: new Error(message),\n })\n Log.error(message)\n return\n }\n\n if (\n !res.getHeader('cache-control') &&\n matchedOutput.type === 'nextStaticFolder'\n ) {\n if (matchedOutput.itemPath.startsWith('/service-worker/')) {\n res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate')\n res.setHeader('Service-Worker-Allowed', config.basePath || '/')\n } else if (opts.dev && !isNextFont(parsedUrl.pathname)) {\n res.setHeader('Cache-Control', 'no-cache, must-revalidate')\n } else {\n res.setHeader(\n 'Cache-Control',\n 'public, max-age=31536000, immutable'\n )\n }\n }\n if (!(req.method === 'GET' || req.method === 'HEAD')) {\n res.setHeader('Allow', ['GET', 'HEAD'])\n res.statusCode = 405\n return await invokeRender(parseUrlUtil('/405'), '/405', handleIndex, {\n invokeStatus: 405,\n })\n }\n\n try {\n return await serveStatic(req, res, matchedOutput.itemPath, {\n root: matchedOutput.itemsRoot,\n // Ensures that etags are not generated for static files when disabled.\n etag: config.generateEtags,\n })\n } catch (err: any) {\n /**\n * Hardcoded every possible error status code that could be thrown by \"serveStatic\" method\n * This is done by searching \"this.error\" inside \"send\" module's source code:\n * https://github.com/pillarjs/send/blob/master/index.js\n * https://github.com/pillarjs/send/blob/develop/index.js\n */\n const POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC = new Set([\n // send module will throw 500 when header is already sent or fs.stat error happens\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L392\n // Note: we will use Next.js built-in 500 page to handle 500 errors\n // 500,\n\n // send module will throw 404 when file is missing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L421\n // Note: we will use Next.js built-in 404 page to handle 404 errors\n // 404,\n\n // send module will throw 403 when redirecting to a directory without enabling directory listing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L484\n // Note: Next.js throws a different error (without status code) for directory listing\n // 403,\n\n // send module will throw 400 when fails to normalize the path\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L520\n 400,\n\n // send module will throw 412 with conditional GET request\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L632\n 412,\n\n // send module will throw 416 when range is not satisfiable\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L669\n 416,\n ])\n\n let validErrorStatus = POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC.has(\n err.statusCode\n )\n\n // normalize non-allowed status codes\n if (!validErrorStatus) {\n ;(err as any).statusCode = 400\n }\n\n if (typeof err.statusCode === 'number') {\n const invokePath = `/${err.statusCode}`\n const invokeStatus = err.statusCode\n res.statusCode = err.statusCode\n return await invokeRender(\n parseUrlUtil(invokePath),\n invokePath,\n handleIndex,\n {\n invokeStatus,\n }\n )\n }\n throw err\n }\n }\n\n if (matchedOutput) {\n invokedOutputs.add(matchedOutput.itemPath)\n\n return await invokeRender(\n parsedUrl,\n parsedUrl.pathname || '/',\n handleIndex,\n {\n invokeOutput: matchedOutput.itemPath,\n }\n )\n }\n\n // We want the original pathname without any basePath or proxy rewrites.\n if (development && isChromeDevtoolsWorkspaceUrl(req.url)) {\n await handleChromeDevtoolsWorkspaceRequest(res, opts, config)\n return\n }\n\n // 404 case\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n\n let realRequestPathname = parsedUrl.pathname ?? ''\n if (realRequestPathname) {\n if (config.basePath) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.basePath\n )\n }\n if (config.assetPrefix) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.assetPrefix\n )\n }\n if (config.i18n) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n '/' + (getRequestMeta(req, 'locale') ?? '')\n )\n }\n }\n // For not found static assets, return plain text 404 instead of\n // full HTML 404 pages to save bandwidth.\n if (realRequestPathname.startsWith('/_next/static/')) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // For subresource requests (e.g. images or fonts), return plain text\n // 404 instead of rendering the not-found route.\n if (\n (req.method === 'GET' || req.method === 'HEAD') &&\n isNonHtmlSecFetchDest(req.headers['sec-fetch-dest'])\n ) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // Short-circuit favicon.ico serving so that the 404 page doesn't get built as favicon is requested by the browser when loading any route.\n if (opts.dev && !matchedOutput && parsedUrl.pathname === '/favicon.ico') {\n res.statusCode = 404\n res.end('')\n return null\n }\n\n const appNotFound = opts.dev\n ? development?.bundler?.serverFields.hasAppNotFound\n : await fsChecker.getItem(UNDERSCORE_NOT_FOUND_ROUTE)\n\n res.statusCode = 404\n\n if (appNotFound) {\n return await invokeRender(\n parsedUrl,\n UNDERSCORE_NOT_FOUND_ROUTE,\n handleIndex,\n {\n invokeStatus: 404,\n }\n )\n }\n\n await invokeRender(parsedUrl, '/404', handleIndex, {\n invokeStatus: 404,\n })\n }\n\n try {\n await handleRequest(0)\n } catch (err) {\n try {\n let invokePath = '/500'\n let invokeStatus = '500'\n\n if (err instanceof DecodeError) {\n invokePath = '/400'\n invokeStatus = '400'\n } else {\n console.error(err)\n }\n res.statusCode = Number(invokeStatus)\n return await invokeRender(parseUrlUtil(invokePath), invokePath, 0, {\n invokeStatus: res.statusCode,\n })\n } catch (err2) {\n console.error(err2)\n }\n res.statusCode = 500\n res.end('Internal Server Error')\n }\n }\n\n let requestHandler: WorkerRequestHandler = requestHandlerImpl\n if (config.experimental.testProxy) {\n // Intercept fetch and other testmode apis.\n const { wrapRequestHandlerWorker, interceptTestApis } =\n // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n require('next/dist/experimental/testmode/server') as typeof import('../../experimental/testmode/server')\n requestHandler = wrapRequestHandlerWorker(requestHandler)\n interceptTestApis()\n // We treat the intercepted fetch as \"original\" fetch that should be reset to during HMR.\n originalFetch = globalThis.fetch\n }\n requestHandlers[opts.dir] = requestHandler\n\n const renderServerOpts: Parameters<RenderServer['initialize']>[0] = {\n port: opts.port,\n dir: opts.dir,\n hostname: opts.hostname,\n minimalMode: opts.minimalMode,\n dev: !!opts.dev,\n server: opts.server,\n serverFields: {\n ...(development?.bundler?.serverFields || {}),\n setIsrStatus: development?.service?.setIsrStatus.bind(\n development?.service\n ),\n } satisfies ServerFields,\n experimentalTestProxy: !!config.experimental.testProxy,\n experimentalHttpsServer: !!opts.experimentalHttpsServer,\n bundlerService: development?.service,\n startServerSpan: opts.startServerSpan,\n quiet: opts.quiet,\n onDevServerCleanup: opts.onDevServerCleanup,\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n }\n renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl\n\n // pre-initialize workers\n const handlers = await renderServer.instance.initialize(renderServerOpts)\n\n // this must come after initialize of render server since it's\n // using initialized methods\n if (!routerServerGlobal[RouterServerContextSymbol]) {\n routerServerGlobal[RouterServerContextSymbol] = {}\n }\n const relativeProjectDir = path.relative(process.cwd(), opts.dir)\n\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {\n nextConfig: getNextConfigRuntime(config),\n hostname: handlers.server.hostname,\n revalidate: handlers.server.revalidate.bind(handlers.server),\n render404: handlers.server.render404.bind(handlers.server),\n experimentalTestProxy: renderServerOpts.experimentalTestProxy,\n logErrorWithOriginalStack: opts.dev\n ? handlers.server.logErrorWithOriginalStack.bind(handlers.server)\n : (err: unknown) => !opts.quiet && Log.error(err),\n setCacheStatus: config.cacheComponents\n ? development?.service?.setCacheStatus.bind(development?.service)\n : undefined,\n setIsrStatus: development?.service?.setIsrStatus.bind(development?.service),\n setReactDebugChannel: development?.config.experimental.reactDebugChannel\n ? development?.service?.setReactDebugChannel.bind(development?.service)\n : undefined,\n sendErrorsToBrowser: development?.service?.sendErrorsToBrowser.bind(\n development?.service\n ),\n }\n\n const logError = async (\n type: 'uncaughtException' | 'unhandledRejection',\n err: Error | undefined\n ) => {\n if (isPostpone(err)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n if (type === 'unhandledRejection') {\n Log.error('unhandledRejection: ', err)\n } else if (type === 'uncaughtException') {\n Log.error('uncaughtException: ', err)\n }\n }\n\n process.on('uncaughtException', logError.bind(null, 'uncaughtException'))\n process.on('unhandledRejection', logError.bind(null, 'unhandledRejection'))\n\n const resolveRoutes = getResolveRoutes(\n fsChecker,\n config,\n opts,\n renderServer.instance,\n renderServerOpts,\n development?.bundler?.ensureMiddleware\n )\n\n const upgradeHandler: WorkerUpgradeHandler = async (req, socket, head) => {\n try {\n req.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n socket.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n\n if (opts.dev && development && req.url) {\n if (\n blockCrossSiteDEV(\n req,\n socket,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n const { basePath, assetPrefix } = config\n\n let hmrPrefix = basePath\n\n // assetPrefix overrides basePath for HMR path\n if (assetPrefix) {\n hmrPrefix = normalizedAssetPrefix(assetPrefix)\n\n if (URL.canParse(hmrPrefix)) {\n // remove trailing slash from pathname\n // return empty string if pathname is '/'\n // to avoid conflicts with '/_next' below\n hmrPrefix = new URL(hmrPrefix).pathname.replace(/\\/$/, '')\n }\n }\n\n const isHMRRequest = req.url.startsWith(\n ensureLeadingSlash(`${hmrPrefix}/_next/hmr`)\n )\n\n // only handle HMR requests if the basePath in the request\n // matches the basePath for the handler responding to the request\n if (isHMRRequest) {\n return development.bundler.hotReloader.onHMR(\n req,\n socket,\n head,\n (client, { isLegacyClient }) => {\n if (isLegacyClient) {\n // Only send the ISR manifest to legacy clients, i.e. Pages\n // Router clients, or App Router clients that have Cache\n // Components disabled. The ISR manifest is only used to inform\n // the static indicator, which currently does not provide useful\n // information if Cache Components is enabled due to its binary\n // nature (i.e. it does not support showing info for partially\n // static pages).\n client.send(\n JSON.stringify({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: development.service?.appIsrManifest || {},\n } satisfies AppIsrManifestMessage)\n )\n }\n }\n )\n }\n }\n\n const res = new MockedResponse({\n resWriter: () => {\n throw new Error(\n 'Invariant: did not expect response writer to be written to for upgrade request'\n )\n },\n })\n const { finished, matchedOutput, parsedUrl, statusCode } =\n await resolveRoutes({\n req,\n res,\n isUpgradeReq: true,\n signal: signalFromNodeResponse(socket),\n })\n\n // TODO: allow upgrade requests to pages/app paths?\n // this was not previously supported\n if (matchedOutput) {\n return socket.end()\n }\n\n if (finished && parsedUrl.protocol) {\n if (!statusCode) {\n return await proxyRequest(req, socket, parsedUrl, head)\n }\n\n return socket.end()\n }\n\n // If there's no matched output, we don't handle the request as user's\n // custom WS server may be listening on the same path.\n } catch (err) {\n console.error('Error handling upgrade request', err)\n socket.end()\n }\n }\n\n return {\n requestHandler,\n upgradeHandler,\n server: handlers.server,\n closeUpgraded() {\n development?.bundler?.hotReloader?.close()\n },\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n agentRules: config.agentRules,\n }\n}\n"],"names":["initialize","debug","setupDebug","isNextFont","pathname","test","requestHandlers","opts","development","process","env","NODE_ENV","dev","bundlerBeforeConfig","getBundlerFromEnv","undefined","experimentalFeatures","config","loadConfig","PHASE_DEVELOPMENT_SERVER","PHASE_PRODUCTION_SERVER","dir","silent","reportExperimentalFeatures","features","toSorted","key","a","b","localeCompare","finalizeBundlerFromConfig","compress","setupCompression","fsChecker","setupFsCheck","minimalMode","renderServer","originalFetch","globalThis","fetch","developmentConfig","Telemetry","require","telemetry","distDir","path","join","traceGlobals","set","pagesDir","appDir","findPagesDir","setupDevBundler","resetFetch","NEXT_PATCH_SYMBOL","setupDevBundlerSpan","startServerSpan","traceChild","trace","cliServerFastRefresh","serverFastRefresh","configServerFastRefresh","experimental","turbopackServerFastRefresh","effectiveServerFastRefresh","Log","warn","developmentBundler","traceAsyncFn","nextConfig","isCustomServer","customServer","turbo","TURBOPACK","port","onDevServerCleanup","devBundlerService","DevBundlerService","req","res","Boolean","requestInsights","bundler","service","instance","requestHandlerImpl","addRequestMeta","relativeProjectDir","NEXT_PRIVATE_TEST_HEADERS","filterInternalHeaders","headers","url","__NEXT_REQUEST_INSIGHTS","urlParts","split","removePathPrefix","basePath","REQUEST_INSIGHTS_DEV_ENDPOINT","blockCrossSiteDEV","allowedDevOrigins","hostname","setHeader","isRequestInsightsEnabled","statusCode","end","JSON","stringify","error","getRequestInsightsSnapshot","i18n","localeDetection","urlNoQuery","pathnameInfo","getNextPathnameInfo","domainLocale","detectDomainLocale","domains","getHostname","defaultLocale","getLocaleRedirect","parsedUrl","parseUrlUtil","replace","redirect","pathLocale","locale","urlParsed","RedirectStatusCode","TemporaryRedirect","on","_err","invokedOutputs","Set","invokeRender","invokePath","handleIndex","additionalRequestMeta","startsWith","getRequestMeta","handleLocale","getMiddlewareMatchers","length","handlers","Error","query","initResult","renderServerOpts","requestHandler","err","NoFallbackError","handleRequest","e","isAbortError","origUrl","pathHasPrefix","assetPrefix","hotReloaderResult","hotReloader","run","finished","resHeaders","bodyStream","matchedOutput","resolveRoutes","isUpgradeReq","signal","signalFromNodeResponse","closed","type","Object","keys","result","destination","format","PermanentRedirect","pipeToNodeResponse","protocol","proxyRequest","cloneBodyStream","proxyTimeout","fsPath","itemPath","appFiles","has","pageFiles","message","invokeStatus","invokeError","getHeader","method","serveStatic","root","itemsRoot","etag","generateEtags","POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC","validErrorStatus","add","invokeOutput","isChromeDevtoolsWorkspaceUrl","handleChromeDevtoolsWorkspaceRequest","realRequestPathname","isNonHtmlSecFetchDest","appNotFound","serverFields","hasAppNotFound","getItem","UNDERSCORE_NOT_FOUND_ROUTE","DecodeError","console","Number","err2","testProxy","wrapRequestHandlerWorker","interceptTestApis","server","setIsrStatus","bind","experimentalTestProxy","experimentalHttpsServer","bundlerService","quiet","cacheComponents","partialPrefetching","routerServerHandler","routerServerGlobal","RouterServerContextSymbol","relative","cwd","getNextConfigRuntime","revalidate","render404","logErrorWithOriginalStack","setCacheStatus","setReactDebugChannel","reactDebugChannel","sendErrorsToBrowser","logError","isPostpone","getResolveRoutes","ensureMiddleware","upgradeHandler","socket","head","hmrPrefix","normalizedAssetPrefix","URL","canParse","isHMRRequest","ensureLeadingSlash","onHMR","client","isLegacyClient","send","HMR_MESSAGE_SENT_TO_BROWSER","ISR_MANIFEST","data","appIsrManifest","MockedResponse","resWriter","closeUpgraded","close","agentRules"],"mappings":"AAAA,oDAAoD;;;;;+BAwF9BA;;;eAAAA;;;QAlFf;QACA;4DAES;6DACC;+DAC8C;yBACF;6BACjC;8DACL;6DACF;uBACO;8BACC;4BACA;8BACA;8BACoB;+BAChB;6BACc;+BACjB;kCACG;oEACJ;6BACU;4BACZ;uCACW;0BACG;2BAOlC;oCAC4B;mCACD;uBACD;oCACE;qCACC;6BACR;oCACO;6BACJ;kCAIxB;uCAC+B;4BACJ;wBAEI;mCACJ;wBACL;yCACG;qCAIzB;yCAIA;8BACuD;iCAIvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEP,MAAMC,QAAQC,IAAAA,cAAU,EAAC;AACzB,MAAMC,aAAa,CAACC,WAClBA,YAAY,4CAA4CC,IAAI,CAACD;AAc/D,MAAME,kBAAwD,CAAC;AAExD,eAAeN,WAAWO,IAchC;QA0sBSC,sBACUA,sBAqCZA,uBAEUA,uBAEVA,uBAEiBA,uBA8BrBA;IAnxBF,IAAI,CAACC,QAAQC,GAAG,CAACC,QAAQ,EAAE;QACzB,0BAA0B;QAC1BF,QAAQC,GAAG,CAACC,QAAQ,GAAGJ,KAAKK,GAAG,GAAG,gBAAgB;IACpD;IA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IACF;IAEA,OAAO;QACL2C;QACA8F;QACA1B,QAAQzE,SAASyE,MAAM;QACvB6C;gBACE5P,kCAAAA;YAAAA,gCAAAA,uBAAAA,YAAa0E,OAAO,sBAApB1E,mCAAAA,qBAAsBqJ,WAAW,qBAAjCrJ,iCAAmC6P,KAAK;QAC1C;QACAzN,SAAS3B,OAAO2B,OAAO;QACvB5B;QACA8M,iBAAiB7M,OAAO6M,eAAe;QACvCC,oBAAoB9M,OAAO8M,kBAAkB;QAC7CuC,YAAYrP,OAAOqP,UAAU;IAC/B;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/lib/router-server.ts"],"sourcesContent":["// this must come first as it includes require hooks\nimport type { WorkerRequestHandler, WorkerUpgradeHandler } from './types'\nimport type { DevBundler, ServerFields } from './router-utils/setup-dev-bundler'\nimport type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta'\n\n// This is required before other imports to ensure the require hook is setup.\nimport '../node-environment'\nimport '../require-hook'\n\nimport url from 'url'\nimport path from 'path'\nimport loadConfig, { type ConfiguredExperimentalFeature } from '../config'\nimport { finalizeBundlerFromConfig, getBundlerFromEnv } from '../../lib/bundler'\nimport { serveStatic } from '../serve-static'\nimport setupDebug from 'next/dist/compiled/debug'\nimport * as Log from '../../build/output/log'\nimport { DecodeError } from '../../shared/lib/utils'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport { setupFsCheck } from './router-utils/filesystem'\nimport { proxyRequest } from './router-utils/proxy-request'\nimport { isAbortError, pipeToNodeResponse } from '../pipe-readable'\nimport { getResolveRoutes } from './router-utils/resolve-routes'\nimport { addRequestMeta, getRequestMeta } from '../request-meta'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport setupCompression from 'next/dist/compiled/compression'\nimport { releaseCompressionStream } from './release-compression-stream'\nimport { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'\nimport { isPostpone } from './router-utils/is-postpone'\nimport { isNonHtmlSecFetchDest } from './is-non-html-sec-fetch-dest'\nimport { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-url'\n\nimport {\n PHASE_PRODUCTION_SERVER,\n PHASE_DEVELOPMENT_SERVER,\n REQUEST_INSIGHTS_DEV_ENDPOINT,\n UNDERSCORE_NOT_FOUND_ROUTE,\n} from '../../shared/lib/constants'\nimport { RedirectStatusCode } from '../../client/components/redirect-status-code'\nimport { DevBundlerService } from './dev-bundler-service'\nimport { type Span, trace } from '../../trace'\nimport { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'\nimport { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { MockedResponse } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type AppIsrManifestMessage,\n} from '../dev/hot-reloader-types'\nimport { normalizedAssetPrefix } from '../../shared/lib/normalized-asset-prefix'\nimport { NEXT_PATCH_SYMBOL } from './patch-fetch'\nimport type { ServerInitResult } from './render-server'\nimport { filterInternalHeaders } from './server-ipc/utils'\nimport { blockCrossSiteDEV } from './router-utils/block-cross-site-dev'\nimport { traceGlobals } from '../../trace/shared'\nimport { NoFallbackError } from '../../shared/lib/no-fallback-error.external'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n} from './router-utils/router-server-context'\nimport {\n handleChromeDevtoolsWorkspaceRequest,\n isChromeDevtoolsWorkspaceUrl,\n} from './chrome-devtools-workspace'\nimport { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'\nimport {\n getRequestInsightsSnapshot,\n isRequestInsightsEnabled,\n} from './trace/request-insights'\n\nconst debug = setupDebug('next:router-server:main')\nconst isNextFont = (pathname: string | null) =>\n pathname && /\\/media\\/[^/]+\\.(woff|woff2|eot|ttf|otf)$/.test(pathname)\n\nexport type RenderServer = Pick<\n typeof import('./render-server'),\n | 'initialize'\n | 'clearModuleContext'\n | 'propagateServerField'\n | 'getServerField'\n>\n\nexport interface LazyRenderServerInstance {\n instance?: RenderServer\n}\n\nconst requestHandlers: Record<string, WorkerRequestHandler> = {}\n\nexport async function initialize(opts: {\n dir: string\n port: number\n dev: boolean\n onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined\n server?: import('http').Server\n minimalMode?: boolean\n hostname?: string\n keepAliveTimeout?: number\n customServer?: boolean\n experimentalHttpsServer?: boolean\n serverFastRefresh?: boolean\n startServerSpan?: Span\n quiet?: boolean\n}): Promise<ServerInitResult> {\n if (!process.env.NODE_ENV) {\n // @ts-ignore not readonly\n process.env.NODE_ENV = opts.dev ? 'development' : 'production'\n }\n\n // Capture the bundler before loading the config\n const bundlerBeforeConfig = opts.dev ? getBundlerFromEnv() : undefined\n\n let experimentalFeatures: ConfiguredExperimentalFeature[] = []\n const config = await loadConfig(\n opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,\n opts.dir,\n {\n silent: false,\n reportExperimentalFeatures(features) {\n experimentalFeatures = features.toSorted(({ key: a }, { key: b }) =>\n a.localeCompare(b)\n )\n },\n }\n )\n\n if (bundlerBeforeConfig !== undefined) {\n finalizeBundlerFromConfig(bundlerBeforeConfig)\n }\n\n let compress: ReturnType<typeof setupCompression> | undefined\n\n if (config?.compress !== false) {\n compress = setupCompression()\n }\n\n const fsChecker = await setupFsCheck({\n dev: opts.dev,\n dir: opts.dir,\n config,\n minimalMode: opts.minimalMode,\n })\n\n const renderServer: LazyRenderServerInstance = {}\n\n let development:\n | {\n bundler: DevBundler\n service: DevBundlerService\n config: NextConfigComplete\n }\n | undefined = undefined\n\n let originalFetch = globalThis.fetch\n\n if (opts.dev) {\n const { Telemetry } =\n require('../../telemetry/storage') as typeof import('../../telemetry/storage')\n\n const telemetry = new Telemetry({\n distDir: path.join(opts.dir, config.distDir),\n })\n traceGlobals.set('telemetry', telemetry)\n\n const { pagesDir, appDir } = findPagesDir(opts.dir)\n\n const { setupDevBundler } =\n require('./router-utils/setup-dev-bundler') as typeof import('./router-utils/setup-dev-bundler')\n\n const resetFetch = () => {\n globalThis.fetch = originalFetch\n ;(globalThis as Record<symbol, unknown>)[NEXT_PATCH_SYMBOL] = false\n }\n\n const setupDevBundlerSpan = opts.startServerSpan\n ? opts.startServerSpan.traceChild('setup-dev-bundler')\n : trace('setup-dev-bundler')\n\n // In development, it's always the complete config.\n let developmentConfig = config as NextConfigComplete\n\n // Resolve the effective serverFastRefresh value.\n // Both default to enabled (true). CLI takes precedence over config.\n const cliServerFastRefresh = opts.serverFastRefresh\n const configServerFastRefresh =\n developmentConfig.experimental?.turbopackServerFastRefresh\n let effectiveServerFastRefresh: boolean | undefined\n if (\n cliServerFastRefresh !== undefined &&\n configServerFastRefresh !== undefined &&\n cliServerFastRefresh !== configServerFastRefresh\n ) {\n Log.warn(\n `The CLI flag \"${cliServerFastRefresh === false ? '--no-server-fast-refresh' : '--server-fast-refresh'}\" conflicts with \"experimental.turbopackServerFastRefresh: ${configServerFastRefresh}\" in your Next.js config. The CLI flag will take precedence.`\n )\n effectiveServerFastRefresh = cliServerFastRefresh\n } else {\n // Default to true when neither CLI nor config specifies a value.\n effectiveServerFastRefresh =\n cliServerFastRefresh ?? configServerFastRefresh ?? true\n }\n\n let developmentBundler = await setupDevBundlerSpan.traceAsyncFn(() =>\n setupDevBundler({\n // Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks.\n renderServer,\n appDir,\n pagesDir,\n telemetry,\n fsChecker,\n dir: opts.dir,\n nextConfig: developmentConfig,\n isCustomServer: opts.customServer,\n turbo: !!process.env.TURBOPACK,\n port: opts.port,\n onDevServerCleanup: opts.onDevServerCleanup,\n resetFetch,\n serverFastRefresh: effectiveServerFastRefresh,\n })\n )\n\n let devBundlerService = new DevBundlerService(\n developmentBundler,\n // The request handler is assigned below, this allows us to create a lazy\n // reference to it.\n (req, res) => {\n return requestHandlers[opts.dir](req, res)\n },\n Boolean(developmentConfig.experimental.requestInsights)\n )\n\n development = {\n bundler: developmentBundler,\n service: devBundlerService,\n config: developmentConfig,\n }\n }\n\n renderServer.instance =\n require('./render-server') as typeof import('./render-server')\n\n const requestHandlerImpl: WorkerRequestHandler = async (req, res) => {\n addRequestMeta(req, 'relativeProjectDir', relativeProjectDir)\n\n // internal headers should not be honored by the request handler\n if (!process.env.NEXT_PRIVATE_TEST_HEADERS) {\n filterInternalHeaders(req.headers)\n }\n\n if (opts.dev && req.url) {\n if (config.experimental.requestInsights) {\n process.env.__NEXT_REQUEST_INSIGHTS = 'true'\n }\n\n const urlParts = req.url.split('?', 1)\n const pathname = removePathPrefix(urlParts[0] || '', config.basePath)\n\n if (pathname === REQUEST_INSIGHTS_DEV_ENDPOINT) {\n if (\n development &&\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n if (\n !config.experimental.requestInsights &&\n !isRequestInsightsEnabled()\n ) {\n res.statusCode = 404\n res.end(\n JSON.stringify({\n error:\n 'Request Insights is not enabled. Set experimental.requestInsights = true and restart next dev.',\n })\n )\n return\n }\n\n res.statusCode = 200\n res.end(JSON.stringify(getRequestInsightsSnapshot()))\n return\n }\n }\n\n if (\n !opts.minimalMode &&\n config.i18n &&\n config.i18n.localeDetection !== false\n ) {\n const urlParts = (req.url || '').split('?', 1)\n let urlNoQuery = urlParts[0] || ''\n\n if (config.basePath) {\n urlNoQuery = removePathPrefix(urlNoQuery, config.basePath)\n }\n\n const pathnameInfo = getNextPathnameInfo(urlNoQuery, {\n nextConfig: config,\n })\n\n const domainLocale = detectDomainLocale(\n config.i18n.domains,\n getHostname({ hostname: urlNoQuery }, req.headers)\n )\n\n const defaultLocale =\n domainLocale?.defaultLocale || config.i18n.defaultLocale\n\n const { getLocaleRedirect } =\n require('../../shared/lib/i18n/get-locale-redirect') as typeof import('../../shared/lib/i18n/get-locale-redirect')\n\n const parsedUrl = parseUrlUtil((req.url || '')?.replace(/^\\/+/, '/'))\n\n const redirect = getLocaleRedirect({\n defaultLocale,\n domainLocale,\n headers: req.headers,\n nextConfig: config,\n pathLocale: pathnameInfo.locale,\n urlParsed: {\n ...parsedUrl,\n pathname: pathnameInfo.locale\n ? `/${pathnameInfo.locale}${urlNoQuery}`\n : urlNoQuery,\n },\n })\n\n if (redirect) {\n res.setHeader('Location', redirect)\n res.statusCode = RedirectStatusCode.TemporaryRedirect\n res.end(redirect)\n return\n }\n }\n\n if (compress) {\n // @ts-expect-error not express req/res\n compress(req, res, () => {})\n\n // On client disconnect the middleware never ends its zlib stream, which\n // then leaks past GC. See `releaseCompressionStream`.\n res.once('close', () => {\n if (res.writableFinished) return\n\n releaseCompressionStream(res)\n })\n }\n req.on('error', (_err) => {\n // TODO: log socket errors?\n })\n res.on('error', (_err) => {\n // TODO: log socket errors?\n })\n\n const invokedOutputs = new Set<string>()\n\n async function invokeRender(\n parsedUrl: NextUrlWithParsedQuery,\n invokePath: string,\n handleIndex: number,\n additionalRequestMeta?: RequestMeta\n ) {\n // invokeRender expects /api routes to not be locale prefixed\n // so normalize here before continuing\n if (\n config.i18n &&\n removePathPrefix(invokePath, config.basePath).startsWith(\n `/${getRequestMeta(req, 'locale')}/api`\n )\n ) {\n invokePath = fsChecker.handleLocale(\n removePathPrefix(invokePath, config.basePath)\n ).pathname\n }\n\n if (\n req.headers['x-nextjs-data'] &&\n fsChecker.getMiddlewareMatchers()?.length &&\n removePathPrefix(invokePath, config.basePath) === '/404'\n ) {\n res.setHeader('x-nextjs-matched-path', parsedUrl.pathname || '')\n res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end('{}')\n return null\n }\n\n if (!handlers) {\n throw new Error('Failed to initialize render server')\n }\n\n addRequestMeta(req, 'invokePath', invokePath)\n addRequestMeta(req, 'invokeQuery', parsedUrl.query)\n addRequestMeta(req, 'middlewareInvoke', false)\n\n for (const key in additionalRequestMeta || {}) {\n addRequestMeta(\n req,\n key as keyof RequestMeta,\n additionalRequestMeta![key as keyof RequestMeta]\n )\n }\n\n debug('invokeRender', req.url, req.headers)\n\n try {\n const initResult =\n await renderServer?.instance?.initialize(renderServerOpts)\n try {\n await initResult?.requestHandler(req, res)\n } catch (err) {\n if (err instanceof NoFallbackError) {\n await handleRequest(handleIndex + 1)\n return\n }\n throw err\n }\n return\n } catch (e) {\n // If the client aborts before we can receive a response object (when\n // the headers are flushed), then we can early exit without further\n // processing.\n if (isAbortError(e)) {\n return\n }\n throw e\n }\n }\n\n const handleRequest = async (handleIndex: number) => {\n if (handleIndex > 5) {\n throw new Error(`Attempted to handle request too many times ${req.url}`)\n }\n\n // handle hot-reloader first\n if (development) {\n if (\n blockCrossSiteDEV(\n req,\n res,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n\n const origUrl = req.url || '/'\n\n // both the basePath and assetPrefix need to be stripped from the URL\n // so that the development bundler can find the correct file\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n const parsedUrl = parseUrlUtil(req.url || '/')\n\n const hotReloaderResult = await development.bundler.hotReloader.run(\n req,\n res,\n parsedUrl\n )\n\n if (hotReloaderResult.finished) {\n return hotReloaderResult\n }\n\n req.url = origUrl\n }\n\n const {\n finished,\n parsedUrl,\n statusCode,\n resHeaders,\n bodyStream,\n matchedOutput,\n } = await resolveRoutes({\n req,\n res,\n isUpgradeReq: false,\n signal: signalFromNodeResponse(res),\n invokedOutputs,\n })\n\n if (res.closed || res.finished) {\n return\n }\n\n if (development && matchedOutput?.type === 'devVirtualFsItem') {\n const origUrl = req.url || '/'\n\n if (config.basePath && pathHasPrefix(origUrl, config.basePath)) {\n req.url = removePathPrefix(origUrl, config.basePath)\n } else if (\n config.assetPrefix &&\n pathHasPrefix(origUrl, config.assetPrefix)\n ) {\n req.url = removePathPrefix(origUrl, config.assetPrefix)\n }\n\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n const result = await development.bundler.requestHandler(req, res)\n\n if (result.finished) {\n return\n }\n // TODO: throw invariant if we resolved to this but it wasn't handled?\n req.url = origUrl\n }\n\n debug('requestHandler!', req.url, {\n matchedOutput,\n statusCode,\n resHeaders,\n bodyStream: !!bodyStream,\n parsedUrl: {\n pathname: parsedUrl.pathname,\n query: parsedUrl.query,\n },\n finished,\n })\n\n // apply any response headers from routing\n if (resHeaders !== null) {\n for (const key of Object.keys(resHeaders)) {\n res.setHeader(key, resHeaders[key])\n }\n }\n\n // handle redirect\n if (!bodyStream && statusCode && statusCode > 300 && statusCode < 400) {\n const destination = url.format(parsedUrl)\n res.statusCode = statusCode\n res.setHeader('location', destination)\n\n if (statusCode === RedirectStatusCode.PermanentRedirect) {\n res.setHeader('Refresh', `0;url=${destination}`)\n }\n return res.end(destination)\n }\n\n // handle middleware body response\n if (bodyStream) {\n res.statusCode = statusCode || 200\n return await pipeToNodeResponse(bodyStream, res)\n }\n\n if (finished && parsedUrl.protocol) {\n return await proxyRequest(\n req,\n res,\n parsedUrl,\n undefined,\n getRequestMeta(req, 'clonableBody')?.cloneBodyStream(),\n config.experimental.proxyTimeout\n )\n }\n\n if (matchedOutput?.fsPath && matchedOutput.itemPath) {\n if (\n opts.dev &&\n (fsChecker.appFiles.has(matchedOutput.itemPath) ||\n fsChecker.pageFiles.has(matchedOutput.itemPath))\n ) {\n res.statusCode = 500\n const message = `A conflicting public file and page file was found for path ${matchedOutput.itemPath} https://nextjs.org/docs/messages/conflicting-public-file-page`\n await invokeRender(parsedUrl, '/_error', handleIndex, {\n invokeStatus: 500,\n invokeError: new Error(message),\n })\n Log.error(message)\n return\n }\n\n if (\n !res.getHeader('cache-control') &&\n matchedOutput.type === 'nextStaticFolder'\n ) {\n if (matchedOutput.itemPath.startsWith('/service-worker/')) {\n res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate')\n res.setHeader('Service-Worker-Allowed', config.basePath || '/')\n } else if (opts.dev && !isNextFont(parsedUrl.pathname)) {\n res.setHeader('Cache-Control', 'no-cache, must-revalidate')\n } else {\n res.setHeader(\n 'Cache-Control',\n 'public, max-age=31536000, immutable'\n )\n }\n }\n if (!(req.method === 'GET' || req.method === 'HEAD')) {\n res.setHeader('Allow', ['GET', 'HEAD'])\n res.statusCode = 405\n return await invokeRender(parseUrlUtil('/405'), '/405', handleIndex, {\n invokeStatus: 405,\n })\n }\n\n try {\n return await serveStatic(req, res, matchedOutput.itemPath, {\n root: matchedOutput.itemsRoot,\n // Ensures that etags are not generated for static files when disabled.\n etag: config.generateEtags,\n })\n } catch (err: any) {\n /**\n * Hardcoded every possible error status code that could be thrown by \"serveStatic\" method\n * This is done by searching \"this.error\" inside \"send\" module's source code:\n * https://github.com/pillarjs/send/blob/master/index.js\n * https://github.com/pillarjs/send/blob/develop/index.js\n */\n const POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC = new Set([\n // send module will throw 500 when header is already sent or fs.stat error happens\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L392\n // Note: we will use Next.js built-in 500 page to handle 500 errors\n // 500,\n\n // send module will throw 404 when file is missing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L421\n // Note: we will use Next.js built-in 404 page to handle 404 errors\n // 404,\n\n // send module will throw 403 when redirecting to a directory without enabling directory listing\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L484\n // Note: Next.js throws a different error (without status code) for directory listing\n // 403,\n\n // send module will throw 400 when fails to normalize the path\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L520\n 400,\n\n // send module will throw 412 with conditional GET request\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L632\n 412,\n\n // send module will throw 416 when range is not satisfiable\n // https://github.com/pillarjs/send/blob/53f0ab476145670a9bdd3dc722ab2fdc8d358fc6/index.js#L669\n 416,\n ])\n\n let validErrorStatus = POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC.has(\n err.statusCode\n )\n\n // normalize non-allowed status codes\n if (!validErrorStatus) {\n ;(err as any).statusCode = 400\n }\n\n if (typeof err.statusCode === 'number') {\n const invokePath = `/${err.statusCode}`\n const invokeStatus = err.statusCode\n res.statusCode = err.statusCode\n return await invokeRender(\n parseUrlUtil(invokePath),\n invokePath,\n handleIndex,\n {\n invokeStatus,\n }\n )\n }\n throw err\n }\n }\n\n if (matchedOutput) {\n invokedOutputs.add(matchedOutput.itemPath)\n\n return await invokeRender(\n parsedUrl,\n parsedUrl.pathname || '/',\n handleIndex,\n {\n invokeOutput: matchedOutput.itemPath,\n }\n )\n }\n\n // We want the original pathname without any basePath or proxy rewrites.\n if (development && isChromeDevtoolsWorkspaceUrl(req.url)) {\n await handleChromeDevtoolsWorkspaceRequest(res, opts, config)\n return\n }\n\n // 404 case\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n\n let realRequestPathname = parsedUrl.pathname ?? ''\n if (realRequestPathname) {\n if (config.basePath) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.basePath\n )\n }\n if (config.assetPrefix) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n config.assetPrefix\n )\n }\n if (config.i18n) {\n realRequestPathname = removePathPrefix(\n realRequestPathname,\n '/' + (getRequestMeta(req, 'locale') ?? '')\n )\n }\n }\n // For not found static assets, return plain text 404 instead of\n // full HTML 404 pages to save bandwidth.\n if (realRequestPathname.startsWith('/_next/static/')) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // For subresource requests (e.g. images or fonts), return plain text\n // 404 instead of rendering the not-found route.\n if (\n (req.method === 'GET' || req.method === 'HEAD') &&\n isNonHtmlSecFetchDest(req.headers['sec-fetch-dest'])\n ) {\n res.statusCode = 404\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end('Not Found')\n return null\n }\n\n // Short-circuit favicon.ico serving so that the 404 page doesn't get built as favicon is requested by the browser when loading any route.\n if (opts.dev && !matchedOutput && parsedUrl.pathname === '/favicon.ico') {\n res.statusCode = 404\n res.end('')\n return null\n }\n\n const appNotFound = opts.dev\n ? development?.bundler?.serverFields.hasAppNotFound\n : await fsChecker.getItem(UNDERSCORE_NOT_FOUND_ROUTE)\n\n res.statusCode = 404\n\n if (appNotFound) {\n return await invokeRender(\n parsedUrl,\n UNDERSCORE_NOT_FOUND_ROUTE,\n handleIndex,\n {\n invokeStatus: 404,\n }\n )\n }\n\n await invokeRender(parsedUrl, '/404', handleIndex, {\n invokeStatus: 404,\n })\n }\n\n try {\n await handleRequest(0)\n } catch (err) {\n try {\n let invokePath = '/500'\n let invokeStatus = '500'\n\n if (err instanceof DecodeError) {\n invokePath = '/400'\n invokeStatus = '400'\n } else {\n console.error(err)\n }\n res.statusCode = Number(invokeStatus)\n return await invokeRender(parseUrlUtil(invokePath), invokePath, 0, {\n invokeStatus: res.statusCode,\n })\n } catch (err2) {\n console.error(err2)\n }\n res.statusCode = 500\n res.end('Internal Server Error')\n }\n }\n\n let requestHandler: WorkerRequestHandler = requestHandlerImpl\n if (config.experimental.testProxy) {\n // Intercept fetch and other testmode apis.\n const { wrapRequestHandlerWorker, interceptTestApis } =\n // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm\n require('next/dist/experimental/testmode/server') as typeof import('../../experimental/testmode/server')\n requestHandler = wrapRequestHandlerWorker(requestHandler)\n interceptTestApis()\n // We treat the intercepted fetch as \"original\" fetch that should be reset to during HMR.\n originalFetch = globalThis.fetch\n }\n requestHandlers[opts.dir] = requestHandler\n\n const renderServerOpts: Parameters<RenderServer['initialize']>[0] = {\n port: opts.port,\n dir: opts.dir,\n hostname: opts.hostname,\n minimalMode: opts.minimalMode,\n dev: !!opts.dev,\n server: opts.server,\n serverFields: {\n ...(development?.bundler?.serverFields || {}),\n setIsrStatus: development?.service?.setIsrStatus.bind(\n development?.service\n ),\n } satisfies ServerFields,\n experimentalTestProxy: !!config.experimental.testProxy,\n experimentalHttpsServer: !!opts.experimentalHttpsServer,\n bundlerService: development?.service,\n startServerSpan: opts.startServerSpan,\n quiet: opts.quiet,\n onDevServerCleanup: opts.onDevServerCleanup,\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n }\n renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl\n\n // pre-initialize workers\n const handlers = await renderServer.instance.initialize(renderServerOpts)\n\n // this must come after initialize of render server since it's\n // using initialized methods\n if (!routerServerGlobal[RouterServerContextSymbol]) {\n routerServerGlobal[RouterServerContextSymbol] = {}\n }\n const relativeProjectDir = path.relative(process.cwd(), opts.dir)\n\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {\n nextConfig: getNextConfigRuntime(config),\n hostname: handlers.server.hostname,\n revalidate: handlers.server.revalidate.bind(handlers.server),\n render404: handlers.server.render404.bind(handlers.server),\n experimentalTestProxy: renderServerOpts.experimentalTestProxy,\n logErrorWithOriginalStack: opts.dev\n ? handlers.server.logErrorWithOriginalStack.bind(handlers.server)\n : (err: unknown) => !opts.quiet && Log.error(err),\n setCacheStatus: config.cacheComponents\n ? development?.service?.setCacheStatus.bind(development?.service)\n : undefined,\n setIsrStatus: development?.service?.setIsrStatus.bind(development?.service),\n setReactDebugChannel: development?.config.experimental.reactDebugChannel\n ? development?.service?.setReactDebugChannel.bind(development?.service)\n : undefined,\n sendErrorsToBrowser: development?.service?.sendErrorsToBrowser.bind(\n development?.service\n ),\n }\n\n const logError = async (\n type: 'uncaughtException' | 'unhandledRejection',\n err: Error | undefined\n ) => {\n if (isPostpone(err)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n if (type === 'unhandledRejection') {\n Log.error('unhandledRejection: ', err)\n } else if (type === 'uncaughtException') {\n Log.error('uncaughtException: ', err)\n }\n }\n\n process.on('uncaughtException', logError.bind(null, 'uncaughtException'))\n process.on('unhandledRejection', logError.bind(null, 'unhandledRejection'))\n\n const resolveRoutes = getResolveRoutes(\n fsChecker,\n config,\n opts,\n renderServer.instance,\n renderServerOpts,\n development?.bundler?.ensureMiddleware\n )\n\n const upgradeHandler: WorkerUpgradeHandler = async (req, socket, head) => {\n try {\n req.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n socket.on('error', (_err) => {\n // TODO: log socket errors?\n // console.error(_err);\n })\n\n if (opts.dev && development && req.url) {\n if (\n blockCrossSiteDEV(\n req,\n socket,\n development.config.allowedDevOrigins,\n opts.hostname\n )\n ) {\n return\n }\n const { basePath, assetPrefix } = config\n\n let hmrPrefix = basePath\n\n // assetPrefix overrides basePath for HMR path\n if (assetPrefix) {\n hmrPrefix = normalizedAssetPrefix(assetPrefix)\n\n if (URL.canParse(hmrPrefix)) {\n // remove trailing slash from pathname\n // return empty string if pathname is '/'\n // to avoid conflicts with '/_next' below\n hmrPrefix = new URL(hmrPrefix).pathname.replace(/\\/$/, '')\n }\n }\n\n const isHMRRequest = req.url.startsWith(\n ensureLeadingSlash(`${hmrPrefix}/_next/hmr`)\n )\n\n // only handle HMR requests if the basePath in the request\n // matches the basePath for the handler responding to the request\n if (isHMRRequest) {\n return development.bundler.hotReloader.onHMR(\n req,\n socket,\n head,\n (client, { isLegacyClient }) => {\n if (isLegacyClient) {\n // Only send the ISR manifest to legacy clients, i.e. Pages\n // Router clients, or App Router clients that have Cache\n // Components disabled. The ISR manifest is only used to inform\n // the static indicator, which currently does not provide useful\n // information if Cache Components is enabled due to its binary\n // nature (i.e. it does not support showing info for partially\n // static pages).\n client.send(\n JSON.stringify({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: development.service?.appIsrManifest || {},\n } satisfies AppIsrManifestMessage)\n )\n }\n }\n )\n }\n }\n\n const res = new MockedResponse({\n resWriter: () => {\n throw new Error(\n 'Invariant: did not expect response writer to be written to for upgrade request'\n )\n },\n })\n const { finished, matchedOutput, parsedUrl, statusCode } =\n await resolveRoutes({\n req,\n res,\n isUpgradeReq: true,\n signal: signalFromNodeResponse(socket),\n })\n\n // TODO: allow upgrade requests to pages/app paths?\n // this was not previously supported\n if (matchedOutput) {\n return socket.end()\n }\n\n if (finished && parsedUrl.protocol) {\n if (!statusCode) {\n return await proxyRequest(req, socket, parsedUrl, head)\n }\n\n return socket.end()\n }\n\n // If there's no matched output, we don't handle the request as user's\n // custom WS server may be listening on the same path.\n } catch (err) {\n console.error('Error handling upgrade request', err)\n socket.end()\n }\n }\n\n return {\n requestHandler,\n upgradeHandler,\n server: handlers.server,\n closeUpgraded() {\n development?.bundler?.hotReloader?.close()\n },\n distDir: config.distDir,\n experimentalFeatures,\n cacheComponents: config.cacheComponents,\n partialPrefetching: config.partialPrefetching,\n agentRules: config.agentRules,\n }\n}\n"],"names":["initialize","debug","setupDebug","isNextFont","pathname","test","requestHandlers","opts","development","process","env","NODE_ENV","dev","bundlerBeforeConfig","getBundlerFromEnv","undefined","experimentalFeatures","config","loadConfig","PHASE_DEVELOPMENT_SERVER","PHASE_PRODUCTION_SERVER","dir","silent","reportExperimentalFeatures","features","toSorted","key","a","b","localeCompare","finalizeBundlerFromConfig","compress","setupCompression","fsChecker","setupFsCheck","minimalMode","renderServer","originalFetch","globalThis","fetch","developmentConfig","Telemetry","require","telemetry","distDir","path","join","traceGlobals","set","pagesDir","appDir","findPagesDir","setupDevBundler","resetFetch","NEXT_PATCH_SYMBOL","setupDevBundlerSpan","startServerSpan","traceChild","trace","cliServerFastRefresh","serverFastRefresh","configServerFastRefresh","experimental","turbopackServerFastRefresh","effectiveServerFastRefresh","Log","warn","developmentBundler","traceAsyncFn","nextConfig","isCustomServer","customServer","turbo","TURBOPACK","port","onDevServerCleanup","devBundlerService","DevBundlerService","req","res","Boolean","requestInsights","bundler","service","instance","requestHandlerImpl","addRequestMeta","relativeProjectDir","NEXT_PRIVATE_TEST_HEADERS","filterInternalHeaders","headers","url","__NEXT_REQUEST_INSIGHTS","urlParts","split","removePathPrefix","basePath","REQUEST_INSIGHTS_DEV_ENDPOINT","blockCrossSiteDEV","allowedDevOrigins","hostname","setHeader","isRequestInsightsEnabled","statusCode","end","JSON","stringify","error","getRequestInsightsSnapshot","i18n","localeDetection","urlNoQuery","pathnameInfo","getNextPathnameInfo","domainLocale","detectDomainLocale","domains","getHostname","defaultLocale","getLocaleRedirect","parsedUrl","parseUrlUtil","replace","redirect","pathLocale","locale","urlParsed","RedirectStatusCode","TemporaryRedirect","once","writableFinished","releaseCompressionStream","on","_err","invokedOutputs","Set","invokeRender","invokePath","handleIndex","additionalRequestMeta","startsWith","getRequestMeta","handleLocale","getMiddlewareMatchers","length","handlers","Error","query","initResult","renderServerOpts","requestHandler","err","NoFallbackError","handleRequest","e","isAbortError","origUrl","pathHasPrefix","assetPrefix","hotReloaderResult","hotReloader","run","finished","resHeaders","bodyStream","matchedOutput","resolveRoutes","isUpgradeReq","signal","signalFromNodeResponse","closed","type","Object","keys","result","destination","format","PermanentRedirect","pipeToNodeResponse","protocol","proxyRequest","cloneBodyStream","proxyTimeout","fsPath","itemPath","appFiles","has","pageFiles","message","invokeStatus","invokeError","getHeader","method","serveStatic","root","itemsRoot","etag","generateEtags","POSSIBLE_ERROR_CODE_FROM_SERVE_STATIC","validErrorStatus","add","invokeOutput","isChromeDevtoolsWorkspaceUrl","handleChromeDevtoolsWorkspaceRequest","realRequestPathname","isNonHtmlSecFetchDest","appNotFound","serverFields","hasAppNotFound","getItem","UNDERSCORE_NOT_FOUND_ROUTE","DecodeError","console","Number","err2","testProxy","wrapRequestHandlerWorker","interceptTestApis","server","setIsrStatus","bind","experimentalTestProxy","experimentalHttpsServer","bundlerService","quiet","cacheComponents","partialPrefetching","routerServerHandler","routerServerGlobal","RouterServerContextSymbol","relative","cwd","getNextConfigRuntime","revalidate","render404","logErrorWithOriginalStack","setCacheStatus","setReactDebugChannel","reactDebugChannel","sendErrorsToBrowser","logError","isPostpone","getResolveRoutes","ensureMiddleware","upgradeHandler","socket","head","hmrPrefix","normalizedAssetPrefix","URL","canParse","isHMRRequest","ensureLeadingSlash","onHMR","client","isLegacyClient","send","HMR_MESSAGE_SENT_TO_BROWSER","ISR_MANIFEST","data","appIsrManifest","MockedResponse","resWriter","closeUpgraded","close","agentRules"],"mappings":"AAAA,oDAAoD;;;;;+BAyF9BA;;;eAAAA;;;QAnFf;QACA;4DAES;6DACC;+DAC8C;yBACF;6BACjC;8DACL;6DACF;uBACO;8BACC;4BACA;8BACA;8BACoB;+BAChB;6BACc;+BACjB;kCACG;oEACJ;0CACY;6BACF;4BACZ;uCACW;0BACG;2BAOlC;oCAC4B;mCACD;uBACD;oCACE;qCACC;6BACR;oCACO;6BACJ;kCAIxB;uCAC+B;4BACJ;wBAEI;mCACJ;wBACL;yCACG;qCAIzB;yCAIA;8BACuD;iCAIvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEP,MAAMC,QAAQC,IAAAA,cAAU,EAAC;AACzB,MAAMC,aAAa,CAACC,WAClBA,YAAY,4CAA4CC,IAAI,CAACD;AAc/D,MAAME,kBAAwD,CAAC;AAExD,eAAeN,WAAWO,IAchC;QAktBSC,sBACUA,sBAqCZA,uBAEUA,uBAEVA,uBAEiBA,uBA8BrBA;IA3xBF,IAAI,CAACC,QAAQC,GAAG,CAACC,QAAQ,EAAE;QACzB,0BAA0B;QAC1BF,QAAQC,GAAG,CAACC,QAAQ,GAAGJ,KAAKK,GAAG,GAAG,gBAAgB;IACpD;IAEA,gDAAgD;IAChD,MAAMC,sBAAsBN,KAAKK,GAAG,GAAGE,IAAAA,0B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QACtE,sDAAsD;QACxD,EAAE,OAAO+C,KAAK;YACZ6D,QAAQzG,KAAK,CAAC,kCAAkC4C;YAChD8F,OAAO7I,GAAG;QACZ;IACF;IAEA,OAAO;QACL8C;QACA8F;QACA1B,QAAQzE,SAASyE,MAAM;QACvB6C;gBACE/P,kCAAAA;YAAAA,gCAAAA,uBAAAA,YAAa0E,OAAO,sBAApB1E,mCAAAA,qBAAsBwJ,WAAW,qBAAjCxJ,iCAAmCgQ,KAAK;QAC1C;QACA5N,SAAS3B,OAAO2B,OAAO;QACvB5B;QACAiN,iBAAiBhN,OAAOgN,eAAe;QACvCC,oBAAoBjN,OAAOiN,kBAAkB;QAC7CuC,YAAYxP,OAAOwP,UAAU;IAC/B;AACF","ignoreList":[0]} |
@@ -30,2 +30,8 @@ /** | ||
| export type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap; | ||
| /** | ||
| * Like `module.findSourceMap`, but returns the source map's payload without | ||
| * cloning it on every call. Callers must not mutate the returned payload. | ||
| * Throws like `module.findSourceMap` does on invalid source maps. | ||
| */ | ||
| export declare function findSourceMapPayload(sourceURL: string): ModernSourceMapPayload | undefined; | ||
| export declare function sourceMapIgnoreListsEverything(sourceMap: BasicSourceMapPayload): boolean; | ||
@@ -32,0 +38,0 @@ /** |
@@ -9,2 +9,3 @@ "use strict"; | ||
| findApplicableSourceMapPayload: null, | ||
| findSourceMapPayload: null, | ||
| findSourceMapURLDEV: null, | ||
@@ -31,2 +32,5 @@ ignoreListAnonymousStackFramesIfSandwiched: null, | ||
| }, | ||
| findSourceMapPayload: function() { | ||
| return findSourceMapPayload; | ||
| }, | ||
| findSourceMapURLDEV: function() { | ||
@@ -51,2 +55,18 @@ return findSourceMapURLDEV; | ||
| const findSourceMap = process.env.NEXT_RUNTIME === 'edge' ? noSourceMap : require('module').findSourceMap; | ||
| // `SourceMap#payload` deep-clones the payload on every access — expensive | ||
| // for large chunk maps — so the clone is shared per `SourceMap` instance, | ||
| // which Node.js memoizes per script. | ||
| const sourceMapPayloads = new WeakMap(); | ||
| function findSourceMapPayload(sourceURL) { | ||
| const sourceMap = findSourceMap(sourceURL); | ||
| if (sourceMap === undefined) { | ||
| return undefined; | ||
| } | ||
| let payload = sourceMapPayloads.get(sourceMap); | ||
| if (payload === undefined) { | ||
| payload = sourceMap.payload; | ||
| sourceMapPayloads.set(sourceMap, payload); | ||
| } | ||
| return payload; | ||
| } | ||
| function sourceMapIgnoreListsEverything(sourceMap) { | ||
@@ -100,9 +120,8 @@ return sourceMap.ignoreList !== undefined && sourceMap.sources.length === sourceMap.ignoreList.length; | ||
| // Make sure this doesn't adversely affect performance when CJS is used by Next.js. | ||
| const sourceMap = findSourceMap(sourceURL); | ||
| if (sourceMap === undefined) { | ||
| // No source map assoicated. | ||
| // TODO: Node.js types should reflect that `findSourceMap` can return `undefined`. | ||
| const payload = findSourceMapPayload(sourceURL); | ||
| if (payload === undefined) { | ||
| // No source map associated. | ||
| return true; | ||
| } | ||
| const sourceMapPayload = findApplicableSourceMapPayload(line1 - 1, column1 - 1, sourceMap.payload); | ||
| const sourceMapPayload = findApplicableSourceMapPayload(line1 - 1, column1 - 1, payload); | ||
| if (sourceMapPayload === undefined) { | ||
@@ -158,4 +177,3 @@ // No source map section applicable to the frame. | ||
| try { | ||
| var _findSourceMap; | ||
| sourceMapPayload = (_findSourceMap = findSourceMap(scriptNameOrSourceURL)) == null ? void 0 : _findSourceMap.payload; | ||
| sourceMapPayload = findSourceMapPayload(scriptNameOrSourceURL); | ||
| } catch (cause) { | ||
@@ -162,0 +180,0 @@ console.error(`${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/lib/source-maps.ts"],"sourcesContent":["import type { SourceMap } from 'module'\nimport { LRUCache } from './lru-cache'\n\nfunction noSourceMap(): SourceMap | undefined {\n return undefined\n}\n\n// Edge runtime does not implement `module`\nconst findSourceMap =\n process.env.NEXT_RUNTIME === 'edge'\n ? noSourceMap\n : (require('module') as typeof import('module')).findSourceMap\n\n/**\n * https://tc39.es/source-map/#index-map\n */\ninterface IndexSourceMapSection {\n offset: {\n line: number\n column: number\n }\n map: BasicSourceMapPayload\n}\n\n// TODO(veil): Upstream types\n/** https://tc39.es/ecma426/#sec-index-source-map */\ninterface IndexSourceMap {\n version: number\n file: string\n sections: IndexSourceMapSection[]\n}\n\n/** https://tc39.es/ecma426/#sec-source-map-format */\nexport interface BasicSourceMapPayload {\n version: number\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `file` is optional. */\n file: string\n sourceRoot?: string\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `sources[number]` can be `null`. */\n sources: Array<string>\n names: Array<string>\n mappings: string\n ignoreList?: number[]\n}\n\nexport type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap\n\nexport function sourceMapIgnoreListsEverything(\n sourceMap: BasicSourceMapPayload\n): boolean {\n return (\n sourceMap.ignoreList !== undefined &&\n sourceMap.sources.length === sourceMap.ignoreList.length\n )\n}\n\n/**\n * Finds the sourcemap payload applicable to a given frame.\n * Equal to the input unless an Index Source Map is used.\n * @param line0 - The line number of the frame, 0-based.\n * @param column0 - The column number of the frame, 0-based.\n */\nexport function findApplicableSourceMapPayload(\n line0: number,\n column0: number,\n payload: ModernSourceMapPayload\n): BasicSourceMapPayload | undefined {\n if ('sections' in payload) {\n if (payload.sections.length === 0) {\n return undefined\n }\n\n // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object\n // Therefore the last section that has an offset less than or equal to the frame is the applicable one.\n const sections = payload.sections\n let left = 0\n let right = sections.length - 1\n let result: IndexSourceMapSection | null = null\n\n while (left <= right) {\n // fast Math.floor\n const middle = ~~((left + right) / 2)\n const section = sections[middle]\n const offset = section.offset\n\n if (\n offset.line < line0 ||\n (offset.line === line0 && offset.column <= column0)\n ) {\n result = section\n left = middle + 1\n } else {\n right = middle - 1\n }\n }\n\n return result === null ? undefined : result.map\n } else {\n return payload\n }\n}\n\nconst didWarnAboutInvalidSourceMapDEV = new Set<string>()\n\nexport function filterStackFrameDEV(\n sourceURL: string,\n functionName: string,\n line1: number,\n column1: number\n): boolean {\n if (sourceURL === '') {\n // The default implementation filters out <anonymous> stack frames\n // but we want to retain them because current Server Components and\n // built-in Components in parent stacks don't have source location.\n // Filter out frames that show up in Promises to get good names in React's\n // Server Request track until we come up with a better heuristic.\n return functionName !== 'new Promise'\n }\n if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) {\n return false\n }\n try {\n // Node.js loads source maps eagerly so this call is cheap.\n // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules).\n // Make sure this doesn't adversely affect performance when CJS is used by Next.js.\n const sourceMap = findSourceMap(sourceURL)\n if (sourceMap === undefined) {\n // No source map assoicated.\n // TODO: Node.js types should reflect that `findSourceMap` can return `undefined`.\n return true\n }\n const sourceMapPayload = findApplicableSourceMapPayload(\n line1 - 1,\n column1 - 1,\n sourceMap.payload\n )\n if (sourceMapPayload === undefined) {\n // No source map section applicable to the frame.\n return true\n }\n return !sourceMapIgnoreListsEverything(sourceMapPayload)\n } catch (cause) {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: Share cache with patch-error-inspect\n if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) {\n didWarnAboutInvalidSourceMapDEV.add(sourceURL)\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`\n )\n }\n }\n\n return true\n }\n}\n\n// `scriptNameOrSourceURL` is what React forwards from the stack frame: the\n// script's `getScriptNameOrSourceURL()`, which for the server chunks we can\n// map is an absolute filesystem path, not a URL. The returned value is the\n// source map's URL (`file:` or `data:`).\ntype FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null\n// Find the URL of a source map using the bundler's API.\n// Shared via `globalThis` because this module is compiled both into the server\n// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`\n// (where the dev server registers the implementation), and each copy has its own\n// module state.\nconst bundlerFindSourceMapURLSymbol = Symbol.for(\n 'next.server.bundlerFindSourceMapURL'\n)\n\nexport function setBundlerFindSourceMapURLImplementation(\n findSourceMapURLImplementation: FindSourceMapURL\n): void {\n ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =\n findSourceMapURLImplementation\n}\n\nfunction bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {\n const implementation: FindSourceMapURL | undefined = (globalThis as any)[\n bundlerFindSourceMapURLSymbol\n ]\n return implementation === undefined\n ? null\n : implementation(scriptNameOrSourceURL)\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(\n 512 * 1024 * 1024,\n (url) =>\n url === invalidSourceMap\n ? // Ideally we'd account for key length. So we just guestimate a small source map\n // so that we don't create a huge cache with empty source maps.\n 8 * 1024\n : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength\n url.length\n)\nexport function findSourceMapURLDEV(\n scriptNameOrSourceURL: string\n): string | null {\n try {\n const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)\n if (bundlerSourceMapURL !== null) {\n return bundlerSourceMapURL\n }\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`\n )\n }\n\n // No bundler implementation (e.g. Webpack): inline the source map Node.js\n // knows as a `data:` URL.\n let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n if (sourceMapURL === undefined) {\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMap(scriptNameOrSourceURL)?.payload\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n }\n\n if (sourceMapPayload === undefined) {\n sourceMapURL = invalidSourceMap\n } else {\n // TODO: Might be more efficient to extract the relevant section from Index Maps.\n // Unclear if that search is worth the smaller payload we have to stringify.\n const sourceMapJSON = JSON.stringify(sourceMapPayload)\n const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString(\n 'base64'\n )\n sourceMapURL = `data:application/json;base64,${sourceMapURLData}`\n }\n\n sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL)\n }\n\n return sourceMapURL === invalidSourceMap ? null : sourceMapURL\n}\n\nexport function devirtualizeReactServerURL(sourceURL: string): string {\n if (sourceURL.startsWith('about://React/')) {\n // about://React/Server/file://<filename>?42 => file://<filename>\n const envIdx = sourceURL.indexOf('/', 'about://React/'.length)\n const suffixIdx = sourceURL.lastIndexOf('?')\n if (envIdx > -1 && suffixIdx > -1) {\n return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx))\n }\n }\n return sourceURL\n}\n\nfunction isAnonymousFrameLikelyJSNative(methodName: string): boolean {\n // Anonymous frames can also be produced in React parent stacks either from\n // host components or Server Components. We don't want to ignore those.\n // This could hide user-space methods that are named like native JS methods but\n // should you really do that?\n return (\n // e.g. JSON.parse\n methodName.startsWith('JSON.') ||\n // E.g. Promise.withResolves\n methodName.startsWith('Function.') ||\n // various JS built-ins\n methodName.startsWith('Promise.') ||\n methodName.startsWith('Array.') ||\n methodName.startsWith('Set.') ||\n methodName.startsWith('Map.')\n )\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched<Frame>(\n frames: Frame[],\n isAnonymousFrame: (frame: Frame) => boolean,\n isIgnoredFrame: (frame: Frame) => boolean,\n getMethodName: (frame: Frame) => string,\n /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */\n ignoreFrame: (frame: Frame) => void\n): void {\n for (let i = 1; i < frames.length; i++) {\n const currentFrame = frames[i]\n if (\n !(\n isAnonymousFrame(currentFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(currentFrame))\n )\n ) {\n continue\n }\n\n const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1])\n if (previousFrameIsIgnored && i < frames.length - 1) {\n let ignoreSandwich = false\n let j = i + 1\n for (j; j < frames.length; j++) {\n const nextFrame = frames[j]\n const nextFrameIsAnonymous =\n isAnonymousFrame(nextFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(nextFrame))\n if (nextFrameIsAnonymous) {\n continue\n }\n\n const nextFrameIsIgnored = isIgnoredFrame(nextFrame)\n if (nextFrameIsIgnored) {\n ignoreSandwich = true\n break\n }\n }\n\n if (ignoreSandwich) {\n for (i; i < j; i++) {\n ignoreFrame(frames[i])\n }\n }\n }\n }\n}\n"],"names":["devirtualizeReactServerURL","filterStackFrameDEV","findApplicableSourceMapPayload","findSourceMapURLDEV","ignoreListAnonymousStackFramesIfSandwiched","setBundlerFindSourceMapURLImplementation","sourceMapIgnoreListsEverything","noSourceMap","undefined","findSourceMap","process","env","NEXT_RUNTIME","require","sourceMap","ignoreList","sources","length","line0","column0","payload","sections","left","right","result","middle","section","offset","line","column","map","didWarnAboutInvalidSourceMapDEV","Set","sourceURL","functionName","line1","column1","startsWith","includes","sourceMapPayload","cause","NODE_ENV","has","add","console","error","bundlerFindSourceMapURLSymbol","Symbol","for","findSourceMapURLImplementation","globalThis","bundlerFindSourceMapURL","scriptNameOrSourceURL","implementation","invalidSourceMap","sourceMapURLs","LRUCache","url","bundlerSourceMapURL","sourceMapURL","get","sourceMapJSON","JSON","stringify","sourceMapURLData","Buffer","from","toString","set","envIdx","indexOf","suffixIdx","lastIndexOf","decodeURI","slice","isAnonymousFrameLikelyJSNative","methodName","frames","isAnonymousFrame","isIgnoredFrame","getMethodName","ignoreFrame","i","currentFrame","previousFrameIsIgnored","ignoreSandwich","j","nextFrame","nextFrameIsAnonymous","nextFrameIsIgnored"],"mappings":";;;;;;;;;;;;;;;;;;;;IAsPgBA,0BAA0B;eAA1BA;;IA5IAC,mBAAmB;eAAnBA;;IA1CAC,8BAA8B;eAA9BA;;IAy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{"version":3,"sources":["../../../src/server/lib/source-maps.ts"],"sourcesContent":["import type { SourceMap } from 'module'\nimport { LRUCache } from './lru-cache'\n\nfunction noSourceMap(): SourceMap | undefined {\n return undefined\n}\n\n// Edge runtime does not implement `module`\nconst findSourceMap =\n process.env.NEXT_RUNTIME === 'edge'\n ? noSourceMap\n : (require('module') as typeof import('module')).findSourceMap\n\n/**\n * https://tc39.es/source-map/#index-map\n */\ninterface IndexSourceMapSection {\n offset: {\n line: number\n column: number\n }\n map: BasicSourceMapPayload\n}\n\n// TODO(veil): Upstream types\n/** https://tc39.es/ecma426/#sec-index-source-map */\ninterface IndexSourceMap {\n version: number\n file: string\n sections: IndexSourceMapSection[]\n}\n\n/** https://tc39.es/ecma426/#sec-source-map-format */\nexport interface BasicSourceMapPayload {\n version: number\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `file` is optional. */\n file: string\n sourceRoot?: string\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `sources[number]` can be `null`. */\n sources: Array<string>\n names: Array<string>\n mappings: string\n ignoreList?: number[]\n}\n\nexport type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap\n\n// `SourceMap#payload` deep-clones the payload on every access — expensive\n// for large chunk maps — so the clone is shared per `SourceMap` instance,\n// which Node.js memoizes per script.\nconst sourceMapPayloads = new WeakMap<SourceMap, ModernSourceMapPayload>()\n\n/**\n * Like `module.findSourceMap`, but returns the source map's payload without\n * cloning it on every call. Callers must not mutate the returned payload.\n * Throws like `module.findSourceMap` does on invalid source maps.\n */\nexport function findSourceMapPayload(\n sourceURL: string\n): ModernSourceMapPayload | undefined {\n const sourceMap = findSourceMap(sourceURL)\n if (sourceMap === undefined) {\n return undefined\n }\n let payload = sourceMapPayloads.get(sourceMap)\n if (payload === undefined) {\n payload = sourceMap.payload as ModernSourceMapPayload\n sourceMapPayloads.set(sourceMap, payload)\n }\n return payload\n}\n\nexport function sourceMapIgnoreListsEverything(\n sourceMap: BasicSourceMapPayload\n): boolean {\n return (\n sourceMap.ignoreList !== undefined &&\n sourceMap.sources.length === sourceMap.ignoreList.length\n )\n}\n\n/**\n * Finds the sourcemap payload applicable to a given frame.\n * Equal to the input unless an Index Source Map is used.\n * @param line0 - The line number of the frame, 0-based.\n * @param column0 - The column number of the frame, 0-based.\n */\nexport function findApplicableSourceMapPayload(\n line0: number,\n column0: number,\n payload: ModernSourceMapPayload\n): BasicSourceMapPayload | undefined {\n if ('sections' in payload) {\n if (payload.sections.length === 0) {\n return undefined\n }\n\n // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object\n // Therefore the last section that has an offset less than or equal to the frame is the applicable one.\n const sections = payload.sections\n let left = 0\n let right = sections.length - 1\n let result: IndexSourceMapSection | null = null\n\n while (left <= right) {\n // fast Math.floor\n const middle = ~~((left + right) / 2)\n const section = sections[middle]\n const offset = section.offset\n\n if (\n offset.line < line0 ||\n (offset.line === line0 && offset.column <= column0)\n ) {\n result = section\n left = middle + 1\n } else {\n right = middle - 1\n }\n }\n\n return result === null ? undefined : result.map\n } else {\n return payload\n }\n}\n\nconst didWarnAboutInvalidSourceMapDEV = new Set<string>()\n\nexport function filterStackFrameDEV(\n sourceURL: string,\n functionName: string,\n line1: number,\n column1: number\n): boolean {\n if (sourceURL === '') {\n // The default implementation filters out <anonymous> stack frames\n // but we want to retain them because current Server Components and\n // built-in Components in parent stacks don't have source location.\n // Filter out frames that show up in Promises to get good names in React's\n // Server Request track until we come up with a better heuristic.\n return functionName !== 'new Promise'\n }\n if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) {\n return false\n }\n try {\n // Node.js loads source maps eagerly so this call is cheap.\n // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules).\n // Make sure this doesn't adversely affect performance when CJS is used by Next.js.\n const payload = findSourceMapPayload(sourceURL)\n if (payload === undefined) {\n // No source map associated.\n return true\n }\n const sourceMapPayload = findApplicableSourceMapPayload(\n line1 - 1,\n column1 - 1,\n payload\n )\n if (sourceMapPayload === undefined) {\n // No source map section applicable to the frame.\n return true\n }\n return !sourceMapIgnoreListsEverything(sourceMapPayload)\n } catch (cause) {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: Share cache with patch-error-inspect\n if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) {\n didWarnAboutInvalidSourceMapDEV.add(sourceURL)\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`\n )\n }\n }\n\n return true\n }\n}\n\n// `scriptNameOrSourceURL` is what React forwards from the stack frame: the\n// script's `getScriptNameOrSourceURL()`, which for the server chunks we can\n// map is an absolute filesystem path, not a URL. The returned value is the\n// source map's URL (`file:` or `data:`).\ntype FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null\n// Find the URL of a source map using the bundler's API.\n// Shared via `globalThis` because this module is compiled both into the server\n// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`\n// (where the dev server registers the implementation), and each copy has its own\n// module state.\nconst bundlerFindSourceMapURLSymbol = Symbol.for(\n 'next.server.bundlerFindSourceMapURL'\n)\n\nexport function setBundlerFindSourceMapURLImplementation(\n findSourceMapURLImplementation: FindSourceMapURL\n): void {\n ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =\n findSourceMapURLImplementation\n}\n\nfunction bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {\n const implementation: FindSourceMapURL | undefined = (globalThis as any)[\n bundlerFindSourceMapURLSymbol\n ]\n return implementation === undefined\n ? null\n : implementation(scriptNameOrSourceURL)\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(\n 512 * 1024 * 1024,\n (url) =>\n url === invalidSourceMap\n ? // Ideally we'd account for key length. So we just guestimate a small source map\n // so that we don't create a huge cache with empty source maps.\n 8 * 1024\n : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength\n url.length\n)\nexport function findSourceMapURLDEV(\n scriptNameOrSourceURL: string\n): string | null {\n try {\n const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)\n if (bundlerSourceMapURL !== null) {\n return bundlerSourceMapURL\n }\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`\n )\n }\n\n // No bundler implementation (e.g. Webpack): inline the source map Node.js\n // knows as a `data:` URL.\n let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n if (sourceMapURL === undefined) {\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMapPayload(scriptNameOrSourceURL)\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n }\n\n if (sourceMapPayload === undefined) {\n sourceMapURL = invalidSourceMap\n } else {\n // TODO: Might be more efficient to extract the relevant section from Index Maps.\n // Unclear if that search is worth the smaller payload we have to stringify.\n const sourceMapJSON = JSON.stringify(sourceMapPayload)\n const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString(\n 'base64'\n )\n sourceMapURL = `data:application/json;base64,${sourceMapURLData}`\n }\n\n sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL)\n }\n\n return sourceMapURL === invalidSourceMap ? null : sourceMapURL\n}\n\nexport function devirtualizeReactServerURL(sourceURL: string): string {\n if (sourceURL.startsWith('about://React/')) {\n // about://React/Server/file://<filename>?42 => file://<filename>\n const envIdx = sourceURL.indexOf('/', 'about://React/'.length)\n const suffixIdx = sourceURL.lastIndexOf('?')\n if (envIdx > -1 && suffixIdx > -1) {\n return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx))\n }\n }\n return sourceURL\n}\n\nfunction isAnonymousFrameLikelyJSNative(methodName: string): boolean {\n // Anonymous frames can also be produced in React parent stacks either from\n // host components or Server Components. We don't want to ignore those.\n // This could hide user-space methods that are named like native JS methods but\n // should you really do that?\n return (\n // e.g. JSON.parse\n methodName.startsWith('JSON.') ||\n // E.g. Promise.withResolves\n methodName.startsWith('Function.') ||\n // various JS built-ins\n methodName.startsWith('Promise.') ||\n methodName.startsWith('Array.') ||\n methodName.startsWith('Set.') ||\n methodName.startsWith('Map.')\n )\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched<Frame>(\n frames: Frame[],\n isAnonymousFrame: (frame: Frame) => boolean,\n isIgnoredFrame: (frame: Frame) => boolean,\n getMethodName: (frame: Frame) => string,\n /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */\n ignoreFrame: (frame: Frame) => void\n): void {\n for (let i = 1; i < frames.length; i++) {\n const currentFrame = frames[i]\n if (\n !(\n isAnonymousFrame(currentFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(currentFrame))\n )\n ) {\n continue\n }\n\n const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1])\n if (previousFrameIsIgnored && i < frames.length - 1) {\n let ignoreSandwich = false\n let j = i + 1\n for (j; j < frames.length; j++) {\n const nextFrame = frames[j]\n const nextFrameIsAnonymous =\n isAnonymousFrame(nextFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(nextFrame))\n if (nextFrameIsAnonymous) {\n continue\n }\n\n const nextFrameIsIgnored = isIgnoredFrame(nextFrame)\n if (nextFrameIsIgnored) {\n ignoreSandwich = true\n break\n }\n }\n\n if (ignoreSandwich) {\n for (i; i < j; i++) {\n ignoreFrame(frames[i])\n }\n }\n }\n }\n}\n"],"names":["devirtualizeReactServerURL","filterStackFrameDEV","findApplicableSourceMapPayload","findSourceMapPayload","findSourceMapURLDEV","ignoreListAnonymousStackFramesIfSandwiched","setBundlerFindSourceMapURLImplementation","sourceMapIgnoreListsEverything","noSourceMap","undefined","findSourceMap","process","env","NEXT_RUNTIME","require","sourceMapPayloads","WeakMap","sourceURL","sourceMap","payload","get","set","ignoreList","sources","length","line0","column0","sections","left","right","result","middle","section","offset","line","column","map","didWarnAboutInvalidSourceMapDEV","Set","functionName","line1","column1","startsWith","includes","sourceMapPayload","cause","NODE_ENV","has","add","console","error","bundlerFindSourceMapURLSymbol","Symbol","for","findSourceMapURLImplementation","globalThis","bundlerFindSourceMapURL","scriptNameOrSourceURL","implementation","invalidSourceMap","sourceMapURLs","LRUCache","url","bundlerSourceMapURL","sourceMapURL","sourceMapJSON","JSON","stringify","sourceMapURLData","Buffer","from","toString","envIdx","indexOf","suffixIdx","lastIndexOf","decodeURI","slice","isAnonymousFrameLikelyJSNative","methodName","frames","isAnonymousFrame","isIgnoredFrame","getMethodName","ignoreFrame","i","currentFrame","previousFrameIsIgnored","ignoreSandwich","j","nextFrame","nextFrameIsAnonymous","nextFrameIsIgnored"],"mappings":";;;;;;;;;;;;;;;;;;;;;IA8QgBA,0BAA0B;eAA1BA;;IA3IAC,mBAAmB;eAAnBA;;IA1CAC,8BAA8B;eAA9BA;;IA9BAC,oBAAoB;eAApBA;;IAsKAC,mBAAmB;eAAnBA;;IA2EAC,0CAA0C;eAA1CA;;IAtGAC,wCAAwC;eAAxCA;;IA5HAC,8BAA8B;eAA9BA;;;0BAzES;AAEzB,SAASC;IACP,OAAOC;AACT;AAEA,2CAA2C;AAC3C,MAAMC,gBACJC,QAAQC,GAAG,CAACC,YAAY,KAAK,SACzBL,cACA,AAACM,QAAQ,UAAsCJ,aAAa;AAsClE,0EAA0E;AAC1E,0EAA0E;AAC1E,qCAAqC;AACrC,MAAMK,oBAAoB,IAAIC;AAOvB,SAASb,qBACdc,SAAiB;IAEjB,MAAMC,YAAYR,cAAcO;IAChC,IAAIC,cAAcT,WAAW;QAC3B,OAAOA;IACT;IACA,IAAIU,UAAUJ,kBAAkBK,GAAG,CAACF;IACpC,IAAIC,YAAYV,WAAW;QACzBU,UAAUD,UAAUC,OAAO;QAC3BJ,kBAAkBM,GAAG,CAACH,WAAWC;IACnC;IACA,OAAOA;AACT;AAEO,SAASZ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C,WACtBqC,WAAWrC,UAAU,CAAC;AAE1B;AAEO,SAASrC,2CACd2E,MAAe,EACfC,gBAA2C,EAC3CC,cAAyC,EACzCC,aAAuC,EACvC,2HAA2H,GAC3HC,WAAmC;IAEnC,IAAK,IAAIC,IAAI,GAAGA,IAAIL,OAAOxD,MAAM,EAAE6D,IAAK;QACtC,MAAMC,eAAeN,MAAM,CAACK,EAAE;QAC9B,IACE,CACEJ,CAAAA,iBAAiBK,iBACjBR,+BAA+BK,cAAcG,cAAa,GAE5D;YACA;QACF;QAEA,MAAMC,yBAAyBL,eAAeF,MAAM,CAACK,IAAI,EAAE;QAC3D,IAAIE,0BAA0BF,IAAIL,OAAOxD,MAAM,GAAG,GAAG;YACnD,IAAIgE,iBAAiB;YACrB,IAAIC,IAAIJ,IAAI;YACZ,IAAKI,GAAGA,IAAIT,OAAOxD,MAAM,EAAEiE,IAAK;gBAC9B,MAAMC,YAAYV,MAAM,CAACS,EAAE;gBAC3B,MAAME,uBACJV,iBAAiBS,cACjBZ,+BAA+BK,cAAcO;gBAC/C,IAAIC,sBAAsB;oBACxB;gBACF;gBAEA,MAAMC,qBAAqBV,eAAeQ;gBAC1C,IAAIE,oBAAoB;oBACtBJ,iBAAiB;oBACjB;gBACF;YACF;YAEA,IAAIA,gBAAgB;gBAClB,IAAKH,GAAGA,IAAII,GAAGJ,IAAK;oBAClBD,YAAYJ,MAAM,CAACK,EAAE;gBACvB;YACF;QACF;IACF;AACF","ignoreList":[0]} |
@@ -180,3 +180,3 @@ // Start CPU profile if it wasn't already started. | ||
| let { port } = serverOptions; | ||
| process.title = `next-server (v${"16.3.0-canary.96"})`; | ||
| process.title = `next-server (v${"16.3.0-canary.97"})`; | ||
| let handlersReady = ()=>{}; | ||
@@ -183,0 +183,0 @@ let handlersError = ()=>{}; |
| import type { IncomingMessage, ServerResponse } from 'node:http'; | ||
| import type { AppType, DocumentType, NextComponentType } from '../shared/lib/utils'; | ||
| import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'; | ||
| import type { PageConfig, GetStaticPaths, GetServerSideProps, GetStaticProps } from '../types'; | ||
@@ -68,2 +69,9 @@ import type { RouteModule } from './route-modules/route-module'; | ||
| export declare function evalManifestWithRetries<T extends object>(manifestPath: string, attempts?: number): Promise<DeepReadonly<T>>; | ||
| /** | ||
| * Loads the client reference manifest that the bundler emitted for an app page, | ||
| * or returns undefined if there is none. Both the manifest file and the entry | ||
| * inside it are addressed by the page with `%5F` decoded back to `_`, so | ||
| * callers pass the page as-is and this resolves both. | ||
| */ | ||
| export declare function loadClientReferenceManifestForPage(distDir: string, page: string, attempts?: number): Promise<DeepReadonly<ClientReferenceManifest> | undefined>; | ||
| declare function loadComponentsImpl<N extends GenericComponentMod = GenericComponentMod>({ distDir, page, isAppPath, isDev, sriEnabled, needsManifestsForLegacyReasons, }: { | ||
@@ -70,0 +78,0 @@ distDir: string; |
@@ -7,2 +7,3 @@ "use strict"; | ||
| evalManifestWithRetries: null, | ||
| loadClientReferenceManifestForPage: null, | ||
| loadComponents: null, | ||
@@ -22,2 +23,5 @@ loadManifestWithRetries: null, | ||
| }, | ||
| loadClientReferenceManifestForPage: function() { | ||
| return loadClientReferenceManifestForPage; | ||
| }, | ||
| loadComponents: function() { | ||
@@ -73,3 +77,5 @@ return loadComponents; | ||
| } | ||
| async function tryLoadClientReferenceManifest(manifestPath, entryName, attempts) { | ||
| async function loadClientReferenceManifestForPage(distDir, page, attempts) { | ||
| const entryName = page.replace(/%5F/g, '_'); | ||
| const manifestPath = (0, _path.join)(/* turbopackIgnore: true */ distDir, 'server', 'app', entryName + '_' + _constants.CLIENT_REFERENCE_MANIFEST + '.js'); | ||
| try { | ||
@@ -121,3 +127,3 @@ const context = await evalManifestWithRetries(manifestPath, attempts); | ||
| isAppPath || process.env.TURBOPACK ? undefined : loadManifestWithRetries((0, _path.join)(/* turbopackIgnore: true */ distDir, `${_constants.DYNAMIC_CSS_MANIFEST}.json`), manifestLoadAttempts).catch(()=>undefined), | ||
| isAppPath && hasClientManifest ? tryLoadClientReferenceManifest((0, _path.join)(/* turbopackIgnore: true */ distDir, 'server', 'app', page.replace(/%5F/g, '_') + '_' + _constants.CLIENT_REFERENCE_MANIFEST + '.js'), page.replace(/%5F/g, '_'), manifestLoadAttempts) : undefined, | ||
| isAppPath && hasClientManifest ? loadClientReferenceManifestForPage(distDir, page, manifestLoadAttempts) : undefined, | ||
| isAppPath ? loadManifestWithRetries((0, _path.join)(/* turbopackIgnore: true */ distDir, 'server', _constants.SERVER_REFERENCE_MANIFEST + '.json'), manifestLoadAttempts).catch(()=>null) : null, | ||
@@ -124,0 +130,0 @@ sriEnabled ? loadManifestWithRetries((0, _path.join)(/* turbopackIgnore: true */ distDir, 'server', _constants.SUBRESOURCE_INTEGRITY_MANIFEST + '.json')).catch(()=>undefined) : undefined |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../src/server/load-components.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type {\n AppType,\n DocumentType,\n NextComponentType,\n} from '../shared/lib/utils'\nimport type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'\nimport type {\n PageConfig,\n GetStaticPaths,\n GetServerSideProps,\n GetStaticProps,\n} from '../types'\nimport type { RouteModule } from './route-modules/route-module'\nimport type { BuildManifest } from './get-page-files'\nimport type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin'\n\nimport {\n BUILD_MANIFEST,\n REACT_LOADABLE_MANIFEST,\n CLIENT_REFERENCE_MANIFEST,\n SERVER_REFERENCE_MANIFEST,\n DYNAMIC_CSS_MANIFEST,\n SUBRESOURCE_INTEGRITY_MANIFEST,\n} from '../shared/lib/constants'\nimport { join } from 'path'\nimport { requirePage } from './require'\nimport { interopDefault } from '../lib/interop-default'\nimport { getTracer } from './lib/trace/tracer'\nimport { LoadComponentsSpan } from './lib/trace/constants'\nimport { evalManifest, loadManifest } from './load-manifest.external'\nimport { wait } from '../lib/wait'\nimport { setManifestsSingleton } from './app-render/manifests-singleton'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { isStaticMetadataRoute } from '../lib/metadata/is-metadata-route'\n\nexport type ManifestItem = {\n id: number | string\n files: string[]\n}\n\nexport type ReactLoadableManifest = { [moduleId: string]: ManifestItem }\n/**\n * This manifest prevents removing server rendered <link> tags after client\n * navigation. This is only needed under `Pages dir && Production && Webpack`.\n * @see https://github.com/vercel/next.js/pull/72959\n */\nexport type DynamicCssManifest = string[]\n\n/**\n * A manifest entry type for the react-loadable-manifest.json.\n *\n * The whole manifest.json is a type of `Record<pathname, LoadableManifest>`\n * where pathname is a string-based key points to the path of the page contains\n * each dynamic imports.\n */\nexport interface LoadableManifest {\n [k: string]: { id: string | number; files: string[] }\n}\n\nexport type GenericComponentMod = {\n handler(\n req: IncomingMessage,\n res: ServerResponse,\n ctx: {\n waitUntil?: (prom: Promise<void>) => void\n }\n ): Promise<void | null>\n}\n\nexport type LoadComponentsReturnType<\n NextModule extends GenericComponentMod = GenericComponentMod,\n> = {\n Component: NextComponentType\n pageConfig: PageConfig\n buildManifest: DeepReadonly<BuildManifest>\n subresourceIntegrityManifest?: DeepReadonly<Record<string, string>>\n reactLoadableManifest: DeepReadonly<ReactLoadableManifest>\n dynamicCssManifest?: DeepReadonly<DynamicCssManifest>\n Document: DocumentType\n App: AppType\n getStaticProps?: GetStaticProps\n getStaticPaths?: GetStaticPaths\n getServerSideProps?: GetServerSideProps\n ComponentMod: NextModule\n routeModule: RouteModule\n isAppPath?: boolean\n page: string\n multiZoneDraftMode?: boolean\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function loadManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return loadManifest<T>(manifestPath)\n } catch (err) {\n attempts--\n if (attempts <= 0) throw err\n\n await wait(100)\n }\n }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts, or return undefined.\n */\nexport async function tryLoadManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n try {\n return await loadManifestWithRetries<T>(manifestPath, attempts)\n } catch (err) {\n return undefined\n }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function evalManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return evalManifest<T>(manifestPath)\n } catch (err) {\n attempts--\n if (attempts <= 0) throw err\n\n await wait(100)\n }\n }\n}\n\nasync function tryLoadClientReferenceManifest(\n manifestPath: string,\n entryName: string,\n attempts?: number\n): Promise<DeepReadonly<ClientReferenceManifest> | undefined> {\n try {\n const context = await evalManifestWithRetries<{\n __RSC_MANIFEST: { [key: string]: ClientReferenceManifest }\n }>(manifestPath, attempts)\n return context.__RSC_MANIFEST[entryName]\n } catch (err) {\n return undefined\n }\n}\n\nasync function loadComponentsImpl<\n N extends GenericComponentMod = GenericComponentMod,\n>({\n distDir,\n page,\n isAppPath,\n isDev,\n sriEnabled,\n // When route modules are used, which is the case for the server calls to loadComponents, it no longer needs manifest to be loaded here.\n // Static generation still needs the manifests to be loaded here.\n // In the future static generation will also use route modules, and we will remove this flag.\n needsManifestsForLegacyReasons,\n}: {\n distDir: string\n page: string\n isAppPath: boolean\n isDev: boolean\n sriEnabled: boolean\n needsManifestsForLegacyReasons: boolean\n}): Promise<LoadComponentsReturnType<N>> {\n let DocumentMod = {}\n let AppMod = {}\n if (!isAppPath) {\n ;[DocumentMod, AppMod] = await Promise.all([\n requirePage('/_document', distDir, false),\n requirePage('/_app', distDir, false),\n ])\n }\n\n if (needsManifestsForLegacyReasons) {\n // In dev mode we retry loading a manifest file to handle a race condition\n // that can occur while app and pages are compiling at the same time, and the\n // build-manifest is still being written to disk while an app path is\n // attempting to load.\n const manifestLoadAttempts = isDev ? 3 : 1\n\n let reactLoadableManifestPath: string\n if (!process.env.TURBOPACK) {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n REACT_LOADABLE_MANIFEST\n )\n } else if (isAppPath) {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'app',\n page,\n REACT_LOADABLE_MANIFEST\n )\n } else {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'pages',\n normalizePagePath(page),\n REACT_LOADABLE_MANIFEST\n )\n }\n\n // Make sure to avoid loading the manifest for static metadata routes for better performance.\n const hasClientManifest = !isStaticMetadataRoute(page)\n\n // Load the manifest files first\n //\n // Loading page-specific manifests shouldn't throw an error if the manifest couldn't be found, so\n // that the `requirePage` call below will throw the correct error in that case\n // (a `PageNotFoundError`).\n const [\n buildManifest,\n reactLoadableManifest,\n dynamicCssManifest,\n clientReferenceManifest,\n serverActionsManifest,\n subresourceIntegrityManifest,\n ] = await Promise.all([\n loadManifestWithRetries<BuildManifest>(\n join(/* turbopackIgnore: true */ distDir, BUILD_MANIFEST),\n manifestLoadAttempts\n ),\n tryLoadManifestWithRetries<ReactLoadableManifest>(\n reactLoadableManifestPath,\n manifestLoadAttempts\n ),\n // This manifest will only exist in Pages dir && Production && Webpack.\n isAppPath || process.env.TURBOPACK\n ? undefined\n : loadManifestWithRetries<DynamicCssManifest>(\n join(\n /* turbopackIgnore: true */ distDir,\n `${DYNAMIC_CSS_MANIFEST}.json`\n ),\n manifestLoadAttempts\n ).catch(() => undefined),\n isAppPath && hasClientManifest\n ? tryLoadClientReferenceManifest(\n join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'app',\n page.replace(/%5F/g, '_') +\n '_' +\n CLIENT_REFERENCE_MANIFEST +\n '.js'\n ),\n page.replace(/%5F/g, '_'),\n manifestLoadAttempts\n )\n : undefined,\n isAppPath\n ? loadManifestWithRetries<ActionManifest>(\n join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n SERVER_REFERENCE_MANIFEST + '.json'\n ),\n manifestLoadAttempts\n ).catch(() => null)\n : null,\n sriEnabled\n ? loadManifestWithRetries<DeepReadonly<Record<string, string>>>(\n join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n SUBRESOURCE_INTEGRITY_MANIFEST + '.json'\n )\n ).catch(() => undefined)\n : undefined,\n ])\n\n // Before requiring the actual page module, we have to set the reference\n // manifests to our global store so Server Action's encryption util can access\n // to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n\n const ComponentMod = await requirePage(page, distDir, isAppPath)\n\n const Component = interopDefault(ComponentMod)\n const Document = interopDefault(DocumentMod)\n const App = interopDefault(AppMod)\n\n const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =\n ComponentMod\n\n return {\n // @ts-expect-error this is indeed `{} || AppType` and not always `AppType`\n App,\n // @ts-expect-error this is indeed `{} || DocumentType` and not always `DocumentType`\n Document,\n Component,\n buildManifest,\n subresourceIntegrityManifest,\n reactLoadableManifest: reactLoadableManifest || {},\n dynamicCssManifest,\n pageConfig: ComponentMod.config || {},\n ComponentMod,\n getServerSideProps,\n getStaticProps,\n getStaticPaths,\n isAppPath,\n page,\n routeModule,\n }\n } else {\n const ComponentMod = await requirePage(page, distDir, isAppPath)\n\n const Component = interopDefault(ComponentMod)\n const Document = interopDefault(DocumentMod)\n const App = interopDefault(AppMod)\n\n const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =\n ComponentMod\n\n return {\n App,\n Document,\n Component,\n pageConfig: ComponentMod.config || {},\n ComponentMod,\n getServerSideProps,\n getStaticProps,\n getStaticPaths,\n isAppPath,\n page,\n routeModule,\n } as any // temporary `as any` to make TypeScript not fail so that the tests will run on the PR.\n }\n}\n\nexport const loadComponents = getTracer().wrap(\n LoadComponentsSpan.loadComponents,\n loadComponentsImpl\n)\n"],"names":["evalManifestWithRetries","loadComponents","loadManifestWithRetries","tryLoadManifestWithRetries","manifestPath","attempts","loadManifest","err","wait","undefined","evalManifest","tryLoadClientReferenceManifest","entryName","context","__RSC_MANIFEST","loadComponentsImpl","distDir","page","isAppPath","isDev","sriEnabled","needsManifestsForLegacyReasons","DocumentMod","AppMod","Promise","all","requirePage","manifestLoadAttempts","reactLoadableManifestPath","process","env","TURBOPACK","join","REACT_LOADABLE_MANIFEST","normalizePagePath","hasClientManifest","isStaticMetadataRoute","buildManifest","reactLoadableManifest","dynamicCssManifest","clientReferenceManifest","serverActionsManifest","subresourceIntegrityManifest","BUILD_MANIFEST","DYNAMIC_CSS_MANIFEST","catch","replace","CLIENT_REFERENCE_MANIFEST","SERVER_REFERENCE_MANIFEST","SUBRESOURCE_INTEGRITY_MANIFEST","setManifestsSingleton","ComponentMod","Component","interopDefault","Document","App","getServerSideProps","getStaticProps","getStaticPaths","routeModule","pageConfig","config","getTracer","wrap","LoadComponentsSpan"],"mappings":";;;;;;;;;;;;;;;;;IAgIsBA,uBAAuB;eAAvBA;;IAkOTC,cAAc;eAAdA;;IAnQSC,uBAAuB;eAAvBA;;IAmBAC,0BAA0B;eAA1BA;;;2BA1Ff;sBACc;yBACO;gCACG;wBACL;4BACS;sCACQ;sBACtB;oCACiB;mCAEJ;iCACI;AA4D/B,eAAeD,wBACpBE,YAAoB,EACpBC,WAAW,CAAC;IAEZ,MAAO,KAAM;QACX,IAAI;YACF,OAAOC,IAAAA,kCAAY,EAAIF;QACzB,EAAE,OAAOG,KAAK;YACZF;YACA,IAAIA,YAAY,GAAG,MAAME;YAEzB,MAAMC,IAAAA,UAAI,EAAC;QACb;IACF;AACF;AAKO,eAAeL,2BACpBC,YAAoB,EACpBC,WAAW,CAAC;IAEZ,IAAI;QACF,OAAO,MAAMH,wBAA2BE,cAAcC;IACxD,EAAE,OAAOE,KAAK;QACZ,OAAOE;IACT;AACF;AAKO,eAAeT,wBACpBI,YAAoB,EACpBC,WAAW,CAAC;IAEZ,MAAO,KAAM;QACX,IAAI;YACF,OAAOK,IAAAA,kCAAY,EAAIN;QACzB,EAAE,OAAOG,KAAK;YACZF;YACA,IAAIA,YA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iC,kBAAkB,EAAEC,cAAc,EAAEC,cAAc,EAAEC,WAAW,EAAE,GACvER;QAEF,OAAO;YACL,2EAA2E;YAC3EI;YACA,qFAAqF;YACrFD;YACAF;YACAf;YACAK;YACAJ,uBAAuBA,yBAAyB,CAAC;YACjDC;YACAqB,YAAYT,aAAaU,MAAM,IAAI,CAAC;YACpCV;YACAK;YACAC;YACAC;YACAxC;YACAD;YACA0C;QACF;IACF,OAAO;QACL,MAAMR,eAAe,MAAMzB,IAAAA,oBAAW,EAACT,MAAMD,SAASE;QAEtD,MAAMkC,YAAYC,IAAAA,8BAAc,EAACF;QACjC,MAAMG,WAAWD,IAAAA,8BAAc,EAAC/B;QAChC,MAAMiC,MAAMF,IAAAA,8BAAc,EAAC9B;QAE3B,MAAM,EAAEiC,kBAAkB,EAAEC,cAAc,EAAEC,cAAc,EAAEC,WAAW,EAAE,GACvER;QAEF,OAAO;YACLI;YACAD;YACAF;YACAQ,YAAYT,aAAaU,MAAM,IAAI,CAAC;YACpCV;YACAK;YACAC;YACAC;YACAxC;YACAD;YACA0C;QACF,GAAS,uFAAuF;IAClG;AACF;AAEO,MAAM1D,iBAAiB6D,IAAAA,iBAAS,IAAGC,IAAI,CAC5CC,8BAAkB,CAAC/D,cAAc,EACjCc","ignoreList":[0]} | ||
| {"version":3,"sources":["../../src/server/load-components.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type {\n AppType,\n DocumentType,\n NextComponentType,\n} from '../shared/lib/utils'\nimport type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'\nimport type {\n PageConfig,\n GetStaticPaths,\n GetServerSideProps,\n GetStaticProps,\n} from '../types'\nimport type { RouteModule } from './route-modules/route-module'\nimport type { BuildManifest } from './get-page-files'\nimport type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin'\n\nimport {\n BUILD_MANIFEST,\n REACT_LOADABLE_MANIFEST,\n CLIENT_REFERENCE_MANIFEST,\n SERVER_REFERENCE_MANIFEST,\n DYNAMIC_CSS_MANIFEST,\n SUBRESOURCE_INTEGRITY_MANIFEST,\n} from '../shared/lib/constants'\nimport { join } from 'path'\nimport { requirePage } from './require'\nimport { interopDefault } from '../lib/interop-default'\nimport { getTracer } from './lib/trace/tracer'\nimport { LoadComponentsSpan } from './lib/trace/constants'\nimport { evalManifest, loadManifest } from './load-manifest.external'\nimport { wait } from '../lib/wait'\nimport { setManifestsSingleton } from './app-render/manifests-singleton'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { isStaticMetadataRoute } from '../lib/metadata/is-metadata-route'\n\nexport type ManifestItem = {\n id: number | string\n files: string[]\n}\n\nexport type ReactLoadableManifest = { [moduleId: string]: ManifestItem }\n/**\n * This manifest prevents removing server rendered <link> tags after client\n * navigation. This is only needed under `Pages dir && Production && Webpack`.\n * @see https://github.com/vercel/next.js/pull/72959\n */\nexport type DynamicCssManifest = string[]\n\n/**\n * A manifest entry type for the react-loadable-manifest.json.\n *\n * The whole manifest.json is a type of `Record<pathname, LoadableManifest>`\n * where pathname is a string-based key points to the path of the page contains\n * each dynamic imports.\n */\nexport interface LoadableManifest {\n [k: string]: { id: string | number; files: string[] }\n}\n\nexport type GenericComponentMod = {\n handler(\n req: IncomingMessage,\n res: ServerResponse,\n ctx: {\n waitUntil?: (prom: Promise<void>) => void\n }\n ): Promise<void | null>\n}\n\nexport type LoadComponentsReturnType<\n NextModule extends GenericComponentMod = GenericComponentMod,\n> = {\n Component: NextComponentType\n pageConfig: PageConfig\n buildManifest: DeepReadonly<BuildManifest>\n subresourceIntegrityManifest?: DeepReadonly<Record<string, string>>\n reactLoadableManifest: DeepReadonly<ReactLoadableManifest>\n dynamicCssManifest?: DeepReadonly<DynamicCssManifest>\n Document: DocumentType\n App: AppType\n getStaticProps?: GetStaticProps\n getStaticPaths?: GetStaticPaths\n getServerSideProps?: GetServerSideProps\n ComponentMod: NextModule\n routeModule: RouteModule\n isAppPath?: boolean\n page: string\n multiZoneDraftMode?: boolean\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function loadManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return loadManifest<T>(manifestPath)\n } catch (err) {\n attempts--\n if (attempts <= 0) throw err\n\n await wait(100)\n }\n }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts, or return undefined.\n */\nexport async function tryLoadManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n try {\n return await loadManifestWithRetries<T>(manifestPath, attempts)\n } catch (err) {\n return undefined\n }\n}\n\n/**\n * Load manifest file with retries, defaults to 3 attempts.\n */\nexport async function evalManifestWithRetries<T extends object>(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return evalManifest<T>(manifestPath)\n } catch (err) {\n attempts--\n if (attempts <= 0) throw err\n\n await wait(100)\n }\n }\n}\n\n/**\n * Loads the client reference manifest that the bundler emitted for an app page,\n * or returns undefined if there is none. Both the manifest file and the entry\n * inside it are addressed by the page with `%5F` decoded back to `_`, so\n * callers pass the page as-is and this resolves both.\n */\nexport async function loadClientReferenceManifestForPage(\n distDir: string,\n page: string,\n attempts?: number\n): Promise<DeepReadonly<ClientReferenceManifest> | undefined> {\n const entryName = page.replace(/%5F/g, '_')\n\n const manifestPath = join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'app',\n entryName + '_' + CLIENT_REFERENCE_MANIFEST + '.js'\n )\n\n try {\n const context = await evalManifestWithRetries<{\n __RSC_MANIFEST: { [key: string]: ClientReferenceManifest }\n }>(manifestPath, attempts)\n return context.__RSC_MANIFEST[entryName]\n } catch (err) {\n return undefined\n }\n}\n\nasync function loadComponentsImpl<\n N extends GenericComponentMod = GenericComponentMod,\n>({\n distDir,\n page,\n isAppPath,\n isDev,\n sriEnabled,\n // When route modules are used, which is the case for the server calls to loadComponents, it no longer needs manifest to be loaded here.\n // Static generation still needs the manifests to be loaded here.\n // In the future static generation will also use route modules, and we will remove this flag.\n needsManifestsForLegacyReasons,\n}: {\n distDir: string\n page: string\n isAppPath: boolean\n isDev: boolean\n sriEnabled: boolean\n needsManifestsForLegacyReasons: boolean\n}): Promise<LoadComponentsReturnType<N>> {\n let DocumentMod = {}\n let AppMod = {}\n if (!isAppPath) {\n ;[DocumentMod, AppMod] = await Promise.all([\n requirePage('/_document', distDir, false),\n requirePage('/_app', distDir, false),\n ])\n }\n\n if (needsManifestsForLegacyReasons) {\n // In dev mode we retry loading a manifest file to handle a race condition\n // that can occur while app and pages are compiling at the same time, and the\n // build-manifest is still being written to disk while an app path is\n // attempting to load.\n const manifestLoadAttempts = isDev ? 3 : 1\n\n let reactLoadableManifestPath: string\n if (!process.env.TURBOPACK) {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n REACT_LOADABLE_MANIFEST\n )\n } else if (isAppPath) {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'app',\n page,\n REACT_LOADABLE_MANIFEST\n )\n } else {\n reactLoadableManifestPath = join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n 'pages',\n normalizePagePath(page),\n REACT_LOADABLE_MANIFEST\n )\n }\n\n // Make sure to avoid loading the manifest for static metadata routes for better performance.\n const hasClientManifest = !isStaticMetadataRoute(page)\n\n // Load the manifest files first\n //\n // Loading page-specific manifests shouldn't throw an error if the manifest couldn't be found, so\n // that the `requirePage` call below will throw the correct error in that case\n // (a `PageNotFoundError`).\n const [\n buildManifest,\n reactLoadableManifest,\n dynamicCssManifest,\n clientReferenceManifest,\n serverActionsManifest,\n subresourceIntegrityManifest,\n ] = await Promise.all([\n loadManifestWithRetries<BuildManifest>(\n join(/* turbopackIgnore: true */ distDir, BUILD_MANIFEST),\n manifestLoadAttempts\n ),\n tryLoadManifestWithRetries<ReactLoadableManifest>(\n reactLoadableManifestPath,\n manifestLoadAttempts\n ),\n // This manifest will only exist in Pages dir && Production && Webpack.\n isAppPath || process.env.TURBOPACK\n ? undefined\n : loadManifestWithRetries<DynamicCssManifest>(\n join(\n /* turbopackIgnore: true */ distDir,\n `${DYNAMIC_CSS_MANIFEST}.json`\n ),\n manifestLoadAttempts\n ).catch(() => undefined),\n isAppPath && hasClientManifest\n ? loadClientReferenceManifestForPage(\n distDir,\n page,\n manifestLoadAttempts\n )\n : undefined,\n isAppPath\n ? loadManifestWithRetries<ActionManifest>(\n join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n SERVER_REFERENCE_MANIFEST + '.json'\n ),\n manifestLoadAttempts\n ).catch(() => null)\n : null,\n sriEnabled\n ? loadManifestWithRetries<DeepReadonly<Record<string, string>>>(\n join(\n /* turbopackIgnore: true */ distDir,\n 'server',\n SUBRESOURCE_INTEGRITY_MANIFEST + '.json'\n )\n ).catch(() => undefined)\n : undefined,\n ])\n\n // Before requiring the actual page module, we have to set the reference\n // manifests to our global store so Server Action's encryption util can access\n // to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n\n const ComponentMod = await requirePage(page, distDir, isAppPath)\n\n const Component = interopDefault(ComponentMod)\n const Document = interopDefault(DocumentMod)\n const App = interopDefault(AppMod)\n\n const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =\n ComponentMod\n\n return {\n // @ts-expect-error this is indeed `{} || AppType` and not always `AppType`\n App,\n // @ts-expect-error this is indeed `{} || DocumentType` and not always `DocumentType`\n Document,\n Component,\n buildManifest,\n subresourceIntegrityManifest,\n reactLoadableManifest: reactLoadableManifest || {},\n dynamicCssManifest,\n pageConfig: ComponentMod.config || {},\n ComponentMod,\n getServerSideProps,\n getStaticProps,\n getStaticPaths,\n isAppPath,\n page,\n routeModule,\n }\n } else {\n const ComponentMod = await requirePage(page, distDir, isAppPath)\n\n const Component = interopDefault(ComponentMod)\n const Document = interopDefault(DocumentMod)\n const App = interopDefault(AppMod)\n\n const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =\n ComponentMod\n\n return {\n App,\n Document,\n Component,\n pageConfig: ComponentMod.config || {},\n ComponentMod,\n getServerSideProps,\n getStaticProps,\n getStaticPaths,\n isAppPath,\n page,\n routeModule,\n } as any // temporary `as any` to make TypeScript not fail so that the tests will run on the PR.\n }\n}\n\nexport const loadComponents = getTracer().wrap(\n LoadComponentsSpan.loadComponents,\n loadComponentsImpl\n)\n"],"names":["evalManifestWithRetries","loadClientReferenceManifestForPage","loadComponents","loadManifestWithRetries","tryLoadManifestWithRetries","manifestPath","attempts","loadManifest","err","wait","undefined","evalManifest","distDir","page","entryName","replace","join","CLIENT_REFERENCE_MANIFEST","context","__RSC_MANIFEST","loadComponentsImpl","isAppPath","isDev","sriEnabled","needsManifestsForLegacyReasons","DocumentMod","AppMod","Promise","all","requirePage","manifestLoadAttempts","reactLoadableManifestPath","process","env","TURBOPACK","REACT_LOADABLE_MANIFEST","normalizePagePath","hasClientManifest","isStaticMetadataRoute","buildManifest","reactLoadableManifest","dynamicCssManifest","clientReferenceManifest","serverActionsManifest","subresourceIntegrityManifest","BUILD_MANIFEST","DYNAMIC_CSS_MANIFEST","catch","SERVER_REFERENCE_MANIFEST","SUBRESOURCE_INTEGRITY_MANIFEST","setManifestsSingleton","ComponentMod","Component","interopDefault","Document","App","getServerSideProps","getStaticProps","getStaticPaths","routeModule","pageConfig","config","getTracer","wrap","LoadComponentsSpan"],"mappings":";;;;;;;;;;;;;;;;;;IAgIsBA,uBAAuB;eAAvBA;;IAsBAC,kCAAkC;eAAlCA;;IAmNTC,cAAc;eAAdA;;IA1QSC,uBAAuB;eAAvBA;;IAmBAC,0BAA0B;eAA1BA;;;2BA1Ff;sBACc;yBACO;gCACG;wBACL;4BACS;sCACQ;sBACtB;oCACiB;mCAEJ;iCACI;AA4D/B,eAAeD,wBACpBE,YAAoB,EACpBC,WAAW,CAAC;IAEZ,MAAO,KAAM;QACX,IAAI;YACF,OAAOC,IAAAA,kCA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 -31,3 +31,2 @@ "use strict"; | ||
| }); | ||
| const _module = require("module"); | ||
| const _path = /*#__PURE__*/ _interop_require_wildcard(require("path")); | ||
@@ -85,11 +84,32 @@ const _url = /*#__PURE__*/ _interop_require_wildcard(require("url")); | ||
| // TODO(veil): Set from Webpack as well | ||
| let bundlerFindSourceMapPayload = ()=>undefined; | ||
| // | ||
| // Stored on `globalThis` for the same reason as the code frame renderer below: | ||
| // this module is bundled into several runtimes that each get their own copy, | ||
| // and the copy that installs the implementation is not necessarily the one that | ||
| // symbolicates a frame. The dev validation worker depends on that, because it | ||
| // installs its implementation from the worker bundle while the frames are | ||
| // symbolicated by the app-page bundle's copy. | ||
| const BUNDLER_FIND_SOURCE_MAP = Symbol.for('next.dev.bundlerFindSourceMap'); | ||
| function setBundlerFindSourceMapImplementation(findSourceMapImplementation) { | ||
| bundlerFindSourceMapPayload = findSourceMapImplementation; | ||
| ; | ||
| globalThis[BUNDLER_FIND_SOURCE_MAP] = findSourceMapImplementation; | ||
| } | ||
| let codeFrameRenderer; | ||
| function bundlerFindSourceMapPayload(sourceURL) { | ||
| var _globalThis_BUNDLER_FIND_SOURCE_MAP; | ||
| return (_globalThis_BUNDLER_FIND_SOURCE_MAP = globalThis[BUNDLER_FIND_SOURCE_MAP]) == null ? void 0 : _globalThis_BUNDLER_FIND_SOURCE_MAP.call(globalThis, sourceURL); | ||
| } | ||
| // The code-frame renderer is stored on `globalThis` rather than in a module | ||
| // variable because this module is bundled into several runtimes (the dev | ||
| // server, the app-page runtime bundle, and the dev worker bundles) that each | ||
| // get their own copy. `Error.prepareStackTrace` is a single process-global, so | ||
| // whichever copy patched it last is the one that renders errors, which may not | ||
| // be the copy `setCodeFrameRenderer` was called on. Sharing the renderer | ||
| // through a `globalThis` symbol lets any copy install it and any copy read it. | ||
| const CODE_FRAME_RENDERER = Symbol.for('next.dev.codeFrameRenderer'); | ||
| function setCodeFrameRenderer(renderer) { | ||
| codeFrameRenderer = renderer; | ||
| ; | ||
| globalThis[CODE_FRAME_RENDERER] = renderer; | ||
| } | ||
| function getOriginalCodeFrame(frame, source, colors = process.stdout.isTTY) { | ||
| const codeFrameRenderer = globalThis[CODE_FRAME_RENDERER]; | ||
| if (!codeFrameRenderer) { | ||
@@ -101,2 +121,23 @@ // No renderer available - gracefully degrade | ||
| } | ||
| // Constructing a consumer indexes the whole payload — expensive for large | ||
| // chunk maps and previously paid per frame — so consumers are shared across | ||
| // all frames and errors whose lookups returned the same payload. The inner | ||
| // key is the URL the consumer resolves relative `sources` against. | ||
| const sourceMapConsumers = new WeakMap(); | ||
| function getOrCreateSourceMapConsumer(payload, sourceMapURL) { | ||
| let consumersByURL = sourceMapConsumers.get(payload); | ||
| let consumer = consumersByURL == null ? void 0 : consumersByURL.get(sourceMapURL); | ||
| if (consumer === undefined) { | ||
| consumer = new _sourcemap.SourceMapConsumer(payload, // @ts-expect-error: our typings don't include this parameter but it is here. | ||
| sourceMapURL); | ||
| if (consumersByURL === undefined) { | ||
| consumersByURL = new Map(); | ||
| // Throws for payloads that aren't objects; those are invalid source | ||
| // maps anyway, and the caller reports them. | ||
| sourceMapConsumers.set(payload, consumersByURL); | ||
| } | ||
| consumersByURL.set(sourceMapURL, consumer); | ||
| } | ||
| return consumer; | ||
| } | ||
| function frameToString(methodName, sourceURL, line1, column1) { | ||
@@ -186,4 +227,16 @@ let sourceLocation = line1 !== null ? `:${line1}` : ''; | ||
| try { | ||
| const sourceMap = (0, _module.findSourceMap)(sourceURL); | ||
| maybeSourceMapPayload = sourceMap == null ? void 0 : sourceMap.payload; | ||
| maybeSourceMapPayload = (0, _sourcemaps.findSourceMapPayload)(sourceURL); | ||
| if (maybeSourceMapPayload === undefined && sourceURL.startsWith('file://')) { | ||
| // Devirtualizing React's fake frame URL decodes the path, while Node.js | ||
| // keys its source map cache by the `pathToFileURL` encoding of the same | ||
| // path, so a path containing characters that encoding escapes (such as | ||
| // the brackets in Turbopack's `[root-of-the-server]` chunks) misses | ||
| // above. Node.js also accepts the plain path, which is unambiguous for | ||
| // both interpretations, so retry with that before giving up. | ||
| // | ||
| // TODO(veil): Making React's fake frame URLs reversible, as proposed in | ||
| // https://github.com/react/react/pull/37105, would let the first lookup | ||
| // succeed on its own and retire this retry. | ||
| maybeSourceMapPayload = (0, _sourcemaps.findSourceMapPayload)(_url.fileURLToPath(sourceURL)); | ||
| } | ||
| } catch (cause) { | ||
@@ -221,4 +274,3 @@ // We should not log an actual error instance here because that will re-enter | ||
| const sourceMapURL = sourceURL + '.map'; | ||
| sourceMapConsumer = new _sourcemap.SourceMapConsumer(sourceMapPayload, // @ts-expect-error: our typings don't include this parameter but it is here. | ||
| sourceMapURL); | ||
| sourceMapConsumer = getOrCreateSourceMapConsumer(sourceMapPayload, sourceMapURL); | ||
| } catch (cause) { | ||
@@ -225,0 +277,0 @@ // We should not log an actual error instance here because that will re-enter |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../src/server/patch-error-inspect.ts"],"sourcesContent":["import { findSourceMap as nativeFindSourceMap } from 'module'\nimport * as path from 'path'\nimport * as url from 'url'\nimport type * as util from 'util'\nimport { SourceMapConsumer as SyncSourceMapConsumer } from 'next/dist/compiled/source-map'\nimport {\n type ModernSourceMapPayload,\n devirtualizeReactServerURL,\n findApplicableSourceMapPayload,\n ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric,\n sourceMapIgnoreListsEverything,\n} from './lib/source-maps'\nimport { parseStack, type StackFrame } from './lib/parse-stack'\nimport type { IgnorableStackFrame } from '../next-devtools/server/shared'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { dim, italic } from '../lib/picocolors'\n\ntype FindSourceMapPayload = (\n sourceURL: string\n) => ModernSourceMapPayload | undefined\n// Find a source map using the bundler's API.\n// This is only a fallback for when Node.js fails to due to bugs e.g. https://github.com/nodejs/node/issues/52102\n// TODO: Remove once all supported Node.js versions are fixed.\n// TODO(veil): Set from Webpack as well\nlet bundlerFindSourceMapPayload: FindSourceMapPayload = () => undefined\n\nexport function setBundlerFindSourceMapImplementation(\n findSourceMapImplementation: FindSourceMapPayload\n): void {\n bundlerFindSourceMapPayload = findSourceMapImplementation\n}\n\n// Code frame renderer - injected by dev/build to avoid hard dependency on native bindings\ntype CodeFrameRenderer = (\n frame: IgnorableStackFrame,\n source: string | null,\n colors: boolean\n) => string | null\n\nlet codeFrameRenderer: CodeFrameRenderer | undefined\n\nexport function setCodeFrameRenderer(renderer: CodeFrameRenderer): void {\n codeFrameRenderer = renderer\n}\n\nfunction getOriginalCodeFrame(\n frame: IgnorableStackFrame,\n source: string | null,\n colors: boolean = process.stdout.isTTY\n): string | null {\n if (!codeFrameRenderer) {\n // No renderer available - gracefully degrade\n return null\n }\n return codeFrameRenderer(frame, source, colors)\n}\n\ntype SourceMapCache = Map<\n string,\n null | { map: SyncSourceMapConsumer; payload: ModernSourceMapPayload }\n>\n\nfunction frameToString(\n methodName: string | null,\n sourceURL: string | null,\n line1: number | null,\n column1: number | null\n): string {\n let sourceLocation = line1 !== null ? `:${line1}` : ''\n if (column1 !== null && sourceLocation !== '') {\n sourceLocation += `:${column1}`\n }\n\n let fileLocation: string | null\n if (\n sourceURL !== null &&\n sourceURL.startsWith('file://') &&\n URL.canParse(sourceURL)\n ) {\n // If not relative to CWD, the path is ambiguous to IDEs and clicking will prompt to select the file first.\n // In a multi-app repo, this leads to potentially larger file names but will make clicking snappy.\n // There's no tradeoff for the cases where `dir` in `next dev [dir]` is omitted\n // since relative to cwd is both the shortest and snappiest.\n fileLocation = path.relative(process.cwd(), url.fileURLToPath(sourceURL))\n } else if (sourceURL !== null && sourceURL.startsWith('/')) {\n fileLocation = path.relative(process.cwd(), sourceURL)\n } else {\n fileLocation = sourceURL\n }\n\n return methodName\n ? ` at ${methodName} (${fileLocation}${sourceLocation})`\n : ` at ${fileLocation}${sourceLocation}`\n}\n\nfunction computeErrorName(error: Error): string {\n // TODO: Node.js seems to use a different algorithm\n // class ReadonlyRequestCookiesError extends Error {}` would read `ReadonlyRequestCookiesError: [...]`\n // in the stack i.e. seems like under certain conditions it favors the constructor name.\n return error.name || 'Error'\n}\n\nfunction prepareUnsourcemappedStackTrace(\n error: Error,\n structuredStackTrace: any[]\n): string {\n const name = computeErrorName(error)\n const message = error.message || ''\n let stack = name + ': ' + message\n for (let i = 0; i < structuredStackTrace.length; i++) {\n stack += '\\n at ' + structuredStackTrace[i].toString()\n }\n return stack\n}\n\nfunction shouldIgnoreListGeneratedFrame(file: string): boolean {\n return file.startsWith('node:') || file.includes('node_modules')\n}\n\nfunction shouldIgnoreListOriginalFrame(file: string): boolean {\n return file.includes('node_modules')\n}\n\ninterface SourcemappableStackFrame extends StackFrame {\n file: NonNullable<StackFrame['file']>\n}\n\ninterface SourceMappedFrame {\n stack: IgnorableStackFrame\n // DEV only\n code: string | null\n}\n\nfunction createUnsourcemappedFrame(\n frame: SourcemappableStackFrame\n): SourceMappedFrame {\n return {\n stack: {\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n arguments: frame.arguments,\n ignored: shouldIgnoreListGeneratedFrame(frame.file),\n },\n code: null,\n }\n}\n\nfunction ignoreListAnonymousStackFramesIfSandwiched(\n sourceMappedFrames: Array<{\n stack: IgnorableStackFrame\n code: string | null\n }>\n) {\n return ignoreListAnonymousStackFramesIfSandwichedGeneric(\n sourceMappedFrames,\n (frame) => frame.stack.file === '<anonymous>',\n (frame) => frame.stack.ignored,\n (frame) => frame.stack.methodName,\n (frame) => {\n frame.stack.ignored = true\n }\n )\n}\n\n/**\n * @param frame\n * @param sourceMapCache\n * @returns The original frame if not sourcemapped.\n */\nfunction getSourcemappedFrameIfPossible(\n frame: SourcemappableStackFrame,\n sourceMapCache: SourceMapCache,\n inspectOptions: util.InspectOptions\n): {\n stack: IgnorableStackFrame\n code: string | null\n} {\n const sourceMapCacheEntry = sourceMapCache.get(frame.file)\n let sourceMapConsumer: SyncSourceMapConsumer\n let sourceMapPayload: ModernSourceMapPayload\n if (sourceMapCacheEntry === undefined) {\n // Fake frame scripts (`about://React/Server/file:///path/to/chunk.js?42`)\n // have their positions padded to match the underlying chunk, so they\n // resolve via the chunk's source map.\n let sourceURL = devirtualizeReactServerURL(frame.file)\n // e.g. \"/Users/foo/APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\"\n // or \"C:\\Users\\foo\\APP\\.next\\server\\chunks\\ssr\\[root-of-the-server]__2934a0._.js\"\n // will be keyed by Node.js as \"file:///APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\".\n // This is likely caused by `callsite.toString()` in `Error.prepareStackTrace converting file URLs to paths.\n //\n // But frame.file might also be \"webpack-internal:///(rsc)/./app/bad-sourcemap/page.js\" or\n // \"<anonymous>\" or \"node:internal/process/task_queues\" here\n if (path.isAbsolute(sourceURL)) {\n sourceURL = url.pathToFileURL(sourceURL).toString()\n }\n let maybeSourceMapPayload: ModernSourceMapPayload | undefined\n try {\n const sourceMap = nativeFindSourceMap(sourceURL)\n maybeSourceMapPayload = sourceMap?.payload\n } catch (cause) {\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n // If loading fails once, it'll fail every time.\n // So set the cache to avoid duplicate errors.\n sourceMapCache.set(frame.file, null)\n // Don't even fall back to the bundler because it might be not as strict\n // with regards to parsing and then we fail later once we consume the\n // source map payload.\n // This essentially avoids a redundant error where we fail here and then\n // later on consumption because the bundler just handed back an invalid\n // source map.\n return createUnsourcemappedFrame(frame)\n }\n if (maybeSourceMapPayload === undefined) {\n maybeSourceMapPayload = bundlerFindSourceMapPayload(sourceURL)\n }\n\n if (maybeSourceMapPayload === undefined) {\n return createUnsourcemappedFrame(frame)\n }\n sourceMapPayload = maybeSourceMapPayload\n try {\n // Pass the source map URL as the second parameter so that the consumer\n // can resolve relative paths in the source map's `sources` array. This is\n // a guess! Turbopack places .map files as siblings to the chunks so this\n // is sufficient to compute relative paths but is actually wrong (the\n // chunk and sourcemap have different content hashes). We are using the\n // node API to read the sourcemap and it doesn't give us access to the\n // URI. `sourceURL` is already devirtualized so that relative `sources`\n // resolve against the real chunk URL, not React's virtual one.\n const sourceMapURL = sourceURL + '.map'\n sourceMapConsumer = new SyncSourceMapConsumer(\n sourceMapPayload,\n // @ts-expect-error: our typings don't include this parameter but it is here.\n sourceMapURL\n )\n } catch (cause) {\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n // If creating the consumer fails once, it'll fail every time.\n // So set the cache to avoid duplicate errors.\n sourceMapCache.set(frame.file, null)\n return createUnsourcemappedFrame(frame)\n }\n sourceMapCache.set(frame.file, {\n map: sourceMapConsumer,\n payload: sourceMapPayload,\n })\n } else if (sourceMapCacheEntry === null) {\n // We failed earlier getting the payload or consumer.\n // Just return an unsourcemapped frame.\n // Errors will already be logged.\n return createUnsourcemappedFrame(frame)\n } else {\n sourceMapConsumer = sourceMapCacheEntry.map\n sourceMapPayload = sourceMapCacheEntry.payload\n }\n\n const sourcePosition = sourceMapConsumer.originalPositionFor({\n column: (frame.column1 ?? 1) - 1,\n line: frame.line1 ?? 1,\n })\n\n const applicableSourceMap = findApplicableSourceMapPayload(\n (frame.line1 ?? 1) - 1,\n (frame.column1 ?? 1) - 1,\n sourceMapPayload\n )\n let ignored =\n applicableSourceMap !== undefined &&\n sourceMapIgnoreListsEverything(applicableSourceMap)\n if (sourcePosition.source === null) {\n return {\n stack: {\n arguments: frame.arguments,\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n ignored: ignored || shouldIgnoreListGeneratedFrame(frame.file),\n },\n code: null,\n }\n }\n\n // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.\n if (applicableSourceMap === undefined) {\n console.error('No applicable source map found in sections for frame', frame)\n } else if (!ignored && shouldIgnoreListOriginalFrame(sourcePosition.source)) {\n // Externals may be libraries that don't ship ignoreLists.\n // This is really taking control away from libraries.\n // They should still ship `ignoreList` so that attached debuggers ignore-list their frames.\n // TODO: Maybe only ignore library sourcemaps if `ignoreList` is absent?\n // Though keep in mind that Turbopack omits empty `ignoreList`.\n // So if we establish this convention, we should communicate it to the ecosystem.\n ignored = true\n } else if (!ignored) {\n // TODO: O(n^2). Consider moving `ignoreList` into a Set\n const sourceIndex = applicableSourceMap.sources.indexOf(\n sourcePosition.source\n )\n ignored = applicableSourceMap.ignoreList?.includes(sourceIndex) ?? false\n }\n\n const originalFrame: IgnorableStackFrame = {\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n methodName: frame.methodName\n ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n ?.replace('__webpack_exports__.', ''),\n file: sourcePosition.source,\n line1: sourcePosition.line,\n column1: sourcePosition.column + 1,\n // TODO: c&p from async createOriginalStackFrame but why not frame.arguments?\n arguments: [],\n ignored,\n }\n\n /** undefined = not yet computed */\n let codeFrame: string | null | undefined\n\n return {\n stack: originalFrame,\n get code() {\n if (codeFrame === undefined) {\n const sourceContent: string | null =\n sourceMapConsumer.sourceContentFor(\n sourcePosition.source,\n /* returnNullOnMissing */ true\n ) ?? null\n codeFrame = getOriginalCodeFrame(\n originalFrame,\n sourceContent,\n inspectOptions.colors\n )\n }\n return codeFrame\n },\n }\n}\n\nfunction parseAndSourceMap(\n error: Error,\n inspectOptions: util.InspectOptions\n): string {\n const showIgnoreListed = process.env.__NEXT_SHOW_IGNORE_LISTED === 'true'\n // We overwrote Error.prepareStackTrace earlier so error.stack is not sourcemapped.\n let unparsedStack = String(error.stack)\n // We could just read it from `error.stack`.\n // This works around cases where a 3rd party `Error.prepareStackTrace` implementation\n // doesn't implement the name computation correctly.\n const errorName = computeErrorName(error)\n\n let idx = unparsedStack.indexOf('react_stack_bottom_frame')\n if (idx !== -1) {\n idx = unparsedStack.lastIndexOf('\\n', idx)\n } else {\n idx = unparsedStack.indexOf('react-stack-bottom-frame')\n if (idx !== -1) {\n idx = unparsedStack.lastIndexOf('\\n', idx)\n }\n }\n if (idx !== -1 && !showIgnoreListed) {\n // Cut off everything after the bottom frame since it'll be React internals.\n unparsedStack = unparsedStack.slice(0, idx)\n }\n\n const unsourcemappedStack = parseStack(unparsedStack)\n const sourceMapCache: SourceMapCache = new Map()\n\n const sourceMappedFrames: Array<{\n stack: IgnorableStackFrame\n code: string | null\n }> = []\n let sourceFrame: null | string = null\n for (const frame of unsourcemappedStack) {\n if (frame.file === null) {\n sourceMappedFrames.push({\n code: null,\n stack: {\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n arguments: frame.arguments,\n ignored: false,\n },\n })\n } else {\n const sourcemappedFrame = getSourcemappedFrameIfPossible(\n // We narrowed this earlier by bailing if `frame.file` is null.\n frame as SourcemappableStackFrame,\n sourceMapCache,\n inspectOptions\n )\n sourceMappedFrames.push(sourcemappedFrame)\n\n // We can determine the sourceframe here.\n // anonymous frames won't have a sourceframe so we don't need to scan\n // all stacks again to check if they are sandwiched between ignored frames.\n if (\n sourceFrame === null &&\n // TODO: Is this the right choice?\n !sourcemappedFrame.stack.ignored &&\n sourcemappedFrame.code !== null\n ) {\n sourceFrame = sourcemappedFrame.code\n }\n }\n }\n\n ignoreListAnonymousStackFramesIfSandwiched(sourceMappedFrames)\n\n let sourceMappedStack = ''\n for (let i = 0; i < sourceMappedFrames.length; i++) {\n const frame = sourceMappedFrames[i]\n\n if (!frame.stack.ignored) {\n sourceMappedStack +=\n '\\n' +\n frameToString(\n frame.stack.methodName,\n frame.stack.file,\n frame.stack.line1,\n frame.stack.column1\n )\n } else if (showIgnoreListed) {\n sourceMappedStack +=\n '\\n' +\n dim(\n frameToString(\n frame.stack.methodName,\n frame.stack.file,\n frame.stack.line1,\n frame.stack.column1\n )\n )\n }\n }\n\n if (sourceMappedStack === '' && sourceMappedFrames.length > 0) {\n // The `at` marker is important so that Node.js doesn't add square brackets\n // around the stringified error i.e. this results in\n // Error: message\n // at <ignore-listed frames>\n // instead of\n // [Error: message\n // at <ignore-listed frames>]\n sourceMappedStack = '\\n at ' + italic('ignore-listed frames')\n }\n\n return (\n errorName +\n ': ' +\n error.message +\n sourceMappedStack +\n (sourceFrame !== null ? '\\n' + sourceFrame : '')\n )\n}\n\nfunction sourceMapError(\n this: void,\n error: Error,\n inspectOptions: util.InspectOptions\n): Error {\n // Setting an undefined `cause` would print `[cause]: undefined`\n const options = error.cause !== undefined ? { cause: error.cause } : undefined\n\n // Create a new Error object with the source mapping applied and then use native\n // Node.js formatting on the result.\n const newError =\n error instanceof AggregateError\n ? // Preserve AggregateError's `errors` instance property\n new AggregateError(error.errors, error.message, options)\n : new Error(error.message, options)\n\n // TODO: Ensure `class MyError extends Error {}` prints `MyError` as the name\n newError.stack = parseAndSourceMap(error, inspectOptions)\n\n for (const key in error) {\n if (!Object.prototype.hasOwnProperty.call(newError, key)) {\n // @ts-expect-error -- We're copying all enumerable properties.\n // So they definitely exist on `this` and obviously have no type on `newError` (yet)\n newError[key] = error[key]\n }\n }\n\n return newError\n}\n\nexport function patchErrorInspectNodeJS(\n errorConstructor: ErrorConstructor\n): void {\n const inspectSymbol = Symbol.for('nodejs.util.inspect.custom')\n\n errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n // @ts-expect-error -- TODO upstream types\n errorConstructor.prototype[inspectSymbol] = function (\n depth: number,\n inspectOptions: util.InspectOptions,\n inspect: typeof util.inspect\n ): string {\n // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n return workUnitAsyncStorage.exit(() => {\n const newError = sourceMapError(this, inspectOptions)\n\n const originalCustomInspect = (newError as any)[inspectSymbol]\n // Prevent infinite recursion.\n // { customInspect: false } would result in `error.cause` not using our inspect.\n Object.defineProperty(newError, inspectSymbol, {\n value: undefined,\n enumerable: false,\n writable: true,\n })\n try {\n return inspect(newError, {\n ...inspectOptions,\n depth,\n })\n } finally {\n ;(newError as any)[inspectSymbol] = originalCustomInspect\n }\n })\n }\n}\n\nexport function patchErrorInspectEdgeLite(\n errorConstructor: ErrorConstructor\n): void {\n const inspectSymbol = Symbol.for('edge-runtime.inspect.custom')\n\n errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n // @ts-expect-error -- TODO upstream types\n errorConstructor.prototype[inspectSymbol] = function ({\n format,\n }: {\n format: (...args: unknown[]) => string\n }): string {\n // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n return workUnitAsyncStorage.exit(() => {\n const newError = sourceMapError(this, {})\n\n const originalCustomInspect = (newError as any)[inspectSymbol]\n // Prevent infinite recursion.\n Object.defineProperty(newError, inspectSymbol, {\n value: undefined,\n enumerable: false,\n writable: true,\n })\n try {\n return format(newError)\n } finally {\n ;(newError as any)[inspectSymbol] = originalCustomInspect\n }\n })\n }\n}\n"],"names":["patchErrorInspectEdgeLite","patchErrorInspectNodeJS","setBundlerFindSourceMapImplementation","setCodeFrameRenderer","bundlerFindSourceMapPayload","undefined","findSourceMapImplementation","codeFrameRenderer","renderer","getOriginalCodeFrame","frame","source","colors","process","stdout","isTTY","frameToString","methodName","sourceURL","line1","column1","sourceLocation","fileLocation","startsWith","URL","canParse","path","relative","cwd","url","fileURLToPath","computeErrorName","error","name","prepareUnsourcemappedStackTrace","structuredStackTrace","message","stack","i","length","toString","shouldIgnoreListGeneratedFrame","file","includes","shouldIgnoreListOriginalFrame","createUnsourcemappedFrame","arguments","ignored","code","ignoreListAnonymousStackFramesIfSandwiched","sourceMappedFrames","ignoreListAnonymousStackFramesIfSandwichedGeneric","getSourcemappedFrameIfPossible","sourceMapCache","inspectOptions","sourceMapCacheEntry","get","sourceMapConsumer","sourceMapPayload","devirtualizeReactServerURL","isAbsolute","pathToFileURL","maybeSourceMapPayload","sourceMap","nativeFindSourceMap","payload","cause","console","set","sourceMapURL","SyncSourceMapConsumer","map","sourcePosition","originalPositionFor","column","line","applicableSourceMap","findApplicableSourceMapPayload","sourceMapIgnoreListsEverything","sourceIndex","sources","indexOf","ignoreList","originalFrame","replace","codeFrame","sourceContent","sourceContentFor","parseAndSourceMap","showIgnoreListed","env","__NEXT_SHOW_IGNORE_LISTED","unparsedStack","String","errorName","idx","lastIndexOf","slice","unsourcemappedStack","parseStack","Map","sourceFrame","push","sourcemappedFrame","sourceMappedStack","dim","italic","sourceMapError","options","newError","AggregateError","errors","Error","key","Object","prototype","hasOwnProperty","call","errorConstructor","inspectSymbol","Symbol","for","prepareStackTrace","depth","inspect","workUnitAsyncStorage","exit","originalCustomInspect","defineProperty","value","enumerable","writable","format"],"mappings":";;;;;;;;;;;;;;;;;IAyhBgBA,yBAAyB;eAAzBA;;IArCAC,uBAAuB;eAAvBA;;IA1dAC,qCAAqC;eAArCA;;IAeAC,oBAAoB;eAApBA;;;wBAzCqC;8DAC/B;6DACD;2BAEsC;4BAOpD;4BACqC;8CAEP;4BACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAK5B,6CAA6C;AAC7C,iHAAiH;AACjH,8DAA8D;AAC9D,uCAAuC;AACvC,IAAIC,8BAAoD,IAAMC;AAEvD,SAASH,sCACdI,2BAAiD;IAEjDF,8BAA8BE;AAChC;AASA,IAAIC;AAEG,SAASJ,qBAAqBK,QAA2B;IAC9DD,oBAAoBC;AACtB;AAEA,SAASC,qBACPC,KAA0B,EAC1BC,MAAqB,EACrBC,SAAkBC,QAAQC,MAAM,CAACC,KAAK;IAEtC,IAAI,CAACR,mBAAmB;QACtB,6CAA6C;QAC7C,OAAO;IACT;IACA,OAAOA,kBAAkBG,OAAOC,QAAQC;AAC1C;AAOA,SAASI,cACPC,UAAyB,EACzBC,SAAwB,EACxBC,KAAoB,EACpBC,OAAsB;IAEtB,IAAIC,iBAAi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AAMyE,wBAAwB,AAAClB,QAAgB,CAACU,cAAc;YAC9D,8BAA8B;YAC9B,gFAAgF;YAChFL,OAAOc,cAAc,CAACnB,UAAUU,eAAe;gBAC7CU,OAAO5H;gBACP6H,YAAY;gBACZC,UAAU;YACZ;YACA,IAAI;gBACF,OAAOP,QAAQf,UAAU;oBACvB,GAAGvD,cAAc;oBACjBqE;gBACF;YACF,SAAU;;gBACNd,QAAgB,CAACU,cAAc,GAAGQ;YACtC;QACF;IACF;AACF;AAEO,SAAS/H,0BACdsH,gBAAkC;IAElC,MAAMC,gBAAgBC,OAAOC,GAAG,CAAC;IAEjCH,iBAAiBI,iBAAiB,GAAGxF;IAErC,0CAA0C;IAC1CoF,iBAAiBH,SAAS,CAACI,cAAc,GAAG,SAAU,EACpDa,MAAM,EAGP;QACC,gGAAgG;QAChG,OAAOP,kDAAoB,CAACC,IAAI,CAAC;YAC/B,MAAMjB,WAAWF,eAAe,IAAI,EAAE,CAAC;YAEvC,MAAMoB,wBAAwB,AAAClB,QAAgB,CAACU,cAAc;YAC9D,8BAA8B;YAC9BL,OAAOc,cAAc,CAACnB,UAAUU,eAAe;gBAC7CU,OAAO5H;gBACP6H,YAAY;gBACZC,UAAU;YACZ;YACA,IAAI;gBACF,OAAOC,OAAOvB;YAChB,SAAU;;gBACNA,QAAgB,CAACU,cAAc,GAAGQ;YACtC;QACF;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../src/server/patch-error-inspect.ts"],"sourcesContent":["import * as path from 'path'\nimport * as url from 'url'\nimport type * as util from 'util'\nimport { SourceMapConsumer as SyncSourceMapConsumer } from 'next/dist/compiled/source-map'\nimport {\n type ModernSourceMapPayload,\n devirtualizeReactServerURL,\n findApplicableSourceMapPayload,\n findSourceMapPayload,\n ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric,\n sourceMapIgnoreListsEverything,\n} from './lib/source-maps'\nimport { parseStack, type StackFrame } from './lib/parse-stack'\nimport type { IgnorableStackFrame } from '../next-devtools/server/shared'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { dim, italic } from '../lib/picocolors'\n\ntype FindSourceMapPayload = (\n sourceURL: string\n) => ModernSourceMapPayload | undefined\n// Find a source map using the bundler's API.\n// This is only a fallback for when Node.js fails to due to bugs e.g. https://github.com/nodejs/node/issues/52102\n// TODO: Remove once all supported Node.js versions are fixed.\n// TODO(veil): Set from Webpack as well\n//\n// Stored on `globalThis` for the same reason as the code frame renderer below:\n// this module is bundled into several runtimes that each get their own copy,\n// and the copy that installs the implementation is not necessarily the one that\n// symbolicates a frame. The dev validation worker depends on that, because it\n// installs its implementation from the worker bundle while the frames are\n// symbolicated by the app-page bundle's copy.\nconst BUNDLER_FIND_SOURCE_MAP = Symbol.for('next.dev.bundlerFindSourceMap')\ntype GlobalWithBundlerFindSourceMap = typeof globalThis & {\n [BUNDLER_FIND_SOURCE_MAP]?: FindSourceMapPayload\n}\n\nexport function setBundlerFindSourceMapImplementation(\n findSourceMapImplementation: FindSourceMapPayload\n): void {\n ;(globalThis as GlobalWithBundlerFindSourceMap)[BUNDLER_FIND_SOURCE_MAP] =\n findSourceMapImplementation\n}\n\nfunction bundlerFindSourceMapPayload(\n sourceURL: string\n): ModernSourceMapPayload | undefined {\n return (globalThis as GlobalWithBundlerFindSourceMap)[\n BUNDLER_FIND_SOURCE_MAP\n ]?.(sourceURL)\n}\n\n// Code frame renderer - injected by dev/build to avoid hard dependency on native bindings\ntype CodeFrameRenderer = (\n frame: IgnorableStackFrame,\n source: string | null,\n colors: boolean\n) => string | null\n\n// The code-frame renderer is stored on `globalThis` rather than in a module\n// variable because this module is bundled into several runtimes (the dev\n// server, the app-page runtime bundle, and the dev worker bundles) that each\n// get their own copy. `Error.prepareStackTrace` is a single process-global, so\n// whichever copy patched it last is the one that renders errors, which may not\n// be the copy `setCodeFrameRenderer` was called on. Sharing the renderer\n// through a `globalThis` symbol lets any copy install it and any copy read it.\nconst CODE_FRAME_RENDERER = Symbol.for('next.dev.codeFrameRenderer')\ntype GlobalWithCodeFrameRenderer = typeof globalThis & {\n [CODE_FRAME_RENDERER]?: CodeFrameRenderer\n}\n\nexport function setCodeFrameRenderer(renderer: CodeFrameRenderer): void {\n ;(globalThis as GlobalWithCodeFrameRenderer)[CODE_FRAME_RENDERER] = renderer\n}\n\nfunction getOriginalCodeFrame(\n frame: IgnorableStackFrame,\n source: string | null,\n colors: boolean = process.stdout.isTTY\n): string | null {\n const codeFrameRenderer = (globalThis as GlobalWithCodeFrameRenderer)[\n CODE_FRAME_RENDERER\n ]\n if (!codeFrameRenderer) {\n // No renderer available - gracefully degrade\n return null\n }\n return codeFrameRenderer(frame, source, colors)\n}\n\ntype SourceMapCache = Map<\n string,\n null | { map: SyncSourceMapConsumer; payload: ModernSourceMapPayload }\n>\n\n// Constructing a consumer indexes the whole payload — expensive for large\n// chunk maps and previously paid per frame — so consumers are shared across\n// all frames and errors whose lookups returned the same payload. The inner\n// key is the URL the consumer resolves relative `sources` against.\nconst sourceMapConsumers = new WeakMap<\n ModernSourceMapPayload,\n Map<string, SyncSourceMapConsumer>\n>()\n\nfunction getOrCreateSourceMapConsumer(\n payload: ModernSourceMapPayload,\n sourceMapURL: string\n): SyncSourceMapConsumer {\n let consumersByURL = sourceMapConsumers.get(payload)\n let consumer = consumersByURL?.get(sourceMapURL)\n if (consumer === undefined) {\n consumer = new SyncSourceMapConsumer(\n payload,\n // @ts-expect-error: our typings don't include this parameter but it is here.\n sourceMapURL\n )\n if (consumersByURL === undefined) {\n consumersByURL = new Map()\n // Throws for payloads that aren't objects; those are invalid source\n // maps anyway, and the caller reports them.\n sourceMapConsumers.set(payload, consumersByURL)\n }\n consumersByURL.set(sourceMapURL, consumer)\n }\n return consumer\n}\n\nfunction frameToString(\n methodName: string | null,\n sourceURL: string | null,\n line1: number | null,\n column1: number | null\n): string {\n let sourceLocation = line1 !== null ? `:${line1}` : ''\n if (column1 !== null && sourceLocation !== '') {\n sourceLocation += `:${column1}`\n }\n\n let fileLocation: string | null\n if (\n sourceURL !== null &&\n sourceURL.startsWith('file://') &&\n URL.canParse(sourceURL)\n ) {\n // If not relative to CWD, the path is ambiguous to IDEs and clicking will prompt to select the file first.\n // In a multi-app repo, this leads to potentially larger file names but will make clicking snappy.\n // There's no tradeoff for the cases where `dir` in `next dev [dir]` is omitted\n // since relative to cwd is both the shortest and snappiest.\n fileLocation = path.relative(process.cwd(), url.fileURLToPath(sourceURL))\n } else if (sourceURL !== null && sourceURL.startsWith('/')) {\n fileLocation = path.relative(process.cwd(), sourceURL)\n } else {\n fileLocation = sourceURL\n }\n\n return methodName\n ? ` at ${methodName} (${fileLocation}${sourceLocation})`\n : ` at ${fileLocation}${sourceLocation}`\n}\n\nfunction computeErrorName(error: Error): string {\n // TODO: Node.js seems to use a different algorithm\n // class ReadonlyRequestCookiesError extends Error {}` would read `ReadonlyRequestCookiesError: [...]`\n // in the stack i.e. seems like under certain conditions it favors the constructor name.\n return error.name || 'Error'\n}\n\nfunction prepareUnsourcemappedStackTrace(\n error: Error,\n structuredStackTrace: any[]\n): string {\n const name = computeErrorName(error)\n const message = error.message || ''\n let stack = name + ': ' + message\n for (let i = 0; i < structuredStackTrace.length; i++) {\n stack += '\\n at ' + structuredStackTrace[i].toString()\n }\n return stack\n}\n\nfunction shouldIgnoreListGeneratedFrame(file: string): boolean {\n return file.startsWith('node:') || file.includes('node_modules')\n}\n\nfunction shouldIgnoreListOriginalFrame(file: string): boolean {\n return file.includes('node_modules')\n}\n\ninterface SourcemappableStackFrame extends StackFrame {\n file: NonNullable<StackFrame['file']>\n}\n\ninterface SourceMappedFrame {\n stack: IgnorableStackFrame\n // DEV only\n code: string | null\n}\n\nfunction createUnsourcemappedFrame(\n frame: SourcemappableStackFrame\n): SourceMappedFrame {\n return {\n stack: {\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n arguments: frame.arguments,\n ignored: shouldIgnoreListGeneratedFrame(frame.file),\n },\n code: null,\n }\n}\n\nfunction ignoreListAnonymousStackFramesIfSandwiched(\n sourceMappedFrames: Array<{\n stack: IgnorableStackFrame\n code: string | null\n }>\n) {\n return ignoreListAnonymousStackFramesIfSandwichedGeneric(\n sourceMappedFrames,\n (frame) => frame.stack.file === '<anonymous>',\n (frame) => frame.stack.ignored,\n (frame) => frame.stack.methodName,\n (frame) => {\n frame.stack.ignored = true\n }\n )\n}\n\n/**\n * @param frame\n * @param sourceMapCache\n * @returns The original frame if not sourcemapped.\n */\nfunction getSourcemappedFrameIfPossible(\n frame: SourcemappableStackFrame,\n sourceMapCache: SourceMapCache,\n inspectOptions: util.InspectOptions\n): {\n stack: IgnorableStackFrame\n code: string | null\n} {\n const sourceMapCacheEntry = sourceMapCache.get(frame.file)\n let sourceMapConsumer: SyncSourceMapConsumer\n let sourceMapPayload: ModernSourceMapPayload\n if (sourceMapCacheEntry === undefined) {\n // Fake frame scripts (`about://React/Server/file:///path/to/chunk.js?42`)\n // have their positions padded to match the underlying chunk, so they\n // resolve via the chunk's source map.\n let sourceURL = devirtualizeReactServerURL(frame.file)\n // e.g. \"/Users/foo/APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\"\n // or \"C:\\Users\\foo\\APP\\.next\\server\\chunks\\ssr\\[root-of-the-server]__2934a0._.js\"\n // will be keyed by Node.js as \"file:///APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js\".\n // This is likely caused by `callsite.toString()` in `Error.prepareStackTrace converting file URLs to paths.\n //\n // But frame.file might also be \"webpack-internal:///(rsc)/./app/bad-sourcemap/page.js\" or\n // \"<anonymous>\" or \"node:internal/process/task_queues\" here\n if (path.isAbsolute(sourceURL)) {\n sourceURL = url.pathToFileURL(sourceURL).toString()\n }\n let maybeSourceMapPayload: ModernSourceMapPayload | undefined\n try {\n maybeSourceMapPayload = findSourceMapPayload(sourceURL)\n\n if (\n maybeSourceMapPayload === undefined &&\n sourceURL.startsWith('file://')\n ) {\n // Devirtualizing React's fake frame URL decodes the path, while Node.js\n // keys its source map cache by the `pathToFileURL` encoding of the same\n // path, so a path containing characters that encoding escapes (such as\n // the brackets in Turbopack's `[root-of-the-server]` chunks) misses\n // above. Node.js also accepts the plain path, which is unambiguous for\n // both interpretations, so retry with that before giving up.\n //\n // TODO(veil): Making React's fake frame URLs reversible, as proposed in\n // https://github.com/react/react/pull/37105, would let the first lookup\n // succeed on its own and retire this retry.\n maybeSourceMapPayload = findSourceMapPayload(\n url.fileURLToPath(sourceURL)\n )\n }\n } catch (cause) {\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n // If loading fails once, it'll fail every time.\n // So set the cache to avoid duplicate errors.\n sourceMapCache.set(frame.file, null)\n // Don't even fall back to the bundler because it might be not as strict\n // with regards to parsing and then we fail later once we consume the\n // source map payload.\n // This essentially avoids a redundant error where we fail here and then\n // later on consumption because the bundler just handed back an invalid\n // source map.\n return createUnsourcemappedFrame(frame)\n }\n if (maybeSourceMapPayload === undefined) {\n maybeSourceMapPayload = bundlerFindSourceMapPayload(sourceURL)\n }\n\n if (maybeSourceMapPayload === undefined) {\n return createUnsourcemappedFrame(frame)\n }\n sourceMapPayload = maybeSourceMapPayload\n try {\n // Pass the source map URL as the second parameter so that the consumer\n // can resolve relative paths in the source map's `sources` array. This is\n // a guess! Turbopack places .map files as siblings to the chunks so this\n // is sufficient to compute relative paths but is actually wrong (the\n // chunk and sourcemap have different content hashes). We are using the\n // node API to read the sourcemap and it doesn't give us access to the\n // URI. `sourceURL` is already devirtualized so that relative `sources`\n // resolve against the real chunk URL, not React's virtual one.\n const sourceMapURL = sourceURL + '.map'\n sourceMapConsumer = getOrCreateSourceMapConsumer(\n sourceMapPayload,\n sourceMapURL\n )\n } catch (cause) {\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n // If creating the consumer fails once, it'll fail every time.\n // So set the cache to avoid duplicate errors.\n sourceMapCache.set(frame.file, null)\n return createUnsourcemappedFrame(frame)\n }\n sourceMapCache.set(frame.file, {\n map: sourceMapConsumer,\n payload: sourceMapPayload,\n })\n } else if (sourceMapCacheEntry === null) {\n // We failed earlier getting the payload or consumer.\n // Just return an unsourcemapped frame.\n // Errors will already be logged.\n return createUnsourcemappedFrame(frame)\n } else {\n sourceMapConsumer = sourceMapCacheEntry.map\n sourceMapPayload = sourceMapCacheEntry.payload\n }\n\n const sourcePosition = sourceMapConsumer.originalPositionFor({\n column: (frame.column1 ?? 1) - 1,\n line: frame.line1 ?? 1,\n })\n\n const applicableSourceMap = findApplicableSourceMapPayload(\n (frame.line1 ?? 1) - 1,\n (frame.column1 ?? 1) - 1,\n sourceMapPayload\n )\n let ignored =\n applicableSourceMap !== undefined &&\n sourceMapIgnoreListsEverything(applicableSourceMap)\n if (sourcePosition.source === null) {\n return {\n stack: {\n arguments: frame.arguments,\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n ignored: ignored || shouldIgnoreListGeneratedFrame(frame.file),\n },\n code: null,\n }\n }\n\n // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.\n if (applicableSourceMap === undefined) {\n console.error('No applicable source map found in sections for frame', frame)\n } else if (!ignored && shouldIgnoreListOriginalFrame(sourcePosition.source)) {\n // Externals may be libraries that don't ship ignoreLists.\n // This is really taking control away from libraries.\n // They should still ship `ignoreList` so that attached debuggers ignore-list their frames.\n // TODO: Maybe only ignore library sourcemaps if `ignoreList` is absent?\n // Though keep in mind that Turbopack omits empty `ignoreList`.\n // So if we establish this convention, we should communicate it to the ecosystem.\n ignored = true\n } else if (!ignored) {\n // TODO: O(n^2). Consider moving `ignoreList` into a Set\n const sourceIndex = applicableSourceMap.sources.indexOf(\n sourcePosition.source\n )\n ignored = applicableSourceMap.ignoreList?.includes(sourceIndex) ?? false\n }\n\n const originalFrame: IgnorableStackFrame = {\n // We ignore the sourcemapped name since it won't be the correct name.\n // The callsite will point to the column of the variable name instead of the\n // name of the enclosing function.\n // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping.\n methodName: frame.methodName\n ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')\n ?.replace('__webpack_exports__.', ''),\n file: sourcePosition.source,\n line1: sourcePosition.line,\n column1: sourcePosition.column + 1,\n // TODO: c&p from async createOriginalStackFrame but why not frame.arguments?\n arguments: [],\n ignored,\n }\n\n /** undefined = not yet computed */\n let codeFrame: string | null | undefined\n\n return {\n stack: originalFrame,\n get code() {\n if (codeFrame === undefined) {\n const sourceContent: string | null =\n sourceMapConsumer.sourceContentFor(\n sourcePosition.source,\n /* returnNullOnMissing */ true\n ) ?? null\n codeFrame = getOriginalCodeFrame(\n originalFrame,\n sourceContent,\n inspectOptions.colors\n )\n }\n return codeFrame\n },\n }\n}\n\nfunction parseAndSourceMap(\n error: Error,\n inspectOptions: util.InspectOptions\n): string {\n const showIgnoreListed = process.env.__NEXT_SHOW_IGNORE_LISTED === 'true'\n // We overwrote Error.prepareStackTrace earlier so error.stack is not sourcemapped.\n let unparsedStack = String(error.stack)\n // We could just read it from `error.stack`.\n // This works around cases where a 3rd party `Error.prepareStackTrace` implementation\n // doesn't implement the name computation correctly.\n const errorName = computeErrorName(error)\n\n let idx = unparsedStack.indexOf('react_stack_bottom_frame')\n if (idx !== -1) {\n idx = unparsedStack.lastIndexOf('\\n', idx)\n } else {\n idx = unparsedStack.indexOf('react-stack-bottom-frame')\n if (idx !== -1) {\n idx = unparsedStack.lastIndexOf('\\n', idx)\n }\n }\n if (idx !== -1 && !showIgnoreListed) {\n // Cut off everything after the bottom frame since it'll be React internals.\n unparsedStack = unparsedStack.slice(0, idx)\n }\n\n const unsourcemappedStack = parseStack(unparsedStack)\n const sourceMapCache: SourceMapCache = new Map()\n\n const sourceMappedFrames: Array<{\n stack: IgnorableStackFrame\n code: string | null\n }> = []\n let sourceFrame: null | string = null\n for (const frame of unsourcemappedStack) {\n if (frame.file === null) {\n sourceMappedFrames.push({\n code: null,\n stack: {\n file: frame.file,\n line1: frame.line1,\n column1: frame.column1,\n methodName: frame.methodName,\n arguments: frame.arguments,\n ignored: false,\n },\n })\n } else {\n const sourcemappedFrame = getSourcemappedFrameIfPossible(\n // We narrowed this earlier by bailing if `frame.file` is null.\n frame as SourcemappableStackFrame,\n sourceMapCache,\n inspectOptions\n )\n sourceMappedFrames.push(sourcemappedFrame)\n\n // We can determine the sourceframe here.\n // anonymous frames won't have a sourceframe so we don't need to scan\n // all stacks again to check if they are sandwiched between ignored frames.\n if (\n sourceFrame === null &&\n // TODO: Is this the right choice?\n !sourcemappedFrame.stack.ignored &&\n sourcemappedFrame.code !== null\n ) {\n sourceFrame = sourcemappedFrame.code\n }\n }\n }\n\n ignoreListAnonymousStackFramesIfSandwiched(sourceMappedFrames)\n\n let sourceMappedStack = ''\n for (let i = 0; i < sourceMappedFrames.length; i++) {\n const frame = sourceMappedFrames[i]\n\n if (!frame.stack.ignored) {\n sourceMappedStack +=\n '\\n' +\n frameToString(\n frame.stack.methodName,\n frame.stack.file,\n frame.stack.line1,\n frame.stack.column1\n )\n } else if (showIgnoreListed) {\n sourceMappedStack +=\n '\\n' +\n dim(\n frameToString(\n frame.stack.methodName,\n frame.stack.file,\n frame.stack.line1,\n frame.stack.column1\n )\n )\n }\n }\n\n if (sourceMappedStack === '' && sourceMappedFrames.length > 0) {\n // The `at` marker is important so that Node.js doesn't add square brackets\n // around the stringified error i.e. this results in\n // Error: message\n // at <ignore-listed frames>\n // instead of\n // [Error: message\n // at <ignore-listed frames>]\n sourceMappedStack = '\\n at ' + italic('ignore-listed frames')\n }\n\n return (\n errorName +\n ': ' +\n error.message +\n sourceMappedStack +\n (sourceFrame !== null ? '\\n' + sourceFrame : '')\n )\n}\n\nfunction sourceMapError(\n this: void,\n error: Error,\n inspectOptions: util.InspectOptions\n): Error {\n // Setting an undefined `cause` would print `[cause]: undefined`\n const options = error.cause !== undefined ? { cause: error.cause } : undefined\n\n // Create a new Error object with the source mapping applied and then use native\n // Node.js formatting on the result.\n const newError =\n error instanceof AggregateError\n ? // Preserve AggregateError's `errors` instance property\n new AggregateError(error.errors, error.message, options)\n : new Error(error.message, options)\n\n // TODO: Ensure `class MyError extends Error {}` prints `MyError` as the name\n newError.stack = parseAndSourceMap(error, inspectOptions)\n\n for (const key in error) {\n if (!Object.prototype.hasOwnProperty.call(newError, key)) {\n // @ts-expect-error -- We're copying all enumerable properties.\n // So they definitely exist on `this` and obviously have no type on `newError` (yet)\n newError[key] = error[key]\n }\n }\n\n return newError\n}\n\nexport function patchErrorInspectNodeJS(\n errorConstructor: ErrorConstructor\n): void {\n const inspectSymbol = Symbol.for('nodejs.util.inspect.custom')\n\n errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n // @ts-expect-error -- TODO upstream types\n errorConstructor.prototype[inspectSymbol] = function (\n depth: number,\n inspectOptions: util.InspectOptions,\n inspect: typeof util.inspect\n ): string {\n // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n return workUnitAsyncStorage.exit(() => {\n const newError = sourceMapError(this, inspectOptions)\n\n const originalCustomInspect = (newError as any)[inspectSymbol]\n // Prevent infinite recursion.\n // { customInspect: false } would result in `error.cause` not using our inspect.\n Object.defineProperty(newError, inspectSymbol, {\n value: undefined,\n enumerable: false,\n writable: true,\n })\n try {\n return inspect(newError, {\n ...inspectOptions,\n depth,\n })\n } finally {\n ;(newError as any)[inspectSymbol] = originalCustomInspect\n }\n })\n }\n}\n\nexport function patchErrorInspectEdgeLite(\n errorConstructor: ErrorConstructor\n): void {\n const inspectSymbol = Symbol.for('edge-runtime.inspect.custom')\n\n errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace\n\n // @ts-expect-error -- TODO upstream types\n errorConstructor.prototype[inspectSymbol] = function ({\n format,\n }: {\n format: (...args: unknown[]) => string\n }): string {\n // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`.\n return workUnitAsyncStorage.exit(() => {\n const newError = sourceMapError(this, {})\n\n const originalCustomInspect = (newError as any)[inspectSymbol]\n // Prevent infinite recursion.\n Object.defineProperty(newError, inspectSymbol, {\n value: undefined,\n enumerable: false,\n writable: true,\n })\n try {\n return format(newError)\n } finally {\n ;(newError as any)[inspectSymbol] = originalCustomInspect\n }\n })\n }\n}\n"],"names":["patchErrorInspectEdgeLite","patchErrorInspectNodeJS","setBundlerFindSourceMapImplementation","setCodeFrameRenderer","BUNDLER_FIND_SOURCE_MAP","Symbol","for","findSourceMapImplementation","globalThis","bundlerFindSourceMapPayload","sourceURL","CODE_FRAME_RENDERER","renderer","getOriginalCodeFrame","frame","source","colors","process","stdout","isTTY","codeFrameRenderer","sourceMapConsumers","WeakMap","getOrCreateSourceMapConsumer","payload","sourceMapURL","consumersByURL","get","consumer","undefined","SyncSourceMapConsumer","Map","set","frameToString","methodName","line1","column1","sourceLocation","fileLocation","startsWith","URL","canParse","path","relative","cwd","url","fileURLToPath","computeErrorName","error","name","prepareUnsourcemappedStackTrace","structuredStackTrace","message","stack","i","length","toString","shouldIgnoreListGeneratedFrame","file","includes","shouldIgnoreListOriginalFrame","createUnsourcemappedFrame","arguments","ignored","code","ignoreListAnonymousStackFramesIfSandwiched","sourceMappedFrames","ignoreListAnonymousStackFramesIfSandwichedGeneric","getSourcemappedFrameIfPossible","sourceMapCache","inspectOptions","sourceMapCacheEntry","sourceMapConsumer","sourceMapPayload","devirtualizeReactServerURL","isAbsolute","pathToFileURL","maybeSourceMapPayload","findSourceMapPayload","cause","console","map","sourcePosition","originalPositionFor","column","line","applicableSourceMap","findApplicableSourceMapPayload","sourceMapIgnoreListsEverything","sourceIndex","sources","indexOf","ignoreList","originalFrame","replace","codeFrame","sourceContent","sourceContentFor","parseAndSourceMap","showIgnoreListed","env","__NEXT_SHOW_IGNORE_LISTED","unparsedStack","String","errorName","idx","lastIndexOf","slice","unsourcemappedStack","parseStack","sourceFrame","push","sourcemappedFrame","sourceMappedStack","dim","italic","sourceMapError","options","newError","AggregateError","errors","Error","key","Object","prototype","hasOwnProperty","call","errorConstructor","inspectSymbol","prepareStackTrace","depth","inspect","workUnitAsyncStorage","exit","originalCustomInspect","defineProperty","value","enumerable","writable","format"],"mappings":";;;;;;;;;;;;;;;;;IA0mBgBA,yBAAyB;eAAzBA;;IArCAC,uBAAuB;eAAvBA;;IAjiBAC,qCAAqC;eAArCA;;IAkCAC,oBAAoB;eAApBA;;;8DAtEM;6DACD;2BAEsC;4BAQpD;4BACqC;8CAEP;4BACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAK5B,6CAA6C;AAC7C,iHAAiH;AACjH,8DAA8D;AAC9D,uCAAuC;AACvC,EAAE;AACF,+EAA+E;AAC/E,6EAA6E;AAC7E,gFAAgF;AAChF,8EAA8E;AAC9E,0EAA0E;AAC1E,8CAA8C;AAC9C,MAAMC,0BAA0BC,OAAOC,GAAG,CAAC;AAKpC,SAASJ,sCACdK,2BAAiD;;IAE/CC,UAA6C,CAACJ,wBAAwB,GACtEG;AACJ;AAEA,SAASE,4BACPC,SAAiB;QAEV;IAAP,QAAO,sCAAA,AAACF,UAA6C,CACnDJ,wBACD,qBAFM,yCAACI,YAEJE;AACN;AASA,4EAA4E;AAC5E,yEAAyE;AACzE,6EAA6E;AAC7E,+EAA+E;AAC/E,+EAA+E;AAC/E,yEAAyE;AACzE,+EAA+E;AAC/E,MAAMC,sBAAsBN,OAAOC,GAAG,CAAC;AAKhC,SAASH,qBAAqBS,QAA2B;;IAC5DJ,UAA0C,CAACG,oBAAoB,GAAGC;AACtE;AAEA,SAASC,qBACPC,KAA0B,EAC1BC,MAAqB,EACrBC,SAAkBC,QAAQC,MAAM,CAACC,KAAK;IAEtC,MAAMC,oBAAoB,AAACZ,UAA0C,CACnEG,oBACD;IACD,IAAI,C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tC;QACF;IACF;AACF;AAEO,SAAStI,0BACd+H,gBAAkC;IAElC,MAAMC,gBAAgB3H,OAAOC,GAAG,CAAC;IAEjCyH,iBAAiBE,iBAAiB,GAAG/E;IAErC,0CAA0C;IAC1C6E,iBAAiBH,SAAS,CAACI,cAAc,GAAG,SAAU,EACpDW,MAAM,EAGP;QACC,gGAAgG;QAChG,OAAOP,kDAAoB,CAACC,IAAI,CAAC;YAC/B,MAAMf,WAAWF,eAAe,IAAI,EAAE,CAAC;YAEvC,MAAMkB,wBAAwB,AAAChB,QAAgB,CAACU,cAAc;YAC9D,8BAA8B;YAC9BL,OAAOY,cAAc,CAACjB,UAAUU,eAAe;gBAC7CQ,OAAO3G;gBACP4G,YAAY;gBACZC,UAAU;YACZ;YACA,IAAI;gBACF,OAAOC,OAAOrB;YAChB,SAAU;;gBACNA,QAAgB,CAACU,cAAc,GAAGM;YACtC;QACF;IACF;AACF","ignoreList":[0]} |
@@ -8,2 +8,3 @@ import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition'; | ||
| import { renderToHTMLOrFlight, type AppSharedContext } from '../../app-render/app-render'; | ||
| import type { DevValidationWorkerMessage } from '../../app-render/dev-validation-worker-globals'; | ||
| import { RouteModule, type RouteModuleOptions, type RouteModuleHandleContext } from '../route-module'; | ||
@@ -43,2 +44,13 @@ import * as vendoredContexts from './vendored/contexts/entrypoints'; | ||
| render(req: BaseNextRequest, res: BaseNextResponse, context: AppPageRouteHandlerContext): Promise<RenderResult>; | ||
| /** | ||
| * Worker entry point for dev Cache Components dev validation. The dev | ||
| * validation worker reloads this route's module and calls this so the whole | ||
| * validation runs inside the app-page bundle's React instance (the same one | ||
| * the user's client components resolve through `componentMod`), rebuilding | ||
| * the render context from the transported `message`. `componentMod` is the | ||
| * reloaded module the worker holds; it's passed in because the route module | ||
| * has no back-reference to it. Returns the validation errors for the worker | ||
| * to serialize and the main thread to deliver to the dev overlay. | ||
| */ | ||
| runValidationInDev(componentMod: AppPageModule, message: DevValidationWorkerMessage, abortSignal: AbortSignal): Promise<Array<unknown> | undefined>; | ||
| private pathCouldBeIntercepted; | ||
@@ -45,0 +57,0 @@ getVaryHeader(resolvedPathname: string, interceptionRoutePatterns: RegExp[]): string; |
@@ -133,2 +133,14 @@ "use strict"; | ||
| } | ||
| /** | ||
| * Worker entry point for dev Cache Components dev validation. The dev | ||
| * validation worker reloads this route's module and calls this so the whole | ||
| * validation runs inside the app-page bundle's React instance (the same one | ||
| * the user's client components resolve through `componentMod`), rebuilding | ||
| * the render context from the transported `message`. `componentMod` is the | ||
| * reloaded module the worker holds; it's passed in because the route module | ||
| * has no back-reference to it. Returns the validation errors for the worker | ||
| * to serialize and the main thread to deliver to the dev overlay. | ||
| */ runValidationInDev(componentMod, message, abortSignal) { | ||
| return (0, _apprender.runValidationInDevFromSnapshot)(message, componentMod, abortSignal); | ||
| } | ||
| pathCouldBeIntercepted(resolvedPathname, interceptionRoutePatterns) { | ||
@@ -135,0 +147,0 @@ return (0, _interceptionroutes.isInterceptionRouteAppPath)(resolvedPathname) || interceptionRoutePatterns.some((regexp)=>{ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/route-modules/app-page/module.ts"],"sourcesContent":["import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition'\nimport type RenderResult from '../../render-result'\nimport type { RenderOpts } from '../../app-render/types'\nimport { addRequestMeta, type NextParsedUrlQuery } from '../../request-meta'\nimport type { LoaderTree } from '../../lib/app-dir-module'\nimport type { PrerenderManifest } from '../../../build'\n\nimport {\n renderToHTMLOrFlight,\n type AppSharedContext,\n} from '../../app-render/app-render'\nimport {\n RouteModule,\n type RouteModuleOptions,\n type RouteModuleHandleContext,\n} from '../route-module'\nimport * as vendoredContexts from './vendored/contexts/entrypoints'\nimport type { BaseNextRequest, BaseNextResponse } from '../../base-http'\nimport type { ServerComponentsHmrCache } from '../../response-cache'\nimport type { OpaqueFallbackRouteParams } from '../../request/fallback-params'\nimport { PrerenderManifestMatcher } from './helpers/prerender-manifest-matcher'\nimport type { DeepReadonly } from '../../../shared/lib/deep-readonly'\nimport {\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n RSC_HEADER,\n} from '../../../client/components/app-router-headers'\nimport { isInterceptionRouteAppPath } from '../../../shared/lib/router/utils/interception-routes'\nimport { RSCPathnameNormalizer } from '../../normalizers/request/rsc'\nimport { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { IncomingMessage } from 'http'\nimport {\n applyAppPageRscRequestMetaFromHeaders,\n normalizeAppPageRequestUrl,\n} from './normalize-request-url'\n\nlet vendoredReactRSC\nlet vendoredReactSSR\n\n// the vendored Reacts are loaded from their original source in the edge runtime\nif (process.env.NEXT_RUNTIME !== 'edge') {\n vendoredReactRSC =\n require('./vendored/rsc/entrypoints') as typeof import('./vendored/rsc/entrypoints')\n vendoredReactSSR =\n require('./vendored/ssr/entrypoints') as typeof import('./vendored/ssr/entrypoints')\n\n // In Node environments we need to access the correct React instance from external modules such\n // as global patches. We register the loaded React instances here.\n const { registerServerReact, registerClientReact } =\n require('../../runtime-reacts.external') as typeof import('../../runtime-reacts.external')\n registerServerReact(vendoredReactRSC.React)\n registerClientReact(vendoredReactSSR.React)\n}\n\n/**\n * The AppPageModule is the type of the module exported by the bundled app page\n * module.\n */\nexport type AppPageModule = typeof import('../../../build/templates/app-page')\n\ntype AppPageUserlandModule = {\n /**\n * The tree created in next-app-loader that holds component segments and modules\n */\n loaderTree: LoaderTree\n}\n\nexport interface AppPageRouteHandlerContext extends RouteModuleHandleContext {\n page: string\n query: NextParsedUrlQuery\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n renderOpts: RenderOpts\n serverComponentsHmrCache?: ServerComponentsHmrCache\n sharedContext: AppSharedContext\n}\n\nexport type AppPageRouteModuleOptions = RouteModuleOptions<\n AppPageRouteDefinition,\n AppPageUserlandModule\n>\n\nexport class AppPageRouteModule extends RouteModule<\n AppPageRouteDefinition,\n AppPageUserlandModule\n> {\n private matchers = new WeakMap<\n DeepReadonly<PrerenderManifest>,\n PrerenderManifestMatcher\n >()\n public match(\n pathname: string,\n prerenderManifest: DeepReadonly<PrerenderManifest>\n ) {\n // Lazily create the matcher based on the provided prerender manifest.\n let matcher = this.matchers.get(prerenderManifest)\n if (!matcher) {\n matcher = new PrerenderManifestMatcher(\n this.definition.pathname,\n prerenderManifest\n )\n this.matchers.set(prerenderManifest, matcher)\n }\n\n // Match the pathname to the dynamic route.\n return matcher.match(pathname)\n }\n\n private normalizers = {\n rsc: new RSCPathnameNormalizer(),\n segmentPrefetchRSC: new SegmentPrefixRSCPathnameNormalizer(),\n }\n\n public normalizeUrl(\n req: IncomingMessage | BaseNextRequest,\n parsedUrl: UrlWithParsedQuery\n ) {\n if (this.normalizers.segmentPrefetchRSC.match(parsedUrl.pathname || '/')) {\n const result = this.normalizers.segmentPrefetchRSC.extract(\n parsedUrl.pathname || '/'\n )\n if (!result) return false\n\n const { originalPathname, segmentPath } = result\n parsedUrl.pathname = originalPathname\n\n // Mark the request as a router prefetch request.\n req.headers[RSC_HEADER] = '1'\n req.headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath\n\n addRequestMeta(req, 'isRSCRequest', true)\n addRequestMeta(req, 'isPrefetchRSCRequest', true)\n addRequestMeta(req, 'segmentPrefetchRSCRequest', segmentPath)\n } else if (this.normalizers.rsc.match(parsedUrl.pathname || '/')) {\n parsedUrl.pathname = this.normalizers.rsc.normalize(\n parsedUrl.pathname || '/',\n true\n )\n\n // Mark the request as a RSC request.\n req.headers[RSC_HEADER] = '1'\n } else {\n super.normalizeUrl(req, parsedUrl)\n }\n\n // Minimal adapters can bypass base-server request normalization and invoke\n // route modules directly, so derive RSC/prefetch metadata from headers.\n applyAppPageRscRequestMetaFromHeaders(req)\n normalizeAppPageRequestUrl(req, parsedUrl.pathname || '/')\n }\n\n public render(\n req: BaseNextRequest,\n res: BaseNextResponse,\n context: AppPageRouteHandlerContext\n ): Promise<RenderResult> {\n return renderToHTMLOrFlight(\n req,\n res,\n context.page,\n context.query,\n context.fallbackRouteParams,\n context.renderOpts,\n context.serverComponentsHmrCache,\n context.sharedContext\n )\n }\n\n private pathCouldBeIntercepted(\n resolvedPathname: string,\n interceptionRoutePatterns: RegExp[]\n ): boolean {\n return (\n isInterceptionRouteAppPath(resolvedPathname) ||\n interceptionRoutePatterns.some((regexp) => {\n return regexp.test(resolvedPathname)\n })\n )\n }\n\n public getVaryHeader(\n resolvedPathname: string,\n interceptionRoutePatterns: RegExp[]\n ): string {\n const baseVaryHeader = `${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE_HEADER}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`\n\n if (\n this.pathCouldBeIntercepted(resolvedPathname, interceptionRoutePatterns)\n ) {\n // Interception route responses can vary based on the `Next-URL` header.\n // We use the Vary header to signal this behavior to the client to properly cache the response.\n return `${baseVaryHeader}, ${NEXT_URL}`\n } else {\n // We don't need to include `Next-URL` in the Vary header for non-interception routes since it won't affect the response.\n // We also set this header for pages to avoid caching issues when navigating between pages and app.\n return baseVaryHeader\n }\n }\n}\n\nconst vendored = {\n 'react-rsc': vendoredReactRSC,\n 'react-ssr': vendoredReactSSR,\n contexts: vendoredContexts,\n}\n\nexport { renderToHTMLOrFlight, vendored }\n\nexport default AppPageRouteModule\n"],"names":["AppPageRouteModule","renderToHTMLOrFlight","vendored","vendoredReactRSC","vendoredReactSSR","process","env","NEXT_RUNTIME","require","registerServerReact","registerClientReact","React","RouteModule","match","pathname","prerenderManifest","matcher","matchers","get","PrerenderManifestMatcher","definition","set","normalizeUrl","req","parsedUrl","normalizers","segmentPrefetchRSC","result","extract","originalPathname","segmentPath","headers","RSC_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","addRequestMeta","rsc","normalize","applyAppPageRscRequestMetaFromHeaders","normalizeAppPageRequestUrl","render","res","context","page","query","fallbackRouteParams","renderOpts","serverComponentsHmrCache","sharedContext","pathCouldBeIntercepted","resolvedPathname","interceptionRoutePatterns","isInterceptionRouteAppPath","some","regexp","test","getVaryHeader","baseVaryHeader","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_URL","WeakMap","RSCPathnameNormalizer","SegmentPrefixRSCPathnameNormalizer","contexts","vendoredContexts"],"mappings":";;;;;;;;;;;;;;;;;IAoFaA,kBAAkB;eAAlBA;;IA+Hb,OAAiC;eAAjC;;IAFSC,oBAAoB;eAApBA,+BAAoB;;IAAEC,QAAQ;eAARA;;;6BA9MyB;2BAOjD;6BAKA;qEAC2B;0CAIO;kCAQlC;oCACoC;qBACL;kCACa;qCAM5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEP,IAAIC;AACJ,IAAIC;AAEJ,gFAAgF;AAChF,IAAIC,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCJ,mBACEK,QAAQ;IACVJ,mBACEI,QAAQ;IAEV,+FAA+F;IAC/F,kEAAkE;IAClE,MAAM,EAAEC,mBAAmB,EAAEC,mBAAmB,EAAE,GAChDF,QAAQ;IACVC,oBAAoBN,iBAAiBQ,KAAK;IAC1CD,oBAAoBN,iBAAiBO,KAAK;AAC5C;AA6BO,MAAMX,2BAA2BY,wBAAW;IAQ1CC,MACLC,QAAgB,EAChBC,iBAAkD,EAClD;QACA,sEAAsE;QACtE,IAAIC,UAAU,IAAI,CAACC,QAAQ,CAACC,GAAG,CAACH;QAChC,IAAI,CAACC,SAAS;YACZA,UAAU,IAAIG,kDAAwB,CACpC,IAAI,CAACC,UAAU,CAACN,QAAQ,EACxBC;YAEF,IAAI,CAACE,QAAQ,CAACI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A,+BAAoB,EACzBsB,KACAkB,KACAC,QAAQC,IAAI,EACZD,QAAQE,KAAK,EACbF,QAAQG,mBAAmB,EAC3BH,QAAQI,UAAU,EAClBJ,QAAQK,wBAAwB,EAChCL,QAAQM,aAAa;IAEzB;IAEQC,uBACNC,gBAAwB,EACxBC,yBAAmC,EAC1B;QACT,OACEC,IAAAA,8CAA0B,EAACF,qBAC3BC,0BAA0BE,IAAI,CAAC,CAACC;YAC9B,OAAOA,OAAOC,IAAI,CAACL;QACrB;IAEJ;IAEOM,cACLN,gBAAwB,EACxBC,yBAAmC,EAC3B;QACR,MAAMM,iBAAiB,GAAGzB,4BAAU,CAAC,EAAE,EAAE0B,+CAA6B,CAAC,EAAE,EAAEzB,6CAA2B,CAAC,EAAE,EAAEC,qDAAmC,EAAE;QAEhJ,IACE,IAAI,CAACe,sBAAsB,CAACC,kBAAkBC,4BAC9C;YACA,wEAAwE;YACxE,+FAA+F;YAC/F,OAAO,GAAGM,eAAe,EAAE,EAAEE,0BAAQ,EAAE;QACzC,OAAO;YACL,yHAAyH;YACzH,mGAAmG;YACnG,OAAOF;QACT;IACF;;QApHK,qBAIGxC,WAAW,IAAI2C,gBAsBfnC,cAAc;YACpBW,KAAK,IAAIyB,0BAAqB;YAC9BnC,oBAAoB,IAAIoC,oDAAkC;QAC5D;;AAwFF;AAEA,MAAM5D,WAAW;IACf,aAAaC;IACb,aAAaC;IACb2D,UAAUC;AACZ;MAIA,WAAehE","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/route-modules/app-page/module.ts"],"sourcesContent":["import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition'\nimport type RenderResult from '../../render-result'\nimport type { RenderOpts } from '../../app-render/types'\nimport { addRequestMeta, type NextParsedUrlQuery } from '../../request-meta'\nimport type { LoaderTree } from '../../lib/app-dir-module'\nimport type { PrerenderManifest } from '../../../build'\n\nimport {\n renderToHTMLOrFlight,\n runValidationInDevFromSnapshot,\n type AppSharedContext,\n} from '../../app-render/app-render'\nimport type { DevValidationWorkerMessage } from '../../app-render/dev-validation-worker-globals'\nimport {\n RouteModule,\n type RouteModuleOptions,\n type RouteModuleHandleContext,\n} from '../route-module'\nimport * as vendoredContexts from './vendored/contexts/entrypoints'\nimport type { BaseNextRequest, BaseNextResponse } from '../../base-http'\nimport type { ServerComponentsHmrCache } from '../../response-cache'\nimport type { OpaqueFallbackRouteParams } from '../../request/fallback-params'\nimport { PrerenderManifestMatcher } from './helpers/prerender-manifest-matcher'\nimport type { DeepReadonly } from '../../../shared/lib/deep-readonly'\nimport {\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n RSC_HEADER,\n} from '../../../client/components/app-router-headers'\nimport { isInterceptionRouteAppPath } from '../../../shared/lib/router/utils/interception-routes'\nimport { RSCPathnameNormalizer } from '../../normalizers/request/rsc'\nimport { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { IncomingMessage } from 'http'\nimport {\n applyAppPageRscRequestMetaFromHeaders,\n normalizeAppPageRequestUrl,\n} from './normalize-request-url'\n\nlet vendoredReactRSC\nlet vendoredReactSSR\n\n// the vendored Reacts are loaded from their original source in the edge runtime\nif (process.env.NEXT_RUNTIME !== 'edge') {\n vendoredReactRSC =\n require('./vendored/rsc/entrypoints') as typeof import('./vendored/rsc/entrypoints')\n vendoredReactSSR =\n require('./vendored/ssr/entrypoints') as typeof import('./vendored/ssr/entrypoints')\n\n // In Node environments we need to access the correct React instance from external modules such\n // as global patches. We register the loaded React instances here.\n const { registerServerReact, registerClientReact } =\n require('../../runtime-reacts.external') as typeof import('../../runtime-reacts.external')\n registerServerReact(vendoredReactRSC.React)\n registerClientReact(vendoredReactSSR.React)\n}\n\n/**\n * The AppPageModule is the type of the module exported by the bundled app page\n * module.\n */\nexport type AppPageModule = typeof import('../../../build/templates/app-page')\n\ntype AppPageUserlandModule = {\n /**\n * The tree created in next-app-loader that holds component segments and modules\n */\n loaderTree: LoaderTree\n}\n\nexport interface AppPageRouteHandlerContext extends RouteModuleHandleContext {\n page: string\n query: NextParsedUrlQuery\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n renderOpts: RenderOpts\n serverComponentsHmrCache?: ServerComponentsHmrCache\n sharedContext: AppSharedContext\n}\n\nexport type AppPageRouteModuleOptions = RouteModuleOptions<\n AppPageRouteDefinition,\n AppPageUserlandModule\n>\n\nexport class AppPageRouteModule extends RouteModule<\n AppPageRouteDefinition,\n AppPageUserlandModule\n> {\n private matchers = new WeakMap<\n DeepReadonly<PrerenderManifest>,\n PrerenderManifestMatcher\n >()\n public match(\n pathname: string,\n prerenderManifest: DeepReadonly<PrerenderManifest>\n ) {\n // Lazily create the matcher based on the provided prerender manifest.\n let matcher = this.matchers.get(prerenderManifest)\n if (!matcher) {\n matcher = new PrerenderManifestMatcher(\n this.definition.pathname,\n prerenderManifest\n )\n this.matchers.set(prerenderManifest, matcher)\n }\n\n // Match the pathname to the dynamic route.\n return matcher.match(pathname)\n }\n\n private normalizers = {\n rsc: new RSCPathnameNormalizer(),\n segmentPrefetchRSC: new SegmentPrefixRSCPathnameNormalizer(),\n }\n\n public normalizeUrl(\n req: IncomingMessage | BaseNextRequest,\n parsedUrl: UrlWithParsedQuery\n ) {\n if (this.normalizers.segmentPrefetchRSC.match(parsedUrl.pathname || '/')) {\n const result = this.normalizers.segmentPrefetchRSC.extract(\n parsedUrl.pathname || '/'\n )\n if (!result) return false\n\n const { originalPathname, segmentPath } = result\n parsedUrl.pathname = originalPathname\n\n // Mark the request as a router prefetch request.\n req.headers[RSC_HEADER] = '1'\n req.headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath\n\n addRequestMeta(req, 'isRSCRequest', true)\n addRequestMeta(req, 'isPrefetchRSCRequest', true)\n addRequestMeta(req, 'segmentPrefetchRSCRequest', segmentPath)\n } else if (this.normalizers.rsc.match(parsedUrl.pathname || '/')) {\n parsedUrl.pathname = this.normalizers.rsc.normalize(\n parsedUrl.pathname || '/',\n true\n )\n\n // Mark the request as a RSC request.\n req.headers[RSC_HEADER] = '1'\n } else {\n super.normalizeUrl(req, parsedUrl)\n }\n\n // Minimal adapters can bypass base-server request normalization and invoke\n // route modules directly, so derive RSC/prefetch metadata from headers.\n applyAppPageRscRequestMetaFromHeaders(req)\n normalizeAppPageRequestUrl(req, parsedUrl.pathname || '/')\n }\n\n public render(\n req: BaseNextRequest,\n res: BaseNextResponse,\n context: AppPageRouteHandlerContext\n ): Promise<RenderResult> {\n return renderToHTMLOrFlight(\n req,\n res,\n context.page,\n context.query,\n context.fallbackRouteParams,\n context.renderOpts,\n context.serverComponentsHmrCache,\n context.sharedContext\n )\n }\n\n /**\n * Worker entry point for dev Cache Components dev validation. The dev\n * validation worker reloads this route's module and calls this so the whole\n * validation runs inside the app-page bundle's React instance (the same one\n * the user's client components resolve through `componentMod`), rebuilding\n * the render context from the transported `message`. `componentMod` is the\n * reloaded module the worker holds; it's passed in because the route module\n * has no back-reference to it. Returns the validation errors for the worker\n * to serialize and the main thread to deliver to the dev overlay.\n */\n public runValidationInDev(\n componentMod: AppPageModule,\n message: DevValidationWorkerMessage,\n abortSignal: AbortSignal\n ): Promise<Array<unknown> | undefined> {\n return runValidationInDevFromSnapshot(message, componentMod, abortSignal)\n }\n\n private pathCouldBeIntercepted(\n resolvedPathname: string,\n interceptionRoutePatterns: RegExp[]\n ): boolean {\n return (\n isInterceptionRouteAppPath(resolvedPathname) ||\n interceptionRoutePatterns.some((regexp) => {\n return regexp.test(resolvedPathname)\n })\n )\n }\n\n public getVaryHeader(\n resolvedPathname: string,\n interceptionRoutePatterns: RegExp[]\n ): string {\n const baseVaryHeader = `${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE_HEADER}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`\n\n if (\n this.pathCouldBeIntercepted(resolvedPathname, interceptionRoutePatterns)\n ) {\n // Interception route responses can vary based on the `Next-URL` header.\n // We use the Vary header to signal this behavior to the client to properly cache the response.\n return `${baseVaryHeader}, ${NEXT_URL}`\n } else {\n // We don't need to include `Next-URL` in the Vary header for non-interception routes since it won't affect the response.\n // We also set this header for pages to avoid caching issues when navigating between pages and app.\n return baseVaryHeader\n }\n }\n}\n\nconst vendored = {\n 'react-rsc': vendoredReactRSC,\n 'react-ssr': vendoredReactSSR,\n contexts: vendoredContexts,\n}\n\nexport { renderToHTMLOrFlight, vendored }\n\nexport default AppPageRouteModule\n"],"names":["AppPageRouteModule","renderToHTMLOrFlight","vendored","vendoredReactRSC","vendoredReactSSR","process","env","NEXT_RUNTIME","require","registerServerReact","registerClientReact","React","RouteModule","match","pathname","prerenderManifest","matcher","matchers","get","PrerenderManifestMatcher","definition","set","normalizeUrl","req","parsedUrl","normalizers","segmentPrefetchRSC","result","extract","originalPathname","segmentPath","headers","RSC_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","addRequestMeta","rsc","normalize","applyAppPageRscRequestMetaFromHeaders","normalizeAppPageRequestUrl","render","res","context","page","query","fallbackRouteParams","renderOpts","serverComponentsHmrCache","sharedContext","runValidationInDev","componentMod","message","abortSignal","runValidationInDevFromSnapshot","pathCouldBeIntercepted","resolvedPathname","interceptionRoutePatterns","isInterceptionRouteAppPath","some","regexp","test","getVaryHeader","baseVaryHeader","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_URL","WeakMap","RSCPathnameNormalizer","SegmentPrefixRSCPathnameNormalizer","contexts","vendoredContexts"],"mappings":";;;;;;;;;;;;;;;;;IAsFaA,kBAAkB;eAAlBA;;IAiJb,OAAiC;eAAjC;;IAFSC,oBAAoB;eAApBA,+BAAoB;;IAAEC,QAAQ;eAARA;;;6BAlOyB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AU,CAAC,EAAE,EAAE+B,+CAA6B,CAAC,EAAE,EAAE9B,6CAA2B,CAAC,EAAE,EAAEC,qDAAmC,EAAE;QAEhJ,IACE,IAAI,CAACoB,sBAAsB,CAACC,kBAAkBC,4BAC9C;YACA,wEAAwE;YACxE,+FAA+F;YAC/F,OAAO,GAAGM,eAAe,EAAE,EAAEE,0BAAQ,EAAE;QACzC,OAAO;YACL,yHAAyH;YACzH,mGAAmG;YACnG,OAAOF;QACT;IACF;;QAtIK,qBAIG7C,WAAW,IAAIgD,gBAsBfxC,cAAc;YACpBW,KAAK,IAAI8B,0BAAqB;YAC9BxC,oBAAoB,IAAIyC,oDAAkC;QAC5D;;AA0GF;AAEA,MAAMjE,WAAW;IACf,aAAaC;IACb,aAAaC;IACbgE,UAAUC;AACZ;MAIA,WAAerE","ignoreList":[0]} |
@@ -7,9 +7,17 @@ declare abstract class ResourceManager<T, Args> { | ||
| remove(resource: T): void; | ||
| /** | ||
| * Stop tracking a resource without destroying it. Used when a resource has | ||
| * already been released by other means (e.g. a one-shot timeout that ran to | ||
| * completion) so it should no longer be retained by this manager. | ||
| */ | ||
| protected untrack(resource: T): void; | ||
| removeAll(): void; | ||
| /** Number of resources currently tracked. Exposed for observability/tests. */ | ||
| get size(): number; | ||
| } | ||
| declare class IntervalsManager extends ResourceManager<number, Parameters<typeof webSetIntervalPolyfill>> { | ||
| export declare class IntervalsManager extends ResourceManager<number, Parameters<typeof webSetIntervalPolyfill>> { | ||
| create(args: Parameters<typeof webSetIntervalPolyfill>): number; | ||
| destroy(interval: number): void; | ||
| } | ||
| declare class TimeoutsManager extends ResourceManager<number, Parameters<typeof webSetTimeoutPolyfill>> { | ||
| export declare class TimeoutsManager extends ResourceManager<number, Parameters<typeof webSetTimeoutPolyfill>> { | ||
| create(args: Parameters<typeof webSetTimeoutPolyfill>): number; | ||
@@ -16,0 +24,0 @@ destroy(timeout: number): void; |
@@ -6,2 +6,4 @@ "use strict"; | ||
| 0 && (module.exports = { | ||
| IntervalsManager: null, | ||
| TimeoutsManager: null, | ||
| intervalsManager: null, | ||
@@ -17,2 +19,8 @@ timeoutsManager: null | ||
| _export(exports, { | ||
| IntervalsManager: function() { | ||
| return IntervalsManager; | ||
| }, | ||
| TimeoutsManager: function() { | ||
| return TimeoutsManager; | ||
| }, | ||
| intervalsManager: function() { | ||
@@ -28,15 +36,27 @@ return intervalsManager; | ||
| const resource = this.create(resourceArgs); | ||
| this.resources.push(resource); | ||
| this.resources.add(resource); | ||
| return resource; | ||
| } | ||
| remove(resource) { | ||
| this.resources = this.resources.filter((r)=>r !== resource); | ||
| this.untrack(resource); | ||
| this.destroy(resource); | ||
| } | ||
| /** | ||
| * Stop tracking a resource without destroying it. Used when a resource has | ||
| * already been released by other means (e.g. a one-shot timeout that ran to | ||
| * completion) so it should no longer be retained by this manager. | ||
| */ untrack(resource) { | ||
| this.resources.delete(resource); | ||
| } | ||
| removeAll() { | ||
| this.resources.forEach(this.destroy); | ||
| this.resources = []; | ||
| for (const resource of this.resources){ | ||
| this.destroy(resource); | ||
| } | ||
| this.resources.clear(); | ||
| } | ||
| /** Number of resources currently tracked. Exposed for observability/tests. */ get size() { | ||
| return this.resources.size; | ||
| } | ||
| constructor(){ | ||
| this.resources = []; | ||
| this.resources = new Set(); | ||
| } | ||
@@ -56,3 +76,18 @@ } | ||
| // TODO: use the edge runtime provided `setTimeout` instead | ||
| return webSetTimeoutPolyfill(...args); | ||
| const [globalObject, callback, ms, ...rest] = args; | ||
| // A one-shot timeout releases itself from tracking once its callback has | ||
| // run. Otherwise fire-and-forget timeouts (whose ids user code never | ||
| // passes to `clearTimeout`) would accumulate for the lifetime of the | ||
| // module context and leak memory in long-lived server processes. | ||
| // See: https://github.com/vercel/next.js/issues/95094 | ||
| let timeoutId; | ||
| const callbackWithRelease = (...callbackArgs)=>{ | ||
| try { | ||
| return callback.apply(globalObject, callbackArgs); | ||
| } finally{ | ||
| this.untrack(timeoutId); | ||
| } | ||
| }; | ||
| timeoutId = webSetTimeoutPolyfill(globalObject, callbackWithRelease, ms, ...rest); | ||
| return timeoutId; | ||
| } | ||
@@ -59,0 +94,0 @@ destroy(timeout) { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/web/sandbox/resource-managers.ts"],"sourcesContent":["abstract class ResourceManager<T, Args> {\n private resources: T[] = []\n\n abstract create(resourceArgs: Args): T\n abstract destroy(resource: T): void\n\n add(resourceArgs: Args) {\n const resource = this.create(resourceArgs)\n this.resources.push(resource)\n return resource\n }\n\n remove(resource: T) {\n this.resources = this.resources.filter((r) => r !== resource)\n this.destroy(resource)\n }\n\n removeAll() {\n this.resources.forEach(this.destroy)\n this.resources = []\n }\n}\n\nclass IntervalsManager extends ResourceManager<\n number,\n Parameters<typeof webSetIntervalPolyfill>\n> {\n create(args: Parameters<typeof webSetIntervalPolyfill>) {\n // TODO: use the edge runtime provided `setInterval` instead\n return webSetIntervalPolyfill(...args)\n }\n\n destroy(interval: number) {\n clearInterval(interval)\n }\n}\n\nclass TimeoutsManager extends ResourceManager<\n number,\n Parameters<typeof webSetTimeoutPolyfill>\n> {\n create(args: Parameters<typeof webSetTimeoutPolyfill>) {\n // TODO: use the edge runtime provided `setTimeout` instead\n return webSetTimeoutPolyfill(...args)\n }\n\n destroy(timeout: number) {\n clearTimeout(timeout)\n }\n}\n\nexport type GlobalObject = import('edge-runtime').EdgeRuntime['context']\n\nfunction webSetIntervalPolyfill<TArgs extends any[]>(\n globalObject: GlobalObject,\n callback: (...args: TArgs) => void,\n ms?: number,\n ...args: TArgs\n): number {\n return setInterval(() => {\n // node's `setInterval` sets `this` to the `Timeout` instance it returned,\n // but web `setInterval` always sets `this` to `window`\n // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval#the_this_problem\n return callback.apply(globalObject, args)\n }, ms)[Symbol.toPrimitive]()\n}\n\nfunction webSetTimeoutPolyfill<TArgs extends any[]>(\n globalObject: GlobalObject,\n callback: (...args: TArgs) => void,\n ms?: number,\n ...args: TArgs\n): number {\n const wrappedCallback = () => {\n try {\n // node's `setTimeout` sets `this` to the `Timeout` instance it returned,\n // but web `setTimeout` always sets `this` to `window`\n // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#the_this_problem\n return callback.apply(globalObject, args)\n } finally {\n // On certain older node versions (<20.16.0, <22.4.0),\n // a `setTimeout` whose Timeout was converted to a primitive will leak.\n // See: https://github.com/nodejs/node/issues/53335\n // We can work around this by explicitly calling `clearTimeout` after the callback runs.\n clearTimeout(timeout)\n }\n }\n const timeout = setTimeout(wrappedCallback, ms)\n return timeout[Symbol.toPrimitive]()\n}\n\nexport const intervalsManager = new IntervalsManager()\nexport const timeoutsManager = new TimeoutsManager()\n"],"names":["intervalsManager","timeoutsManager","ResourceManager","add","resourceArgs","resource","create","resources","push","remove","filter","r","destroy","removeAll","forEach","IntervalsManager","args","webSetIntervalPolyfill","interval","clearInterval","TimeoutsManager","webSetTimeoutPolyfill","timeout","clearTimeout","globalObject","callback","ms","setInterval","apply","Symbol","toPrimitive","wrappedCallback","setTimeout"],"mappings":";;;;;;;;;;;;;;;IA2FaA,gBAAgB;eAAhBA;;IACAC,eAAe;eAAfA;;;AA5Fb,MAAeC;IAMbC,IAAIC,YAAkB,EAAE;QACtB,MAAMC,WAAW,IAAI,CAACC,MAAM,CAACF;QAC7B,IAAI,CAACG,SAAS,CAACC,IAAI,CAACH;QACpB,OAAOA;IACT;IAEAI,OAAOJ,QAAW,EAAE;QAClB,IAAI,CAACE,SAAS,GAAG,IAAI,CAACA,SAAS,CAACG,MAAM,CAAC,CAACC,IAAMA,MAAMN;QACpD,IAAI,CAACO,OAAO,CAACP;IACf;IAEAQ,YAAY;QACV,IAAI,CAACN,SAAS,CAACO,OAAO,CAAC,IAAI,CAACF,OAAO;QACnC,IAAI,CAACL,SAAS,GAAG,EAAE;IACrB;;aAnBQA,YAAiB,EAAE;;AAoB7B;AAEA,MAAMQ,yBAAyBb;IAI7BI,OAAOU,IAA+C,EAAE;QACtD,4DAA4D;QAC5D,OAAOC,0BAA0BD;IACnC;IAEAJ,QAAQM,QAAgB,EAAE;QACxBC,cAAcD;IAChB;AACF;AAEA,MAAME,wBAAwBlB;IAI5BI,OAAOU,IAA8C,EAAE;QACrD,2DAA2D;QAC3D,OAAOK,yBAAyBL;IAClC;IAEAJ,QAAQU,OAAe,EAAE;QACvBC,aAAaD;IACf;AACF;AAIA,SAASL,uBACPO,YAA0B,EAC1BC,QAAkC,EAClCC,EAAW,EACX,GAAGV,IAAW;IAEd,OAAOW,YAAY;QACjB,0EAA0E;QAC1E,uDAAuD;QACvD,4FAA4F;QAC5F,OAAOF,SAASG,KAAK,CAACJ,cAAcR;IACtC,GAAGU,GAAG,CAACG,OAAOC,WAAW,CAAC;AAC5B;AAEA,SAAST,sBACPG,YAA0B,EAC1BC,QAAkC,EAClCC,EAAW,EACX,GAAGV,IAAW;IAEd,MAAMe,kBAAkB;QACtB,IAAI;YACF,yEAAyE;YACzE,sDAAsD;YACtD,2FAA2F;YAC3F,OAAON,SAASG,KAAK,CAACJ,cAAcR;QACtC,SAAU;YACR,sDAAsD;YACtD,uEAAuE;YACvE,mDAAmD;YACnD,wFAAwF;YACxFO,aAAaD;QACf;IACF;IACA,MAAMA,UAAUU,WAAWD,iBAAiBL;IAC5C,OAAOJ,OAAO,CAACO,OAAOC,WAAW,CAAC;AACpC;AAEO,MAAM9B,mBAAmB,IAAIe;AAC7B,MAAMd,kBAAkB,IAAImB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/web/sandbox/resource-managers.ts"],"sourcesContent":["abstract class ResourceManager<T, Args> {\n private resources = new Set<T>()\n\n abstract create(resourceArgs: Args): T\n abstract destroy(resource: T): void\n\n add(resourceArgs: Args) {\n const resource = this.create(resourceArgs)\n this.resources.add(resource)\n return resource\n }\n\n remove(resource: T) {\n this.untrack(resource)\n this.destroy(resource)\n }\n\n /**\n * Stop tracking a resource without destroying it. Used when a resource has\n * already been released by other means (e.g. a one-shot timeout that ran to\n * completion) so it should no longer be retained by this manager.\n */\n protected untrack(resource: T) {\n this.resources.delete(resource)\n }\n\n removeAll() {\n for (const resource of this.resources) {\n this.destroy(resource)\n }\n this.resources.clear()\n }\n\n /** Number of resources currently tracked. Exposed for observability/tests. */\n get size() {\n return this.resources.size\n }\n}\n\nexport class IntervalsManager extends ResourceManager<\n number,\n Parameters<typeof webSetIntervalPolyfill>\n> {\n create(args: Parameters<typeof webSetIntervalPolyfill>) {\n // TODO: use the edge runtime provided `setInterval` instead\n return webSetIntervalPolyfill(...args)\n }\n\n destroy(interval: number) {\n clearInterval(interval)\n }\n}\n\nexport class TimeoutsManager extends ResourceManager<\n number,\n Parameters<typeof webSetTimeoutPolyfill>\n> {\n create(args: Parameters<typeof webSetTimeoutPolyfill>) {\n // TODO: use the edge runtime provided `setTimeout` instead\n const [globalObject, callback, ms, ...rest] = args\n\n // A one-shot timeout releases itself from tracking once its callback has\n // run. Otherwise fire-and-forget timeouts (whose ids user code never\n // passes to `clearTimeout`) would accumulate for the lifetime of the\n // module context and leak memory in long-lived server processes.\n // See: https://github.com/vercel/next.js/issues/95094\n let timeoutId: number\n const callbackWithRelease = (...callbackArgs: typeof rest) => {\n try {\n return callback.apply(globalObject, callbackArgs)\n } finally {\n this.untrack(timeoutId)\n }\n }\n\n timeoutId = webSetTimeoutPolyfill(\n globalObject,\n callbackWithRelease,\n ms,\n ...rest\n )\n return timeoutId\n }\n\n destroy(timeout: number) {\n clearTimeout(timeout)\n }\n}\n\nexport type GlobalObject = import('edge-runtime').EdgeRuntime['context']\n\nfunction webSetIntervalPolyfill<TArgs extends any[]>(\n globalObject: GlobalObject,\n callback: (...args: TArgs) => void,\n ms?: number,\n ...args: TArgs\n): number {\n return setInterval(() => {\n // node's `setInterval` sets `this` to the `Timeout` instance it returned,\n // but web `setInterval` always sets `this` to `window`\n // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval#the_this_problem\n return callback.apply(globalObject, args)\n }, ms)[Symbol.toPrimitive]()\n}\n\nfunction webSetTimeoutPolyfill<TArgs extends any[]>(\n globalObject: GlobalObject,\n callback: (...args: TArgs) => void,\n ms?: number,\n ...args: TArgs\n): number {\n const wrappedCallback = () => {\n try {\n // node's `setTimeout` sets `this` to the `Timeout` instance it returned,\n // but web `setTimeout` always sets `this` to `window`\n // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#the_this_problem\n return callback.apply(globalObject, args)\n } finally {\n // On certain older node versions (<20.16.0, <22.4.0),\n // a `setTimeout` whose Timeout was converted to a primitive will leak.\n // See: https://github.com/nodejs/node/issues/53335\n // We can work around this by explicitly calling `clearTimeout` after the callback runs.\n clearTimeout(timeout)\n }\n }\n const timeout = setTimeout(wrappedCallback, ms)\n return timeout[Symbol.toPrimitive]()\n}\n\nexport const intervalsManager = new IntervalsManager()\nexport const timeoutsManager = new TimeoutsManager()\n"],"names":["IntervalsManager","TimeoutsManager","intervalsManager","timeoutsManager","ResourceManager","add","resourceArgs","resource","create","resources","remove","untrack","destroy","delete","removeAll","clear","size","Set","args","webSetIntervalPolyfill","interval","clearInterval","globalObject","callback","ms","rest","timeoutId","callbackWithRelease","callbackArgs","apply","webSetTimeoutPolyfill","timeout","clearTimeout","setInterval","Symbol","toPrimitive","wrappedCallback","setTimeout"],"mappings":";;;;;;;;;;;;;;;;;IAuCaA,gBAAgB;eAAhBA;;IAcAC,eAAe;eAAfA;;IA4EAC,gBAAgB;eAAhBA;;IACAC,eAAe;eAAfA;;;AAlIb,MAAeC;IAMbC,IAAIC,YAAkB,EAAE;QACtB,MAAMC,WAAW,IAAI,CAACC,MAAM,CAACF;QAC7B,IAAI,CAACG,SAAS,CAACJ,GAAG,CAACE;QACnB,OAAOA;IACT;IAEAG,OAAOH,QAAW,EAAE;QAClB,IAAI,CAACI,OAAO,CAACJ;QACb,IAAI,CAACK,OAAO,CAACL;IACf;IAEA;;;;GAIC,GACD,AAAUI,QAAQJ,QAAW,EAAE;QAC7B,IAAI,CAACE,SAAS,CAACI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,yEAAyE;YACzE,sDAAsD;YACtD,2FAA2F;YAC3F,OAAOb,SAASM,KAAK,CAACP,cAAcJ;QACtC,SAAU;YACR,sDAAsD;YACtD,uEAAuE;YACvE,mDAAmD;YACnD,wFAAwF;YACxFc,aAAaD;QACf;IACF;IACA,MAAMA,UAAUM,WAAWD,iBAAiBZ;IAC5C,OAAOO,OAAO,CAACG,OAAOC,WAAW,CAAC;AACpC;AAEO,MAAMjC,mBAAmB,IAAIF;AAC7B,MAAMG,kBAAkB,IAAIF","ignoreList":[0]} |
@@ -24,3 +24,3 @@ "use strict"; | ||
| function isStableBuild() { | ||
| return !"16.3.0-canary.96"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| return !"16.3.0-canary.97"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| } | ||
@@ -27,0 +27,0 @@ class CanaryOnlyConfigError extends Error { |
@@ -85,3 +85,3 @@ "use strict"; | ||
| ciName: _ciinfo.isCI && _ciinfo.name || null, | ||
| nextVersion: "16.3.0-canary.96", | ||
| nextVersion: "16.3.0-canary.97", | ||
| agentName: await (0, _agentname.getAgentName)() | ||
@@ -88,0 +88,0 @@ }; |
@@ -14,7 +14,7 @@ "use strict"; | ||
| // This should be an invariant, if it fails our build tooling is broken. | ||
| if (typeof "16.3.0-canary.96" !== 'string') { | ||
| if (typeof "16.3.0-canary.97" !== 'string') { | ||
| return []; | ||
| } | ||
| const payload = { | ||
| nextVersion: "16.3.0-canary.96", | ||
| nextVersion: "16.3.0-canary.97", | ||
| nodeVersion: process.version, | ||
@@ -21,0 +21,0 @@ cliCommand: event.cliCommand, |
@@ -41,3 +41,3 @@ "use strict"; | ||
| payload: { | ||
| nextVersion: "16.3.0-canary.96", | ||
| nextVersion: "16.3.0-canary.97", | ||
| glibcVersion, | ||
@@ -44,0 +44,0 @@ installedSwcPackages, |
@@ -15,3 +15,3 @@ "use strict"; | ||
| // This should be an invariant, if it fails our build tooling is broken. | ||
| if (typeof "16.3.0-canary.96" !== 'string') { | ||
| if (typeof "16.3.0-canary.97" !== 'string') { | ||
| return []; | ||
@@ -21,3 +21,3 @@ } | ||
| const payload = { | ||
| nextVersion: "16.3.0-canary.96", | ||
| nextVersion: "16.3.0-canary.97", | ||
| nodeVersion: process.version, | ||
@@ -24,0 +24,0 @@ cliCommand: event.cliCommand, |
+10
-10
| { | ||
| "name": "next", | ||
| "version": "16.3.0-canary.96", | ||
| "version": "16.3.0-canary.97", | ||
| "description": "The React Framework", | ||
@@ -84,3 +84,3 @@ "main": "./dist/server/next.js", | ||
| "dependencies": { | ||
| "@next/env": "16.3.0-canary.96", | ||
| "@next/env": "16.3.0-canary.97", | ||
| "@swc/helpers": "0.5.15", | ||
@@ -116,10 +116,10 @@ "baseline-browser-mapping": "^2.9.19", | ||
| "sharp": "^0.35.3", | ||
| "@next/swc-darwin-arm64": "16.3.0-canary.96", | ||
| "@next/swc-darwin-x64": "16.3.0-canary.96", | ||
| "@next/swc-linux-arm64-gnu": "16.3.0-canary.96", | ||
| "@next/swc-linux-arm64-musl": "16.3.0-canary.96", | ||
| "@next/swc-linux-x64-gnu": "16.3.0-canary.96", | ||
| "@next/swc-linux-x64-musl": "16.3.0-canary.96", | ||
| "@next/swc-win32-arm64-msvc": "16.3.0-canary.96", | ||
| "@next/swc-win32-x64-msvc": "16.3.0-canary.96" | ||
| "@next/swc-darwin-arm64": "16.3.0-canary.97", | ||
| "@next/swc-darwin-x64": "16.3.0-canary.97", | ||
| "@next/swc-linux-arm64-gnu": "16.3.0-canary.97", | ||
| "@next/swc-linux-arm64-musl": "16.3.0-canary.97", | ||
| "@next/swc-linux-x64-gnu": "16.3.0-canary.97", | ||
| "@next/swc-linux-x64-musl": "16.3.0-canary.97", | ||
| "@next/swc-win32-arm64-msvc": "16.3.0-canary.97", | ||
| "@next/swc-win32-x64-msvc": "16.3.0-canary.97" | ||
| }, | ||
@@ -126,0 +126,0 @@ "keywords": [ |
| self.__BUILD_MANIFEST = { | ||
| "__rewrites": { | ||
| "afterFiles": [], | ||
| "beforeFiles": [], | ||
| "fallback": [] | ||
| }, | ||
| "sortedPages": [ | ||
| "/_app", | ||
| "/_error" | ||
| ] | ||
| };self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB() |
| self.__MIDDLEWARE_MATCHERS = [];self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB() |
| self.__SSG_MANIFEST=new Set([]);self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB() |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Potential vulnerability
Supply chain riskInitial human review suggests the presence of a vulnerability in this package. It is pending further analysis and confirmation.
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 7 instances
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Potential vulnerability
Supply chain riskInitial human review suggests the presence of a vulnerability in this package. It is pending further analysis and confirmation.
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 7 instances
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
181698439
5.55%8500
0.51%1302022
0.9%219
1.86%4520
1.99%730
1.67%+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
Updated