diff --git a/e-commerce/node_modules/next/dist/server/lib/server-ipc/utils.js.map b/e-commerce/node_modules/next/dist/server/lib/server-ipc/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..06f75eb57b359d7255e2c39e0292c4e7ade88192 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/server-ipc/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/lib/server-ipc/utils.ts"],"sourcesContent":["export const ipcForbiddenHeaders = [\n 'accept-encoding',\n 'keepalive',\n 'keep-alive',\n 'content-encoding',\n 'transfer-encoding',\n // https://github.com/nodejs/undici/issues/1470\n 'connection',\n // marked as unsupported by undici: https://github.com/nodejs/undici/blob/c83b084879fa0bb8e0469d31ec61428ac68160d5/lib/core/request.js#L354\n 'expect',\n]\n\nexport const actionsForbiddenHeaders = [\n ...ipcForbiddenHeaders,\n 'content-length',\n 'set-cookie',\n]\n\nexport const filterReqHeaders = (\n headers: Record,\n forbiddenHeaders: string[]\n) => {\n // Some browsers are not matching spec and sending Content-Length: 0. This causes issues in undici\n // https://github.com/nodejs/undici/issues/2046\n if (headers['content-length'] && headers['content-length'] === '0') {\n delete headers['content-length']\n }\n\n for (const [key, value] of Object.entries(headers)) {\n if (\n forbiddenHeaders.includes(key) ||\n !(Array.isArray(value) || typeof value === 'string')\n ) {\n delete headers[key]\n }\n }\n return headers as Record\n}\n\n// These are headers that are only used internally and should\n// not be honored from the external request\nconst INTERNAL_HEADERS = [\n 'x-middleware-rewrite',\n 'x-middleware-redirect',\n 'x-middleware-set-cookie',\n 'x-middleware-skip',\n 'x-middleware-override-headers',\n 'x-middleware-next',\n 'x-now-route-matches',\n 'x-matched-path',\n 'x-nextjs-data',\n 'x-next-resume-state-length',\n 'next-resume',\n]\n\nexport const filterInternalHeaders = (\n headers: Record\n) => {\n for (const header in headers) {\n if (INTERNAL_HEADERS.includes(header)) {\n delete headers[header]\n }\n }\n}\n"],"names":["actionsForbiddenHeaders","filterInternalHeaders","filterReqHeaders","ipcForbiddenHeaders","headers","forbiddenHeaders","key","value","Object","entries","includes","Array","isArray","INTERNAL_HEADERS","header"],"mappings":";;;;;;;;;;;;;;;;;IAYaA,uBAAuB;eAAvBA;;IA2CAC,qBAAqB;eAArBA;;IArCAC,gBAAgB;eAAhBA;;IAlBAC,mBAAmB;eAAnBA;;;AAAN,MAAMA,sBAAsB;IACjC;IACA;IACA;IACA;IACA;IACA,+CAA+C;IAC/C;IACA,2IAA2I;IAC3I;CACD;AAEM,MAAMH,0BAA0B;OAClCG;IACH;IACA;CACD;AAEM,MAAMD,mBAAmB,CAC9BE,SACAC;IAEA,kGAAkG;IAClG,+CAA+C;IAC/C,IAAID,OAAO,CAAC,iBAAiB,IAAIA,OAAO,CAAC,iBAAiB,KAAK,KAAK;QAClE,OAAOA,OAAO,CAAC,iBAAiB;IAClC;IAEA,KAAK,MAAM,CAACE,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACL,SAAU;QAClD,IACEC,iBAAiBK,QAAQ,CAACJ,QAC1B,CAAEK,CAAAA,MAAMC,OAAO,CAACL,UAAU,OAAOA,UAAU,QAAO,GAClD;YACA,OAAOH,OAAO,CAACE,IAAI;QACrB;IACF;IACA,OAAOF;AACT;AAEA,6DAA6D;AAC7D,2CAA2C;AAC3C,MAAMS,mBAAmB;IACvB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAEM,MAAMZ,wBAAwB,CACnCG;IAEA,IAAK,MAAMU,UAAUV,QAAS;QAC5B,IAAIS,iBAAiBH,QAAQ,CAACI,SAAS;YACrC,OAAOV,OAAO,CAACU,OAAO;QACxB;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/source-maps.d.ts b/e-commerce/node_modules/next/dist/server/lib/source-maps.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..77808f1bbb3fc67473887ba63c841bda23ca55c9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/source-maps.d.ts @@ -0,0 +1,52 @@ +/** + * https://tc39.es/source-map/#index-map + */ +interface IndexSourceMapSection { + offset: { + line: number; + column: number; + }; + map: BasicSourceMapPayload; +} +/** https://tc39.es/ecma426/#sec-index-source-map */ +interface IndexSourceMap { + version: number; + file: string; + sections: IndexSourceMapSection[]; +} +/** https://tc39.es/ecma426/#sec-source-map-format */ +export interface BasicSourceMapPayload { + version: number; + /** WARNING: `file` is optional. */ + file: string; + sourceRoot?: string; + /** WARNING: `sources[number]` can be `null`. */ + sources: Array; + names: Array; + mappings: string; + ignoreList?: number[]; +} +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; +/** + * Finds the sourcemap payload applicable to a given frame. + * Equal to the input unless an Index Source Map is used. + * @param line0 - The line number of the frame, 0-based. + * @param column0 - The column number of the frame, 0-based. + */ +export declare function findApplicableSourceMapPayload(line0: number, column0: number, payload: ModernSourceMapPayload): BasicSourceMapPayload | undefined; +export declare function filterStackFrameDEV(sourceURL: string, functionName: string, line1: number, column1: number): boolean; +type FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null; +export declare function setBundlerFindSourceMapURLImplementation(findSourceMapURLImplementation: FindSourceMapURL): void; +export declare function findSourceMapURLDEV(scriptNameOrSourceURL: string): string | null; +export declare function devirtualizeReactServerURL(sourceURL: string): string; +export declare function ignoreListAnonymousStackFramesIfSandwiched(frames: Frame[], isAnonymousFrame: (frame: Frame) => boolean, isIgnoredFrame: (frame: Frame) => boolean, getMethodName: (frame: Frame) => string, +/** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */ +ignoreFrame: (frame: Frame) => void): void; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/lib/source-maps.js b/e-commerce/node_modules/next/dist/server/lib/source-maps.js new file mode 100644 index 0000000000000000000000000000000000000000..9a58c947f5cfbef6343574baa14055a83765b113 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/source-maps.js @@ -0,0 +1,241 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + devirtualizeReactServerURL: null, + filterStackFrameDEV: null, + findApplicableSourceMapPayload: null, + findSourceMapPayload: null, + findSourceMapURLDEV: null, + ignoreListAnonymousStackFramesIfSandwiched: null, + setBundlerFindSourceMapURLImplementation: null, + sourceMapIgnoreListsEverything: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + devirtualizeReactServerURL: function() { + return devirtualizeReactServerURL; + }, + filterStackFrameDEV: function() { + return filterStackFrameDEV; + }, + findApplicableSourceMapPayload: function() { + return findApplicableSourceMapPayload; + }, + findSourceMapPayload: function() { + return findSourceMapPayload; + }, + findSourceMapURLDEV: function() { + return findSourceMapURLDEV; + }, + ignoreListAnonymousStackFramesIfSandwiched: function() { + return ignoreListAnonymousStackFramesIfSandwiched; + }, + setBundlerFindSourceMapURLImplementation: function() { + return setBundlerFindSourceMapURLImplementation; + }, + sourceMapIgnoreListsEverything: function() { + return sourceMapIgnoreListsEverything; + } +}); +const _lrucache = require("./lru-cache"); +function noSourceMap() { + return undefined; +} +// Edge runtime does not implement `module` +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) { + return sourceMap.ignoreList !== undefined && sourceMap.sources.length === sourceMap.ignoreList.length; +} +function findApplicableSourceMapPayload(line0, column0, payload) { + if ('sections' in payload) { + if (payload.sections.length === 0) { + return undefined; + } + // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object + // Therefore the last section that has an offset less than or equal to the frame is the applicable one. + const sections = payload.sections; + let left = 0; + let right = sections.length - 1; + let result = null; + while(left <= right){ + // fast Math.floor + const middle = ~~((left + right) / 2); + const section = sections[middle]; + const offset = section.offset; + if (offset.line < line0 || offset.line === line0 && offset.column <= column0) { + result = section; + left = middle + 1; + } else { + right = middle - 1; + } + } + return result === null ? undefined : result.map; + } else { + return payload; + } +} +const didWarnAboutInvalidSourceMapDEV = new Set(); +function filterStackFrameDEV(sourceURL, functionName, line1, column1) { + if (sourceURL === '') { + // The default implementation filters out stack frames + // but we want to retain them because current Server Components and + // built-in Components in parent stacks don't have source location. + // Filter out frames that show up in Promises to get good names in React's + // Server Request track until we come up with a better heuristic. + return functionName !== 'new Promise'; + } + if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) { + return false; + } + try { + // Node.js loads source maps eagerly so this call is cheap. + // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules). + // Make sure this doesn't adversely affect performance when CJS is used by Next.js. + const payload = findSourceMapPayload(sourceURL); + if (payload === undefined) { + // No source map associated. + return true; + } + const sourceMapPayload = findApplicableSourceMapPayload(line1 - 1, column1 - 1, payload); + if (sourceMapPayload === undefined) { + // No source map section applicable to the frame. + return true; + } + return !sourceMapIgnoreListsEverything(sourceMapPayload); + } catch (cause) { + if (process.env.NODE_ENV !== 'production') { + // TODO: Share cache with patch-error-inspect + if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) { + didWarnAboutInvalidSourceMapDEV.add(sourceURL); + // We should not log an actual error instance here because that will re-enter + // this codepath during error inspection and could lead to infinite recursion. + console.error(`${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`); + } + } + return true; + } +} +// Find the URL of a source map using the bundler's API. +// Shared via `globalThis` because this module is compiled both into the server +// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server` +// (where the dev server registers the implementation), and each copy has its own +// module state. +const bundlerFindSourceMapURLSymbol = Symbol.for('next.server.bundlerFindSourceMapURL'); +function setBundlerFindSourceMapURLImplementation(findSourceMapURLImplementation) { + ; + globalThis[bundlerFindSourceMapURLSymbol] = findSourceMapURLImplementation; +} +function bundlerFindSourceMapURL(scriptNameOrSourceURL) { + const implementation = globalThis[bundlerFindSourceMapURLSymbol]; + return implementation === undefined ? null : implementation(scriptNameOrSourceURL); +} +const invalidSourceMap = Symbol('invalid-source-map'); +const sourceMapURLs = new _lrucache.LRUCache(512 * 1024 * 1024, (url, sourceURL)=>sourceURL.length + (url === invalidSourceMap ? 8 * 1024 : url.length)); +function findSourceMapURLDEV(scriptNameOrSourceURL) { + try { + const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL); + if (bundlerSourceMapURL !== null) { + return bundlerSourceMapURL; + } + } catch (cause) { + console.error(`${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`); + } + // No bundler implementation (e.g. Webpack): inline the source map Node.js + // knows as a `data:` URL. + let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL); + if (sourceMapURL === undefined) { + let sourceMapPayload; + try { + sourceMapPayload = findSourceMapPayload(scriptNameOrSourceURL); + } catch (cause) { + console.error(`${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`); + } + if (sourceMapPayload === undefined) { + sourceMapURL = invalidSourceMap; + } else { + // TODO: Might be more efficient to extract the relevant section from Index Maps. + // Unclear if that search is worth the smaller payload we have to stringify. + const sourceMapJSON = JSON.stringify(sourceMapPayload); + const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString('base64'); + sourceMapURL = `data:application/json;base64,${sourceMapURLData}`; + } + sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL); + } + return sourceMapURL === invalidSourceMap ? null : sourceMapURL; +} +function devirtualizeReactServerURL(sourceURL) { + if (sourceURL.startsWith('about://React/')) { + // about://React/Server/file://?42 => file:// + const envIdx = sourceURL.indexOf('/', 'about://React/'.length); + const suffixIdx = sourceURL.lastIndexOf('?'); + if (envIdx > -1 && suffixIdx > -1) { + return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx)); + } + } + return sourceURL; +} +function isAnonymousFrameLikelyJSNative(methodName) { + // Anonymous frames can also be produced in React parent stacks either from + // host components or Server Components. We don't want to ignore those. + // This could hide user-space methods that are named like native JS methods but + // should you really do that? + return(// e.g. JSON.parse + methodName.startsWith('JSON.') || // E.g. Promise.withResolves + methodName.startsWith('Function.') || // various JS built-ins + methodName.startsWith('Promise.') || methodName.startsWith('Array.') || methodName.startsWith('Set.') || methodName.startsWith('Map.')); +} +function ignoreListAnonymousStackFramesIfSandwiched(frames, isAnonymousFrame, isIgnoredFrame, getMethodName, /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */ ignoreFrame) { + for(let i = 1; i < frames.length; i++){ + const currentFrame = frames[i]; + if (!(isAnonymousFrame(currentFrame) && isAnonymousFrameLikelyJSNative(getMethodName(currentFrame)))) { + continue; + } + const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1]); + if (previousFrameIsIgnored && i < frames.length - 1) { + let ignoreSandwich = false; + let j = i + 1; + for(j; j < frames.length; j++){ + const nextFrame = frames[j]; + const nextFrameIsAnonymous = isAnonymousFrame(nextFrame) && isAnonymousFrameLikelyJSNative(getMethodName(nextFrame)); + if (nextFrameIsAnonymous) { + continue; + } + const nextFrameIsIgnored = isIgnoredFrame(nextFrame); + if (nextFrameIsIgnored) { + ignoreSandwich = true; + break; + } + } + if (ignoreSandwich) { + for(i; i < j; i++){ + ignoreFrame(frames[i]); + } + } + } + } +} + +//# sourceMappingURL=source-maps.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/source-maps.js.map b/e-commerce/node_modules/next/dist/server/lib/source-maps.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ebe3366054db0a894a4a59a2434a18ed0c1ddc61 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/source-maps.js.map @@ -0,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\n names: Array\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()\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()\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 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(\n 512 * 1024 * 1024,\n (url, sourceURL) =>\n sourceURL.length +\n (url === invalidSourceMap\n ? // Guestimate a small source map so invalid entries don't fill the cache.\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://?42 => file://\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(\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,U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kBAAkB;IAClBA,WAAWrC,UAAU,CAAC,YACtB,4BAA4B;IAC5BqC,WAAWrC,UAAU,CAAC,gBACtB,uBAAuB;IACvBqC,WAAWrC,UAAU,CAAC,eACtBqC,WAAWrC,UAAU,CAAC,aACtBqC,WAAWrC,UAAU,CAAC,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]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/start-server.d.ts b/e-commerce/node_modules/next/dist/server/lib/start-server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad404547eb5bcedc083f7c2c2cbe8c695f534960 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/start-server.d.ts @@ -0,0 +1,34 @@ +import './cpu-profile'; +import '../next'; +import '../require-hook'; +import type { SelfSignedCertificate } from '../../lib/mkcert'; +import { initialize } from './router-server'; +export interface StartServerOptions { + dir: string; + port: number; + isDev: boolean; + hostname?: string; + allowRetry?: boolean; + customServer?: boolean; + minimalMode?: boolean; + keepAliveTimeout?: number; + selfSignedCertificate?: SelfSignedCertificate; + serverFastRefresh?: boolean; +} +export declare function getRequestHandlers({ dir, port, isDev, onDevServerCleanup, server, hostname, minimalMode, keepAliveTimeout, experimentalHttpsServer, serverFastRefresh, quiet, }: { + dir: string; + port: number; + isDev: boolean; + onDevServerCleanup: ((listener: () => Promise) => void) | undefined; + server?: import('http').Server; + hostname?: string; + minimalMode?: boolean; + keepAliveTimeout?: number; + experimentalHttpsServer?: boolean; + serverFastRefresh?: boolean; + quiet?: boolean; +}): ReturnType; +export type StartServerResult = { + distDir: string; +}; +export declare function startServer(serverOptions: StartServerOptions): Promise; diff --git a/e-commerce/node_modules/next/dist/server/lib/start-server.js b/e-commerce/node_modules/next/dist/server/lib/start-server.js new file mode 100644 index 0000000000000000000000000000000000000000..4f20807e6e54b96d8b26bae5c16b6ed7370aa9fd --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/start-server.js @@ -0,0 +1,550 @@ +// Start CPU profile if it wasn't already started. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getRequestHandlers: null, + startServer: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getRequestHandlers: function() { + return getRequestHandlers; + }, + startServer: function() { + return startServer; + } +}); +require("./cpu-profile"); +const _getnetworkhost = require("../../lib/get-network-host"); +require("../next"); +require("../require-hook"); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _v8 = /*#__PURE__*/ _interop_require_default(require("v8")); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _http = /*#__PURE__*/ _interop_require_default(require("http")); +const _https = /*#__PURE__*/ _interop_require_default(require("https")); +const _os = /*#__PURE__*/ _interop_require_default(require("os")); +const _child_process = require("child_process"); +const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log")); +const _debug = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/debug")); +const _utils = require("./utils"); +const _formathostname = require("./format-hostname"); +const _routerserver = require("./router-server"); +const _constants = require("../../shared/lib/constants"); +const _appinfolog = require("./app-info-log"); +const _turbopackwarning = require("../../lib/turbopack-warning"); +const _trace = require("../../trace"); +const _isipv6 = require("./is-ipv6"); +const _asynccallbackset = require("./async-callback-set"); +const _durationtostring = require("../../build/duration-to-string"); +const _ciinfo = require("../ci-info"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +const debug = (0, _debug.default)('next:start-server'); +let startServerSpan; +/** + * Get the process ID (PID) of the process using the specified port + */ async function getProcessIdUsingPort(port) { + const timeoutMs = 250; + const processLookupController = new AbortController(); + const pidPromise = new Promise((resolve)=>{ + const handleError = (error)=>{ + debug('Failed to get process ID for port', port, error); + resolve(null); + }; + try { + // Use lsof on Unix-like systems (macOS, Linux) + if (process.platform !== 'win32') { + (0, _child_process.exec)(`lsof -ti:${port} -sTCP:LISTEN`, { + signal: processLookupController.signal + }, (error, stdout)=>{ + if (error) { + handleError(error); + return; + } + // `-sTCP` will ensure there's only one port, clean up output + const pid = stdout.trim(); + resolve(pid || null); + }); + } else { + // Use netstat on Windows + (0, _child_process.exec)(`netstat -ano | findstr /C:":${port} " | findstr LISTENING`, { + signal: processLookupController.signal + }, (error, stdout)=>{ + if (error) { + handleError(error); + return; + } + // Clean up output and extract PID + const cleanOutput = stdout.replace(/\s+/g, ' ').trim(); + if (cleanOutput) { + const lines = cleanOutput.split('\n'); + const firstLine = lines[0].trim(); + if (firstLine) { + const parts = firstLine.split(' '); + const pid = parts[parts.length - 1]; + resolve(pid || null); + } else { + resolve(null); + } + } else { + resolve(null); + } + }); + } + } catch (cause) { + handleError(new Error('Unexpected error during process lookup', { + cause + })); + } + }); + const timeoutId = setTimeout(()=>{ + processLookupController.abort(`PID detection timed out after ${timeoutMs}ms for port ${port}.`); + }, timeoutMs); + pidPromise.finally(()=>clearTimeout(timeoutId)); + return pidPromise; +} +async function getRequestHandlers({ dir, port, isDev, onDevServerCleanup, server, hostname, minimalMode, keepAliveTimeout, experimentalHttpsServer, serverFastRefresh, quiet }) { + return (0, _routerserver.initialize)({ + dir, + port, + hostname, + onDevServerCleanup, + dev: isDev, + minimalMode, + server, + keepAliveTimeout, + experimentalHttpsServer, + serverFastRefresh, + startServerSpan, + quiet + }); +} +async function startServer(serverOptions) { + const { dir, isDev, hostname, minimalMode, allowRetry, keepAliveTimeout, selfSignedCertificate, serverFastRefresh } = serverOptions; + let { port } = serverOptions; + process.title = `next-server (v${"16.4.0"})`; + let handlersReady = ()=>{}; + let handlersError = ()=>{}; + let handlersPromise = new Promise((resolve, reject)=>{ + handlersReady = resolve; + handlersError = reject; + }); + let requestHandler = async (req, res)=>{ + if (handlersPromise) { + await handlersPromise; + return requestHandler(req, res); + } + throw new Error('Invariant request handler was not setup'); + }; + let upgradeHandler = async (req, socket, head)=>{ + if (handlersPromise) { + await handlersPromise; + return upgradeHandler(req, socket, head); + } + throw new Error('Invariant upgrade handler was not setup'); + }; + let nextServer; + let devMemoryThresholdRestart = true; + // setup server listener as fast as possible + if (selfSignedCertificate && !isDev) { + throw new Error('Using a self signed certificate is only supported with `next dev`.'); + } + async function requestListener(req, res) { + try { + if (handlersPromise) { + await handlersPromise; + handlersPromise = undefined; + } + await requestHandler(req, res); + } catch (err) { + res.statusCode = 500; + res.end('Internal Server Error'); + _log.error(`Failed to handle request for ${req.url}`); + console.error(err); + } finally{ + const memoryRestartStats = (0, _utils.getMemoryRestartStats)(isDev, devMemoryThresholdRestart, _v8.default.getHeapStatistics); + if (memoryRestartStats) { + _log.warn(`Server is approaching the used memory threshold, restarting...`); + (0, _trace.trace)('server-restart-close-to-memory-threshold', undefined, { + 'memory.heapSizeLimit': String(memoryRestartStats.heap_size_limit), + 'memory.heapUsed': String(memoryRestartStats.used_heap_size) + }).stop(); + (0, _trace.flushAllTraces)(); + process.exit(_utils.RESTART_EXIT_CODE); + } + } + } + const server = selfSignedCertificate ? _https.default.createServer({ + key: _fs.default.readFileSync(selfSignedCertificate.key), + cert: _fs.default.readFileSync(selfSignedCertificate.cert) + }, requestListener) : _http.default.createServer(requestListener); + if (keepAliveTimeout) { + server.keepAliveTimeout = keepAliveTimeout; + } + server.on('upgrade', async (req, socket, head)=>{ + try { + await upgradeHandler(req, socket, head); + } catch (err) { + socket.destroy(); + _log.error(`Failed to handle request for ${req.url}`); + console.error(err); + } + }); + let portRetryCount = 0; + const originalPort = port; + server.on('error', (err)=>{ + if (allowRetry && port && isDev && err.code === 'EADDRINUSE' && portRetryCount < 10) { + port += 1; + portRetryCount += 1; + server.listen(port, hostname); + } else { + _log.error(`Failed to start server`); + console.error(err); + process.exit(1); + } + }); + let cleanupListeners = isDev ? new _asynccallbackset.AsyncCallbackSet() : undefined; + const distDir = await new Promise((resolve)=>{ + server.on('listening', async ()=>{ + const addr = server.address(); + const actualHostname = (0, _formathostname.formatHostname)(typeof addr === 'object' ? (addr == null ? void 0 : addr.address) || hostname || 'localhost' : addr); + const formattedHostname = !hostname || actualHostname === '0.0.0.0' ? 'localhost' : actualHostname === '[::]' ? '[::1]' : (0, _formathostname.formatHostname)(hostname); + port = typeof addr === 'object' ? (addr == null ? void 0 : addr.port) || port : port; + if (portRetryCount) { + const pid = await getProcessIdUsingPort(originalPort); + if (pid) { + _log.warn(`Port ${originalPort} is in use by process ${pid}, using available port ${port} instead.`); + } else { + _log.warn(`Port ${originalPort} is in use by an unknown process, using available port ${port} instead.`); + } + } + const networkHostname = hostname ?? (0, _getnetworkhost.getNetworkHost)((0, _isipv6.isIPv6)(actualHostname) ? 'IPv6' : 'IPv4'); + const protocol = selfSignedCertificate ? 'https' : 'http'; + const networkUrl = networkHostname ? `${protocol}://${(0, _formathostname.formatHostname)(networkHostname)}:${port}` : null; + const appUrl = `${protocol}://${formattedHostname}:${port}`; + // Store the selected port to: + // - expose it to render workers + // - re-use it for automatic dev server restarts with a randomly selected port + process.env.PORT = port + ''; + process.env.__NEXT_PRIVATE_ORIGIN = appUrl; + // Set experimental HTTPS flag for metadata resolution + if (selfSignedCertificate) { + process.env.__NEXT_EXPERIMENTAL_HTTPS = '1'; + } + // Get env info first (fast, doesn't require config) + const envInfo = isDev ? (0, _appinfolog.getEnvInfo)(dir) : undefined; + // Log basic startup info immediately (before loading config) + (0, _appinfolog.logStartInfo)({ + networkUrl, + appUrl, + envInfo, + logBundler: isDev + }); + // Calculate and log "Ready in X" before loading config + // so it reflects actual framework startup time. + // NEXT_PRIVATE_START_TIME is set by bin/next.ts or cli/next-start.ts. + const startTime = parseInt(process.env.NEXT_PRIVATE_START_TIME || '0', 10); + const endTime = Date.now(); + const startServerProcessDurationMs = startTime ? endTime - startTime : 0; + const formattedStartDuration = (0, _durationtostring.durationToString)(startServerProcessDurationMs / 1000); + _log.event(`Ready in ${formattedStartDuration}`); + try { + let cleanupStarted = false; + let closeUpgraded = null; + const cleanup = (signal)=>{ + if (cleanupStarted) { + // We can get duplicate signals, e.g. when `ctrl+c` is used in an + // interactive shell (i.e. bash, zsh), the shell will recursively + // send SIGINT to children. The parent `next-dev` process will also + // send us SIGINT. + return; + } + cleanupStarted = true; + (async ()=>{ + debug('start-server process cleanup'); + // first, stop accepting new connections and finish pending requests, + // because they might affect `nextServer.close()` (e.g. by scheduling an `after`) + await new Promise((res)=>{ + server.close((err)=>{ + if (err) console.error(err); + res(); + }); + if (isDev) { + server.closeAllConnections(); + closeUpgraded == null ? void 0 : closeUpgraded(); + } + }); + // now that no new requests can come in, clean up the rest + await Promise.all([ + nextServer == null ? void 0 : nextServer.close().catch(console.error), + cleanupListeners == null ? void 0 : cleanupListeners.runAll().catch(console.error) + ]); + // Flush any remaining traces to the trace file on shutdown + (0, _trace.flushAllTraces)(); + // Flush telemetry if this is a dev server + if (isDev) { + try { + const { traceGlobals } = require('../../trace/shared'); + const telemetry = traceGlobals.get('telemetry'); + if (telemetry) { + // Use flushDetached to avoid blocking process exit + // Each process writes to a unique file (_events_${pid}.json) + // to avoid race conditions with the parent process + telemetry.flushDetached({ + mode: 'dev', + dir, + distDir: null, + events: null + }); + } + } catch (_) { + // Ignore telemetry errors during cleanup + } + } + debug('start-server process cleanup finished'); + // Exit with signal-based exit code (128 + signal number) so that + // Node.js treats this as a signal termination, not a normal exit. + // This avoids waiting for the debugger to disconnect. + switch(signal){ + case 'SIGINT': + process.exit(130); + break; + case 'SIGTERM': + process.exit(143); + break; + default: + // Make sure all handled signals have explicit exit codes. + // This is just a fallback to guard against unsound types. + signal; + process.exit(128); + } + })(); + }; + // Make sure commands gracefully respect termination signals (e.g. from Docker) + // Allow the graceful termination to be manually configurable + if (!process.env.NEXT_MANUAL_SIG_HANDLE) { + process.on('SIGINT', cleanup); + process.on('SIGTERM', cleanup); + } + // Now load config via getRequestHandlers (single loadConfig call) + const initResult = await getRequestHandlers({ + dir, + port, + isDev, + onDevServerCleanup: cleanupListeners ? cleanupListeners.add.bind(cleanupListeners) : undefined, + server, + hostname, + minimalMode, + keepAliveTimeout, + experimentalHttpsServer: !!selfSignedCertificate, + serverFastRefresh + }); + devMemoryThresholdRestart = initResult.devMemoryThresholdRestart; + requestHandler = initResult.requestHandler; + upgradeHandler = initResult.upgradeHandler; + nextServer = initResult.server; + closeUpgraded = initResult.closeUpgraded; + // Log experimental features after config is loaded + if (isDev) { + (0, _appinfolog.logExperimentalInfo)({ + experimentalFeatures: initResult.experimentalFeatures, + cacheComponents: initResult.cacheComponents, + partialPrefetching: initResult.partialPrefetching + }); + logAgentFileSync(await (0, _appinfolog.syncAgentRulesForDev)(dir, initResult.agentRules !== false), (files)=>`Generated ${files} for AI agents. Set \`agentRules: false\` in next.config to disable.`, (files)=>`Removed agent rules from ${files} because \`agentRules\` is disabled.`); + if (!_ciinfo.isCI) { + const { traceGlobals } = require('../../trace/shared'); + const telemetry = traceGlobals.get('telemetry'); + const agentFeedbackConfigured = initResult.agentFeedback === true; + const telemetryEnabled = (telemetry == null ? void 0 : telemetry.isEnabled) === true; + logAgentFileSync(await (0, _appinfolog.syncAgentFeedbackForDev)(dir, agentFeedbackConfigured && telemetryEnabled), (files)=>`Generated agent feedback instructions in ${files}. Set \`experimental.agentFeedback: false\` in next.config to disable.`, (files)=>agentFeedbackConfigured ? `Removed agent feedback instructions from ${files} because Next.js Telemetry is disabled.` : `Removed agent feedback instructions from ${files} because \`experimental.agentFeedback\` is disabled.`); + } + } + handlersReady(); + if (process.env.TURBOPACK && isDev) { + await (0, _turbopackwarning.validateTurboNextConfig)({ + dir: serverOptions.dir, + configPhase: _constants.PHASE_DEVELOPMENT_SERVER + }); + } + resolve(initResult.distDir); + } catch (err) { + // fatal error if we can't setup + handlersError(); + console.error(err); + process.exit(1); + } + }); + server.listen(port, hostname); + }); + // Watch config files for changes and distDir ancestors for deletion. + if (isDev) { + // Note: dir is absolute and normalized (`..` segments removed), `absDistDir` + // is also normalized because `path.join()` performs normalization. `distDir` + // does not have to be inside of `dir`! + const absDistDir = _path.default.join(dir, distDir); + // always watch dir and absDistDir + const dirWatchPaths = [ + dir, + absDistDir + ]; + // also watch ancestors of absDistDir that are inside of dir. + let prevAncestor = absDistDir; + while(true){ + const nextAncestor = _path.default.dirname(prevAncestor); + // note: `dirname('/') === '/'` if we happen to reach the FS root + if (!nextAncestor.startsWith(dir + _path.default.sep) || nextAncestor === prevAncestor) { + break; + } + dirWatchPaths.push(nextAncestor); + prevAncestor = nextAncestor; + } + const configFiles = _constants.CONFIG_FILES.map((file)=>_path.default.join(dir, file)); + const Watchpack = require('next/dist/compiled/watchpack'); + const wp = new Watchpack(); + wp.watch({ + files: configFiles, + missing: dirWatchPaths + }); + wp.on('change', async (filename)=>{ + if (!configFiles.includes(filename)) { + return; + } + _log.warn(`Found a change in ${_path.default.basename(filename)}. Restarting the server to apply the changes...`); + process.exit(_utils.RESTART_EXIT_CODE); + }); + wp.on('remove', (removedPath)=>{ + if (dirWatchPaths.includes(removedPath)) { + _log.error(`The directory at "${removedPath}" was deleted.\n\n` + 'Deleting this directory removes caches and will cause slower ' + 'performance.\n\n' + 'Deleting this directory while Next.js is running can lead to ' + 'undefined behavior. Restarting the server to recover...'); + process.exit(_utils.RESTART_EXIT_CODE); + } + }); + } + return { + distDir + }; +} +if (process.env.NEXT_PRIVATE_WORKER && process.send) { + // Output is piped to the CLI to hold it while the upgrade menu is open. + if (process.env.NEXT_PRIVATE_PROMPT_OUTPUT === '1') { + (0, _utils.blockOnOutputWrites)(); + } + process.addListener('message', async (msg)=>{ + if (msg && typeof msg === 'object' && msg.nextWorkerOptions && process.send) { + let enabledFeaturesFromParent = {}; + if (process.env.NEXT_PRIVATE_ENABLED_FEATURES) { + const parsed = JSON.parse(process.env.NEXT_PRIVATE_ENABLED_FEATURES); + enabledFeaturesFromParent = Object.fromEntries(Object.entries(parsed).map(([key, value])=>[ + `feature.${key}`, + value + ])); + } + let rageRestartAttrsFromParent = {}; + if (process.env.NEXT_PRIVATE_DEV_SPAN_ATTRS) { + rageRestartAttrsFromParent = JSON.parse(process.env.NEXT_PRIVATE_DEV_SPAN_ATTRS); + } + startServerSpan = (0, _trace.trace)('start-dev-server', undefined, { + cpus: String(_os.default.cpus().length), + platform: _os.default.platform(), + 'memory.freeMem': String(_os.default.freemem()), + 'memory.totalMem': String(_os.default.totalmem()), + 'memory.heapSizeLimit': String(_v8.default.getHeapStatistics().heap_size_limit), + ...enabledFeaturesFromParent, + ...rageRestartAttrsFromParent + }); + (0, _trace.initializeTraceState)({ + ...(0, _trace.exportTraceState)(), + defaultParentSpanId: startServerSpan.getId() + }); + const result = await startServerSpan.traceAsyncFn(()=>startServer(msg.nextWorkerOptions)); + const memoryUsage = process.memoryUsage(); + startServerSpan.setAttribute('memory.rss', String(memoryUsage.rss)); + startServerSpan.setAttribute('memory.heapTotal', String(memoryUsage.heapTotal)); + startServerSpan.setAttribute('memory.heapUsed', String(memoryUsage.heapUsed)); + process.send({ + nextServerReady: true, + port: process.env.PORT, + distDir: result.distDir + }); + } + }); + process.send({ + nextWorkerReady: true + }); +} +/** + * Report which agent files a managed-block sync touched. Silent when the sync + * was a no-op so every `next dev` start doesn't mention the files. + */ function logAgentFileSync(result, generatedMessage, removedMessage) { + if (!result) return; + const generated = []; + const removed = []; + for (const [file, action] of [ + [ + 'AGENTS.md', + result.agentsMd + ] + ]){ + if (action === 'created' || action === 'updated') { + generated.push(file); + } else if (action === 'removed') { + removed.push(file); + } + } + if (generated.length > 0) _log.event(generatedMessage(generated.join(' and '))); + if (removed.length > 0) _log.event(removedMessage(removed.join(' and '))); +} + +//# sourceMappingURL=start-server.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/start-server.js.map b/e-commerce/node_modules/next/dist/server/lib/start-server.js.map new file mode 100644 index 0000000000000000000000000000000000000000..11827094aa8636f241de2fecc60e5ae614b06341 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/start-server.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/lib/start-server.ts"],"sourcesContent":["// Start CPU profile if it wasn't already started.\nimport './cpu-profile'\nimport { getNetworkHost } from '../../lib/get-network-host'\n\nimport '../next'\nimport '../require-hook'\n\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { SelfSignedCertificate } from '../../lib/mkcert'\nimport type { WorkerRequestHandler, WorkerUpgradeHandler } from './types'\n\nimport fs from 'fs'\nimport v8 from 'v8'\nimport path from 'path'\nimport http from 'http'\nimport https from 'https'\nimport os from 'os'\nimport { exec } from 'child_process'\nimport * as Log from '../../build/output/log'\nimport setupDebug from 'next/dist/compiled/debug'\nimport {\n blockOnOutputWrites,\n getMemoryRestartStats,\n RESTART_EXIT_CODE,\n} from './utils'\nimport { formatHostname } from './format-hostname'\nimport { initialize } from './router-server'\nimport {\n CONFIG_FILES,\n PHASE_DEVELOPMENT_SERVER,\n} from '../../shared/lib/constants'\nimport {\n getEnvInfo,\n logExperimentalInfo,\n logStartInfo,\n syncAgentFeedbackForDev,\n syncAgentRulesForDev,\n} from './app-info-log'\nimport type { AgentFilesResult } from './generate-agent-files'\nimport { validateTurboNextConfig } from '../../lib/turbopack-warning'\nimport {\n type Span,\n trace,\n flushAllTraces,\n exportTraceState,\n initializeTraceState,\n} from '../../trace'\nimport { isIPv6 } from './is-ipv6'\nimport { AsyncCallbackSet } from './async-callback-set'\nimport type { NextServer } from '../next'\nimport { durationToString } from '../../build/duration-to-string'\nimport { isCI } from '../ci-info'\n\nconst debug = setupDebug('next:start-server')\nlet startServerSpan: Span | undefined\n\n/**\n * Get the process ID (PID) of the process using the specified port\n */\nasync function getProcessIdUsingPort(port: number): Promise {\n const timeoutMs = 250\n const processLookupController = new AbortController()\n\n const pidPromise = new Promise((resolve) => {\n const handleError = (error: Error) => {\n debug('Failed to get process ID for port', port, error)\n resolve(null)\n }\n\n try {\n // Use lsof on Unix-like systems (macOS, Linux)\n if (process.platform !== 'win32') {\n exec(\n `lsof -ti:${port} -sTCP:LISTEN`,\n { signal: processLookupController.signal },\n (error, stdout) => {\n if (error) {\n handleError(error)\n return\n }\n // `-sTCP` will ensure there's only one port, clean up output\n const pid = stdout.trim()\n resolve(pid || null)\n }\n )\n } else {\n // Use netstat on Windows\n exec(\n `netstat -ano | findstr /C:\":${port} \" | findstr LISTENING`,\n { signal: processLookupController.signal },\n (error, stdout) => {\n if (error) {\n handleError(error)\n return\n }\n // Clean up output and extract PID\n const cleanOutput = stdout.replace(/\\s+/g, ' ').trim()\n if (cleanOutput) {\n const lines = cleanOutput.split('\\n')\n const firstLine = lines[0].trim()\n if (firstLine) {\n const parts = firstLine.split(' ')\n const pid = parts[parts.length - 1]\n resolve(pid || null)\n } else {\n resolve(null)\n }\n } else {\n resolve(null)\n }\n }\n )\n }\n } catch (cause) {\n handleError(\n new Error('Unexpected error during process lookup', { cause })\n )\n }\n })\n\n const timeoutId = setTimeout(() => {\n processLookupController.abort(\n `PID detection timed out after ${timeoutMs}ms for port ${port}.`\n )\n }, timeoutMs)\n\n pidPromise.finally(() => clearTimeout(timeoutId))\n\n return pidPromise\n}\n\nexport interface StartServerOptions {\n dir: string\n port: number\n isDev: boolean\n hostname?: string\n allowRetry?: boolean\n customServer?: boolean\n minimalMode?: boolean\n keepAliveTimeout?: number\n // this is dev-server only\n selfSignedCertificate?: SelfSignedCertificate\n serverFastRefresh?: boolean\n}\n\nexport async function getRequestHandlers({\n dir,\n port,\n isDev,\n onDevServerCleanup,\n server,\n hostname,\n minimalMode,\n keepAliveTimeout,\n experimentalHttpsServer,\n serverFastRefresh,\n quiet,\n}: {\n dir: string\n port: number\n isDev: boolean\n onDevServerCleanup: ((listener: () => Promise) => void) | undefined\n server?: import('http').Server\n hostname?: string\n minimalMode?: boolean\n keepAliveTimeout?: number\n experimentalHttpsServer?: boolean\n serverFastRefresh?: boolean\n quiet?: boolean\n}): ReturnType {\n return initialize({\n dir,\n port,\n hostname,\n onDevServerCleanup,\n dev: isDev,\n minimalMode,\n server,\n keepAliveTimeout,\n experimentalHttpsServer,\n serverFastRefresh,\n startServerSpan,\n quiet,\n })\n}\n\nexport type StartServerResult = {\n distDir: string\n}\n\nexport async function startServer(\n serverOptions: StartServerOptions\n): Promise {\n const {\n dir,\n isDev,\n hostname,\n minimalMode,\n allowRetry,\n keepAliveTimeout,\n selfSignedCertificate,\n serverFastRefresh,\n } = serverOptions\n let { port } = serverOptions\n\n process.title = `next-server (v${process.env.__NEXT_VERSION})`\n let handlersReady = () => {}\n let handlersError = () => {}\n\n let handlersPromise: Promise | undefined = new Promise(\n (resolve, reject) => {\n handlersReady = resolve\n handlersError = reject\n }\n )\n let requestHandler: WorkerRequestHandler = async (\n req: IncomingMessage,\n res: ServerResponse\n ): Promise => {\n if (handlersPromise) {\n await handlersPromise\n return requestHandler(req, res)\n }\n throw new Error('Invariant request handler was not setup')\n }\n let upgradeHandler: WorkerUpgradeHandler = async (\n req,\n socket,\n head\n ): Promise => {\n if (handlersPromise) {\n await handlersPromise\n return upgradeHandler(req, socket, head)\n }\n throw new Error('Invariant upgrade handler was not setup')\n }\n\n let nextServer: NextServer | undefined\n let devMemoryThresholdRestart = true\n\n // setup server listener as fast as possible\n if (selfSignedCertificate && !isDev) {\n throw new Error(\n 'Using a self signed certificate is only supported with `next dev`.'\n )\n }\n\n async function requestListener(req: IncomingMessage, res: ServerResponse) {\n try {\n if (handlersPromise) {\n await handlersPromise\n handlersPromise = undefined\n }\n await requestHandler(req, res)\n } catch (err) {\n res.statusCode = 500\n res.end('Internal Server Error')\n Log.error(`Failed to handle request for ${req.url}`)\n console.error(err)\n } finally {\n const memoryRestartStats = getMemoryRestartStats(\n isDev,\n devMemoryThresholdRestart,\n v8.getHeapStatistics\n )\n if (memoryRestartStats) {\n Log.warn(\n `Server is approaching the used memory threshold, restarting...`\n )\n trace('server-restart-close-to-memory-threshold', undefined, {\n 'memory.heapSizeLimit': String(memoryRestartStats.heap_size_limit),\n 'memory.heapUsed': String(memoryRestartStats.used_heap_size),\n }).stop()\n flushAllTraces()\n process.exit(RESTART_EXIT_CODE)\n }\n }\n }\n\n const server = selfSignedCertificate\n ? https.createServer(\n {\n key: fs.readFileSync(selfSignedCertificate.key),\n cert: fs.readFileSync(selfSignedCertificate.cert),\n },\n requestListener\n )\n : http.createServer(requestListener)\n\n if (keepAliveTimeout) {\n server.keepAliveTimeout = keepAliveTimeout\n }\n server.on('upgrade', async (req, socket, head) => {\n try {\n await upgradeHandler(req, socket, head)\n } catch (err) {\n socket.destroy()\n Log.error(`Failed to handle request for ${req.url}`)\n console.error(err)\n }\n })\n\n let portRetryCount = 0\n const originalPort = port\n\n server.on('error', (err: NodeJS.ErrnoException) => {\n if (\n allowRetry &&\n port &&\n isDev &&\n err.code === 'EADDRINUSE' &&\n portRetryCount < 10\n ) {\n port += 1\n portRetryCount += 1\n server.listen(port, hostname)\n } else {\n Log.error(`Failed to start server`)\n console.error(err)\n process.exit(1)\n }\n })\n\n let cleanupListeners = isDev ? new AsyncCallbackSet() : undefined\n\n const distDir = await new Promise((resolve) => {\n server.on('listening', async () => {\n const addr = server.address()\n const actualHostname = formatHostname(\n typeof addr === 'object'\n ? addr?.address || hostname || 'localhost'\n : addr\n )\n const formattedHostname =\n !hostname || actualHostname === '0.0.0.0'\n ? 'localhost'\n : actualHostname === '[::]'\n ? '[::1]'\n : formatHostname(hostname)\n\n port = typeof addr === 'object' ? addr?.port || port : port\n\n if (portRetryCount) {\n const pid = await getProcessIdUsingPort(originalPort)\n if (pid) {\n Log.warn(\n `Port ${originalPort} is in use by process ${pid}, using available port ${port} instead.`\n )\n } else {\n Log.warn(\n `Port ${originalPort} is in use by an unknown process, using available port ${port} instead.`\n )\n }\n }\n\n const networkHostname =\n hostname ?? getNetworkHost(isIPv6(actualHostname) ? 'IPv6' : 'IPv4')\n\n const protocol = selfSignedCertificate ? 'https' : 'http'\n\n const networkUrl = networkHostname\n ? `${protocol}://${formatHostname(networkHostname)}:${port}`\n : null\n\n const appUrl = `${protocol}://${formattedHostname}:${port}`\n\n // Store the selected port to:\n // - expose it to render workers\n // - re-use it for automatic dev server restarts with a randomly selected port\n process.env.PORT = port + ''\n\n process.env.__NEXT_PRIVATE_ORIGIN = appUrl\n\n // Set experimental HTTPS flag for metadata resolution\n if (selfSignedCertificate) {\n process.env.__NEXT_EXPERIMENTAL_HTTPS = '1'\n }\n\n // Get env info first (fast, doesn't require config)\n const envInfo = isDev ? getEnvInfo(dir) : undefined\n\n // Log basic startup info immediately (before loading config)\n logStartInfo({\n networkUrl,\n appUrl,\n envInfo,\n logBundler: isDev,\n })\n\n // Calculate and log \"Ready in X\" before loading config\n // so it reflects actual framework startup time.\n // NEXT_PRIVATE_START_TIME is set by bin/next.ts or cli/next-start.ts.\n const startTime = parseInt(process.env.NEXT_PRIVATE_START_TIME || '0', 10)\n const endTime = Date.now()\n const startServerProcessDurationMs = startTime ? endTime - startTime : 0\n\n const formattedStartDuration = durationToString(\n startServerProcessDurationMs / 1000\n )\n\n Log.event(`Ready in ${formattedStartDuration}`)\n\n try {\n let cleanupStarted = false\n let closeUpgraded: (() => void) | null = null\n const cleanup = (signal: 'SIGINT' | 'SIGTERM') => {\n if (cleanupStarted) {\n // We can get duplicate signals, e.g. when `ctrl+c` is used in an\n // interactive shell (i.e. bash, zsh), the shell will recursively\n // send SIGINT to children. The parent `next-dev` process will also\n // send us SIGINT.\n return\n }\n cleanupStarted = true\n ;(async () => {\n debug('start-server process cleanup')\n\n // first, stop accepting new connections and finish pending requests,\n // because they might affect `nextServer.close()` (e.g. by scheduling an `after`)\n await new Promise((res) => {\n server.close((err) => {\n if (err) console.error(err)\n res()\n })\n if (isDev) {\n server.closeAllConnections()\n closeUpgraded?.()\n }\n })\n\n // now that no new requests can come in, clean up the rest\n await Promise.all([\n nextServer?.close().catch(console.error),\n cleanupListeners?.runAll().catch(console.error),\n ])\n\n // Flush any remaining traces to the trace file on shutdown\n flushAllTraces()\n\n // Flush telemetry if this is a dev server\n if (isDev) {\n try {\n const { traceGlobals } =\n require('../../trace/shared') as typeof import('../../trace/shared')\n const telemetry = traceGlobals.get('telemetry') as\n | InstanceType<\n typeof import('../../telemetry/storage').Telemetry\n >\n | undefined\n if (telemetry) {\n // Use flushDetached to avoid blocking process exit\n // Each process writes to a unique file (_events_${pid}.json)\n // to avoid race conditions with the parent process\n telemetry.flushDetached({\n mode: 'dev',\n dir,\n distDir: null,\n events: null,\n })\n }\n } catch (_) {\n // Ignore telemetry errors during cleanup\n }\n }\n\n debug('start-server process cleanup finished')\n\n // Exit with signal-based exit code (128 + signal number) so that\n // Node.js treats this as a signal termination, not a normal exit.\n // This avoids waiting for the debugger to disconnect.\n switch (signal) {\n case 'SIGINT':\n process.exit(130)\n break\n case 'SIGTERM':\n process.exit(143)\n break\n default:\n // Make sure all handled signals have explicit exit codes.\n // This is just a fallback to guard against unsound types.\n signal satisfies never\n process.exit(128)\n }\n })()\n }\n\n // Make sure commands gracefully respect termination signals (e.g. from Docker)\n // Allow the graceful termination to be manually configurable\n if (!process.env.NEXT_MANUAL_SIG_HANDLE) {\n process.on('SIGINT', cleanup)\n process.on('SIGTERM', cleanup)\n }\n\n // Now load config via getRequestHandlers (single loadConfig call)\n const initResult = await getRequestHandlers({\n dir,\n port,\n isDev,\n onDevServerCleanup: cleanupListeners\n ? cleanupListeners.add.bind(cleanupListeners)\n : undefined,\n server,\n hostname,\n minimalMode,\n keepAliveTimeout,\n experimentalHttpsServer: !!selfSignedCertificate,\n serverFastRefresh,\n })\n devMemoryThresholdRestart = initResult.devMemoryThresholdRestart\n requestHandler = initResult.requestHandler\n upgradeHandler = initResult.upgradeHandler\n nextServer = initResult.server\n closeUpgraded = initResult.closeUpgraded\n\n // Log experimental features after config is loaded\n if (isDev) {\n logExperimentalInfo({\n experimentalFeatures: initResult.experimentalFeatures,\n cacheComponents: initResult.cacheComponents,\n partialPrefetching: initResult.partialPrefetching,\n })\n\n logAgentFileSync(\n await syncAgentRulesForDev(dir, initResult.agentRules !== false),\n (files) =>\n `Generated ${files} for AI agents. Set \\`agentRules: false\\` in next.config to disable.`,\n (files) =>\n `Removed agent rules from ${files} because \\`agentRules\\` is disabled.`\n )\n\n if (!isCI) {\n const { traceGlobals } =\n require('../../trace/shared') as typeof import('../../trace/shared')\n const telemetry = traceGlobals.get('telemetry') as\n | InstanceType\n | undefined\n const agentFeedbackConfigured = initResult.agentFeedback === true\n const telemetryEnabled = telemetry?.isEnabled === true\n\n logAgentFileSync(\n await syncAgentFeedbackForDev(\n dir,\n agentFeedbackConfigured && telemetryEnabled\n ),\n (files) =>\n `Generated agent feedback instructions in ${files}. Set \\`experimental.agentFeedback: false\\` in next.config to disable.`,\n (files) =>\n agentFeedbackConfigured\n ? `Removed agent feedback instructions from ${files} because Next.js Telemetry is disabled.`\n : `Removed agent feedback instructions from ${files} because \\`experimental.agentFeedback\\` is disabled.`\n )\n }\n }\n\n handlersReady()\n\n if (process.env.TURBOPACK && isDev) {\n await validateTurboNextConfig({\n dir: serverOptions.dir,\n configPhase: PHASE_DEVELOPMENT_SERVER,\n })\n }\n\n resolve(initResult.distDir)\n } catch (err) {\n // fatal error if we can't setup\n handlersError()\n console.error(err)\n process.exit(1)\n }\n })\n server.listen(port, hostname)\n })\n\n // Watch config files for changes and distDir ancestors for deletion.\n if (isDev) {\n // Note: dir is absolute and normalized (`..` segments removed), `absDistDir`\n // is also normalized because `path.join()` performs normalization. `distDir`\n // does not have to be inside of `dir`!\n const absDistDir = path.join(dir, distDir)\n // always watch dir and absDistDir\n const dirWatchPaths: string[] = [dir, absDistDir]\n // also watch ancestors of absDistDir that are inside of dir.\n let prevAncestor = absDistDir\n while (true) {\n const nextAncestor = path.dirname(prevAncestor)\n // note: `dirname('/') === '/'` if we happen to reach the FS root\n if (\n !nextAncestor.startsWith(dir + path.sep) ||\n nextAncestor === prevAncestor\n ) {\n break\n }\n dirWatchPaths.push(nextAncestor)\n prevAncestor = nextAncestor\n }\n\n const configFiles = CONFIG_FILES.map((file) => path.join(dir, file))\n const Watchpack =\n require('next/dist/compiled/watchpack') as typeof import('next/dist/compiled/watchpack').default\n const wp = new Watchpack()\n wp.watch({\n files: configFiles,\n missing: dirWatchPaths,\n })\n wp.on('change', async (filename) => {\n if (!configFiles.includes(filename)) {\n return\n }\n Log.warn(\n `Found a change in ${path.basename(\n filename\n )}. Restarting the server to apply the changes...`\n )\n process.exit(RESTART_EXIT_CODE)\n })\n wp.on('remove', (removedPath: string) => {\n if (dirWatchPaths.includes(removedPath)) {\n Log.error(\n `The directory at \"${removedPath}\" was deleted.\\n\\n` +\n 'Deleting this directory removes caches and will cause slower ' +\n 'performance.\\n\\n' +\n 'Deleting this directory while Next.js is running can lead to ' +\n 'undefined behavior. Restarting the server to recover...'\n )\n process.exit(RESTART_EXIT_CODE)\n }\n })\n }\n\n return { distDir }\n}\n\nif (process.env.NEXT_PRIVATE_WORKER && process.send) {\n // Output is piped to the CLI to hold it while the upgrade menu is open.\n if (process.env.NEXT_PRIVATE_PROMPT_OUTPUT === '1') {\n blockOnOutputWrites()\n }\n process.addListener('message', async (msg: any) => {\n if (\n msg &&\n typeof msg === 'object' &&\n msg.nextWorkerOptions &&\n process.send\n ) {\n let enabledFeaturesFromParent = {}\n if (process.env.NEXT_PRIVATE_ENABLED_FEATURES) {\n const parsed = JSON.parse(process.env.NEXT_PRIVATE_ENABLED_FEATURES)\n enabledFeaturesFromParent = Object.fromEntries(\n Object.entries(parsed).map(([key, value]) => [\n `feature.${key}`,\n value,\n ])\n )\n }\n\n let rageRestartAttrsFromParent = {}\n if (process.env.NEXT_PRIVATE_DEV_SPAN_ATTRS) {\n rageRestartAttrsFromParent = JSON.parse(\n process.env.NEXT_PRIVATE_DEV_SPAN_ATTRS\n )\n }\n\n startServerSpan = trace('start-dev-server', undefined, {\n cpus: String(os.cpus().length),\n platform: os.platform(),\n 'memory.freeMem': String(os.freemem()),\n 'memory.totalMem': String(os.totalmem()),\n 'memory.heapSizeLimit': String(v8.getHeapStatistics().heap_size_limit),\n ...enabledFeaturesFromParent,\n ...rageRestartAttrsFromParent,\n })\n\n initializeTraceState({\n ...exportTraceState(),\n defaultParentSpanId: startServerSpan.getId(),\n })\n\n const result = await startServerSpan.traceAsyncFn(() =>\n startServer(msg.nextWorkerOptions)\n )\n const memoryUsage = process.memoryUsage()\n startServerSpan.setAttribute('memory.rss', String(memoryUsage.rss))\n startServerSpan.setAttribute(\n 'memory.heapTotal',\n String(memoryUsage.heapTotal)\n )\n startServerSpan.setAttribute(\n 'memory.heapUsed',\n String(memoryUsage.heapUsed)\n )\n process.send({\n nextServerReady: true,\n port: process.env.PORT,\n distDir: result.distDir,\n })\n }\n })\n process.send({ nextWorkerReady: true })\n}\n\n/**\n * Report which agent files a managed-block sync touched. Silent when the sync\n * was a no-op so every `next dev` start doesn't mention the files.\n */\nfunction logAgentFileSync(\n result: AgentFilesResult | null,\n generatedMessage: (files: string) => string,\n removedMessage: (files: string) => string\n): void {\n if (!result) return\n\n const generated: string[] = []\n const removed: string[] = []\n for (const [file, action] of [['AGENTS.md', result.agentsMd]] as const) {\n if (action === 'created' || action === 'updated') {\n generated.push(file)\n } else if (action === 'removed') {\n removed.push(file)\n }\n }\n if (generated.length > 0) Log.event(generatedMessage(generated.join(' and ')))\n if (removed.length > 0) Log.event(removedMessage(removed.join(' and ')))\n}\n"],"names":["getRequestHandlers","startServer","debug","setupDebug","startServerSpan","getProcessIdUsingPort","port","timeoutMs","processLookupController","AbortController","pidPromise","Promise","resolve","handleError","error","process","platform","exec","signal","stdout","pid","trim","cleanOutput","replace","lines","split","firstLine","parts","length","cause","Error","timeoutId","setTimeout","abort","finally","clearTimeout","dir","isDev","onDevServerCleanup","server","hostname","minimalMode","keepAliveTimeout","experimentalHttpsServer","serverFastRefresh","quiet","initialize","dev","serverOptions","allowRetry","selfSignedCertificate","title","env","__NEXT_VERSION","handlersReady","handlersError","handlersPromise","reject","requestHandler","req","res","upgradeHandler","socket","head","nextServer","devMemoryThresholdRestart","requestListener","undefined","err","statusCode","end","Log","url","console","memoryRestartStats","getMemoryRestartStats","v8","getHeapStatistics","warn","trace","String","heap_size_limit","used_heap_size","stop","flushAllTraces","exit","RESTART_EXIT_CODE","https","createServer","key","fs","readFileSync","cert","http","on","destroy","portRetryCount","originalPort","code","listen","cleanupListeners","AsyncCallbackSet","distDir","addr","address","actualHostname","formatHostname","formattedHostname","networkHostname","getNetworkHost","isIPv6","protocol","networkUrl","appUrl","PORT","__NEXT_PRIVATE_ORIGIN","__NEXT_EXPERIMENTAL_HTTPS","envInfo","getEnvInfo","logStartInfo","logBundler","startTime","parseInt","NEXT_PRIVATE_START_TIME","endTime","Date","now","startServerProcessDurationMs","formattedStartDuration","durationToString","event","cleanupStarted","closeUpgraded","cleanup","close","closeAllConnections","all","catch","runAll","traceGlobals","require","telemetry","get","flushDetached","mode","events","_","NEXT_MANUAL_SIG_HANDLE","initResult","add","bind","logExperimentalInfo","experimentalFeatures","cacheComponents","partialPrefetching","logAgentFileSync","syncAgentRulesForDev","agentRules","files","isCI","agentFeedbackConfigured","agentFeedback","telemetryEnabled","isEnabled","syncAgentFeedbackForDev","TURBOPACK","validateTurboNextConfig","configPhase","PHASE_DEVELOPMENT_SERVER","absDistDir","path","join","dirWatchPaths","prevAncestor","nextAncestor","dirname","startsWith","sep","push","configFiles","CONFIG_FILES","map","file","Watchpack","wp","watch","missing","filename","includes","basename","removedPath","NEXT_PRIVATE_WORKER","send","NEXT_PRIVATE_PROMPT_OUTPUT","blockOnOutputWrites","addListener","msg","nextWorkerOptions","enabledFeaturesFromParent","NEXT_PRIVATE_ENABLED_FEATURES","parsed","JSON","parse","Object","fromEntries","entries","value","rageRestartAttrsFromParent","NEXT_PRIVATE_DEV_SPAN_ATTRS","cpus","os","freemem","totalmem","initializeTraceState","exportTraceState","defaultParentSpanId","getId","result","traceAsyncFn","memoryUsage","setAttribute","rss","heapTotal","heapUsed","nextServerReady","nextWorkerReady","generatedMessage","removedMessage","generated","removed","action","agentsMd"],"mappings":"AAAA,kDAAkD;;;;;;;;;;;;;;;;IAiJ5BA,kBAAkB;eAAlBA;;IA6CAC,WAAW;eAAXA;;;QA7Lf;gCACwB;QAExB;QACA;2DAMQ;2DACA;6DACE;6DACA;8DACC;2DACH;+BACM;6DACA;8DACE;uBAKhB;gCACwB;8BACJ;2BAIpB;4BAOA;kCAEiC;uBAOjC;wBACgB;kCACU;kCAEA;wBACZ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErB,MAAMC,QAAQC,IAAAA,cAAU,EAAC;AACzB,IAAIC;AAEJ;;CAEC,GACD,eAAeC,sBAAsBC,IAAY;IAC/C,MAAMC,YAAY;IAClB,MAAMC,0BAA0B,IAAIC;IAEpC,MAAMC,aAAa,IAAIC,QAAuB,CAACC;QAC7C,MAAMC,cAAc,CAACC;YACnBZ,MAAM,qCAAqCI,MAAMQ;YACjDF,QAAQ;QACV;QAEA,IAAI;YACF,+CAA+C;YAC/C,IAAIG,QAAQC,QAAQ,KAAK,SAAS;gBAChCC,IAAAA,mBAAI,EACF,CAAC,SAAS,EAAEX,KAAK,aAAa,CAAC,EAC/B;oBAAEY,QAAQV,wBAAwBU,MAAM;gBAAC,GACzC,CAACJ,OAAOK;oBACN,IAAIL,OAAO;wBACTD,YAAYC;wBACZ;oBACF;oBACA,6DAA6D;oBAC7D,MAAMM,MAAMD,OAAOE,IAAI;oBACvBT,QAAQQ,OAAO;gBACjB;YAEJ,OAAO;gBACL,yBAAyB;gBACzBH,IAAAA,mBAAI,EACF,CAAC,4BAA4B,EAAEX,KAAK,sBAAsB,CAAC,EAC3D;oBAAEY,QAAQV,wBAAwBU,MAAM;gBAAC,GACzC,CAACJ,OAAOK;oBACN,IAAIL,OAAO;wBACTD,YAAYC;wBACZ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,mBACA5I,OAAO2I,YAAYI,QAAQ;YAE7BhN,QAAQiL,IAAI,CAAC;gBACXgC,iBAAiB;gBACjB1N,MAAMS,QAAQqC,GAAG,CAAC8D,IAAI;gBACtBZ,SAASmH,OAAOnH,OAAO;YACzB;QACF;IACF;IACAvF,QAAQiL,IAAI,CAAC;QAAEiC,iBAAiB;IAAK;AACvC;AAEA;;;CAGC,GACD,SAAStE,iBACP8D,MAA+B,EAC/BS,gBAA2C,EAC3CC,cAAyC;IAEzC,IAAI,CAACV,QAAQ;IAEb,MAAMW,YAAsB,EAAE;IAC9B,MAAMC,UAAoB,EAAE;IAC5B,KAAK,MAAM,CAAC/C,MAAMgD,OAAO,IAAI;QAAC;YAAC;YAAab,OAAOc,QAAQ;SAAC;KAAC,CAAW;QACtE,IAAID,WAAW,aAAaA,WAAW,WAAW;YAChDF,UAAUlD,IAAI,CAACI;QACjB,OAAO,IAAIgD,WAAW,WAAW;YAC/BD,QAAQnD,IAAI,CAACI;QACf;IACF;IACA,IAAI8C,UAAUxM,MAAM,GAAG,GAAG2C,KAAI2D,KAAK,CAACgG,iBAAiBE,UAAUzD,IAAI,CAAC;IACpE,IAAI0D,QAAQzM,MAAM,GAAG,GAAG2C,KAAI2D,KAAK,CAACiG,eAAeE,QAAQ1D,IAAI,CAAC;AAChE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/streaming-metadata.d.ts b/e-commerce/node_modules/next/dist/server/lib/streaming-metadata.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d523ed469d0ef185bc90d2ae8b8874f37f29d109 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/streaming-metadata.d.ts @@ -0,0 +1 @@ +export declare function shouldServeStreamingMetadata(userAgent: string, htmlLimitedBots: string | undefined): boolean; diff --git a/e-commerce/node_modules/next/dist/server/lib/streaming-metadata.js b/e-commerce/node_modules/next/dist/server/lib/streaming-metadata.js new file mode 100644 index 0000000000000000000000000000000000000000..1d257e8b243a8407482f32f4c3a475acbfa8ce40 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/streaming-metadata.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "shouldServeStreamingMetadata", { + enumerable: true, + get: function() { + return shouldServeStreamingMetadata; + } +}); +const _isbot = require("../../shared/lib/router/utils/is-bot"); +let cachedPattern; +let cachedRegex; +function shouldServeStreamingMetadata(userAgent, htmlLimitedBots) { + const pattern = htmlLimitedBots || _isbot.HTML_LIMITED_BOT_UA_RE_STRING; + if (cachedPattern !== pattern) { + cachedPattern = pattern; + cachedRegex = new RegExp(pattern, 'i'); + } + // Only block metadata for HTML-limited bots + if (userAgent && cachedRegex.test(userAgent)) { + return false; + } + return true; +} + +//# sourceMappingURL=streaming-metadata.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/streaming-metadata.js.map b/e-commerce/node_modules/next/dist/server/lib/streaming-metadata.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bfd2ba198ebffaeeb92f6d5bd662d5525e053ec8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/streaming-metadata.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/lib/streaming-metadata.ts"],"sourcesContent":["import { HTML_LIMITED_BOT_UA_RE_STRING } from '../../shared/lib/router/utils/is-bot'\n\nlet cachedPattern: string | undefined\nlet cachedRegex: RegExp | undefined\n\nexport function shouldServeStreamingMetadata(\n userAgent: string,\n htmlLimitedBots: string | undefined\n): boolean {\n const pattern = htmlLimitedBots || HTML_LIMITED_BOT_UA_RE_STRING\n if (cachedPattern !== pattern) {\n cachedPattern = pattern\n cachedRegex = new RegExp(pattern, 'i')\n }\n // Only block metadata for HTML-limited bots\n if (userAgent && cachedRegex!.test(userAgent)) {\n return false\n }\n return true\n}\n"],"names":["shouldServeStreamingMetadata","cachedPattern","cachedRegex","userAgent","htmlLimitedBots","pattern","HTML_LIMITED_BOT_UA_RE_STRING","RegExp","test"],"mappings":";;;;+BAKgBA;;;eAAAA;;;uBAL8B;AAE9C,IAAIC;AACJ,IAAIC;AAEG,SAASF,6BACdG,SAAiB,EACjBC,eAAmC;IAEnC,MAAMC,UAAUD,mBAAmBE,oCAA6B;IAChE,IAAIL,kBAAkBI,SAAS;QAC7BJ,gBAAgBI;QAChBH,cAAc,IAAIK,OAAOF,SAAS;IACpC;IACA,4CAA4C;IAC5C,IAAIF,aAAaD,YAAaM,IAAI,CAACL,YAAY;QAC7C,OAAO;IACT;IACA,OAAO;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/to-route.d.ts b/e-commerce/node_modules/next/dist/server/lib/to-route.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..980c15c3ab2f4d111754c60e90ddf647d55f1a67 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/to-route.d.ts @@ -0,0 +1,24 @@ +/** + * This transforms a URL pathname into a route. It removes any trailing slashes + * and the `/index` suffix. + * + * @param pathname - The URL path that needs to be optimized. + * @returns - The route + * + * @example + * // returns '/example' + * toRoute('/example/index/'); + * + * @example + * // returns '/example' + * toRoute('/example/'); + * + * @example + * // returns '/' + * toRoute('/index/'); + * + * @example + * // returns '/' + * toRoute('/'); + */ +export declare function toRoute(pathname: string): string; diff --git a/e-commerce/node_modules/next/dist/server/lib/to-route.js b/e-commerce/node_modules/next/dist/server/lib/to-route.js new file mode 100644 index 0000000000000000000000000000000000000000..6299fbe60a3011eb29b56740ad418102e25c6bb4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/to-route.js @@ -0,0 +1,37 @@ +/** + * This transforms a URL pathname into a route. It removes any trailing slashes + * and the `/index` suffix. + * + * @param pathname - The URL path that needs to be optimized. + * @returns - The route + * + * @example + * // returns '/example' + * toRoute('/example/index/'); + * + * @example + * // returns '/example' + * toRoute('/example/'); + * + * @example + * // returns '/' + * toRoute('/index/'); + * + * @example + * // returns '/' + * toRoute('/'); + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "toRoute", { + enumerable: true, + get: function() { + return toRoute; + } +}); +function toRoute(pathname) { + return pathname.replace(/(?:\/index)?\/?$/, '') || '/'; +} + +//# sourceMappingURL=to-route.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/to-route.js.map b/e-commerce/node_modules/next/dist/server/lib/to-route.js.map new file mode 100644 index 0000000000000000000000000000000000000000..95b62be82ec68154c99af8458f67a8eb4c31c3d3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/to-route.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/lib/to-route.ts"],"sourcesContent":["/**\n * This transforms a URL pathname into a route. It removes any trailing slashes\n * and the `/index` suffix.\n *\n * @param pathname - The URL path that needs to be optimized.\n * @returns - The route\n *\n * @example\n * // returns '/example'\n * toRoute('/example/index/');\n *\n * @example\n * // returns '/example'\n * toRoute('/example/');\n *\n * @example\n * // returns '/'\n * toRoute('/index/');\n *\n * @example\n * // returns '/'\n * toRoute('/');\n */\nexport function toRoute(pathname: string): string {\n return pathname.replace(/(?:\\/index)?\\/?$/, '') || '/'\n}\n"],"names":["toRoute","pathname","replace"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;CAsBC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,QAAQC,QAAgB;IACtC,OAAOA,SAASC,OAAO,CAAC,oBAAoB,OAAO;AACrD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/constants.d.ts b/e-commerce/node_modules/next/dist/server/lib/trace/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25d053df01a4021385ccd78049c96991ad55c066 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/constants.d.ts @@ -0,0 +1,120 @@ +/** + * Contains predefined constants for the trace span name in next/server. + * + * Currently, next/server/tracer is internal implementation only for tracking + * next.js's implementation only with known span names defined here. + **/ +declare enum BaseServerSpan { + handleRequest = "BaseServer.handleRequest", + run = "BaseServer.run", + pipe = "BaseServer.pipe", + getStaticHTML = "BaseServer.getStaticHTML", + render = "BaseServer.render", + renderToResponseWithComponents = "BaseServer.renderToResponseWithComponents", + renderToResponse = "BaseServer.renderToResponse", + renderToHTML = "BaseServer.renderToHTML", + renderError = "BaseServer.renderError", + renderErrorToResponse = "BaseServer.renderErrorToResponse", + renderErrorToHTML = "BaseServer.renderErrorToHTML", + render404 = "BaseServer.render404" +} +declare enum LoadComponentsSpan { + loadDefaultErrorComponents = "LoadComponents.loadDefaultErrorComponents", + loadComponents = "LoadComponents.loadComponents", + loadRouteModule = "LoadComponents.loadRouteModule" +} +declare enum InstrumentationSpan { + loadModule = "Instrumentation.loadModule", + register = "Instrumentation.register" +} +declare enum NextServerSpan { + getRequestHandler = "NextServer.getRequestHandler", + getRequestHandlerWithMetadata = "NextServer.getRequestHandlerWithMetadata", + getServer = "NextServer.getServer", + getServerRequestHandler = "NextServer.getServerRequestHandler", + createServer = "createServer.createServer" +} +declare enum NextNodeServerSpan { + compression = "NextNodeServer.compression", + getBuildId = "NextNodeServer.getBuildId", + createComponentTree = "NextNodeServer.createComponentTree", + clientComponentLoading = "NextNodeServer.clientComponentLoading", + getLayoutOrPageModule = "NextNodeServer.getLayoutOrPageModule", + generateStaticRoutes = "NextNodeServer.generateStaticRoutes", + generateFsStaticRoutes = "NextNodeServer.generateFsStaticRoutes", + generatePublicRoutes = "NextNodeServer.generatePublicRoutes", + generateImageRoutes = "NextNodeServer.generateImageRoutes.route", + sendRenderResult = "NextNodeServer.sendRenderResult", + proxyRequest = "NextNodeServer.proxyRequest", + runApi = "NextNodeServer.runApi", + render = "NextNodeServer.render", + renderHTML = "NextNodeServer.renderHTML", + imageOptimizer = "NextNodeServer.imageOptimizer", + getPagePath = "NextNodeServer.getPagePath", + getRoutesManifest = "NextNodeServer.getRoutesManifest", + findPageComponents = "NextNodeServer.findPageComponents", + getFontManifest = "NextNodeServer.getFontManifest", + getServerComponentManifest = "NextNodeServer.getServerComponentManifest", + getRequestHandler = "NextNodeServer.getRequestHandler", + renderToHTML = "NextNodeServer.renderToHTML", + renderError = "NextNodeServer.renderError", + renderErrorToHTML = "NextNodeServer.renderErrorToHTML", + render404 = "NextNodeServer.render404", + startResponse = "NextNodeServer.startResponse", + route = "route", + onProxyReq = "onProxyReq", + apiResolver = "apiResolver", + internalFetch = "internalFetch" +} +declare enum StartServerSpan { + startServer = "startServer.startServer" +} +declare enum RenderSpan { + getServerSideProps = "Render.getServerSideProps", + getStaticProps = "Render.getStaticProps", + renderToString = "Render.renderToString", + renderDocument = "Render.renderDocument", + createBodyResult = "Render.createBodyResult" +} +declare enum AppRenderSpan { + renderToString = "AppRender.renderToString", + renderToReadableStream = "AppRender.renderToReadableStream", + getBodyResult = "AppRender.getBodyResult", + fetch = "AppRender.fetch", + waitShellReady = "AppRender.waitShellReady", + renderToNodeFizzStream = "AppRender.renderToNodeFizzStream", + instantInsights = "AppRender.instantInsights", + instantInsightsPrepareValidation = "AppRender.instantInsights.prepareValidation", + instantInsightsRunValidation = "AppRender.instantInsights.runValidation" +} +declare enum DevBundlerServiceSpan { + ensurePage = "DevBundlerService.ensurePage" +} +declare enum RouterSpan { + executeRoute = "Router.executeRoute" +} +declare enum NodeSpan { + runHandler = "Node.runHandler" +} +declare enum AppRouteRouteHandlersSpan { + runHandler = "AppRouteRouteHandlers.runHandler" +} +declare enum AppRouteRouteModuleSpan { + loadUserland = "AppRouteRouteModule.loadUserland" +} +declare enum RouteModuleSpan { + prepare = "RouteModule.prepare", + loadManifests = "RouteModule.loadManifests" +} +declare enum ResolveMetadataSpan { + generateMetadata = "ResolveMetadata.generateMetadata", + generateViewport = "ResolveMetadata.generateViewport" +} +declare enum MiddlewareSpan { + execute = "Middleware.execute" +} +type SpanTypes = `${BaseServerSpan}` | `${LoadComponentsSpan}` | `${InstrumentationSpan}` | `${NextServerSpan}` | `${StartServerSpan}` | `${NextNodeServerSpan}` | `${RenderSpan}` | `${RouterSpan}` | `${AppRenderSpan}` | `${DevBundlerServiceSpan}` | `${NodeSpan}` | `${AppRouteRouteHandlersSpan}` | `${AppRouteRouteModuleSpan}` | `${RouteModuleSpan}` | `${ResolveMetadataSpan}` | `${MiddlewareSpan}`; +export declare const NextVanillaSpanAllowlist: Set; +export declare const LogSpanAllowList: Set; +export { BaseServerSpan, LoadComponentsSpan, InstrumentationSpan, NextServerSpan, NextNodeServerSpan, StartServerSpan, RenderSpan, RouterSpan, AppRenderSpan, DevBundlerServiceSpan, NodeSpan, AppRouteRouteHandlersSpan, AppRouteRouteModuleSpan, RouteModuleSpan, ResolveMetadataSpan, MiddlewareSpan, }; +export type { SpanTypes }; diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/constants.js b/e-commerce/node_modules/next/dist/server/lib/trace/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..3c7b62b7fb449b82757f8a3e06954815050ee0a5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/constants.js @@ -0,0 +1,248 @@ +/** + * Contains predefined constants for the trace span name in next/server. + * + * Currently, next/server/tracer is internal implementation only for tracking + * next.js's implementation only with known span names defined here. + **/ // eslint typescript has a bug with TS enums +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + AppRenderSpan: null, + AppRouteRouteHandlersSpan: null, + AppRouteRouteModuleSpan: null, + BaseServerSpan: null, + DevBundlerServiceSpan: null, + InstrumentationSpan: null, + LoadComponentsSpan: null, + LogSpanAllowList: null, + MiddlewareSpan: null, + NextNodeServerSpan: null, + NextServerSpan: null, + NextVanillaSpanAllowlist: null, + NodeSpan: null, + RenderSpan: null, + ResolveMetadataSpan: null, + RouteModuleSpan: null, + RouterSpan: null, + StartServerSpan: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + AppRenderSpan: function() { + return AppRenderSpan; + }, + AppRouteRouteHandlersSpan: function() { + return AppRouteRouteHandlersSpan; + }, + AppRouteRouteModuleSpan: function() { + return AppRouteRouteModuleSpan; + }, + BaseServerSpan: function() { + return BaseServerSpan; + }, + DevBundlerServiceSpan: function() { + return DevBundlerServiceSpan; + }, + InstrumentationSpan: function() { + return InstrumentationSpan; + }, + LoadComponentsSpan: function() { + return LoadComponentsSpan; + }, + LogSpanAllowList: function() { + return LogSpanAllowList; + }, + MiddlewareSpan: function() { + return MiddlewareSpan; + }, + NextNodeServerSpan: function() { + return NextNodeServerSpan; + }, + NextServerSpan: function() { + return NextServerSpan; + }, + NextVanillaSpanAllowlist: function() { + return NextVanillaSpanAllowlist; + }, + NodeSpan: function() { + return NodeSpan; + }, + RenderSpan: function() { + return RenderSpan; + }, + ResolveMetadataSpan: function() { + return ResolveMetadataSpan; + }, + RouteModuleSpan: function() { + return RouteModuleSpan; + }, + RouterSpan: function() { + return RouterSpan; + }, + StartServerSpan: function() { + return StartServerSpan; + } +}); +var BaseServerSpan = /*#__PURE__*/ function(BaseServerSpan) { + BaseServerSpan["handleRequest"] = "BaseServer.handleRequest"; + BaseServerSpan["run"] = "BaseServer.run"; + BaseServerSpan["pipe"] = "BaseServer.pipe"; + BaseServerSpan["getStaticHTML"] = "BaseServer.getStaticHTML"; + BaseServerSpan["render"] = "BaseServer.render"; + BaseServerSpan["renderToResponseWithComponents"] = "BaseServer.renderToResponseWithComponents"; + BaseServerSpan["renderToResponse"] = "BaseServer.renderToResponse"; + BaseServerSpan["renderToHTML"] = "BaseServer.renderToHTML"; + BaseServerSpan["renderError"] = "BaseServer.renderError"; + BaseServerSpan["renderErrorToResponse"] = "BaseServer.renderErrorToResponse"; + BaseServerSpan["renderErrorToHTML"] = "BaseServer.renderErrorToHTML"; + BaseServerSpan["render404"] = "BaseServer.render404"; + return BaseServerSpan; +}(BaseServerSpan || {}); +var LoadComponentsSpan = /*#__PURE__*/ function(LoadComponentsSpan) { + LoadComponentsSpan["loadDefaultErrorComponents"] = "LoadComponents.loadDefaultErrorComponents"; + LoadComponentsSpan["loadComponents"] = "LoadComponents.loadComponents"; + LoadComponentsSpan["loadRouteModule"] = "LoadComponents.loadRouteModule"; + return LoadComponentsSpan; +}(LoadComponentsSpan || {}); +var InstrumentationSpan = /*#__PURE__*/ function(InstrumentationSpan) { + InstrumentationSpan["loadModule"] = "Instrumentation.loadModule"; + InstrumentationSpan["register"] = "Instrumentation.register"; + return InstrumentationSpan; +}(InstrumentationSpan || {}); +var NextServerSpan = /*#__PURE__*/ function(NextServerSpan) { + NextServerSpan["getRequestHandler"] = "NextServer.getRequestHandler"; + NextServerSpan["getRequestHandlerWithMetadata"] = "NextServer.getRequestHandlerWithMetadata"; + NextServerSpan["getServer"] = "NextServer.getServer"; + NextServerSpan["getServerRequestHandler"] = "NextServer.getServerRequestHandler"; + NextServerSpan["createServer"] = "createServer.createServer"; + return NextServerSpan; +}(NextServerSpan || {}); +var NextNodeServerSpan = /*#__PURE__*/ function(NextNodeServerSpan) { + NextNodeServerSpan["compression"] = "NextNodeServer.compression"; + NextNodeServerSpan["getBuildId"] = "NextNodeServer.getBuildId"; + NextNodeServerSpan["createComponentTree"] = "NextNodeServer.createComponentTree"; + NextNodeServerSpan["clientComponentLoading"] = "NextNodeServer.clientComponentLoading"; + NextNodeServerSpan["getLayoutOrPageModule"] = "NextNodeServer.getLayoutOrPageModule"; + NextNodeServerSpan["generateStaticRoutes"] = "NextNodeServer.generateStaticRoutes"; + NextNodeServerSpan["generateFsStaticRoutes"] = "NextNodeServer.generateFsStaticRoutes"; + NextNodeServerSpan["generatePublicRoutes"] = "NextNodeServer.generatePublicRoutes"; + NextNodeServerSpan["generateImageRoutes"] = "NextNodeServer.generateImageRoutes.route"; + NextNodeServerSpan["sendRenderResult"] = "NextNodeServer.sendRenderResult"; + NextNodeServerSpan["proxyRequest"] = "NextNodeServer.proxyRequest"; + NextNodeServerSpan["runApi"] = "NextNodeServer.runApi"; + NextNodeServerSpan["render"] = "NextNodeServer.render"; + NextNodeServerSpan["renderHTML"] = "NextNodeServer.renderHTML"; + NextNodeServerSpan["imageOptimizer"] = "NextNodeServer.imageOptimizer"; + NextNodeServerSpan["getPagePath"] = "NextNodeServer.getPagePath"; + NextNodeServerSpan["getRoutesManifest"] = "NextNodeServer.getRoutesManifest"; + NextNodeServerSpan["findPageComponents"] = "NextNodeServer.findPageComponents"; + NextNodeServerSpan["getFontManifest"] = "NextNodeServer.getFontManifest"; + NextNodeServerSpan["getServerComponentManifest"] = "NextNodeServer.getServerComponentManifest"; + NextNodeServerSpan["getRequestHandler"] = "NextNodeServer.getRequestHandler"; + NextNodeServerSpan["renderToHTML"] = "NextNodeServer.renderToHTML"; + NextNodeServerSpan["renderError"] = "NextNodeServer.renderError"; + NextNodeServerSpan["renderErrorToHTML"] = "NextNodeServer.renderErrorToHTML"; + NextNodeServerSpan["render404"] = "NextNodeServer.render404"; + NextNodeServerSpan["startResponse"] = "NextNodeServer.startResponse"; + // nested inner span, does not require parent scope name + NextNodeServerSpan["route"] = "route"; + NextNodeServerSpan["onProxyReq"] = "onProxyReq"; + NextNodeServerSpan["apiResolver"] = "apiResolver"; + NextNodeServerSpan["internalFetch"] = "internalFetch"; + return NextNodeServerSpan; +}(NextNodeServerSpan || {}); +var StartServerSpan = /*#__PURE__*/ function(StartServerSpan) { + StartServerSpan["startServer"] = "startServer.startServer"; + return StartServerSpan; +}(StartServerSpan || {}); +var RenderSpan = /*#__PURE__*/ function(RenderSpan) { + RenderSpan["getServerSideProps"] = "Render.getServerSideProps"; + RenderSpan["getStaticProps"] = "Render.getStaticProps"; + RenderSpan["renderToString"] = "Render.renderToString"; + RenderSpan["renderDocument"] = "Render.renderDocument"; + RenderSpan["createBodyResult"] = "Render.createBodyResult"; + return RenderSpan; +}(RenderSpan || {}); +var AppRenderSpan = /*#__PURE__*/ function(AppRenderSpan) { + AppRenderSpan["renderToString"] = "AppRender.renderToString"; + AppRenderSpan["renderToReadableStream"] = "AppRender.renderToReadableStream"; + AppRenderSpan["getBodyResult"] = "AppRender.getBodyResult"; + AppRenderSpan["fetch"] = "AppRender.fetch"; + AppRenderSpan["waitShellReady"] = "AppRender.waitShellReady"; + AppRenderSpan["renderToNodeFizzStream"] = "AppRender.renderToNodeFizzStream"; + AppRenderSpan["instantInsights"] = "AppRender.instantInsights"; + AppRenderSpan["instantInsightsPrepareValidation"] = "AppRender.instantInsights.prepareValidation"; + AppRenderSpan["instantInsightsRunValidation"] = "AppRender.instantInsights.runValidation"; + return AppRenderSpan; +}(AppRenderSpan || {}); +var DevBundlerServiceSpan = /*#__PURE__*/ function(DevBundlerServiceSpan) { + DevBundlerServiceSpan["ensurePage"] = "DevBundlerService.ensurePage"; + return DevBundlerServiceSpan; +}(DevBundlerServiceSpan || {}); +var RouterSpan = /*#__PURE__*/ function(RouterSpan) { + RouterSpan["executeRoute"] = "Router.executeRoute"; + return RouterSpan; +}(RouterSpan || {}); +var NodeSpan = /*#__PURE__*/ function(NodeSpan) { + NodeSpan["runHandler"] = "Node.runHandler"; + return NodeSpan; +}(NodeSpan || {}); +var AppRouteRouteHandlersSpan = /*#__PURE__*/ function(AppRouteRouteHandlersSpan) { + AppRouteRouteHandlersSpan["runHandler"] = "AppRouteRouteHandlers.runHandler"; + return AppRouteRouteHandlersSpan; +}(AppRouteRouteHandlersSpan || {}); +var AppRouteRouteModuleSpan = /*#__PURE__*/ function(AppRouteRouteModuleSpan) { + AppRouteRouteModuleSpan["loadUserland"] = "AppRouteRouteModule.loadUserland"; + return AppRouteRouteModuleSpan; +}(AppRouteRouteModuleSpan || {}); +var RouteModuleSpan = /*#__PURE__*/ function(RouteModuleSpan) { + RouteModuleSpan["prepare"] = "RouteModule.prepare"; + RouteModuleSpan["loadManifests"] = "RouteModule.loadManifests"; + return RouteModuleSpan; +}(RouteModuleSpan || {}); +var ResolveMetadataSpan = /*#__PURE__*/ function(ResolveMetadataSpan) { + ResolveMetadataSpan["generateMetadata"] = "ResolveMetadata.generateMetadata"; + ResolveMetadataSpan["generateViewport"] = "ResolveMetadata.generateViewport"; + return ResolveMetadataSpan; +}(ResolveMetadataSpan || {}); +var MiddlewareSpan = /*#__PURE__*/ function(MiddlewareSpan) { + MiddlewareSpan["execute"] = "Middleware.execute"; + return MiddlewareSpan; +}(MiddlewareSpan || {}); +const NextVanillaSpanAllowlist = new Set([ + "Middleware.execute", + "BaseServer.handleRequest", + "Render.getServerSideProps", + "Render.getStaticProps", + "AppRender.fetch", + "AppRender.getBodyResult", + "LoadComponents.loadRouteModule", + "Render.renderDocument", + "Node.runHandler", + "AppRouteRouteHandlers.runHandler", + "AppRouteRouteModule.loadUserland", + "RouteModule.prepare", + "Instrumentation.loadModule", + "Instrumentation.register", + "ResolveMetadata.generateMetadata", + "ResolveMetadata.generateViewport", + "NextNodeServer.createComponentTree", + "NextNodeServer.findPageComponents", + "NextNodeServer.getLayoutOrPageModule", + "NextNodeServer.startResponse", + "NextNodeServer.clientComponentLoading" +]); +const LogSpanAllowList = new Set([ + "NextNodeServer.findPageComponents", + "NextNodeServer.createComponentTree", + "NextNodeServer.clientComponentLoading" +]); + +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/constants.js.map b/e-commerce/node_modules/next/dist/server/lib/trace/constants.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6c04e023bdc7d2905d86bbcf95e04bb822303fdf --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/constants.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/lib/trace/constants.ts"],"sourcesContent":["/**\n * Contains predefined constants for the trace span name in next/server.\n *\n * Currently, next/server/tracer is internal implementation only for tracking\n * next.js's implementation only with known span names defined here.\n **/\n\n// eslint typescript has a bug with TS enums\n\nenum BaseServerSpan {\n handleRequest = 'BaseServer.handleRequest',\n run = 'BaseServer.run',\n pipe = 'BaseServer.pipe',\n getStaticHTML = 'BaseServer.getStaticHTML',\n render = 'BaseServer.render',\n renderToResponseWithComponents = 'BaseServer.renderToResponseWithComponents',\n renderToResponse = 'BaseServer.renderToResponse',\n renderToHTML = 'BaseServer.renderToHTML',\n renderError = 'BaseServer.renderError',\n renderErrorToResponse = 'BaseServer.renderErrorToResponse',\n renderErrorToHTML = 'BaseServer.renderErrorToHTML',\n render404 = 'BaseServer.render404',\n}\n\nenum LoadComponentsSpan {\n loadDefaultErrorComponents = 'LoadComponents.loadDefaultErrorComponents',\n loadComponents = 'LoadComponents.loadComponents',\n loadRouteModule = 'LoadComponents.loadRouteModule',\n}\n\nenum InstrumentationSpan {\n loadModule = 'Instrumentation.loadModule',\n register = 'Instrumentation.register',\n}\n\nenum NextServerSpan {\n getRequestHandler = 'NextServer.getRequestHandler',\n getRequestHandlerWithMetadata = 'NextServer.getRequestHandlerWithMetadata',\n getServer = 'NextServer.getServer',\n getServerRequestHandler = 'NextServer.getServerRequestHandler',\n createServer = 'createServer.createServer',\n}\n\nenum NextNodeServerSpan {\n compression = 'NextNodeServer.compression',\n getBuildId = 'NextNodeServer.getBuildId',\n createComponentTree = 'NextNodeServer.createComponentTree',\n clientComponentLoading = 'NextNodeServer.clientComponentLoading',\n getLayoutOrPageModule = 'NextNodeServer.getLayoutOrPageModule',\n generateStaticRoutes = 'NextNodeServer.generateStaticRoutes',\n generateFsStaticRoutes = 'NextNodeServer.generateFsStaticRoutes',\n generatePublicRoutes = 'NextNodeServer.generatePublicRoutes',\n generateImageRoutes = 'NextNodeServer.generateImageRoutes.route',\n sendRenderResult = 'NextNodeServer.sendRenderResult',\n proxyRequest = 'NextNodeServer.proxyRequest',\n runApi = 'NextNodeServer.runApi',\n render = 'NextNodeServer.render',\n renderHTML = 'NextNodeServer.renderHTML',\n imageOptimizer = 'NextNodeServer.imageOptimizer',\n getPagePath = 'NextNodeServer.getPagePath',\n getRoutesManifest = 'NextNodeServer.getRoutesManifest',\n findPageComponents = 'NextNodeServer.findPageComponents',\n getFontManifest = 'NextNodeServer.getFontManifest',\n getServerComponentManifest = 'NextNodeServer.getServerComponentManifest',\n getRequestHandler = 'NextNodeServer.getRequestHandler',\n renderToHTML = 'NextNodeServer.renderToHTML',\n renderError = 'NextNodeServer.renderError',\n renderErrorToHTML = 'NextNodeServer.renderErrorToHTML',\n render404 = 'NextNodeServer.render404',\n startResponse = 'NextNodeServer.startResponse',\n\n // nested inner span, does not require parent scope name\n route = 'route',\n onProxyReq = 'onProxyReq',\n apiResolver = 'apiResolver',\n internalFetch = 'internalFetch',\n}\n\nenum StartServerSpan {\n startServer = 'startServer.startServer',\n}\n\nenum RenderSpan {\n getServerSideProps = 'Render.getServerSideProps',\n getStaticProps = 'Render.getStaticProps',\n renderToString = 'Render.renderToString',\n renderDocument = 'Render.renderDocument',\n createBodyResult = 'Render.createBodyResult',\n}\n\nenum AppRenderSpan {\n renderToString = 'AppRender.renderToString',\n renderToReadableStream = 'AppRender.renderToReadableStream',\n getBodyResult = 'AppRender.getBodyResult',\n fetch = 'AppRender.fetch',\n waitShellReady = 'AppRender.waitShellReady',\n renderToNodeFizzStream = 'AppRender.renderToNodeFizzStream',\n instantInsights = 'AppRender.instantInsights',\n instantInsightsPrepareValidation = 'AppRender.instantInsights.prepareValidation',\n instantInsightsRunValidation = 'AppRender.instantInsights.runValidation',\n}\n\nenum DevBundlerServiceSpan {\n ensurePage = 'DevBundlerService.ensurePage',\n}\n\nenum RouterSpan {\n executeRoute = 'Router.executeRoute',\n}\n\nenum NodeSpan {\n runHandler = 'Node.runHandler',\n}\n\nenum AppRouteRouteHandlersSpan {\n runHandler = 'AppRouteRouteHandlers.runHandler',\n}\n\nenum AppRouteRouteModuleSpan {\n loadUserland = 'AppRouteRouteModule.loadUserland',\n}\n\nenum RouteModuleSpan {\n prepare = 'RouteModule.prepare',\n loadManifests = 'RouteModule.loadManifests',\n}\nenum ResolveMetadataSpan {\n generateMetadata = 'ResolveMetadata.generateMetadata',\n generateViewport = 'ResolveMetadata.generateViewport',\n}\n\nenum MiddlewareSpan {\n execute = 'Middleware.execute',\n}\n\ntype SpanTypes =\n | `${BaseServerSpan}`\n | `${LoadComponentsSpan}`\n | `${InstrumentationSpan}`\n | `${NextServerSpan}`\n | `${StartServerSpan}`\n | `${NextNodeServerSpan}`\n | `${RenderSpan}`\n | `${RouterSpan}`\n | `${AppRenderSpan}`\n | `${DevBundlerServiceSpan}`\n | `${NodeSpan}`\n | `${AppRouteRouteHandlersSpan}`\n | `${AppRouteRouteModuleSpan}`\n | `${RouteModuleSpan}`\n | `${ResolveMetadataSpan}`\n | `${MiddlewareSpan}`\n\n// This list is used to filter out spans that are not relevant to the user\nexport const NextVanillaSpanAllowlist = new Set([\n MiddlewareSpan.execute,\n BaseServerSpan.handleRequest,\n RenderSpan.getServerSideProps,\n RenderSpan.getStaticProps,\n AppRenderSpan.fetch,\n AppRenderSpan.getBodyResult,\n LoadComponentsSpan.loadRouteModule,\n RenderSpan.renderDocument,\n NodeSpan.runHandler,\n AppRouteRouteHandlersSpan.runHandler,\n AppRouteRouteModuleSpan.loadUserland,\n RouteModuleSpan.prepare,\n InstrumentationSpan.loadModule,\n InstrumentationSpan.register,\n ResolveMetadataSpan.generateMetadata,\n ResolveMetadataSpan.generateViewport,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.getLayoutOrPageModule,\n NextNodeServerSpan.startResponse,\n NextNodeServerSpan.clientComponentLoading,\n])\n\n// These Spans are allowed to be always logged\n// when the otel log prefix env is set\nexport const LogSpanAllowList = new Set([\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.clientComponentLoading,\n])\n\nexport {\n BaseServerSpan,\n LoadComponentsSpan,\n InstrumentationSpan,\n NextServerSpan,\n NextNodeServerSpan,\n StartServerSpan,\n RenderSpan,\n RouterSpan,\n AppRenderSpan,\n DevBundlerServiceSpan,\n NodeSpan,\n AppRouteRouteHandlersSpan,\n AppRouteRouteModuleSpan,\n RouteModuleSpan,\n ResolveMetadataSpan,\n MiddlewareSpan,\n}\n\nexport type { SpanTypes }\n"],"names":["AppRenderSpan","AppRouteRouteHandlersSpan","AppRouteRouteModuleSpan","BaseServerSpan","DevBundlerServiceSpan","InstrumentationSpan","LoadComponentsSpan","LogSpanAllowList","MiddlewareSpan","NextNodeServerSpan","NextServerSpan","NextVanillaSpanAllowlist","NodeSpan","RenderSpan","ResolveMetadataSpan","RouteModuleSpan","RouterSpan","StartServerSpan","Set"],"mappings":"AAAA;;;;;EAKE,GAEF,4CAA4C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4L1CA,aAAa;eAAbA;;IAGAC,yBAAyB;eAAzBA;;IACAC,uBAAuB;eAAvBA;;IAZAC,cAAc;eAAdA;;IASAC,qBAAqB;eAArBA;;IAPAC,mBAAmB;eAAnBA;;IADAC,kBAAkB;eAAlBA;;IARWC,gBAAgB;eAAhBA;;IAsBXC,cAAc;eAAdA;;IAXAC,kBAAkB;eAAlBA;;IADAC,cAAc;eAAdA;;IApCWC,wBAAwB;eAAxBA;;IA2CXC,QAAQ;eAARA;;IAJAC,UAAU;eAAVA;;IAQAC,mBAAmB;eAAnBA;;IADAC,eAAe;eAAfA;;IANAC,UAAU;eAAVA;;IAFAC,eAAe;eAAfA;;;AAvLF,IAAA,AAAKd,wCAAAA;;;;;;;;;;;;;WAAAA;EAAAA;AAeL,IAAA,AAAKG,4CAAAA;;;;WAAAA;EAAAA;AAML,IAAA,AAAKD,6CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKK,wCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKD,4CAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4BH,wDAAwD;;;;;WA5BrDA;EAAAA;AAmCL,IAAA,AAAKQ,yCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKJ,oCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKb,uCAAAA;;;;;;;;;;WAAAA;EAAAA;AAYL,IAAA,AAAKI,+CAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKY,oCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKJ,kCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKX,mDAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,iDAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKa,yCAAAA;;;WAAAA;EAAAA;AAIL,IAAA,AAAKD,6CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKN,wCAAAA;;WAAAA;EAAAA;AAuBE,MAAMG,2BAA2B,IAAIO,IAAI;;;;;;;;;;;;;;;;;;;;;;CAsB/C;AAIM,MAAMX,mBAAmB,IAAIW,IAAI;;;;CAIvC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/local-span-recorder.d.ts b/e-commerce/node_modules/next/dist/server/lib/trace/local-span-recorder.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..36363542da3715c93e4f845560d488b03934f350 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/local-span-recorder.d.ts @@ -0,0 +1,39 @@ +import type { AttributeValue, Span, SpanOptions } from 'next/dist/compiled/@opentelemetry/api'; +import { isLocalSpanRecordingEnabled, isRequestInsightsEnabled } from './span-store'; +export { isLocalSpanRecordingEnabled } from './span-store'; +type LocalSpanAttributes = Partial>; +type LocalSpanOptions = { + name: string; + attributes?: LocalSpanAttributes; + links?: SpanOptions['links']; + startTime?: SpanOptions['startTime']; + traceId?: string; + spanId?: string; + parentSpanId?: string; + delegateSpan?: Span; + isolateOpenTelemetry?: boolean; +}; +type TraceLocalSpanOptions = Omit & { + parentSpan?: Span | null; +}; +export declare function createLocalSpan({ name, attributes, links, startTime, traceId, spanId, parentSpanId, delegateSpan, isolateOpenTelemetry, }: LocalSpanOptions): Span; +export declare function getActiveLocalSpan(): Span | undefined; +export declare function isLocalRecordingSpan(span: Span): boolean; +export declare function isOpenTelemetryIsolatedSpan(span: Span): boolean; +export declare function withLocalSpan(span: Span, fn: () => T): T; +/** + * Records an async operation without replacing or exporting through the active + * OpenTelemetry context. Nested Next.js spans remain in the local trace. + */ +export declare function traceLocalSpan({ parentSpan, ...options }: TraceLocalSpanOptions, fn: () => Promise): Promise; +export type LocalSpanRecorder = { + createLocalSpan: typeof createLocalSpan; + getActiveLocalSpan: typeof getActiveLocalSpan; + isLocalRecordingSpan: typeof isLocalRecordingSpan; + isOpenTelemetryIsolatedSpan: typeof isOpenTelemetryIsolatedSpan; + isLocalSpanRecordingEnabled: typeof isLocalSpanRecordingEnabled; + isRequestInsightsEnabled: typeof isRequestInsightsEnabled; + traceLocalSpan: typeof traceLocalSpan; + withLocalSpan: typeof withLocalSpan; +}; +export declare function registerLocalSpanRecorder(): void; diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/local-span-recorder.js b/e-commerce/node_modules/next/dist/server/lib/trace/local-span-recorder.js new file mode 100644 index 0000000000000000000000000000000000000000..737da3ddf65741fd5bd69523ad30cacc58289001 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/local-span-recorder.js @@ -0,0 +1,385 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + createLocalSpan: null, + getActiveLocalSpan: null, + isLocalRecordingSpan: null, + isLocalSpanRecordingEnabled: null, + isOpenTelemetryIsolatedSpan: null, + registerLocalSpanRecorder: null, + traceLocalSpan: null, + withLocalSpan: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + createLocalSpan: function() { + return createLocalSpan; + }, + getActiveLocalSpan: function() { + return getActiveLocalSpan; + }, + isLocalRecordingSpan: function() { + return isLocalRecordingSpan; + }, + isLocalSpanRecordingEnabled: function() { + return _spanstore.isLocalSpanRecordingEnabled; + }, + isOpenTelemetryIsolatedSpan: function() { + return isOpenTelemetryIsolatedSpan; + }, + registerLocalSpanRecorder: function() { + return registerLocalSpanRecorder; + }, + traceLocalSpan: function() { + return traceLocalSpan; + }, + withLocalSpan: function() { + return withLocalSpan; + } +}); +const _api = require("next/dist/compiled/@opentelemetry/api"); +const _spanstore = require("./span-store"); +const TRACE_ID_HEX_LENGTH = 32; +const SPAN_ID_HEX_LENGTH = 16; +let lastLocalTraceId = 0; +let lastLocalSpanId = 0; +let localSpanAsyncStorage; +const getLocalTraceId = ()=>(++lastLocalTraceId).toString(16).padStart(TRACE_ID_HEX_LENGTH, '0'); +const getLocalSpanId = ()=>(++lastLocalSpanId).toString(16).padStart(SPAN_ID_HEX_LENGTH, '0'); +function createLocalSpan({ name, attributes, links, startTime, traceId, spanId, parentSpanId, delegateSpan, isolateOpenTelemetry }) { + return new LocalRecordingSpan({ + name, + attributes, + links, + startTime, + delegateSpan, + traceId: traceId ?? getLocalTraceId(), + spanId: spanId ?? getLocalSpanId(), + parentSpanId, + requestIdentity: getCurrentRequestIdentity(), + isolateOpenTelemetry: isolateOpenTelemetry ?? false + }); +} +function getActiveLocalSpan() { + return localSpanAsyncStorage == null ? void 0 : localSpanAsyncStorage.getStore(); +} +function isLocalRecordingSpan(span) { + return span instanceof LocalRecordingSpan; +} +function isOpenTelemetryIsolatedSpan(span) { + return span instanceof LocalRecordingSpan && span.isOpenTelemetryIsolated(); +} +function withLocalSpan(span, fn) { + return getLocalSpanAsyncStorage().run(span, fn); +} +async function traceLocalSpan({ parentSpan, ...options }, fn) { + const resolvedParentSpan = parentSpan === undefined ? getActiveLocalSpan() : parentSpan; + const parentSpanContext = resolvedParentSpan == null ? void 0 : resolvedParentSpan.spanContext(); + const span = createLocalSpan({ + ...options, + traceId: parentSpanContext == null ? void 0 : parentSpanContext.traceId, + parentSpanId: parentSpanContext == null ? void 0 : parentSpanContext.spanId, + isolateOpenTelemetry: true + }); + return withLocalSpan(span, async ()=>{ + try { + return await fn(); + } catch (err) { + span.recordException(err); + span.setStatus({ + code: _api.SpanStatusCode.ERROR + }); + throw err; + } finally{ + span.end(); + } + }); +} +function registerLocalSpanRecorder() { + const key = Symbol.for('@next/local-span-recorder'); + globalThis[key] = { + createLocalSpan, + getActiveLocalSpan, + isLocalRecordingSpan, + isOpenTelemetryIsolatedSpan, + isLocalSpanRecordingEnabled: _spanstore.isLocalSpanRecordingEnabled, + isRequestInsightsEnabled: _spanstore.isRequestInsightsEnabled, + traceLocalSpan, + withLocalSpan + }; +} +function getLocalSpanAsyncStorage() { + if (!localSpanAsyncStorage) { + const { createAsyncLocalStorage } = require('../../app-render/async-local-storage'); + localSpanAsyncStorage = createAsyncLocalStorage(); + } + return localSpanAsyncStorage; +} +class LocalRecordingSpan { + constructor({ name, attributes, links, startTime, delegateSpan, traceId, spanId, parentSpanId, requestIdentity, isolateOpenTelemetry }){ + this.name = name; + this.attributes = cleanSpanStoreAttributes(attributes); + this.events = []; + this.delegateSpan = delegateSpan; + this.openTelemetryIsolated = isolateOpenTelemetry; + this.spanContextValue = (delegateSpan == null ? void 0 : delegateSpan.spanContext()) ?? { + traceId, + spanId, + traceFlags: 0 + }; + this.links = getSpanStoreLinks(links); + this.parentSpanId = parentSpanId; + this.requestIdentity = requestIdentity; + this.startTime = getTimestamp(startTime); + this.statusCode = undefined; + this.statusMessage = undefined; + this.exception = undefined; + this.ended = false; + } + spanContext() { + return this.spanContextValue; + } + isOpenTelemetryIsolated() { + return this.openTelemetryIsolated; + } + setAttribute(key, value) { + var _this_delegateSpan; + if (this.ended) { + return this; + } + this.attributes[key] = value; + (_this_delegateSpan = this.delegateSpan) == null ? void 0 : _this_delegateSpan.setAttribute(key, value); + return this; + } + setAttributes(attributes) { + var _this_delegateSpan; + if (this.ended) { + return this; + } + // OpenTelemetry attributes may be undefined. Ignore them instead of + // overwriting an existing value as Object.assign would. + for (const key of Object.keys(attributes)){ + const value = attributes[key]; + if (value !== undefined) { + this.attributes[key] = value; + } + } + (_this_delegateSpan = this.delegateSpan) == null ? void 0 : _this_delegateSpan.setAttributes(attributes); + return this; + } + addEvent(name, attributesOrStartTime, startTime) { + var _this_delegateSpan; + if (this.ended) { + return this; + } + const eventTime = startTime === undefined && isTimestampInput(attributesOrStartTime) ? attributesOrStartTime : startTime; + this.events.push({ + name, + timestamp: getTimestamp(eventTime), + attributes: isSpanStoreAttributes(attributesOrStartTime) ? cleanSpanStoreAttributes(attributesOrStartTime) : undefined + }); + (_this_delegateSpan = this.delegateSpan) == null ? void 0 : _this_delegateSpan.addEvent(name, attributesOrStartTime, startTime); + return this; + } + setStatus(status) { + var _this_delegateSpan; + if (this.ended) { + return this; + } + this.statusCode = status.code; + this.statusMessage = status.message; + (_this_delegateSpan = this.delegateSpan) == null ? void 0 : _this_delegateSpan.setStatus(status); + return this; + } + updateName(name) { + var _this_delegateSpan; + if (this.ended) { + return this; + } + this.name = name; + (_this_delegateSpan = this.delegateSpan) == null ? void 0 : _this_delegateSpan.updateName(name); + return this; + } + end(endTime) { + if (this.ended) { + return; + } + this.ended = true; + try { + var _this_delegateSpan; + (_this_delegateSpan = this.delegateSpan) == null ? void 0 : _this_delegateSpan.end(endTime); + } finally{ + try { + this.record(endTime); + } finally{ + this.releaseReferences(); + } + } + } + isRecording() { + return !this.ended; + } + recordException(exception, time) { + var _this_delegateSpan; + if (this.ended) { + return; + } + this.exception = getSpanStoreException(exception); + this.events.push({ + name: 'exception', + timestamp: getTimestamp(time), + attributes: getSpanStoreExceptionAttributes(this.exception) + }); + (_this_delegateSpan = this.delegateSpan) == null ? void 0 : _this_delegateSpan.recordException(exception, time); + } + record(endTime) { + const recordAttributes = Object.keys(this.attributes).length > 0 ? this.attributes : undefined; + (0, _spanstore.recordSpan)({ + name: this.name, + startTime: this.startTime, + durationMs: Math.max(0, getTimestamp(endTime) - this.startTime), + status: this.statusCode === _api.SpanStatusCode.ERROR ? 'error' : 'ok', + traceId: this.spanContextValue.traceId, + spanId: this.spanContextValue.spanId, + parentSpanId: this.parentSpanId, + requestId: this.requestIdentity.requestId, + requestInsightKind: this.requestIdentity.requestInsightKind, + htmlRequestId: this.requestIdentity.htmlRequestId, + route: getStringAttribute(recordAttributes, 'next.route') ?? getStringAttribute(recordAttributes, 'http.route') ?? this.requestIdentity.route, + url: getStringAttribute(recordAttributes, 'http.url') ?? this.requestIdentity.url, + attributes: recordAttributes, + links: this.links, + events: this.events.length > 0 ? this.events : undefined, + error: this.getRecordError() + }); + } + releaseReferences() { + // AsyncLocalStorage can keep an ended span reachable when work spawned + // inside the span outlives it. Keep only the immutable span context and + // primitive timing/identity fields needed by the Span API after end. + this.name = ''; + this.attributes = {}; + this.events = []; + this.delegateSpan = undefined; + this.links = undefined; + this.requestIdentity = {}; + this.statusMessage = undefined; + this.exception = undefined; + } + getRecordError() { + if (this.exception) { + return this.exception; + } + if (this.statusCode === _api.SpanStatusCode.ERROR && this.statusMessage) { + return { + message: this.statusMessage + }; + } + return undefined; + } +} +function getSpanStoreLinks(links) { + const spanStoreLinks = links == null ? void 0 : links.map((link)=>({ + traceId: link.context.traceId, + spanId: link.context.spanId, + attributes: cleanSpanStoreAttributes(link.attributes) + })); + return (spanStoreLinks == null ? void 0 : spanStoreLinks.length) ? spanStoreLinks : undefined; +} +function cleanSpanStoreAttributes(attributes) { + const cleanedAttributes = {}; + if (attributes) { + for (const key of Object.keys(attributes)){ + const value = attributes[key]; + if (value !== undefined) { + cleanedAttributes[key] = value; + } + } + } + return cleanedAttributes; +} +function getTimestamp(time) { + if (time instanceof Date) { + return time.getTime(); + } + if (Array.isArray(time)) { + return time[0] * 1000 + time[1] / 1000000; + } + if (typeof time === 'number') { + return time < performance.timeOrigin / 2 ? performance.timeOrigin + time : time; + } + return performance.timeOrigin + performance.now(); +} +function getStringAttribute(attributes, key) { + const value = attributes == null ? void 0 : attributes[key]; + return typeof value === 'string' ? value : undefined; +} +function isSpanStoreAttributes(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date); +} +function isTimestampInput(value) { + return typeof value === 'number' || Array.isArray(value) || value instanceof Date; +} +function getSpanStoreException(exception) { + if (exception instanceof Error) { + return { + type: exception.name, + message: exception.message + }; + } + if (typeof exception === 'string') { + return { + message: exception + }; + } + if (exception && typeof exception === 'object') { + var _exception_constructor; + return { + type: (_exception_constructor = exception.constructor) == null ? void 0 : _exception_constructor.name, + message: 'message' in exception ? String(exception.message) : undefined + }; + } + return undefined; +} +function getSpanStoreExceptionAttributes(exception) { + if (!exception) { + return undefined; + } + const attributes = {}; + if (exception.type !== undefined) { + attributes['exception.type'] = exception.type; + } + if (exception.message !== undefined) { + attributes['exception.message'] = exception.message; + } + return Object.keys(attributes).length > 0 ? attributes : undefined; +} +function getCurrentRequestIdentity() { + try { + const { getRequestInsightsIdentity } = require('./request-insights-identity'); + const { workAsyncStorage } = require('../../app-render/work-async-storage.external'); + const { workUnitAsyncStorage } = require('../../app-render/work-unit-async-storage.external'); + const workStore = workAsyncStorage.getStore(); + const workUnitStore = workUnitAsyncStorage.getStore(); + const requestInsightsIdentity = getRequestInsightsIdentity(); + const url = workUnitStore && 'url' in workUnitStore ? workUnitStore.url : undefined; + return { + requestId: (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.requestId) ?? (workStore == null ? void 0 : workStore.requestId), + requestInsightKind: requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.kind, + htmlRequestId: (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.htmlRequestId) ?? (workStore == null ? void 0 : workStore.htmlRequestId), + route: workStore == null ? void 0 : workStore.route, + url: url ? `${url.pathname}${url.search}` : requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.url + }; + } catch { + return {}; + } +} + +//# sourceMappingURL=local-span-recorder.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/local-span-recorder.js.map b/e-commerce/node_modules/next/dist/server/lib/trace/local-span-recorder.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2bb302a301fe66c27ea49dbf0e6e0bfb125ffb2d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/local-span-recorder.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/lib/trace/local-span-recorder.ts"],"sourcesContent":["import type {\n AttributeValue,\n Span,\n SpanOptions,\n} from 'next/dist/compiled/@opentelemetry/api'\nimport type { AsyncLocalStorage } from 'async_hooks'\nimport { SpanStatusCode } from 'next/dist/compiled/@opentelemetry/api'\nimport {\n isLocalSpanRecordingEnabled,\n isRequestInsightsEnabled,\n recordSpan,\n type SpanStoreAttributes,\n type SpanStoreEvent,\n type SpanStoreLink,\n} from './span-store'\nimport type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'\n\nexport { isLocalSpanRecordingEnabled } from './span-store'\n\nconst TRACE_ID_HEX_LENGTH = 32\nconst SPAN_ID_HEX_LENGTH = 16\n\ntype LocalSpanAttributes = Partial>\n\ntype LocalSpanOptions = {\n name: string\n attributes?: LocalSpanAttributes\n links?: SpanOptions['links']\n startTime?: SpanOptions['startTime']\n traceId?: string\n spanId?: string\n parentSpanId?: string\n delegateSpan?: Span\n isolateOpenTelemetry?: boolean\n}\n\ntype TraceLocalSpanOptions = Omit<\n LocalSpanOptions,\n | 'traceId'\n | 'spanId'\n | 'parentSpanId'\n | 'delegateSpan'\n | 'isolateOpenTelemetry'\n> & {\n parentSpan?: Span | null\n}\n\nlet lastLocalTraceId = 0\nlet lastLocalSpanId = 0\nlet localSpanAsyncStorage: AsyncLocalStorage | undefined\n\nconst getLocalTraceId = () =>\n (++lastLocalTraceId).toString(16).padStart(TRACE_ID_HEX_LENGTH, '0')\n\nconst getLocalSpanId = () =>\n (++lastLocalSpanId).toString(16).padStart(SPAN_ID_HEX_LENGTH, '0')\n\nexport function createLocalSpan({\n name,\n attributes,\n links,\n startTime,\n traceId,\n spanId,\n parentSpanId,\n delegateSpan,\n isolateOpenTelemetry,\n}: LocalSpanOptions): Span {\n return new LocalRecordingSpan({\n name,\n attributes,\n links,\n startTime,\n delegateSpan,\n traceId: traceId ?? getLocalTraceId(),\n spanId: spanId ?? getLocalSpanId(),\n parentSpanId,\n requestIdentity: getCurrentRequestIdentity(),\n isolateOpenTelemetry: isolateOpenTelemetry ?? false,\n })\n}\n\nexport function getActiveLocalSpan(): Span | undefined {\n return localSpanAsyncStorage?.getStore()\n}\n\nexport function isLocalRecordingSpan(span: Span): boolean {\n return span instanceof LocalRecordingSpan\n}\n\nexport function isOpenTelemetryIsolatedSpan(span: Span): boolean {\n return span instanceof LocalRecordingSpan && span.isOpenTelemetryIsolated()\n}\n\nexport function withLocalSpan(span: Span, fn: () => T): T {\n return getLocalSpanAsyncStorage().run(span, fn)\n}\n\n/**\n * Records an async operation without replacing or exporting through the active\n * OpenTelemetry context. Nested Next.js spans remain in the local trace.\n */\nexport async function traceLocalSpan(\n { parentSpan, ...options }: TraceLocalSpanOptions,\n fn: () => Promise\n): Promise {\n const resolvedParentSpan =\n parentSpan === undefined ? getActiveLocalSpan() : parentSpan\n const parentSpanContext = resolvedParentSpan?.spanContext()\n const span = createLocalSpan({\n ...options,\n traceId: parentSpanContext?.traceId,\n parentSpanId: parentSpanContext?.spanId,\n isolateOpenTelemetry: true,\n })\n\n return withLocalSpan(span, async () => {\n try {\n return await fn()\n } catch (err) {\n span.recordException(err as Error)\n span.setStatus({ code: SpanStatusCode.ERROR })\n throw err\n } finally {\n span.end()\n }\n })\n}\n\nexport type LocalSpanRecorder = {\n createLocalSpan: typeof createLocalSpan\n getActiveLocalSpan: typeof getActiveLocalSpan\n isLocalRecordingSpan: typeof isLocalRecordingSpan\n isOpenTelemetryIsolatedSpan: typeof isOpenTelemetryIsolatedSpan\n isLocalSpanRecordingEnabled: typeof isLocalSpanRecordingEnabled\n isRequestInsightsEnabled: typeof isRequestInsightsEnabled\n traceLocalSpan: typeof traceLocalSpan\n withLocalSpan: typeof withLocalSpan\n}\n\nexport function registerLocalSpanRecorder(): void {\n const key = Symbol.for('@next/local-span-recorder')\n ;(\n globalThis as typeof globalThis & {\n [key]?: LocalSpanRecorder\n }\n )[key] = {\n createLocalSpan,\n getActiveLocalSpan,\n isLocalRecordingSpan,\n isOpenTelemetryIsolatedSpan,\n isLocalSpanRecordingEnabled,\n isRequestInsightsEnabled,\n traceLocalSpan,\n withLocalSpan,\n }\n}\n\nfunction getLocalSpanAsyncStorage(): AsyncLocalStorage {\n if (!localSpanAsyncStorage) {\n const { createAsyncLocalStorage } =\n require('../../app-render/async-local-storage') as typeof import('../../app-render/async-local-storage')\n localSpanAsyncStorage = createAsyncLocalStorage()\n }\n\n return localSpanAsyncStorage\n}\n\ntype RequestIdentity = {\n requestId?: string\n requestInsightKind?: RequestInsightKind\n htmlRequestId?: string\n route?: string\n url?: string\n}\n\nclass LocalRecordingSpan implements Span {\n public name: string\n\n private attributes: SpanStoreAttributes\n private events: SpanStoreEvent[]\n private readonly spanContextValue: ReturnType\n private readonly openTelemetryIsolated: boolean\n private delegateSpan?: Span\n private links?: SpanStoreLink[]\n private readonly parentSpanId?: string\n private requestIdentity: RequestIdentity\n private readonly startTime: number\n private statusCode: number | undefined\n private statusMessage: string | undefined\n private exception:\n | {\n type?: string\n message?: string\n }\n | undefined\n private ended: boolean\n\n constructor({\n name,\n attributes,\n links,\n startTime,\n delegateSpan,\n traceId,\n spanId,\n parentSpanId,\n requestIdentity,\n isolateOpenTelemetry,\n }: {\n name: string\n attributes?: LocalSpanAttributes\n links?: SpanOptions['links']\n startTime?: SpanOptions['startTime']\n delegateSpan?: Span\n traceId: string\n spanId: string\n parentSpanId?: string\n requestIdentity: RequestIdentity\n isolateOpenTelemetry: boolean\n }) {\n this.name = name\n this.attributes = cleanSpanStoreAttributes(attributes)\n this.events = []\n this.delegateSpan = delegateSpan\n this.openTelemetryIsolated = isolateOpenTelemetry\n this.spanContextValue = delegateSpan?.spanContext() ?? {\n traceId,\n spanId,\n traceFlags: 0,\n }\n this.links = getSpanStoreLinks(links)\n this.parentSpanId = parentSpanId\n this.requestIdentity = requestIdentity\n this.startTime = getTimestamp(startTime)\n this.statusCode = undefined\n this.statusMessage = undefined\n this.exception = undefined\n this.ended = false\n }\n\n spanContext(): ReturnType {\n return this.spanContextValue\n }\n\n isOpenTelemetryIsolated(): boolean {\n return this.openTelemetryIsolated\n }\n\n setAttribute(key: string, value: AttributeValue): this {\n if (this.ended) {\n return this\n }\n\n this.attributes[key] = value\n this.delegateSpan?.setAttribute(key, value)\n return this\n }\n\n setAttributes(attributes: Parameters[0]): this {\n if (this.ended) {\n return this\n }\n\n // OpenTelemetry attributes may be undefined. Ignore them instead of\n // overwriting an existing value as Object.assign would.\n for (const key of Object.keys(attributes)) {\n const value = attributes[key]\n if (value !== undefined) {\n this.attributes[key] = value\n }\n }\n this.delegateSpan?.setAttributes(attributes)\n return this\n }\n\n addEvent(\n name: string,\n attributesOrStartTime?: Parameters[1],\n startTime?: Parameters[2]\n ): this {\n if (this.ended) {\n return this\n }\n\n const eventTime =\n startTime === undefined && isTimestampInput(attributesOrStartTime)\n ? attributesOrStartTime\n : startTime\n this.events.push({\n name,\n timestamp: getTimestamp(eventTime),\n attributes: isSpanStoreAttributes(attributesOrStartTime)\n ? cleanSpanStoreAttributes(attributesOrStartTime)\n : undefined,\n })\n this.delegateSpan?.addEvent(name, attributesOrStartTime, startTime)\n return this\n }\n\n setStatus(status: Parameters[0]): this {\n if (this.ended) {\n return this\n }\n\n this.statusCode = status.code\n this.statusMessage = status.message\n this.delegateSpan?.setStatus(status)\n return this\n }\n\n updateName(name: string): this {\n if (this.ended) {\n return this\n }\n\n this.name = name\n this.delegateSpan?.updateName(name)\n return this\n }\n\n end(endTime?: Parameters[0]): void {\n if (this.ended) {\n return\n }\n\n this.ended = true\n try {\n this.delegateSpan?.end(endTime)\n } finally {\n try {\n this.record(endTime)\n } finally {\n this.releaseReferences()\n }\n }\n }\n\n isRecording(): boolean {\n return !this.ended\n }\n\n recordException(\n exception: Parameters[0],\n time?: Parameters[1]\n ): void {\n if (this.ended) {\n return\n }\n\n this.exception = getSpanStoreException(exception)\n this.events.push({\n name: 'exception',\n timestamp: getTimestamp(time),\n attributes: getSpanStoreExceptionAttributes(this.exception),\n })\n this.delegateSpan?.recordException(exception, time)\n }\n\n private record(endTime: Parameters[0]): void {\n const recordAttributes =\n Object.keys(this.attributes).length > 0 ? this.attributes : undefined\n\n recordSpan({\n name: this.name,\n startTime: this.startTime,\n durationMs: Math.max(0, getTimestamp(endTime) - this.startTime),\n status: this.statusCode === SpanStatusCode.ERROR ? 'error' : 'ok',\n traceId: this.spanContextValue.traceId,\n spanId: this.spanContextValue.spanId,\n parentSpanId: this.parentSpanId,\n requestId: this.requestIdentity.requestId,\n requestInsightKind: this.requestIdentity.requestInsightKind,\n htmlRequestId: this.requestIdentity.htmlRequestId,\n route:\n getStringAttribute(recordAttributes, 'next.route') ??\n getStringAttribute(recordAttributes, 'http.route') ??\n this.requestIdentity.route,\n url:\n getStringAttribute(recordAttributes, 'http.url') ??\n this.requestIdentity.url,\n attributes: recordAttributes,\n links: this.links,\n events: this.events.length > 0 ? this.events : undefined,\n error: this.getRecordError(),\n })\n }\n\n private releaseReferences(): void {\n // AsyncLocalStorage can keep an ended span reachable when work spawned\n // inside the span outlives it. Keep only the immutable span context and\n // primitive timing/identity fields needed by the Span API after end.\n this.name = ''\n this.attributes = {}\n this.events = []\n this.delegateSpan = undefined\n this.links = undefined\n this.requestIdentity = {}\n this.statusMessage = undefined\n this.exception = undefined\n }\n\n private getRecordError():\n | {\n type?: string\n message?: string\n }\n | undefined {\n if (this.exception) {\n return this.exception\n }\n\n if (this.statusCode === SpanStatusCode.ERROR && this.statusMessage) {\n return {\n message: this.statusMessage,\n }\n }\n\n return undefined\n }\n}\n\nfunction getSpanStoreLinks(\n links: SpanOptions['links'] | undefined\n): SpanStoreLink[] | undefined {\n const spanStoreLinks = links?.map((link) => ({\n traceId: link.context.traceId,\n spanId: link.context.spanId,\n attributes: cleanSpanStoreAttributes(link.attributes),\n }))\n\n return spanStoreLinks?.length ? spanStoreLinks : undefined\n}\n\nfunction cleanSpanStoreAttributes(\n attributes:\n | Record\n | SpanStoreAttributes\n | undefined\n): SpanStoreAttributes {\n const cleanedAttributes: SpanStoreAttributes = {}\n if (attributes) {\n for (const key of Object.keys(attributes)) {\n const value = attributes[key]\n if (value !== undefined) {\n cleanedAttributes[key] = value\n }\n }\n }\n return cleanedAttributes\n}\n\nfunction getTimestamp(time?: SpanOptions['startTime']): number {\n if (time instanceof Date) {\n return time.getTime()\n }\n\n if (Array.isArray(time)) {\n return time[0] * 1000 + time[1] / 1_000_000\n }\n\n if (typeof time === 'number') {\n return time < performance.timeOrigin / 2\n ? performance.timeOrigin + time\n : time\n }\n\n return performance.timeOrigin + performance.now()\n}\n\nfunction getStringAttribute(\n attributes: SpanStoreAttributes | undefined,\n key: string\n): string | undefined {\n const value = attributes?.[key]\n return typeof value === 'string' ? value : undefined\n}\n\nfunction isSpanStoreAttributes(\n value: Parameters[1]\n): value is SpanStoreAttributes {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n )\n}\n\nfunction isTimestampInput(\n value: Parameters[1]\n): value is SpanOptions['startTime'] {\n return (\n typeof value === 'number' || Array.isArray(value) || value instanceof Date\n )\n}\n\nfunction getSpanStoreException(\n exception: Parameters[0]\n):\n | {\n type?: string\n message?: string\n }\n | undefined {\n if (exception instanceof Error) {\n return {\n type: exception.name,\n message: exception.message,\n }\n }\n\n if (typeof exception === 'string') {\n return {\n message: exception,\n }\n }\n\n if (exception && typeof exception === 'object') {\n return {\n type: exception.constructor?.name,\n message: 'message' in exception ? String(exception.message) : undefined,\n }\n }\n\n return undefined\n}\n\nfunction getSpanStoreExceptionAttributes(\n exception:\n | {\n type?: string\n message?: string\n }\n | undefined\n): SpanStoreAttributes | undefined {\n if (!exception) {\n return undefined\n }\n\n const attributes: SpanStoreAttributes = {}\n if (exception.type !== undefined) {\n attributes['exception.type'] = exception.type\n }\n if (exception.message !== undefined) {\n attributes['exception.message'] = exception.message\n }\n return Object.keys(attributes).length > 0 ? attributes : undefined\n}\n\nfunction getCurrentRequestIdentity(): RequestIdentity {\n try {\n const { getRequestInsightsIdentity } =\n require('./request-insights-identity') as typeof import('./request-insights-identity')\n const { workAsyncStorage } =\n require('../../app-render/work-async-storage.external') as typeof import('../../app-render/work-async-storage.external')\n const { workUnitAsyncStorage } =\n require('../../app-render/work-unit-async-storage.external') as typeof import('../../app-render/work-unit-async-storage.external')\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n const requestInsightsIdentity = getRequestInsightsIdentity()\n const url =\n workUnitStore && 'url' in workUnitStore ? workUnitStore.url : undefined\n\n return {\n requestId: requestInsightsIdentity?.requestId ?? workStore?.requestId,\n requestInsightKind: requestInsightsIdentity?.kind,\n htmlRequestId:\n requestInsightsIdentity?.htmlRequestId ?? workStore?.htmlRequestId,\n route: workStore?.route,\n url: url ? `${url.pathname}${url.search}` : requestInsightsIdentity?.url,\n }\n } catch {\n return {}\n }\n}\n"],"names":["createLocalSpan","getActiveLocalSpan","isLocalRecordingSpan","isLocalSpanRecordingEnabled","isOpenTelemetryIsolatedSpan","registerLocalSpanRecorder","traceLocalSpan","withLocalSpan","TRACE_ID_HEX_LENGTH","SPAN_ID_HEX_LENGTH","lastLocalTraceId","lastLocalSpanId","localSpanAsyncStorage","getLocalTraceId","toString","padStart","getLocalSpanId","name","attributes","links","startTime","traceId","spanId","parentSpanId","delegateSpan","isolateOpenTelemetry","LocalRecordingSpan","requestIdentity","getCurrentRequestIdentity","getStore","span","isOpenTelemetryIsolated","fn","getLocalSpanAsyncStorage","run","parentSpan","options","resolvedParentSpan","undefined","parentSpanContext","spanContext","err","recordException","setStatus","code","SpanStatusCode","ERROR","end","key","Symbol","for","globalThis","isRequestInsightsEnabled","createAsyncLocalStorage","require","constructor","cleanSpanStoreAttributes","events","openTelemetryIsolated","spanContextValue","traceFlags","getSpanStoreLinks","getTimestamp","statusCode","statusMessage","exception","ended","setAttribute","value","setAttributes","Object","keys","addEvent","attributesOrStartTime","eventTime","isTimestampInput","push","timestamp","isSpanStoreAttributes","status","message","updateName","endTime","record","releaseReferences","isRecording","time","getSpanStoreException","getSpanStoreExceptionAttributes","recordAttributes","length","recordSpan","durationMs","Math","max","requestId","requestInsightKind","htmlRequestId","route","getStringAttribute","url","error","getRecordError","spanStoreLinks","map","link","context","cleanedAttributes","Date","getTime","Array","isArray","performance","timeOrigin","now","Error","type","String","getRequestInsightsIdentity","workAsyncStorage","workUnitAsyncStorage","workStore","workUnitStore","requestInsightsIdentity","kind","pathname","search"],"mappings":";;;;;;;;;;;;;;;;;;;;;IAyDgBA,eAAe;eAAfA;;IAyBAC,kBAAkB;eAAlBA;;IAIAC,oBAAoB;eAApBA;;IArEPC,2BAA2B;eAA3BA,sCAA2B;;IAyEpBC,2BAA2B;eAA3BA;;IAkDAC,yBAAyB;eAAzBA;;IAtCMC,cAAc;eAAdA;;IARNC,aAAa;eAAbA;;;qBAxFe;2BAQxB;AAKP,MAAMC,sBAAsB;AAC5B,MAAMC,qBAAqB;AA2B3B,IAAIC,mBAAmB;AACvB,IAAIC,kBAAkB;AACtB,IAAIC;AAEJ,MAAMC,kBAAkB,IACtB,AAAC,CAAA,EAAEH,gBAAe,EAAGI,QAAQ,CAAC,IAAIC,QAAQ,CAACP,qBAAqB;AAElE,MAAMQ,iBAAiB,IACrB,AAAC,CAAA,EAAEL,eAAc,EAAGG,QAAQ,CAAC,IAAIC,QAAQ,CAACN,oBAAoB;AAEzD,SAAST,gBAAgB,EAC9BiB,IAAI,EACJC,UAAU,EACVC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,YAAY,EACZC,YAAY,EACZC,oBAAoB,EACH;IACjB,OAAO,IAAIC,mBAAmB;QAC5BT;QACAC;QACAC;QACAC;QACAI;QACAH,SAASA,WAAWR;QACpBS,QAAQA,UAAUN;QAClBO;QACAI,iBAAiBC;QACjBH,sBAAsBA,wBAAwB;IAChD;AACF;AAEO,SAASxB;IACd,OAAOW,yCAAAA,sBAAuBiB,QAAQ;AACxC;AAEO,SAAS3B,qBAAqB4B,IAAU;IAC7C,OAAOA,gBAAgBJ;AACzB;AAEO,S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Q,GAAGzB,IAAI0B,MAAM,EAAE,GAAGH,2CAAAA,wBAAyBvB,GAAG;QAC1E;IACF,EAAE,OAAM;QACN,OAAO,CAAC;IACV;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/request-insights-identity.d.ts b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights-identity.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f816811d445d0e0ebb3c37b1e16c29ea1bf97179 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights-identity.d.ts @@ -0,0 +1,9 @@ +import type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'; +export type RequestInsightsIdentity = { + requestId: string; + kind?: RequestInsightKind; + htmlRequestId: string; + url: string | undefined; +}; +export declare function runWithRequestInsightsIdentity(identity: RequestInsightsIdentity, fn: () => T): T; +export declare function getRequestInsightsIdentity(): RequestInsightsIdentity | undefined; diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/request-insights-identity.js b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights-identity.js new file mode 100644 index 0000000000000000000000000000000000000000..4828da63d708319013077e67e54982698d0a6065 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights-identity.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getRequestInsightsIdentity: null, + runWithRequestInsightsIdentity: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getRequestInsightsIdentity: function() { + return getRequestInsightsIdentity; + }, + runWithRequestInsightsIdentity: function() { + return runWithRequestInsightsIdentity; + } +}); +const _asynclocalstorage = require("../../app-render/async-local-storage"); +// This storage covers the part of BaseServer request handling that runs before +// App Render creates workAsyncStorage. Once available, workStore remains the +// primary identity source for locally recorded spans. +function getRequestInsightsIdentityStorage() { + return (0, _asynclocalstorage.getOrCreateGlobalAsyncLocalStorage)('request-insights-identity-storage'); +} +function runWithRequestInsightsIdentity(identity, fn) { + return getRequestInsightsIdentityStorage().run(identity, fn); +} +function getRequestInsightsIdentity() { + return getRequestInsightsIdentityStorage().getStore(); +} + +//# sourceMappingURL=request-insights-identity.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/request-insights-identity.js.map b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights-identity.js.map new file mode 100644 index 0000000000000000000000000000000000000000..afff7ca977609bfcdb0adbfc08aadbf11c6eab7f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights-identity.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/lib/trace/request-insights-identity.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'\nimport { getOrCreateGlobalAsyncLocalStorage } from '../../app-render/async-local-storage'\n\nexport type RequestInsightsIdentity = {\n requestId: string\n kind?: RequestInsightKind\n htmlRequestId: string\n url: string | undefined\n}\n\n// This storage covers the part of BaseServer request handling that runs before\n// App Render creates workAsyncStorage. Once available, workStore remains the\n// primary identity source for locally recorded spans.\nfunction getRequestInsightsIdentityStorage(): AsyncLocalStorage {\n return getOrCreateGlobalAsyncLocalStorage('request-insights-identity-storage')\n}\n\nexport function runWithRequestInsightsIdentity(\n identity: RequestInsightsIdentity,\n fn: () => T\n): T {\n return getRequestInsightsIdentityStorage().run(identity, fn)\n}\n\nexport function getRequestInsightsIdentity():\n | RequestInsightsIdentity\n | undefined {\n return getRequestInsightsIdentityStorage().getStore()\n}\n"],"names":["getRequestInsightsIdentity","runWithRequestInsightsIdentity","getRequestInsightsIdentityStorage","getOrCreateGlobalAsyncLocalStorage","identity","fn","run","getStore"],"mappings":";;;;;;;;;;;;;;;IAyBgBA,0BAA0B;eAA1BA;;IAPAC,8BAA8B;eAA9BA;;;mCAhBmC;AASnD,+EAA+E;AAC/E,6EAA6E;AAC7E,sDAAsD;AACtD,SAASC;IACP,OAAOC,IAAAA,qDAAkC,EAAC;AAC5C;AAEO,SAASF,+BACdG,QAAiC,EACjCC,EAAW;IAEX,OAAOH,oCAAoCI,GAAG,CAACF,UAAUC;AAC3D;AAEO,SAASL;IAGd,OAAOE,oCAAoCK,QAAQ;AACrD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/request-insights.d.ts b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5bce7a00f55ad71b5d51a5a852623aeea1da0778 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights.d.ts @@ -0,0 +1,17 @@ +import type { RequestInsight, RequestInsightFetch, RequestInsightsSnapshot } from '../../../next-devtools/shared/request-insights'; +import type { RequestInsightKind } from '../../../shared/lib/request-insights'; +import type { SpanStoreRecord } from './span-store'; +export { isRequestInsightsEnabled } from './span-store'; +type RequestInsightsListener = (insight: RequestInsight) => void; +type RequestInsightIdentity = { + requestId?: string; + kind?: RequestInsightKind; + htmlRequestId?: string; + route?: string; + url?: string; +}; +export declare function recordRequestInsightSpan(span: SpanStoreRecord): void; +export declare function recordRequestInsightFetch(identity: RequestInsightIdentity, fetch: RequestInsightFetch): void; +export declare function getRequestInsightsSnapshot(): RequestInsightsSnapshot; +export declare function subscribeRequestInsights(listener: RequestInsightsListener): () => void; +export declare function clearRequestInsightsForTest(): void; diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/request-insights.js b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights.js new file mode 100644 index 0000000000000000000000000000000000000000..27ddaa3cc5d4ef73727b77cec93f3f3f2e2ba383 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights.js @@ -0,0 +1,308 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + clearRequestInsightsForTest: null, + getRequestInsightsSnapshot: null, + isRequestInsightsEnabled: null, + recordRequestInsightFetch: null, + recordRequestInsightSpan: null, + subscribeRequestInsights: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + clearRequestInsightsForTest: function() { + return clearRequestInsightsForTest; + }, + getRequestInsightsSnapshot: function() { + return getRequestInsightsSnapshot; + }, + isRequestInsightsEnabled: function() { + return _spanstore.isRequestInsightsEnabled; + }, + recordRequestInsightFetch: function() { + return recordRequestInsightFetch; + }, + recordRequestInsightSpan: function() { + return recordRequestInsightSpan; + }, + subscribeRequestInsights: function() { + return subscribeRequestInsights; + } +}); +const _requestinsights = require("../../../shared/lib/request-insights"); +const _spanstore = require("./span-store"); +const MAX_REQUEST_INSIGHTS = 100; +const REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store'); +const CLIENT_COMPONENT_LOADING_SPAN_TYPE = 'NextNodeServer.clientComponentLoading'; +const REDACTED_VALUE = 'redacted'; +const SAFE_SPAN_ATTRIBUTE_KEYS = new Set([ + 'http.method', + 'http.route', + 'http.status_code', + 'http.url', + 'net.peer.name', + 'net.peer.port', + 'next.fetch.cache_reason', + 'next.fetch.cache_status', + 'next.fetch.idx', + 'next.route', + 'next.rsc', + 'next.segment', + 'next.span_category', + 'next.span_name', + 'next.span_type' +]); +const SENSITIVE_PARAM_NAME_RE = /(?:^|[_-])(?:access[_-]?token|api[_-]?key|auth|authorization|code|cookie|credential|id[_-]?token|jwt|key|password|secret|session|signature|sig|token)(?:$|[_-])/i; +class InMemoryRequestInsightsStore { + recordSpan(span) { + var _span_attributes; + if (!span.requestId) { + return; + } + const insight = this.getOrCreateRequest({ + requestId: span.requestId, + kind: span.requestInsightKind, + htmlRequestId: span.htmlRequestId, + route: span.route, + url: span.url + }, span.startTime ?? span.timestamp); + const spanStartTime = span.startTime ?? span.timestamp; + insight.htmlRequestId = span.htmlRequestId ?? insight.htmlRequestId; + insight.route = insight.route ?? span.route; + insight.url = insight.url ?? sanitizeUrl(span.url); + this.updateTiming(insight, spanStartTime, span.durationMs, ((_span_attributes = span.attributes) == null ? void 0 : _span_attributes['next.span_type']) === 'BaseServer.handleRequest'); + insight.status = insight.status === 'error' || span.status === 'error' ? 'error' : span.status === 'ok' ? 'ok' : insight.status; + insight.spans.push({ + name: span.name, + startTime: spanStartTime, + durationMs: span.durationMs, + status: span.status, + traceId: span.traceId, + spanId: span.spanId, + parentSpanId: span.parentSpanId, + attributes: sanitizeSpanAttributes(span.attributes), + links: sanitizeSpanLinks(span.links), + events: sanitizeSpanEvents(span.events), + error: span.error + }); + const fetch = getFetchInsight(span); + if (fetch) { + this.recordFetchForInsight(insight, fetch); + } + this.notify(insight); + } + recordFetch(identity, fetch) { + if (!identity.requestId) { + return; + } + const fetchStartTime = fetch.startTime ?? getCurrentTimestamp(); + const insight = this.getOrCreateRequest(identity, fetchStartTime); + this.updateTiming(insight, fetchStartTime, fetch.durationMs, false); + this.recordFetchForInsight(insight, sanitizeFetchInsight(fetch)); + this.notify(insight); + } + getSnapshot() { + return { + requests: this.requestOrder.map((insightKey)=>this.requests.get(insightKey)).filter((request)=>request !== undefined) + }; + } + subscribe(listener) { + this.listeners.add(listener); + return ()=>{ + this.listeners.delete(listener); + }; + } + clear() { + this.requests.clear(); + this.requestTimings.clear(); + this.requestOrder.length = 0; + } + updateTiming(insight, startTime, durationMs, isRequestSpan) { + const insightKey = (0, _requestinsights.getRequestInsightKey)(insight); + if (isRequestSpan && durationMs !== undefined) { + const requestTiming = { + startTime, + durationMs + }; + this.requestTimings.set(insightKey, requestTiming); + insight.startTime = requestTiming.startTime; + insight.durationMs = requestTiming.durationMs; + return; + } + const requestTiming = this.requestTimings.get(insightKey); + if (requestTiming) { + insight.startTime = requestTiming.startTime; + insight.durationMs = requestTiming.durationMs; + return; + } + const endTime = startTime + (durationMs ?? 0); + const requestEndTime = insight.startTime + (insight.durationMs ?? 0); + insight.startTime = Math.min(insight.startTime, startTime); + insight.durationMs = Math.max(requestEndTime, endTime) - insight.startTime; + } + notify(insight) { + for (const listener of this.listeners){ + listener(insight); + } + } + getOrCreateRequest(identity, startTime) { + const requestId = identity.requestId; + const insightKey = (0, _requestinsights.getRequestInsightKey)({ + requestId, + kind: identity.kind + }); + let insight = this.requests.get(insightKey); + if (!insight) { + insight = { + requestId, + kind: (0, _requestinsights.getRequestInsightKind)(identity), + htmlRequestId: identity.htmlRequestId ?? requestId, + route: identity.route, + url: sanitizeUrl(identity.url), + startTime, + status: 'pending', + spans: [], + fetches: [] + }; + this.requests.set(insightKey, insight); + this.requestOrder.push(insightKey); + this.trim(); + } + insight.htmlRequestId = identity.htmlRequestId ?? insight.htmlRequestId; + insight.route = insight.route ?? identity.route; + insight.url = insight.url ?? sanitizeUrl(identity.url); + insight.startTime = Math.min(insight.startTime, startTime); + return insight; + } + recordFetchForInsight(insight, fetch) { + if (insight.fetches.some((existingFetch)=>existingFetch.url === fetch.url && (existingFetch.index !== undefined && fetch.index !== undefined ? existingFetch.index === fetch.index : existingFetch.startTime === fetch.startTime))) { + return; + } + insight.fetches.push(sanitizeFetchInsight(fetch)); + } + trim() { + while(this.requestOrder.length > MAX_REQUEST_INSIGHTS){ + const insightKey = this.requestOrder.shift(); + if (insightKey) { + this.requests.delete(insightKey); + this.requestTimings.delete(insightKey); + } + } + } + constructor(){ + this.requests = new Map(); + this.requestTimings = new Map(); + this.requestOrder = []; + this.listeners = new Set(); + } +} +function recordRequestInsightSpan(span) { + var _span_attributes; + if (((_span_attributes = span.attributes) == null ? void 0 : _span_attributes['next.span_type']) === CLIENT_COMPONENT_LOADING_SPAN_TYPE) { + return; + } + getRequestInsightsStore().recordSpan(span); +} +function recordRequestInsightFetch(identity, fetch) { + getRequestInsightsStore().recordFetch(identity, fetch); +} +function getRequestInsightsSnapshot() { + return getRequestInsightsStore().getSnapshot(); +} +function subscribeRequestInsights(listener) { + return getRequestInsightsStore().subscribe(listener); +} +function clearRequestInsightsForTest() { + getRequestInsightsStore().clear(); +} +function getRequestInsightsStore() { + const globalStore = globalThis; + return globalStore[REQUEST_INSIGHTS_STORE_KEY] ??= new InMemoryRequestInsightsStore(); +} +function getFetchInsight(span) { + const attributes = span.attributes; + if (!attributes || attributes['next.span_type'] !== 'AppRender.fetch') { + return null; + } + return { + url: sanitizeUrl(getStringAttribute(attributes['http.url']) ?? span.url), + method: getStringAttribute(attributes['http.method']), + statusCode: getNumberAttribute(attributes['http.status_code']), + startTime: span.startTime ?? span.timestamp, + durationMs: span.durationMs, + cacheStatus: getStringAttribute(attributes['next.fetch.cache_status']), + cacheReason: getStringAttribute(attributes['next.fetch.cache_reason']), + index: getNumberAttribute(attributes['next.fetch.idx']) + }; +} +function sanitizeFetchInsight(fetch) { + return { + ...fetch, + url: sanitizeUrl(fetch.url) + }; +} +function getCurrentTimestamp() { + return performance.timeOrigin + performance.now(); +} +function sanitizeSpanAttributes(attributes) { + if (!attributes) { + return undefined; + } + const sanitized = {}; + for (const [key, value] of Object.entries(attributes)){ + if (!SAFE_SPAN_ATTRIBUTE_KEYS.has(key)) { + continue; + } + sanitized[key] = key === 'http.url' ? sanitizeUrlAttribute(value) : value; + } + return Object.keys(sanitized).length > 0 ? sanitized : undefined; +} +function sanitizeSpanEvents(events) { + return events == null ? void 0 : events.map((event)=>({ + ...event, + attributes: sanitizeSpanAttributes(event.attributes) + })); +} +function sanitizeSpanLinks(links) { + return links == null ? void 0 : links.map((link)=>({ + ...link, + attributes: sanitizeSpanAttributes(link.attributes) + })); +} +function sanitizeUrlAttribute(value) { + return typeof value === 'string' ? sanitizeUrl(value) ?? '' : value; +} +function sanitizeUrl(value) { + if (!value) { + return value; + } + const isRelativeUrl = value.startsWith('/'); + try { + const url = isRelativeUrl ? new URL(value, 'http://n') : new URL(value); + url.username = ''; + url.password = ''; + for (const name of Array.from(url.searchParams.keys())){ + if (SENSITIVE_PARAM_NAME_RE.test(name)) { + url.searchParams.set(name, REDACTED_VALUE); + } + } + return isRelativeUrl ? `${url.pathname}${url.search}${url.hash}` : url.href; + } catch { + return value; + } +} +function getStringAttribute(value) { + return typeof value === 'string' ? value : undefined; +} +function getNumberAttribute(value) { + return typeof value === 'number' ? value : undefined; +} + +//# sourceMappingURL=request-insights.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/request-insights.js.map b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2801111d0121bcb0481f5791ffb0491df343db55 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/request-insights.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/lib/trace/request-insights.ts"],"sourcesContent":["import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\nimport type {\n RequestInsight,\n RequestInsightFetch,\n RequestInsightsSnapshot,\n} from '../../../next-devtools/shared/request-insights'\nimport type { RequestInsightKind } from '../../../shared/lib/request-insights'\nimport {\n getRequestInsightKey,\n getRequestInsightKind,\n} from '../../../shared/lib/request-insights'\nimport type { SpanStoreRecord } from './span-store'\nexport { isRequestInsightsEnabled } from './span-store'\n\nconst MAX_REQUEST_INSIGHTS = 100\nconst REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store')\nconst CLIENT_COMPONENT_LOADING_SPAN_TYPE =\n 'NextNodeServer.clientComponentLoading'\n\ntype RequestInsightsListener = (insight: RequestInsight) => void\ntype RequestInsightIdentity = {\n requestId?: string\n kind?: RequestInsightKind\n htmlRequestId?: string\n route?: string\n url?: string\n}\n\nconst REDACTED_VALUE = 'redacted'\nconst SAFE_SPAN_ATTRIBUTE_KEYS = new Set([\n 'http.method',\n 'http.route',\n 'http.status_code',\n 'http.url',\n 'net.peer.name',\n 'net.peer.port',\n 'next.fetch.cache_reason',\n 'next.fetch.cache_status',\n 'next.fetch.idx',\n 'next.route',\n 'next.rsc',\n 'next.segment',\n 'next.span_category',\n 'next.span_name',\n 'next.span_type',\n])\nconst SENSITIVE_PARAM_NAME_RE =\n /(?:^|[_-])(?:access[_-]?token|api[_-]?key|auth|authorization|code|cookie|credential|id[_-]?token|jwt|key|password|secret|session|signature|sig|token)(?:$|[_-])/i\n\nclass InMemoryRequestInsightsStore {\n private readonly requests = new Map()\n private readonly requestTimings = new Map<\n string,\n { startTime: number; durationMs: number }\n >()\n private readonly requestOrder: string[] = []\n private readonly listeners = new Set()\n\n recordSpan(span: SpanStoreRecord): void {\n if (!span.requestId) {\n return\n }\n\n const insight = this.getOrCreateRequest(\n {\n requestId: span.requestId,\n kind: span.requestInsightKind,\n htmlRequestId: span.htmlRequestId,\n route: span.route,\n url: span.url,\n },\n span.startTime ?? span.timestamp\n )\n\n const spanStartTime = span.startTime ?? span.timestamp\n insight.htmlRequestId = span.htmlRequestId ?? insight.htmlRequestId\n insight.route = insight.route ?? span.route\n insight.url = insight.url ?? sanitizeUrl(span.url)\n this.updateTiming(\n insight,\n spanStartTime,\n span.durationMs,\n span.attributes?.['next.span_type'] === 'BaseServer.handleRequest'\n )\n insight.status =\n insight.status === 'error' || span.status === 'error'\n ? 'error'\n : span.status === 'ok'\n ? 'ok'\n : insight.status\n\n insight.spans.push({\n name: span.name,\n startTime: spanStartTime,\n durationMs: span.durationMs,\n status: span.status,\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n attributes: sanitizeSpanAttributes(span.attributes),\n links: sanitizeSpanLinks(span.links),\n events: sanitizeSpanEvents(span.events),\n error: span.error,\n })\n\n const fetch = getFetchInsight(span)\n if (fetch) {\n this.recordFetchForInsight(insight, fetch)\n }\n\n this.notify(insight)\n }\n\n recordFetch(identity: RequestInsightIdentity, fetch: RequestInsightFetch) {\n if (!identity.requestId) {\n return\n }\n\n const fetchStartTime = fetch.startTime ?? getCurrentTimestamp()\n const insight = this.getOrCreateRequest(identity, fetchStartTime)\n this.updateTiming(insight, fetchStartTime, fetch.durationMs, false)\n this.recordFetchForInsight(insight, sanitizeFetchInsight(fetch))\n this.notify(insight)\n }\n\n getSnapshot(): RequestInsightsSnapshot {\n return {\n requests: this.requestOrder\n .map((insightKey) => this.requests.get(insightKey))\n .filter((request): request is RequestInsight => request !== undefined),\n }\n }\n\n subscribe(listener: RequestInsightsListener): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n clear(): void {\n this.requests.clear()\n this.requestTimings.clear()\n this.requestOrder.length = 0\n }\n\n private updateTiming(\n insight: RequestInsight,\n startTime: number,\n durationMs: number | undefined,\n isRequestSpan: boolean\n ): void {\n const insightKey = getRequestInsightKey(insight)\n if (isRequestSpan && durationMs !== undefined) {\n const requestTiming = { startTime, durationMs }\n this.requestTimings.set(insightKey, requestTiming)\n insight.startTime = requestTiming.startTime\n insight.durationMs = requestTiming.durationMs\n return\n }\n\n const requestTiming = this.requestTimings.get(insightKey)\n if (requestTiming) {\n insight.startTime = requestTiming.startTime\n insight.durationMs = requestTiming.durationMs\n return\n }\n\n const endTime = startTime + (durationMs ?? 0)\n const requestEndTime = insight.startTime + (insight.durationMs ?? 0)\n insight.startTime = Math.min(insight.startTime, startTime)\n insight.durationMs = Math.max(requestEndTime, endTime) - insight.startTime\n }\n\n private notify(insight: RequestInsight): void {\n for (const listener of this.listeners) {\n listener(insight)\n }\n }\n\n private getOrCreateRequest(\n identity: RequestInsightIdentity,\n startTime: number\n ): RequestInsight {\n const requestId = identity.requestId!\n const insightKey = getRequestInsightKey({\n requestId,\n kind: identity.kind,\n })\n let insight = this.requests.get(insightKey)\n\n if (!insight) {\n insight = {\n requestId,\n kind: getRequestInsightKind(identity),\n htmlRequestId: identity.htmlRequestId ?? requestId,\n route: identity.route,\n url: sanitizeUrl(identity.url),\n startTime,\n status: 'pending',\n spans: [],\n fetches: [],\n }\n this.requests.set(insightKey, insight)\n this.requestOrder.push(insightKey)\n this.trim()\n }\n\n insight.htmlRequestId = identity.htmlRequestId ?? insight.htmlRequestId\n insight.route = insight.route ?? identity.route\n insight.url = insight.url ?? sanitizeUrl(identity.url)\n insight.startTime = Math.min(insight.startTime, startTime)\n\n return insight\n }\n\n private recordFetchForInsight(\n insight: RequestInsight,\n fetch: RequestInsightFetch\n ): void {\n if (\n insight.fetches.some(\n (existingFetch) =>\n existingFetch.url === fetch.url &&\n (existingFetch.index !== undefined && fetch.index !== undefined\n ? existingFetch.index === fetch.index\n : existingFetch.startTime === fetch.startTime)\n )\n ) {\n return\n }\n\n insight.fetches.push(sanitizeFetchInsight(fetch))\n }\n\n private trim(): void {\n while (this.requestOrder.length > MAX_REQUEST_INSIGHTS) {\n const insightKey = this.requestOrder.shift()\n if (insightKey) {\n this.requests.delete(insightKey)\n this.requestTimings.delete(insightKey)\n }\n }\n }\n}\n\nexport function recordRequestInsightSpan(span: SpanStoreRecord): void {\n if (\n span.attributes?.['next.span_type'] === CLIENT_COMPONENT_LOADING_SPAN_TYPE\n ) {\n return\n }\n\n getRequestInsightsStore().recordSpan(span)\n}\n\nexport function recordRequestInsightFetch(\n identity: RequestInsightIdentity,\n fetch: RequestInsightFetch\n): void {\n getRequestInsightsStore().recordFetch(identity, fetch)\n}\n\nexport function getRequestInsightsSnapshot(): RequestInsightsSnapshot {\n return getRequestInsightsStore().getSnapshot()\n}\n\nexport function subscribeRequestInsights(\n listener: RequestInsightsListener\n): () => void {\n return getRequestInsightsStore().subscribe(listener)\n}\n\nexport function clearRequestInsightsForTest(): void {\n getRequestInsightsStore().clear()\n}\n\nfunction getRequestInsightsStore(): InMemoryRequestInsightsStore {\n const globalStore = globalThis as typeof globalThis & {\n [REQUEST_INSIGHTS_STORE_KEY]?: InMemoryRequestInsightsStore\n }\n\n return (globalStore[REQUEST_INSIGHTS_STORE_KEY] ??=\n new InMemoryRequestInsightsStore())\n}\n\nfunction getFetchInsight(span: SpanStoreRecord): RequestInsightFetch | null {\n const attributes = span.attributes\n\n if (!attributes || attributes['next.span_type'] !== 'AppRender.fetch') {\n return null\n }\n\n return {\n url: sanitizeUrl(getStringAttribute(attributes['http.url']) ?? span.url),\n method: getStringAttribute(attributes['http.method']),\n statusCode: getNumberAttribute(attributes['http.status_code']),\n startTime: span.startTime ?? span.timestamp,\n durationMs: span.durationMs,\n cacheStatus: getStringAttribute(attributes['next.fetch.cache_status']),\n cacheReason: getStringAttribute(attributes['next.fetch.cache_reason']),\n index: getNumberAttribute(attributes['next.fetch.idx']),\n }\n}\n\nfunction sanitizeFetchInsight(fetch: RequestInsightFetch): RequestInsightFetch {\n return {\n ...fetch,\n url: sanitizeUrl(fetch.url),\n }\n}\n\nfunction getCurrentTimestamp(): number {\n return performance.timeOrigin + performance.now()\n}\n\nfunction sanitizeSpanAttributes(\n attributes: SpanStoreRecord['attributes']\n): SpanStoreRecord['attributes'] {\n if (!attributes) {\n return undefined\n }\n\n const sanitized: NonNullable = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (!SAFE_SPAN_ATTRIBUTE_KEYS.has(key)) {\n continue\n }\n\n sanitized[key] = key === 'http.url' ? sanitizeUrlAttribute(value) : value\n }\n\n return Object.keys(sanitized).length > 0 ? sanitized : undefined\n}\n\nfunction sanitizeSpanEvents(\n events: SpanStoreRecord['events']\n): SpanStoreRecord['events'] {\n return events?.map((event) => ({\n ...event,\n attributes: sanitizeSpanAttributes(event.attributes),\n }))\n}\n\nfunction sanitizeSpanLinks(\n links: SpanStoreRecord['links']\n): SpanStoreRecord['links'] {\n return links?.map((link) => ({\n ...link,\n attributes: sanitizeSpanAttributes(link.attributes),\n }))\n}\n\nfunction sanitizeUrlAttribute(value: AttributeValue): AttributeValue {\n return typeof value === 'string' ? (sanitizeUrl(value) ?? '') : value\n}\n\nfunction sanitizeUrl(value: string | undefined): string | undefined {\n if (!value) {\n return value\n }\n\n const isRelativeUrl = value.startsWith('/')\n\n try {\n const url = isRelativeUrl ? new URL(value, 'http://n') : new URL(value)\n\n url.username = ''\n url.password = ''\n\n for (const name of Array.from(url.searchParams.keys())) {\n if (SENSITIVE_PARAM_NAME_RE.test(name)) {\n url.searchParams.set(name, REDACTED_VALUE)\n }\n }\n\n return isRelativeUrl ? `${url.pathname}${url.search}${url.hash}` : url.href\n } catch {\n return value\n }\n}\n\nfunction getStringAttribute(value: AttributeValue | undefined) {\n return typeof value === 'string' ? value : undefined\n}\n\nfunction getNumberAttribute(value: AttributeValue | undefined) {\n return typeof value === 'number' ? value : undefined\n}\n"],"names":["clearRequestInsightsForTest","getRequestInsightsSnapshot","isRequestInsightsEnabled","recordRequestInsightFetch","recordRequestInsightSpan","subscribeRequestInsights","MAX_REQUEST_INSIGHTS","REQUEST_INSIGHTS_STORE_KEY","Symbol","for","CLIENT_COMPONENT_LOADING_SPAN_TYPE","REDACTED_VALUE","SAFE_SPAN_ATTRIBUTE_KEYS","Set","SENSITIVE_PARAM_NAME_RE","InMemoryRequestInsightsStore","recordSpan","span","requestId","insight","getOrCreateRequest","kind","requestInsightKind","htmlRequestId","route","url","startTime","timestamp","spanStartTime","sanitizeUrl","updateTiming","durationMs","attributes","status","spans","push","name","traceId","spanId","parentSpanId","sanitizeSpanAttributes","links","sanitizeSpanLinks","events","sanitizeSpanEvents","error","fetch","getFetchInsight","recordFetchForInsight","notify","recordFetch","identity","fetchStartTime","getCurrentTimestamp","sanitizeFetchInsight","getSnapshot","requests","requestOrder","map","insightKey","get","filter","request","undefined","subscribe","listener","listeners","add","delete","clear","requestTimings","length","isRequestSpan","getRequestInsightKey","requestTiming","set","endTime","requestEndTime","Math","min","max","getRequestInsightKind","fetches","trim","some","existingFetch","index","shift","Map","getRequestInsightsStore","globalStore","globalThis","getStringAttribute","method","statusCode","getNumberAttribute","cacheStatus","cacheReason","performance","timeOrigin","now","sanitized","key","value","Object","entries","has","sanitizeUrlAttribute","keys","event","link","isRelativeUrl","startsWith","URL","username","password","Array","from","searchParams","test","pathname","search","hash","href"],"mappings":";;;;;;;;;;;;;;;;;;;IAiRgBA,2BAA2B;eAA3BA;;IAVAC,0BAA0B;eAA1BA;;IA3PPC,wBAAwB;eAAxBA,mCAAwB;;IAoPjBC,yBAAyB;eAAzBA;;IAVAC,wBAAwB;eAAxBA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,CAAC5F,IAAI6F,YAAY,CAACV,IAAI,IAAK;YACtD,IAAI9F,wBAAwByG,IAAI,CAACnF,OAAO;gBACtCX,IAAI6F,YAAY,CAAC3C,GAAG,CAACvC,MAAMzB;YAC7B;QACF;QAEA,OAAOoG,gBAAgB,GAAGtF,IAAI+F,QAAQ,GAAG/F,IAAIgG,MAAM,GAAGhG,IAAIiG,IAAI,EAAE,GAAGjG,IAAIkG,IAAI;IAC7E,EAAE,OAAM;QACN,OAAOpB;IACT;AACF;AAEA,SAASX,mBAAmBW,KAAiC;IAC3D,OAAO,OAAOA,UAAU,WAAWA,QAAQxC;AAC7C;AAEA,SAASgC,mBAAmBQ,KAAiC;IAC3D,OAAO,OAAOA,UAAU,WAAWA,QAAQxC;AAC7C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/span-store.d.ts b/e-commerce/node_modules/next/dist/server/lib/trace/span-store.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..13ecdecc8f52fcda541d56c25fe5f389a6aa197c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/span-store.d.ts @@ -0,0 +1,41 @@ +import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'; +import type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'; +export type SpanStoreAttributes = Record; +export type SpanStoreLink = { + traceId: string; + spanId: string; + attributes?: SpanStoreAttributes; +}; +export type SpanStoreEvent = { + name: string; + timestamp: number; + attributes?: SpanStoreAttributes; +}; +export type SpanStoreRecord = { + name: string; + timestamp: number; + startTime?: number; + durationMs?: number; + status?: 'ok' | 'error'; + traceId?: string; + spanId?: string; + parentSpanId?: string; + requestId?: string; + requestInsightKind?: RequestInsightKind; + htmlRequestId?: string; + route?: string; + url?: string; + attributes?: SpanStoreAttributes; + links?: SpanStoreLink[]; + events?: SpanStoreEvent[]; + error?: { + type?: string; + message?: string; + }; +}; +type SpanRecorderForTest = (span: SpanStoreRecord) => void; +export declare function recordSpan(record: Omit): void; +export declare function setSpanRecorderForTest(recorder: SpanRecorderForTest | undefined): void; +export declare function isLocalSpanRecordingEnabled(): boolean; +export declare function isRequestInsightsEnabled(): boolean; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/span-store.js b/e-commerce/node_modules/next/dist/server/lib/trace/span-store.js new file mode 100644 index 0000000000000000000000000000000000000000..4b401cc474eebc64bc5cbe03a7065cda9dbc660c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/span-store.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + isLocalSpanRecordingEnabled: null, + isRequestInsightsEnabled: null, + recordSpan: null, + setSpanRecorderForTest: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + isLocalSpanRecordingEnabled: function() { + return isLocalSpanRecordingEnabled; + }, + isRequestInsightsEnabled: function() { + return isRequestInsightsEnabled; + }, + recordSpan: function() { + return recordSpan; + }, + setSpanRecorderForTest: function() { + return setSpanRecorderForTest; + } +}); +let spanRecorderForTest; +function recordSpan(record) { + if (!isLocalSpanRecordingEnabled()) { + return; + } + const spanRecord = { + timestamp: getCurrentTimestamp(), + ...record + }; + spanRecorderForTest == null ? void 0 : spanRecorderForTest(spanRecord); + if (isRequestInsightsEnabled() && spanRecord.requestId) { + const { recordRequestInsightSpan } = require('./request-insights'); + recordRequestInsightSpan(spanRecord); + } +} +function setSpanRecorderForTest(recorder) { + spanRecorderForTest = recorder; +} +function isLocalSpanRecordingEnabled() { + if (!process.env.__NEXT_DEV_SERVER) { + return false; + } + return spanRecorderForTest !== undefined || isRequestInsightsEnabled(); +} +function isRequestInsightsEnabled() { + if (!process.env.__NEXT_DEV_SERVER) { + return false; + } + const value = process.env.__NEXT_REQUEST_INSIGHTS; + return isEnabledEnvValue(value); +} +function isEnabledEnvValue(value) { + return value === '1' || value === 'true' || value === true; +} +function getCurrentTimestamp() { + return performance.timeOrigin + performance.now(); +} + +//# sourceMappingURL=span-store.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/span-store.js.map b/e-commerce/node_modules/next/dist/server/lib/trace/span-store.js.map new file mode 100644 index 0000000000000000000000000000000000000000..24cd49d2973647878a4ec4e22c660dad61580425 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/span-store.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/lib/trace/span-store.ts"],"sourcesContent":["import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\nimport type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'\n\nexport type SpanStoreAttributes = Record\n\nexport type SpanStoreLink = {\n traceId: string\n spanId: string\n attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreEvent = {\n name: string\n timestamp: number\n attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreRecord = {\n name: string\n timestamp: number\n startTime?: number\n durationMs?: number\n status?: 'ok' | 'error'\n traceId?: string\n spanId?: string\n parentSpanId?: string\n requestId?: string\n requestInsightKind?: RequestInsightKind\n htmlRequestId?: string\n route?: string\n url?: string\n attributes?: SpanStoreAttributes\n links?: SpanStoreLink[]\n events?: SpanStoreEvent[]\n error?: {\n type?: string\n message?: string\n }\n}\n\ntype SpanRecorderForTest = (span: SpanStoreRecord) => void\n\nlet spanRecorderForTest: SpanRecorderForTest | undefined\n\nexport function recordSpan(record: Omit): void {\n if (!isLocalSpanRecordingEnabled()) {\n return\n }\n\n const spanRecord: SpanStoreRecord = {\n timestamp: getCurrentTimestamp(),\n ...record,\n }\n\n spanRecorderForTest?.(spanRecord)\n\n if (isRequestInsightsEnabled() && spanRecord.requestId) {\n const { recordRequestInsightSpan } =\n require('./request-insights') as typeof import('./request-insights')\n recordRequestInsightSpan(spanRecord)\n }\n}\n\nexport function setSpanRecorderForTest(\n recorder: SpanRecorderForTest | undefined\n): void {\n spanRecorderForTest = recorder\n}\n\nexport function isLocalSpanRecordingEnabled(): boolean {\n if (!process.env.__NEXT_DEV_SERVER) {\n return false\n }\n\n return spanRecorderForTest !== undefined || isRequestInsightsEnabled()\n}\n\nexport function isRequestInsightsEnabled(): boolean {\n if (!process.env.__NEXT_DEV_SERVER) {\n return false\n }\n\n const value = process.env.__NEXT_REQUEST_INSIGHTS\n return isEnabledEnvValue(value)\n}\n\nfunction isEnabledEnvValue(value: string | undefined): boolean {\n return value === '1' || value === 'true' || (value as unknown) === true\n}\n\nfunction getCurrentTimestamp(): number {\n return performance.timeOrigin + performance.now()\n}\n"],"names":["isLocalSpanRecordingEnabled","isRequestInsightsEnabled","recordSpan","setSpanRecorderForTest","spanRecorderForTest","record","spanRecord","timestamp","getCurrentTimestamp","requestId","recordRequestInsightSpan","require","recorder","process","env","__NEXT_DEV_SERVER","undefined","value","__NEXT_REQUEST_INSIGHTS","isEnabledEnvValue","performance","timeOrigin","now"],"mappings":";;;;;;;;;;;;;;;;;IAqEgBA,2BAA2B;eAA3BA;;IAQAC,wBAAwB;eAAxBA;;IAjCAC,UAAU;eAAVA;;IAmBAC,sBAAsB;eAAtBA;;;AArBhB,IAAIC;AAEG,SAASF,WAAWG,MAA0C;IACnE,IAAI,CAACL,+BAA+B;QAClC;IACF;IAEA,MAAMM,aAA8B;QAClCC,WAAWC;QACX,GAAGH,MAAM;IACX;IAEAD,uCAAAA,oBAAsBE;IAEtB,IAAIL,8BAA8BK,WAAWG,SAAS,EAAE;QACtD,MAAM,EAAEC,wBAAwB,EAAE,GAChCC,QAAQ;QACVD,yBAAyBJ;IAC3B;AACF;AAEO,SAASH,uBACdS,QAAyC;IAEzCR,sBAAsBQ;AACxB;AAEO,SAASZ;IACd,IAAI,CAACa,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAO;IACT;IAEA,OAAOX,wBAAwBY,aAAaf;AAC9C;AAEO,SAASA;IACd,IAAI,CAACY,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAO;IACT;IAEA,MAAME,QAAQJ,QAAQC,GAAG,CAACI,uBAAuB;IACjD,OAAOC,kBAAkBF;AAC3B;AAEA,SAASE,kBAAkBF,KAAyB;IAClD,OAAOA,UAAU,OAAOA,UAAU,UAAU,AAACA,UAAsB;AACrE;AAEA,SAAST;IACP,OAAOY,YAAYC,UAAU,GAAGD,YAAYE,GAAG;AACjD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/tracer.d.ts b/e-commerce/node_modules/next/dist/server/lib/trace/tracer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fc6d5dc4a005df1e3a9ff9e254549c9701d07c6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/tracer.d.ts @@ -0,0 +1,126 @@ +import type { FetchEventResult } from '../../web/types'; +import type { SpanTypes } from './constants'; +import type { ContextAPI, Span, SpanOptions, AttributeValue, TextMapGetter } from 'next/dist/compiled/@opentelemetry/api'; +declare const SpanStatusCode: typeof import("next/dist/compiled/@opentelemetry/api").SpanStatusCode, SpanKind: typeof import("next/dist/compiled/@opentelemetry/api").SpanKind; +export declare class BubbledError extends Error { + readonly bubble?: boolean | undefined; + readonly result?: FetchEventResult | undefined; + constructor(bubble?: boolean | undefined, result?: FetchEventResult | undefined); +} +export declare function isBubbledError(error: unknown): error is BubbledError; +type TracerSpanOptions = Omit & { + endTime?: Parameters[0]; + parentSpan?: Span; + spanName?: string; + attributes?: Partial>; + hideSpan?: boolean; +}; +interface NextTracer { + getContext(): ContextAPI; + /** + * Instruments a function by automatically creating a span activated on its + * scope. + * + * The span will automatically be finished when one of these conditions is + * met: + * + * * The function returns a promise, in which case the span will finish when + * the promise is resolved or rejected. + * * The function takes a callback as its second parameter, in which case the + * span will finish when that callback is called. + * * The function doesn't accept a callback and doesn't return a promise, in + * which case the span will finish at the end of the function execution. + * + */ + trace(type: SpanTypes, fn: (span?: Span, done?: (error?: Error) => any) => Promise): Promise; + trace(type: SpanTypes, fn: (span?: Span, done?: (error?: Error) => any) => T): T; + trace(type: SpanTypes, options: TracerSpanOptions, fn: (span?: Span, done?: (error?: Error) => any) => Promise): Promise; + trace(type: SpanTypes, options: TracerSpanOptions, fn: (span?: Span, done?: (error?: Error) => any) => T): T; + /** + * Wrap a function to automatically create a span activated on its + * scope when it's called. + * + * The span will automatically be finished when one of these conditions is + * met: + * + * * The function returns a promise, in which case the span will finish when + * the promise is resolved or rejected. + * * The function takes a callback as its last parameter, in which case the + * span will finish when that callback is called. + * * The function doesn't accept a callback and doesn't return a promise, in + * which case the span will finish at the end of the function execution. + */ + wrap) => any>(type: SpanTypes, fn: T): T; + wrap) => any>(type: SpanTypes, options: TracerSpanOptions, fn: T): T; + wrap) => any>(type: SpanTypes, options: (...args: any[]) => TracerSpanOptions, fn: T): T; + /** + * Starts and returns a new Span representing a logical unit of work. + * + * This method do NOT modify the current Context by default. In result, any inner span will not + * automatically set its parent context to the span created by this method unless manually activate + * context via `tracer.getContext().with`. `trace`, or `wrap` is generally recommended as it gracefully + * handles context activation. (ref: https://github.com/open-telemetry/opentelemetry-js/issues/1923) + */ + startSpan(type: SpanTypes): Span; + startSpan(type: SpanTypes, options: TracerSpanOptions): Span; + /** + * Returns currently activated span if current context is in the scope of the span. + * Returns undefined otherwise. + */ + getActiveScopeSpan(): Span | undefined; + /** + * Returns trace propagation data for the currently active context. The format is equal to data provided + * through the OpenTelemetry propagator API. + */ + getTracePropagationData(): ClientTraceDataEntry[]; + /** + * Executes a function with the given span set as the active span in the context. + * This allows child spans created within the function to automatically parent to this span. + */ + withSpan(span: Span, fn: () => T): T; +} +type NextAttributeNames = 'next.route' | 'next.page' | 'next.rsc' | 'next.segment' | 'next.span_category' | 'next.span_name' | 'next.span_type' | 'next.clientComponentLoadCount'; +type OTELAttributeNames = `http.${string}` | `net.${string}`; +type AttributeNames = NextAttributeNames | OTELAttributeNames; +export interface ClientTraceDataEntry { + key: string; + value: string; +} +declare class NextTracerImpl implements NextTracer { + /** + * Returns an instance to the trace with configured name. + * Since wrap / trace can be defined in any place prior to actual trace subscriber initialization, + * This should be lazily evaluated. + */ + private getTracerInstance; + private isOpenTelemetryEnabled; + getContext(): ContextAPI; + getTracePropagationData(): ClientTraceDataEntry[]; + getActiveScopeSpan(): Span | undefined; + /** + * Run `fn` with the active span cleared, so spans created inside become new + * roots (or parent to incoming propagated context). Used for in-process + * Node.js middleware so its span is a sibling of the request span, matching + * edge middleware which runs in a detached sandbox. + */ + runWithDetachedContext(fn: () => T): T; + withPropagatedContext(carrier: C, fn: () => T, getter?: TextMapGetter, force?: boolean): T; + trace(type: SpanTypes, fn: (span?: Span, done?: (error?: Error) => any) => Promise): Promise; + trace(type: SpanTypes, fn: (span?: Span, done?: (error?: Error) => any) => T): T; + trace(type: SpanTypes, options: TracerSpanOptions, fn: (span?: Span, done?: (error?: Error) => any) => Promise): Promise; + trace(type: SpanTypes, options: TracerSpanOptions, fn: (span?: Span, done?: (error?: Error) => any) => T): T; + private runWithActiveSpan; + private createLocalRecordingSpan; + wrap) => any>(type: SpanTypes, fn: T): T; + wrap) => any>(type: SpanTypes, options: TracerSpanOptions, fn: T): T; + wrap) => any>(type: SpanTypes, options: (...args: any[]) => TracerSpanOptions, fn: T): T; + startSpan(type: SpanTypes): Span; + startSpan(type: SpanTypes, options: TracerSpanOptions): Span; + private getSpanContext; + getRootSpanAttributes(): Map | undefined; + setRootSpanAttribute(key: AttributeNames, value: AttributeValue): void; + withSpan(span: Span, fn: () => T): T; +} +declare const getTracer: () => NextTracerImpl; +export { getTracer, SpanStatusCode, SpanKind }; +export type { NextTracer, Span, SpanOptions, ContextAPI, TracerSpanOptions }; diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/tracer.js b/e-commerce/node_modules/next/dist/server/lib/trace/tracer.js new file mode 100644 index 0000000000000000000000000000000000000000..73c7440deacedff1697af3c8d47498b52632a685 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/tracer.js @@ -0,0 +1,392 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + BubbledError: null, + SpanKind: null, + SpanStatusCode: null, + getTracer: null, + isBubbledError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + BubbledError: function() { + return BubbledError; + }, + SpanKind: function() { + return SpanKind; + }, + SpanStatusCode: function() { + return SpanStatusCode; + }, + getTracer: function() { + return getTracer; + }, + isBubbledError: function() { + return isBubbledError; + } +}); +const _constants = require("./constants"); +const _isthenable = require("../../../shared/lib/is-thenable"); +const NEXT_OTEL_PERFORMANCE_PREFIX = process.env.NEXT_OTEL_PERFORMANCE_PREFIX; +const LOCAL_SPAN_RECORDER_KEY = Symbol.for('@next/local-span-recorder'); +let api; +function getLocalSpanRecorder() { + if (process.env.__NEXT_DEV_SERVER) { + return globalThis[LOCAL_SPAN_RECORDER_KEY]; + } else { + return undefined; + } +} +// we want to allow users to use their own version of @opentelemetry/api if they +// want to, so we try to require it first, and if it fails we fall back to the +// version that is bundled with Next.js +// this is because @opentelemetry/api has to be synced with the version of +// @opentelemetry/tracing that is used, and we don't want to force users to use +// the version that is bundled with Next.js. +// the API is ~stable, so this should be fine +if (process.env.NEXT_RUNTIME === 'edge') { + api = require('@opentelemetry/api'); +} else { + try { + api = require('@opentelemetry/api'); + } catch (err) { + api = require('next/dist/compiled/@opentelemetry/api'); + } +} +const { context, propagation, trace, SpanStatusCode, SpanKind, ROOT_CONTEXT } = api; +class BubbledError extends Error { + constructor(bubble, result){ + super(), this.bubble = bubble, this.result = result; + } +} +function isBubbledError(error) { + if (typeof error !== 'object' || error === null) return false; + return error instanceof BubbledError; +} +const closeSpanWithError = (span, error, endTime)=>{ + if (isBubbledError(error) && error.bubble) { + span.setAttribute('next.bubble', true); + } else { + if (error) { + span.recordException(error); + span.setAttribute('error.type', error.name); + } + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error == null ? void 0 : error.message + }); + } + span.end(endTime); +}; +/** we use this map to propagate attributes from nested spans to the top span */ const rootSpanAttributesStore = new Map(); +const rootSpanIdKey = api.createContextKey('next.rootSpanId'); +let lastSpanId = 0; +const getSpanId = ()=>lastSpanId++; +const clientTraceDataSetter = { + set (carrier, key, value) { + carrier.push({ + key, + value + }); + } +}; +class NextTracerImpl { + /** + * Returns an instance to the trace with configured name. + * Since wrap / trace can be defined in any place prior to actual trace subscriber initialization, + * This should be lazily evaluated. + */ getTracerInstance() { + return trace.getTracer('next.js', "16.4.0"); + } + isOpenTelemetryEnabled() { + var _tracerProvider_getDelegate_constructor, _tracerProvider_getDelegate; + const activeSpan = trace.getSpan(context.active()); + if (activeSpan == null ? void 0 : activeSpan.isRecording()) { + return true; + } + const tracerProvider = trace.getTracerProvider(); + if (!('getDelegate' in tracerProvider)) { + return true; + } + return (tracerProvider.getDelegate == null ? void 0 : (_tracerProvider_getDelegate = tracerProvider.getDelegate.call(tracerProvider)) == null ? void 0 : (_tracerProvider_getDelegate_constructor = _tracerProvider_getDelegate.constructor) == null ? void 0 : _tracerProvider_getDelegate_constructor.name) !== 'NoopTracerProvider'; + } + getContext() { + return context; + } + getTracePropagationData() { + const activeContext = context.active(); + const entries = []; + propagation.inject(activeContext, entries, clientTraceDataSetter); + return entries; + } + getActiveScopeSpan() { + const localSpanRecorder = getLocalSpanRecorder(); + const activeLocalSpan = localSpanRecorder == null ? void 0 : localSpanRecorder.getActiveLocalSpan(); + if (activeLocalSpan && (localSpanRecorder == null ? void 0 : localSpanRecorder.isOpenTelemetryIsolatedSpan(activeLocalSpan))) { + return activeLocalSpan; + } + const activeSpan = trace.getSpan(context.active()); + if (activeSpan || !process.env.__NEXT_DEV_SERVER) { + return activeSpan; + } + return activeLocalSpan; + } + /** + * Run `fn` with the active span cleared, so spans created inside become new + * roots (or parent to incoming propagated context). Used for in-process + * Node.js middleware so its span is a sibling of the request span, matching + * edge middleware which runs in a detached sandbox. + */ runWithDetachedContext(fn) { + if (!NEXT_OTEL_PERFORMANCE_PREFIX && !this.isOpenTelemetryEnabled()) { + return fn(); + } + return context.with(ROOT_CONTEXT, fn); + } + withPropagatedContext(carrier, fn, getter, force = false) { + const activeContext = context.active(); + if (!NEXT_OTEL_PERFORMANCE_PREFIX && !this.isOpenTelemetryEnabled() && !trace.getSpanContext(activeContext)) { + return fn(); + } + if (force) { + const remoteContext = propagation.extract(ROOT_CONTEXT, carrier, getter); + if (trace.getSpanContext(remoteContext)) { + return context.with(remoteContext, fn); + } + // Preserve the current active span while still merging any extracted + // baggage/context values from the carrier. + const mergedContext = propagation.extract(activeContext, carrier, getter); + return context.with(mergedContext, fn); + } + if (trace.getSpanContext(activeContext)) { + // Active span is already set, too late to propagate. + return fn(); + } + const remoteContext = propagation.extract(activeContext, carrier, getter); + return context.with(remoteContext, fn); + } + trace(...args) { + const [type, fnOrOptions, fnOrEmpty] = args; + const tracingEnabled = Boolean(NEXT_OTEL_PERFORMANCE_PREFIX) || this.isOpenTelemetryEnabled(); + const localSpanRecorder = getLocalSpanRecorder(); + const localSpanRecordingEnabled = (localSpanRecorder == null ? void 0 : localSpanRecorder.isLocalSpanRecordingEnabled()) ?? false; + if (!tracingEnabled && !localSpanRecordingEnabled) { + return typeof fnOrOptions === 'function' ? fnOrOptions() : fnOrEmpty(); + } + // coerce options form overload + const { fn, options } = typeof fnOrOptions === 'function' ? { + fn: fnOrOptions, + options: {} + } : { + fn: fnOrEmpty, + options: { + ...fnOrOptions + } + }; + const spanName = options.spanName ?? type; + const parentSpan = options.parentSpan ?? this.getActiveScopeSpan(); + const isolatedParentSpan = parentSpan && (localSpanRecorder == null ? void 0 : localSpanRecorder.isOpenTelemetryIsolatedSpan(parentSpan)) ? parentSpan : undefined; + const shouldDelegateSpan = !isolatedParentSpan && (_constants.NextVanillaSpanAllowlist.has(type) || process.env.NEXT_OTEL_VERBOSE === '1'); + const shouldTraceSpan = shouldDelegateSpan || ((localSpanRecorder == null ? void 0 : localSpanRecorder.isRequestInsightsEnabled()) ?? false); + if (!shouldTraceSpan || options.hideSpan) { + return fn(); + } + // Trying to get active scoped span to assign parent. If option specifies parent span manually, will try to use it. + let spanContext = isolatedParentSpan ? context.active() : this.getSpanContext(parentSpan); + if (!spanContext) { + spanContext = (context == null ? void 0 : context.active()) ?? ROOT_CONTEXT; + } + // Check if there's already a root span in the store for this trace + // We are intentionally not checking whether there is an active context + // from outside of nextjs to ensure that we can provide the same level + // of telemetry when using a custom server + const existingRootSpanId = spanContext.getValue(rootSpanIdKey); + const isRootSpan = typeof existingRootSpanId !== 'number' || !rootSpanAttributesStore.has(existingRootSpanId); + const spanId = getSpanId(); + options.attributes = { + 'next.span_category': 'nextjs', + 'next.span_name': spanName, + 'next.span_type': type, + ...options.attributes + }; + return context.with(spanContext.setValue(rootSpanIdKey, spanId), ()=>this.runWithActiveSpan(spanName, options, spanContext, tracingEnabled && shouldDelegateSpan, localSpanRecordingEnabled, isolatedParentSpan, (span)=>{ + let startTime; + if (NEXT_OTEL_PERFORMANCE_PREFIX && type && _constants.LogSpanAllowList.has(type)) { + startTime = 'performance' in globalThis && 'measure' in performance ? globalThis.performance.now() : undefined; + } + let cleanedUp = false; + const onCleanup = ()=>{ + if (cleanedUp) return; + cleanedUp = true; + rootSpanAttributesStore.delete(spanId); + if (startTime) { + performance.measure(`${NEXT_OTEL_PERFORMANCE_PREFIX}:next-${(type.split('.').pop() || '').replace(/[A-Z]/g, (match)=>'-' + match.toLowerCase())}`, { + start: startTime, + end: performance.now() + }); + } + }; + if (isRootSpan) { + rootSpanAttributesStore.set(spanId, new Map(Object.entries(options.attributes ?? {}))); + } + if (fn.length > 1) { + try { + return fn(span, (err)=>{ + if (err) { + closeSpanWithError(span, err, options.endTime); + } else { + span.end(options.endTime); + } + }); + } catch (err) { + closeSpanWithError(span, err, options.endTime); + throw err; + } finally{ + onCleanup(); + } + } + try { + const result = fn(span); + if ((0, _isthenable.isThenable)(result)) { + // If there's error make sure it throws + return result.then((res)=>{ + span.end(options.endTime); + // Need to pass down the promise result, + // it could be react stream response with error { error, stream } + return res; + }).catch((err)=>{ + closeSpanWithError(span, err, options.endTime); + throw err; + }).finally(onCleanup); + } else { + span.end(options.endTime); + onCleanup(); + } + return result; + } catch (err) { + closeSpanWithError(span, err, options.endTime); + onCleanup(); + throw err; + } + })); + } + runWithActiveSpan(spanName, options, parentContext, tracingEnabled, localSpanRecordingEnabled, isolatedParentSpan, fn) { + if (tracingEnabled) { + return this.getTracerInstance().startActiveSpan(spanName, options, (span)=>fn(localSpanRecordingEnabled ? this.createLocalRecordingSpan(spanName, options, parentContext, span, isolatedParentSpan) : span)); + } + const span = this.createLocalRecordingSpan(spanName, options, parentContext, undefined, isolatedParentSpan); + const localSpanRecorder = getLocalSpanRecorder(); + return localSpanRecorder.withLocalSpan(span, ()=>localSpanRecorder.isOpenTelemetryIsolatedSpan(span) ? fn(span) : context.with(trace.setSpan(context.active(), span), fn, undefined, span)); + } + createLocalRecordingSpan(name, options, parentContext, delegateSpan, isolatedParentSpan) { + const parentSpanContext = (isolatedParentSpan == null ? void 0 : isolatedParentSpan.spanContext()) ?? trace.getSpanContext(parentContext); + const delegateSpanContext = delegateSpan == null ? void 0 : delegateSpan.spanContext(); + return getLocalSpanRecorder().createLocalSpan({ + name, + attributes: options.attributes, + links: options.links, + startTime: options.startTime, + delegateSpan, + traceId: (delegateSpanContext == null ? void 0 : delegateSpanContext.traceId) ?? (parentSpanContext == null ? void 0 : parentSpanContext.traceId), + spanId: delegateSpanContext == null ? void 0 : delegateSpanContext.spanId, + parentSpanId: parentSpanContext == null ? void 0 : parentSpanContext.spanId, + isolateOpenTelemetry: isolatedParentSpan !== undefined + }); + } + wrap(...args) { + const tracer = this; + const [name, options, fn] = args.length === 3 ? args : [ + args[0], + {}, + args[1] + ]; + if (!_constants.NextVanillaSpanAllowlist.has(name) && process.env.NEXT_OTEL_VERBOSE !== '1' && !process.env.__NEXT_DEV_SERVER) { + return fn; + } + return function() { + let optionsObj = options; + if (typeof optionsObj === 'function' && typeof fn === 'function') { + optionsObj = optionsObj.apply(this, arguments); + } + const lastArgId = arguments.length - 1; + const cb = arguments[lastArgId]; + if (typeof cb === 'function') { + const scopeBoundCb = tracer.getContext().bind(context.active(), cb); + return tracer.trace(name, optionsObj, (_span, done)=>{ + arguments[lastArgId] = function(err) { + done == null ? void 0 : done(err); + return scopeBoundCb.apply(this, arguments); + }; + return fn.apply(this, arguments); + }); + } else { + return tracer.trace(name, optionsObj, ()=>fn.apply(this, arguments)); + } + }; + } + startSpan(...args) { + const [type, passedOptions] = args; + const options = passedOptions ? { + ...passedOptions, + attributes: { + 'next.span_category': 'nextjs', + ...passedOptions.attributes + } + } : { + attributes: { + 'next.span_category': 'nextjs' + } + }; + const localSpanRecorder = getLocalSpanRecorder(); + const parentSpan = options.parentSpan ?? this.getActiveScopeSpan(); + const isolatedParentSpan = parentSpan && (localSpanRecorder == null ? void 0 : localSpanRecorder.isOpenTelemetryIsolatedSpan(parentSpan)) ? parentSpan : undefined; + const parentContext = (isolatedParentSpan ? undefined : this.getSpanContext(parentSpan)) ?? context.active(); + const localSpanRecordingEnabled = (localSpanRecorder == null ? void 0 : localSpanRecorder.isLocalSpanRecordingEnabled()) ?? false; + if (!localSpanRecordingEnabled) { + return this.getTracerInstance().startSpan(type, options, parentContext); + } + const delegateSpan = !isolatedParentSpan && this.isOpenTelemetryEnabled() ? this.getTracerInstance().startSpan(type, options, parentContext) : undefined; + return this.createLocalRecordingSpan(type, options, parentContext, delegateSpan, isolatedParentSpan); + } + getSpanContext(parentSpan) { + const spanContext = parentSpan ? trace.setSpan(context.active(), parentSpan) : undefined; + return spanContext; + } + getRootSpanAttributes() { + const spanId = context.active().getValue(rootSpanIdKey); + return rootSpanAttributesStore.get(spanId); + } + setRootSpanAttribute(key, value) { + const spanId = context.active().getValue(rootSpanIdKey); + const attributes = rootSpanAttributesStore.get(spanId); + if (attributes && !attributes.has(key)) { + attributes.set(key, value); + } + if (process.env.__NEXT_DEV_SERVER) { + var _getLocalSpanRecorder; + const localSpan = (_getLocalSpanRecorder = getLocalSpanRecorder()) == null ? void 0 : _getLocalSpanRecorder.getActiveLocalSpan(); + if (localSpan) { + localSpan.setAttribute(key, value); + } + } + } + withSpan(span, fn) { + const recorder = getLocalSpanRecorder(); + if (recorder == null ? void 0 : recorder.isLocalRecordingSpan(span)) { + return recorder.withLocalSpan(span, ()=>recorder.isOpenTelemetryIsolatedSpan(span) ? fn() : context.with(trace.setSpan(context.active(), span), fn)); + } + return context.with(trace.setSpan(context.active(), span), fn); + } +} +const getTracer = (()=>{ + const tracer = new NextTracerImpl(); + return ()=>tracer; +})(); + +//# sourceMappingURL=tracer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/tracer.js.map b/e-commerce/node_modules/next/dist/server/lib/trace/tracer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..222da3d5e4679b9236ab63c56c7fbd9b4cb91de2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/tracer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/lib/trace/tracer.ts"],"sourcesContent":["import type { FetchEventResult } from '../../web/types'\nimport type { TextMapSetter } from '@opentelemetry/api'\nimport type { SpanTypes } from './constants'\nimport type { LocalSpanRecorder } from './local-span-recorder'\nimport { LogSpanAllowList, NextVanillaSpanAllowlist } from './constants'\n\nimport type {\n Context,\n ContextAPI,\n Span,\n SpanOptions,\n Tracer,\n AttributeValue,\n TextMapGetter,\n} from 'next/dist/compiled/@opentelemetry/api'\nimport { isThenable } from '../../../shared/lib/is-thenable'\n\nconst NEXT_OTEL_PERFORMANCE_PREFIX = process.env.NEXT_OTEL_PERFORMANCE_PREFIX\nconst LOCAL_SPAN_RECORDER_KEY = Symbol.for('@next/local-span-recorder')\n\ntype GlobalWithLocalSpanRecorder = typeof globalThis & {\n [LOCAL_SPAN_RECORDER_KEY]?: LocalSpanRecorder\n}\n\nlet api: typeof import('next/dist/compiled/@opentelemetry/api')\n\nfunction getLocalSpanRecorder() {\n if (process.env.__NEXT_DEV_SERVER) {\n return (globalThis as GlobalWithLocalSpanRecorder)[LOCAL_SPAN_RECORDER_KEY]\n } else {\n return undefined\n }\n}\n\n// we want to allow users to use their own version of @opentelemetry/api if they\n// want to, so we try to require it first, and if it fails we fall back to the\n// version that is bundled with Next.js\n// this is because @opentelemetry/api has to be synced with the version of\n// @opentelemetry/tracing that is used, and we don't want to force users to use\n// the version that is bundled with Next.js.\n// the API is ~stable, so this should be fine\nif (process.env.NEXT_RUNTIME === 'edge') {\n api = require('@opentelemetry/api') as typeof import('@opentelemetry/api')\n} else {\n try {\n api = require('@opentelemetry/api') as typeof import('@opentelemetry/api')\n } catch (err) {\n api =\n require('next/dist/compiled/@opentelemetry/api') as typeof import('next/dist/compiled/@opentelemetry/api')\n }\n}\n\nconst { context, propagation, trace, SpanStatusCode, SpanKind, ROOT_CONTEXT } =\n api\n\nexport class BubbledError extends Error {\n constructor(\n public readonly bubble?: boolean,\n public readonly result?: FetchEventResult\n ) {\n super()\n }\n}\n\nexport function isBubbledError(error: unknown): error is BubbledError {\n if (typeof error !== 'object' || error === null) return false\n return error instanceof BubbledError\n}\n\nconst closeSpanWithError = (\n span: Span,\n error?: Error,\n endTime?: Parameters[0]\n) => {\n if (isBubbledError(error) && error.bubble) {\n span.setAttribute('next.bubble', true)\n } else {\n if (error) {\n span.recordException(error)\n span.setAttribute('error.type', error.name)\n }\n span.setStatus({ code: SpanStatusCode.ERROR, message: error?.message })\n }\n span.end(endTime)\n}\n\ntype TracerSpanOptions = Omit & {\n endTime?: Parameters[0]\n parentSpan?: Span\n spanName?: string\n attributes?: Partial>\n hideSpan?: boolean\n}\n\ninterface NextTracer {\n getContext(): ContextAPI\n\n /**\n * Instruments a function by automatically creating a span activated on its\n * scope.\n *\n * The span will automatically be finished when one of these conditions is\n * met:\n *\n * * The function returns a promise, in which case the span will finish when\n * the promise is resolved or rejected.\n * * The function takes a callback as its second parameter, in which case the\n * span will finish when that callback is called.\n * * The function doesn't accept a callback and doesn't return a promise, in\n * which case the span will finish at the end of the function execution.\n *\n */\n trace(\n type: SpanTypes,\n fn: (span?: Span, done?: (error?: Error) => any) => Promise\n ): Promise\n trace(\n type: SpanTypes,\n fn: (span?: Span, done?: (error?: Error) => any) => T\n ): T\n trace(\n type: SpanTypes,\n options: TracerSpanOptions,\n fn: (span?: Span, done?: (error?: Error) => any) => Promise\n ): Promise\n trace(\n type: SpanTypes,\n options: TracerSpanOptions,\n fn: (span?: Span, done?: (error?: Error) => any) => T\n ): T\n\n /**\n * Wrap a function to automatically create a span activated on its\n * scope when it's called.\n *\n * The span will automatically be finished when one of these conditions is\n * met:\n *\n * * The function returns a promise, in which case the span will finish when\n * the promise is resolved or rejected.\n * * The function takes a callback as its last parameter, in which case the\n * span will finish when that callback is called.\n * * The function doesn't accept a callback and doesn't return a promise, in\n * which case the span will finish at the end of the function execution.\n */\n wrap) => any>(type: SpanTypes, fn: T): T\n wrap) => any>(\n type: SpanTypes,\n options: TracerSpanOptions,\n fn: T\n ): T\n wrap) => any>(\n type: SpanTypes,\n options: (...args: any[]) => TracerSpanOptions,\n fn: T\n ): T\n\n /**\n * Starts and returns a new Span representing a logical unit of work.\n *\n * This method do NOT modify the current Context by default. In result, any inner span will not\n * automatically set its parent context to the span created by this method unless manually activate\n * context via `tracer.getContext().with`. `trace`, or `wrap` is generally recommended as it gracefully\n * handles context activation. (ref: https://github.com/open-telemetry/opentelemetry-js/issues/1923)\n */\n startSpan(type: SpanTypes): Span\n startSpan(type: SpanTypes, options: TracerSpanOptions): Span\n\n /**\n * Returns currently activated span if current context is in the scope of the span.\n * Returns undefined otherwise.\n */\n getActiveScopeSpan(): Span | undefined\n\n /**\n * Returns trace propagation data for the currently active context. The format is equal to data provided\n * through the OpenTelemetry propagator API.\n */\n getTracePropagationData(): ClientTraceDataEntry[]\n\n /**\n * Executes a function with the given span set as the active span in the context.\n * This allows child spans created within the function to automatically parent to this span.\n */\n withSpan(span: Span, fn: () => T): T\n}\n\ntype NextAttributeNames =\n | 'next.route'\n | 'next.page'\n | 'next.rsc'\n | 'next.segment'\n | 'next.span_category'\n | 'next.span_name'\n | 'next.span_type'\n | 'next.clientComponentLoadCount'\ntype OTELAttributeNames = `http.${string}` | `net.${string}`\ntype AttributeNames = NextAttributeNames | OTELAttributeNames\n\n/** we use this map to propagate attributes from nested spans to the top span */\nconst rootSpanAttributesStore = new Map<\n number,\n Map\n>()\nconst rootSpanIdKey = api.createContextKey('next.rootSpanId')\nlet lastSpanId = 0\nconst getSpanId = () => lastSpanId++\n\nexport interface ClientTraceDataEntry {\n key: string\n value: string\n}\n\nconst clientTraceDataSetter: TextMapSetter = {\n set(carrier, key, value) {\n carrier.push({\n key,\n value,\n })\n },\n}\n\nclass NextTracerImpl implements NextTracer {\n /**\n * Returns an instance to the trace with configured name.\n * Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,\n * This should be lazily evaluated.\n */\n private getTracerInstance(): Tracer {\n return trace.getTracer('next.js', process.env.__NEXT_VERSION)\n }\n\n private isOpenTelemetryEnabled(): boolean {\n const activeSpan = trace.getSpan(context.active())\n if (activeSpan?.isRecording()) {\n return true\n }\n\n const tracerProvider = trace.getTracerProvider() as {\n getDelegate?: () => { constructor?: { name?: string } } | undefined\n }\n\n if (!('getDelegate' in tracerProvider)) {\n return true\n }\n\n return (\n tracerProvider.getDelegate?.()?.constructor?.name !== 'NoopTracerProvider'\n )\n }\n\n public getContext(): ContextAPI {\n return context\n }\n\n public getTracePropagationData(): ClientTraceDataEntry[] {\n const activeContext = context.active()\n const entries: ClientTraceDataEntry[] = []\n propagation.inject(activeContext, entries, clientTraceDataSetter)\n return entries\n }\n\n public getActiveScopeSpan(): Span | undefined {\n const localSpanRecorder = getLocalSpanRecorder()\n const activeLocalSpan = localSpanRecorder?.getActiveLocalSpan()\n if (\n activeLocalSpan &&\n localSpanRecorder?.isOpenTelemetryIsolatedSpan(activeLocalSpan)\n ) {\n return activeLocalSpan\n }\n\n const activeSpan = trace.getSpan(context.active())\n if (activeSpan || !process.env.__NEXT_DEV_SERVER) {\n return activeSpan\n }\n return activeLocalSpan\n }\n\n /**\n * Run `fn` with the active span cleared, so spans created inside become new\n * roots (or parent to incoming propagated context). Used for in-process\n * Node.js middleware so its span is a sibling of the request span, matching\n * edge middleware which runs in a detached sandbox.\n */\n public runWithDetachedContext(fn: () => T): T {\n if (!NEXT_OTEL_PERFORMANCE_PREFIX && !this.isOpenTelemetryEnabled()) {\n return fn()\n }\n return context.with(ROOT_CONTEXT, fn)\n }\n\n public withPropagatedContext(\n carrier: C,\n fn: () => T,\n getter?: TextMapGetter,\n force = false\n ): T {\n const activeContext = context.active()\n\n if (\n !NEXT_OTEL_PERFORMANCE_PREFIX &&\n !this.isOpenTelemetryEnabled() &&\n !trace.getSpanContext(activeContext)\n ) {\n return fn()\n }\n\n if (force) {\n const remoteContext = propagation.extract(ROOT_CONTEXT, carrier, getter)\n\n if (trace.getSpanContext(remoteContext)) {\n return context.with(remoteContext, fn)\n }\n\n // Preserve the current active span while still merging any extracted\n // baggage/context values from the carrier.\n const mergedContext = propagation.extract(activeContext, carrier, getter)\n return context.with(mergedContext, fn)\n }\n\n if (trace.getSpanContext(activeContext)) {\n // Active span is already set, too late to propagate.\n return fn()\n }\n\n const remoteContext = propagation.extract(activeContext, carrier, getter)\n return context.with(remoteContext, fn)\n }\n\n // Trace, wrap implementation is inspired by datadog trace implementation\n // (https://datadoghq.dev/dd-trace-js/interfaces/tracer.html#trace).\n public trace(\n type: SpanTypes,\n fn: (span?: Span, done?: (error?: Error) => any) => Promise\n ): Promise\n public trace(\n type: SpanTypes,\n fn: (span?: Span, done?: (error?: Error) => any) => T\n ): T\n public trace(\n type: SpanTypes,\n options: TracerSpanOptions,\n fn: (span?: Span, done?: (error?: Error) => any) => Promise\n ): Promise\n public trace(\n type: SpanTypes,\n options: TracerSpanOptions,\n fn: (span?: Span, done?: (error?: Error) => any) => T\n ): T\n public trace(...args: Array) {\n const [type, fnOrOptions, fnOrEmpty] = args\n const tracingEnabled =\n Boolean(NEXT_OTEL_PERFORMANCE_PREFIX) || this.isOpenTelemetryEnabled()\n const localSpanRecorder = getLocalSpanRecorder()\n const localSpanRecordingEnabled =\n localSpanRecorder?.isLocalSpanRecordingEnabled() ?? false\n\n if (!tracingEnabled && !localSpanRecordingEnabled) {\n return typeof fnOrOptions === 'function' ? fnOrOptions() : fnOrEmpty()\n }\n\n // coerce options form overload\n const {\n fn,\n options,\n }: {\n fn: (span?: Span, done?: (error?: Error) => any) => T | Promise\n options: TracerSpanOptions\n } =\n typeof fnOrOptions === 'function'\n ? {\n fn: fnOrOptions,\n options: {},\n }\n : {\n fn: fnOrEmpty,\n options: { ...fnOrOptions },\n }\n\n const spanName = options.spanName ?? type\n\n const parentSpan = options.parentSpan ?? this.getActiveScopeSpan()\n const isolatedParentSpan =\n parentSpan && localSpanRecorder?.isOpenTelemetryIsolatedSpan(parentSpan)\n ? parentSpan\n : undefined\n const shouldDelegateSpan =\n !isolatedParentSpan &&\n (NextVanillaSpanAllowlist.has(type) ||\n process.env.NEXT_OTEL_VERBOSE === '1')\n const shouldTraceSpan =\n shouldDelegateSpan ||\n (localSpanRecorder?.isRequestInsightsEnabled() ?? false)\n\n if (!shouldTraceSpan || options.hideSpan) {\n return fn()\n }\n\n // Trying to get active scoped span to assign parent. If option specifies parent span manually, will try to use it.\n let spanContext = isolatedParentSpan\n ? context.active()\n : this.getSpanContext(parentSpan)\n\n if (!spanContext) {\n spanContext = context?.active() ?? ROOT_CONTEXT\n }\n // Check if there's already a root span in the store for this trace\n // We are intentionally not checking whether there is an active context\n // from outside of nextjs to ensure that we can provide the same level\n // of telemetry when using a custom server\n const existingRootSpanId = spanContext.getValue(rootSpanIdKey)\n const isRootSpan =\n typeof existingRootSpanId !== 'number' ||\n !rootSpanAttributesStore.has(existingRootSpanId)\n\n const spanId = getSpanId()\n\n options.attributes = {\n 'next.span_category': 'nextjs',\n 'next.span_name': spanName,\n 'next.span_type': type,\n ...options.attributes,\n }\n\n return context.with(spanContext.setValue(rootSpanIdKey, spanId), () =>\n this.runWithActiveSpan(\n spanName,\n options,\n spanContext,\n tracingEnabled && shouldDelegateSpan,\n localSpanRecordingEnabled,\n isolatedParentSpan,\n (span: Span) => {\n let startTime: number | undefined\n if (\n NEXT_OTEL_PERFORMANCE_PREFIX &&\n type &&\n LogSpanAllowList.has(type)\n ) {\n startTime =\n 'performance' in globalThis && 'measure' in performance\n ? globalThis.performance.now()\n : undefined\n }\n\n let cleanedUp = false\n const onCleanup = () => {\n if (cleanedUp) return\n cleanedUp = true\n rootSpanAttributesStore.delete(spanId)\n if (startTime) {\n performance.measure(\n `${NEXT_OTEL_PERFORMANCE_PREFIX}:next-${(\n type.split('.').pop() || ''\n ).replace(\n /[A-Z]/g,\n (match: string) => '-' + match.toLowerCase()\n )}`,\n {\n start: startTime,\n end: performance.now(),\n }\n )\n }\n }\n\n if (isRootSpan) {\n rootSpanAttributesStore.set(\n spanId,\n new Map(\n Object.entries(options.attributes ?? {}) as [\n AttributeNames,\n AttributeValue | undefined,\n ][]\n )\n )\n }\n if (fn.length > 1) {\n try {\n return fn(span, (err) => {\n if (err) {\n closeSpanWithError(span, err, options.endTime)\n } else {\n span.end(options.endTime)\n }\n })\n } catch (err: any) {\n closeSpanWithError(span, err, options.endTime)\n throw err\n } finally {\n onCleanup()\n }\n }\n\n try {\n const result = fn(span)\n if (isThenable(result)) {\n // If there's error make sure it throws\n return result\n .then((res) => {\n span.end(options.endTime)\n // Need to pass down the promise result,\n // it could be react stream response with error { error, stream }\n return res\n })\n .catch((err) => {\n closeSpanWithError(span, err, options.endTime)\n throw err\n })\n .finally(onCleanup)\n } else {\n span.end(options.endTime)\n onCleanup()\n }\n\n return result\n } catch (err: any) {\n closeSpanWithError(span, err, options.endTime)\n onCleanup()\n throw err\n }\n }\n )\n )\n }\n\n private runWithActiveSpan(\n spanName: string,\n options: TracerSpanOptions,\n parentContext: Context,\n tracingEnabled: boolean,\n localSpanRecordingEnabled: boolean,\n isolatedParentSpan: Span | undefined,\n fn: (span: Span) => T\n ): T {\n if (tracingEnabled) {\n return this.getTracerInstance().startActiveSpan(\n spanName,\n options,\n (span: Span) =>\n fn(\n localSpanRecordingEnabled\n ? this.createLocalRecordingSpan(\n spanName,\n options,\n parentContext,\n span,\n isolatedParentSpan\n )\n : span\n )\n )\n }\n\n const span = this.createLocalRecordingSpan(\n spanName,\n options,\n parentContext,\n undefined,\n isolatedParentSpan\n )\n const localSpanRecorder = getLocalSpanRecorder()!\n return localSpanRecorder.withLocalSpan(span, () =>\n localSpanRecorder.isOpenTelemetryIsolatedSpan(span)\n ? fn(span)\n : context.with(\n trace.setSpan(context.active(), span),\n fn,\n undefined,\n span\n )\n )\n }\n\n private createLocalRecordingSpan(\n name: string,\n options: TracerSpanOptions,\n parentContext: Context,\n delegateSpan?: Span,\n isolatedParentSpan?: Span\n ): Span {\n const parentSpanContext =\n isolatedParentSpan?.spanContext() ?? trace.getSpanContext(parentContext)\n const delegateSpanContext = delegateSpan?.spanContext()\n\n return getLocalSpanRecorder()!.createLocalSpan({\n name,\n attributes: options.attributes,\n links: options.links,\n startTime: options.startTime,\n delegateSpan,\n traceId: delegateSpanContext?.traceId ?? parentSpanContext?.traceId,\n spanId: delegateSpanContext?.spanId,\n parentSpanId: parentSpanContext?.spanId,\n isolateOpenTelemetry: isolatedParentSpan !== undefined,\n })\n }\n\n public wrap) => any>(type: SpanTypes, fn: T): T\n public wrap) => any>(\n type: SpanTypes,\n options: TracerSpanOptions,\n fn: T\n ): T\n public wrap) => any>(\n type: SpanTypes,\n options: (...args: any[]) => TracerSpanOptions,\n fn: T\n ): T\n public wrap(...args: Array) {\n const tracer = this\n const [name, options, fn] =\n args.length === 3 ? args : [args[0], {}, args[1]]\n\n if (\n !NextVanillaSpanAllowlist.has(name) &&\n process.env.NEXT_OTEL_VERBOSE !== '1' &&\n !process.env.__NEXT_DEV_SERVER\n ) {\n return fn\n }\n\n return function (this: any) {\n let optionsObj = options\n if (typeof optionsObj === 'function' && typeof fn === 'function') {\n optionsObj = optionsObj.apply(this, arguments)\n }\n\n const lastArgId = arguments.length - 1\n const cb = arguments[lastArgId]\n\n if (typeof cb === 'function') {\n const scopeBoundCb = tracer.getContext().bind(context.active(), cb)\n return tracer.trace(name, optionsObj, (_span, done) => {\n arguments[lastArgId] = function (err: any) {\n done?.(err)\n return scopeBoundCb.apply(this, arguments)\n }\n\n return fn.apply(this, arguments)\n })\n } else {\n return tracer.trace(name, optionsObj, () => fn.apply(this, arguments))\n }\n }\n }\n\n public startSpan(type: SpanTypes): Span\n public startSpan(type: SpanTypes, options: TracerSpanOptions): Span\n public startSpan(...args: Array): Span {\n const [type, passedOptions]: [string, TracerSpanOptions | undefined] =\n args as any\n const options: TracerSpanOptions = passedOptions\n ? {\n ...passedOptions,\n attributes: {\n 'next.span_category': 'nextjs',\n ...passedOptions.attributes,\n },\n }\n : { attributes: { 'next.span_category': 'nextjs' } }\n\n const localSpanRecorder = getLocalSpanRecorder()\n const parentSpan = options.parentSpan ?? this.getActiveScopeSpan()\n const isolatedParentSpan =\n parentSpan && localSpanRecorder?.isOpenTelemetryIsolatedSpan(parentSpan)\n ? parentSpan\n : undefined\n const parentContext =\n (isolatedParentSpan ? undefined : this.getSpanContext(parentSpan)) ??\n context.active()\n const localSpanRecordingEnabled =\n localSpanRecorder?.isLocalSpanRecordingEnabled() ?? false\n\n if (!localSpanRecordingEnabled) {\n return this.getTracerInstance().startSpan(type, options, parentContext)\n }\n\n const delegateSpan =\n !isolatedParentSpan && this.isOpenTelemetryEnabled()\n ? this.getTracerInstance().startSpan(type, options, parentContext)\n : undefined\n\n return this.createLocalRecordingSpan(\n type,\n options,\n parentContext,\n delegateSpan,\n isolatedParentSpan\n )\n }\n\n private getSpanContext(parentSpan?: Span) {\n const spanContext = parentSpan\n ? trace.setSpan(context.active(), parentSpan)\n : undefined\n\n return spanContext\n }\n\n public getRootSpanAttributes() {\n const spanId = context.active().getValue(rootSpanIdKey) as number\n return rootSpanAttributesStore.get(spanId)\n }\n\n public setRootSpanAttribute(key: AttributeNames, value: AttributeValue) {\n const spanId = context.active().getValue(rootSpanIdKey) as number\n const attributes = rootSpanAttributesStore.get(spanId)\n if (attributes && !attributes.has(key)) {\n attributes.set(key, value)\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n const localSpan = getLocalSpanRecorder()?.getActiveLocalSpan()\n if (localSpan) {\n localSpan.setAttribute(key, value)\n }\n }\n }\n\n public withSpan(span: Span, fn: () => T): T {\n const recorder = getLocalSpanRecorder()\n if (recorder?.isLocalRecordingSpan(span)) {\n return recorder.withLocalSpan(span, () =>\n recorder.isOpenTelemetryIsolatedSpan(span)\n ? fn()\n : context.with(trace.setSpan(context.active(), span), fn)\n )\n }\n return context.with(trace.setSpan(context.active(), span), fn)\n }\n}\n\nconst getTracer = (() => {\n const tracer = new NextTracerImpl()\n\n return () => tracer\n})()\n\nexport { getTracer, SpanStatusCode, SpanKind }\nexport type { NextTracer, Span, SpanOptions, ContextAPI, TracerSpanOptions }\n"],"names":["BubbledError","SpanKind","SpanStatusCode","getTracer","isBubbledError","NEXT_OTEL_PERFORMANCE_PREFIX","process","env","LOCAL_SPAN_RECORDER_KEY","Symbol","for","api","getLocalSpanRecorder","__NEXT_DEV_SERVER","globalThis","undefined","NEXT_RUNTIME","require","err","context","propagation","trace","ROOT_CONTEXT","Error","constructor","bubble","result","error","closeSpanWithError","span","endTime","setAttribute","recordException","name","setStatus","code","ERROR","message","end","rootSpanAttributesStore","Map","rootSpanIdKey","createContextKey","lastSpanId","getSpanId","clientTraceDataSetter","set","carrier","key","value","push","NextTracerImpl","getTracerInstance","__NEXT_VERSION","isOpenTelemetryEnabled","tracerProvider","activeSpan","getSpan","active","isRecording","getTracerProvider","getDelegate","getContext","getTracePropagationData","activeContext","entries","inject","getActiveScopeSpan","localSpanRecorder","activeLocalSpan","getActiveLocalSpan","isOpenTelemetryIsolatedSpan","runWithDetachedContext","fn","with","withPropagatedContext","getter","force","getSpanContext","remoteContext","extract","mergedContext","args","type","fnOrOptions","fnOrEmpty","tracingEnabled","Boolean","localSpanRecordingEnabled","isLocalSpanRecordingEnabled","options","spanName","parentSpan","isolatedParentSpan","shouldDelegateSpan","NextVanillaSpanAllowlist","has","NEXT_OTEL_VERBOSE","shouldTraceSpan","isRequestInsightsEnabled","hideSpan","spanContext","existingRootSpanId","getValue","isRootSpan","spanId","attributes","setValue","runWithActiveSpan","startTime","LogSpanAllowList","performance","now","cleanedUp","onCleanup","delete","measure","split","pop","replace","match","toLowerCase","start","Object","length","isThenable","then","res","catch","finally","parentContext","startActiveSpan","createLocalRecordingSpan","withLocalSpan","setSpan","delegateSpan","parentSpanContext","delegateSpanContext","createLocalSpan","links","traceId","parentSpanId","isolateOpenTelemetry","wrap","tracer","optionsObj","apply","arguments","lastArgId","cb","scopeBoundCb","bind","_span","done","startSpan","passedOptions","getRootSpanAttributes","get","setRootSpanAttribute","localSpan","withSpan","recorder","isLocalRecordingSpan"],"mappings":";;;;;;;;;;;;;;;;;;IAuDaA,YAAY;eAAZA;;IA6qBuBC,QAAQ;eAARA;;IAAhBC,cAAc;eAAdA;;IAAXC,SAAS;eAATA;;IApqBOC,cAAc;eAAdA;;;2BA5D2C;4BAWhC;AAE3B,MAAMC,+BAA+BC,QAAQC,GAAG,CAACF,4BAA4B;AAC7E,MAAMG,0BAA0BC,OAAOC,GAAG,CAAC;AAM3C,IAAIC;AAEJ,SAASC;IACP,IAAIN,QAAQC,GAAG,CAACM,iBAAiB,EAAE;QACjC,OAAO,AAACC,UAA0C,CAACN,wBAAwB;IAC7E,OAAO;QACL,OAAOO;IACT;AACF;AAEA,gFAAgF;AAChF,8EAA8E;AAC9E,uCAAuC;AACvC,0EAA0E;AAC1E,+EAA+E;AAC/E,4CAA4C;AAC5C,6CAA6C;AAC7C,IAAIT,QAAQC,GAAG,CAACS,YAAY,KAAK,QAAQ;IACvCL,MAAMM,QAAQ;AAChB,OAAO;IACL,IAAI;QACFN,MAAMM,QAAQ;IAChB,EAAE,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3C,QAAQC,GAAG,CAACM,iBAAiB,EAAE;gBACfD;YAAlB,MAAMmJ,aAAYnJ,wBAAAA,2CAAAA,sBAAwB0D,kBAAkB;YAC5D,IAAIyF,WAAW;gBACbA,UAAUhI,YAAY,CAACiB,KAAKC;YAC9B;QACF;IACF;IAEO+G,SAAYnI,IAAU,EAAE4C,EAAW,EAAK;QAC7C,MAAMwF,WAAWrJ;QACjB,IAAIqJ,4BAAAA,SAAUC,oBAAoB,CAACrI,OAAO;YACxC,OAAOoI,SAAS5B,aAAa,CAACxG,MAAM,IAClCoI,SAAS1F,2BAA2B,CAAC1C,QACjC4C,OACAtD,QAAQuD,IAAI,CAACrD,MAAMiH,OAAO,CAACnH,QAAQuC,MAAM,IAAI7B,OAAO4C;QAE5D;QACA,OAAOtD,QAAQuD,IAAI,CAACrD,MAAMiH,OAAO,CAACnH,QAAQuC,MAAM,IAAI7B,OAAO4C;IAC7D;AACF;AAEA,MAAMtE,YAAY,AAAC,CAAA;IACjB,MAAM6I,SAAS,IAAI7F;IAEnB,OAAO,IAAM6F;AACf,CAAA","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/utils.d.ts b/e-commerce/node_modules/next/dist/server/lib/trace/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..28e8f79f592eb93dba4de40e14e03120ed3c0b24 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/utils.d.ts @@ -0,0 +1,6 @@ +import type { ClientTraceDataEntry } from './tracer'; +/** + * Takes OpenTelemetry client trace data and the `clientTraceMetadata` option configured in the Next.js config (currently + * experimental) and returns a filtered/allowed list of client trace data entries. + */ +export declare function getTracedMetadata(traceData: ClientTraceDataEntry[], clientTraceMetadata: string[] | undefined): ClientTraceDataEntry[] | undefined; diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/utils.js b/e-commerce/node_modules/next/dist/server/lib/trace/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..a9b70015b681aa9238030a71bdeb08d050f70ef2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/utils.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getTracedMetadata", { + enumerable: true, + get: function() { + return getTracedMetadata; + } +}); +function getTracedMetadata(traceData, clientTraceMetadata) { + if (!clientTraceMetadata) return undefined; + return traceData.filter(({ key })=>clientTraceMetadata.includes(key)); +} + +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/trace/utils.js.map b/e-commerce/node_modules/next/dist/server/lib/trace/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad60fe17ef846773bb7eb8748937d75d9e4ed12f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/trace/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/lib/trace/utils.ts"],"sourcesContent":["import type { ClientTraceDataEntry } from './tracer'\n\n/**\n * Takes OpenTelemetry client trace data and the `clientTraceMetadata` option configured in the Next.js config (currently\n * experimental) and returns a filtered/allowed list of client trace data entries.\n */\nexport function getTracedMetadata(\n traceData: ClientTraceDataEntry[],\n clientTraceMetadata: string[] | undefined\n): ClientTraceDataEntry[] | undefined {\n if (!clientTraceMetadata) return undefined\n return traceData.filter(({ key }) => clientTraceMetadata.includes(key))\n}\n"],"names":["getTracedMetadata","traceData","clientTraceMetadata","undefined","filter","key","includes"],"mappings":";;;;+BAMgBA;;;eAAAA;;;AAAT,SAASA,kBACdC,SAAiC,EACjCC,mBAAyC;IAEzC,IAAI,CAACA,qBAAqB,OAAOC;IACjC,OAAOF,UAAUG,MAAM,CAAC,CAAC,EAAEC,GAAG,EAAE,GAAKH,oBAAoBI,QAAQ,CAACD;AACpE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/types.d.ts b/e-commerce/node_modules/next/dist/server/lib/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..668cb09a4e47f7a6d3aa4fa24691218822b42d42 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/types.d.ts @@ -0,0 +1,4 @@ +import type { IncomingMessage, ServerResponse } from 'http'; +import type { Duplex } from 'stream'; +export type WorkerRequestHandler = (req: IncomingMessage, res: ServerResponse) => Promise; +export type WorkerUpgradeHandler = (req: IncomingMessage, socket: Duplex, head: Buffer) => any; diff --git a/e-commerce/node_modules/next/dist/server/lib/types.js b/e-commerce/node_modules/next/dist/server/lib/types.js new file mode 100644 index 0000000000000000000000000000000000000000..f89b9ccce54e89b62b432c4802c4612600a703d4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/types.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/types.js.map b/e-commerce/node_modules/next/dist/server/lib/types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/utils.d.ts b/e-commerce/node_modules/next/dist/server/lib/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..15fe79ebd1bcb148a22a2ec1b753fed93ceee6bb --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/utils.d.ts @@ -0,0 +1,84 @@ +export declare function printAndExit(message: string, code?: number): never; +export type NodeOptions = Record; +/** + * Tokenizes the arguments string into an array of strings, supporting quoted + * values and escaped characters. + * Converted from: https://github.com/nodejs/node/blob/c29d53c5cfc63c5a876084e788d70c9e87bed880/src/node_options.cc#L1401 + * + * @param input The arguments string to be tokenized. + * @returns An array of strings with the tokenized arguments. + */ +export declare const tokenizeArgs: (input: string) => string[]; +/** + * Get the node options from the environment variable `NODE_OPTIONS` and returns + * them as an array of strings. + * + * @returns An array of strings with the node options. + */ +export declare const getNodeOptionsArgs: () => string[]; +/** + * The debug address is in the form of `[host:]port`. The host is optional. + */ +export interface DebugAddress { + host: string | undefined; + port: number; +} +/** + * Formats the debug address into a string. + */ +export declare const formatDebugAddress: ({ host, port }: DebugAddress) => string; +/** + * Get's the debug address from the `NODE_OPTIONS` environment variable. If the + * address is not found, it returns the default host (`undefined`) and port + * (`9229`). + * + * @returns An object with the host and port of the debug address. + */ +export declare const getParsedDebugAddress: (address: string | string[] | boolean | undefined) => DebugAddress; +/** + * Stringify the arguments to be used in a command line. It will ignore any + * argument that has a value of `undefined`. Options that are not allowed in + * NODE_OPTIONS are returned separately as execArgv. + * + * @param args The arguments to be stringified. + * @returns An object with `nodeOptions` string and `execArgv` array. + */ +export declare function formatNodeOptions(args: NodeOptions): { + nodeOptions: string; + execArgv: string[]; +}; +export declare function getParsedNodeOptions(): NodeOptions; +/** + * Get the node options from the `NODE_OPTIONS` environment variable and parse + * them into an object without the inspect options. + * + * @returns An object with the parsed node options. + */ +export declare function getParsedNodeOptionsWithoutInspect(): NodeOptions; +/** + * Get the node options from the `NODE_OPTIONS` environment variable and format + * them into a string without the inspect options. + * + * @returns A string with the formatted node options. + */ +export declare function getFormattedNodeOptionsWithoutInspect(): string; +/** + * Check if the value is a valid positive integer and parse it. If it's not, it will throw an error. + * + * @param value The value to be parsed. + */ +export declare function parseValidPositiveInteger(value: string): number; +export declare const RESTART_EXIT_CODE = 77; +export type NodeInspectType = 'inspect' | 'inspect-brk' | undefined; +/** + * Get the debug type from the `NODE_OPTIONS` environment variable. + */ +export declare function getNodeDebugType(nodeOptions: NodeOptions): NodeInspectType; +/** + * Get the `max-old-space-size` value from the `NODE_OPTIONS` environment + * variable. + * + * @returns The value of the `max-old-space-size` option as a number. + */ +export declare function getMaxOldSpaceSize(): number | undefined; +export declare function blockOnOutputWrites(): void; diff --git a/e-commerce/node_modules/next/dist/server/lib/utils.js b/e-commerce/node_modules/next/dist/server/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..e037cfe805923ea32857aa7dc0cdfc51778b960c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/utils.js @@ -0,0 +1,343 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + RESTART_EXIT_CODE: null, + blockOnOutputWrites: null, + formatDebugAddress: null, + formatNodeOptions: null, + getFormattedNodeOptionsWithoutInspect: null, + getMaxOldSpaceSize: null, + getMemoryRestartStats: null, + getNodeDebugType: null, + getNodeOptionsArgs: null, + getParsedDebugAddress: null, + getParsedNodeOptions: null, + getParsedNodeOptionsWithoutInspect: null, + parseValidPositiveInteger: null, + printAndExit: null, + tokenizeArgs: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + RESTART_EXIT_CODE: function() { + return RESTART_EXIT_CODE; + }, + blockOnOutputWrites: function() { + return blockOnOutputWrites; + }, + formatDebugAddress: function() { + return formatDebugAddress; + }, + formatNodeOptions: function() { + return formatNodeOptions; + }, + getFormattedNodeOptionsWithoutInspect: function() { + return getFormattedNodeOptionsWithoutInspect; + }, + getMaxOldSpaceSize: function() { + return getMaxOldSpaceSize; + }, + getMemoryRestartStats: function() { + return getMemoryRestartStats; + }, + getNodeDebugType: function() { + return getNodeDebugType; + }, + getNodeOptionsArgs: function() { + return getNodeOptionsArgs; + }, + getParsedDebugAddress: function() { + return getParsedDebugAddress; + }, + getParsedNodeOptions: function() { + return getParsedNodeOptions; + }, + getParsedNodeOptionsWithoutInspect: function() { + return getParsedNodeOptionsWithoutInspect; + }, + parseValidPositiveInteger: function() { + return parseValidPositiveInteger; + }, + printAndExit: function() { + return printAndExit; + }, + tokenizeArgs: function() { + return tokenizeArgs; + } +}); +const _nodeutil = require("node:util"); +const _commander = require("next/dist/compiled/commander"); +function printAndExit(message, code = 1) { + if (code === 0) { + console.log(message); + } else { + console.error(message); + } + return process.exit(code); +} +/** + * Node.js CLI flags that can be repeated. Node runs every occurrence of these + * flags, so they need to be preserved individually rather than collapsed into + * a single value keyed by option name. + * https://nodejs.org/api/cli.html#--requiremodule + * https://nodejs.org/api/cli.html#--importmodule + */ const REPEATABLE_OPTIONS = { + require: { + type: 'string', + multiple: true + }, + import: { + type: 'string', + multiple: true + } +}; +const parseNodeArgs = (args)=>{ + const parsed = (0, _nodeutil.parseArgs)({ + args, + strict: false, + tokens: true, + options: REPEATABLE_OPTIONS + }); + const values = parsed.values; + const tokens = parsed.tokens; + // For the `NODE_OPTIONS`, we support arguments with values without the `=` + // sign. We need to parse them manually. + let orphan = null; + for(let i = 0; i < tokens.length; i++){ + const token = tokens[i]; + if (token.kind === 'option-terminator') { + break; + } + // When we encounter an option, if it's value is undefined, we should check + // to see if the following tokens are positional parameters. If they are, + // then the option is orphaned, and we can assign it. + if (token.kind === 'option') { + orphan = typeof token.value === 'undefined' ? token : null; + continue; + } + // If the token isn't a positional one, then we can't assign it to the found + // orphaned option. + if (token.kind !== 'positional') { + orphan = null; + continue; + } + // If we don't have an orphan, then we can skip this token. + if (!orphan) { + continue; + } + const name = orphan.name; + // If the option is repeatable, accumulate each occurrence instead of + // collapsing them into a single value. + if (name in REPEATABLE_OPTIONS) { + if (Array.isArray(values[name])) { + values[name].push(token.value); + } else if (typeof values[name] === 'string') { + values[name] = [ + values[name], + token.value + ]; + } else { + values[name] = token.value; + } + continue; + } + // If the token is a positional one, and it has a value, so add it to the + // values object. If it already exists, append it with a space. + if (name in values && typeof values[name] === 'string') { + values[name] += ` ${token.value}`; + } else { + values[name] = token.value; + } + } + return values; +}; +const tokenizeArgs = (input)=>{ + let args = []; + let isInString = false; + let willStartNewArg = true; + for(let i = 0; i < input.length; i++){ + let char = input[i]; + // Skip any escaped characters in strings. + if (char === '\\' && isInString) { + // Ensure we don't have an escape character at the end. + if (input.length === i + 1) { + throw new Error('Invalid escape character at the end.'); + } + // Skip the next character. + char = input[++i]; + } else if (char === ' ' && !isInString) { + willStartNewArg = true; + continue; + } else if (char === '"') { + isInString = !isInString; + continue; + } + // If we're starting a new argument, we should add it to the array. + if (willStartNewArg) { + args.push(char); + willStartNewArg = false; + } else { + args[args.length - 1] += char; + } + } + if (isInString) { + throw new Error('Unterminated string'); + } + return args; +}; +const getNodeOptionsArgs = ()=>{ + if (!process.env.NODE_OPTIONS) return []; + return tokenizeArgs(process.env.NODE_OPTIONS); +}; +const formatDebugAddress = ({ host, port })=>{ + if (host) return `${host}:${port}`; + return `${port}`; +}; +const getParsedDebugAddress = (address)=>{ + if (!address || typeof address !== 'string') { + return { + host: undefined, + port: 9229 + }; + } + // The address is in the form of `[host:]port`. Let's parse the address. + if (address.includes(':')) { + const [host, port] = address.split(':'); + return { + host, + port: parseInt(port, 10) + }; + } + return { + host: undefined, + port: parseInt(address, 10) + }; +}; +/** + * Node.js CLI flags that are not allowed in NODE_OPTIONS and must be + * passed as direct CLI arguments via execArgv. + * This set is the difference between all Node.js CLI flags and the ones **not** + * allowed in NODE_OPTIONS, as listed in the Node.js documentation: + * https://nodejs.org/api/cli.html#node_optionsoptions + * + * It is not exhaustive since not all options make sense for Next.js (e.g. --test) + */ const EXEC_ARGV_ONLY_OPTIONS = new Set([ + 'experimental-network-inspection', + 'experimental-storage-inspection', + 'experimental-worker-inspection', + 'experimental-inspector-network-resource' +]); +function formatArg(key, value) { + if (value === true) { + return `--${key}`; + } + if (Array.isArray(value)) { + const formatted = []; + for (const item of value){ + const formattedItem = formatArg(key, item); + if (formattedItem !== null) { + formatted.push(formattedItem); + } + } + return formatted.length > 0 ? formatted.join(' ') : null; + } + if (value) { + return `--${key}=${// Values with spaces need to be quoted. We use JSON.stringify to + // also escape any nested quotes. + value.includes(' ') && !value.startsWith('"') ? JSON.stringify(value) : value}`; + } + return null; +} +function formatNodeOptions(args) { + const nodeOptionsParts = []; + const execArgv = []; + for (const [key, value] of Object.entries(args)){ + const formatted = formatArg(key, value); + if (formatted === null) continue; + if (EXEC_ARGV_ONLY_OPTIONS.has(key)) { + execArgv.push(formatted); + } else { + nodeOptionsParts.push(formatted); + } + } + return { + nodeOptions: nodeOptionsParts.join(' '), + execArgv + }; +} +function getParsedNodeOptions() { + const args = [ + ...process.execArgv, + ...getNodeOptionsArgs() + ]; + if (args.length === 0) return {}; + return parseNodeArgs(args); +} +function getParsedNodeOptionsWithoutInspect() { + const args = getNodeOptionsArgs(); + if (args.length === 0) return {}; + const parsed = parseNodeArgs(args); + // Remove inspect options. + delete parsed.inspect; + delete parsed['inspect-brk']; + delete parsed['inspect_brk']; + return parsed; +} +function getFormattedNodeOptionsWithoutInspect() { + const args = getParsedNodeOptionsWithoutInspect(); + if (Object.keys(args).length === 0) return ''; + return formatNodeOptions(args).nodeOptions; +} +function parseValidPositiveInteger(value) { + const parsedValue = parseInt(value, 10); + if (isNaN(parsedValue) || !isFinite(parsedValue) || parsedValue < 0) { + throw new _commander.InvalidArgumentError(`'${value}' is not a non-negative number.`); + } + return parsedValue; +} +const RESTART_EXIT_CODE = 77; +function getMemoryRestartStats(isDev, devMemoryThresholdRestart, getHeapStatistics) { + if (!isDev || !devMemoryThresholdRestart) { + return undefined; + } + const heapStatistics = getHeapStatistics(); + if (heapStatistics.used_heap_size > 0.8 * heapStatistics.heap_size_limit) { + return heapStatistics; + } + return undefined; +} +function getNodeDebugType(nodeOptions) { + if (nodeOptions.inspect) { + return 'inspect'; + } + if (nodeOptions['inspect-brk'] || nodeOptions['inspect_brk']) { + return 'inspect-brk'; + } +} +function getMaxOldSpaceSize() { + const args = getNodeOptionsArgs(); + if (args.length === 0) return; + const parsed = parseNodeArgs(args); + const size = parsed['max-old-space-size'] || parsed['max_old_space_size']; + if (!size || typeof size !== 'string') return; + return parseInt(size, 10); +} +function blockOnOutputWrites() { + for (const stream of [ + process.stdout, + process.stderr + ]){ + var _stream__handle_setBlocking, _stream__handle; + ; + (_stream__handle = stream._handle) == null ? void 0 : (_stream__handle_setBlocking = _stream__handle.setBlocking) == null ? void 0 : _stream__handle_setBlocking.call(_stream__handle, true); + } +} + +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/utils.js.map b/e-commerce/node_modules/next/dist/server/lib/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e40708909b9fe4e0caf9f4546396e626c224360c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/lib/utils.ts"],"sourcesContent":["import { parseArgs } from 'node:util'\nimport { InvalidArgumentError } from 'next/dist/compiled/commander'\n\nexport function printAndExit(message: string, code = 1) {\n if (code === 0) {\n console.log(message)\n } else {\n console.error(message)\n }\n\n return process.exit(code)\n}\n\nexport type NodeOptions = Record<\n string,\n string | string[] | boolean | undefined\n>\n\n/**\n * Node.js CLI flags that can be repeated. Node runs every occurrence of these\n * flags, so they need to be preserved individually rather than collapsed into\n * a single value keyed by option name.\n * https://nodejs.org/api/cli.html#--requiremodule\n * https://nodejs.org/api/cli.html#--importmodule\n */\nconst REPEATABLE_OPTIONS: Record = {\n require: { type: 'string', multiple: true },\n import: { type: 'string', multiple: true },\n}\n\nconst parseNodeArgs = (args: string[]): NodeOptions => {\n const parsed = parseArgs({\n args,\n strict: false,\n tokens: true,\n options: REPEATABLE_OPTIONS,\n })\n const values: NodeOptions = parsed.values\n const tokens = parsed.tokens\n\n // For the `NODE_OPTIONS`, we support arguments with values without the `=`\n // sign. We need to parse them manually.\n let orphan = null\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i]\n\n if (token.kind === 'option-terminator') {\n break\n }\n\n // When we encounter an option, if it's value is undefined, we should check\n // to see if the following tokens are positional parameters. If they are,\n // then the option is orphaned, and we can assign it.\n if (token.kind === 'option') {\n orphan = typeof token.value === 'undefined' ? token : null\n continue\n }\n\n // If the token isn't a positional one, then we can't assign it to the found\n // orphaned option.\n if (token.kind !== 'positional') {\n orphan = null\n continue\n }\n\n // If we don't have an orphan, then we can skip this token.\n if (!orphan) {\n continue\n }\n\n const name = orphan.name\n\n // If the option is repeatable, accumulate each occurrence instead of\n // collapsing them into a single value.\n if (name in REPEATABLE_OPTIONS) {\n if (Array.isArray(values[name])) {\n values[name].push(token.value)\n } else if (typeof values[name] === 'string') {\n values[name] = [values[name], token.value]\n } else {\n values[name] = token.value\n }\n continue\n }\n\n // If the token is a positional one, and it has a value, so add it to the\n // values object. If it already exists, append it with a space.\n if (name in values && typeof values[name] === 'string') {\n values[name] += ` ${token.value}`\n } else {\n values[name] = token.value\n }\n }\n\n return values\n}\n\n/**\n * Tokenizes the arguments string into an array of strings, supporting quoted\n * values and escaped characters.\n * Converted from: https://github.com/nodejs/node/blob/c29d53c5cfc63c5a876084e788d70c9e87bed880/src/node_options.cc#L1401\n *\n * @param input The arguments string to be tokenized.\n * @returns An array of strings with the tokenized arguments.\n */\nexport const tokenizeArgs = (input: string): string[] => {\n let args: string[] = []\n let isInString = false\n let willStartNewArg = true\n\n for (let i = 0; i < input.length; i++) {\n let char = input[i]\n\n // Skip any escaped characters in strings.\n if (char === '\\\\' && isInString) {\n // Ensure we don't have an escape character at the end.\n if (input.length === i + 1) {\n throw new Error('Invalid escape character at the end.')\n }\n\n // Skip the next character.\n char = input[++i]\n }\n // If we find a space outside of a string, we should start a new argument.\n else if (char === ' ' && !isInString) {\n willStartNewArg = true\n continue\n }\n\n // If we find a quote, we should toggle the string flag.\n else if (char === '\"') {\n isInString = !isInString\n continue\n }\n\n // If we're starting a new argument, we should add it to the array.\n if (willStartNewArg) {\n args.push(char)\n willStartNewArg = false\n }\n // Otherwise, add it to the last argument.\n else {\n args[args.length - 1] += char\n }\n }\n\n if (isInString) {\n throw new Error('Unterminated string')\n }\n\n return args\n}\n\n/**\n * Get the node options from the environment variable `NODE_OPTIONS` and returns\n * them as an array of strings.\n *\n * @returns An array of strings with the node options.\n */\nexport const getNodeOptionsArgs = () => {\n if (!process.env.NODE_OPTIONS) return []\n\n return tokenizeArgs(process.env.NODE_OPTIONS)\n}\n\n/**\n * The debug address is in the form of `[host:]port`. The host is optional.\n */\nexport interface DebugAddress {\n host: string | undefined\n port: number\n}\n\n/**\n * Formats the debug address into a string.\n */\nexport const formatDebugAddress = ({ host, port }: DebugAddress): string => {\n if (host) return `${host}:${port}`\n return `${port}`\n}\n\n/**\n * Get's the debug address from the `NODE_OPTIONS` environment variable. If the\n * address is not found, it returns the default host (`undefined`) and port\n * (`9229`).\n *\n * @returns An object with the host and port of the debug address.\n */\nexport const getParsedDebugAddress = (\n address: string | string[] | boolean | undefined\n): DebugAddress => {\n if (!address || typeof address !== 'string') {\n return { host: undefined, port: 9229 }\n }\n\n // The address is in the form of `[host:]port`. Let's parse the address.\n if (address.includes(':')) {\n const [host, port] = address.split(':')\n return { host, port: parseInt(port, 10) }\n }\n\n return { host: undefined, port: parseInt(address, 10) }\n}\n\n/**\n * Node.js CLI flags that are not allowed in NODE_OPTIONS and must be\n * passed as direct CLI arguments via execArgv.\n * This set is the difference between all Node.js CLI flags and the ones **not**\n * allowed in NODE_OPTIONS, as listed in the Node.js documentation:\n * https://nodejs.org/api/cli.html#node_optionsoptions\n *\n * It is not exhaustive since not all options make sense for Next.js (e.g. --test)\n */\nconst EXEC_ARGV_ONLY_OPTIONS = new Set([\n 'experimental-network-inspection',\n 'experimental-storage-inspection',\n 'experimental-worker-inspection',\n 'experimental-inspector-network-resource',\n])\n\nfunction formatArg(\n key: string,\n value: string | string[] | boolean | undefined\n): string | null {\n if (value === true) {\n return `--${key}`\n }\n\n if (Array.isArray(value)) {\n const formatted: string[] = []\n for (const item of value) {\n const formattedItem = formatArg(key, item)\n if (formattedItem !== null) {\n formatted.push(formattedItem)\n }\n }\n return formatted.length > 0 ? formatted.join(' ') : null\n }\n\n if (value) {\n return `--${key}=${\n // Values with spaces need to be quoted. We use JSON.stringify to\n // also escape any nested quotes.\n value.includes(' ') && !value.startsWith('\"')\n ? JSON.stringify(value)\n : value\n }`\n }\n\n return null\n}\n\n/**\n * Stringify the arguments to be used in a command line. It will ignore any\n * argument that has a value of `undefined`. Options that are not allowed in\n * NODE_OPTIONS are returned separately as execArgv.\n *\n * @param args The arguments to be stringified.\n * @returns An object with `nodeOptions` string and `execArgv` array.\n */\nexport function formatNodeOptions(args: NodeOptions): {\n nodeOptions: string\n execArgv: string[]\n} {\n const nodeOptionsParts: string[] = []\n const execArgv: string[] = []\n\n for (const [key, value] of Object.entries(args)) {\n const formatted = formatArg(key, value)\n if (formatted === null) continue\n\n if (EXEC_ARGV_ONLY_OPTIONS.has(key)) {\n execArgv.push(formatted)\n } else {\n nodeOptionsParts.push(formatted)\n }\n }\n\n return { nodeOptions: nodeOptionsParts.join(' '), execArgv }\n}\n\nexport function getParsedNodeOptions(): NodeOptions {\n const args = [...process.execArgv, ...getNodeOptionsArgs()]\n if (args.length === 0) return {}\n\n return parseNodeArgs(args)\n}\n\n/**\n * Get the node options from the `NODE_OPTIONS` environment variable and parse\n * them into an object without the inspect options.\n *\n * @returns An object with the parsed node options.\n */\nexport function getParsedNodeOptionsWithoutInspect() {\n const args = getNodeOptionsArgs()\n if (args.length === 0) return {}\n\n const parsed = parseNodeArgs(args)\n\n // Remove inspect options.\n delete parsed.inspect\n delete parsed['inspect-brk']\n delete parsed['inspect_brk']\n\n return parsed\n}\n\n/**\n * Get the node options from the `NODE_OPTIONS` environment variable and format\n * them into a string without the inspect options.\n *\n * @returns A string with the formatted node options.\n */\nexport function getFormattedNodeOptionsWithoutInspect() {\n const args = getParsedNodeOptionsWithoutInspect()\n if (Object.keys(args).length === 0) return ''\n\n return formatNodeOptions(args).nodeOptions\n}\n\n/**\n * Check if the value is a valid positive integer and parse it. If it's not, it will throw an error.\n *\n * @param value The value to be parsed.\n */\nexport function parseValidPositiveInteger(value: string): number {\n const parsedValue = parseInt(value, 10)\n\n if (isNaN(parsedValue) || !isFinite(parsedValue) || parsedValue < 0) {\n throw new InvalidArgumentError(`'${value}' is not a non-negative number.`)\n }\n return parsedValue\n}\n\nexport const RESTART_EXIT_CODE = 77\n\ntype HeapStatistics = {\n used_heap_size: number\n heap_size_limit: number\n}\n\n/**\n * @internal\n */\nexport function getMemoryRestartStats(\n isDev: boolean,\n devMemoryThresholdRestart: boolean,\n getHeapStatistics: () => T\n): T | undefined {\n if (!isDev || !devMemoryThresholdRestart) {\n return undefined\n }\n\n const heapStatistics = getHeapStatistics()\n if (heapStatistics.used_heap_size > 0.8 * heapStatistics.heap_size_limit) {\n return heapStatistics\n }\n\n return undefined\n}\n\nexport type NodeInspectType = 'inspect' | 'inspect-brk' | undefined\n\n/**\n * Get the debug type from the `NODE_OPTIONS` environment variable.\n */\nexport function getNodeDebugType(nodeOptions: NodeOptions): NodeInspectType {\n if (nodeOptions.inspect) {\n return 'inspect'\n }\n if (nodeOptions['inspect-brk'] || nodeOptions['inspect_brk']) {\n return 'inspect-brk'\n }\n}\n\n/**\n * Get the `max-old-space-size` value from the `NODE_OPTIONS` environment\n * variable.\n *\n * @returns The value of the `max-old-space-size` option as a number.\n */\nexport function getMaxOldSpaceSize() {\n const args = getNodeOptionsArgs()\n if (args.length === 0) return\n\n const parsed = parseNodeArgs(args)\n\n const size = parsed['max-old-space-size'] || parsed['max_old_space_size']\n if (!size || typeof size !== 'string') return\n\n return parseInt(size, 10)\n}\n\n// For a child whose output is piped to its parent. Without this,\n// process.exit() can drop the last lines written to the pipe. Node already\n// does this for terminals.\nexport function blockOnOutputWrites() {\n for (const stream of [process.stdout, process.stderr]) {\n ;(stream as any)._handle?.setBlocking?.(true)\n }\n}\n"],"names":["RESTART_EXIT_CODE","blockOnOutputWrites","formatDebugAddress","formatNodeOptions","getFormattedNodeOptionsWithoutInspect","getMaxOldSpaceSize","getMemoryRestartStats","getNodeDebugType","getNodeOptionsArgs","getParsedDebugAddress","getParsedNodeOptions","getParsedNodeOptionsWithoutInspect","parseValidPositiveInteger","printAndExit","tokenizeArgs","message","code","console","log","error","process","exit","REPEATABLE_OPTIONS","require","type","multiple","import","parseNodeArgs","args","parsed","parseArgs","strict","tokens","options","values","orphan","i","length","token","kind","value","name","Array","isArray","push","input","isInString","willStartNewArg","char","Error","env","NODE_OPTIONS","host","port","address","undefined","includes","split","parseInt","EXEC_ARGV_ONLY_OPTIONS","Set","formatArg","key","formatted","item","formattedItem","join","startsWith","JSON","stringify","nodeOptionsParts","execArgv","Object","entries","has","nodeOptions","inspect","keys","parsedValue","isNaN","isFinite","InvalidArgumentError","isDev","devMemoryThresholdRestart","getHeapStatistics","heapStatistics","used_heap_size","heap_size_limit","size","stream","stdout","stderr","_handle","setBlocking"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;IA+UaA,iBAAiB;eAAjBA;;IA8DGC,mBAAmB;eAAnBA;;IA7NHC,kBAAkB;eAAlBA;;IAoFGC,iBAAiB;eAAjBA;;IAsDAC,qCAAqC;eAArCA;;IAoEAC,kBAAkB;eAAlBA;;IArCAC,qBAAqB;eAArBA;;IAsBAC,gBAAgB;eAAhBA;;IAhNHC,kBAAkB;eAAlBA;;IA6BAC,qBAAqB;eAArBA;;IA6FGC,oBAAoB;eAApBA;;IAaAC,kCAAkC;eAAlCA;;IAgCAC,yBAAyB;eAAzBA;;IAnUAC,YAAY;eAAZA;;IAsGHC,YAAY;eAAZA;;;0BAzGa;2BACW;AAE9B,SAASD,aAAaE,OAAe,EAAEC,OAAO,CAAC;IACpD,IAAIA,SAAS,GAAG;QACdC,QAAQC,GAAG,CAACH;IACd,OAAO;QACLE,QAAQE,KAAK,CAACJ;IAChB;IAEA,OAAOK,QAAQC,IAAI,CAACL;AACtB;AAOA;;;;;;CAMC,GACD,MAAMM,qBAAyE;IAC7EC,SAAS;QAAEC,MAAM;QAAUC,UAAU;IAAK;IAC1CC,QAAQ;QAAEF,MAAM;QAAUC,UAAU;IAAK;AAC3C;AAEA,MAAME,gBAAgB,CAACC;IACrB,MAAMC,SAASC,IAAAA,mBAAS,EAAC;QACvBF;QACAG,QAAQ;QACRC,QAAQ;QACRC,SAASX;IAC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c,EAAE;QAC5D,OAAO;IACT;AACF;AAQO,SAAStE;IACd,MAAMuB,OAAOpB;IACb,IAAIoB,KAAKS,MAAM,KAAK,GAAG;IAEvB,MAAMR,SAASF,cAAcC;IAE7B,MAAM4D,OAAO3D,MAAM,CAAC,qBAAqB,IAAIA,MAAM,CAAC,qBAAqB;IACzE,IAAI,CAAC2D,QAAQ,OAAOA,SAAS,UAAU;IAEvC,OAAO9B,SAAS8B,MAAM;AACxB;AAKO,SAASvF;IACd,KAAK,MAAMwF,UAAU;QAACrE,QAAQsE,MAAM;QAAEtE,QAAQuE,MAAM;KAAC,CAAE;YACpD,6BAAA;;SAAA,kBAAA,AAACF,OAAeG,OAAO,sBAAvB,8BAAA,gBAAyBC,WAAW,qBAApC,iCAAA,iBAAuC;IAC1C;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/worker-utils.d.ts b/e-commerce/node_modules/next/dist/server/lib/worker-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..73a3d092224e93af74182d49bc09767e30566e1e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/worker-utils.d.ts @@ -0,0 +1 @@ +export declare const getFreePort: () => Promise; diff --git a/e-commerce/node_modules/next/dist/server/lib/worker-utils.js b/e-commerce/node_modules/next/dist/server/lib/worker-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..d99cbfbd80220bd7cf8fac54a347cd023755a473 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/worker-utils.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getFreePort", { + enumerable: true, + get: function() { + return getFreePort; + } +}); +const _http = /*#__PURE__*/ _interop_require_default(require("http")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +const getFreePort = async ()=>{ + return new Promise((resolve, reject)=>{ + const server = _http.default.createServer(()=>{}); + server.listen(0, ()=>{ + const address = server.address(); + server.close(); + if (address && typeof address === 'object') { + resolve(address.port); + } else { + reject(new Error('invalid address from server: ' + (address == null ? void 0 : address.toString()))); + } + }); + }); +}; + +//# sourceMappingURL=worker-utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/lib/worker-utils.js.map b/e-commerce/node_modules/next/dist/server/lib/worker-utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..84be06cca1b90a4ddf039915a3ad78f65f3d3d81 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/lib/worker-utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/lib/worker-utils.ts"],"sourcesContent":["import http from 'http'\n\nexport const getFreePort = async (): Promise => {\n return new Promise((resolve, reject) => {\n const server = http.createServer(() => {})\n server.listen(0, () => {\n const address = server.address()\n server.close()\n\n if (address && typeof address === 'object') {\n resolve(address.port)\n } else {\n reject(new Error('invalid address from server: ' + address?.toString()))\n }\n })\n })\n}\n"],"names":["getFreePort","Promise","resolve","reject","server","http","createServer","listen","address","close","port","Error","toString"],"mappings":";;;;+BAEaA;;;eAAAA;;;6DAFI;;;;;;AAEV,MAAMA,cAAc;IACzB,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3B,MAAMC,SAASC,aAAI,CAACC,YAAY,CAAC,KAAO;QACxCF,OAAOG,MAAM,CAAC,GAAG;YACf,MAAMC,UAAUJ,OAAOI,OAAO;YAC9BJ,OAAOK,KAAK;YAEZ,IAAID,WAAW,OAAOA,YAAY,UAAU;gBAC1CN,QAAQM,QAAQE,IAAI;YACtB,OAAO;gBACLP,OAAO,IAAIQ,MAAM,mCAAkCH,2BAAAA,QAASI,QAAQ;YACtE;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/load-components.d.ts b/e-commerce/node_modules/next/dist/server/load-components.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..70efa6865a7354a02eb8973c4fdf239f701893be --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/load-components.d.ts @@ -0,0 +1,85 @@ +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'; +import type { RouteModule } from './route-modules/route-module'; +import type { BuildManifest } from './get-page-files'; +import type { DeepReadonly } from '../shared/lib/deep-readonly'; +export type ManifestItem = { + id: number | string; + files: string[]; +}; +export type ReactLoadableManifest = { + [moduleId: string]: ManifestItem; +}; +/** + * This manifest prevents removing server rendered tags after client + * navigation. This is only needed under `Pages dir && Production && Webpack`. + * @see https://github.com/vercel/next.js/pull/72959 + */ +export type DynamicCssManifest = string[]; +/** + * A manifest entry type for the react-loadable-manifest.json. + * + * The whole manifest.json is a type of `Record` + * where pathname is a string-based key points to the path of the page contains + * each dynamic imports. + */ +export interface LoadableManifest { + [k: string]: { + id: string | number; + files: string[]; + }; +} +export type GenericComponentMod = { + handler(req: IncomingMessage, res: ServerResponse, ctx: { + waitUntil?: (prom: Promise) => void; + }): Promise; +}; +export type LoadComponentsReturnType = { + Component: NextComponentType; + pageConfig: PageConfig; + buildManifest: DeepReadonly; + subresourceIntegrityManifest?: DeepReadonly>; + reactLoadableManifest: DeepReadonly; + dynamicCssManifest?: DeepReadonly; + Document: DocumentType; + App: AppType; + getStaticProps?: GetStaticProps; + getStaticPaths?: GetStaticPaths; + getServerSideProps?: GetServerSideProps; + ComponentMod: NextModule; + routeModule: RouteModule; + isAppPath?: boolean; + page: string; + multiZoneDraftMode?: boolean; +}; +/** + * Load manifest file with retries, defaults to 3 attempts. + */ +export declare function loadManifestWithRetries(manifestPath: string, attempts?: number): Promise>; +/** + * Load manifest file with retries, defaults to 3 attempts, or return undefined. + */ +export declare function tryLoadManifestWithRetries(manifestPath: string, attempts?: number): Promise | undefined>; +/** + * Load manifest file with retries, defaults to 3 attempts. + */ +export declare function evalManifestWithRetries(manifestPath: string, attempts?: number): Promise>; +/** + * 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 | undefined>; +declare function loadComponentsImpl({ distDir, page, isAppPath, isDev, sriEnabled, needsManifestsForLegacyReasons, }: { + distDir: string; + page: string; + isAppPath: boolean; + isDev: boolean; + sriEnabled: boolean; + needsManifestsForLegacyReasons: boolean; +}): Promise>; +export declare const loadComponents: typeof loadComponentsImpl; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/load-components.js b/e-commerce/node_modules/next/dist/server/load-components.js new file mode 100644 index 0000000000000000000000000000000000000000..6fc540c77aac7c7c4b759dea2ffac7855d0e684b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/load-components.js @@ -0,0 +1,190 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + evalManifestWithRetries: null, + loadClientReferenceManifestForPage: null, + loadComponents: null, + loadManifestWithRetries: null, + tryLoadManifestWithRetries: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + evalManifestWithRetries: function() { + return evalManifestWithRetries; + }, + loadClientReferenceManifestForPage: function() { + return loadClientReferenceManifestForPage; + }, + loadComponents: function() { + return loadComponents; + }, + loadManifestWithRetries: function() { + return loadManifestWithRetries; + }, + tryLoadManifestWithRetries: function() { + return tryLoadManifestWithRetries; + } +}); +const _constants = require("../shared/lib/constants"); +const _path = require("path"); +const _require = require("./require"); +const _interopdefault = require("../lib/interop-default"); +const _tracer = require("./lib/trace/tracer"); +const _constants1 = require("./lib/trace/constants"); +const _loadmanifestexternal = require("./load-manifest.external"); +const _wait = require("../lib/wait"); +const _manifestssingleton = require("./app-render/manifests-singleton"); +const _normalizepagepath = require("../shared/lib/page-path/normalize-page-path"); +const _ismetadataroute = require("../lib/metadata/is-metadata-route"); +async function loadManifestWithRetries(manifestPath, attempts = 3) { + while(true){ + try { + return (0, _loadmanifestexternal.loadManifest)(manifestPath); + } catch (err) { + attempts--; + if (attempts <= 0) throw err; + await (0, _wait.wait)(100); + } + } +} +async function tryLoadManifestWithRetries(manifestPath, attempts = 3) { + try { + return await loadManifestWithRetries(manifestPath, attempts); + } catch (err) { + return undefined; + } +} +async function evalManifestWithRetries(manifestPath, attempts = 3) { + while(true){ + try { + return (0, _loadmanifestexternal.evalManifest)(manifestPath); + } catch (err) { + attempts--; + if (attempts <= 0) throw err; + await (0, _wait.wait)(100); + } + } +} +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 { + const context = await evalManifestWithRetries(manifestPath, attempts); + return context.__RSC_MANIFEST[entryName]; + } catch (err) { + return undefined; + } +} +function loadRouteModule(page, distDir, isAppPath) { + return (0, _tracer.getTracer)().trace(_constants1.LoadComponentsSpan.loadRouteModule, { + spanName: 'load route module' + }, ()=>(0, _require.requirePage)(page, distDir, isAppPath)); +} +async function loadComponentsImpl({ distDir, page, isAppPath, isDev, sriEnabled, // When route modules are used, which is the case for the server calls to loadComponents, it no longer needs manifest to be loaded here. +// Static generation still needs the manifests to be loaded here. +// In the future static generation will also use route modules, and we will remove this flag. +needsManifestsForLegacyReasons }) { + let DocumentMod = {}; + let AppMod = {}; + if (!isAppPath) { + ; + [DocumentMod, AppMod] = await Promise.all([ + (0, _require.requirePage)('/_document', distDir, false), + (0, _require.requirePage)('/_app', distDir, false) + ]); + } + if (needsManifestsForLegacyReasons) { + // In dev mode we retry loading a manifest file to handle a race condition + // that can occur while app and pages are compiling at the same time, and the + // build-manifest is still being written to disk while an app path is + // attempting to load. + const manifestLoadAttempts = isDev ? 3 : 1; + let reactLoadableManifestPath; + if (!process.env.TURBOPACK) { + reactLoadableManifestPath = (0, _path.join)(/* turbopackIgnore: true */ distDir, _constants.REACT_LOADABLE_MANIFEST); + } else if (isAppPath) { + reactLoadableManifestPath = (0, _path.join)(/* turbopackIgnore: true */ distDir, 'server', 'app', page, _constants.REACT_LOADABLE_MANIFEST); + } else { + reactLoadableManifestPath = (0, _path.join)(/* turbopackIgnore: true */ distDir, 'server', 'pages', (0, _normalizepagepath.normalizePagePath)(page), _constants.REACT_LOADABLE_MANIFEST); + } + // Make sure to avoid loading the manifest for static metadata routes for better performance. + const hasClientManifest = !(0, _ismetadataroute.isStaticMetadataRoute)(page); + // Load the manifest files first + // + // Loading page-specific manifests shouldn't throw an error if the manifest couldn't be found, so + // that the `requirePage` call below will throw the correct error in that case + // (a `PageNotFoundError`). + const [buildManifest, reactLoadableManifest, dynamicCssManifest, clientReferenceManifest, serverActionsManifest, subresourceIntegrityManifest] = await Promise.all([ + loadManifestWithRetries((0, _path.join)(/* turbopackIgnore: true */ distDir, _constants.BUILD_MANIFEST), manifestLoadAttempts), + tryLoadManifestWithRetries(reactLoadableManifestPath, manifestLoadAttempts), + // This manifest will only exist in Pages dir && Production && Webpack. + isAppPath || process.env.TURBOPACK ? undefined : loadManifestWithRetries((0, _path.join)(/* turbopackIgnore: true */ distDir, `${_constants.DYNAMIC_CSS_MANIFEST}.json`), manifestLoadAttempts).catch(()=>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, + sriEnabled ? loadManifestWithRetries((0, _path.join)(/* turbopackIgnore: true */ distDir, 'server', _constants.SUBRESOURCE_INTEGRITY_MANIFEST + '.json')).catch(()=>undefined) : undefined + ]); + // Before requiring the actual page module, we have to set the reference + // manifests to our global store so Server Action's encryption util can access + // to them at the top level of the page module. + if (serverActionsManifest && clientReferenceManifest) { + (0, _manifestssingleton.setManifestsSingleton)({ + page, + clientReferenceManifest, + serverActionsManifest + }); + } + const ComponentMod = await loadRouteModule(page, distDir, isAppPath); + const Component = (0, _interopdefault.interopDefault)(ComponentMod); + const Document = (0, _interopdefault.interopDefault)(DocumentMod); + const App = (0, _interopdefault.interopDefault)(AppMod); + const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } = ComponentMod; + return { + // @ts-expect-error this is indeed `{} || AppType` and not always `AppType` + App, + // @ts-expect-error this is indeed `{} || DocumentType` and not always `DocumentType` + Document, + Component, + buildManifest, + subresourceIntegrityManifest, + reactLoadableManifest: reactLoadableManifest || {}, + dynamicCssManifest, + pageConfig: ComponentMod.config || {}, + ComponentMod, + getServerSideProps, + getStaticProps, + getStaticPaths, + isAppPath, + page, + routeModule + }; + } else { + const ComponentMod = await loadRouteModule(page, distDir, isAppPath); + const Component = (0, _interopdefault.interopDefault)(ComponentMod); + const Document = (0, _interopdefault.interopDefault)(DocumentMod); + const App = (0, _interopdefault.interopDefault)(AppMod); + const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } = ComponentMod; + return { + App, + Document, + Component, + pageConfig: ComponentMod.config || {}, + ComponentMod, + getServerSideProps, + getStaticProps, + getStaticPaths, + isAppPath, + page, + routeModule + }; // temporary `as any` to make TypeScript not fail so that the tests will run on the PR. + } +} +const loadComponents = (0, _tracer.getTracer)().wrap(_constants1.LoadComponentsSpan.loadComponents, loadComponentsImpl); + +//# sourceMappingURL=load-components.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/load-components.js.map b/e-commerce/node_modules/next/dist/server/load-components.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d348c2cd6918166e2bce2cd738ce679d5b751e54 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/load-components.js.map @@ -0,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 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`\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\n }\n ): Promise\n}\n\nexport type LoadComponentsReturnType<\n NextModule extends GenericComponentMod = GenericComponentMod,\n> = {\n Component: NextComponentType\n pageConfig: PageConfig\n buildManifest: DeepReadonly\n subresourceIntegrityManifest?: DeepReadonly>\n reactLoadableManifest: DeepReadonly\n dynamicCssManifest?: DeepReadonly\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(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return loadManifest(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(\n manifestPath: string,\n attempts = 3\n) {\n try {\n return await loadManifestWithRetries(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(\n manifestPath: string,\n attempts = 3\n) {\n while (true) {\n try {\n return evalManifest(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 | 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\nfunction loadRouteModule(page: string, distDir: string, isAppPath: boolean) {\n return getTracer().trace(\n LoadComponentsSpan.loadRouteModule,\n { spanName: 'load route module' },\n () => requirePage(page, distDir, isAppPath)\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> {\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(\n join(/* turbopackIgnore: true */ distDir, BUILD_MANIFEST),\n manifestLoadAttempts\n ),\n tryLoadManifestWithRetries(\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(\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(\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>>(\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 loadRouteModule(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 loadRouteModule(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","loadRouteModule","isAppPath","getTracer","trace","LoadComponentsSpan","spanName","requirePage","loadComponentsImpl","isDev","sriEnabled","needsManifestsForLegacyReasons","DocumentMod","AppMod","Promise","all","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","wrap"],"mappings":";;;;;;;;;;;;;;;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MAAMpC,gBAAgBP,MAAMD,SAASS;QAE1D,MAAMoC,YAAYC,IAAAA,8BAAc,EAACF;QACjC,MAAMG,WAAWD,IAAAA,8BAAc,EAAC3B;QAChC,MAAM6B,MAAMF,IAAAA,8BAAc,EAAC1B;QAE3B,MAAM,EAAE6B,kBAAkB,EAAEC,cAAc,EAAEC,cAAc,EAAEC,WAAW,EAAE,GACvER;QAEF,OAAO;YACLI;YACAD;YACAF;YACAQ,YAAYT,aAAaU,MAAM,IAAI,CAAC;YACpCV;YACAK;YACAC;YACAC;YACA1C;YACAR;YACAmD;QACF,GAAS,uFAAuF;IAClG;AACF;AAEO,MAAM9D,iBAAiBoB,IAAAA,iBAAS,IAAG6C,IAAI,CAC5C3C,8BAAkB,CAACtB,cAAc,EACjCyB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/load-default-error-components.d.ts b/e-commerce/node_modules/next/dist/server/load-default-error-components.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..05f6b896e8f70b603ad9a5b3dfe78f526930af05 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/load-default-error-components.d.ts @@ -0,0 +1,12 @@ +import { type LoadComponentsReturnType } from './load-components'; +export type ManifestItem = { + id: number | string; + files: string[]; +}; +export type ReactLoadableManifest = { + [moduleId: string]: ManifestItem; +}; +export type ErrorModule = typeof import('./route-modules/pages/builtin/_error'); +declare function loadDefaultErrorComponentsImpl(distDir: string): Promise>; +export declare const loadDefaultErrorComponents: typeof loadDefaultErrorComponentsImpl; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/load-default-error-components.js b/e-commerce/node_modules/next/dist/server/load-default-error-components.js new file mode 100644 index 0000000000000000000000000000000000000000..155519535f3083ab7121d0cfcf84867b6acd2f54 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/load-default-error-components.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "loadDefaultErrorComponents", { + enumerable: true, + get: function() { + return loadDefaultErrorComponents; + } +}); +const _constants = require("../shared/lib/constants"); +const _path = require("path"); +const _interopdefault = require("../lib/interop-default"); +const _tracer = require("./lib/trace/tracer"); +const _constants1 = require("./lib/trace/constants"); +const _loadcomponents = require("./load-components"); +async function loadDefaultErrorComponentsImpl(distDir) { + // eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports? + const Document = (0, _interopdefault.interopDefault)(require('next/dist/pages/_document')); + // eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports? + const AppMod = require('next/dist/pages/_app'); + const App = (0, _interopdefault.interopDefault)(AppMod); + // Load the compiled route module for this builtin error. + // TODO: (wyattjoh) replace this with just exporting the route module when the transition is complete + const ComponentMod = require('./route-modules/pages/builtin/_error'); + const Component = ComponentMod.routeModule.userland.default; + return { + App, + Document, + Component, + pageConfig: {}, + buildManifest: await (0, _loadcomponents.loadManifestWithRetries)((0, _path.join)(distDir, `fallback-${_constants.BUILD_MANIFEST}`)), + reactLoadableManifest: {}, + ComponentMod, + page: '/_error', + routeModule: ComponentMod.routeModule + }; +} +const loadDefaultErrorComponents = (0, _tracer.getTracer)().wrap(_constants1.LoadComponentsSpan.loadDefaultErrorComponents, loadDefaultErrorComponentsImpl); + +//# sourceMappingURL=load-default-error-components.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/load-default-error-components.js.map b/e-commerce/node_modules/next/dist/server/load-default-error-components.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6f14f5a188697d0b273482362f5081b077bf6e14 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/load-default-error-components.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/load-default-error-components.ts"],"sourcesContent":["import type { BuildManifest } from './get-page-files'\n\nimport { BUILD_MANIFEST } from '../shared/lib/constants'\nimport { join } from 'path'\nimport { interopDefault } from '../lib/interop-default'\nimport { getTracer } from './lib/trace/tracer'\nimport { LoadComponentsSpan } from './lib/trace/constants'\nimport {\n loadManifestWithRetries,\n type LoadComponentsReturnType,\n} from './load-components'\nexport type ManifestItem = {\n id: number | string\n files: string[]\n}\n\nexport type ReactLoadableManifest = { [moduleId: string]: ManifestItem }\n\nexport type ErrorModule = typeof import('./route-modules/pages/builtin/_error')\n\nasync function loadDefaultErrorComponentsImpl(\n distDir: string\n): Promise> {\n // eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports?\n const Document = interopDefault(require('next/dist/pages/_document'))\n // eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports?\n const AppMod = require('next/dist/pages/_app')\n const App = interopDefault(AppMod)\n\n // Load the compiled route module for this builtin error.\n // TODO: (wyattjoh) replace this with just exporting the route module when the transition is complete\n const ComponentMod =\n require('./route-modules/pages/builtin/_error') as typeof import('./route-modules/pages/builtin/_error')\n const Component = ComponentMod.routeModule.userland.default\n\n return {\n App,\n Document,\n Component,\n pageConfig: {},\n buildManifest: (await loadManifestWithRetries(\n join(distDir, `fallback-${BUILD_MANIFEST}`)\n )) as BuildManifest,\n reactLoadableManifest: {},\n ComponentMod,\n page: '/_error',\n routeModule: ComponentMod.routeModule,\n }\n}\nexport const loadDefaultErrorComponents = getTracer().wrap(\n LoadComponentsSpan.loadDefaultErrorComponents,\n loadDefaultErrorComponentsImpl\n)\n"],"names":["loadDefaultErrorComponents","loadDefaultErrorComponentsImpl","distDir","Document","interopDefault","require","AppMod","App","ComponentMod","Component","routeModule","userland","default","pageConfig","buildManifest","loadManifestWithRetries","join","BUILD_MANIFEST","reactLoadableManifest","page","getTracer","wrap","LoadComponentsSpan"],"mappings":";;;;+BAiDaA;;;eAAAA;;;2BA/CkB;sBACV;gCACU;wBACL;4BACS;gCAI5B;AAUP,eAAeC,+BACbC,OAAe;IAEf,2FAA2F;IAC3F,MAAMC,WAAWC,IAAAA,8BAAc,EAACC,QAAQ;IACxC,2FAA2F;IAC3F,MAAMC,SAASD,QAAQ;IACvB,MAAME,MAAMH,IAAAA,8BAAc,EAACE;IAE3B,yDAAyD;IACzD,qGAAqG;IACrG,MAAME,eACJH,QAAQ;IACV,MAAMI,YAAYD,aAAaE,WAAW,CAACC,QAAQ,CAACC,OAAO;IAE3D,OAAO;QACLL;QACAJ;QACAM;QACAI,YAAY,CAAC;QACbC,eAAgB,MAAMC,IAAAA,uCAAuB,EAC3CC,IAAAA,UAAI,EAACd,SAAS,CAAC,SAAS,EAAEe,yBAAc,EAAE;QAE5CC,uBAAuB,CAAC;QACxBV;QACAW,MAAM;QACNT,aAAaF,aAAaE,WAAW;IACvC;AACF;AACO,MAAMV,6BAA6BoB,IAAAA,iBAAS,IAAGC,IAAI,CACxDC,8BAAkB,CAACtB,0BAA0B,EAC7CC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/load-manifest.external.d.ts b/e-commerce/node_modules/next/dist/server/load-manifest.external.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4725e3068d3b75ec1f4340fdf22b90c9e9511a8e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/load-manifest.external.d.ts @@ -0,0 +1,46 @@ +import type { DeepReadonly } from '../shared/lib/deep-readonly'; +/** + * Load a manifest file from the file system. Optionally cache the manifest in + * memory to avoid reading the file multiple times using the provided cache or + * defaulting to a shared module cache. The manifest is frozen to prevent + * modifications if it is cached. + * + * @param path the path to the manifest file + * @param shouldCache whether to cache the manifest in memory + * @param cache the cache to use for storing the manifest + * @returns the manifest object + */ +export declare function loadManifest(path: string, shouldCache: false): T; +export declare function loadManifest(path: string, shouldCache?: boolean, cache?: Map, skipParse?: boolean): DeepReadonly; +export declare function loadManifest(path: string, shouldCache?: boolean, cache?: Map, skipParse?: boolean, handleMissing?: boolean): DeepReadonly; +export declare function evalManifest(path: string, shouldCache: false): T; +export declare function evalManifest(path: string, shouldCache?: true, cache?: Map): DeepReadonly; +export declare function evalManifest(path: string, shouldCache?: boolean, cache?: Map, handleMissing?: boolean): DeepReadonly; +export declare function evalManifestFromRelativePath({ projectDir, distDir, manifest, shouldCache, cache, handleMissing, }: { + projectDir: string; + distDir: string; + manifest: string; + shouldCache: boolean; + cache?: Map; + skipParse?: boolean; + handleMissing?: boolean; +}): DeepReadonly; +export declare function loadManifestFromRelativePath({ projectDir, distDir, manifest, shouldCache, cache, skipParse, handleMissing, }: { + projectDir: string; + distDir: string; + manifest: string; + shouldCache: boolean; + cache?: Map; + skipParse?: boolean; + handleMissing?: false | undefined; +}): DeepReadonly; +export declare function loadManifestFromRelativePath({ projectDir, distDir, manifest, shouldCache, cache, skipParse, handleMissing, }: { + projectDir: string; + distDir: string; + manifest: string; + shouldCache: boolean; + cache?: Map; + skipParse?: boolean; + handleMissing: true; +}): DeepReadonly; +export declare function clearManifestCache(path: string, cache?: Map): boolean; diff --git a/e-commerce/node_modules/next/dist/server/load-manifest.external.js b/e-commerce/node_modules/next/dist/server/load-manifest.external.js new file mode 100644 index 0000000000000000000000000000000000000000..f6cc72ac616cd7076b1b32d19e12cba9291610b9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/load-manifest.external.js @@ -0,0 +1,116 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + clearManifestCache: null, + evalManifest: null, + evalManifestFromRelativePath: null, + loadManifest: null, + loadManifestFromRelativePath: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + clearManifestCache: function() { + return clearManifestCache; + }, + evalManifest: function() { + return evalManifest; + }, + evalManifestFromRelativePath: function() { + return evalManifestFromRelativePath; + }, + loadManifest: function() { + return loadManifest; + }, + loadManifestFromRelativePath: function() { + return loadManifestFromRelativePath; + } +}); +const _path = require("path"); +const _fs = require("fs"); +const _vm = require("vm"); +const _deepfreeze = require("../shared/lib/deep-freeze"); +const sharedCache = new Map(); +function loadManifest(path, shouldCache = true, cache = sharedCache, skipParse = false, handleMissing) { + if (shouldCache && cache.has(path)) { + return cache.get(path); + } + let manifest; + if (handleMissing) { + try { + manifest = (0, _fs.readFileSync)(/* turbopackIgnore: true */ path, 'utf8'); + } catch (err) { + let result = undefined; + cache.set(path, result); + return result; + } + } else { + manifest = (0, _fs.readFileSync)(/* turbopackIgnore: true */ path, 'utf8'); + } + if (!skipParse) { + manifest = JSON.parse(manifest); + // Freeze the manifest so it cannot be modified if we're caching it. + if (shouldCache) { + manifest = (0, _deepfreeze.deepFreeze)(manifest); + } + } + if (shouldCache) { + cache.set(path, manifest); + } + return manifest; +} +function evalManifest(path, shouldCache = true, cache = sharedCache, handleMissing) { + if (shouldCache && cache.has(path)) { + return cache.get(path); + } + let content; + if (handleMissing) { + try { + content = (0, _fs.readFileSync)(/* turbopackIgnore: true */ path, 'utf8'); + } catch (err) { + let result = undefined; + cache.set(path, result); + return result; + } + } else { + content = (0, _fs.readFileSync)(/* turbopackIgnore: true */ path, 'utf8'); + } + if (content.length === 0) { + throw new Error('Manifest file is empty'); + } + let contextObject = { + process: { + env: { + NEXT_DEPLOYMENT_ID: process.env.NEXT_DEPLOYMENT_ID + } + } + }; + (0, _vm.runInNewContext)(content, contextObject); + // Freeze the context object so it cannot be modified if we're caching it. + if (shouldCache) { + contextObject = (0, _deepfreeze.deepFreeze)(contextObject); + } + if (shouldCache) { + cache.set(path, contextObject); + } + return contextObject; +} +function evalManifestFromRelativePath({ projectDir, distDir, manifest, shouldCache, cache, handleMissing }) { + const manifestPath = (0, _path.join)(/* turbopackIgnore: true */ projectDir, distDir, manifest); + return evalManifest(manifestPath, shouldCache, cache, handleMissing); +} +function loadManifestFromRelativePath({ projectDir, distDir, manifest, shouldCache, cache, skipParse, handleMissing }) { + const manifestPath = (0, _path.join)(/* turbopackIgnore: true */ projectDir, distDir, manifest); + return loadManifest(manifestPath, shouldCache, cache, skipParse, handleMissing); +} +function clearManifestCache(path, cache = sharedCache) { + return cache.delete(path); +} + +//# sourceMappingURL=load-manifest.external.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/load-manifest.external.js.map b/e-commerce/node_modules/next/dist/server/load-manifest.external.js.map new file mode 100644 index 0000000000000000000000000000000000000000..afc39a0eadb0476d52adba885c3b96ac1d4d23d6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/load-manifest.external.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/load-manifest.external.ts"],"sourcesContent":["import type { DeepReadonly } from '../shared/lib/deep-readonly'\n\nimport { join } from 'path'\nimport { readFileSync } from 'fs'\nimport { runInNewContext } from 'vm'\nimport { deepFreeze } from '../shared/lib/deep-freeze'\n\nconst sharedCache = new Map()\n\n/**\n * Load a manifest file from the file system. Optionally cache the manifest in\n * memory to avoid reading the file multiple times using the provided cache or\n * defaulting to a shared module cache. The manifest is frozen to prevent\n * modifications if it is cached.\n *\n * @param path the path to the manifest file\n * @param shouldCache whether to cache the manifest in memory\n * @param cache the cache to use for storing the manifest\n * @returns the manifest object\n */\nexport function loadManifest(\n path: string,\n shouldCache: false\n): T\nexport function loadManifest(\n path: string,\n shouldCache?: boolean,\n cache?: Map,\n skipParse?: boolean\n): DeepReadonly\nexport function loadManifest(\n path: string,\n shouldCache?: boolean,\n cache?: Map,\n skipParse?: boolean,\n handleMissing?: boolean\n): DeepReadonly\nexport function loadManifest(\n path: string,\n shouldCache: boolean = true,\n cache = sharedCache,\n skipParse = false,\n handleMissing?: boolean\n): T | undefined {\n if (shouldCache && cache.has(path)) {\n return cache.get(path) as T\n }\n\n let manifest: any\n\n if (handleMissing) {\n try {\n manifest = readFileSync(/* turbopackIgnore: true */ path, 'utf8')\n } catch (err) {\n let result = undefined\n cache.set(path, result)\n return result\n }\n } else {\n manifest = readFileSync(/* turbopackIgnore: true */ path, 'utf8')\n }\n\n if (!skipParse) {\n manifest = JSON.parse(manifest)\n\n // Freeze the manifest so it cannot be modified if we're caching it.\n if (shouldCache) {\n manifest = deepFreeze(manifest)\n }\n }\n\n if (shouldCache) {\n cache.set(path, manifest)\n }\n\n return manifest\n}\n\nexport function evalManifest(\n path: string,\n shouldCache: false\n): T\nexport function evalManifest(\n path: string,\n shouldCache?: true,\n cache?: Map\n): DeepReadonly\nexport function evalManifest(\n path: string,\n shouldCache?: boolean,\n cache?: Map,\n handleMissing?: boolean\n): DeepReadonly\nexport function evalManifest(\n path: string,\n shouldCache: boolean = true,\n cache = sharedCache,\n handleMissing?: boolean\n): T | undefined {\n if (shouldCache && cache.has(path)) {\n return cache.get(path) as T\n }\n\n let content: any\n if (handleMissing) {\n try {\n content = readFileSync(/* turbopackIgnore: true */ path, 'utf8')\n } catch (err) {\n let result = undefined\n cache.set(path, result)\n return result\n }\n } else {\n content = readFileSync(/* turbopackIgnore: true */ path, 'utf8')\n }\n\n if (content.length === 0) {\n throw new Error('Manifest file is empty')\n }\n\n let contextObject = {\n process: { env: { NEXT_DEPLOYMENT_ID: process.env.NEXT_DEPLOYMENT_ID } },\n }\n runInNewContext(content, contextObject)\n\n // Freeze the context object so it cannot be modified if we're caching it.\n if (shouldCache) {\n contextObject = deepFreeze(contextObject)\n }\n\n if (shouldCache) {\n cache.set(path, contextObject)\n }\n\n return contextObject as T\n}\n\nexport function evalManifestFromRelativePath({\n projectDir,\n distDir,\n manifest,\n shouldCache,\n cache,\n handleMissing,\n}: {\n projectDir: string\n distDir: string\n manifest: string\n shouldCache: boolean\n cache?: Map\n skipParse?: boolean\n handleMissing?: boolean\n}): DeepReadonly {\n const manifestPath = join(\n /* turbopackIgnore: true */ projectDir,\n distDir,\n manifest\n )\n return evalManifest(manifestPath, shouldCache, cache, handleMissing)\n}\n\nexport function loadManifestFromRelativePath({\n projectDir,\n distDir,\n manifest,\n shouldCache,\n cache,\n skipParse,\n handleMissing,\n}: {\n projectDir: string\n distDir: string\n manifest: string\n shouldCache: boolean\n cache?: Map\n skipParse?: boolean\n handleMissing?: false | undefined\n}): DeepReadonly\nexport function loadManifestFromRelativePath({\n projectDir,\n distDir,\n manifest,\n shouldCache,\n cache,\n skipParse,\n handleMissing,\n}: {\n projectDir: string\n distDir: string\n manifest: string\n shouldCache: boolean\n cache?: Map\n skipParse?: boolean\n handleMissing: true\n}): DeepReadonly\nexport function loadManifestFromRelativePath({\n projectDir,\n distDir,\n manifest,\n shouldCache,\n cache,\n skipParse,\n handleMissing,\n}: {\n projectDir: string\n distDir: string\n manifest: string\n shouldCache: boolean\n cache?: Map\n skipParse?: boolean\n handleMissing?: boolean\n}): DeepReadonly {\n const manifestPath = join(\n /* turbopackIgnore: true */ projectDir,\n distDir,\n manifest\n )\n return loadManifest(\n manifestPath,\n shouldCache,\n cache,\n skipParse,\n handleMissing\n )\n}\n\nexport function clearManifestCache(path: string, cache = sharedCache): boolean {\n return cache.delete(path)\n}\n"],"names":["clearManifestCache","evalManifest","evalManifestFromRelativePath","loadManifest","loadManifestFromRelativePath","sharedCache","Map","path","shouldCache","cache","skipParse","handleMissing","has","get","manifest","readFileSync","err","result","undefined","set","JSON","parse","deepFreeze","content","length","Error","contextObject","process","env","NEXT_DEPLOYMENT_ID","runInNewContext","projectDir","distDir","manifestPath","join","delete"],"mappings":";;;;;;;;;;;;;;;;;;IAkOgBA,kBAAkB;eAAlBA;;IArIAC,YAAY;eAAZA;;IA4CAC,4BAA4B;eAA5BA;;IApGAC,YAAY;eAAZA;;IA8JAC,4BAA4B;eAA5BA;;;sBAjMK;oBACQ;oBACG;4BACL;AAE3B,MAAMC,cAAc,IAAIC;AA8BjB,SAASH,aACdI,IAAY,EACZC,cAAuB,IAAI,EAC3BC,QAAQJ,WAAW,EACnBK,YAAY,KAAK,EACjBC,aAAuB;IAEvB,IAAIH,eAAeC,MAAMG,GAAG,CAACL,OAAO;QAClC,OAAOE,MAAMI,GAAG,CAACN;IACnB;IAEA,IAAIO;IAEJ,IAAIH,eAAe;QACjB,IAAI;YACFG,WAAWC,IAAAA,gBAAY,EAAC,yBAAyB,GAAGR,MAAM;QAC5D,EAAE,OAAOS,KAAK;YACZ,IAAIC,SAASC;YACbT,MAAMU,GAAG,CAACZ,MAAMU;YAChB,OAAOA;QACT;IACF,OAAO;QACLH,WAAWC,IAAAA,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H,YAC5BC,SACAlB;IAEF,OAAOb,aAAgBgC,cAAczB,aAAaC,OAAOE;AAC3D;AAoCO,SAASP,6BAA+C,EAC7D2B,UAAU,EACVC,OAAO,EACPlB,QAAQ,EACRN,WAAW,EACXC,KAAK,EACLC,SAAS,EACTC,aAAa,EASd;IACC,MAAMsB,eAAeC,IAAAA,UAAI,EACvB,yBAAyB,GAAGH,YAC5BC,SACAlB;IAEF,OAAOX,aACL8B,cACAzB,aACAC,OACAC,WACAC;AAEJ;AAEO,SAASX,mBAAmBO,IAAY,EAAEE,QAAQJ,WAAW;IAClE,OAAOI,MAAM0B,MAAM,CAAC5B;AACtB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/match-bundle.d.ts b/e-commerce/node_modules/next/dist/server/match-bundle.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ccf803e7fad810d63e5f9c27de7492588781af52 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/match-bundle.d.ts @@ -0,0 +1 @@ +export default function matchBundle(regex: RegExp, input: string): string | null; diff --git a/e-commerce/node_modules/next/dist/server/match-bundle.js b/e-commerce/node_modules/next/dist/server/match-bundle.js new file mode 100644 index 0000000000000000000000000000000000000000..a9d5cf07e98a8e535e10098a7f41b592f10e7c88 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/match-bundle.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return matchBundle; + } +}); +const _getroutefromassetpath = /*#__PURE__*/ _interop_require_default(require("../shared/lib/router/utils/get-route-from-asset-path")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function matchBundle(regex, input) { + const result = regex.exec(input); + if (!result) { + return null; + } + return (0, _getroutefromassetpath.default)(`/${result[1]}`); +} + +//# sourceMappingURL=match-bundle.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/match-bundle.js.map b/e-commerce/node_modules/next/dist/server/match-bundle.js.map new file mode 100644 index 0000000000000000000000000000000000000000..013db665dd3fa52d1d4658e7ef40058b41bb5d8d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/match-bundle.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/match-bundle.ts"],"sourcesContent":["import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path'\n\nexport default function matchBundle(\n regex: RegExp,\n input: string\n): string | null {\n const result = regex.exec(input)\n\n if (!result) {\n return null\n }\n\n return getRouteFromAssetPath(`/${result[1]}`)\n}\n"],"names":["matchBundle","regex","input","result","exec","getRouteFromAssetPath"],"mappings":";;;;+BAEA;;;eAAwBA;;;8EAFU;;;;;;AAEnB,SAASA,YACtBC,KAAa,EACbC,KAAa;IAEb,MAAMC,SAASF,MAAMG,IAAI,CAACF;IAE1B,IAAI,CAACC,QAAQ;QACX,OAAO;IACT;IAEA,OAAOE,IAAAA,8BAAqB,EAAC,CAAC,CAAC,EAAEF,MAAM,CAAC,EAAE,EAAE;AAC9C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/get-mcp-middleware.d.ts b/e-commerce/node_modules/next/dist/server/mcp/get-mcp-middleware.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eeee240a30b5d972e3babe16381404cfff610f60 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/get-mcp-middleware.d.ts @@ -0,0 +1,3 @@ +import type { ServerResponse, IncomingMessage } from 'http'; +import { type McpServerOptions } from './get-or-create-mcp-server'; +export declare function getMcpMiddleware(options: McpServerOptions): (req: IncomingMessage, res: ServerResponse, next: () => void) => Promise; diff --git a/e-commerce/node_modules/next/dist/server/mcp/get-mcp-middleware.js b/e-commerce/node_modules/next/dist/server/mcp/get-mcp-middleware.js new file mode 100644 index 0000000000000000000000000000000000000000..6361a8a5fd0df66803b3ad7ca6fc9637d3d3028b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/get-mcp-middleware.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getMcpMiddleware", { + enumerable: true, + get: function() { + return getMcpMiddleware; + } +}); +const _getorcreatemcpserver = require("./get-or-create-mcp-server"); +const _parsebody = require("../api-utils/node/parse-body"); +const _parsepath = require("../../shared/lib/router/utils/parse-path"); +const _removetrailingslash = require("../../shared/lib/router/utils/remove-trailing-slash"); +const _streamableHttp = require("next/dist/compiled/@modelcontextprotocol/sdk/server/streamableHttp"); +function getMcpMiddleware(options) { + return async function(req, res, next) { + const { pathname } = (0, _parsepath.parsePath)(req.url || ''); + if ((0, _removetrailingslash.removeTrailingSlash)(pathname) !== '/_next/mcp') { + return next(); + } + const mcpServer = (0, _getorcreatemcpserver.getOrCreateMcpServer)(options); + const transport = new _streamableHttp.StreamableHTTPServerTransport({ + sessionIdGenerator: undefined + }); + try { + res.on('close', ()=>{ + transport.close(); + }); + await mcpServer.connect(transport); + const parsedBody = await (0, _parsebody.parseBody)(req, 1024 * 1024) // 1MB limit + ; + await transport.handleRequest(req, res, parsedBody); + } catch (error) { + if (!res.headersSent) { + res.statusCode = 500; + res.setHeader('Content-Type', 'application/json; charset=utf-8'); + res.end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Internal server error' + }, + id: null + })); + } + } + }; +} + +//# sourceMappingURL=get-mcp-middleware.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/get-mcp-middleware.js.map b/e-commerce/node_modules/next/dist/server/mcp/get-mcp-middleware.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8fd927567cba16163db395955ac3a945809a848c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/get-mcp-middleware.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/mcp/get-mcp-middleware.ts"],"sourcesContent":["import type { ServerResponse, IncomingMessage } from 'http'\nimport {\n getOrCreateMcpServer,\n type McpServerOptions,\n} from './get-or-create-mcp-server'\nimport { parseBody } from '../api-utils/node/parse-body'\nimport { parsePath } from '../../shared/lib/router/utils/parse-path'\nimport { removeTrailingSlash } from '../../shared/lib/router/utils/remove-trailing-slash'\nimport { StreamableHTTPServerTransport } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/streamableHttp'\n\nexport function getMcpMiddleware(options: McpServerOptions) {\n return async function (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void\n ): Promise {\n const { pathname } = parsePath(req.url || '')\n if (removeTrailingSlash(pathname) !== '/_next/mcp') {\n return next()\n }\n const mcpServer = getOrCreateMcpServer(options)\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n })\n try {\n res.on('close', () => {\n transport.close()\n })\n await mcpServer.connect(transport)\n const parsedBody = await parseBody(req, 1024 * 1024) // 1MB limit\n await transport.handleRequest(req, res, parsedBody)\n } catch (error) {\n if (!res.headersSent) {\n res.statusCode = 500\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: { code: -32000, message: 'Internal server error' },\n id: null,\n })\n )\n }\n }\n }\n}\n"],"names":["getMcpMiddleware","options","req","res","next","pathname","parsePath","url","removeTrailingSlash","mcpServer","getOrCreateMcpServer","transport","StreamableHTTPServerTransport","sessionIdGenerator","undefined","on","close","connect","parsedBody","parseBody","handleRequest","error","headersSent","statusCode","setHeader","end","JSON","stringify","jsonrpc","code","message","id"],"mappings":";;;;+BAUgBA;;;eAAAA;;;sCANT;2BACmB;2BACA;qCACU;gCACU;AAEvC,SAASA,iBAAiBC,OAAyB;IACxD,OAAO,eACLC,GAAoB,EACpBC,GAAmB,EACnBC,IAAgB;QAEhB,MAAM,EAAEC,QAAQ,EAAE,GAAGC,IAAAA,oBAAS,EAACJ,IAAIK,GAAG,IAAI;QAC1C,IAAIC,IAAAA,wCAAmB,EAACH,cAAc,cAAc;YAClD,OAAOD;QACT;QACA,MAAMK,YAAYC,IAAAA,0CAAoB,EAACT;QACvC,MAAMU,YAAY,IAAIC,6CAA6B,CAAC;YAClDC,oBAAoBC;QACtB;QACA,IAAI;YACFX,IAAIY,EAAE,CAAC,SAAS;gBACdJ,UAAUK,KAAK;YACjB;YACA,MAAMP,UAAUQ,OAAO,CAACN;YACxB,MAAMO,aAAa,MAAMC,IAAAA,oBAAS,EAACjB,KAAK,OAAO,MAAM,YAAY;;YACjE,MAAMS,UAAUS,aAAa,CAAClB,KAAKC,KAAKe;QAC1C,EAAE,OAAOG,OAAO;YACd,IAAI,CAAClB,IAAImB,WAAW,EAAE;gBACpBnB,IAAIoB,UAAU,GAAG;gBACjBpB,IAAIqB,SAAS,CAAC,gBAAgB;gBAC9BrB,IAAIsB,GAAG,CACLC,KAAKC,SAAS,CAAC;oBACbC,SAAS;oBACTP,OAAO;wBAAEQ,MAAM,CAAC;wBAAOC,SAAS;oBAAwB;oBACxDC,IAAI;gBACN;YAEJ;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/get-or-create-mcp-server.d.ts b/e-commerce/node_modules/next/dist/server/mcp/get-or-create-mcp-server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8128392c1da24f23d9c09ede67eb954876897ac0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/get-or-create-mcp-server.d.ts @@ -0,0 +1,24 @@ +import { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'; +import type { HmrMessageSentToBrowser } from '../dev/hot-reloader-types'; +import type { NextConfigComplete } from '../config-shared'; +import type { Project } from '../../build/swc/types'; +import type { FormattedIssue } from './tools/utils/format-compilation-issues'; +export interface McpServerOptions { + projectPath: string; + distDir: string; + nextConfig: NextConfigComplete; + pagesDir: string | undefined; + appDir: string | undefined; + sendHmrMessage: (message: HmrMessageSentToBrowser) => void; + getActiveConnectionCount: () => number; + getDevServerUrl: () => string | undefined; + getTurbopackProject?: () => Project | undefined; + compileRoute?: (opts: { + routeSpecifier?: string; + path?: string; + }) => Promise<{ + routeSpecifier: string; + issues: FormattedIssue[]; + }>; +} +export declare const getOrCreateMcpServer: (options: McpServerOptions) => McpServer; diff --git a/e-commerce/node_modules/next/dist/server/mcp/get-or-create-mcp-server.js b/e-commerce/node_modules/next/dist/server/mcp/get-or-create-mcp-server.js new file mode 100644 index 0000000000000000000000000000000000000000..c4b1b48ce44f1afbc6bae012c8bb2971c9c84d80 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/get-or-create-mcp-server.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getOrCreateMcpServer", { + enumerable: true, + get: function() { + return getOrCreateMcpServer; + } +}); +const _mcp = require("next/dist/compiled/@modelcontextprotocol/sdk/server/mcp"); +const _getprojectmetadata = require("./tools/get-project-metadata"); +const _geterrors = require("./tools/get-errors"); +const _getpagemetadata = require("./tools/get-page-metadata"); +const _getlogs = require("./tools/get-logs"); +const _getserveractionbyid = require("./tools/get-server-action-by-id"); +const _getroutes = require("./tools/get-routes"); +const _getcompilationissues = require("./tools/get-compilation-issues"); +const _compileroute = require("./tools/compile-route"); +const _getrequestinsights = require("./tools/get-request-insights"); +let mcpServer; +const getOrCreateMcpServer = (options)=>{ + if (mcpServer) { + return mcpServer; + } + mcpServer = new _mcp.McpServer({ + name: 'Next.js MCP Server', + version: '0.2.0' + }); + (0, _getprojectmetadata.registerGetProjectMetadataTool)(mcpServer, options.projectPath, options.getDevServerUrl); + (0, _geterrors.registerGetErrorsTool)(mcpServer, options.sendHmrMessage, options.getActiveConnectionCount); + (0, _getpagemetadata.registerGetPageMetadataTool)(mcpServer, options.sendHmrMessage, options.getActiveConnectionCount); + (0, _getlogs.registerGetLogsTool)(mcpServer, options.distDir); + (0, _getserveractionbyid.registerGetActionByIdTool)(mcpServer, options.distDir); + (0, _getroutes.registerGetRoutesTool)(mcpServer, { + projectPath: options.projectPath, + nextConfig: options.nextConfig, + pagesDir: options.pagesDir, + appDir: options.appDir + }); + (0, _getrequestinsights.registerGetRequestInsightsTool)(mcpServer); + if (options.getTurbopackProject) { + (0, _getcompilationissues.registerGetCompilationIssuesTool)(mcpServer, options.getTurbopackProject); + } + if (options.compileRoute) { + (0, _compileroute.registerCompileRouteTool)(mcpServer, options.compileRoute); + } + return mcpServer; +}; + +//# sourceMappingURL=get-or-create-mcp-server.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/get-or-create-mcp-server.js.map b/e-commerce/node_modules/next/dist/server/mcp/get-or-create-mcp-server.js.map new file mode 100644 index 0000000000000000000000000000000000000000..82da4638df4edaec62fc617df21d1abf0647aa0a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/get-or-create-mcp-server.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/mcp/get-or-create-mcp-server.ts"],"sourcesContent":["import { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'\nimport { registerGetProjectMetadataTool } from './tools/get-project-metadata'\nimport { registerGetErrorsTool } from './tools/get-errors'\nimport { registerGetPageMetadataTool } from './tools/get-page-metadata'\nimport { registerGetLogsTool } from './tools/get-logs'\nimport { registerGetActionByIdTool } from './tools/get-server-action-by-id'\nimport { registerGetRoutesTool } from './tools/get-routes'\nimport { registerGetCompilationIssuesTool } from './tools/get-compilation-issues'\nimport { registerCompileRouteTool } from './tools/compile-route'\nimport { registerGetRequestInsightsTool } from './tools/get-request-insights'\nimport type { HmrMessageSentToBrowser } from '../dev/hot-reloader-types'\nimport type { NextConfigComplete } from '../config-shared'\nimport type { Project } from '../../build/swc/types'\nimport type { FormattedIssue } from './tools/utils/format-compilation-issues'\n\nexport interface McpServerOptions {\n projectPath: string\n distDir: string\n nextConfig: NextConfigComplete\n pagesDir: string | undefined\n appDir: string | undefined\n sendHmrMessage: (message: HmrMessageSentToBrowser) => void\n getActiveConnectionCount: () => number\n getDevServerUrl: () => string | undefined\n getTurbopackProject?: () => Project | undefined\n compileRoute?: (opts: {\n routeSpecifier?: string\n path?: string\n }) => Promise<{ routeSpecifier: string; issues: FormattedIssue[] }>\n}\n\nlet mcpServer: McpServer | undefined\n\nexport const getOrCreateMcpServer = (options: McpServerOptions) => {\n if (mcpServer) {\n return mcpServer\n }\n\n mcpServer = new McpServer({\n name: 'Next.js MCP Server',\n version: '0.2.0',\n })\n\n registerGetProjectMetadataTool(\n mcpServer,\n options.projectPath,\n options.getDevServerUrl\n )\n registerGetErrorsTool(\n mcpServer,\n options.sendHmrMessage,\n options.getActiveConnectionCount\n )\n registerGetPageMetadataTool(\n mcpServer,\n options.sendHmrMessage,\n options.getActiveConnectionCount\n )\n registerGetLogsTool(mcpServer, options.distDir)\n registerGetActionByIdTool(mcpServer, options.distDir)\n registerGetRoutesTool(mcpServer, {\n projectPath: options.projectPath,\n nextConfig: options.nextConfig,\n pagesDir: options.pagesDir,\n appDir: options.appDir,\n })\n registerGetRequestInsightsTool(mcpServer)\n\n if (options.getTurbopackProject) {\n registerGetCompilationIssuesTool(mcpServer, options.getTurbopackProject)\n }\n\n if (options.compileRoute) {\n registerCompileRouteTool(mcpServer, options.compileRoute)\n }\n\n return mcpServer\n}\n"],"names":["getOrCreateMcpServer","mcpServer","options","McpServer","name","version","registerGetProjectMetadataTool","projectPath","getDevServerUrl","registerGetErrorsTool","sendHmrMessage","getActiveConnectionCount","registerGetPageMetadataTool","registerGetLogsTool","distDir","registerGetActionByIdTool","registerGetRoutesTool","nextConfig","pagesDir","appDir","registerGetRequestInsightsTool","getTurbopackProject","registerGetCompilationIssuesTool","compileRoute","registerCompileRouteTool"],"mappings":";;;;+BAiCaA;;;eAAAA;;;qBAjCa;oCACqB;2BACT;iCACM;yBACR;qCACM;2BACJ;sCACW;8BACR;oCACM;AAsB/C,IAAIC;AAEG,MAAMD,uBAAuB,CAACE;IACnC,IAAID,WAAW;QACb,OAAOA;IACT;IAEAA,YAAY,IAAIE,cAAS,CAAC;QACxBC,MAAM;QACNC,SAAS;IACX;IAEAC,IAAAA,kDAA8B,EAC5BL,WACAC,QAAQK,WAAW,EACnBL,QAAQM,eAAe;IAEzBC,IAAAA,gCAAqB,EACnBR,WACAC,QAAQQ,cAAc,EACtBR,QAAQS,wBAAwB;IAElCC,IAAAA,4CAA2B,EACzBX,WACAC,QAAQQ,cAAc,EACtBR,QAAQS,wBAAwB;IAElCE,IAAAA,4BAAmB,EAACZ,WAAWC,QAAQY,OAAO;IAC9CC,IAAAA,8CAAyB,EAACd,WAAWC,QAAQY,OAAO;IACpDE,IAAAA,gCAAqB,EAACf,WAAW;QAC/BM,aAAaL,QAAQK,WAAW;QAChCU,YAAYf,QAAQe,UAAU;QAC9BC,UAAUhB,QAAQgB,QAAQ;QAC1BC,QAAQjB,QAAQiB,MAAM;IACxB;IACAC,IAAAA,kDAA8B,EAACnB;IAE/B,IAAIC,QAAQmB,mBAAmB,EAAE;QAC/BC,IAAAA,sDAAgC,EAACrB,WAAWC,QAAQmB,mBAAmB;IACzE;IAEA,IAAInB,QAAQqB,YAAY,EAAE;QACxBC,IAAAA,sCAAwB,EAACvB,WAAWC,QAAQqB,YAAY;IAC1D;IAEA,OAAOtB;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/mcp-telemetry-tracker.d.ts b/e-commerce/node_modules/next/dist/server/mcp/mcp-telemetry-tracker.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ae4bf2f89379d735d12cc4d5f1d097411ee17f0d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/mcp-telemetry-tracker.d.ts @@ -0,0 +1,44 @@ +/** + * Telemetry tracker for MCP tool call usage. + * Tracks invocation counts for each MCP tool to be reported via telemetry. + */ +import type { McpToolName } from '../../telemetry/events/build'; +export interface McpToolUsage { + featureName: McpToolName; + invocationCount: number; +} +declare class McpTelemetryTracker { + private usageMap; + /** + * Record a tool call invocation + */ + recordToolCall(toolName: McpToolName): void; + /** + * Get all tool usages as an array + */ + getUsages(): McpToolUsage[]; + /** + * Reset all usage tracking + */ + reset(): void; + /** + * Check if any tools have been called + */ + hasUsage(): boolean; +} +export declare const mcpTelemetryTracker: McpTelemetryTracker; +/** + * Get MCP tool usage telemetry + */ +export declare function getMcpTelemetryUsage(): McpToolUsage[]; +/** + * Reset MCP telemetry tracker + */ +export declare function resetMcpTelemetry(): void; +/** + * Record MCP telemetry usage to the telemetry instance + */ +export declare function recordMcpTelemetry(telemetry: { + record: (event: any) => void; +}): void; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/mcp/mcp-telemetry-tracker.js b/e-commerce/node_modules/next/dist/server/mcp/mcp-telemetry-tracker.js new file mode 100644 index 0000000000000000000000000000000000000000..bdb288a0bdeaaa01a340611d25dbe6e949ded53b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/mcp-telemetry-tracker.js @@ -0,0 +1,82 @@ +/** + * Telemetry tracker for MCP tool call usage. + * Tracks invocation counts for each MCP tool to be reported via telemetry. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getMcpTelemetryUsage: null, + mcpTelemetryTracker: null, + recordMcpTelemetry: null, + resetMcpTelemetry: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getMcpTelemetryUsage: function() { + return getMcpTelemetryUsage; + }, + mcpTelemetryTracker: function() { + return mcpTelemetryTracker; + }, + recordMcpTelemetry: function() { + return recordMcpTelemetry; + }, + resetMcpTelemetry: function() { + return resetMcpTelemetry; + } +}); +class McpTelemetryTracker { + /** + * Record a tool call invocation + */ recordToolCall(toolName) { + const current = this.usageMap.get(toolName) || 0; + this.usageMap.set(toolName, current + 1); + } + /** + * Get all tool usages as an array + */ getUsages() { + return Array.from(this.usageMap.entries()).map(([featureName, count])=>({ + featureName, + invocationCount: count + })); + } + /** + * Reset all usage tracking + */ reset() { + this.usageMap.clear(); + } + /** + * Check if any tools have been called + */ hasUsage() { + return this.usageMap.size > 0; + } + constructor(){ + this.usageMap = new Map(); + } +} +const mcpTelemetryTracker = new McpTelemetryTracker(); +function getMcpTelemetryUsage() { + return mcpTelemetryTracker.getUsages(); +} +function resetMcpTelemetry() { + mcpTelemetryTracker.reset(); +} +function recordMcpTelemetry(telemetry) { + const mcpUsages = getMcpTelemetryUsage(); + if (mcpUsages.length === 0) { + return; + } + const { eventMcpToolUsage } = require('../../telemetry/events/build'); + const events = eventMcpToolUsage(mcpUsages); + for (const event of events){ + telemetry.record(event); + } +} + +//# sourceMappingURL=mcp-telemetry-tracker.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/mcp-telemetry-tracker.js.map b/e-commerce/node_modules/next/dist/server/mcp/mcp-telemetry-tracker.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8157a1af0897456b187c1d14c3166de1e21b554f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/mcp-telemetry-tracker.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/mcp/mcp-telemetry-tracker.ts"],"sourcesContent":["/**\n * Telemetry tracker for MCP tool call usage.\n * Tracks invocation counts for each MCP tool to be reported via telemetry.\n */\n\nimport type { McpToolName } from '../../telemetry/events/build'\n\nexport interface McpToolUsage {\n featureName: McpToolName\n invocationCount: number\n}\n\nclass McpTelemetryTracker {\n private usageMap = new Map()\n\n /**\n * Record a tool call invocation\n */\n recordToolCall(toolName: McpToolName): void {\n const current = this.usageMap.get(toolName) || 0\n this.usageMap.set(toolName, current + 1)\n }\n\n /**\n * Get all tool usages as an array\n */\n getUsages(): McpToolUsage[] {\n return Array.from(this.usageMap.entries()).map(([featureName, count]) => ({\n featureName,\n invocationCount: count,\n }))\n }\n\n /**\n * Reset all usage tracking\n */\n reset(): void {\n this.usageMap.clear()\n }\n\n /**\n * Check if any tools have been called\n */\n hasUsage(): boolean {\n return this.usageMap.size > 0\n }\n}\n\n// Singleton instance\nexport const mcpTelemetryTracker = new McpTelemetryTracker()\n\n/**\n * Get MCP tool usage telemetry\n */\nexport function getMcpTelemetryUsage(): McpToolUsage[] {\n return mcpTelemetryTracker.getUsages()\n}\n\n/**\n * Reset MCP telemetry tracker\n */\nexport function resetMcpTelemetry(): void {\n mcpTelemetryTracker.reset()\n}\n\n/**\n * Record MCP telemetry usage to the telemetry instance\n */\nexport function recordMcpTelemetry(telemetry: {\n record: (event: any) => void\n}): void {\n const mcpUsages = getMcpTelemetryUsage()\n if (mcpUsages.length === 0) {\n return\n }\n\n const { eventMcpToolUsage } =\n require('../../telemetry/events/build') as typeof import('../../telemetry/events/build')\n const events = eventMcpToolUsage(mcpUsages)\n for (const event of events) {\n telemetry.record(event)\n }\n}\n"],"names":["getMcpTelemetryUsage","mcpTelemetryTracker","recordMcpTelemetry","resetMcpTelemetry","McpTelemetryTracker","recordToolCall","toolName","current","usageMap","get","set","getUsages","Array","from","entries","map","featureName","count","invocationCount","reset","clear","hasUsage","size","Map","telemetry","mcpUsages","length","eventMcpToolUsage","require","events","event","record"],"mappings":"AAAA;;;CAGC;;;;;;;;;;;;;;;;;IAmDeA,oBAAoB;eAApBA;;IALHC,mBAAmB;eAAnBA;;IAmBGC,kBAAkB;eAAlBA;;IAPAC,iBAAiB;eAAjBA;;;AAjDhB,MAAMC;IAGJ;;GAEC,GACDC,eAAeC,QAAqB,EAAQ;QAC1C,MAAMC,UAAU,IAAI,CAACC,QAAQ,CAACC,GAAG,CAACH,aAAa;QAC/C,IAAI,CAACE,QAAQ,CAACE,GAAG,CAACJ,UAAUC,UAAU;IACxC;IAEA;;GAEC,GACDI,YAA4B;QAC1B,OAAOC,MAAMC,IAAI,CAAC,IAAI,CAACL,QAAQ,CAACM,OAAO,IAAIC,GAAG,CAAC,CAAC,CAACC,aAAaC,MAAM,GAAM,CAAA;gBACxED;gBACAE,iBAAiBD;YACnB,CAAA;IACF;IAEA;;GAEC,GACDE,QAAc;QACZ,IAAI,CAACX,QAAQ,CAACY,KAAK;IACrB;IAEA;;GAEC,GACDC,WAAoB;QAClB,OAAO,IAAI,CAACb,QAAQ,CAACc,IAAI,GAAG;IAC9B;;aAhCQd,WAAW,IAAIe;;AAiCzB;AAGO,MAAMtB,sBAAsB,IAAIG;AAKhC,SAASJ;IACd,OAAOC,oBAAoBU,SAAS;AACtC;AAKO,SAASR;IACdF,oBAAoBkB,KAAK;AAC3B;AAKO,SAASjB,mBAAmBsB,SAElC;IACC,MAAMC,YAAYzB;IAClB,IAAIyB,UAAUC,MAAM,KAAK,GAAG;QAC1B;IACF;IAEA,MAAM,EAAEC,iBAAiB,EAAE,GACzBC,QAAQ;IACV,MAAMC,SAASF,kBAAkBF;IACjC,KAAK,MAAMK,SAASD,OAAQ;QAC1BL,UAAUO,MAAM,CAACD;IACnB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/compile-route.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/compile-route.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..100cf17f975ea3232be663bb4b9aa2ff0f14c383 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/compile-route.d.ts @@ -0,0 +1,18 @@ +/** + * MCP tool for compiling a specific route via the on-demand entry handler. + * + * Triggers on-demand compilation so the route's assets are built without making an + * HTTP request to the route. This is the same call path the dev server uses + * when a route is first navigated to, making it useful for warming the module + * graph, measuring compile time, or pre-compiling routes for memory + * benchmarking without requiring live backends. + */ +import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'; +import type { FormattedIssue } from './utils/format-compilation-issues'; +export declare function registerCompileRouteTool(server: McpServer, compileRoute: (opts: { + routeSpecifier?: string; + path?: string; +}) => Promise<{ + routeSpecifier: string; + issues: FormattedIssue[]; +}>): void; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/compile-route.js b/e-commerce/node_modules/next/dist/server/mcp/tools/compile-route.js new file mode 100644 index 0000000000000000000000000000000000000000..9f3c23ab57ef9723ef4ec894c08b3d0f30296aac --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/compile-route.js @@ -0,0 +1,86 @@ +/** + * MCP tool for compiling a specific route via the on-demand entry handler. + * + * Triggers on-demand compilation so the route's assets are built without making an + * HTTP request to the route. This is the same call path the dev server uses + * when a route is first navigated to, making it useful for warming the module + * graph, measuring compile time, or pre-compiling routes for memory + * benchmarking without requiring live backends. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "registerCompileRouteTool", { + enumerable: true, + get: function() { + return registerCompileRouteTool; + } +}); +const _mcptelemetrytracker = require("../mcp-telemetry-tracker"); +const _zod = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/zod")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function registerCompileRouteTool(server, compileRoute) { + server.registerTool('compile_route', { + description: 'Compile a specific route (page or API route) without making an HTTP request. ' + 'Triggers the same on-demand compilation the dev server uses when a route is first visited. ' + 'Useful for warming up the module graph, measuring compile time, or pre-compiling routes for memory benchmarking. ' + 'Returns { routeSpecifier, issues } on success where routeSpecifier is the resolved route and issues contains any compilation warnings or errors. ' + 'Returns an error if no matching route exists.', + inputSchema: { + routeSpecifier: _zod.default.string().describe('A route specifier as returned by the get_routes tool (e.g. "/", "/blog/[slug]", "/api/users/[id]"). ' + 'Mutually exclusive with `path`; provide exactly one.').optional(), + path: _zod.default.string().describe('A URL path on this site (e.g. "/blog/hello-world", "/docs/a/b/c"). ' + 'Query strings are allowed and ignored. Do not include scheme/host/port. ' + "The path is resolved to its matching route specifier using the dev router's live route table. " + 'Mutually exclusive with `routeSpecifier`; provide exactly one.').optional() + } + }, async ({ routeSpecifier, path })=>{ + _mcptelemetrytracker.mcpTelemetryTracker.recordToolCall('mcp/compile_route'); + if (routeSpecifier == null === (path == null)) { + return { + isError: true, + content: [ + { + type: 'text', + text: JSON.stringify({ + error: 'Provide exactly one of `routeSpecifier` or `path`.' + }) + } + ] + }; + } + try { + const { routeSpecifier: resolvedRouteSpecifier, issues } = await compileRoute({ + routeSpecifier, + path + }); + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + routeSpecifier: resolvedRouteSpecifier, + issues + }) + } + ] + }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + const notFound = error instanceof Error && error.code === 'ENOENT'; + return { + isError: true, + content: [ + { + type: 'text', + text: JSON.stringify(notFound ? { + notFound: true, + input: path ?? routeSpecifier + } : { + input: path ?? routeSpecifier, + error: message + }) + } + ] + }; + } + }); +} + +//# sourceMappingURL=compile-route.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/compile-route.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/compile-route.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5b7fb6d8ef7766a954bb6f2cae47f3023c884164 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/compile-route.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/mcp/tools/compile-route.ts"],"sourcesContent":["/**\n * MCP tool for compiling a specific route via the on-demand entry handler.\n *\n * Triggers on-demand compilation so the route's assets are built without making an\n * HTTP request to the route. This is the same call path the dev server uses\n * when a route is first navigated to, making it useful for warming the module\n * graph, measuring compile time, or pre-compiling routes for memory\n * benchmarking without requiring live backends.\n */\nimport type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'\nimport { mcpTelemetryTracker } from '../mcp-telemetry-tracker'\nimport type { FormattedIssue } from './utils/format-compilation-issues'\nimport z from 'next/dist/compiled/zod'\n\nexport function registerCompileRouteTool(\n server: McpServer,\n compileRoute: (opts: {\n routeSpecifier?: string\n path?: string\n }) => Promise<{ routeSpecifier: string; issues: FormattedIssue[] }>\n) {\n server.registerTool(\n 'compile_route',\n {\n description:\n 'Compile a specific route (page or API route) without making an HTTP request. ' +\n 'Triggers the same on-demand compilation the dev server uses when a route is first visited. ' +\n 'Useful for warming up the module graph, measuring compile time, or pre-compiling routes for memory benchmarking. ' +\n 'Returns { routeSpecifier, issues } on success where routeSpecifier is the resolved route and issues contains any compilation warnings or errors. ' +\n 'Returns an error if no matching route exists.',\n inputSchema: {\n routeSpecifier: z\n .string()\n .describe(\n 'A route specifier as returned by the get_routes tool (e.g. \"/\", \"/blog/[slug]\", \"/api/users/[id]\"). ' +\n 'Mutually exclusive with `path`; provide exactly one.'\n )\n .optional(),\n path: z\n .string()\n .describe(\n 'A URL path on this site (e.g. \"/blog/hello-world\", \"/docs/a/b/c\"). ' +\n 'Query strings are allowed and ignored. Do not include scheme/host/port. ' +\n \"The path is resolved to its matching route specifier using the dev router's live route table. \" +\n 'Mutually exclusive with `routeSpecifier`; provide exactly one.'\n )\n .optional(),\n },\n },\n async ({ routeSpecifier, path }) => {\n mcpTelemetryTracker.recordToolCall('mcp/compile_route')\n\n if ((routeSpecifier == null) === (path == null)) {\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: 'Provide exactly one of `routeSpecifier` or `path`.',\n }),\n },\n ],\n }\n }\n\n try {\n const { routeSpecifier: resolvedRouteSpecifier, issues } =\n await compileRoute({ routeSpecifier, path })\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n routeSpecifier: resolvedRouteSpecifier,\n issues,\n }),\n },\n ],\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n const notFound =\n error instanceof Error &&\n (error as NodeJS.ErrnoException).code === 'ENOENT'\n return {\n isError: true,\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n notFound\n ? { notFound: true, input: path ?? routeSpecifier }\n : { input: path ?? routeSpecifier, error: message }\n ),\n },\n ],\n }\n }\n }\n )\n}\n"],"names":["registerCompileRouteTool","server","compileRoute","registerTool","description","inputSchema","routeSpecifier","z","string","describe","optional","path","mcpTelemetryTracker","recordToolCall","isError","content","type","text","JSON","stringify","error","resolvedRouteSpecifier","issues","message","Error","String","notFound","code","input"],"mappings":"AAAA;;;;;;;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IACF;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-compilation-issues.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/get-compilation-issues.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb3b9c4cf32ec24e0356ce6210e1fc2313ad182e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-compilation-issues.d.ts @@ -0,0 +1,12 @@ +/** + * MCP tool for getting compilation issues from all routes via Turbopack. + * + * Unlike get_errors (which requires a browser session and reflects the runtime + * error overlay), this tool builds the module graph for every endpoint and + * collects Turbopack issues directly — no browser needed. Covers + * module-not-found, syntax errors, and other transform failures across all + * routes. + */ +import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'; +import type { Project } from '../../../build/swc/types'; +export declare function registerGetCompilationIssuesTool(server: McpServer, getProject: () => Project | undefined): void; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-compilation-issues.js b/e-commerce/node_modules/next/dist/server/mcp/tools/get-compilation-issues.js new file mode 100644 index 0000000000000000000000000000000000000000..152e2120c6ae9796b96c331bdc9dbf1209099ed7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-compilation-issues.js @@ -0,0 +1,68 @@ +/** + * MCP tool for getting compilation issues from all routes via Turbopack. + * + * Unlike get_errors (which requires a browser session and reflects the runtime + * error overlay), this tool builds the module graph for every endpoint and + * collects Turbopack issues directly — no browser needed. Covers + * module-not-found, syntax errors, and other transform failures across all + * routes. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "registerGetCompilationIssuesTool", { + enumerable: true, + get: function() { + return registerGetCompilationIssuesTool; + } +}); +const _mcptelemetrytracker = require("../mcp-telemetry-tracker"); +const _formatcompilationissues = require("./utils/format-compilation-issues"); +function registerGetCompilationIssuesTool(server, getProject) { + server.registerTool('get_compilation_issues', { + description: 'Build the module graph for all routes and return all compilation issues (resolve errors, missing modules, transform errors, etc.). Does not require a browser session. Covers all routes proactively.', + inputSchema: {} + }, async ()=>{ + _mcptelemetrytracker.mcpTelemetryTracker.recordToolCall('mcp/get_compilation_issues'); + try { + const project = getProject(); + if (!project) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: 'Turbopack project is not available. This tool requires the Turbopack bundler.' + }) + } + ] + }; + } + const { issues } = await project.getAllCompilationIssues(); + const formattedIssues = (0, _formatcompilationissues.formatCompilationIssues)(issues); + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + issues: formattedIssues + }) + } + ] + }; + } catch (error) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: error instanceof Error ? error.message : String(error) + }) + } + ] + }; + } + }); +} + +//# sourceMappingURL=get-compilation-issues.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-compilation-issues.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/get-compilation-issues.js.map new file mode 100644 index 0000000000000000000000000000000000000000..24f56618992df3fb38edf2dd7bd3806d89e0d161 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-compilation-issues.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/mcp/tools/get-compilation-issues.ts"],"sourcesContent":["/**\n * MCP tool for getting compilation issues from all routes via Turbopack.\n *\n * Unlike get_errors (which requires a browser session and reflects the runtime\n * error overlay), this tool builds the module graph for every endpoint and\n * collects Turbopack issues directly — no browser needed. Covers\n * module-not-found, syntax errors, and other transform failures across all\n * routes.\n */\nimport type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'\nimport type { Project } from '../../../build/swc/types'\nimport { mcpTelemetryTracker } from '../mcp-telemetry-tracker'\nimport { formatCompilationIssues } from './utils/format-compilation-issues'\n\nexport function registerGetCompilationIssuesTool(\n server: McpServer,\n getProject: () => Project | undefined\n) {\n server.registerTool(\n 'get_compilation_issues',\n {\n description:\n 'Build the module graph for all routes and return all compilation issues (resolve errors, missing modules, transform errors, etc.). Does not require a browser session. Covers all routes proactively.',\n inputSchema: {},\n },\n async () => {\n mcpTelemetryTracker.recordToolCall('mcp/get_compilation_issues')\n\n try {\n const project = getProject()\n if (!project) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error:\n 'Turbopack project is not available. This tool requires the Turbopack bundler.',\n }),\n },\n ],\n }\n }\n\n const { issues } = await project.getAllCompilationIssues()\n const formattedIssues = formatCompilationIssues(issues)\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ issues: formattedIssues }),\n },\n ],\n }\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: error instanceof Error ? error.message : String(error),\n }),\n },\n ],\n }\n }\n }\n )\n}\n"],"names":["registerGetCompilationIssuesTool","server","getProject","registerTool","description","inputSchema","mcpTelemetryTracker","recordToolCall","project","content","type","text","JSON","stringify","error","issues","getAllCompilationIssues","formattedIssues","formatCompilationIssues","Error","message","String"],"mappings":"AAAA;;;;;;;;CAQC;;;;+BAMeA;;;eAAAA;;;qCAHoB;yCACI;AAEjC,SAASA,iCACdC,MAAiB,EACjBC,UAAqC;IAErCD,OAAOE,YAAY,CACjB,0BACA;QACEC,aACE;QACFC,aAAa,CAAC;IAChB,GACA;QACEC,wCAAmB,CAACC,cAAc,CAAC;QAEnC,IAAI;YACF,MAAMC,UAAUN;YAChB,IAAI,CAACM,SAAS;gBACZ,OAAO;oBACLC,SAAS;wBACP;4BACEC,MAAM;4BACNC,MAAMC,KAAKC,SAAS,CAAC;gCACnBC,OACE;4BACJ;wBACF;qBACD;gBACH;YACF;YAEA,MAAM,EAAEC,MAAM,EAAE,GAAG,MAAMP,QAAQQ,uBAAuB;YACxD,MAAMC,kBAAkBC,IAAAA,gDAAuB,EAACH;YAEhD,OAAO;gBACLN,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC;4BAAEE,QAAQE;wBAAgB;oBACjD;iBACD;YACH;QACF,EAAE,OAAOH,OAAO;YACd,OAAO;gBACLL,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC;4BACnBC,OAAOA,iBAAiBK,QAAQL,MAAMM,OAAO,GAAGC,OAAOP;wBACzD;oBACF;iBACD;YACH;QACF;IACF;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-errors.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/get-errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..06135089851b34a7d523479484e32920ab370396 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-errors.d.ts @@ -0,0 +1,20 @@ +/** + * MCP tool for retrieving error state from Next.js dev server. + * + * This tool provides comprehensive error reporting including: + * - Next.js global errors (e.g., next.config validation errors) + * - Browser runtime errors with source-mapped stack traces + * - Build errors from webpack/turbopack compilation + * + * For browser errors, it leverages the HMR infrastructure for server-to-browser communication. + * + * Flow: + * MCP client → server generates request ID → HMR message to browser → + * browser queries error overlay state → HMR response back → server performs source mapping → + * combined with global errors → formatted output. + */ +import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'; +import type { OverlayState } from '../../../next-devtools/dev-overlay/shared'; +import { type HmrMessageSentToBrowser } from '../../dev/hot-reloader-types'; +export declare function registerGetErrorsTool(server: McpServer, sendHmrMessage: (message: HmrMessageSentToBrowser) => void, getActiveConnectionCount: () => number): void; +export declare function handleErrorStateResponse(requestId: string, errorState: OverlayState | null, url: string | undefined): void; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-errors.js b/e-commerce/node_modules/next/dist/server/mcp/tools/get-errors.js new file mode 100644 index 0000000000000000000000000000000000000000..c3cc35a4af111f08074cbba992bdd042880d632b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-errors.js @@ -0,0 +1,114 @@ +/** + * MCP tool for retrieving error state from Next.js dev server. + * + * This tool provides comprehensive error reporting including: + * - Next.js global errors (e.g., next.config validation errors) + * - Browser runtime errors with source-mapped stack traces + * - Build errors from webpack/turbopack compilation + * + * For browser errors, it leverages the HMR infrastructure for server-to-browser communication. + * + * Flow: + * MCP client → server generates request ID → HMR message to browser → + * browser queries error overlay state → HMR response back → server performs source mapping → + * combined with global errors → formatted output. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + handleErrorStateResponse: null, + registerGetErrorsTool: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + handleErrorStateResponse: function() { + return handleErrorStateResponse; + }, + registerGetErrorsTool: function() { + return registerGetErrorsTool; + } +}); +const _hotreloadertypes = require("../../dev/hot-reloader-types"); +const _formaterrors = require("./utils/format-errors"); +const _browsercommunication = require("./utils/browser-communication"); +const _nextinstanceerrorstate = require("./next-instance-error-state"); +const _mcptelemetrytracker = require("../mcp-telemetry-tracker"); +function registerGetErrorsTool(server, sendHmrMessage, getActiveConnectionCount) { + server.registerTool('get_errors', { + description: 'Get the current error state from the Next.js dev server, including Next.js global errors (e.g., next.config validation), browser runtime errors, and build errors with source-mapped stack traces', + inputSchema: {} + }, async (_request)=>{ + // Track telemetry + _mcptelemetrytracker.mcpTelemetryTracker.recordToolCall('mcp/get_errors'); + try { + const connectionCount = getActiveConnectionCount(); + if (connectionCount === 0) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: 'No browser sessions connected. Please open your application in a browser to retrieve error state.' + }) + } + ] + }; + } + const responses = await (0, _browsercommunication.createBrowserRequest)(_hotreloadertypes.HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE, sendHmrMessage, getActiveConnectionCount, _browsercommunication.DEFAULT_BROWSER_REQUEST_TIMEOUT_MS); + // The error state for each route + // key is the route path, value is the error state + const routesErrorState = new Map(); + for (const response of responses){ + if (response.data) { + routesErrorState.set(response.url, response.data); + } + } + const hasRouteErrors = Array.from(routesErrorState.values()).some((state)=>state.errors.length > 0 || !!state.buildError); + const hasInstanceErrors = _nextinstanceerrorstate.NextInstanceErrorState.nextConfig.length > 0; + if (!hasRouteErrors && !hasInstanceErrors) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + configErrors: [], + sessionErrors: [] + }) + } + ] + }; + } + const output = await (0, _formaterrors.formatErrors)(routesErrorState, _nextinstanceerrorstate.NextInstanceErrorState); + return { + content: [ + { + type: 'text', + text: JSON.stringify(output) + } + ] + }; + } catch (error) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: error instanceof Error ? error.message : String(error) + }) + } + ] + }; + } + }); +} +function handleErrorStateResponse(requestId, errorState, url) { + (0, _browsercommunication.handleBrowserPageResponse)(requestId, errorState, url || ''); +} + +//# sourceMappingURL=get-errors.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-errors.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/get-errors.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9000bbc65d1ee031e352af22b1971ae042b8e222 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-errors.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/mcp/tools/get-errors.ts"],"sourcesContent":["/**\n * MCP tool for retrieving error state from Next.js dev server.\n *\n * This tool provides comprehensive error reporting including:\n * - Next.js global errors (e.g., next.config validation errors)\n * - Browser runtime errors with source-mapped stack traces\n * - Build errors from webpack/turbopack compilation\n *\n * For browser errors, it leverages the HMR infrastructure for server-to-browser communication.\n *\n * Flow:\n * MCP client → server generates request ID → HMR message to browser →\n * browser queries error overlay state → HMR response back → server performs source mapping →\n * combined with global errors → formatted output.\n */\nimport type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'\nimport type { OverlayState } from '../../../next-devtools/dev-overlay/shared'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type HmrMessageSentToBrowser,\n} from '../../dev/hot-reloader-types'\nimport { formatErrors } from './utils/format-errors'\nimport {\n createBrowserRequest,\n handleBrowserPageResponse,\n DEFAULT_BROWSER_REQUEST_TIMEOUT_MS,\n} from './utils/browser-communication'\nimport { NextInstanceErrorState } from './next-instance-error-state'\nimport { mcpTelemetryTracker } from '../mcp-telemetry-tracker'\n\nexport function registerGetErrorsTool(\n server: McpServer,\n sendHmrMessage: (message: HmrMessageSentToBrowser) => void,\n getActiveConnectionCount: () => number\n) {\n server.registerTool(\n 'get_errors',\n {\n description:\n 'Get the current error state from the Next.js dev server, including Next.js global errors (e.g., next.config validation), browser runtime errors, and build errors with source-mapped stack traces',\n inputSchema: {},\n },\n async (_request) => {\n // Track telemetry\n mcpTelemetryTracker.recordToolCall('mcp/get_errors')\n\n try {\n const connectionCount = getActiveConnectionCount()\n if (connectionCount === 0) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error:\n 'No browser sessions connected. Please open your application in a browser to retrieve error state.',\n }),\n },\n ],\n }\n }\n\n const responses = await createBrowserRequest(\n HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE,\n sendHmrMessage,\n getActiveConnectionCount,\n DEFAULT_BROWSER_REQUEST_TIMEOUT_MS\n )\n\n // The error state for each route\n // key is the route path, value is the error state\n const routesErrorState = new Map()\n for (const response of responses) {\n if (response.data) {\n routesErrorState.set(response.url, response.data)\n }\n }\n\n const hasRouteErrors = Array.from(routesErrorState.values()).some(\n (state) => state.errors.length > 0 || !!state.buildError\n )\n const hasInstanceErrors = NextInstanceErrorState.nextConfig.length > 0\n\n if (!hasRouteErrors && !hasInstanceErrors) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n configErrors: [],\n sessionErrors: [],\n }),\n },\n ],\n }\n }\n\n const output = await formatErrors(\n routesErrorState,\n NextInstanceErrorState\n )\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(output),\n },\n ],\n }\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: error instanceof Error ? error.message : String(error),\n }),\n },\n ],\n }\n }\n }\n )\n}\n\n// Browser will first receive an HMR message from server to send back its error state.\n// The actual state is sent back in a subsequent HMR message, which is handled by this function\n// on the server.\nexport function handleErrorStateResponse(\n requestId: string,\n errorState: OverlayState | null,\n url: string | undefined\n) {\n handleBrowserPageResponse(\n requestId,\n errorState,\n url || ''\n )\n}\n"],"names":["handleErrorStateResponse","registerGetErrorsTool","server","sendHmrMessage","getActiveConnectionCount","registerTool","description","inputSchema","_request","mcpTelemetryTracker","recordToolCall","connectionCount","content","type","text","JSON","stringify","error","responses","createBrowserRequest","HMR_MESSAGE_SENT_TO_BROWSER","REQUEST_CURRENT_ERROR_STATE","DEFAULT_BROWSER_REQUEST_TIMEOUT_MS","routesErrorState","Map","response","data","set","url","hasRouteErrors","Array","from","values","some","state","errors","length","buildError","hasInstanceErrors","NextInstanceErrorState","nextConfig","configErrors","sessionErrors","output","formatErrors","Error","message","String","requestId","errorState","handleBrowserPageResponse"],"mappings":"AAAA;;;;;;;;;;;;;;CAcC;;;;;;;;;;;;;;;IAmHeA,wBAAwB;eAAxBA;;IAnGAC,qBAAqB;eAArBA;;;kCAVT;8BACsB;sCAKtB;wCACgC;qCACH;AAE7B,SAASA,sBACdC,MAAiB,EACjBC,cAA0D,EAC1DC,wBAAsC;IAEtCF,OAAOG,YAAY,CACjB,cACA;QACEC,aACE;QACFC,aAAa,CAAC;IAChB,GACA,OAAOC;QACL,kBAAkB;QAClBC,wCAAmB,CAACC,cAAc,CAAC;QAEnC,IAAI;YACF,MAAMC,kBAAkBP;YACxB,IAAIO,oBAAoB,GAAG;gBACzB,OAAO;oBACLC,SAAS;wBACP;4BACEC,MAAM;4BACNC,MAAMC,KAAKC,SAAS,CAAC;gCACnBC,OACE;4BACJ;wBACF;qBACD;gBACH;YACF;YAEA,MAAMC,YAAY,MAAMC,IAAAA,0CAAoB,EAC1CC,6CAA2B,CAACC,2BAA2B,EACvDlB,gBACAC,0BACAkB,wDAAkC;YAGpC,iCAAiC;YACjC,kDAAkD;YAClD,MAAMC,mBAAmB,IAAIC;YAC7B,KAAK,MAAMC,YAAYP,UAAW;gBAChC,IAAIO,SAASC,IAAI,EAAE;oBACjBH,iBAAiBI,GAAG,CAACF,SAASG,GAAG,EAAEH,SAASC,IAAI;gBAClD;YACF;YAEA,MAAMG,iBAAiBC,MAAMC,IAAI,CAACR,iBAAiBS,MAAM,IAAIC,IAAI,CAC/D,CAACC,QAAUA,MAAMC,MAAM,CAACC,MAAM,GAAG,KAAK,CAAC,CAACF,MAAMG,UAAU;YAE1D,MAAMC,oBAAoBC,8CAAsB,CAACC,UAAU,CAACJ,MAAM,GAAG;YAErE,IAAI,CAACP,kBAAkB,CAACS,mBAAmB;gBACzC,OAAO;oBACL1B,SAAS;wBACP;4BACEC,MAAM;4BACNC,MAAMC,KAAKC,SAAS,CAAC;gCACnByB,cAAc,EAAE;gCAChBC,eAAe,EAAE;4BACnB;wBACF;qBACD;gBACH;YACF;YAEA,MAAMC,SAAS,MAAMC,IAAAA,0BAAY,EAC/BrB,kBACAgB,8CAAsB;YAGxB,OAAO;gBACL3B,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC2B;oBACvB;iBACD;YACH;QACF,EAAE,OAAO1B,OAAO;YACd,OAAO;gBACLL,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC;4BACnBC,OAAOA,iBAAiB4B,QAAQ5B,MAAM6B,OAAO,GAAGC,OAAO9B;wBACzD;oBACF;iBACD;YACH;QACF;IACF;AAEJ;AAKO,SAASjB,yBACdgD,SAAiB,EACjBC,UAA+B,EAC/BrB,GAAuB;IAEvBsB,IAAAA,+CAAyB,EACvBF,WACAC,YACArB,OAAO;AAEX","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-logs.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/get-logs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..126b78c43a9cceaf9f5f8961423a195137dc1686 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-logs.d.ts @@ -0,0 +1,8 @@ +/** + * MCP tool for getting the path to the Next.js development log file. + * + * This tool returns the path to the {nextConfig.distDir}/logs/next-development.log file + * that contains browser console logs and other development information. + */ +import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'; +export declare function registerGetLogsTool(server: McpServer, distDir: string): void; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-logs.js b/e-commerce/node_modules/next/dist/server/mcp/tools/get-logs.js new file mode 100644 index 0000000000000000000000000000000000000000..fa66e411540dd2193f50e6b98629b56910cd13b5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-logs.js @@ -0,0 +1,67 @@ +/** + * MCP tool for getting the path to the Next.js development log file. + * + * This tool returns the path to the {nextConfig.distDir}/logs/next-development.log file + * that contains browser console logs and other development information. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "registerGetLogsTool", { + enumerable: true, + get: function() { + return registerGetLogsTool; + } +}); +const _promises = require("fs/promises"); +const _path = require("path"); +const _mcptelemetrytracker = require("../mcp-telemetry-tracker"); +function registerGetLogsTool(server, distDir) { + server.registerTool('get_logs', { + description: 'Get the path to the Next.js development log file. Returns the file path so the agent can read the logs directly.' + }, async ()=>{ + // Track telemetry + _mcptelemetrytracker.mcpTelemetryTracker.recordToolCall('mcp/get_logs'); + try { + const logFilePath = (0, _path.join)(distDir, 'logs', 'next-development.log'); + // Check if the log file exists + try { + await (0, _promises.stat)(logFilePath); + } catch (error) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: `Log file not found at ${logFilePath}.` + }) + } + ] + }; + } + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + logFilePath + }) + } + ] + }; + } catch (error) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: `Error getting log file path: ${error instanceof Error ? error.message : String(error)}` + }) + } + ] + }; + } + }); +} + +//# sourceMappingURL=get-logs.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-logs.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/get-logs.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ac7f5c5fc8f1729cfb491afce89d8c965c3a036f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-logs.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/mcp/tools/get-logs.ts"],"sourcesContent":["/**\n * MCP tool for getting the path to the Next.js development log file.\n *\n * This tool returns the path to the {nextConfig.distDir}/logs/next-development.log file\n * that contains browser console logs and other development information.\n */\nimport type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'\nimport { stat } from 'fs/promises'\nimport { join } from 'path'\nimport { mcpTelemetryTracker } from '../mcp-telemetry-tracker'\n\nexport function registerGetLogsTool(server: McpServer, distDir: string) {\n server.registerTool(\n 'get_logs',\n {\n description:\n 'Get the path to the Next.js development log file. Returns the file path so the agent can read the logs directly.',\n },\n async () => {\n // Track telemetry\n mcpTelemetryTracker.recordToolCall('mcp/get_logs')\n\n try {\n const logFilePath = join(distDir, 'logs', 'next-development.log')\n\n // Check if the log file exists\n try {\n await stat(logFilePath)\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: `Log file not found at ${logFilePath}.`,\n }),\n },\n ],\n }\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n logFilePath,\n }),\n },\n ],\n }\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: `Error getting log file path: ${error instanceof Error ? error.message : String(error)}`,\n }),\n },\n ],\n }\n }\n }\n )\n}\n"],"names":["registerGetLogsTool","server","distDir","registerTool","description","mcpTelemetryTracker","recordToolCall","logFilePath","join","stat","error","content","type","text","JSON","stringify","Error","message","String"],"mappings":"AAAA;;;;;CAKC;;;;+BAMeA;;;eAAAA;;;0BAJK;sBACA;qCACe;AAE7B,SAASA,oBAAoBC,MAAiB,EAAEC,OAAe;IACpED,OAAOE,YAAY,CACjB,YACA;QACEC,aACE;IACJ,GACA;QACE,kBAAkB;QAClBC,wCAAmB,CAACC,cAAc,CAAC;QAEnC,IAAI;YACF,MAAMC,cAAcC,IAAAA,UAAI,EAACN,SAAS,QAAQ;YAE1C,+BAA+B;YAC/B,IAAI;gBACF,MAAMO,IAAAA,cAAI,EAACF;YACb,EAAE,OAAOG,OAAO;gBACd,OAAO;oBACLC,SAAS;wBACP;4BACEC,MAAM;4BACNC,MAAMC,KAAKC,SAAS,CAAC;gCACnBL,OAAO,CAAC,sBAAsB,EAAEH,YAAY,CAAC,CAAC;4BAChD;wBACF;qBACD;gBACH;YACF;YAEA,OAAO;gBACLI,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC;4BACnBR;wBACF;oBACF;iBACD;YACH;QACF,EAAE,OAAOG,OAAO;YACd,OAAO;gBACLC,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC;4BACnBL,OAAO,CAAC,6BAA6B,EAAEA,iBAAiBM,QAAQN,MAAMO,OAAO,GAAGC,OAAOR,QAAQ;wBACjG;oBACF;iBACD;YACH;QACF;IACF;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-page-metadata.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/get-page-metadata.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f23f916b72aa4bebb4df51749f273ace3aafdbf --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-page-metadata.d.ts @@ -0,0 +1,5 @@ +import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'; +import { type HmrMessageSentToBrowser } from '../../dev/hot-reloader-types'; +import type { SegmentTrieData } from '../../../shared/lib/mcp-page-metadata-types'; +export declare function registerGetPageMetadataTool(server: McpServer, sendHmrMessage: (message: HmrMessageSentToBrowser) => void, getActiveConnectionCount: () => number): void; +export declare function handlePageMetadataResponse(requestId: string, segmentTrieData: SegmentTrieData | null, url: string | undefined): void; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-page-metadata.js b/e-commerce/node_modules/next/dist/server/mcp/tools/get-page-metadata.js new file mode 100644 index 0000000000000000000000000000000000000000..dac8dbb7d16f1f0746fc661073d9e88e6da94cee --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-page-metadata.js @@ -0,0 +1,188 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + handlePageMetadataResponse: null, + registerGetPageMetadataTool: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + handlePageMetadataResponse: function() { + return handlePageMetadataResponse; + }, + registerGetPageMetadataTool: function() { + return registerGetPageMetadataTool; + } +}); +const _hotreloadertypes = require("../../dev/hot-reloader-types"); +const _browsercommunication = require("./utils/browser-communication"); +const _mcptelemetrytracker = require("../mcp-telemetry-tracker"); +function registerGetPageMetadataTool(server, sendHmrMessage, getActiveConnectionCount) { + server.registerTool('get_page_metadata', { + description: 'Get runtime metadata about what contributes to the current page render from active browser sessions.', + inputSchema: {} + }, async (_request)=>{ + // Track telemetry + _mcptelemetrytracker.mcpTelemetryTracker.recordToolCall('mcp/get_page_metadata'); + try { + const connectionCount = getActiveConnectionCount(); + if (connectionCount === 0) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: 'No browser sessions connected. Please open your application in a browser to retrieve page metadata.' + }) + } + ] + }; + } + const responses = await (0, _browsercommunication.createBrowserRequest)(_hotreloadertypes.HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_PAGE_METADATA, sendHmrMessage, getActiveConnectionCount, _browsercommunication.DEFAULT_BROWSER_REQUEST_TIMEOUT_MS); + if (responses.length === 0) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + sessions: [] + }) + } + ] + }; + } + const sessionMetadata = []; + for (const response of responses){ + if (response.data) { + // TODO: Add other metadata for the current page render here. Currently, we only have segment trie data. + const pageMetadata = convertSegmentTrieToPageMetadata(response.data); + sessionMetadata.push({ + url: response.url, + metadata: pageMetadata + }); + } + } + if (sessionMetadata.length === 0) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + sessions: [] + }) + } + ] + }; + } + const output = formatPageMetadata(sessionMetadata); + return { + content: [ + { + type: 'text', + text: JSON.stringify(output) + } + ] + }; + } catch (error) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: error instanceof Error ? error.message : String(error) + }) + } + ] + }; + } + }); +} +function handlePageMetadataResponse(requestId, segmentTrieData, url) { + (0, _browsercommunication.handleBrowserPageResponse)(requestId, segmentTrieData, url || ''); +} +function convertSegmentTrieToPageMetadata(data) { + const segments = []; + if (data.segmentTrie) { + // Traverse the trie and collect all segments + function traverseTrie(node) { + if (node.value) { + segments.push({ + type: node.value.type, + pagePath: node.value.pagePath, + boundaryType: node.value.boundaryType + }); + } + for (const childNode of Object.values(node.children)){ + if (childNode) { + traverseTrie(childNode); + } + } + } + traverseTrie(data.segmentTrie); + } + return { + segments, + routerType: data.routerType + }; +} +function formatPageMetadata(sessionMetadata) { + const sessions = []; + for (const { url, metadata } of sessionMetadata){ + let displayUrl = url; + try { + const urlObj = new URL(url); + displayUrl = urlObj.pathname + urlObj.search + urlObj.hash; + } catch { + // If URL parsing fails, use the original URL + } + // Ensure consistent output to avoid flaky tests + const sortedSegments = [ + ...metadata.segments + ].sort((a, b)=>{ + const typeOrder = (segment)=>{ + const type = segment.boundaryType || segment.type; + if (type === 'layout') return 0; + if (type.startsWith('boundary:')) return 1; + if (type === 'page') return 2; + return 3; + }; + const aOrder = typeOrder(a); + const bOrder = typeOrder(b); + if (aOrder !== bOrder) return aOrder - bOrder; + return a.pagePath.localeCompare(b.pagePath); + }); + const formattedSegments = []; + for (const segment of sortedSegments){ + const path = segment.pagePath; + const isBuiltin = path.startsWith('__next_builtin__'); + const type = segment.boundaryType || segment.type; + const isBoundary = type.startsWith('boundary:'); + let displayPath = path.replace(/@boundary$/, '').replace(/^__next_builtin__/, ''); + if (!isBuiltin && !displayPath.startsWith('app/')) { + displayPath = `app/${displayPath}`; + } + formattedSegments.push({ + path: displayPath, + type, + isBoundary, + isBuiltin + }); + } + sessions.push({ + url: displayUrl, + routerType: metadata.routerType, + segments: formattedSegments + }); + } + return { + sessions + }; +} + +//# sourceMappingURL=get-page-metadata.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-page-metadata.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/get-page-metadata.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9668e41e22723ff8c5113be64d916f41ee523816 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-page-metadata.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/mcp/tools/get-page-metadata.ts"],"sourcesContent":["import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type HmrMessageSentToBrowser,\n} from '../../dev/hot-reloader-types'\nimport {\n createBrowserRequest,\n handleBrowserPageResponse,\n DEFAULT_BROWSER_REQUEST_TIMEOUT_MS,\n} from './utils/browser-communication'\nimport type {\n PageMetadata,\n PageSegment,\n SegmentTrieData,\n} from '../../../shared/lib/mcp-page-metadata-types'\nimport type { SegmentTrieNode } from '../../../next-devtools/dev-overlay/segment-explorer-trie'\nimport { mcpTelemetryTracker } from '../mcp-telemetry-tracker'\n\nexport function registerGetPageMetadataTool(\n server: McpServer,\n sendHmrMessage: (message: HmrMessageSentToBrowser) => void,\n getActiveConnectionCount: () => number\n) {\n server.registerTool(\n 'get_page_metadata',\n {\n description:\n 'Get runtime metadata about what contributes to the current page render from active browser sessions.',\n inputSchema: {},\n },\n async (_request) => {\n // Track telemetry\n mcpTelemetryTracker.recordToolCall('mcp/get_page_metadata')\n\n try {\n const connectionCount = getActiveConnectionCount()\n if (connectionCount === 0) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error:\n 'No browser sessions connected. Please open your application in a browser to retrieve page metadata.',\n }),\n },\n ],\n }\n }\n\n const responses = await createBrowserRequest(\n HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_PAGE_METADATA,\n sendHmrMessage,\n getActiveConnectionCount,\n DEFAULT_BROWSER_REQUEST_TIMEOUT_MS\n )\n\n if (responses.length === 0) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n sessions: [],\n }),\n },\n ],\n }\n }\n\n const sessionMetadata: Array<{ url: string; metadata: PageMetadata }> =\n []\n for (const response of responses) {\n if (response.data) {\n // TODO: Add other metadata for the current page render here. Currently, we only have segment trie data.\n const pageMetadata = convertSegmentTrieToPageMetadata(response.data)\n sessionMetadata.push({ url: response.url, metadata: pageMetadata })\n }\n }\n\n if (sessionMetadata.length === 0) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n sessions: [],\n }),\n },\n ],\n }\n }\n\n const output = formatPageMetadata(sessionMetadata)\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(output),\n },\n ],\n }\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: error instanceof Error ? error.message : String(error),\n }),\n },\n ],\n }\n }\n }\n )\n}\n\nexport function handlePageMetadataResponse(\n requestId: string,\n segmentTrieData: SegmentTrieData | null,\n url: string | undefined\n) {\n handleBrowserPageResponse(\n requestId,\n segmentTrieData,\n url || ''\n )\n}\n\nfunction convertSegmentTrieToPageMetadata(data: SegmentTrieData): PageMetadata {\n const segments: PageSegment[] = []\n\n if (data.segmentTrie) {\n // Traverse the trie and collect all segments\n function traverseTrie(node: SegmentTrieNode): void {\n if (node.value) {\n segments.push({\n type: node.value.type,\n pagePath: node.value.pagePath,\n boundaryType: node.value.boundaryType,\n })\n }\n\n for (const childNode of Object.values(node.children)) {\n if (childNode) {\n traverseTrie(childNode)\n }\n }\n }\n\n traverseTrie(data.segmentTrie)\n }\n\n return {\n segments,\n routerType: data.routerType,\n }\n}\n\ninterface FormattedSegment {\n path: string\n type: string\n isBoundary: boolean\n isBuiltin: boolean\n}\n\ninterface FormattedSession {\n url: string\n routerType: string\n segments: FormattedSegment[]\n}\n\ninterface FormattedPageMetadataOutput {\n sessions: FormattedSession[]\n}\n\nfunction formatPageMetadata(\n sessionMetadata: Array<{ url: string; metadata: PageMetadata }>\n): FormattedPageMetadataOutput {\n const sessions: FormattedSession[] = []\n\n for (const { url, metadata } of sessionMetadata) {\n let displayUrl = url\n try {\n const urlObj = new URL(url)\n displayUrl = urlObj.pathname + urlObj.search + urlObj.hash\n } catch {\n // If URL parsing fails, use the original URL\n }\n\n // Ensure consistent output to avoid flaky tests\n const sortedSegments = [...metadata.segments].sort((a, b) => {\n const typeOrder = (segment: PageSegment): number => {\n const type = segment.boundaryType || segment.type\n if (type === 'layout') return 0\n if (type.startsWith('boundary:')) return 1\n if (type === 'page') return 2\n return 3\n }\n const aOrder = typeOrder(a)\n const bOrder = typeOrder(b)\n if (aOrder !== bOrder) return aOrder - bOrder\n return a.pagePath.localeCompare(b.pagePath)\n })\n\n const formattedSegments: FormattedSegment[] = []\n for (const segment of sortedSegments) {\n const path = segment.pagePath\n const isBuiltin = path.startsWith('__next_builtin__')\n const type = segment.boundaryType || segment.type\n const isBoundary = type.startsWith('boundary:')\n\n let displayPath = path\n .replace(/@boundary$/, '')\n .replace(/^__next_builtin__/, '')\n\n if (!isBuiltin && !displayPath.startsWith('app/')) {\n displayPath = `app/${displayPath}`\n }\n\n formattedSegments.push({\n path: displayPath,\n type,\n isBoundary,\n isBuiltin,\n })\n }\n\n sessions.push({\n url: displayUrl,\n routerType: metadata.routerType,\n segments: formattedSegments,\n })\n }\n\n return { sessions }\n}\n"],"names":["handlePageMetadataResponse","registerGetPageMetadataTool","server","sendHmrMessage","getActiveConnectionCount","registerTool","description","inputSchema","_request","mcpTelemetryTracker","recordToolCall","connectionCount","content","type","text","JSON","stringify","error","responses","createBrowserRequest","HMR_MESSAGE_SENT_TO_BROWSER","REQUEST_PAGE_METADATA","DEFAULT_BROWSER_REQUEST_TIMEOUT_MS","length","sessions","sessionMetadata","response","data","pageMetadata","convertSegmentTrieToPageMetadata","push","url","metadata","output","formatPageMetadata","Error","message","String","requestId","segmentTrieData","handleBrowserPageResponse","segments","segmentTrie","traverseTrie","node","value","pagePath","boundaryType","childNode","Object","values","children","routerType","displayUrl","urlObj","URL","pathname","search","hash","sortedSegments","sort","a","b","typeOrder","segment","startsWith","aOrder","bOrder","localeCompare","formattedSegments","path","isBuiltin","isBoundary","displayPath","replace"],"mappings":";;;;;;;;;;;;;;;IAuHgBA,0BAA0B;eAA1BA;;IArGAC,2BAA2B;eAA3BA;;;kCAdT;sCAKA;qCAO6B;AAE7B,SAASA,4BACdC,MAAiB,EACjBC,cAA0D,EAC1DC,wBAAsC;IAEtCF,OAAOG,YAAY,CACjB,qBACA;QACEC,aACE;QACFC,aAAa,CAAC;IAChB,GACA,OAAOC;QACL,kBAAkB;QAClBC,wCAAmB,CAACC,cAAc,CAAC;QAEnC,IAAI;YACF,MAAMC,kBAAkBP;YACxB,IAAIO,oBAAoB,GAAG;gBACzB,OAAO;oBACLC,SAAS;wBACP;4BACEC,MAAM;4BACNC,MAAMC,KAAKC,SAAS,CAAC;gCACnBC,OACE;4BACJ;wBACF;qBACD;gBACH;YACF;YAEA,MAAMC,YAAY,MAAMC,IAAAA,0CAAoB,EAC1CC,6CAA2B,CAACC,qBAAqB,EACjDlB,gBACAC,0BACAkB,wDAAkC;YAGpC,IAAIJ,UAAUK,MAAM,KAAK,GAAG;gBAC1B,OAAO;oBACLX,SAAS;wBACP;4BACEC,MAAM;4BACNC,MAAMC,KAAKC,SAAS,CAAC;gCACnBQ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UAAU,CAAC;YAEnC,IAAIQ,cAAcH,KACfI,OAAO,CAAC,cAAc,IACtBA,OAAO,CAAC,qBAAqB;YAEhC,IAAI,CAACH,aAAa,CAACE,YAAYR,UAAU,CAAC,SAAS;gBACjDQ,cAAc,CAAC,IAAI,EAAEA,aAAa;YACpC;YAEAJ,kBAAkBvC,IAAI,CAAC;gBACrBwC,MAAMG;gBACN5D;gBACA2D;gBACAD;YACF;QACF;QAEA/C,SAASM,IAAI,CAAC;YACZC,KAAKsB;YACLD,YAAYpB,SAASoB,UAAU;YAC/BX,UAAU4B;QACZ;IACF;IAEA,OAAO;QAAE7C;IAAS;AACpB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-project-metadata.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/get-project-metadata.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1aa1692c306e58d7b1d6fab9c2a3acbff4e8c096 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-project-metadata.d.ts @@ -0,0 +1,2 @@ +import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'; +export declare function registerGetProjectMetadataTool(server: McpServer, projectPath: string, getDevServerUrl: () => string | undefined): void; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-project-metadata.js b/e-commerce/node_modules/next/dist/server/mcp/tools/get-project-metadata.js new file mode 100644 index 0000000000000000000000000000000000000000..3c9aa99875d04990f7ab1bd48ef1d1c348262253 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-project-metadata.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "registerGetProjectMetadataTool", { + enumerable: true, + get: function() { + return registerGetProjectMetadataTool; + } +}); +const _mcptelemetrytracker = require("../mcp-telemetry-tracker"); +function registerGetProjectMetadataTool(server, projectPath, getDevServerUrl) { + server.registerTool('get_project_metadata', { + description: 'Returns the the metadata of this Next.js project, including project path, dev server URL, etc.', + inputSchema: {} + }, async (_request)=>{ + // Track telemetry + _mcptelemetrytracker.mcpTelemetryTracker.recordToolCall('mcp/get_project_metadata'); + try { + if (!projectPath) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: 'Unable to determine the absolute path of the Next.js project.' + }) + } + ] + }; + } + const devServerUrl = getDevServerUrl(); + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + projectPath, + devServerUrl + }) + } + ] + }; + } catch (error) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: error instanceof Error ? error.message : String(error) + }) + } + ] + }; + } + }); +} + +//# sourceMappingURL=get-project-metadata.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-project-metadata.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/get-project-metadata.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d469e772dd6badc59f3142fafc02de89e26e4c81 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-project-metadata.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/mcp/tools/get-project-metadata.ts"],"sourcesContent":["import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'\nimport { mcpTelemetryTracker } from '../mcp-telemetry-tracker'\n\nexport function registerGetProjectMetadataTool(\n server: McpServer,\n projectPath: string,\n getDevServerUrl: () => string | undefined\n) {\n server.registerTool(\n 'get_project_metadata',\n {\n description:\n 'Returns the the metadata of this Next.js project, including project path, dev server URL, etc.',\n inputSchema: {},\n },\n async (_request) => {\n // Track telemetry\n mcpTelemetryTracker.recordToolCall('mcp/get_project_metadata')\n\n try {\n if (!projectPath) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error:\n 'Unable to determine the absolute path of the Next.js project.',\n }),\n },\n ],\n }\n }\n\n const devServerUrl = getDevServerUrl()\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n projectPath,\n devServerUrl,\n }),\n },\n ],\n }\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: error instanceof Error ? error.message : String(error),\n }),\n },\n ],\n }\n }\n }\n )\n}\n"],"names":["registerGetProjectMetadataTool","server","projectPath","getDevServerUrl","registerTool","description","inputSchema","_request","mcpTelemetryTracker","recordToolCall","content","type","text","JSON","stringify","error","devServerUrl","Error","message","String"],"mappings":";;;;+BAGgBA;;;eAAAA;;;qCAFoB;AAE7B,SAASA,+BACdC,MAAiB,EACjBC,WAAmB,EACnBC,eAAyC;IAEzCF,OAAOG,YAAY,CACjB,wBACA;QACEC,aACE;QACFC,aAAa,CAAC;IAChB,GACA,OAAOC;QACL,kBAAkB;QAClBC,wCAAmB,CAACC,cAAc,CAAC;QAEnC,IAAI;YACF,IAAI,CAACP,aAAa;gBAChB,OAAO;oBACLQ,SAAS;wBACP;4BACEC,MAAM;4BACNC,MAAMC,KAAKC,SAAS,CAAC;gCACnBC,OACE;4BACJ;wBACF;qBACD;gBACH;YACF;YAEA,MAAMC,eAAeb;YAErB,OAAO;gBACLO,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC;4BACnBZ;4BACAc;wBACF;oBACF;iBACD;YACH;QACF,EAAE,OAAOD,OAAO;YACd,OAAO;gBACLL,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC;4BACnBC,OAAOA,iBAAiBE,QAAQF,MAAMG,OAAO,GAAGC,OAAOJ;wBACzD;oBACF;iBACD;YACH;QACF;IACF;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-request-insights.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/get-request-insights.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c15ab77a90c60a334e521527eebbebff1f46853 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-request-insights.d.ts @@ -0,0 +1,2 @@ +import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'; +export declare function registerGetRequestInsightsTool(server: McpServer): void; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-request-insights.js b/e-commerce/node_modules/next/dist/server/mcp/tools/get-request-insights.js new file mode 100644 index 0000000000000000000000000000000000000000..d39e50cd2c07a402fa4de260d6fe1e3013c2bd0d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-request-insights.js @@ -0,0 +1,57 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "registerGetRequestInsightsTool", { + enumerable: true, + get: function() { + return registerGetRequestInsightsTool; + } +}); +const _zod = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/zod")); +const _requestinsights = require("../../lib/trace/request-insights"); +const _mcptelemetrytracker = require("../mcp-telemetry-tracker"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function registerGetRequestInsightsTool(server) { + server.registerTool('get_request_insights', { + description: 'Get recent App Router request insights captured by the local Next.js span recorder. Useful for debugging slow renders, server fetches, cache behavior, and request timelines without an external OTEL collector. Requires experimental.requestInsights.', + inputSchema: { + requestId: _zod.default.string().optional(), + htmlRequestId: _zod.default.string().optional() + } + }, async (request)=>{ + _mcptelemetrytracker.mcpTelemetryTracker.recordToolCall('mcp/get_request_insights'); + if (!(0, _requestinsights.isRequestInsightsEnabled)()) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: 'Request Insights is not enabled. Set experimental.requestInsights = true in next.config.js and restart next dev.' + }) + } + ] + }; + } + const snapshot = (0, _requestinsights.getRequestInsightsSnapshot)(); + const requests = snapshot.requests.filter((insight)=>{ + return (request.requestId === undefined || insight.requestId === request.requestId) && (request.htmlRequestId === undefined || insight.htmlRequestId === request.htmlRequestId); + }); + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + requests + }, null, 2) + } + ] + }; + }); +} + +//# sourceMappingURL=get-request-insights.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-request-insights.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/get-request-insights.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d0296755129bb4d6e3274088195f8490897d67f8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-request-insights.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/mcp/tools/get-request-insights.ts"],"sourcesContent":["import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'\nimport z from 'next/dist/compiled/zod'\nimport {\n getRequestInsightsSnapshot,\n isRequestInsightsEnabled,\n} from '../../lib/trace/request-insights'\nimport { mcpTelemetryTracker } from '../mcp-telemetry-tracker'\n\nexport function registerGetRequestInsightsTool(server: McpServer) {\n server.registerTool(\n 'get_request_insights',\n {\n description:\n 'Get recent App Router request insights captured by the local Next.js span recorder. Useful for debugging slow renders, server fetches, cache behavior, and request timelines without an external OTEL collector. Requires experimental.requestInsights.',\n inputSchema: {\n requestId: z.string().optional(),\n htmlRequestId: z.string().optional(),\n },\n },\n async (request) => {\n mcpTelemetryTracker.recordToolCall('mcp/get_request_insights')\n\n if (!isRequestInsightsEnabled()) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error:\n 'Request Insights is not enabled. Set experimental.requestInsights = true in next.config.js and restart next dev.',\n }),\n },\n ],\n }\n }\n\n const snapshot = getRequestInsightsSnapshot()\n const requests = snapshot.requests.filter((insight) => {\n return (\n (request.requestId === undefined ||\n insight.requestId === request.requestId) &&\n (request.htmlRequestId === undefined ||\n insight.htmlRequestId === request.htmlRequestId)\n )\n })\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ requests }, null, 2),\n },\n ],\n }\n }\n )\n}\n"],"names":["registerGetRequestInsightsTool","server","registerTool","description","inputSchema","requestId","z","string","optional","htmlRequestId","request","mcpTelemetryTracker","recordToolCall","isRequestInsightsEnabled","content","type","text","JSON","stringify","error","snapshot","getRequestInsightsSnapshot","requests","filter","insight","undefined"],"mappings":";;;;+BAQgBA;;;eAAAA;;;4DAPF;iCAIP;qCAC6B;;;;;;AAE7B,SAASA,+BAA+BC,MAAiB;IAC9DA,OAAOC,YAAY,CACjB,wBACA;QACEC,aACE;QACFC,aAAa;YACXC,WAAWC,YAAC,CAACC,MAAM,GAAGC,QAAQ;YAC9BC,eAAeH,YAAC,CAACC,MAAM,GAAGC,QAAQ;QACpC;IACF,GACA,OAAOE;QACLC,wCAAmB,CAACC,cAAc,CAAC;QAEnC,IAAI,CAACC,IAAAA,yCAAwB,KAAI;YAC/B,OAAO;gBACLC,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC;4BACnBC,OACE;wBACJ;oBACF;iBACD;YACH;QACF;QAEA,MAAMC,WAAWC,IAAAA,2CAA0B;QAC3C,MAAMC,WAAWF,SAASE,QAAQ,CAACC,MAAM,CAAC,CAACC;YACzC,OACE,AAACd,CAAAA,QAAQL,SAAS,KAAKoB,aACrBD,QAAQnB,SAAS,KAAKK,QAAQL,SAAS,AAAD,KACvCK,CAAAA,QAAQD,aAAa,KAAKgB,aACzBD,QAAQf,aAAa,KAAKC,QAAQD,aAAa,AAAD;QAEpD;QAEA,OAAO;YACLK,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAMC,KAAKC,SAAS,CAAC;wBAAEI;oBAAS,GAAG,MAAM;gBAC3C;aACD;QACH;IACF;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-routes.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/get-routes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d257555d5b6bfc093c682b927d2c5144cd6f7dd --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-routes.d.ts @@ -0,0 +1,22 @@ +/** + * MCP tool for getting all routes that become entry points in a Next.js application. + * + * This tool discovers routes by scanning the filesystem directly. It finds all route + * files in the app/ and pages/ directories and converts them to route paths. + * + * Returns routes grouped by router type: + * - appRouter: App Router pages and route handlers + * - pagesRouter: Pages Router pages and API routes + * + * Dynamic route segments appear as [id], [slug], or [...slug] patterns. This tool + * does NOT expand getStaticParams - it only shows the route patterns as defined in + * the filesystem. + */ +import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'; +import type { NextConfigComplete } from '../../../server/config-shared'; +export declare function registerGetRoutesTool(server: McpServer, options: { + projectPath: string; + nextConfig: NextConfigComplete; + pagesDir: string | undefined; + appDir: string | undefined; +}): void; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-routes.js b/e-commerce/node_modules/next/dist/server/mcp/tools/get-routes.js new file mode 100644 index 0000000000000000000000000000000000000000..56e756bec3a98b9bc31381d969602517581959da --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-routes.js @@ -0,0 +1,136 @@ +/** + * MCP tool for getting all routes that become entry points in a Next.js application. + * + * This tool discovers routes by scanning the filesystem directly. It finds all route + * files in the app/ and pages/ directories and converts them to route paths. + * + * Returns routes grouped by router type: + * - appRouter: App Router pages and route handlers + * - pagesRouter: Pages Router pages and API routes + * + * Dynamic route segments appear as [id], [slug], or [...slug] patterns. This tool + * does NOT expand getStaticParams - it only shows the route patterns as defined in + * the filesystem. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "registerGetRoutesTool", { + enumerable: true, + get: function() { + return registerGetRoutesTool; + } +}); +const _mcptelemetrytracker = require("../mcp-telemetry-tracker"); +const _routediscovery = require("../../../build/route-discovery"); +const _zod = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/zod")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function registerGetRoutesTool(server, options) { + server.registerTool('get_routes', { + description: 'Get all routes that will become entry points in the Next.js application by scanning the filesystem. Returns routes grouped by router type (appRouter, pagesRouter). Dynamic segments appear as [param] or [...slug] patterns. API routes are included in their respective routers (e.g., /api/* routes from pages/ are in pagesRouter). Optional parameter: routerType ("app" | "pages") - filter by specific router type, omit to get all routes.', + inputSchema: { + routerType: _zod.default.union([ + _zod.default.literal('app'), + _zod.default.literal('pages') + ]).optional() + } + }, async (request)=>{ + // Track telemetry + _mcptelemetrytracker.mcpTelemetryTracker.recordToolCall('mcp/get_routes'); + try { + const routerType = request.routerType === 'app' || request.routerType === 'pages' ? request.routerType : undefined; + const { projectPath, nextConfig, pagesDir, appDir } = options; + // Check if we have any directories to scan + if (!pagesDir && !appDir) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: 'No pages or app directory found in the project.' + }) + } + ] + }; + } + const isSrcDir = pagesDir && pagesDir.includes('/src/') || appDir && appDir.includes('/src/'); + const commonOpts = { + pageExtensions: nextConfig.pageExtensions, + isDev: true, + baseDir: projectPath, + isSrcDir: !!isSrcDir + }; + // Discover app and pages routes independently so a failure in one + // router doesn't prevent the other from returning results. + let appRoutes = []; + let pageRoutes = []; + const wantApp = routerType !== 'pages' && appDir; + const wantPages = routerType !== 'app' && pagesDir; + const [appResult, pagesResult] = await Promise.all([ + wantApp ? (0, _routediscovery.discoverRoutes)({ + ...commonOpts, + appDir + }).catch(()=>null) : null, + wantPages ? (0, _routediscovery.discoverRoutes)({ + ...commonOpts, + pagesDir + }).catch(()=>null) : null + ]); + if (appResult) { + appRoutes = [ + ...appResult.appRoutes, + ...appResult.appRouteHandlers + ].map((r)=>r.route).sort(); + } + if (pagesResult) { + pageRoutes = [ + ...pagesResult.pageRoutes, + ...pagesResult.pageApiRoutes + ].map((r)=>r.route).sort(); + } + if (appRoutes.length === 0 && pageRoutes.length === 0) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + appRouter: [], + pagesRouter: [] + }) + } + ] + }; + } + // Format the output with grouped routes + const output = { + appRouter: appRoutes.length > 0 ? appRoutes : undefined, + pagesRouter: pageRoutes.length > 0 ? pageRoutes : undefined + }; + return { + content: [ + { + type: 'text', + text: JSON.stringify(output, null, 2) + } + ] + }; + } catch (error) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: error instanceof Error ? error.message : String(error) + }) + } + ] + }; + } + }); +} + +//# sourceMappingURL=get-routes.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-routes.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/get-routes.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8b998307ffd2656b5da3f6c98c8a3a167c22f055 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-routes.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/mcp/tools/get-routes.ts"],"sourcesContent":["/**\n * MCP tool for getting all routes that become entry points in a Next.js application.\n *\n * This tool discovers routes by scanning the filesystem directly. It finds all route\n * files in the app/ and pages/ directories and converts them to route paths.\n *\n * Returns routes grouped by router type:\n * - appRouter: App Router pages and route handlers\n * - pagesRouter: Pages Router pages and API routes\n *\n * Dynamic route segments appear as [id], [slug], or [...slug] patterns. This tool\n * does NOT expand getStaticParams - it only shows the route patterns as defined in\n * the filesystem.\n */\nimport type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'\nimport { mcpTelemetryTracker } from '../mcp-telemetry-tracker'\nimport { discoverRoutes } from '../../../build/route-discovery'\nimport type { NextConfigComplete } from '../../../server/config-shared'\nimport z from 'next/dist/compiled/zod'\n\nexport function registerGetRoutesTool(\n server: McpServer,\n options: {\n projectPath: string\n nextConfig: NextConfigComplete\n pagesDir: string | undefined\n appDir: string | undefined\n }\n) {\n server.registerTool(\n 'get_routes',\n {\n description:\n 'Get all routes that will become entry points in the Next.js application by scanning the filesystem. Returns routes grouped by router type (appRouter, pagesRouter). Dynamic segments appear as [param] or [...slug] patterns. API routes are included in their respective routers (e.g., /api/* routes from pages/ are in pagesRouter). Optional parameter: routerType (\"app\" | \"pages\") - filter by specific router type, omit to get all routes.',\n inputSchema: {\n routerType: z.union([z.literal('app'), z.literal('pages')]).optional(),\n },\n },\n async (request) => {\n // Track telemetry\n mcpTelemetryTracker.recordToolCall('mcp/get_routes')\n\n try {\n const routerType =\n request.routerType === 'app' || request.routerType === 'pages'\n ? request.routerType\n : undefined\n\n const { projectPath, nextConfig, pagesDir, appDir } = options\n\n // Check if we have any directories to scan\n if (!pagesDir && !appDir) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: 'No pages or app directory found in the project.',\n }),\n },\n ],\n }\n }\n\n const isSrcDir =\n (pagesDir && pagesDir.includes('/src/')) ||\n (appDir && appDir.includes('/src/'))\n\n const commonOpts = {\n pageExtensions: nextConfig.pageExtensions,\n isDev: true,\n baseDir: projectPath,\n isSrcDir: !!isSrcDir,\n } as const\n\n // Discover app and pages routes independently so a failure in one\n // router doesn't prevent the other from returning results.\n let appRoutes: string[] = []\n let pageRoutes: string[] = []\n\n const wantApp = routerType !== 'pages' && appDir\n const wantPages = routerType !== 'app' && pagesDir\n\n const [appResult, pagesResult] = await Promise.all([\n wantApp\n ? discoverRoutes({ ...commonOpts, appDir }).catch(() => null)\n : null,\n wantPages\n ? discoverRoutes({ ...commonOpts, pagesDir }).catch(() => null)\n : null,\n ])\n\n if (appResult) {\n appRoutes = [...appResult.appRoutes, ...appResult.appRouteHandlers]\n .map((r) => r.route)\n .sort()\n }\n\n if (pagesResult) {\n pageRoutes = [...pagesResult.pageRoutes, ...pagesResult.pageApiRoutes]\n .map((r) => r.route)\n .sort()\n }\n\n if (appRoutes.length === 0 && pageRoutes.length === 0) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n appRouter: [],\n pagesRouter: [],\n }),\n },\n ],\n }\n }\n\n // Format the output with grouped routes\n const output = {\n appRouter: appRoutes.length > 0 ? appRoutes : undefined,\n pagesRouter: pageRoutes.length > 0 ? pageRoutes : undefined,\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(output, null, 2),\n },\n ],\n }\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: error instanceof Error ? error.message : String(error),\n }),\n },\n ],\n }\n }\n }\n )\n}\n"],"names":["registerGetRoutesTool","server","options","registerTool","description","inputSchema","routerType","z","union","literal","optional","request","mcpTelemetryTracker","recordToolCall","undefined","projectPath","nextConfig","pagesDir","appDir","content","type","text","JSON","stringify","error","isSrcDir","includes","commonOpts","pageExtensions","isDev","baseDir","appRoutes","pageRoutes","wantApp","wantPages","appResult","pagesResult","Promise","all","discoverRoutes","catch","appRouteHandlers","map","r","route","sort","pageApiRoutes","length","appRouter","pagesRouter","output","Error","message","String"],"mappings":"AAAA;;;;;;;;;;;;;CAaC;;;;+BAOeA;;;eAAAA;;;qCALoB;gCACL;4DAEjB;;;;;;AAEP,SAASA,sBACdC,MAAiB,EACjBC,OAKC;IAEDD,OAAOE,YAAY,CACjB,cACA;QACEC,aACE;QACFC,aAAa;YACXC,YAAYC,YAAC,CAACC,KAAK,CAAC;gBAACD,YAAC,CAACE,OAAO,CAAC;gBAAQF,YAAC,CAACE,OAAO,CAAC;aAAS,EAAEC,QAAQ;QACtE;IACF,GACA,OAAOC;QACL,kBAAkB;QAClBC,wCAAmB,CAACC,cAAc,CAAC;QAEnC,IAAI;YACF,MAAMP,aACJK,QAAQL,UAAU,KAAK,SAASK,QAAQL,UAAU,KAAK,UACnDK,QAAQL,UAAU,GAClBQ;YAEN,MAAM,EAAEC,WAAW,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,MAAM,EAAE,GAAGhB;YAEtD,2CAA2C;YAC3C,IAAI,CAACe,YAAY,CAACC,QAAQ;gBACxB,OAAO;oBACLC,SAAS;wBACP;4BACEC,MAAM;4BACNC,MAAMC,KAAKC,SAAS,CAAC;gCACnBC,OAAO;4BACT;wBACF;qBACD;gBACH;YACF;YAEA,MAAMC,WACJ,AAACR,YAAYA,SAASS,QAAQ,CAAC,YAC9BR,UAAUA,OAAOQ,QAAQ,CAAC;YAE7B,MAAMC,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;wBACNC,MAAMC,KAAKC,SAAS,CAAC2B,QAAQ,MAAM;oBACrC;iBACD;YACH;QACF,EAAE,OAAO1B,OAAO;YACd,OAAO;gBACLL,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC;4BACnBC,OAAOA,iBAAiB2B,QAAQ3B,MAAM4B,OAAO,GAAGC,OAAO7B;wBACzD;oBACF;iBACD;YACH;QACF;IACF;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-server-action-by-id.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/get-server-action-by-id.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a88baf932b90f81f01a01e9eb9cd47d8fdcd0f80 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-server-action-by-id.d.ts @@ -0,0 +1,2 @@ +import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'; +export declare function registerGetActionByIdTool(server: McpServer, distDir: string): void; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-server-action-by-id.js b/e-commerce/node_modules/next/dist/server/mcp/tools/get-server-action-by-id.js new file mode 100644 index 0000000000000000000000000000000000000000..6d5fcb07463f9391ae51a5d99cc09c8662c97d36 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-server-action-by-id.js @@ -0,0 +1,121 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "registerGetActionByIdTool", { + enumerable: true, + get: function() { + return registerGetActionByIdTool; + } +}); +const _zod = require("next/dist/compiled/zod"); +const _fs = require("fs"); +const _path = require("path"); +const _mcptelemetrytracker = require("../mcp-telemetry-tracker"); +const INLINE_ACTION_PREFIX = '$$RSC_SERVER_ACTION_'; +function registerGetActionByIdTool(server, distDir) { + server.registerTool('get_server_action_by_id', { + description: 'Locates a Server Action by its ID in the server-reference-manifest.json. Returns the filename and export name for the action.', + inputSchema: { + actionId: _zod.z.string() + } + }, async (request)=>{ + // Track telemetry + _mcptelemetrytracker.mcpTelemetryTracker.recordToolCall('mcp/get_server_action_by_id'); + try { + const { actionId } = request; + if (!actionId) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: 'actionId parameter is required' + }) + } + ] + }; + } + const manifestPath = (0, _path.join)(distDir, 'server', 'server-reference-manifest.json'); + let manifestContent; + try { + manifestContent = await _fs.promises.readFile(manifestPath, 'utf-8'); + } catch (error) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: `Could not read server-reference-manifest.json at ${manifestPath}.` + }) + } + ] + }; + } + const manifest = JSON.parse(manifestContent); + // Search in node entries + if (manifest.node && manifest.node[actionId]) { + const entry = manifest.node[actionId]; + const isInlineAction = entry.exportedName.startsWith(INLINE_ACTION_PREFIX); + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + actionId, + runtime: 'node', + filename: entry.filename, + functionName: isInlineAction ? 'inline server action' : entry.exportedName, + layer: entry.layer, + workers: entry.workers + }, null, 2) + } + ] + }; + } + // Search in edge entries + if (manifest.edge && manifest.edge[actionId]) { + const entry = manifest.edge[actionId]; + const isInlineAction = entry.exportedName.startsWith(INLINE_ACTION_PREFIX); + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + actionId, + runtime: 'edge', + filename: entry.filename, + functionName: isInlineAction ? 'inline server action' : entry.exportedName, + layer: entry.layer, + workers: entry.workers + }, null, 2) + } + ] + }; + } + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: `Action ID "${actionId}" not found in server-reference-manifest.json` + }) + } + ] + }; + } catch (error) { + return { + content: [ + { + type: 'text', + text: JSON.stringify({ + error: error instanceof Error ? error.message : String(error) + }) + } + ] + }; + } + }); +} + +//# sourceMappingURL=get-server-action-by-id.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/get-server-action-by-id.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/get-server-action-by-id.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ce4e339eaf54a6b00da8ed8649bace7d1d91a066 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/get-server-action-by-id.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/mcp/tools/get-server-action-by-id.ts"],"sourcesContent":["import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'\nimport { z } from 'next/dist/compiled/zod'\nimport { promises as fs } from 'fs'\nimport { join } from 'path'\nimport { mcpTelemetryTracker } from '../mcp-telemetry-tracker'\n\nconst INLINE_ACTION_PREFIX = '$$RSC_SERVER_ACTION_'\n\ninterface ActionEntry {\n workers?: Record\n layer?: Record\n filename: string\n exportedName: string\n}\n\ninterface ServerReferenceManifest {\n node: Record\n edge: Record\n encryptionKey: string\n}\n\nexport function registerGetActionByIdTool(server: McpServer, distDir: string) {\n server.registerTool(\n 'get_server_action_by_id',\n {\n description:\n 'Locates a Server Action by its ID in the server-reference-manifest.json. Returns the filename and export name for the action.',\n inputSchema: {\n actionId: z.string(),\n },\n },\n async (request) => {\n // Track telemetry\n mcpTelemetryTracker.recordToolCall('mcp/get_server_action_by_id')\n\n try {\n const { actionId } = request\n\n if (!actionId) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: 'actionId parameter is required',\n }),\n },\n ],\n }\n }\n\n const manifestPath = join(\n distDir,\n 'server',\n 'server-reference-manifest.json'\n )\n\n let manifestContent: string\n try {\n manifestContent = await fs.readFile(manifestPath, 'utf-8')\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: `Could not read server-reference-manifest.json at ${manifestPath}.`,\n }),\n },\n ],\n }\n }\n\n const manifest: ServerReferenceManifest = JSON.parse(manifestContent)\n\n // Search in node entries\n if (manifest.node && manifest.node[actionId]) {\n const entry = manifest.node[actionId]\n const isInlineAction =\n entry.exportedName.startsWith(INLINE_ACTION_PREFIX)\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n actionId,\n runtime: 'node',\n filename: entry.filename,\n functionName: isInlineAction\n ? 'inline server action'\n : entry.exportedName,\n layer: entry.layer,\n workers: entry.workers,\n },\n null,\n 2\n ),\n },\n ],\n }\n }\n\n // Search in edge entries\n if (manifest.edge && manifest.edge[actionId]) {\n const entry = manifest.edge[actionId]\n const isInlineAction =\n entry.exportedName.startsWith(INLINE_ACTION_PREFIX)\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n actionId,\n runtime: 'edge',\n filename: entry.filename,\n functionName: isInlineAction\n ? 'inline server action'\n : entry.exportedName,\n layer: entry.layer,\n workers: entry.workers,\n },\n null,\n 2\n ),\n },\n ],\n }\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: `Action ID \"${actionId}\" not found in server-reference-manifest.json`,\n }),\n },\n ],\n }\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({\n error: error instanceof Error ? error.message : String(error),\n }),\n },\n ],\n }\n }\n }\n )\n}\n"],"names":["registerGetActionByIdTool","INLINE_ACTION_PREFIX","server","distDir","registerTool","description","inputSchema","actionId","z","string","request","mcpTelemetryTracker","recordToolCall","content","type","text","JSON","stringify","error","manifestPath","join","manifestContent","fs","readFile","manifest","parse","node","entry","isInlineAction","exportedName","startsWith","runtime","filename","functionName","layer","workers","edge","Error","message","String"],"mappings":";;;;+BAqBgBA;;;eAAAA;;;qBApBE;oBACa;sBACV;qCACe;AAEpC,MAAMC,uBAAuB;AAetB,SAASD,0BAA0BE,MAAiB,EAAEC,OAAe;IAC1ED,OAAOE,YAAY,CACjB,2BACA;QACEC,aACE;QACFC,aAAa;YACXC,UAAUC,MAAC,CAACC,MAAM;QACpB;IACF,GACA,OAAOC;QACL,kBAAkB;QAClBC,wCAAmB,CAACC,cAAc,CAAC;QAEnC,IAAI;YACF,MAAM,EAAEL,QAAQ,EAAE,GAAGG;YAErB,IAAI,CAACH,UAAU;gBACb,OAAO;oBACLM,SAAS;wBAC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BC,cAAcL,iBACV,yBACAD,MAAME,YAAY;gCACtBK,OAAOP,MAAMO,KAAK;gCAClBC,SAASR,MAAMQ,OAAO;4BACxB,GACA,MACA;wBAEJ;qBACD;gBACH;YACF;YAEA,OAAO;gBACLtB,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC;4BACnBC,OAAO,CAAC,WAAW,EAAEX,SAAS,6CAA6C,CAAC;wBAC9E;oBACF;iBACD;YACH;QACF,EAAE,OAAOW,OAAO;YACd,OAAO;gBACLL,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAMC,KAAKC,SAAS,CAAC;4BACnBC,OAAOA,iBAAiBmB,QAAQnB,MAAMoB,OAAO,GAAGC,OAAOrB;wBACzD;oBACF;iBACD;YACH;QACF;IACF;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/next-instance-error-state.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/next-instance-error-state.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c903fb502be1ef4191830b6856612edac7416fa3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/next-instance-error-state.d.ts @@ -0,0 +1,20 @@ +/** + * Global error state for Next.js instance-level errors that are not associated + * with a specific browser session or route. This state is exposed through the MCP server's `get_errors` + * tool as well. This covers the errors that are global to the Next.js instance, such as errors in next.config.js. + * + * + * ## Usage + * + * This state is directly manipulated by various parts of the Next.js dev server: + * + * // Reset the error state + * NextInstanceErrorState.[errorType] = [] + * + * // Capture an error for a specific error type + * NextInstanceErrorState.[errorType].push(err) + * + */ +export declare const NextInstanceErrorState: { + nextConfig: unknown[]; +}; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/next-instance-error-state.js b/e-commerce/node_modules/next/dist/server/mcp/tools/next-instance-error-state.js new file mode 100644 index 0000000000000000000000000000000000000000..688abbdad98fe3d437dfd1da319e803b407d42b0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/next-instance-error-state.js @@ -0,0 +1,31 @@ +/** + * Global error state for Next.js instance-level errors that are not associated + * with a specific browser session or route. This state is exposed through the MCP server's `get_errors` + * tool as well. This covers the errors that are global to the Next.js instance, such as errors in next.config.js. + * + * + * ## Usage + * + * This state is directly manipulated by various parts of the Next.js dev server: + * + * // Reset the error state + * NextInstanceErrorState.[errorType] = [] + * + * // Capture an error for a specific error type + * NextInstanceErrorState.[errorType].push(err) + * + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NextInstanceErrorState", { + enumerable: true, + get: function() { + return NextInstanceErrorState; + } +}); +const NextInstanceErrorState = { + nextConfig: [] +}; + +//# sourceMappingURL=next-instance-error-state.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/next-instance-error-state.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/next-instance-error-state.js.map new file mode 100644 index 0000000000000000000000000000000000000000..21cd23491c578e7459cb61db0f312d2264b7e347 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/next-instance-error-state.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/mcp/tools/next-instance-error-state.ts"],"sourcesContent":["/**\n * Global error state for Next.js instance-level errors that are not associated\n * with a specific browser session or route. This state is exposed through the MCP server's `get_errors`\n * tool as well. This covers the errors that are global to the Next.js instance, such as errors in next.config.js.\n *\n *\n * ## Usage\n *\n * This state is directly manipulated by various parts of the Next.js dev server:\n *\n * // Reset the error state\n * NextInstanceErrorState.[errorType] = []\n *\n * // Capture an error for a specific error type\n * NextInstanceErrorState.[errorType].push(err)\n *\n */\nexport const NextInstanceErrorState: {\n nextConfig: unknown[]\n} = {\n nextConfig: [],\n}\n"],"names":["NextInstanceErrorState","nextConfig"],"mappings":"AAAA;;;;;;;;;;;;;;;;CAgBC;;;;+BACYA;;;eAAAA;;;AAAN,MAAMA,yBAET;IACFC,YAAY,EAAE;AAChB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/browser-communication.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/browser-communication.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec55ac74247181694c1b10555d334b64b2a012a5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/browser-communication.d.ts @@ -0,0 +1,13 @@ +/** + * Shared utilities for MCP tools that communicate with the browser. + * This module provides a common infrastructure for request-response + * communication between MCP endpoints and browser sessions via HMR. + */ +import type { HMR_MESSAGE_SENT_TO_BROWSER, HmrMessageSentToBrowser } from '../../../dev/hot-reloader-types'; +export declare const DEFAULT_BROWSER_REQUEST_TIMEOUT_MS = 5000; +export type BrowserResponse = { + url: string; + data: T; +}; +export declare function createBrowserRequest(messageType: HMR_MESSAGE_SENT_TO_BROWSER, sendHmrMessage: (message: HmrMessageSentToBrowser) => void, getActiveConnectionCount: () => number, timeoutMs: number): Promise[]>; +export declare function handleBrowserPageResponse(requestId: string, data: T, url: string): void; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/browser-communication.js b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/browser-communication.js new file mode 100644 index 0000000000000000000000000000000000000000..53230ce2a05246441659ca9b33bf5b85c2adf86e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/browser-communication.js @@ -0,0 +1,82 @@ +/** + * Shared utilities for MCP tools that communicate with the browser. + * This module provides a common infrastructure for request-response + * communication between MCP endpoints and browser sessions via HMR. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + DEFAULT_BROWSER_REQUEST_TIMEOUT_MS: null, + createBrowserRequest: null, + handleBrowserPageResponse: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + DEFAULT_BROWSER_REQUEST_TIMEOUT_MS: function() { + return DEFAULT_BROWSER_REQUEST_TIMEOUT_MS; + }, + createBrowserRequest: function() { + return createBrowserRequest; + }, + handleBrowserPageResponse: function() { + return handleBrowserPageResponse; + } +}); +const _nanoid = require("next/dist/compiled/nanoid"); +const DEFAULT_BROWSER_REQUEST_TIMEOUT_MS = 5000; +const pendingRequests = new Map(); +function createBrowserRequest(messageType, sendHmrMessage, getActiveConnectionCount, timeoutMs) { + const connectionCount = getActiveConnectionCount(); + if (connectionCount === 0) { + return Promise.resolve([]); + } + const requestId = `mcp-${messageType}-${(0, _nanoid.nanoid)()}`; + const responsePromise = new Promise((resolve, reject)=>{ + const timeout = setTimeout(()=>{ + const pending = pendingRequests.get(requestId); + if (pending && pending.responses.length > 0) { + resolve(pending.responses); + } else { + reject(new Error(`Timeout waiting for response from frontend. The browser may not be responding to HMR messages.`)); + } + pendingRequests.delete(requestId); + }, timeoutMs); + pendingRequests.set(requestId, { + responses: [], + expectedCount: connectionCount, + resolve: resolve, + reject, + timeout + }); + }); + sendHmrMessage({ + type: messageType, + requestId + }); + return responsePromise; +} +function handleBrowserPageResponse(requestId, data, url) { + if (!url) { + throw new Error('URL is required in MCP browser response. This is a bug in Next.js.'); + } + const pending = pendingRequests.get(requestId); + if (pending) { + pending.responses.push({ + url, + data + }); + if (pending.responses.length >= pending.expectedCount) { + clearTimeout(pending.timeout); + pending.resolve(pending.responses); + pendingRequests.delete(requestId); + } + } +} + +//# sourceMappingURL=browser-communication.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/browser-communication.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/browser-communication.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4d357b7f705384df93d6546ec76442ded30887e7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/browser-communication.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/mcp/tools/utils/browser-communication.ts"],"sourcesContent":["/**\n * Shared utilities for MCP tools that communicate with the browser.\n * This module provides a common infrastructure for request-response\n * communication between MCP endpoints and browser sessions via HMR.\n */\n\nimport { nanoid } from 'next/dist/compiled/nanoid'\nimport type {\n HMR_MESSAGE_SENT_TO_BROWSER,\n HmrMessageSentToBrowser,\n} from '../../../dev/hot-reloader-types'\n\nexport const DEFAULT_BROWSER_REQUEST_TIMEOUT_MS = 5000\n\nexport type BrowserResponse = {\n url: string\n data: T\n}\n\ntype PendingRequest = {\n responses: BrowserResponse[]\n expectedCount: number\n resolve: (value: BrowserResponse[]) => void\n reject: (reason?: unknown) => void\n timeout: NodeJS.Timeout\n}\n\nconst pendingRequests = new Map>()\n\nexport function createBrowserRequest(\n messageType: HMR_MESSAGE_SENT_TO_BROWSER,\n sendHmrMessage: (message: HmrMessageSentToBrowser) => void,\n getActiveConnectionCount: () => number,\n timeoutMs: number\n): Promise[]> {\n const connectionCount = getActiveConnectionCount()\n if (connectionCount === 0) {\n return Promise.resolve([])\n }\n\n const requestId = `mcp-${messageType}-${nanoid()}`\n\n const responsePromise = new Promise[]>(\n (resolve, reject) => {\n const timeout = setTimeout(() => {\n const pending = pendingRequests.get(requestId)\n if (pending && pending.responses.length > 0) {\n resolve(pending.responses as BrowserResponse[])\n } else {\n reject(\n new Error(\n `Timeout waiting for response from frontend. The browser may not be responding to HMR messages.`\n )\n )\n }\n pendingRequests.delete(requestId)\n }, timeoutMs)\n\n pendingRequests.set(requestId, {\n responses: [],\n expectedCount: connectionCount,\n resolve: resolve as (value: BrowserResponse[]) => void,\n reject,\n timeout,\n })\n }\n )\n\n sendHmrMessage({\n type: messageType,\n requestId,\n } as HmrMessageSentToBrowser)\n\n return responsePromise\n}\n\nexport function handleBrowserPageResponse(\n requestId: string,\n data: T,\n url: string\n): void {\n if (!url) {\n throw new Error(\n 'URL is required in MCP browser response. This is a bug in Next.js.'\n )\n }\n\n const pending = pendingRequests.get(requestId)\n if (pending) {\n pending.responses.push({ url, data })\n if (pending.responses.length >= pending.expectedCount) {\n clearTimeout(pending.timeout)\n pending.resolve(pending.responses)\n pendingRequests.delete(requestId)\n }\n }\n}\n"],"names":["DEFAULT_BROWSER_REQUEST_TIMEOUT_MS","createBrowserRequest","handleBrowserPageResponse","pendingRequests","Map","messageType","sendHmrMessage","getActiveConnectionCount","timeoutMs","connectionCount","Promise","resolve","requestId","nanoid","responsePromise","reject","timeout","setTimeout","pending","get","responses","length","Error","delete","set","expectedCount","type","data","url","push","clearTimeout"],"mappings":"AAAA;;;;CAIC;;;;;;;;;;;;;;;;IAQYA,kCAAkC;eAAlCA;;IAiBGC,oBAAoB;eAApBA;;IA+CAC,yBAAyB;eAAzBA;;;wBAtEO;AAMhB,MAAMF,qCAAqC;AAelD,MAAMG,kBAAkB,IAAIC;AAErB,SAASH,qBACdI,WAAwC,EACxCC,cAA0D,EAC1DC,wBAAsC,EACtCC,SAAiB;IAEjB,MAAMC,kBAAkBF;IACxB,IAAIE,oBAAoB,GAAG;QACzB,OAAOC,QAAQC,OAAO,CAAC,EAAE;IAC3B;IAEA,MAAMC,YAAY,CAAC,IAAI,EAAEP,YAAY,CAAC,EAAEQ,IAAAA,cAAM,KAAI;IAElD,MAAMC,kBAAkB,IAAIJ,QAC1B,CAACC,SAASI;QACR,MAAMC,UAAUC,WAAW;YACzB,MAAMC,UAAUf,gBAAgBgB,GAAG,CAACP;YACpC,IAAIM,WAAWA,QAAQE,SAAS,CAACC,MAAM,GAAG,GAAG;gBAC3CV,QAAQO,QAAQE,SAAS;YAC3B,OAAO;gBACLL,OACE,IAAIO,MACF,CAAC,8FAA8F,CAAC;YAGtG;YACAnB,gBAAgBoB,MAAM,CAACX;QACzB,GAAGJ;QAEHL,gBAAgBqB,GAAG,CAACZ,WAAW;YAC7BQ,WAAW,EAAE;YACbK,eAAehB;YACfE,SAASA;YACTI;YACAC;QACF;IACF;IAGFV,eAAe;QACboB,MAAMrB;QACNO;IACF;IAEA,OAAOE;AACT;AAEO,SAASZ,0BACdU,SAAiB,EACjBe,IAAO,EACPC,GAAW;IAEX,IAAI,CAACA,KAAK;QACR,MAAM,IAAIN,MACR;IAEJ;IAEA,MAAMJ,UAAUf,gBAAgBgB,GAAG,CAACP;IACpC,IAAIM,SAAS;QACXA,QAAQE,SAAS,CAACS,IAAI,CAAC;YAAED;YAAKD;QAAK;QACnC,IAAIT,QAAQE,SAAS,CAACC,MAAM,IAAIH,QAAQO,aAAa,EAAE;YACrDK,aAAaZ,QAAQF,OAAO;YAC5BE,QAAQP,OAAO,CAACO,QAAQE,SAAS;YACjCjB,gBAAgBoB,MAAM,CAACX;QACzB;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-compilation-issues.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-compilation-issues.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..73b17133468762df1f13aefdda4958aecbe7b1f4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-compilation-issues.d.ts @@ -0,0 +1,33 @@ +import type { Issue } from '../../../../build/swc/types'; +export interface FormattedIssue { + severity: string; + filePath: string; + title: string; + description?: string; + detail?: string; + source?: { + filePath: string; + range?: { + /** 1-indexed */ + start: { + line: number; + column: number; + }; + /** 1-indexed */ + end: { + line: number; + column: number; + }; + }; + }; + /** Code frame with ANSI codes stripped */ + codeFrame?: string; +} +/** + * Transform raw Turbopack issues into a clean format for MCP consumers: + * - Converts StyledString trees (title/description/detail) to Markdown + * - Strips ANSI codes from code frames + * - Converts 0-indexed source positions to 1-indexed + * - Deduplicates issues (same error can surface from multiple endpoints) + */ +export declare function formatCompilationIssues(issues: Issue[]): FormattedIssue[]; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-compilation-issues.js b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-compilation-issues.js new file mode 100644 index 0000000000000000000000000000000000000000..1314600c7d5129e15a0a5bcc10ba54a6111e3a2b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-compilation-issues.js @@ -0,0 +1,72 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "formatCompilationIssues", { + enumerable: true, + get: function() { + return formatCompilationIssues; + } +}); +const _stripansi = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/strip-ansi")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +/** Convert a StyledString tree to Markdown. */ function styledStringToMarkdown(s) { + switch(s.type){ + case 'text': + return s.value; + case 'code': + return `\`${s.value}\``; + case 'strong': + return `**${s.value}**`; + case 'line': + return s.value.map(styledStringToMarkdown).join(''); + case 'stack': + return s.value.map(styledStringToMarkdown).join('\n'); + default: + return ''; + } +} +function formatCompilationIssues(issues) { + const seen = new Set(); + const formattedIssues = []; + for (const issue of issues){ + var _issue_source_range, _issue_source, _issue_source_range1, _issue_source1; + const title = styledStringToMarkdown(issue.title); + // Include source position in the key so two distinct errors in the same + // file with the same message are not collapsed into one. + const startLine = ((_issue_source = issue.source) == null ? void 0 : (_issue_source_range = _issue_source.range) == null ? void 0 : _issue_source_range.start.line) ?? ''; + const startCol = ((_issue_source1 = issue.source) == null ? void 0 : (_issue_source_range1 = _issue_source1.range) == null ? void 0 : _issue_source_range1.start.column) ?? ''; + const key = `${issue.severity}|${issue.filePath}|${title}|${startLine}:${startCol}`; + if (seen.has(key)) continue; + seen.add(key); + const { range } = issue.source ?? {}; + formattedIssues.push({ + severity: issue.severity, + filePath: issue.filePath, + title, + description: issue.description ? styledStringToMarkdown(issue.description) : undefined, + detail: issue.detail ? styledStringToMarkdown(issue.detail) : undefined, + source: issue.source ? { + filePath: issue.source.source.filePath, + range: range ? { + start: { + line: range.start.line + 1, + column: range.start.column + 1 + }, + end: { + line: range.end.line + 1, + column: range.end.column + 1 + } + } : undefined + } : undefined, + codeFrame: issue.codeFrame ? (0, _stripansi.default)(issue.codeFrame) : undefined + }); + } + return formattedIssues; +} + +//# sourceMappingURL=format-compilation-issues.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-compilation-issues.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-compilation-issues.js.map new file mode 100644 index 0000000000000000000000000000000000000000..670a9272abdb9d492434e38e570ff10f7e4e6efa --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-compilation-issues.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/mcp/tools/utils/format-compilation-issues.ts"],"sourcesContent":["import type { Issue, StyledString } from '../../../../build/swc/types'\nimport stripAnsi from 'next/dist/compiled/strip-ansi'\n\n/** Convert a StyledString tree to Markdown. */\nfunction styledStringToMarkdown(s: StyledString): string {\n switch (s.type) {\n case 'text':\n return s.value\n case 'code':\n return `\\`${s.value}\\``\n case 'strong':\n return `**${s.value}**`\n case 'line':\n return s.value.map(styledStringToMarkdown).join('')\n case 'stack':\n return s.value.map(styledStringToMarkdown).join('\\n')\n default:\n return ''\n }\n}\n\nexport interface FormattedIssue {\n severity: string\n filePath: string\n title: string\n description?: string\n detail?: string\n source?: {\n filePath: string\n range?: {\n /** 1-indexed */\n start: { line: number; column: number }\n /** 1-indexed */\n end: { line: number; column: number }\n }\n }\n /** Code frame with ANSI codes stripped */\n codeFrame?: string\n}\n\n/**\n * Transform raw Turbopack issues into a clean format for MCP consumers:\n * - Converts StyledString trees (title/description/detail) to Markdown\n * - Strips ANSI codes from code frames\n * - Converts 0-indexed source positions to 1-indexed\n * - Deduplicates issues (same error can surface from multiple endpoints)\n */\nexport function formatCompilationIssues(issues: Issue[]): FormattedIssue[] {\n const seen = new Set()\n const formattedIssues: FormattedIssue[] = []\n\n for (const issue of issues) {\n const title = styledStringToMarkdown(issue.title)\n // Include source position in the key so two distinct errors in the same\n // file with the same message are not collapsed into one.\n const startLine = issue.source?.range?.start.line ?? ''\n const startCol = issue.source?.range?.start.column ?? ''\n const key = `${issue.severity}|${issue.filePath}|${title}|${startLine}:${startCol}`\n if (seen.has(key)) continue\n seen.add(key)\n\n const { range } = issue.source ?? {}\n formattedIssues.push({\n severity: issue.severity,\n filePath: issue.filePath,\n title,\n description: issue.description\n ? styledStringToMarkdown(issue.description)\n : undefined,\n detail: issue.detail ? styledStringToMarkdown(issue.detail) : undefined,\n source: issue.source\n ? {\n filePath: issue.source.source.filePath,\n range: range\n ? {\n start: {\n line: range.start.line + 1,\n column: range.start.column + 1,\n },\n end: {\n line: range.end.line + 1,\n column: range.end.column + 1,\n },\n }\n : undefined,\n }\n : undefined,\n codeFrame: issue.codeFrame ? stripAnsi(issue.codeFrame) : undefined,\n })\n }\n\n return formattedIssues\n}\n"],"names":["formatCompilationIssues","styledStringToMarkdown","s","type","value","map","join","issues","seen","Set","formattedIssues","issue","title","startLine","source","range","start","line","startCol","column","key","severity","filePath","has","add","push","description","undefined","detail","end","codeFrame","stripAnsi"],"mappings":";;;;+BA+CgBA;;;eAAAA;;;kEA9CM;;;;;;AAEtB,6CAA6C,GAC7C,SAASC,uBAAuBC,CAAe;IAC7C,OAAQA,EAAEC,IAAI;QACZ,KAAK;YACH,OAAOD,EAAEE,KAAK;QAChB,KAAK;YACH,OAAO,CAAC,EAAE,EAAEF,EAAEE,KAAK,CAAC,EAAE,CAAC;QACzB,KAAK;YACH,OAAO,CAAC,EAAE,EAAEF,EAAEE,KAAK,CAAC,EAAE,CAAC;QACzB,KAAK;YACH,OAAOF,EAAEE,KAAK,CAACC,GAAG,CAACJ,wBAAwBK,IAAI,CAAC;QAClD,KAAK;YACH,OAAOJ,EAAEE,KAAK,CAACC,GAAG,CAACJ,wBAAwBK,IAAI,CAAC;QAClD;YACE,OAAO;IACX;AACF;AA4BO,SAASN,wBAAwBO,MAAe;IACrD,MAAMC,OAAO,IAAIC;IACjB,MAAMC,kBAAoC,EAAE;IAE5C,KAAK,MAAMC,SAASJ,OAAQ;YAIRI,qBAAAA,eACDA,sBAAAA;QAJjB,MAAMC,QAAQX,uBAAuBU,MAAMC,KAAK;QAChD,wEAAwE;QACxE,yDAA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ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-errors.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8851fbe1135c00d4d2f1d19e5e391f57f6b0a5ca --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-errors.d.ts @@ -0,0 +1,35 @@ +import type { OverlayState } from '../../../../next-devtools/dev-overlay/shared'; +import type { OriginalStackFramesRequest, OriginalStackFramesResponse } from '../../../../next-devtools/server/shared'; +type StackFrameResolver = (request: OriginalStackFramesRequest) => Promise; +export declare function setStackFrameResolver(fn: StackFrameResolver): void; +export declare function resolveStackFrames(request: OriginalStackFramesRequest): Promise; +interface StackFrame { + file: string; + methodName: string; + line: number | null; + column: number | null; +} +interface FormattedRuntimeError { + type: string; + errorName: string; + message: string; + stack: StackFrame[]; +} +interface FormattedSessionError { + url: string; + buildError: string | null; + runtimeErrors: FormattedRuntimeError[]; +} +interface FormattedConfigError { + name: string; + message: string; + stack: string | null; +} +export interface FormattedErrorsOutput { + configErrors: FormattedConfigError[]; + sessionErrors: FormattedSessionError[]; +} +export declare function formatErrors(errorsByUrl: Map, nextInstanceErrors?: { + nextConfig: unknown[]; +}): Promise; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-errors.js b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-errors.js new file mode 100644 index 0000000000000000000000000000000000000000..ca5d1ed4fc627e9e9f9855d63a3ee76ef6f92050 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-errors.js @@ -0,0 +1,137 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + formatErrors: null, + resolveStackFrames: null, + setStackFrameResolver: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + formatErrors: function() { + return formatErrors; + }, + resolveStackFrames: function() { + return resolveStackFrames; + }, + setStackFrameResolver: function() { + return setStackFrameResolver; + } +}); +const _errorsource = require("../../../../shared/lib/error-source"); +// Dependency injection for stack frame resolver +let stackFrameResolver; +function setStackFrameResolver(fn) { + stackFrameResolver = fn; +} +async function resolveStackFrames(request) { + if (!stackFrameResolver) { + throw new Error('Stack frame resolver not initialized. This is a bug in Next.js.'); + } + return stackFrameResolver(request); +} +const formatStackFrameToObject = (frame)=>{ + return { + file: frame.file || '', + methodName: frame.methodName || '', + line: frame.line1, + column: frame.column1 + }; +}; +const resolveErrorFrames = async (frames, context)=>{ + try { + const resolvedFrames = await resolveStackFrames({ + frames: frames.map((frame)=>({ + file: frame.file || null, + methodName: frame.methodName || '', + arguments: [], + line1: frame.line1 || null, + column1: frame.column1 || null + })), + isServer: context.isServer, + isEdgeServer: context.isEdgeServer, + isAppDirectory: context.isAppDirectory + }); + return resolvedFrames.filter((resolvedFrame)=>{ + var _resolvedFrame_value_originalStackFrame; + return !(resolvedFrame.status === 'fulfilled' && ((_resolvedFrame_value_originalStackFrame = resolvedFrame.value.originalStackFrame) == null ? void 0 : _resolvedFrame_value_originalStackFrame.ignored)); + }).map((resolvedFrame, j)=>resolvedFrame.status === 'fulfilled' && resolvedFrame.value.originalStackFrame ? formatStackFrameToObject(resolvedFrame.value.originalStackFrame) : formatStackFrameToObject(frames[j])); + } catch { + return frames.map(formatStackFrameToObject); + } +}; +async function formatRuntimeErrorsToObjects(errors, isAppDirectory) { + const formattedErrors = []; + for (const error of errors){ + var _error_error, _error_error1, _error_frames; + const errorName = ((_error_error = error.error) == null ? void 0 : _error_error.name) || 'Error'; + const errorMsg = ((_error_error1 = error.error) == null ? void 0 : _error_error1.message) || 'Unknown error'; + let stack = []; + if ((_error_frames = error.frames) == null ? void 0 : _error_frames.length) { + const errorSource = (0, _errorsource.getErrorSource)(error.error); + stack = await resolveErrorFrames(error.frames, { + isServer: errorSource === 'server', + isEdgeServer: errorSource === 'edge-server', + isAppDirectory + }); + } + formattedErrors.push({ + type: error.type, + errorName, + message: errorMsg, + stack + }); + } + return formattedErrors; +} +async function formatErrors(errorsByUrl, nextInstanceErrors = { + nextConfig: [] +}) { + const output = { + configErrors: [], + sessionErrors: [] + }; + // Format Next.js instance errors first (e.g., next.config.js errors) + for (const error of nextInstanceErrors.nextConfig){ + if (error instanceof Error) { + output.configErrors.push({ + name: error.name, + message: error.message, + stack: error.stack || null + }); + } else { + output.configErrors.push({ + name: 'Error', + message: String(error), + stack: null + }); + } + } + // Format browser session errors + for (const [url, overlayState] of errorsByUrl){ + const totalErrorCount = overlayState.errors.length + (overlayState.buildError ? 1 : 0); + if (totalErrorCount === 0) continue; + let displayUrl = url; + try { + const urlObj = new URL(url); + displayUrl = urlObj.pathname + urlObj.search + urlObj.hash; + } catch { + // If URL parsing fails, use the original URL + } + const runtimeErrors = await formatRuntimeErrorsToObjects(overlayState.errors, overlayState.routerType === 'app'); + output.sessionErrors.push({ + url: displayUrl, + buildError: overlayState.buildError || null, + runtimeErrors + }); + } + return output; +} + +//# sourceMappingURL=format-errors.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-errors.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-errors.js.map new file mode 100644 index 0000000000000000000000000000000000000000..caf7811fba20b77166cb841e4cfe8aab8c2d1a23 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/format-errors.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/mcp/tools/utils/format-errors.ts"],"sourcesContent":["import type { OverlayState } from '../../../../next-devtools/dev-overlay/shared'\nimport type { SupportedErrorEvent } from '../../../../next-devtools/dev-overlay/container/runtime-error/render-error'\nimport { getErrorSource } from '../../../../shared/lib/error-source'\nimport type {\n OriginalStackFramesRequest,\n OriginalStackFramesResponse,\n} from '../../../../next-devtools/server/shared'\n\ntype StackFrameForFormatting = {\n file: string | null\n methodName: string\n line1: number | null\n column1: number | null\n}\n\ntype StackFrameResolver = (\n request: OriginalStackFramesRequest\n) => Promise\n\n// Dependency injection for stack frame resolver\nlet stackFrameResolver: StackFrameResolver | undefined\n\nexport function setStackFrameResolver(fn: StackFrameResolver) {\n stackFrameResolver = fn\n}\n\nexport async function resolveStackFrames(\n request: OriginalStackFramesRequest\n): Promise {\n if (!stackFrameResolver) {\n throw new Error(\n 'Stack frame resolver not initialized. This is a bug in Next.js.'\n )\n }\n return stackFrameResolver(request)\n}\n\ninterface StackFrame {\n file: string\n methodName: string\n line: number | null\n column: number | null\n}\n\ninterface FormattedRuntimeError {\n type: string\n errorName: string\n message: string\n stack: StackFrame[]\n}\n\ninterface FormattedSessionError {\n url: string\n buildError: string | null\n runtimeErrors: FormattedRuntimeError[]\n}\n\ninterface FormattedConfigError {\n name: string\n message: string\n stack: string | null\n}\n\nexport interface FormattedErrorsOutput {\n configErrors: FormattedConfigError[]\n sessionErrors: FormattedSessionError[]\n}\n\nconst formatStackFrameToObject = (\n frame: StackFrameForFormatting\n): StackFrame => {\n return {\n file: frame.file || '',\n methodName: frame.methodName || '',\n line: frame.line1,\n column: frame.column1,\n }\n}\n\nconst resolveErrorFrames = async (\n frames: readonly StackFrameForFormatting[],\n context: {\n isServer: boolean\n isEdgeServer: boolean\n isAppDirectory: boolean\n }\n): Promise => {\n try {\n const resolvedFrames = await resolveStackFrames({\n frames: frames.map((frame) => ({\n file: frame.file || null,\n methodName: frame.methodName || '',\n arguments: [],\n line1: frame.line1 || null,\n column1: frame.column1 || null,\n })),\n isServer: context.isServer,\n isEdgeServer: context.isEdgeServer,\n isAppDirectory: context.isAppDirectory,\n })\n\n return resolvedFrames\n .filter(\n (resolvedFrame) =>\n !(\n resolvedFrame.status === 'fulfilled' &&\n resolvedFrame.value.originalStackFrame?.ignored\n )\n )\n .map((resolvedFrame, j) =>\n resolvedFrame.status === 'fulfilled' &&\n resolvedFrame.value.originalStackFrame\n ? formatStackFrameToObject(resolvedFrame.value.originalStackFrame)\n : formatStackFrameToObject(frames[j])\n )\n } catch {\n return frames.map(formatStackFrameToObject)\n }\n}\n\nasync function formatRuntimeErrorsToObjects(\n errors: readonly SupportedErrorEvent[],\n isAppDirectory: boolean\n): Promise {\n const formattedErrors: FormattedRuntimeError[] = []\n\n for (const error of errors) {\n const errorName = error.error?.name || 'Error'\n const errorMsg = error.error?.message || 'Unknown error'\n\n let stack: StackFrame[] = []\n if (error.frames?.length) {\n const errorSource = getErrorSource(error.error)\n stack = await resolveErrorFrames(error.frames, {\n isServer: errorSource === 'server',\n isEdgeServer: errorSource === 'edge-server',\n isAppDirectory,\n })\n }\n\n formattedErrors.push({\n type: error.type,\n errorName,\n message: errorMsg,\n stack,\n })\n }\n\n return formattedErrors\n}\n\nexport async function formatErrors(\n errorsByUrl: Map,\n nextInstanceErrors: { nextConfig: unknown[] } = { nextConfig: [] }\n): Promise {\n const output: FormattedErrorsOutput = {\n configErrors: [],\n sessionErrors: [],\n }\n\n // Format Next.js instance errors first (e.g., next.config.js errors)\n for (const error of nextInstanceErrors.nextConfig) {\n if (error instanceof Error) {\n output.configErrors.push({\n name: error.name,\n message: error.message,\n stack: error.stack || null,\n })\n } else {\n output.configErrors.push({\n name: 'Error',\n message: String(error),\n stack: null,\n })\n }\n }\n\n // Format browser session errors\n for (const [url, overlayState] of errorsByUrl) {\n const totalErrorCount =\n overlayState.errors.length + (overlayState.buildError ? 1 : 0)\n\n if (totalErrorCount === 0) continue\n\n let displayUrl = url\n try {\n const urlObj = new URL(url)\n displayUrl = urlObj.pathname + urlObj.search + urlObj.hash\n } catch {\n // If URL parsing fails, use the original URL\n }\n\n const runtimeErrors = await formatRuntimeErrorsToObjects(\n overlayState.errors,\n overlayState.routerType === 'app'\n )\n\n output.sessionErrors.push({\n url: displayUrl,\n buildError: overlayState.buildError || null,\n runtimeErrors,\n })\n }\n\n return output\n}\n"],"names":["formatErrors","resolveStackFrames","setStackFrameResolver","stackFrameResolver","fn","request","Error","formatStackFrameToObject","frame","file","methodName","line","line1","column","column1","resolveErrorFrames","frames","context","resolvedFrames","map","arguments","isServer","isEdgeServer","isAppDirectory","filter","resolvedFrame","status","value","originalStackFrame","ignored","j","formatRuntimeErrorsToObjects","errors","formattedErrors","error","errorName","name","errorMsg","message","stack","length","errorSource","getErrorSource","push","type","errorsByUrl","nextInstanceErrors","nextConfig","output","configErrors","sessionErrors","String","url","overlayState","totalErrorCount","buildError","displayUrl","urlObj","URL","pathname","search","hash","runtimeErrors","routerType"],"mappings":";;;;;;;;;;;;;;;;IAuJsBA,YAAY;eAAZA;;IA7HAC,kBAAkB;eAAlBA;;IAJNC,qBAAqB;eAArBA;;;6BApBe;AAiB/B,gDAAgD;AAChD,IAAIC;AAEG,SAASD,sBAAsBE,EAAsB;IAC1DD,qBAAqBC;AACvB;AAEO,eAAeH,mBACpBI,OAAmC;IAEnC,IAAI,CAACF,oBAAoB;QACvB,MAAM,IAAIG,MACR;IAEJ;IACA,OAAOH,mBAAmBE;AAC5B;AAiCA,MAAME,2BAA2B,CAC/BC;IAEA,OAAO;QACLC,MAAMD,MAAMC,IAAI,IAAI;QACpBC,YAAYF,MAAME,UAAU,IAAI;QAChCC,MAAMH,MAAMI,KAAK;QACjBC,QAAQL,MAAMM,OAAO;IACvB;AACF;AAEA,MAAMC,qBAAqB,OACzBC,QACAC;IAMA,IAAI;QACF,MAAMC,iBAAiB,MAAMjB,mBAAmB;YAC9Ce,QAAQA,OAAOG,GAAG,CAAC,CAACX,QAAW,CAAA;oBAC7BC,MAAMD,MAAMC,IAAI,IAAI;oBACpBC,YAAYF,MAAME,UAAU,IAAI;oBAChCU,WAAW,EAAE;oBACbR,OAAOJ,MAAMI,KAAK,IAAI;oBACtBE,SAASN,MAAMM,OAAO,IAAI;gBAC5B,CAAA;YACAO,UAAUJ,QAAQI,QAAQ;YAC1BC,cAAcL,QAAQK,YAAY;YAClCC,gBAAgBN,QAAQM,cAAc;QACxC;QAEA,OAAOL,eACJM,MAAM,CACL,CAACC;gBAGGA;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AAIb,iBAAiB5B,OAAO;YAC1B0C,OAAOC,YAAY,CAACN,IAAI,CAAC;gBACvBP,MAAMF,MAAME,IAAI;gBAChBE,SAASJ,MAAMI,OAAO;gBACtBC,OAAOL,MAAMK,KAAK,IAAI;YACxB;QACF,OAAO;YACLS,OAAOC,YAAY,CAACN,IAAI,CAAC;gBACvBP,MAAM;gBACNE,SAASa,OAAOjB;gBAChBK,OAAO;YACT;QACF;IACF;IAEA,gCAAgC;IAChC,KAAK,MAAM,CAACa,KAAKC,aAAa,IAAIR,YAAa;QAC7C,MAAMS,kBACJD,aAAarB,MAAM,CAACQ,MAAM,GAAIa,CAAAA,aAAaE,UAAU,GAAG,IAAI,CAAA;QAE9D,IAAID,oBAAoB,GAAG;QAE3B,IAAIE,aAAaJ;QACjB,IAAI;YACF,MAAMK,SAAS,IAAIC,IAAIN;YACvBI,aAAaC,OAAOE,QAAQ,GAAGF,OAAOG,MAAM,GAAGH,OAAOI,IAAI;QAC5D,EAAE,OAAM;QACN,6CAA6C;QAC/C;QAEA,MAAMC,gBAAgB,MAAM/B,6BAC1BsB,aAAarB,MAAM,EACnBqB,aAAaU,UAAU,KAAK;QAG9Bf,OAAOE,aAAa,CAACP,IAAI,CAAC;YACxBS,KAAKI;YACLD,YAAYF,aAAaE,UAAU,IAAI;YACvCO;QACF;IACF;IAEA,OAAOd;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/resolve-path-to-route.d.ts b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/resolve-path-to-route.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e8ce98963ff2e67eb3f52bce648dce853ed00fa2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/resolve-path-to-route.d.ts @@ -0,0 +1,23 @@ +/** + * Resolves a URL path (e.g. "/blog/hello-world") to its matching Next.js route + * specifier (e.g. "/blog/[slug]") using the dev router's own live route table. + * + * The `matchers` argument is a thin view of `fsChecker` from the router-server + * process — the same data structure `resolve-routes.ts` iterates on every + * incoming HTTP request — so first-match ordering and live route updates are + * inherited for free. + */ +export interface RouteMatcherView { + appFiles: ReadonlySet; + pageFiles: ReadonlySet; + dynamicRoutes: ReadonlyArray<{ + page: string; + match: (pathname: string) => false | object; + }>; +} +export declare function resolvePathToRoute(path: string, matchers: RouteMatcherView): { + routeSpecifier: string; +} | { + notFound: true; + pathname: string; +}; diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/resolve-path-to-route.js b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/resolve-path-to-route.js new file mode 100644 index 0000000000000000000000000000000000000000..f41ca35dacf963e0cbda2b9cc8e3673781b2e56e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/resolve-path-to-route.js @@ -0,0 +1,49 @@ +/** + * Resolves a URL path (e.g. "/blog/hello-world") to its matching Next.js route + * specifier (e.g. "/blog/[slug]") using the dev router's own live route table. + * + * The `matchers` argument is a thin view of `fsChecker` from the router-server + * process — the same data structure `resolve-routes.ts` iterates on every + * incoming HTTP request — so first-match ordering and live route updates are + * inherited for free. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "resolvePathToRoute", { + enumerable: true, + get: function() { + return resolvePathToRoute; + } +}); +function resolvePathToRoute(path, matchers) { + let pathname = path; + const q = pathname.indexOf('?'); + if (q >= 0) pathname = pathname.slice(0, q); + const h = pathname.indexOf('#'); + if (h >= 0) pathname = pathname.slice(0, h); + if (!pathname.startsWith('/')) pathname = '/' + pathname; + if (pathname !== '/' && pathname.endsWith('/')) { + pathname = pathname.slice(0, -1); + } + if (matchers.appFiles.has(pathname) || matchers.pageFiles.has(pathname)) { + return { + routeSpecifier: pathname + }; + } + for (const route of matchers.dynamicRoutes){ + // Skip SSG/SSP data-route variants prepended by setup-dev-bundler. + if (route.page.startsWith('/_next/data/')) continue; + if (route.match(pathname)) { + return { + routeSpecifier: route.page + }; + } + } + return { + notFound: true, + pathname + }; +} + +//# sourceMappingURL=resolve-path-to-route.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/mcp/tools/utils/resolve-path-to-route.js.map b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/resolve-path-to-route.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c702e17132b986684d0841b53b24c1bf30deedfe --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/mcp/tools/utils/resolve-path-to-route.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/mcp/tools/utils/resolve-path-to-route.ts"],"sourcesContent":["/**\n * Resolves a URL path (e.g. \"/blog/hello-world\") to its matching Next.js route\n * specifier (e.g. \"/blog/[slug]\") using the dev router's own live route table.\n *\n * The `matchers` argument is a thin view of `fsChecker` from the router-server\n * process — the same data structure `resolve-routes.ts` iterates on every\n * incoming HTTP request — so first-match ordering and live route updates are\n * inherited for free.\n */\nexport interface RouteMatcherView {\n appFiles: ReadonlySet\n pageFiles: ReadonlySet\n dynamicRoutes: ReadonlyArray<{\n page: string\n match: (pathname: string) => false | object\n }>\n}\n\nexport function resolvePathToRoute(\n path: string,\n matchers: RouteMatcherView\n): { routeSpecifier: string } | { notFound: true; pathname: string } {\n let pathname = path\n const q = pathname.indexOf('?')\n if (q >= 0) pathname = pathname.slice(0, q)\n const h = pathname.indexOf('#')\n if (h >= 0) pathname = pathname.slice(0, h)\n if (!pathname.startsWith('/')) pathname = '/' + pathname\n if (pathname !== '/' && pathname.endsWith('/')) {\n pathname = pathname.slice(0, -1)\n }\n\n if (matchers.appFiles.has(pathname) || matchers.pageFiles.has(pathname)) {\n return { routeSpecifier: pathname }\n }\n\n for (const route of matchers.dynamicRoutes) {\n // Skip SSG/SSP data-route variants prepended by setup-dev-bundler.\n if (route.page.startsWith('/_next/data/')) continue\n if (route.match(pathname)) {\n return { routeSpecifier: route.page }\n }\n }\n\n return { notFound: true, pathname }\n}\n"],"names":["resolvePathToRoute","path","matchers","pathname","q","indexOf","slice","h","startsWith","endsWith","appFiles","has","pageFiles","routeSpecifier","route","dynamicRoutes","page","match","notFound"],"mappings":"AAAA;;;;;;;;CAQC;;;;+BAUeA;;;eAAAA;;;AAAT,SAASA,mBACdC,IAAY,EACZC,QAA0B;IAE1B,IAAIC,WAAWF;IACf,MAAMG,IAAID,SAASE,OAAO,CAAC;IAC3B,IAAID,KAAK,GAAGD,WAAWA,SAASG,KAAK,CAAC,GAAGF;IACzC,MAAMG,IAAIJ,SAASE,OAAO,CAAC;IAC3B,IAAIE,KAAK,GAAGJ,WAAWA,SAASG,KAAK,CAAC,GAAGC;IACzC,IAAI,CAACJ,SAASK,UAAU,CAAC,MAAML,WAAW,MAAMA;IAChD,IAAIA,aAAa,OAAOA,SAASM,QAAQ,CAAC,MAAM;QAC9CN,WAAWA,SAASG,KAAK,CAAC,GAAG,CAAC;IAChC;IAEA,IAAIJ,SAASQ,QAAQ,CAACC,GAAG,CAACR,aAAaD,SAASU,SAAS,CAACD,GAAG,CAACR,WAAW;QACvE,OAAO;YAAEU,gBAAgBV;QAAS;IACpC;IAEA,KAAK,MAAMW,SAASZ,SAASa,aAAa,CAAE;QAC1C,mEAAmE;QACnE,IAAID,MAAME,IAAI,CAACR,UAAU,CAAC,iBAAiB;QAC3C,IAAIM,MAAMG,KAAK,CAACd,WAAW;YACzB,OAAO;gBAAEU,gBAAgBC,MAAME,IAAI;YAAC;QACtC;IACF;IAEA,OAAO;QAAEE,UAAU;QAAMf;IAAS;AACpC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/next-server.d.ts b/e-commerce/node_modules/next/dist/server/next-server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fad03e2a5037942be93b6c5185fdcf344fd7f313 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/next-server.d.ts @@ -0,0 +1,235 @@ +import './node-environment'; +import './require-hook'; +import './node-polyfill-crypto'; +import type { CacheFs } from '../shared/lib/utils'; +import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'; +import type RenderResult from './render-result'; +import type { FetchEventResult } from './web/types'; +import type { PrerenderManifest, PreviewPropsManifest } from '../build'; +import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'; +import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta'; +import type { Params } from './request/params'; +import type { RouteMatch } from './route-matches/route-match'; +import type { RouteMatch as AppRenderRouteMatch } from './route-modules/app-page/module'; +import type { IncomingMessage, ServerResponse } from 'http'; +import type { ParsedUrlQuery } from 'querystring'; +import type { ParsedUrl } from '../shared/lib/router/utils/parse-url'; +import type { CacheControl } from './lib/cache-control'; +import type { WaitUntil } from './after/builtin-request-context'; +import type { ErrorModule } from './load-default-error-components'; +import { NodeNextRequest, NodeNextResponse } from './base-http/node'; +import type { Options, FindComponentsResult, MiddlewareRoutingItem, RequestContext, NormalizedRouteManifest, LoadedRenderOpts, RouteHandler, NextEnabledDirectories, BaseRequestHandler } from './base-server'; +import BaseServer from './base-server'; +import type { LoadComponentsReturnType } from './load-components'; +import { type IncrementalResponseCacheEntry } from './response-cache'; +import { IncrementalCache } from './lib/incremental-cache'; +import type { PagesAPIRouteMatch } from './route-matches/pages-api-route-match'; +import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'; +import type { ServerOnInstrumentationRequestError } from './app-render/types'; +import type { PrefetchHints } from '../shared/lib/app-router-types'; +import { AsyncCallbackSet } from './lib/async-callback-set'; +import type { DeepReadonly } from '../shared/lib/deep-readonly'; +export * from './base-server'; +export type NodeRequestHandler = BaseRequestHandler; +type NodeRouteHandler = RouteHandler; +export default class NextNodeServer extends BaseServer { + protected middlewareManifestPath: string; + private _serverDistDir; + private imageResponseCache?; + private imageCacheHandler?; + protected renderWorkersPromises?: Promise; + protected dynamicRoutes?: { + match: import('../shared/lib/router/utils/route-matcher').RouteMatchFn; + page: string; + re: RegExp; + }[]; + private routerServerHandler?; + protected cleanupListeners: AsyncCallbackSet; + protected internalWaitUntil: WaitUntil | undefined; + private isDev; + private sriEnabled; + constructor(options: Options); + unstable_preloadEntries(): Promise; + protected handleUpgrade(): Promise; + protected loadInstrumentationModule(): Promise; + protected prepareImpl(): Promise; + protected runInstrumentationHookIfAvailable(): Promise; + protected loadEnvConfig({ dev, forceReload, }: { + dev: boolean; + forceReload: boolean; + }): void; + private loadCustomCacheHandlers; + protected getIncrementalCache({ requestHeaders, }: { + requestHeaders: IncrementalCache['requestHeaders']; + }): Promise; + protected getPublicDir(): string; + protected getHasStaticDir(): boolean; + protected getPagesManifest(): PagesManifest | undefined; + protected getAppPathsManifest(): PagesManifest | undefined; + protected getinterceptionRoutePatterns(): RegExp[]; + protected hasPage(pathname: string): Promise; + protected getBuildId(): string; + protected getEnabledDirectories(dev: boolean): NextEnabledDirectories; + protected sendRenderResult(req: NodeNextRequest, res: NodeNextResponse, options: { + result: RenderResult; + generateEtags: boolean; + poweredByHeader: boolean; + cacheControl: CacheControl | undefined; + }): Promise; + protected runApi(req: NodeNextRequest, res: NodeNextResponse, query: ParsedUrlQuery, match: PagesAPIRouteMatch): Promise; + protected renderHTML(req: NodeNextRequest, res: NodeNextResponse, pathname: string, query: NextParsedUrlQuery, renderOpts: LoadedRenderOpts, routeMatch: AppRenderRouteMatch): Promise; + private renderHTMLImpl; + protected imageOptimizer(req: NodeNextRequest, res: NodeNextResponse, paramsResult: import('./image-optimizer').ImageParamsResult, previousCacheEntry?: IncrementalResponseCacheEntry | null): Promise<{ + buffer: Buffer; + contentType: string; + maxAge: number; + upstreamEtag: string; + etag: string; + }>; + protected getPagePath(pathname: string, locales?: string[]): string; + protected renderPageComponent(ctx: RequestContext, bubbleNoFallback: boolean): Promise; + protected findPageComponents({ locale, page, query, params, isAppPath, url, }: { + locale: string | undefined; + page: string; + query: NextParsedUrlQuery; + params: Params; + isAppPath: boolean; + sriEnabled?: boolean; + appPaths?: ReadonlyArray | null; + shouldEnsure: boolean; + url?: string; + }): Promise; + private findPageComponentsImpl; + protected getNextFontManifest(): DeepReadonly | undefined; + protected handleNextImageRequest: NodeRouteHandler; + protected handleCatchallRenderRequest: NodeRouteHandler; + protected logErrorWithOriginalStack(_err?: unknown, _type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'): void; + protected ensurePage(_opts: { + page: string; + clientOnly: boolean; + appPaths?: ReadonlyArray | null; + match?: RouteMatch; + url?: string; + }): Promise; + /** + * Resolves `API` request, in development builds on demand + * @param req http request + * @param res http response + * @param pathname path of request + */ + protected handleApiRequest(req: NodeNextRequest, res: NodeNextResponse, query: ParsedUrlQuery, match: PagesAPIRouteMatch): Promise; + protected getCacheFilesystem(): CacheFs; + protected normalizeReq(req: NodeNextRequest | IncomingMessage): NodeNextRequest; + protected normalizeRes(res: NodeNextResponse | ServerResponse): NodeNextResponse; + getRequestHandler(): NodeRequestHandler; + private makeRequestHandler; + revalidate({ urlPath, headers, opts, }: { + urlPath: string; + headers: { + [key: string]: string | string[]; + }; + opts: { + unstable_onlyGenerated?: boolean; + }; + }): Promise; + render(req: NodeNextRequest | IncomingMessage, res: NodeNextResponse | ServerResponse, pathname: string, query?: NextParsedUrlQuery, parsedUrl?: NextUrlWithParsedQuery, internal?: boolean): Promise; + renderToHTML(req: NodeNextRequest | IncomingMessage, res: NodeNextResponse | ServerResponse, pathname: string, query?: ParsedUrlQuery): Promise; + protected renderErrorToResponseImpl(ctx: RequestContext, err: Error | null): Promise<{ + body: RenderResult; + cacheControl?: CacheControl; + } | null>; + renderError(err: Error | null, req: NodeNextRequest | IncomingMessage, res: NodeNextResponse | ServerResponse, pathname: string, query?: NextParsedUrlQuery, setHeaders?: boolean): Promise; + renderErrorToHTML(err: Error | null, req: NodeNextRequest | IncomingMessage, res: NodeNextResponse | ServerResponse, pathname: string, query?: ParsedUrlQuery): Promise; + render404(req: NodeNextRequest | IncomingMessage, res: NodeNextResponse | ServerResponse, parsedUrl?: NextUrlWithParsedQuery, setHeaders?: boolean): Promise; + protected getMiddlewareManifest(): MiddlewareManifest | null; + /** Returns the middleware routing item if there is one. */ + protected getMiddleware(): Promise; + protected getEdgeFunctionsPages(): string[]; + /** + * Get information for the edge function located in the provided page + * folder. If the edge function info can't be found it will throw + * an error. + */ + protected getEdgeFunctionInfo(params: { + page: string; + /** Whether we should look for a middleware or not */ + middleware: boolean; + }): { + name: string; + paths: string[]; + wasm: { + filePath: string; + name: string; + }[]; + env: { + [key: string]: string; + }; + assets?: { + filePath: string; + name: string; + }[]; + } | null; + private loadNodeMiddleware; + /** + * Checks if a middleware exists. This method is useful for the development + * server where we need to check the filesystem. Here we just check the + * middleware manifest. + */ + protected hasMiddleware(pathname: string): Promise; + /** + * A placeholder for a function to be defined in the development server. + * It will make sure that the root middleware or an edge function has been compiled + * so that we can run it. + */ + protected ensureMiddleware(_url?: string): Promise; + protected ensureEdgeFunction(_params: { + page: string; + appPaths: string[] | null; + url?: string; + }): Promise; + /** + * This method gets all middleware matchers and execute them when the request + * matches. It will make sure that each middleware exists and is compiled and + * ready to be invoked. The development server will decorate it to add warns + * and errors with rich traces. + */ + protected runMiddleware(params: { + request: NodeNextRequest; + response: NodeNextResponse; + parsedUrl: ParsedUrl; + parsed: NextUrlWithParsedQuery; + onWarning?: (warning: Error) => void; + }): Promise; + protected handleCatchallMiddlewareRequest: NodeRouteHandler; + private _cachedPrerenderManifest; + protected getPrerenderManifest(): DeepReadonly; + private _cachedPreviewPropsManifest; + protected getPreviewProps(): PreviewPropsManifest; + private _cachedPrefetchHints; + protected getPrefetchHints(): Record; + protected getRoutesManifest(): NormalizedRouteManifest | undefined; + protected attachRequestMeta(req: NodeNextRequest, parsedUrl: NextUrlWithParsedQuery, isUpgradeReq?: boolean): void; + protected runEdgeFunction(params: { + req: NodeNextRequest; + res: NodeNextResponse; + query: ParsedUrlQuery; + params: Params | undefined; + page: string; + appPaths: string[] | null; + match?: RouteMatch; + onError?: (err: unknown) => void; + onWarning?: (warning: Error) => void; + }): Promise; + protected get serverDistDir(): string; + protected getFallbackErrorComponents(_url?: string): Promise | null>; + protected instrumentationOnRequestError(...args: Parameters): Promise; + protected onServerClose(listener: () => Promise): void; + close(): Promise; + protected getInternalWaitUntil(): WaitUntil; + private createInternalWaitUntil; +} diff --git a/e-commerce/node_modules/next/dist/server/next-server.js b/e-commerce/node_modules/next/dist/server/next-server.js new file mode 100644 index 0000000000000000000000000000000000000000..317cf8ce7a9cba8bccdefeb64407f126b55c79bc --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/next-server.js @@ -0,0 +1,1453 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return NextNodeServer; + } +}); +0 && __export(require("./base-server")); +require("./node-environment"); +require("./require-hook"); +require("./node-polyfill-crypto"); +const _utils = require("../shared/lib/utils"); +const _devrendercontext = require("./route-modules/app-page/dev-render-context"); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _path = require("path"); +const _url = require("url"); +const _routematcher = require("../shared/lib/router/utils/route-matcher"); +const _requestmeta = require("./request-meta"); +const _constants = require("../shared/lib/constants"); +const _findpagesdir = require("../lib/find-pages-dir"); +const _node = require("./base-http/node"); +const _sendpayload = require("./send-payload"); +const _parseurl = require("../shared/lib/router/utils/parse-url"); +const _log = /*#__PURE__*/ _interop_require_wildcard(require("../build/output/log")); +const _baseserver = /*#__PURE__*/ _interop_require_default(_export_star(require("./base-server"), exports)); +const _require = require("./require"); +const _denormalizepagepath = require("../shared/lib/page-path/denormalize-page-path"); +const _normalizepagepath = require("../shared/lib/page-path/normalize-page-path"); +const _apppaths = require("../shared/lib/router/utils/app-paths"); +const _loadcomponents = require("./load-components"); +const _iserror = /*#__PURE__*/ _interop_require_wildcard(require("../lib/is-error")); +const _utils1 = require("./web/utils"); +const _middlewareroutematcher = require("../shared/lib/router/utils/middleware-route-matcher"); +const _env = require("@next/env"); +const _querystring = require("../shared/lib/router/utils/querystring"); +const _removetrailingslash = require("../shared/lib/router/utils/remove-trailing-slash"); +const _getnextpathnameinfo = require("../shared/lib/router/utils/get-next-pathname-info"); +const _bodystreams = require("./body-streams"); +const _apiutils = require("./api-utils"); +const _responsecache = /*#__PURE__*/ _interop_require_wildcard(require("./response-cache")); +const _incrementalcache = require("./lib/incremental-cache"); +const _setuphttpagentenv = require("./setup-http-agent-env"); +const _pagesapiroutematch = require("./route-matches/pages-api-route-match"); +const _tracer = require("./lib/trace/tracer"); +const _constants1 = require("./lib/trace/constants"); +const _nodefsmethods = require("./lib/node-fs-methods"); +const _routeregex = require("../shared/lib/router/utils/route-regex"); +const _pipereadable = require("./pipe-readable"); +const _mockrequest = require("./lib/mock-request"); +const _approuterheaders = require("../client/components/app-router-headers"); +const _nextrequest = require("./web/spec-extension/adapters/next-request"); +const _loadmanifestexternal = require("./load-manifest.external"); +const _modulerender = require("./route-modules/app-page/module.render"); +const _parserequestheaders = require("./route-modules/app-page/parse-request-headers"); +const _modulerender1 = require("./route-modules/pages/module.render"); +const _interopdefault = require("../lib/interop-default"); +const _formatdynamicimportpath = require("../lib/format-dynamic-import-path"); +const _isinterceptionrouterewrite = require("../lib/is-interception-route-rewrite"); +const _routekind = require("./route-kind"); +const _invarianterror = require("../shared/lib/invariant-error"); +const _awaiter = require("./after/awaiter"); +const _asynccallbackset = require("./lib/async-callback-set"); +const _handlers = require("./use-cache/handlers"); +const _staticenv = require("../lib/static-env"); +const _nodemoduleloader = require("./lib/module-loader/node-module-loader"); +const _nofallbackerrorexternal = require("../shared/lib/no-fallback-error.external"); +const _instrumentationglobalsexternal = require("./lib/router-utils/instrumentation-globals.external"); +const _routerservercontext = require("./lib/router-utils/router-server-context"); +const _globalbehaviors = require("./node-environment-extensions/global-behaviors"); +const _processerrorhandlers = require("./node-environment-extensions/process-error-handlers"); +function _export_star(from, to) { + Object.keys(from).forEach(function(k) { + if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { + Object.defineProperty(to, k, { + enumerable: true, + get: function() { + return from[k]; + } + }); + } + }); + return from; +} +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +// For module that can be both CJS or ESM +const dynamicImportEsmDefault = process.env.NEXT_MINIMAL ? (id)=>import(/* webpackIgnore: true */ id).then((mod)=>mod.default || mod) : (id)=>import(id).then((mod)=>mod.default || mod); +const MiddlewareMatcherCache = new WeakMap(); +function getMiddlewareMatcher(info) { + const stored = MiddlewareMatcherCache.get(info); + if (stored) { + return stored; + } + if (!Array.isArray(info.matchers)) { + throw new Error(`Invariant: invalid matchers for middleware ${JSON.stringify(info)}`); + } + const matcher = (0, _middlewareroutematcher.getMiddlewareRouteMatcher)(info.matchers); + MiddlewareMatcherCache.set(info, matcher); + return matcher; +} +class NextNodeServer extends _baseserver.default { + constructor(options){ + var _options_conf_experimental_sri, _options_conf_experimental, _options_conf_experimental1; + // Initialize super class + super(options), this.cleanupListeners = new _asynccallbackset.AsyncCallbackSet(), this.handleNextImageRequest = async (req, res, parsedUrl)=>{ + if (!parsedUrl.pathname || !parsedUrl.pathname.startsWith('/_next/image')) { + return false; + } + // Ignore if its a middleware request + if ((0, _requestmeta.getRequestMeta)(req, 'middlewareInvoke')) { + return false; + } + if (this.minimalMode || this.nextConfig.output === 'export' || process.env.NEXT_MINIMAL) { + res.statusCode = 400; + res.body('Bad Request').send(); + return true; + // the `else` branch is needed for tree-shaking + } else { + const { ImageOptimizerCache } = require('./image-optimizer'); + // Load custom cache handler if configured and opt-in via images.customCacheHandler + // Cache the handler instance to preserve state across requests + if (!this.imageCacheHandler && this.nextConfig.images.customCacheHandler) { + const { cacheHandler } = this.nextConfig; + if (cacheHandler) { + const CacheHandler = (0, _interopdefault.interopDefault)(await dynamicImportEsmDefault((0, _formatdynamicimportpath.formatDynamicImportPath)(this.distDir, cacheHandler))); + this.imageCacheHandler = new CacheHandler({ + dev: !!this.dev, + flushToDisk: this.nextConfig.experimental.isrFlushToDisk, + serverDistDir: this.serverDistDir, + maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize, + revalidatedTags: [], + _requestHeaders: {} + }); + } + } + const imageOptimizerCache = new ImageOptimizerCache({ + distDir: this.distDir, + nextConfig: this.nextConfig, + cacheHandler: this.imageCacheHandler + }); + const { sendResponse, ImageError } = require('./image-optimizer'); + if (!this.imageResponseCache) { + throw new Error('invariant image optimizer cache was not initialized'); + } + const imagesConfig = this.nextConfig.images; + if (imagesConfig.loader !== 'default' || imagesConfig.unoptimized) { + await this.render404(req, res); + return true; + } + const paramsResult = ImageOptimizerCache.validateParams(req.originalRequest, parsedUrl.query, this.nextConfig, !!this.dev); + if ('errorMessage' in paramsResult) { + res.statusCode = 400; + res.body(paramsResult.errorMessage).send(); + return true; + } + const cacheKey = ImageOptimizerCache.getCacheKey(paramsResult); + try { + var _cacheEntry_value, _cacheEntry_cacheControl; + const { getExtension } = require('./serve-static'); + const cacheEntry = await this.imageResponseCache.get(cacheKey, async ({ previousCacheEntry })=>{ + const { buffer, contentType, maxAge, upstreamEtag, etag } = await this.imageOptimizer(req, res, paramsResult, previousCacheEntry); + return { + value: { + kind: _responsecache.CachedRouteKind.IMAGE, + buffer, + etag, + extension: getExtension(contentType), + upstreamEtag + }, + cacheControl: { + revalidate: maxAge, + expire: undefined + } + }; + }, { + routeKind: _routekind.RouteKind.IMAGE, + incrementalCache: imageOptimizerCache, + isFallback: false + }); + if (cacheEntry !== null && 'error' in cacheEntry) { + throw cacheEntry.error; + } + if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== _responsecache.CachedRouteKind.IMAGE) { + throw new Error('invariant did not get entry from image response cache'); + } + sendResponse(req.originalRequest, res.originalResponse, paramsResult.href, cacheEntry.value.extension, cacheEntry.value.buffer, cacheEntry.value.etag, paramsResult.isStatic, cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT', imagesConfig, ((_cacheEntry_cacheControl = cacheEntry.cacheControl) == null ? void 0 : _cacheEntry_cacheControl.revalidate) || 0, Boolean(this.dev)); + return true; + } catch (err) { + if (err instanceof ImageError) { + res.statusCode = err.statusCode; + res.body(err.message).send(); + return true; + } + throw err; + } + } + }, this.handleCatchallRenderRequest = async (req, res, parsedUrl)=>{ + let { pathname, query } = parsedUrl; + if (!pathname) { + throw new Error('Invariant: pathname is undefined'); + } + // When in minimal mode we do not bubble the fallback as the + // router-server is not present to handle the error + (0, _requestmeta.addRequestMeta)(req, 'bubbleNoFallback', this.minimalMode ? undefined : true); + // This is needed to expose render404 and nextConfig + // for environments without router-server + if (!_routerservercontext.routerServerGlobal[_routerservercontext.RouterServerContextSymbol]) { + _routerservercontext.routerServerGlobal[_routerservercontext.RouterServerContextSymbol] = {}; + } + const relativeProjectDir = (0, _path.relative)(process.cwd(), this.dir); + const existingServerContext = _routerservercontext.routerServerGlobal[_routerservercontext.RouterServerContextSymbol][relativeProjectDir]; + if (!existingServerContext) { + _routerservercontext.routerServerGlobal[_routerservercontext.RouterServerContextSymbol][relativeProjectDir] = { + render404: this.render404.bind(this), + getAssetPrefix: this.getAssetPrefix.bind(this) + }; + } + _routerservercontext.routerServerGlobal[_routerservercontext.RouterServerContextSymbol][relativeProjectDir].nextConfig = this.nextConfig; + _routerservercontext.routerServerGlobal[_routerservercontext.RouterServerContextSymbol][relativeProjectDir].isWrappedByNextServer = true; + try { + // next.js core assumes page path without trailing slash + pathname = (0, _removetrailingslash.removeTrailingSlash)(pathname); + let match = (0, _requestmeta.getRequestMeta)(req, 'match'); + // router-server normally attaches the fsChecker match. Direct internal + // requests, such as on-demand revalidation, bypass router-server and need + // to resolve the route from the manifests here. + if (!match) { + var _this_i18nProvider; + const localeAnalysisResult = (_this_i18nProvider = this.i18nProvider) == null ? void 0 : _this_i18nProvider.analyze(pathname, { + defaultLocale: (0, _requestmeta.getRequestMeta)(req, 'defaultLocale') + }); + const routeMatch = this.getRouteMatch(pathname, localeAnalysisResult); + if (routeMatch) { + match = routeMatch; + } + } + // The matcher manager previously fell through to render for unknown + // paths. Preserve that behavior for direct render-server requests that do + // not pass through fsChecker. + if (!match) { + await this.render(req, res, pathname, query, parsedUrl, true); + return true; + } + // Add the match to the request so we don't have to re-run the matcher + // for the same request. + (0, _requestmeta.addRequestMeta)(req, 'match', match); + // TODO-APP: move this to a route handler + const edgeFunctionsPages = this.getEdgeFunctionsPages(); + for (const edgeFunctionsPage of edgeFunctionsPages){ + // If the page doesn't match the edge function page, skip it. + if (edgeFunctionsPage !== match.definition.page) continue; + if (this.nextConfig.output === 'export') { + await this.render404(req, res, parsedUrl); + return true; + } + delete query[_approuterheaders.NEXT_RSC_UNION_QUERY]; + // If we handled the request, we can return early. + // For api routes edge runtime + try { + const handled = await this.runEdgeFunction({ + req, + res, + query, + params: match.params, + page: match.definition.page, + match, + appPaths: null + }); + if (handled) return true; + } catch (apiError) { + const silenceLog = false; + await this.instrumentationOnRequestError(apiError, req, { + routePath: match.definition.page, + routerKind: 'Pages Router', + routeType: 'route', + // Edge runtime does not support ISR + revalidateReason: undefined + }, silenceLog); + throw apiError; + } + } + // If the route was detected as being a Pages API route, then handle + // it. + // TODO: move this behavior into a route handler. + if ((0, _pagesapiroutematch.isPagesAPIRouteMatch)(match)) { + if (this.nextConfig.output === 'export') { + await this.render404(req, res, parsedUrl); + return true; + } + const handled = await this.handleApiRequest(req, res, query, match); + if (handled) return true; + } + await this.render(req, res, pathname, query, parsedUrl, true); + return true; + } catch (err) { + if (err instanceof _nofallbackerrorexternal.NoFallbackError) { + throw err; + } + try { + if (this.dev) { + const { formatServerError } = require('../lib/format-server-error'); + formatServerError(err); + this.logErrorWithOriginalStack(err); + } else { + this.logError(err); + } + res.statusCode = 500; + await this.renderError(err, req, res, pathname, query); + return true; + } catch {} + throw err; + } + }, this.handleCatchallMiddlewareRequest = async (req, res, parsed)=>{ + const isMiddlewareInvoke = (0, _requestmeta.getRequestMeta)(req, 'middlewareInvoke'); + if (!isMiddlewareInvoke) { + return false; + } + const handleFinished = ()=>{ + (0, _requestmeta.addRequestMeta)(req, 'middlewareInvoke', true); + res.body('').send(); + return true; + }; + const middleware = await this.getMiddleware(); + if (!middleware) { + return handleFinished(); + } + const initUrl = (0, _requestmeta.getRequestMeta)(req, 'initURL'); + const parsedUrl = (0, _parseurl.parseUrl)(initUrl); + const pathnameInfo = (0, _getnextpathnameinfo.getNextPathnameInfo)(parsedUrl.pathname, { + nextConfig: this.nextConfig, + i18nProvider: this.i18nProvider + }); + parsedUrl.pathname = pathnameInfo.pathname; + const normalizedPathname = (0, _removetrailingslash.removeTrailingSlash)(parsed.pathname || ''); + let maybeDecodedPathname = normalizedPathname; + try { + maybeDecodedPathname = decodeURIComponent(normalizedPathname); + } catch { + /* non-fatal we can't decode so can't match it */ } + if (!(middleware.match(normalizedPathname, req, parsedUrl.query) || middleware.match(maybeDecodedPathname, req, parsedUrl.query))) { + return handleFinished(); + } + let result; + let bubblingResult = false; + try { + await this.ensureMiddleware(req.url); + result = await this.runMiddleware({ + request: req, + response: res, + parsedUrl: parsedUrl, + parsed: parsed + }); + if ('response' in result) { + if (isMiddlewareInvoke) { + bubblingResult = true; + throw new _tracer.BubbledError(true, result); + } + for (const [key, value] of Object.entries((0, _utils1.toNodeOutgoingHttpHeaders)(result.response.headers))){ + if (key !== 'content-encoding' && value !== undefined) { + res.setHeader(key, value); + } + } + res.statusCode = result.response.status; + const { originalResponse } = res; + if (result.response.body) { + await (0, _pipereadable.pipeToNodeResponse)(result.response.body, originalResponse); + } else { + originalResponse.end(); + } + return true; + } + } catch (err) { + if (bubblingResult) { + throw err; + } + if ((0, _iserror.default)(err) && err.code === 'ENOENT') { + await this.render404(req, res, parsed); + return true; + } + if (err instanceof _utils.DecodeError) { + res.statusCode = 400; + await this.renderError(err, req, res, parsed.pathname || ''); + return true; + } + const error = (0, _iserror.getProperError)(err); + console.error(error); + res.statusCode = 500; + await this.renderError(error, req, res, parsed.pathname || ''); + return true; + } + return result.finished; + }; + (0, _globalbehaviors.installGlobalBehaviors)(this.nextConfig); + // Load prefetch hints from the build output. This must happen before + // any render to ensure segment inlining decisions are available. + this.renderOpts.prefetchHints = this.getPrefetchHints(); + const isDev = options.dev ?? false; + this.isDev = isDev; + this.sriEnabled = Boolean((_options_conf_experimental = options.conf.experimental) == null ? void 0 : (_options_conf_experimental_sri = _options_conf_experimental.sri) == null ? void 0 : _options_conf_experimental_sri.algorithm); + /** + * This sets environment variable to be used at the time of SSR by head.tsx. + * Using this from process.env allows targeting SSR by calling + * `process.env.__NEXT_OPTIMIZE_CSS`. + */ if (this.renderOpts.optimizeCss) { + process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true); + } + if (this.renderOpts.nextScriptWorkers) { + process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true); + } + if ((isDev || process.env.__NEXT_DEV_SERVER) && this.nextConfig.experimental.requestInsights) { + process.env.__NEXT_REQUEST_INSIGHTS = 'true'; + } else { + delete process.env.__NEXT_REQUEST_INSIGHTS; + } + if (!this.minimalMode) { + this.imageResponseCache = new _responsecache.default({ + minimalMode: this.minimalMode, + route: 'image' + }); + } + if (!options.dev && !this.minimalMode && this.nextConfig.experimental.preloadEntriesOnStart) { + // Preloading may join a failing registration started by a request. + void this.unstable_preloadEntries().catch((err)=>{ + _log.error('Failed to preload entries:', err); + }); + } + if (!options.dev) { + const { dynamicRoutes = [] } = this.getRoutesManifest() ?? {}; + this.dynamicRoutes = dynamicRoutes.map((r)=>{ + // TODO: can we just re-use the regex from the manifest? + const regex = (0, _routeregex.getRouteRegex)(r.page); + const match = (0, _routematcher.getRouteMatcher)(regex); + return { + match, + page: r.page, + re: regex.re + }; + }); + } + // ensure options are set when loadConfig isn't called + (0, _setuphttpagentenv.setHttpClientAndAgentOptions)(this.nextConfig); + // Intercept fetch and other testmode apis. + if (this.serverOptions.experimentalTestProxy) { + process.env.NEXT_PRIVATE_TEST_PROXY = 'true'; + const { interceptTestApis } = // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm + require('next/dist/experimental/testmode/server'); + interceptTestApis(); + } + this.middlewareManifestPath = (0, _path.join)(/* turbopackIgnore: true */ this.serverDistDir, _constants.MIDDLEWARE_MANIFEST); + // This is just optimization to fire prepare as soon as possible. It will be + // properly awaited later. We add the catch here to ensure that it does not + // cause a unhandled promise rejection. The promise rejection will be + // handled later on via the `await` when the request handler is called. + if (!options.dev) { + this.prepare().catch((err)=>{ + console.error('Failed to prepare server', err); + }); + } + // when using compile mode static env isn't inlined so we + // need to populate in normal runtime env + if (this.renderOpts.isExperimentalCompile) { + // supportsImmutableAssets only works with Turbopack, and `isExperimentalCompile` isn't supported + // with that anyway, so we can assign just use deploymentId here + (0, _staticenv.populateStaticEnv)(this.nextConfig, this.deploymentId || ''); + } + const shouldRemoveUncaughtErrorAndRejectionListeners = Boolean((_options_conf_experimental1 = options.conf.experimental) == null ? void 0 : _options_conf_experimental1.removeUncaughtErrorAndRejectionListeners); + (0, _processerrorhandlers.installProcessErrorHandlers)(shouldRemoveUncaughtErrorAndRejectionListeners); + } + async unstable_preloadEntries() { + // Ensure prepare process will be finished before preloading entries. + await this.prepare(); + const appPathsManifest = this.getAppPathsManifest(); + const pagesManifest = this.getPagesManifest(); + await this.loadCustomCacheHandlers(); + for (const page of Object.keys(pagesManifest || {})){ + try { + await (0, _loadcomponents.loadComponents)({ + distDir: this.distDir, + page, + isAppPath: false, + isDev: this.isDev, + sriEnabled: this.sriEnabled, + needsManifestsForLegacyReasons: false + }); + } catch (_err) { + // Intentionally ignored because this is a preload step. + } + } + for (const page of Object.keys(appPathsManifest || {})){ + try { + const { ComponentMod } = await (0, _loadcomponents.loadComponents)({ + distDir: this.distDir, + page, + isAppPath: true, + isDev: this.isDev, + sriEnabled: this.sriEnabled, + needsManifestsForLegacyReasons: false + }); + // we need to ensure fetch is patched before we require the page, + // otherwise if the fetch is patched by user code, we will be patching it + // too late and there won't be any caching behaviors + ComponentMod.patchFetch(); + } catch (_err) { + // Intentionally ignored because this is a preload step. + } + } + } + async handleUpgrade() { + // The web server does not support web sockets, it's only used for HMR in + // development. + } + async loadInstrumentationModule() { + if (!this.serverOptions.dev) { + try { + this.instrumentation = await (0, _instrumentationglobalsexternal.getInstrumentationModule)(this.dir, this.nextConfig.distDir); + } catch (err) { + if (err.code !== 'MODULE_NOT_FOUND') { + throw new Error('An error occurred while loading the instrumentation hook', { + cause: err + }); + } + } + } + return this.instrumentation; + } + async prepareImpl() { + await super.prepareImpl(); + await this.runInstrumentationHookIfAvailable(); + } + async runInstrumentationHookIfAvailable() { + await (0, _instrumentationglobalsexternal.ensureInstrumentationRegistered)(this.dir, this.nextConfig.distDir); + } + loadEnvConfig({ dev, forceReload }) { + (0, _env.loadEnvConfig)(this.dir, dev, _log, forceReload, forceReload ? (envFilePath)=>{ + _log.info(`Reload env: ${envFilePath}`); + } : undefined); + } + async loadCustomCacheHandlers() { + const { cacheMaxMemorySize, cacheHandlers } = this.nextConfig; + if (!cacheHandlers) return; + (0, _handlers.initializeCacheHandlers)(cacheMaxMemorySize); + await (0, _handlers.registerCustomCacheHandlers)(async ()=>{ + for (const [kind, handler] of Object.entries(cacheHandlers)){ + if (!handler) continue; + (0, _handlers.setCacheHandler)(kind, (0, _interopdefault.interopDefault)(await dynamicImportEsmDefault((0, _formatdynamicimportpath.formatDynamicImportPath)(this.distDir, handler)))); + } + }); + } + async getIncrementalCache({ requestHeaders }) { + var _this_nextConfig_i18n; + const dev = !!this.dev; + let CacheHandler; + const { cacheHandler } = this.nextConfig; + if (cacheHandler) { + CacheHandler = (0, _interopdefault.interopDefault)(await dynamicImportEsmDefault((0, _formatdynamicimportpath.formatDynamicImportPath)(this.distDir, cacheHandler))); + } + await this.loadCustomCacheHandlers(); + // incremental-cache is request specific + // although can have shared caches in module scope + // per-cache handler + return new _incrementalcache.IncrementalCache({ + fs: this.getCacheFilesystem(), + dev, + requestHeaders, + allowedRevalidateHeaderKeys: this.nextConfig.experimental.allowedRevalidateHeaderKeys, + minimalMode: this.minimalMode, + serverDistDir: this.serverDistDir, + fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix, + maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize, + flushToDisk: !this.minimalMode && this.nextConfig.experimental.isrFlushToDisk, + previewProps: this.getPreviewProps(), + prerenderManifest: this.getPrerenderManifest(), + locales: (_this_nextConfig_i18n = this.nextConfig.i18n) == null ? void 0 : _this_nextConfig_i18n.locales, + CurCacheHandler: CacheHandler + }); + } + getPublicDir() { + return (0, _path.join)(/* turbopackIgnore: true */ this.dir, _constants.CLIENT_PUBLIC_FILES_PATH); + } + getHasStaticDir() { + return _fs.default.existsSync(/* turbopackIgnore: true */ (0, _path.join)(/* turbopackIgnore: true */ this.dir, 'static')); + } + getPagesManifest() { + return (0, _loadmanifestexternal.loadManifest)((0, _path.join)(/* turbopackIgnore: true */ this.serverDistDir, _constants.PAGES_MANIFEST)); + } + getAppPathsManifest() { + if (!this.enabledDirectories.app) return undefined; + return (0, _loadmanifestexternal.loadManifest)((0, _path.join)(/* turbopackIgnore: true */ this.serverDistDir, _constants.APP_PATHS_MANIFEST)); + } + getinterceptionRoutePatterns() { + if (!this.enabledDirectories.app) return []; + const routesManifest = this.getRoutesManifest(); + return (routesManifest == null ? void 0 : routesManifest.rewrites.beforeFiles.filter(_isinterceptionrouterewrite.isInterceptionRouteRewrite).map((rewrite)=>new RegExp(rewrite.regex))) ?? []; + } + async hasPage(pathname) { + var _this_nextConfig_i18n; + return !!(0, _require.getMaybePagePath)(pathname, this.distDir, (_this_nextConfig_i18n = this.nextConfig.i18n) == null ? void 0 : _this_nextConfig_i18n.locales, this.enabledDirectories.app); + } + getBuildId() { + const buildIdFile = (0, _path.join)(/* turbopackIgnore: true */ this.distDir, _constants.BUILD_ID_FILE); + try { + return _fs.default.readFileSync(/* turbopackIgnore: true */ buildIdFile, 'utf8').trim(); + } catch (err) { + if (err.code === 'ENOENT') { + throw new Error(`Could not find a production build in the '${this.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`); + } + throw err; + } + } + getEnabledDirectories(dev) { + const dir = dev ? this.dir : this.serverDistDir; + return { + app: (0, _findpagesdir.findDir)(dir, 'app') ? true : false, + pages: (0, _findpagesdir.findDir)(dir, 'pages') ? true : false + }; + } + sendRenderResult(req, res, options) { + return (0, _sendpayload.sendRenderResult)({ + req: req.originalRequest, + res: res.originalResponse, + result: options.result, + generateEtags: options.generateEtags, + poweredByHeader: options.poweredByHeader, + cacheControl: options.cacheControl + }); + } + async runApi(req, res, query, match) { + const edgeFunctionsPages = this.getEdgeFunctionsPages(); + for (const edgeFunctionsPage of edgeFunctionsPages){ + if (edgeFunctionsPage === match.definition.pathname) { + const handledAsEdgeFunction = await this.runEdgeFunction({ + req, + res, + query, + params: match.params, + page: match.definition.pathname, + appPaths: null + }); + if (handledAsEdgeFunction) { + return true; + } + } + } + // The module supports minimal mode, load the minimal module. + // Restore original URL as the handler handles it's own parsing + const parsedInitUrl = (0, _parseurl.parseUrl)((0, _requestmeta.getRequestMeta)(req, 'initURL') || req.url); + req.url = `${parsedInitUrl.pathname}${parsedInitUrl.search || ''}`; + const loader = new _nodemoduleloader.NodeModuleLoader(); + // Dev definitions retain source filenames for watcher bookkeeping. API + // execution still needs to load the compiled server bundle. + const modulePath = this.isDev ? (0, _path.join)(this.distDir, 'server', `${match.definition.bundlePath}.js`) : match.definition.filename; + const module = await loader.load(modulePath); + (0, _requestmeta.addRequestMeta)(req.originalRequest, 'relativeProjectDir', (0, _path.relative)(process.cwd(), this.dir)); + (0, _requestmeta.addRequestMeta)(req.originalRequest, 'distDir', this.distDir); + await module.handler(req.originalRequest, res.originalResponse, { + waitUntil: this.getWaitUntil(), + requestMeta: { + ...(0, _requestmeta.getRequestMeta)(req.originalRequest), + query, + params: match.params + } + }); + return true; + } + async renderHTML(req, res, pathname, query, renderOpts, routeMatch) { + return (0, _tracer.getTracer)().trace(_constants1.NextNodeServerSpan.renderHTML, async ()=>this.renderHTMLImpl(req, res, pathname, query, renderOpts, routeMatch)); + } + async renderHTMLImpl(req, res, pathname, query, renderOpts, routeMatch) { + if (process.env.NEXT_MINIMAL) { + throw new Error('Invariant: renderHTML should not be called in minimal mode'); + // the `else` branch is needed for tree-shaking + } else { + // Due to the way we pass data by mutating `renderOpts`, we can't extend the + // object here but only updating its `nextFontManifest` field. + // https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952 + renderOpts.nextFontManifest = this.nextFontManifest; + if (this.enabledDirectories.app && renderOpts.isAppPath) { + var _renderOpts_previewProps; + const renderAppPage = !renderOpts.supportsDynamicResponse && !renderOpts.isDraftMode && !renderOpts.isPossibleServerAction ? _modulerender.lazyPrerenderAppPage : _modulerender.lazyRenderAppPage; + const dev = (0, _devrendercontext.createDevRenderContext)(req, process.env.__NEXT_DEV_SERVER ? this.getServerComponentsHmrCache() : undefined); + const parsedRequestHeaders = (0, _parserequestheaders.parseRequestHeaders)(req.headers, { + isRoutePPREnabled: renderOpts.experimental.isRoutePPREnabled === true, + previewModeId: (_renderOpts_previewProps = renderOpts.previewProps) == null ? void 0 : _renderOpts_previewProps.previewModeId + }); + const result = await renderAppPage(req, res, pathname, query, // This code path does not service revalidations for unknown param + // shells. As a result, we don't need to pass in the unknown params. + null, renderOpts, dev, { + buildId: this.buildId, + deploymentId: this.deploymentId, + clientAssetToken: this.nextConfig.supportsImmutableAssets ? '' : this.deploymentId + }, routeMatch, parsedRequestHeaders); + if ('error' in result) { + throw result.error; + } + return result; + } else { + // TODO: re-enable this once we've refactored to use implicit matches + // throw new Error('Invariant: render should have used routeModule') + return (0, _modulerender1.lazyRenderPagesPage)(req.originalRequest, res.originalResponse, pathname, query, renderOpts, { + buildId: this.buildId, + deploymentId: this.deploymentId, + clientAssetToken: this.nextConfig.supportsImmutableAssets ? undefined : this.deploymentId, + customServer: this.serverOptions.customServer || undefined + }, { + isFallback: false, + isDraftMode: renderOpts.isDraftMode, + developmentNotFoundSourcePage: (0, _requestmeta.getRequestMeta)(req, 'developmentNotFoundSourcePage') + }); + } + } + } + async imageOptimizer(req, res, paramsResult, previousCacheEntry) { + if (process.env.NEXT_MINIMAL) { + throw new Error('invariant: imageOptimizer should not be called in minimal mode'); + } else { + const { imageOptimizer, fetchExternalImage, fetchInternalImage } = require('./image-optimizer'); + const handleInternalReq = async (newReq, newRes)=>{ + if (newReq.url === req.url) { + throw new Error(`Invariant attempted to optimize _next/image itself`); + } + if (!this.routerServerHandler) { + throw new Error(`Invariant missing routerServerHandler`); + } + await this.routerServerHandler(newReq, newRes); + return; + }; + let { href } = paramsResult; + if (process.env.__NEXT_TEST_MODE && process.env.IS_TURBOPACK_TEST && !paramsResult.isAbsolute) { + // Forward the dpl query param from the original /_next/image request to the + // internal static file request so that the static file validation in + // resolve-routes.ts can verify it. + const dpl = typeof req.url === 'string' ? new URL(req.url, 'http://n').searchParams.get('dpl') : undefined; + if (dpl) { + href += `${href.includes('?') ? '&' : '?'}dpl=${dpl}`; + } + } + const imageUpstream = paramsResult.isAbsolute ? await fetchExternalImage(href, this.nextConfig.images.dangerouslyAllowLocalIP, this.nextConfig.images.maximumResponseBody, this.nextConfig.images.maximumRedirects) : await fetchInternalImage(href, req.originalRequest, res.originalResponse, this.nextConfig.images.maximumResponseBody, handleInternalReq); + return imageOptimizer(imageUpstream, paramsResult, this.nextConfig, { + isDev: this.dev, + previousCacheEntry + }); + } + } + getPagePath(pathname, locales) { + return (0, _require.getPagePath)(pathname, this.distDir, locales, this.enabledDirectories.app); + } + async renderPageComponent(ctx, bubbleNoFallback) { + const edgeFunctionsPages = this.getEdgeFunctionsPages() || []; + if (edgeFunctionsPages.length) { + const appPaths = this.getOriginalAppPaths(ctx.pathname); + const isAppPath = Array.isArray(appPaths); + let page = ctx.pathname; + if (isAppPath) { + // When it's an array, we need to pass all parallel routes to the loader. + page = (0, _apppaths.selectAppPageEntry)(ctx.pathname, appPaths); + } + for (const edgeFunctionsPage of edgeFunctionsPages){ + if (edgeFunctionsPage === page) { + await this.runEdgeFunction({ + req: ctx.req, + res: ctx.res, + query: ctx.query, + params: ctx.renderOpts.params, + page, + appPaths + }); + return null; + } + } + } + return super.renderPageComponent(ctx, bubbleNoFallback); + } + async findPageComponents({ locale, page, query, params, isAppPath, url }) { + return (0, _tracer.getTracer)().trace(_constants1.NextNodeServerSpan.findPageComponents, { + spanName: 'resolve page components', + attributes: { + 'next.route': isAppPath ? (0, _apppaths.normalizeAppPath)(page) : page + } + }, ()=>this.findPageComponentsImpl({ + locale, + page, + query, + params, + isAppPath, + url + })); + } + async findPageComponentsImpl({ locale, page, query, params, isAppPath, url: _url }) { + const pagePaths = [ + page + ]; + if (locale) { + pagePaths.unshift(...pagePaths.map((path)=>`/${locale}${path === '/' ? '' : path}`)); + } + for (const pagePath of pagePaths){ + try { + const components = await (0, _loadcomponents.loadComponents)({ + distDir: this.distDir, + page: pagePath, + isAppPath, + isDev: this.isDev, + sriEnabled: this.sriEnabled, + needsManifestsForLegacyReasons: false + }); + if (locale && typeof components.Component === 'string' && !pagePath.startsWith(`/${locale}/`) && pagePath !== `/${locale}`) { + continue; + } + return { + components, + query: { + ...!this.renderOpts.isExperimentalCompile && components.getStaticProps ? {} : query, + // For appDir params is excluded. + ...(isAppPath ? {} : params) || {} + } + }; + } catch (err) { + // we should only not throw if we failed to find the page + // in the pages-manifest + if (!(err instanceof _utils.PageNotFoundError)) { + throw err; + } + } + } + return null; + } + getNextFontManifest() { + return (0, _loadmanifestexternal.loadManifest)((0, _path.join)(/* turbopackIgnore: true */ this.distDir, 'server', _constants.NEXT_FONT_MANIFEST + '.json')); + } + // Used in development only, overloaded in next-dev-server + logErrorWithOriginalStack(_err, _type) { + throw new Error('Invariant: logErrorWithOriginalStack can only be called on the development server'); + } + // Used in development only, overloaded in next-dev-server + async ensurePage(_opts) { + throw new Error('Invariant: ensurePage can only be called on the development server'); + } + /** + * Resolves `API` request, in development builds on demand + * @param req http request + * @param res http response + * @param pathname path of request + */ async handleApiRequest(req, res, query, match) { + return this.runApi(req, res, query, match); + } + getCacheFilesystem() { + return _nodefsmethods.nodeFs; + } + normalizeReq(req) { + return !(req instanceof _node.NodeNextRequest) ? new _node.NodeNextRequest(req) : req; + } + normalizeRes(res) { + return !(res instanceof _node.NodeNextResponse) ? new _node.NodeNextResponse(res) : res; + } + getRequestHandler() { + const handler = this.makeRequestHandler(); + if (this.serverOptions.experimentalTestProxy) { + const { wrapRequestHandlerNode } = // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm + require('next/dist/experimental/testmode/server'); + return wrapRequestHandlerNode(handler); + } + return handler; + } + /** + * @internal - this method is internal to Next.js and should not be used directly by end-users + */ getRequestHandlerWithMetadata(meta) { + const handler = this.makeRequestHandler(); + return (req, res, parsedUrl)=>{ + (0, _requestmeta.setRequestMeta)(req, meta); + return handler(req, res, parsedUrl); + }; + } + makeRequestHandler() { + // This is just optimization to fire prepare as soon as possible. It will be + // properly awaited later. We add the catch here to ensure that it does not + // cause an unhandled promise rejection. The promise rejection will be + // handled later on via the `await` when the request handler is called. + this.prepare().catch((err)=>{ + console.error('Failed to prepare server', err); + }); + const handler = super.getRequestHandler(); + return (req, res, parsedUrl)=>handler(this.normalizeReq(req), this.normalizeRes(res), parsedUrl); + } + async revalidate({ urlPath, headers, opts }) { + const mocked = (0, _mockrequest.createRequestResponseMocks)({ + url: urlPath, + headers + }); + const handler = this.getRequestHandler(); + await handler(new _node.NodeNextRequest(mocked.req), new _node.NodeNextResponse(mocked.res)); + await mocked.res.hasStreamed; + if (mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' && mocked.res.statusCode !== 200 && !(mocked.res.statusCode === 404 && opts.unstable_onlyGenerated)) { + throw new Error(`Invalid response ${mocked.res.statusCode}`); + } + } + async render(req, res, pathname, query, parsedUrl, internal = false) { + return super.render(this.normalizeReq(req), this.normalizeRes(res), pathname, query, parsedUrl, internal); + } + async renderToHTML(req, res, pathname, query) { + const normalizedRes = this.normalizeRes(res); + const normalizedReq = this.normalizeReq(req); + normalizedReq.url = (0, _url.format)({ + pathname, + query + }); + if (this.dev) { + await this.ensurePage({ + page: pathname, + clientOnly: false, + url: normalizedReq.url + }); + } + // renderToHTML returns the body to legacy custom servers. Route modules + // write to the response, so capture their output instead of sending it. + const mockedRes = new _mockrequest.MockedResponse({ + headers: normalizedRes.getHeaders(), + statusCode: normalizedRes.statusCode, + socket: normalizedRes.originalResponse.socket + }); + const result = await super.renderToHTML(normalizedReq, this.normalizeRes(mockedRes), pathname, query); + if (result === null && mockedRes.isSent) { + await mockedRes.hasStreamed; + } + const mockedHeaders = mockedRes.getHeaders(); + for(const key in mockedHeaders){ + const value = mockedHeaders[key]; + if (value !== undefined) { + normalizedRes.setHeader(key, Array.isArray(value) ? value.map(String) : String(value)); + } + } + normalizedRes.statusCode = mockedRes.statusCode; + if (result !== null) { + return result; + } + if (mockedRes.buffers.length > 0) { + return Buffer.concat(mockedRes.buffers).toString('utf8'); + } + return null; + } + async renderErrorToResponseImpl(ctx, err) { + const { req, res, query } = ctx; + const is404 = res.statusCode === 404; + if (is404 && this.enabledDirectories.app) { + if (this.dev) { + await this.ensurePage({ + page: _constants.UNDERSCORE_NOT_FOUND_ROUTE_ENTRY, + clientOnly: false, + url: req.url + }).catch(()=>{}); + } + if (this.getEdgeFunctionsPages().includes(_constants.UNDERSCORE_NOT_FOUND_ROUTE_ENTRY)) { + await this.runEdgeFunction({ + req, + res, + query: query || {}, + params: {}, + page: _constants.UNDERSCORE_NOT_FOUND_ROUTE_ENTRY, + appPaths: null + }); + return null; + } + } + return super.renderErrorToResponseImpl(ctx, err); + } + async renderError(err, req, res, pathname, query, setHeaders) { + return super.renderError(err, this.normalizeReq(req), this.normalizeRes(res), pathname, query, setHeaders); + } + async renderErrorToHTML(err, req, res, pathname, query) { + return super.renderErrorToHTML(err, this.normalizeReq(req), this.normalizeRes(res), pathname, query); + } + async render404(req, res, parsedUrl, setHeaders) { + return super.render404(this.normalizeReq(req), this.normalizeRes(res), parsedUrl, setHeaders); + } + getMiddlewareManifest() { + if (this.minimalMode) { + return null; + } else { + const manifest = require(this.middlewareManifestPath); + return manifest; + } + } + /** Returns the middleware routing item if there is one. */ async getMiddleware() { + var _manifest_middleware; + const manifest = this.getMiddlewareManifest(); + const middleware = manifest == null ? void 0 : (_manifest_middleware = manifest.middleware) == null ? void 0 : _manifest_middleware['/']; + if (!middleware) { + const middlewareModule = await this.loadNodeMiddleware(); + if (middlewareModule) { + var _middlewareModule_config; + return { + match: (0, _middlewareroutematcher.getMiddlewareRouteMatcher)(((_middlewareModule_config = middlewareModule.config) == null ? void 0 : _middlewareModule_config.matchers) || [ + { + regexp: '.*', + originalSource: '/:path*' + } + ]), + page: '/' + }; + } + return; + } + return { + match: getMiddlewareMatcher(middleware), + page: '/' + }; + } + getEdgeFunctionsPages() { + const manifest = this.getMiddlewareManifest(); + if (!manifest) { + return []; + } + return Object.keys(manifest.functions); + } + /** + * Get information for the edge function located in the provided page + * folder. If the edge function info can't be found it will throw + * an error. + */ getEdgeFunctionInfo(params) { + const manifest = this.getMiddlewareManifest(); + if (!manifest) { + return null; + } + let foundPage; + try { + foundPage = (0, _denormalizepagepath.denormalizePagePath)((0, _normalizepagepath.normalizePagePath)(params.page)); + } catch (err) { + return null; + } + let pageInfo = params.middleware ? manifest.middleware[foundPage] : manifest.functions[foundPage]; + if (!pageInfo) { + if (!params.middleware) { + throw new _utils.PageNotFoundError(foundPage); + } + return null; + } + return { + name: pageInfo.name, + paths: pageInfo.files.map((file)=>(0, _path.join)(/* turbopackIgnore: true */ this.distDir, file)), + wasm: (pageInfo.wasm ?? []).map((binding)=>({ + ...binding, + filePath: (0, _path.join)(/* turbopackIgnore: true */ this.distDir, binding.filePath) + })), + assets: pageInfo.assets && pageInfo.assets.map((binding)=>{ + return { + ...binding, + filePath: (0, _path.join)(/* turbopackIgnore: true */ this.distDir, binding.filePath) + }; + }), + env: pageInfo.env + }; + } + async loadNodeMiddleware() { + if (!process.env.NEXT_MINIMAL) { + try { + var _functionsConfig_functions; + const functionsConfig = this.dev ? {} : require((0, _path.join)(/* turbopackIgnore: true */ this.distDir, 'server', _constants.FUNCTIONS_CONFIG_MANIFEST)); + if (this.dev || (functionsConfig == null ? void 0 : (_functionsConfig_functions = functionsConfig.functions) == null ? void 0 : _functionsConfig_functions['/_middleware'])) { + // if used with top level await, this will be a promise + return require((0, _path.join)(/* turbopackIgnore: true */ this.distDir, 'server', 'middleware.js')); + } + } catch (err) { + if ((0, _iserror.default)(err) && err.code !== 'ENOENT' && err.code !== 'MODULE_NOT_FOUND') { + throw err; + } + } + } + } + /** + * Checks if a middleware exists. This method is useful for the development + * server where we need to check the filesystem. Here we just check the + * middleware manifest. + */ async hasMiddleware(pathname) { + const info = this.getEdgeFunctionInfo({ + page: pathname, + middleware: true + }); + const nodeMiddleware = await this.loadNodeMiddleware(); + if (!info && nodeMiddleware) { + return true; + } + return Boolean(info && info.paths.length > 0); + } + /** + * A placeholder for a function to be defined in the development server. + * It will make sure that the root middleware or an edge function has been compiled + * so that we can run it. + */ async ensureMiddleware(_url) {} + async ensureEdgeFunction(_params) {} + /** + * This method gets all middleware matchers and execute them when the request + * matches. It will make sure that each middleware exists and is compiled and + * ready to be invoked. The development server will decorate it to add warns + * and errors with rich traces. + */ async runMiddleware(params) { + if (process.env.NEXT_MINIMAL) { + throw new Error('invariant: runMiddleware should not be called in minimal mode'); + } + // Middleware is skipped for on-demand revalidate requests + if ((0, _apiutils.checkIsOnDemandRevalidate)(params.request.headers, this.renderOpts.previewProps).isOnDemandRevalidate) { + return { + response: new Response(null, { + headers: { + 'x-middleware-next': '1' + } + }) + }; + } + let url; + if (this.nextConfig.skipProxyUrlNormalize) { + url = (0, _requestmeta.getRequestMeta)(params.request, 'initURL'); + } else { + // For middleware to "fetch" we must always provide an absolute URL + const query = (0, _querystring.urlQueryToSearchParams)(params.parsed.query).toString(); + const locale = (0, _requestmeta.getRequestMeta)(params.request, 'locale'); + url = `${(0, _requestmeta.getRequestMeta)(params.request, 'initProtocol')}://${this.fetchHostname || 'localhost'}:${this.port}${locale ? `/${locale}` : ''}${params.parsed.pathname}${query ? `?${query}` : ''}`; + } + if (!url.startsWith('http')) { + throw new Error('To use middleware you must provide a `hostname` and `port` to the Next.js Server'); + } + const page = {}; + const middleware = await this.getMiddleware(); + if (!middleware) { + return { + finished: false + }; + } + if (!await this.hasMiddleware(middleware.page)) { + return { + finished: false + }; + } + await this.ensureMiddleware(params.request.url); + const middlewareInfo = this.getEdgeFunctionInfo({ + page: middleware.page, + middleware: true + }); + const method = (params.request.method || 'GET').toUpperCase(); + const requestData = { + headers: params.request.headers, + method, + nextConfig: { + basePath: this.nextConfig.basePath, + i18n: this.nextConfig.i18n, + trailingSlash: this.nextConfig.trailingSlash, + experimental: this.nextConfig.experimental + }, + url: url, + page, + body: method !== 'GET' && method !== 'HEAD' ? (0, _requestmeta.getRequestMeta)(params.request, 'clonableBody') : undefined, + signal: (0, _nextrequest.signalFromNodeResponse)(params.response.originalResponse), + waitUntil: this.getWaitUntil() + }; + let result; + // if no middleware info check for Node.js middleware + // this is not in the middleware-manifest as that historically + // has only included edge-functions, we need to do a breaking + // version bump for that manifest to write this info there if + // we decide we want to + if (!middlewareInfo) { + let middlewareModule; + middlewareModule = await this.loadNodeMiddleware(); + if (!middlewareModule) { + throw new _utils.MiddlewareNotFoundError(); + } + const adapterFn = middlewareModule.default || middlewareModule; + const hasRequestBody = ![ + 'HEAD', + 'GET' + ].includes(params.request.method) && Boolean(requestData.body); + try { + // Node.js middleware runs in-process, inside the active + // `handleRequest` span. Detach that span so the middleware span + // becomes a sibling root (or parents to an incoming traceparent), + // matching edge middleware which runs in a detached sandbox. + result = await (0, _tracer.getTracer)().runWithDetachedContext(()=>adapterFn({ + handler: middlewareModule.proxy || middlewareModule.middleware || middlewareModule, + request: { + ...requestData, + body: hasRequestBody ? requestData.body.cloneBodyStream() : undefined + }, + page: 'middleware' + })); + } finally{ + if (hasRequestBody) { + await requestData.body.finalize(); + } + } + } else { + const { run } = require('./web/sandbox'); + result = await run({ + distDir: this.distDir, + name: middlewareInfo.name, + paths: middlewareInfo.paths, + edgeFunctionEntry: middlewareInfo, + request: requestData, + useCache: true, + onWarning: params.onWarning, + clientAssetToken: this.nextConfig.supportsImmutableAssets ? '' : this.deploymentId + }); + } + if (!this.dev) { + result.waitUntil.catch((error)=>{ + console.error(`Uncaught: middleware waitUntil errored`, error); + }); + } + if (!result) { + this.render404(params.request, params.response, params.parsed); + return { + finished: true + }; + } + // Split compound (comma-separated) set-cookie headers + if (result.response.headers.has('set-cookie')) { + const cookies = result.response.headers.getSetCookie().flatMap((maybeCompoundCookie)=>(0, _utils1.splitCookiesString)(maybeCompoundCookie)); + // Clear existing header(s) + result.response.headers.delete('set-cookie'); + // Append each cookie individually. + for (const cookie of cookies){ + result.response.headers.append('set-cookie', cookie); + } + // Add cookies to request meta. + (0, _requestmeta.addRequestMeta)(params.request, 'middlewareCookie', cookies); + } + return result; + } + getPrerenderManifest() { + if (this._cachedPrerenderManifest) { + return this._cachedPrerenderManifest; + } + this._cachedPrerenderManifest = (0, _loadmanifestexternal.loadManifest)((0, _path.join)(/* turbopackIgnore: true */ this.distDir, _constants.PRERENDER_MANIFEST)); + return this._cachedPrerenderManifest; + } + getPreviewProps() { + if (this._cachedPreviewPropsManifest) { + return this._cachedPreviewPropsManifest; + } + this._cachedPreviewPropsManifest = (0, _loadmanifestexternal.loadManifest)((0, _path.join)(/* turbopackIgnore: true */ this.distDir, 'server', _constants.PREVIEW_PROPS_MANIFEST)); + return this._cachedPreviewPropsManifest; + } + getPrefetchHints() { + if (this._cachedPrefetchHints) { + return this._cachedPrefetchHints; + } + this._cachedPrefetchHints = (0, _loadmanifestexternal.loadManifest)((0, _path.join)(/* turbopackIgnore: true */ this.distDir, _constants.SERVER_DIRECTORY, _constants.PREFETCH_HINTS), true, undefined, false, true // handleMissing: don't crash if the file doesn't exist + ) ?? {}; + return this._cachedPrefetchHints; + } + getRoutesManifest() { + return (0, _tracer.getTracer)().trace(_constants1.NextNodeServerSpan.getRoutesManifest, ()=>(0, _loadmanifestexternal.loadManifest)((0, _path.join)(/* turbopackIgnore: true */ this.distDir, _constants.ROUTES_MANIFEST))); + } + attachRequestMeta(req, parsedUrl, isUpgradeReq) { + var _req_headers_xforwardedproto; + // Injected in base-server.ts + const protocol = ((_req_headers_xforwardedproto = req.headers['x-forwarded-proto']) == null ? void 0 : _req_headers_xforwardedproto.includes('https')) ? 'https' : 'http'; + // When there are hostname and port we build an absolute URL + const initUrl = this.fetchHostname && this.port ? `${protocol}://${this.fetchHostname}:${this.port}${req.url}` : this.nextConfig.experimental.trustHostHeader ? `https://${req.headers.host || 'localhost'}${req.url}` : req.url; + (0, _requestmeta.addRequestMeta)(req, 'initURL', initUrl); + (0, _requestmeta.addRequestMeta)(req, 'initQuery', { + ...parsedUrl.query + }); + (0, _requestmeta.addRequestMeta)(req, 'initProtocol', protocol); + if (!isUpgradeReq) { + var _this_nextConfig_experimental; + const bodySizeLimit = (_this_nextConfig_experimental = this.nextConfig.experimental) == null ? void 0 : _this_nextConfig_experimental.proxyClientMaxBodySize; + (0, _requestmeta.addRequestMeta)(req, 'clonableBody', (0, _bodystreams.getCloneableBody)(req.originalRequest, bodySizeLimit)); + } + } + async runEdgeFunction(params) { + if (process.env.NEXT_MINIMAL) { + throw new Error('Middleware is not supported in minimal mode. Please remove the `NEXT_MINIMAL` environment variable.'); + } + let edgeInfo; + const { query, page, match } = params; + if (!match) await this.ensureEdgeFunction({ + page, + appPaths: params.appPaths, + url: params.req.url + }); + edgeInfo = this.getEdgeFunctionInfo({ + page, + middleware: false + }); + if (!edgeInfo) { + return null; + } + // For edge to "fetch" we must always provide an absolute URL + const isNextDataRequest = (0, _requestmeta.getRequestMeta)(params.req, 'isNextDataReq'); + const initialUrl = new URL((0, _requestmeta.getRequestMeta)(params.req, 'initURL') || '/', 'http://n'); + const queryString = (0, _querystring.urlQueryToSearchParams)({ + ...Object.fromEntries(initialUrl.searchParams), + ...query, + ...params.params + }).toString(); + if (isNextDataRequest) { + params.req.headers['x-nextjs-data'] = '1'; + } + initialUrl.search = queryString; + const url = initialUrl.toString(); + if (!url.startsWith('http')) { + throw new Error('To use middleware you must provide a `hostname` and `port` to the Next.js Server'); + } + const { run } = require('./web/sandbox'); + const result = await run({ + distDir: this.distDir, + name: edgeInfo.name, + paths: edgeInfo.paths, + edgeFunctionEntry: edgeInfo, + request: { + headers: params.req.headers, + method: params.req.method, + nextConfig: { + basePath: this.nextConfig.basePath, + i18n: this.nextConfig.i18n, + trailingSlash: this.nextConfig.trailingSlash + }, + url, + page: { + name: params.page, + ...params.params && { + params: params.params + } + }, + body: (0, _requestmeta.getRequestMeta)(params.req, 'clonableBody'), + signal: (0, _nextrequest.signalFromNodeResponse)(params.res.originalResponse), + waitUntil: this.getWaitUntil() + }, + useCache: true, + onError: params.onError, + onWarning: params.onWarning, + incrementalCache: globalThis.__incrementalCache || (0, _requestmeta.getRequestMeta)(params.req, 'incrementalCache'), + serverComponentsHmrCache: (0, _requestmeta.getRequestMeta)(params.req, 'serverComponentsHmrCache'), + clientAssetToken: this.nextConfig.supportsImmutableAssets ? '' : this.deploymentId + }); + if (result.fetchMetrics) { + params.req.fetchMetrics = result.fetchMetrics; + } + if (!params.res.statusCode || params.res.statusCode < 400) { + params.res.statusCode = result.response.status; + params.res.statusMessage = result.response.statusText; + } + // TODO: (wyattjoh) investigate improving this + result.response.headers.forEach((value, key)=>{ + // The append handling is special cased for `set-cookie`. + if (key.toLowerCase() === 'set-cookie') { + // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici + for (const cookie of (0, _utils1.splitCookiesString)(value)){ + params.res.appendHeader(key, cookie); + } + } else { + params.res.appendHeader(key, value); + } + }); + const { originalResponse } = params.res; + if (result.response.body) { + await (0, _pipereadable.pipeToNodeResponse)(result.response.body, originalResponse); + } else { + originalResponse.end(); + } + return result; + } + get serverDistDir() { + if (this._serverDistDir) { + return this._serverDistDir; + } + const serverDistDir = (0, _path.join)(/* turbopackIgnore: true */ this.distDir, _constants.SERVER_DIRECTORY); + this._serverDistDir = serverDistDir; + return serverDistDir; + } + async getFallbackErrorComponents(_url) { + // Not implemented for production use cases, this is implemented on the + // development server. + return null; + } + async instrumentationOnRequestError(...args) { + await super.instrumentationOnRequestError(...args); + // For Node.js runtime production logs, in dev it will be overridden by next-dev-server + if (!this.dev) { + const [err, , , silenceLog] = args; + if (!silenceLog) { + this.logError(err); + } + } + } + onServerClose(listener) { + this.cleanupListeners.add(listener); + } + async close() { + await this.cleanupListeners.runAll(); + } + getInternalWaitUntil() { + this.internalWaitUntil ??= this.createInternalWaitUntil(); + return this.internalWaitUntil; + } + createInternalWaitUntil() { + if (this.minimalMode) { + throw new _invarianterror.InvariantError('createInternalWaitUntil should never be called in minimal mode'); + } + const awaiter = new _awaiter.AwaiterOnce({ + onError: console.error + }); + // TODO(after): warn if the process exits before these are awaited + this.onServerClose(()=>awaiter.awaiting()); + return awaiter.waitUntil; + } +} + +//# sourceMappingURL=next-server.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/next-server.js.map b/e-commerce/node_modules/next/dist/server/next-server.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7c77919a5ab04f5f29d9ab4e86a8b872f82a9e11 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/next-server.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/next-server.ts"],"sourcesContent":["import './node-environment'\nimport './require-hook'\nimport './node-polyfill-crypto'\n\nimport type { CacheFs } from '../shared/lib/utils'\nimport {\n DecodeError,\n PageNotFoundError,\n MiddlewareNotFoundError,\n} from '../shared/lib/utils'\nimport type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'\nimport type RenderResult from './render-result'\nimport type { FetchEventResult } from './web/types'\nimport type {\n PrerenderManifest,\n PreviewPropsManifest,\n RoutesManifest,\n} from '../build'\nimport type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'\nimport type {\n NextParsedUrlQuery,\n NextUrlWithParsedQuery,\n RequestMeta,\n} from './request-meta'\nimport type { Params } from './request/params'\nimport type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'\nimport type { RouteMatch } from './route-matches/route-match'\nimport type {\n DevRenderContext,\n RouteMatch as AppRenderRouteMatch,\n} from './route-modules/app-page/module'\nimport { createDevRenderContext } from './route-modules/app-page/dev-render-context'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { ParsedUrl } from '../shared/lib/router/utils/parse-url'\nimport type { CacheControl } from './lib/cache-control'\nimport type { WaitUntil } from './after/builtin-request-context'\nimport type { AppPageModule } from './route-modules/app-page/module'\nimport type { AppRouteModule } from './route-modules/app-route/module.compiled'\nimport type { ErrorModule } from './load-default-error-components'\nimport type { PagesModule } from './route-modules/pages/module.compiled'\n\nimport fs from 'fs'\nimport { join, relative } from 'path'\nimport { format as formatUrl } from 'url'\nimport { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from './request-meta'\nimport {\n PAGES_MANIFEST,\n BUILD_ID_FILE,\n MIDDLEWARE_MANIFEST,\n PREFETCH_HINTS,\n PRERENDER_MANIFEST,\n ROUTES_MANIFEST,\n CLIENT_PUBLIC_FILES_PATH,\n APP_PATHS_MANIFEST,\n SERVER_DIRECTORY,\n NEXT_FONT_MANIFEST,\n UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n FUNCTIONS_CONFIG_MANIFEST,\n PREVIEW_PROPS_MANIFEST,\n} from '../shared/lib/constants'\nimport { findDir } from '../lib/find-pages-dir'\nimport { NodeNextRequest, NodeNextResponse } from './base-http/node'\nimport { sendRenderResult } from './send-payload'\nimport { parseUrl } from '../shared/lib/router/utils/parse-url'\nimport * as Log from '../build/output/log'\n\nimport type {\n Options,\n FindComponentsResult,\n MiddlewareRoutingItem,\n RequestContext,\n NormalizedRouteManifest,\n LoadedRenderOpts,\n RouteHandler,\n NextEnabledDirectories,\n BaseRequestHandler,\n} from './base-server'\nimport BaseServer from './base-server'\nimport { getMaybePagePath, getPagePath } from './require'\nimport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { selectAppPageEntry } from '../shared/lib/router/utils/app-paths'\nimport { loadComponents } from './load-components'\nimport type { LoadComponentsReturnType } from './load-components'\nimport isError, { getProperError } from '../lib/is-error'\nimport { splitCookiesString, toNodeOutgoingHttpHeaders } from './web/utils'\nimport { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher'\nimport { loadEnvConfig } from '@next/env'\nimport { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\nimport { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'\nimport { getCloneableBody } from './body-streams'\nimport { checkIsOnDemandRevalidate } from './api-utils'\nimport ResponseCache, {\n CachedRouteKind,\n type IncrementalResponseCacheEntry,\n} from './response-cache'\nimport {\n IncrementalCache,\n type CacheHandler as ICacheHandler,\n} from './lib/incremental-cache'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\n\nimport { setHttpClientAndAgentOptions } from './setup-http-agent-env'\n\nimport { isPagesAPIRouteMatch } from './route-matches/pages-api-route-match'\nimport type { PagesAPIRouteMatch } from './route-matches/pages-api-route-match'\nimport { BubbledError, getTracer } from './lib/trace/tracer'\nimport { NextNodeServerSpan } from './lib/trace/constants'\nimport { nodeFs } from './lib/node-fs-methods'\nimport { getRouteRegex } from '../shared/lib/router/utils/route-regex'\nimport { pipeToNodeResponse } from './pipe-readable'\nimport { createRequestResponseMocks, MockedResponse } from './lib/mock-request'\nimport { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'\nimport { signalFromNodeResponse } from './web/spec-extension/adapters/next-request'\nimport { loadManifest } from './load-manifest.external'\nimport {\n lazyPrerenderAppPage,\n lazyRenderAppPage,\n} from './route-modules/app-page/module.render'\nimport {\n parseRequestHeaders,\n type ParsedRequestHeaders,\n} from './route-modules/app-page/parse-request-headers'\nimport { lazyRenderPagesPage } from './route-modules/pages/module.render'\nimport { interopDefault } from '../lib/interop-default'\nimport { formatDynamicImportPath } from '../lib/format-dynamic-import-path'\nimport type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'\nimport { isInterceptionRouteRewrite } from '../lib/is-interception-route-rewrite'\nimport type { ServerOnInstrumentationRequestError } from './app-render/types'\nimport type { PrefetchHints } from '../shared/lib/app-router-types'\nimport { RouteKind } from './route-kind'\nimport { InvariantError } from '../shared/lib/invariant-error'\nimport { AwaiterOnce } from './after/awaiter'\nimport { AsyncCallbackSet } from './lib/async-callback-set'\nimport {\n initializeCacheHandlers,\n registerCustomCacheHandlers,\n setCacheHandler,\n} from './use-cache/handlers'\nimport type { UnwrapPromise } from '../lib/coalesced-function'\nimport { populateStaticEnv } from '../lib/static-env'\nimport { NodeModuleLoader } from './lib/module-loader/node-module-loader'\nimport { NoFallbackError } from '../shared/lib/no-fallback-error.external'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from './lib/router-utils/instrumentation-globals.external'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n} from './lib/router-utils/router-server-context'\nimport { installGlobalBehaviors } from './node-environment-extensions/global-behaviors'\nimport { installProcessErrorHandlers } from './node-environment-extensions/process-error-handlers'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\n\nexport * from './base-server'\n\n// For module that can be both CJS or ESM\nconst dynamicImportEsmDefault = process.env.NEXT_MINIMAL\n ? (id: string) =>\n import(/* webpackIgnore: true */ id).then((mod) => mod.default || mod)\n : (id: string) => import(id).then((mod) => mod.default || mod)\n\nexport type NodeRequestHandler = BaseRequestHandler<\n IncomingMessage | NodeNextRequest,\n ServerResponse | NodeNextResponse\n>\n\ntype NodeRouteHandler = RouteHandler\n\nconst MiddlewareMatcherCache = new WeakMap<\n MiddlewareManifest['middleware'][string],\n MiddlewareRouteMatch\n>()\n\nfunction getMiddlewareMatcher(\n info: MiddlewareManifest['middleware'][string]\n): MiddlewareRouteMatch {\n const stored = MiddlewareMatcherCache.get(info)\n if (stored) {\n return stored\n }\n\n if (!Array.isArray(info.matchers)) {\n throw new Error(\n `Invariant: invalid matchers for middleware ${JSON.stringify(info)}`\n )\n }\n\n const matcher = getMiddlewareRouteMatcher(info.matchers)\n MiddlewareMatcherCache.set(info, matcher)\n return matcher\n}\n\nexport default class NextNodeServer extends BaseServer<\n Options,\n NodeNextRequest,\n NodeNextResponse\n> {\n protected middlewareManifestPath: string\n private _serverDistDir: string | undefined\n private imageResponseCache?: ResponseCache\n private imageCacheHandler?: ICacheHandler\n protected renderWorkersPromises?: Promise\n protected dynamicRoutes?: {\n match: import('../shared/lib/router/utils/route-matcher').RouteMatchFn\n page: string\n re: RegExp\n }[]\n private routerServerHandler?: (\n req: IncomingMessage,\n res: ServerResponse\n ) => void\n\n protected cleanupListeners = new AsyncCallbackSet()\n protected internalWaitUntil: WaitUntil | undefined\n private isDev: boolean\n private sriEnabled: boolean\n\n constructor(options: Options) {\n // Initialize super class\n super(options)\n\n installGlobalBehaviors(this.nextConfig)\n\n // Load prefetch hints from the build output. This must happen before\n // any render to ensure segment inlining decisions are available.\n this.renderOpts.prefetchHints = this.getPrefetchHints()\n\n const isDev = options.dev ?? false\n this.isDev = isDev\n this.sriEnabled = Boolean(options.conf.experimental?.sri?.algorithm)\n\n /**\n * This sets environment variable to be used at the time of SSR by head.tsx.\n * Using this from process.env allows targeting SSR by calling\n * `process.env.__NEXT_OPTIMIZE_CSS`.\n */\n if (this.renderOpts.optimizeCss) {\n process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)\n }\n if (this.renderOpts.nextScriptWorkers) {\n process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true)\n }\n if (\n (isDev || process.env.__NEXT_DEV_SERVER) &&\n this.nextConfig.experimental.requestInsights\n ) {\n process.env.__NEXT_REQUEST_INSIGHTS = 'true'\n } else {\n delete process.env.__NEXT_REQUEST_INSIGHTS\n }\n\n if (!this.minimalMode) {\n this.imageResponseCache = new ResponseCache({\n minimalMode: this.minimalMode,\n route: 'image',\n })\n }\n\n if (\n !options.dev &&\n !this.minimalMode &&\n this.nextConfig.experimental.preloadEntriesOnStart\n ) {\n // Preloading may join a failing registration started by a request.\n void this.unstable_preloadEntries().catch((err) => {\n Log.error('Failed to preload entries:', err)\n })\n }\n\n if (!options.dev) {\n const { dynamicRoutes = [] } = this.getRoutesManifest() ?? {}\n this.dynamicRoutes = dynamicRoutes.map((r) => {\n // TODO: can we just re-use the regex from the manifest?\n const regex = getRouteRegex(r.page)\n const match = getRouteMatcher(regex)\n\n return {\n match,\n page: r.page,\n re: regex.re,\n }\n })\n }\n\n // ensure options are set when loadConfig isn't called\n setHttpClientAndAgentOptions(this.nextConfig)\n\n // Intercept fetch and other testmode apis.\n if (this.serverOptions.experimentalTestProxy) {\n process.env.NEXT_PRIVATE_TEST_PROXY = 'true'\n const { 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 interceptTestApis()\n }\n\n this.middlewareManifestPath = join(\n /* turbopackIgnore: true */ this.serverDistDir,\n MIDDLEWARE_MANIFEST\n )\n\n // This is just optimization to fire prepare as soon as possible. It will be\n // properly awaited later. We add the catch here to ensure that it does not\n // cause a unhandled promise rejection. The promise rejection will be\n // handled later on via the `await` when the request handler is called.\n if (!options.dev) {\n this.prepare().catch((err) => {\n console.error('Failed to prepare server', err)\n })\n }\n\n // when using compile mode static env isn't inlined so we\n // need to populate in normal runtime env\n if (this.renderOpts.isExperimentalCompile) {\n // supportsImmutableAssets only works with Turbopack, and `isExperimentalCompile` isn't supported\n // with that anyway, so we can assign just use deploymentId here\n populateStaticEnv(this.nextConfig, this.deploymentId || '')\n }\n\n const shouldRemoveUncaughtErrorAndRejectionListeners = Boolean(\n options.conf.experimental?.removeUncaughtErrorAndRejectionListeners\n )\n installProcessErrorHandlers(shouldRemoveUncaughtErrorAndRejectionListeners)\n }\n\n public async unstable_preloadEntries(): Promise {\n // Ensure prepare process will be finished before preloading entries.\n await this.prepare()\n\n const appPathsManifest = this.getAppPathsManifest()\n const pagesManifest = this.getPagesManifest()\n\n await this.loadCustomCacheHandlers()\n\n for (const page of Object.keys(pagesManifest || {})) {\n try {\n await loadComponents({\n distDir: this.distDir,\n page,\n isAppPath: false,\n isDev: this.isDev,\n sriEnabled: this.sriEnabled,\n needsManifestsForLegacyReasons: false,\n })\n } catch (_err) {\n // Intentionally ignored because this is a preload step.\n }\n }\n\n for (const page of Object.keys(appPathsManifest || {})) {\n try {\n const { ComponentMod } = await loadComponents<\n AppPageModule | AppRouteModule\n >({\n distDir: this.distDir,\n page,\n isAppPath: true,\n isDev: this.isDev,\n sriEnabled: this.sriEnabled,\n needsManifestsForLegacyReasons: false,\n })\n // we need to ensure fetch is patched before we require the page,\n // otherwise if the fetch is patched by user code, we will be patching it\n // too late and there won't be any caching behaviors\n ComponentMod.patchFetch()\n } catch (_err) {\n // Intentionally ignored because this is a preload step.\n }\n }\n }\n\n protected async handleUpgrade(): Promise {\n // The web server does not support web sockets, it's only used for HMR in\n // development.\n }\n\n protected async loadInstrumentationModule() {\n if (!this.serverOptions.dev) {\n try {\n this.instrumentation = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n if (err.code !== 'MODULE_NOT_FOUND') {\n throw new Error(\n 'An error occurred while loading the instrumentation hook',\n { cause: err }\n )\n }\n }\n }\n return this.instrumentation\n }\n\n protected async prepareImpl() {\n await super.prepareImpl()\n await this.runInstrumentationHookIfAvailable()\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected loadEnvConfig({\n dev,\n forceReload,\n }: {\n dev: boolean\n forceReload: boolean\n }) {\n loadEnvConfig(\n this.dir,\n dev,\n Log,\n forceReload,\n forceReload\n ? (envFilePath) => {\n Log.info(`Reload env: ${envFilePath}`)\n }\n : undefined\n )\n }\n\n private async loadCustomCacheHandlers() {\n const { cacheMaxMemorySize, cacheHandlers } = this.nextConfig\n if (!cacheHandlers) return\n\n initializeCacheHandlers(cacheMaxMemorySize)\n await registerCustomCacheHandlers(async () => {\n for (const [kind, handler] of Object.entries(cacheHandlers)) {\n if (!handler) continue\n\n setCacheHandler(\n kind,\n interopDefault(\n await dynamicImportEsmDefault(\n formatDynamicImportPath(this.distDir, handler)\n )\n )\n )\n }\n })\n }\n\n protected async getIncrementalCache({\n requestHeaders,\n }: {\n requestHeaders: IncrementalCache['requestHeaders']\n }) {\n const dev = !!this.dev\n let CacheHandler: any\n const { cacheHandler } = this.nextConfig\n\n if (cacheHandler) {\n CacheHandler = interopDefault(\n await dynamicImportEsmDefault(\n formatDynamicImportPath(this.distDir, cacheHandler)\n )\n )\n }\n\n await this.loadCustomCacheHandlers()\n\n // incremental-cache is request specific\n // although can have shared caches in module scope\n // per-cache handler\n return new IncrementalCache({\n fs: this.getCacheFilesystem(),\n dev,\n requestHeaders,\n allowedRevalidateHeaderKeys:\n this.nextConfig.experimental.allowedRevalidateHeaderKeys,\n minimalMode: this.minimalMode,\n serverDistDir: this.serverDistDir,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,\n flushToDisk:\n !this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,\n previewProps: this.getPreviewProps(),\n prerenderManifest: this.getPrerenderManifest(),\n locales: this.nextConfig.i18n?.locales,\n CurCacheHandler: CacheHandler,\n })\n }\n\n protected getPublicDir(): string {\n return join(/* turbopackIgnore: true */ this.dir, CLIENT_PUBLIC_FILES_PATH)\n }\n\n protected getHasStaticDir(): boolean {\n return fs.existsSync(\n /* turbopackIgnore: true */ join(\n /* turbopackIgnore: true */ this.dir,\n 'static'\n )\n )\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return loadManifest(\n join(/* turbopackIgnore: true */ this.serverDistDir, PAGES_MANIFEST)\n ) as PagesManifest\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return loadManifest(\n join(/* turbopackIgnore: true */ this.serverDistDir, APP_PATHS_MANIFEST)\n ) as PagesManifest\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n if (!this.enabledDirectories.app) return []\n\n const routesManifest = this.getRoutesManifest()\n return (\n routesManifest?.rewrites.beforeFiles\n .filter(isInterceptionRouteRewrite)\n .map((rewrite) => new RegExp(rewrite.regex)) ?? []\n )\n }\n\n protected async hasPage(pathname: string): Promise {\n return !!getMaybePagePath(\n pathname,\n this.distDir,\n this.nextConfig.i18n?.locales,\n this.enabledDirectories.app\n )\n }\n\n protected getBuildId(): string {\n const buildIdFile = join(\n /* turbopackIgnore: true */ this.distDir,\n BUILD_ID_FILE\n )\n try {\n return fs\n .readFileSync(/* turbopackIgnore: true */ buildIdFile, 'utf8')\n .trim()\n } catch (err: any) {\n if (err.code === 'ENOENT') {\n throw new Error(\n `Could not find a production build in the '${this.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`\n )\n }\n\n throw err\n }\n }\n\n protected getEnabledDirectories(dev: boolean): NextEnabledDirectories {\n const dir = dev ? this.dir : this.serverDistDir\n\n return {\n app: findDir(dir, 'app') ? true : false,\n pages: findDir(dir, 'pages') ? true : false,\n }\n }\n\n protected sendRenderResult(\n req: NodeNextRequest,\n res: NodeNextResponse,\n options: {\n result: RenderResult\n generateEtags: boolean\n poweredByHeader: boolean\n cacheControl: CacheControl | undefined\n }\n ): Promise {\n return sendRenderResult({\n req: req.originalRequest,\n res: res.originalResponse,\n result: options.result,\n generateEtags: options.generateEtags,\n poweredByHeader: options.poweredByHeader,\n cacheControl: options.cacheControl,\n })\n }\n\n protected async runApi(\n req: NodeNextRequest,\n res: NodeNextResponse,\n query: ParsedUrlQuery,\n match: PagesAPIRouteMatch\n ): Promise {\n const edgeFunctionsPages = this.getEdgeFunctionsPages()\n\n for (const edgeFunctionsPage of edgeFunctionsPages) {\n if (edgeFunctionsPage === match.definition.pathname) {\n const handledAsEdgeFunction = await this.runEdgeFunction({\n req,\n res,\n query,\n params: match.params,\n page: match.definition.pathname,\n appPaths: null,\n })\n\n if (handledAsEdgeFunction) {\n return true\n }\n }\n }\n // The module supports minimal mode, load the minimal module.\n // Restore original URL as the handler handles it's own parsing\n const parsedInitUrl = parseUrl(getRequestMeta(req, 'initURL') || req.url)\n req.url = `${parsedInitUrl.pathname}${parsedInitUrl.search || ''}`\n\n const loader = new NodeModuleLoader()\n // Dev definitions retain source filenames for watcher bookkeeping. API\n // execution still needs to load the compiled server bundle.\n const modulePath = this.isDev\n ? join(this.distDir, 'server', `${match.definition.bundlePath}.js`)\n : match.definition.filename\n const module = (await loader.load(modulePath)) as {\n handler: (\n req: IncomingMessage,\n res: ServerResponse,\n ctx: {\n waitUntil: ReturnType\n requestMeta?: RequestMeta\n }\n ) => Promise\n }\n addRequestMeta(\n req.originalRequest,\n 'relativeProjectDir',\n relative(process.cwd(), this.dir)\n )\n addRequestMeta(req.originalRequest, 'distDir', this.distDir)\n await module.handler(req.originalRequest, res.originalResponse, {\n waitUntil: this.getWaitUntil(),\n requestMeta: {\n ...getRequestMeta(req.originalRequest),\n query,\n params: match.params,\n },\n })\n return true\n }\n\n protected async renderHTML(\n req: NodeNextRequest,\n res: NodeNextResponse,\n pathname: string,\n query: NextParsedUrlQuery,\n renderOpts: LoadedRenderOpts,\n routeMatch: AppRenderRouteMatch\n ): Promise {\n return getTracer().trace(NextNodeServerSpan.renderHTML, async () =>\n this.renderHTMLImpl(req, res, pathname, query, renderOpts, routeMatch)\n )\n }\n\n private async renderHTMLImpl(\n req: NodeNextRequest,\n res: NodeNextResponse,\n pathname: string,\n query: NextParsedUrlQuery,\n renderOpts: LoadedRenderOpts,\n routeMatch: AppRenderRouteMatch\n ): Promise {\n if (process.env.NEXT_MINIMAL) {\n throw new Error(\n 'Invariant: renderHTML should not be called in minimal mode'\n )\n // the `else` branch is needed for tree-shaking\n } else {\n // Due to the way we pass data by mutating `renderOpts`, we can't extend the\n // object here but only updating its `nextFontManifest` field.\n // https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952\n renderOpts.nextFontManifest = this.nextFontManifest\n\n if (this.enabledDirectories.app && renderOpts.isAppPath) {\n const renderAppPage =\n !renderOpts.supportsDynamicResponse &&\n !renderOpts.isDraftMode &&\n !renderOpts.isPossibleServerAction\n ? lazyPrerenderAppPage\n : lazyRenderAppPage\n const dev: DevRenderContext | undefined = createDevRenderContext(\n req,\n process.env.__NEXT_DEV_SERVER\n ? this.getServerComponentsHmrCache()\n : undefined\n )\n const parsedRequestHeaders: ParsedRequestHeaders = parseRequestHeaders(\n req.headers,\n {\n isRoutePPREnabled:\n renderOpts.experimental.isRoutePPREnabled === true,\n previewModeId: renderOpts.previewProps?.previewModeId,\n }\n )\n\n const result = await renderAppPage(\n req,\n res,\n pathname,\n query,\n // This code path does not service revalidations for unknown param\n // shells. As a result, we don't need to pass in the unknown params.\n null,\n renderOpts as LoadedRenderOpts,\n dev,\n {\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n clientAssetToken: this.nextConfig.supportsImmutableAssets\n ? ''\n : this.deploymentId,\n },\n routeMatch,\n parsedRequestHeaders\n )\n if ('error' in result) {\n throw result.error\n }\n return result\n } else {\n // TODO: re-enable this once we've refactored to use implicit matches\n // throw new Error('Invariant: render should have used routeModule')\n\n return lazyRenderPagesPage(\n req.originalRequest,\n res.originalResponse,\n pathname,\n query,\n renderOpts as LoadedRenderOpts,\n {\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n clientAssetToken: this.nextConfig.supportsImmutableAssets\n ? undefined\n : this.deploymentId,\n customServer: this.serverOptions.customServer || undefined,\n },\n {\n isFallback: false,\n isDraftMode: renderOpts.isDraftMode,\n developmentNotFoundSourcePage: getRequestMeta(\n req,\n 'developmentNotFoundSourcePage'\n ),\n }\n )\n }\n }\n }\n\n protected async imageOptimizer(\n req: NodeNextRequest,\n res: NodeNextResponse,\n paramsResult: import('./image-optimizer').ImageParamsResult,\n previousCacheEntry?: IncrementalResponseCacheEntry | null\n ): Promise<{\n buffer: Buffer\n contentType: string\n maxAge: number\n upstreamEtag: string\n etag: string\n }> {\n if (process.env.NEXT_MINIMAL) {\n throw new Error(\n 'invariant: imageOptimizer should not be called in minimal mode'\n )\n } else {\n const { imageOptimizer, fetchExternalImage, fetchInternalImage } =\n require('./image-optimizer') as typeof import('./image-optimizer')\n\n const handleInternalReq = async (\n newReq: IncomingMessage,\n newRes: ServerResponse\n ) => {\n if (newReq.url === req.url) {\n throw new Error(`Invariant attempted to optimize _next/image itself`)\n }\n\n if (!this.routerServerHandler) {\n throw new Error(`Invariant missing routerServerHandler`)\n }\n\n await this.routerServerHandler(newReq, newRes)\n return\n }\n\n let { href } = paramsResult\n\n if (\n process.env.__NEXT_TEST_MODE &&\n process.env.IS_TURBOPACK_TEST &&\n !paramsResult.isAbsolute\n ) {\n // Forward the dpl query param from the original /_next/image request to the\n // internal static file request so that the static file validation in\n // resolve-routes.ts can verify it.\n const dpl =\n typeof req.url === 'string'\n ? new URL(req.url, 'http://n').searchParams.get('dpl')\n : undefined\n if (dpl) {\n href += `${href.includes('?') ? '&' : '?'}dpl=${dpl}`\n }\n }\n\n const imageUpstream = paramsResult.isAbsolute\n ? await fetchExternalImage(\n href,\n this.nextConfig.images.dangerouslyAllowLocalIP,\n this.nextConfig.images.maximumResponseBody,\n this.nextConfig.images.maximumRedirects\n )\n : await fetchInternalImage(\n href,\n req.originalRequest,\n res.originalResponse,\n this.nextConfig.images.maximumResponseBody,\n handleInternalReq\n )\n\n return imageOptimizer(imageUpstream, paramsResult, this.nextConfig, {\n isDev: this.dev,\n previousCacheEntry,\n })\n }\n }\n\n protected getPagePath(pathname: string, locales?: string[]): string {\n return getPagePath(\n pathname,\n this.distDir,\n locales,\n this.enabledDirectories.app\n )\n }\n\n protected async renderPageComponent(\n ctx: RequestContext,\n bubbleNoFallback: boolean\n ) {\n const edgeFunctionsPages = this.getEdgeFunctionsPages() || []\n if (edgeFunctionsPages.length) {\n const appPaths = this.getOriginalAppPaths(ctx.pathname)\n const isAppPath = Array.isArray(appPaths)\n\n let page = ctx.pathname\n if (isAppPath) {\n // When it's an array, we need to pass all parallel routes to the loader.\n page = selectAppPageEntry(ctx.pathname, appPaths)\n }\n\n for (const edgeFunctionsPage of edgeFunctionsPages) {\n if (edgeFunctionsPage === page) {\n await this.runEdgeFunction({\n req: ctx.req,\n res: ctx.res,\n query: ctx.query,\n params: ctx.renderOpts.params,\n page,\n appPaths,\n })\n return null\n }\n }\n }\n\n return super.renderPageComponent(ctx, bubbleNoFallback)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n // The following parameters are used in the development server's\n // implementation.\n sriEnabled?: boolean\n appPaths?: ReadonlyArray | null\n shouldEnsure: boolean\n url?: string\n }): Promise {\n return getTracer().trace(\n NextNodeServerSpan.findPageComponents,\n {\n spanName: 'resolve page components',\n attributes: {\n 'next.route': isAppPath ? normalizeAppPath(page) : page,\n },\n },\n () =>\n this.findPageComponentsImpl({\n locale,\n page,\n query,\n params,\n isAppPath,\n url,\n })\n )\n }\n\n private async findPageComponentsImpl({\n locale,\n page,\n query,\n params,\n isAppPath,\n url: _url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n url?: string\n }): Promise {\n const pagePaths: string[] = [page]\n\n if (locale) {\n pagePaths.unshift(\n ...pagePaths.map((path) => `/${locale}${path === '/' ? '' : path}`)\n )\n }\n\n for (const pagePath of pagePaths) {\n try {\n const components = await loadComponents({\n distDir: this.distDir,\n page: pagePath,\n isAppPath,\n isDev: this.isDev,\n sriEnabled: this.sriEnabled,\n needsManifestsForLegacyReasons: false,\n })\n\n if (\n locale &&\n typeof components.Component === 'string' &&\n !pagePath.startsWith(`/${locale}/`) &&\n pagePath !== `/${locale}`\n ) {\n // if loading an static HTML file the locale is required\n // to be present since all HTML files are output under their locale\n continue\n }\n\n return {\n components,\n query: {\n ...(!this.renderOpts.isExperimentalCompile &&\n components.getStaticProps\n ? {}\n : query),\n // For appDir params is excluded.\n ...((isAppPath ? {} : params) || {}),\n },\n }\n } catch (err) {\n // we should only not throw if we failed to find the page\n // in the pages-manifest\n if (!(err instanceof PageNotFoundError)) {\n throw err\n }\n }\n }\n return null\n }\n\n protected getNextFontManifest(): DeepReadonly | undefined {\n return loadManifest(\n join(\n /* turbopackIgnore: true */ this.distDir,\n 'server',\n NEXT_FONT_MANIFEST + '.json'\n )\n )\n }\n\n protected handleNextImageRequest: NodeRouteHandler = async (\n req,\n res,\n parsedUrl\n ) => {\n if (!parsedUrl.pathname || !parsedUrl.pathname.startsWith('/_next/image')) {\n return false\n }\n // Ignore if its a middleware request\n if (getRequestMeta(req, 'middlewareInvoke')) {\n return false\n }\n\n if (\n this.minimalMode ||\n this.nextConfig.output === 'export' ||\n process.env.NEXT_MINIMAL\n ) {\n res.statusCode = 400\n res.body('Bad Request').send()\n return true\n // the `else` branch is needed for tree-shaking\n } else {\n const { ImageOptimizerCache } =\n require('./image-optimizer') as typeof import('./image-optimizer')\n\n // Load custom cache handler if configured and opt-in via images.customCacheHandler\n // Cache the handler instance to preserve state across requests\n if (\n !this.imageCacheHandler &&\n this.nextConfig.images.customCacheHandler\n ) {\n const { cacheHandler } = this.nextConfig\n if (cacheHandler) {\n const CacheHandler = interopDefault(\n await dynamicImportEsmDefault(\n formatDynamicImportPath(this.distDir, cacheHandler)\n )\n )\n this.imageCacheHandler = new CacheHandler({\n dev: !!this.dev,\n flushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n serverDistDir: this.serverDistDir,\n maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,\n revalidatedTags: [],\n _requestHeaders: {},\n })\n }\n }\n\n const imageOptimizerCache = new ImageOptimizerCache({\n distDir: this.distDir,\n nextConfig: this.nextConfig,\n cacheHandler: this.imageCacheHandler,\n })\n\n const { sendResponse, ImageError } =\n require('./image-optimizer') as typeof import('./image-optimizer')\n\n if (!this.imageResponseCache) {\n throw new Error('invariant image optimizer cache was not initialized')\n }\n const imagesConfig = this.nextConfig.images\n\n if (imagesConfig.loader !== 'default' || imagesConfig.unoptimized) {\n await this.render404(req, res)\n return true\n }\n\n const paramsResult = ImageOptimizerCache.validateParams(\n req.originalRequest,\n parsedUrl.query,\n this.nextConfig,\n !!this.dev\n )\n\n if ('errorMessage' in paramsResult) {\n res.statusCode = 400\n res.body(paramsResult.errorMessage).send()\n return true\n }\n\n const cacheKey = ImageOptimizerCache.getCacheKey(paramsResult)\n\n try {\n const { getExtension } =\n require('./serve-static') as typeof import('./serve-static')\n const cacheEntry = await this.imageResponseCache.get(\n cacheKey,\n async ({ previousCacheEntry }) => {\n const { buffer, contentType, maxAge, upstreamEtag, etag } =\n await this.imageOptimizer(\n req,\n res,\n paramsResult,\n previousCacheEntry\n )\n\n return {\n value: {\n kind: CachedRouteKind.IMAGE,\n buffer,\n etag,\n extension: getExtension(contentType) as string,\n upstreamEtag,\n },\n cacheControl: { revalidate: maxAge, expire: undefined },\n }\n },\n {\n routeKind: RouteKind.IMAGE,\n incrementalCache: imageOptimizerCache,\n isFallback: false,\n }\n )\n\n if (cacheEntry !== null && 'error' in cacheEntry) {\n throw cacheEntry.error\n }\n\n if (cacheEntry?.value?.kind !== CachedRouteKind.IMAGE) {\n throw new Error(\n 'invariant did not get entry from image response cache'\n )\n }\n\n sendResponse(\n req.originalRequest,\n res.originalResponse,\n paramsResult.href,\n cacheEntry.value.extension,\n cacheEntry.value.buffer,\n cacheEntry.value.etag,\n paramsResult.isStatic,\n cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT',\n imagesConfig,\n cacheEntry.cacheControl?.revalidate || 0,\n Boolean(this.dev)\n )\n return true\n } catch (err) {\n if (err instanceof ImageError) {\n res.statusCode = err.statusCode\n res.body(err.message).send()\n return true\n }\n throw err\n }\n }\n }\n\n protected handleCatchallRenderRequest: NodeRouteHandler = async (\n req,\n res,\n parsedUrl\n ) => {\n let { pathname, query } = parsedUrl\n if (!pathname) {\n throw new Error('Invariant: pathname is undefined')\n }\n\n // When in minimal mode we do not bubble the fallback as the\n // router-server is not present to handle the error\n addRequestMeta(req, 'bubbleNoFallback', this.minimalMode ? undefined : true)\n\n // This is needed to expose render404 and nextConfig\n // for environments without router-server\n if (!routerServerGlobal[RouterServerContextSymbol]) {\n routerServerGlobal[RouterServerContextSymbol] = {}\n }\n const relativeProjectDir = relative(process.cwd(), this.dir)\n const existingServerContext =\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir]\n\n if (!existingServerContext) {\n routerServerGlobal[RouterServerContextSymbol][relativeProjectDir] = {\n render404: this.render404.bind(this),\n getAssetPrefix: this.getAssetPrefix.bind(this),\n }\n }\n routerServerGlobal[RouterServerContextSymbol][\n relativeProjectDir\n ].nextConfig = this.nextConfig\n routerServerGlobal[RouterServerContextSymbol][\n relativeProjectDir\n ].isWrappedByNextServer = true\n\n try {\n // next.js core assumes page path without trailing slash\n pathname = removeTrailingSlash(pathname)\n\n let match = getRequestMeta(req, 'match')\n\n // router-server normally attaches the fsChecker match. Direct internal\n // requests, such as on-demand revalidation, bypass router-server and need\n // to resolve the route from the manifests here.\n if (!match) {\n const localeAnalysisResult = this.i18nProvider?.analyze(pathname, {\n defaultLocale: getRequestMeta(req, 'defaultLocale'),\n })\n\n const routeMatch = this.getRouteMatch(pathname, localeAnalysisResult)\n if (routeMatch) {\n match = routeMatch\n }\n }\n\n // The matcher manager previously fell through to render for unknown\n // paths. Preserve that behavior for direct render-server requests that do\n // not pass through fsChecker.\n if (!match) {\n await this.render(req, res, pathname, query, parsedUrl, true)\n\n return true\n }\n\n // Add the match to the request so we don't have to re-run the matcher\n // for the same request.\n addRequestMeta(req, 'match', match)\n\n // TODO-APP: move this to a route handler\n const edgeFunctionsPages = this.getEdgeFunctionsPages()\n for (const edgeFunctionsPage of edgeFunctionsPages) {\n // If the page doesn't match the edge function page, skip it.\n if (edgeFunctionsPage !== match.definition.page) continue\n\n if (this.nextConfig.output === 'export') {\n await this.render404(req, res, parsedUrl)\n return true\n }\n delete query[NEXT_RSC_UNION_QUERY]\n\n // If we handled the request, we can return early.\n // For api routes edge runtime\n try {\n const handled = await this.runEdgeFunction({\n req,\n res,\n query,\n params: match.params,\n page: match.definition.page,\n match,\n appPaths: null,\n })\n if (handled) return true\n } catch (apiError) {\n const silenceLog = false\n await this.instrumentationOnRequestError(\n apiError,\n req,\n {\n routePath: match.definition.page,\n routerKind: 'Pages Router',\n routeType: 'route',\n // Edge runtime does not support ISR\n revalidateReason: undefined,\n },\n silenceLog\n )\n throw apiError\n }\n }\n\n // If the route was detected as being a Pages API route, then handle\n // it.\n // TODO: move this behavior into a route handler.\n if (isPagesAPIRouteMatch(match)) {\n if (this.nextConfig.output === 'export') {\n await this.render404(req, res, parsedUrl)\n return true\n }\n\n const handled = await this.handleApiRequest(req, res, query, match)\n if (handled) return true\n }\n\n await this.render(req, res, pathname, query, parsedUrl, true)\n\n return true\n } catch (err: any) {\n if (err instanceof NoFallbackError) {\n throw err\n }\n\n try {\n if (this.dev) {\n const { formatServerError } =\n require('../lib/format-server-error') as typeof import('../lib/format-server-error')\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n } else {\n this.logError(err)\n }\n res.statusCode = 500\n await this.renderError(err, req, res, pathname, query)\n return true\n } catch {}\n\n throw err\n }\n }\n\n // Used in development only, overloaded in next-dev-server\n protected logErrorWithOriginalStack(\n _err?: unknown,\n _type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n throw new Error(\n 'Invariant: logErrorWithOriginalStack can only be called on the development server'\n )\n }\n\n // Used in development only, overloaded in next-dev-server\n protected async ensurePage(_opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray | null\n match?: RouteMatch\n url?: string\n }): Promise {\n throw new Error(\n 'Invariant: ensurePage can only be called on the development server'\n )\n }\n\n /**\n * Resolves `API` request, in development builds on demand\n * @param req http request\n * @param res http response\n * @param pathname path of request\n */\n protected async handleApiRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n query: ParsedUrlQuery,\n match: PagesAPIRouteMatch\n ): Promise {\n return this.runApi(req, res, query, match)\n }\n\n protected getCacheFilesystem(): CacheFs {\n return nodeFs\n }\n\n protected normalizeReq(\n req: NodeNextRequest | IncomingMessage\n ): NodeNextRequest {\n return !(req instanceof NodeNextRequest) ? new NodeNextRequest(req) : req\n }\n\n protected normalizeRes(\n res: NodeNextResponse | ServerResponse\n ): NodeNextResponse {\n return !(res instanceof NodeNextResponse) ? new NodeNextResponse(res) : res\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = this.makeRequestHandler()\n if (this.serverOptions.experimentalTestProxy) {\n const { wrapRequestHandlerNode } =\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 return wrapRequestHandlerNode(handler)\n }\n return handler\n }\n\n /**\n * @internal - this method is internal to Next.js and should not be used directly by end-users\n */\n public getRequestHandlerWithMetadata(meta: RequestMeta): NodeRequestHandler {\n const handler = this.makeRequestHandler()\n return (req, res, parsedUrl) => {\n setRequestMeta(req, meta)\n return handler(req, res, parsedUrl)\n }\n }\n\n private makeRequestHandler(): NodeRequestHandler {\n // This is just optimization to fire prepare as soon as possible. It will be\n // properly awaited later. We add the catch here to ensure that it does not\n // cause an unhandled promise rejection. The promise rejection will be\n // handled later on via the `await` when the request handler is called.\n this.prepare().catch((err) => {\n console.error('Failed to prepare server', err)\n })\n\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) =>\n handler(this.normalizeReq(req), this.normalizeRes(res), parsedUrl)\n }\n\n public async revalidate({\n urlPath,\n headers,\n opts,\n }: {\n urlPath: string\n headers: { [key: string]: string | string[] }\n opts: { unstable_onlyGenerated?: boolean }\n }) {\n const mocked = createRequestResponseMocks({\n url: urlPath,\n headers,\n })\n\n const handler = this.getRequestHandler()\n await handler(\n new NodeNextRequest(mocked.req),\n new NodeNextResponse(mocked.res)\n )\n await mocked.res.hasStreamed\n\n if (\n mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&\n mocked.res.statusCode !== 200 &&\n !(mocked.res.statusCode === 404 && opts.unstable_onlyGenerated)\n ) {\n throw new Error(`Invalid response ${mocked.res.statusCode}`)\n }\n }\n\n public async render(\n req: NodeNextRequest | IncomingMessage,\n res: NodeNextResponse | ServerResponse,\n pathname: string,\n query?: NextParsedUrlQuery,\n parsedUrl?: NextUrlWithParsedQuery,\n internal = false\n ): Promise {\n return super.render(\n this.normalizeReq(req),\n this.normalizeRes(res),\n pathname,\n query,\n parsedUrl,\n internal\n )\n }\n\n public async renderToHTML(\n req: NodeNextRequest | IncomingMessage,\n res: NodeNextResponse | ServerResponse,\n pathname: string,\n query?: ParsedUrlQuery\n ): Promise {\n const normalizedRes = this.normalizeRes(res)\n const normalizedReq = this.normalizeReq(req)\n normalizedReq.url = formatUrl({\n pathname,\n query,\n })\n\n if (this.dev) {\n await this.ensurePage({\n page: pathname,\n clientOnly: false,\n url: normalizedReq.url,\n })\n }\n\n // renderToHTML returns the body to legacy custom servers. Route modules\n // write to the response, so capture their output instead of sending it.\n const mockedRes = new MockedResponse({\n headers: normalizedRes.getHeaders(),\n statusCode: normalizedRes.statusCode,\n socket: normalizedRes.originalResponse.socket,\n })\n\n const result = await super.renderToHTML(\n normalizedReq,\n this.normalizeRes(mockedRes),\n pathname,\n query\n )\n\n if (result === null && mockedRes.isSent) {\n await mockedRes.hasStreamed\n }\n\n const mockedHeaders = mockedRes.getHeaders()\n for (const key in mockedHeaders) {\n const value = mockedHeaders[key]\n if (value !== undefined) {\n normalizedRes.setHeader(\n key,\n Array.isArray(value) ? value.map(String) : String(value)\n )\n }\n }\n normalizedRes.statusCode = mockedRes.statusCode\n\n if (result !== null) {\n return result\n }\n if (mockedRes.buffers.length > 0) {\n return Buffer.concat(mockedRes.buffers).toString('utf8')\n }\n return null\n }\n\n protected async renderErrorToResponseImpl(\n ctx: RequestContext,\n err: Error | null\n ) {\n const { req, res, query } = ctx\n const is404 = res.statusCode === 404\n\n if (is404 && this.enabledDirectories.app) {\n if (this.dev) {\n await this.ensurePage({\n page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n clientOnly: false,\n url: req.url,\n }).catch(() => {})\n }\n\n if (\n this.getEdgeFunctionsPages().includes(UNDERSCORE_NOT_FOUND_ROUTE_ENTRY)\n ) {\n await this.runEdgeFunction({\n req,\n res,\n query: query || {},\n params: {},\n page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n appPaths: null,\n })\n return null\n }\n }\n return super.renderErrorToResponseImpl(ctx, err)\n }\n\n public async renderError(\n err: Error | null,\n req: NodeNextRequest | IncomingMessage,\n res: NodeNextResponse | ServerResponse,\n pathname: string,\n query?: NextParsedUrlQuery,\n setHeaders?: boolean\n ): Promise {\n return super.renderError(\n err,\n this.normalizeReq(req),\n this.normalizeRes(res),\n pathname,\n query,\n setHeaders\n )\n }\n\n public async renderErrorToHTML(\n err: Error | null,\n req: NodeNextRequest | IncomingMessage,\n res: NodeNextResponse | ServerResponse,\n pathname: string,\n query?: ParsedUrlQuery\n ): Promise {\n return super.renderErrorToHTML(\n err,\n this.normalizeReq(req),\n this.normalizeRes(res),\n pathname,\n query\n )\n }\n\n public async render404(\n req: NodeNextRequest | IncomingMessage,\n res: NodeNextResponse | ServerResponse,\n parsedUrl?: NextUrlWithParsedQuery,\n setHeaders?: boolean\n ): Promise {\n return super.render404(\n this.normalizeReq(req),\n this.normalizeRes(res),\n parsedUrl,\n setHeaders\n )\n }\n\n protected getMiddlewareManifest(): MiddlewareManifest | null {\n if (this.minimalMode) {\n return null\n } else {\n const manifest: MiddlewareManifest = require(this.middlewareManifestPath)\n return manifest\n }\n }\n\n /** Returns the middleware routing item if there is one. */\n protected async getMiddleware(): Promise {\n const manifest = this.getMiddlewareManifest()\n const middleware = manifest?.middleware?.['/']\n if (!middleware) {\n const middlewareModule = await this.loadNodeMiddleware()\n\n if (middlewareModule) {\n return {\n match: getMiddlewareRouteMatcher(\n middlewareModule.config?.matchers || [\n { regexp: '.*', originalSource: '/:path*' },\n ]\n ),\n page: '/',\n }\n }\n\n return\n }\n\n return {\n match: getMiddlewareMatcher(middleware),\n page: '/',\n }\n }\n\n protected getEdgeFunctionsPages(): string[] {\n const manifest = this.getMiddlewareManifest()\n if (!manifest) {\n return []\n }\n\n return Object.keys(manifest.functions)\n }\n\n /**\n * Get information for the edge function located in the provided page\n * folder. If the edge function info can't be found it will throw\n * an error.\n */\n protected getEdgeFunctionInfo(params: {\n page: string\n /** Whether we should look for a middleware or not */\n middleware: boolean\n }): {\n name: string\n paths: string[]\n wasm: { filePath: string; name: string }[]\n env: { [key: string]: string }\n assets?: { filePath: string; name: string }[]\n } | null {\n const manifest = this.getMiddlewareManifest()\n if (!manifest) {\n return null\n }\n\n let foundPage: string\n\n try {\n foundPage = denormalizePagePath(normalizePagePath(params.page))\n } catch (err) {\n return null\n }\n\n let pageInfo = params.middleware\n ? manifest.middleware[foundPage]\n : manifest.functions[foundPage]\n\n if (!pageInfo) {\n if (!params.middleware) {\n throw new PageNotFoundError(foundPage)\n }\n return null\n }\n\n return {\n name: pageInfo.name,\n paths: pageInfo.files.map((file) =>\n join(/* turbopackIgnore: true */ this.distDir, file)\n ),\n wasm: (pageInfo.wasm ?? []).map((binding) => ({\n ...binding,\n filePath: join(\n /* turbopackIgnore: true */ this.distDir,\n binding.filePath\n ),\n })),\n assets:\n pageInfo.assets &&\n pageInfo.assets.map((binding) => {\n return {\n ...binding,\n filePath: join(\n /* turbopackIgnore: true */ this.distDir,\n binding.filePath\n ),\n }\n }),\n env: pageInfo.env,\n }\n }\n\n private async loadNodeMiddleware() {\n if (!process.env.NEXT_MINIMAL) {\n try {\n const functionsConfig = this.dev\n ? {}\n : require(\n join(\n /* turbopackIgnore: true */ this.distDir,\n 'server',\n FUNCTIONS_CONFIG_MANIFEST\n )\n )\n\n if (this.dev || functionsConfig?.functions?.['/_middleware']) {\n // if used with top level await, this will be a promise\n return require(\n join(\n /* turbopackIgnore: true */ this.distDir,\n 'server',\n 'middleware.js'\n )\n )\n }\n } catch (err) {\n if (\n isError(err) &&\n err.code !== 'ENOENT' &&\n err.code !== 'MODULE_NOT_FOUND'\n ) {\n throw err\n }\n }\n }\n }\n\n /**\n * Checks if a middleware exists. This method is useful for the development\n * server where we need to check the filesystem. Here we just check the\n * middleware manifest.\n */\n protected async hasMiddleware(pathname: string): Promise {\n const info = this.getEdgeFunctionInfo({ page: pathname, middleware: true })\n const nodeMiddleware = await this.loadNodeMiddleware()\n\n if (!info && nodeMiddleware) {\n return true\n }\n return Boolean(info && info.paths.length > 0)\n }\n\n /**\n * A placeholder for a function to be defined in the development server.\n * It will make sure that the root middleware or an edge function has been compiled\n * so that we can run it.\n */\n protected async ensureMiddleware(_url?: string) {}\n protected async ensureEdgeFunction(_params: {\n page: string\n appPaths: string[] | null\n url?: string\n }) {}\n\n /**\n * This method gets all middleware matchers and execute them when the request\n * matches. It will make sure that each middleware exists and is compiled and\n * ready to be invoked. The development server will decorate it to add warns\n * and errors with rich traces.\n */\n protected async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: NextUrlWithParsedQuery\n onWarning?: (warning: Error) => void\n }) {\n if (process.env.NEXT_MINIMAL) {\n throw new Error(\n 'invariant: runMiddleware should not be called in minimal mode'\n )\n }\n\n // Middleware is skipped for on-demand revalidate requests\n if (\n checkIsOnDemandRevalidate(\n params.request.headers,\n this.renderOpts.previewProps\n ).isOnDemandRevalidate\n ) {\n return {\n response: new Response(null, { headers: { 'x-middleware-next': '1' } }),\n } as FetchEventResult\n }\n\n let url: string\n\n if (this.nextConfig.skipProxyUrlNormalize) {\n url = getRequestMeta(params.request, 'initURL')!\n } else {\n // For middleware to \"fetch\" we must always provide an absolute URL\n const query = urlQueryToSearchParams(params.parsed.query).toString()\n const locale = getRequestMeta(params.request, 'locale')\n\n url = `${getRequestMeta(params.request, 'initProtocol')}://${\n this.fetchHostname || 'localhost'\n }:${this.port}${locale ? `/${locale}` : ''}${params.parsed.pathname}${\n query ? `?${query}` : ''\n }`\n }\n\n if (!url.startsWith('http')) {\n throw new Error(\n 'To use middleware you must provide a `hostname` and `port` to the Next.js Server'\n )\n }\n\n const page: {\n name?: string\n params?: { [key: string]: string | string[] }\n } = {}\n\n const middleware = await this.getMiddleware()\n if (!middleware) {\n return { finished: false }\n }\n if (!(await this.hasMiddleware(middleware.page))) {\n return { finished: false }\n }\n\n await this.ensureMiddleware(params.request.url)\n const middlewareInfo = this.getEdgeFunctionInfo({\n page: middleware.page,\n middleware: true,\n })\n\n const method = (params.request.method || 'GET').toUpperCase()\n const requestData = {\n headers: params.request.headers,\n method,\n nextConfig: {\n basePath: this.nextConfig.basePath,\n i18n: this.nextConfig.i18n,\n trailingSlash: this.nextConfig.trailingSlash,\n experimental: this.nextConfig.experimental,\n },\n url: url,\n page,\n body:\n method !== 'GET' && method !== 'HEAD'\n ? (getRequestMeta(params.request, 'clonableBody') as any)\n : undefined,\n\n signal: signalFromNodeResponse(params.response.originalResponse),\n waitUntil: this.getWaitUntil(),\n }\n let result:\n | UnwrapPromise>\n | undefined\n\n // if no middleware info check for Node.js middleware\n // this is not in the middleware-manifest as that historically\n // has only included edge-functions, we need to do a breaking\n // version bump for that manifest to write this info there if\n // we decide we want to\n if (!middlewareInfo) {\n let middlewareModule\n middlewareModule = await this.loadNodeMiddleware()\n\n if (!middlewareModule) {\n throw new MiddlewareNotFoundError()\n }\n const adapterFn: typeof import('./web/adapter').adapter =\n middlewareModule.default || middlewareModule\n\n const hasRequestBody =\n !['HEAD', 'GET'].includes(params.request.method) &&\n Boolean(requestData.body)\n\n try {\n // Node.js middleware runs in-process, inside the active\n // `handleRequest` span. Detach that span so the middleware span\n // becomes a sibling root (or parents to an incoming traceparent),\n // matching edge middleware which runs in a detached sandbox.\n result = await getTracer().runWithDetachedContext(() =>\n adapterFn({\n handler:\n middlewareModule.proxy ||\n middlewareModule.middleware ||\n middlewareModule,\n request: {\n ...requestData,\n body: hasRequestBody\n ? requestData.body.cloneBodyStream()\n : undefined,\n },\n page: 'middleware',\n })\n )\n } finally {\n if (hasRequestBody) {\n await requestData.body.finalize()\n }\n }\n } else {\n const { run } = require('./web/sandbox') as typeof import('./web/sandbox')\n\n result = await run({\n distDir: this.distDir,\n name: middlewareInfo.name,\n paths: middlewareInfo.paths,\n edgeFunctionEntry: middlewareInfo,\n request: requestData,\n useCache: true,\n onWarning: params.onWarning,\n clientAssetToken: this.nextConfig.supportsImmutableAssets\n ? ''\n : this.deploymentId,\n })\n }\n\n if (!this.dev) {\n result.waitUntil.catch((error) => {\n console.error(`Uncaught: middleware waitUntil errored`, error)\n })\n }\n\n if (!result) {\n this.render404(params.request, params.response, params.parsed)\n return { finished: true }\n }\n\n // Split compound (comma-separated) set-cookie headers\n if (result.response.headers.has('set-cookie')) {\n const cookies = result.response.headers\n .getSetCookie()\n .flatMap((maybeCompoundCookie) =>\n splitCookiesString(maybeCompoundCookie)\n )\n\n // Clear existing header(s)\n result.response.headers.delete('set-cookie')\n\n // Append each cookie individually.\n for (const cookie of cookies) {\n result.response.headers.append('set-cookie', cookie)\n }\n\n // Add cookies to request meta.\n addRequestMeta(params.request, 'middlewareCookie', cookies)\n }\n\n return result\n }\n\n protected handleCatchallMiddlewareRequest: NodeRouteHandler = async (\n req,\n res,\n parsed\n ) => {\n const isMiddlewareInvoke = getRequestMeta(req, 'middlewareInvoke')\n\n if (!isMiddlewareInvoke) {\n return false\n }\n\n const handleFinished = () => {\n addRequestMeta(req, 'middlewareInvoke', true)\n res.body('').send()\n return true\n }\n\n const middleware = await this.getMiddleware()\n if (!middleware) {\n return handleFinished()\n }\n\n const initUrl = getRequestMeta(req, 'initURL')!\n const parsedUrl = parseUrl(initUrl)\n const pathnameInfo = getNextPathnameInfo(parsedUrl.pathname, {\n nextConfig: this.nextConfig,\n i18nProvider: this.i18nProvider,\n })\n\n parsedUrl.pathname = pathnameInfo.pathname\n const normalizedPathname = removeTrailingSlash(parsed.pathname || '')\n let maybeDecodedPathname = normalizedPathname\n\n try {\n maybeDecodedPathname = decodeURIComponent(normalizedPathname)\n } catch {\n /* non-fatal we can't decode so can't match it */\n }\n\n if (\n !(\n middleware.match(normalizedPathname, req, parsedUrl.query) ||\n middleware.match(maybeDecodedPathname, req, parsedUrl.query)\n )\n ) {\n return handleFinished()\n }\n\n let result: Awaited<\n ReturnType\n >\n let bubblingResult = false\n\n try {\n await this.ensureMiddleware(req.url)\n\n result = await this.runMiddleware({\n request: req,\n response: res,\n parsedUrl: parsedUrl,\n parsed: parsed,\n })\n\n if ('response' in result) {\n if (isMiddlewareInvoke) {\n bubblingResult = true\n throw new BubbledError(true, result)\n }\n\n for (const [key, value] of Object.entries(\n toNodeOutgoingHttpHeaders(result.response.headers)\n )) {\n if (key !== 'content-encoding' && value !== undefined) {\n res.setHeader(key, value as string | string[])\n }\n }\n res.statusCode = result.response.status\n\n const { originalResponse } = res\n if (result.response.body) {\n await pipeToNodeResponse(result.response.body, originalResponse)\n } else {\n originalResponse.end()\n }\n return true\n }\n } catch (err: unknown) {\n if (bubblingResult) {\n throw err\n }\n\n if (isError(err) && err.code === 'ENOENT') {\n await this.render404(req, res, parsed)\n return true\n }\n\n if (err instanceof DecodeError) {\n res.statusCode = 400\n await this.renderError(err, req, res, parsed.pathname || '')\n return true\n }\n\n const error = getProperError(err)\n console.error(error)\n res.statusCode = 500\n await this.renderError(error, req, res, parsed.pathname || '')\n return true\n }\n\n return result.finished\n }\n\n private _cachedPrerenderManifest: DeepReadonly | undefined\n protected getPrerenderManifest(): DeepReadonly {\n if (this._cachedPrerenderManifest) {\n return this._cachedPrerenderManifest\n }\n\n this._cachedPrerenderManifest = loadManifest(\n join(/* turbopackIgnore: true */ this.distDir, PRERENDER_MANIFEST)\n )\n\n return this._cachedPrerenderManifest\n }\n\n private _cachedPreviewPropsManifest: PreviewPropsManifest | undefined\n protected getPreviewProps(): PreviewPropsManifest {\n if (this._cachedPreviewPropsManifest) {\n return this._cachedPreviewPropsManifest\n }\n\n this._cachedPreviewPropsManifest = loadManifest(\n join(\n /* turbopackIgnore: true */ this.distDir,\n 'server',\n PREVIEW_PROPS_MANIFEST\n )\n ) as PreviewPropsManifest\n\n return this._cachedPreviewPropsManifest\n }\n\n private _cachedPrefetchHints: Record | undefined\n protected getPrefetchHints(): Record {\n if (this._cachedPrefetchHints) {\n return this._cachedPrefetchHints\n }\n\n this._cachedPrefetchHints =\n loadManifest>(\n join(\n /* turbopackIgnore: true */ this.distDir,\n SERVER_DIRECTORY,\n PREFETCH_HINTS\n ),\n true,\n undefined,\n false,\n true // handleMissing: don't crash if the file doesn't exist\n ) ?? {}\n\n return this._cachedPrefetchHints\n }\n\n protected getRoutesManifest(): NormalizedRouteManifest | undefined {\n return getTracer().trace(\n NextNodeServerSpan.getRoutesManifest,\n () =>\n loadManifest(\n join(/* turbopackIgnore: true */ this.distDir, ROUTES_MANIFEST)\n ) as RoutesManifest\n )\n }\n\n protected attachRequestMeta(\n req: NodeNextRequest,\n parsedUrl: NextUrlWithParsedQuery,\n isUpgradeReq?: boolean\n ) {\n // Injected in base-server.ts\n const protocol = req.headers['x-forwarded-proto']?.includes('https')\n ? 'https'\n : 'http'\n\n // When there are hostname and port we build an absolute URL\n const initUrl =\n this.fetchHostname && this.port\n ? `${protocol}://${this.fetchHostname}:${this.port}${req.url}`\n : this.nextConfig.experimental.trustHostHeader\n ? `https://${req.headers.host || 'localhost'}${req.url}`\n : req.url\n\n addRequestMeta(req, 'initURL', initUrl)\n addRequestMeta(req, 'initQuery', { ...parsedUrl.query })\n addRequestMeta(req, 'initProtocol', protocol)\n\n if (!isUpgradeReq) {\n const bodySizeLimit = this.nextConfig.experimental\n ?.proxyClientMaxBodySize as number | undefined\n addRequestMeta(\n req,\n 'clonableBody',\n getCloneableBody(req.originalRequest, bodySizeLimit)\n )\n }\n }\n\n protected async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n match?: RouteMatch\n onError?: (err: unknown) => void\n onWarning?: (warning: Error) => void\n }): Promise {\n if (process.env.NEXT_MINIMAL) {\n throw new Error(\n 'Middleware is not supported in minimal mode. Please remove the `NEXT_MINIMAL` environment variable.'\n )\n }\n let edgeInfo: ReturnType | undefined\n\n const { query, page, match } = params\n\n if (!match)\n await this.ensureEdgeFunction({\n page,\n appPaths: params.appPaths,\n url: params.req.url,\n })\n edgeInfo = this.getEdgeFunctionInfo({\n page,\n middleware: false,\n })\n\n if (!edgeInfo) {\n return null\n }\n\n // For edge to \"fetch\" we must always provide an absolute URL\n const isNextDataRequest = getRequestMeta(params.req, 'isNextDataReq')\n const initialUrl = new URL(\n getRequestMeta(params.req, 'initURL') || '/',\n 'http://n'\n )\n const queryString = urlQueryToSearchParams({\n ...Object.fromEntries(initialUrl.searchParams),\n ...query,\n ...params.params,\n }).toString()\n\n if (isNextDataRequest) {\n params.req.headers['x-nextjs-data'] = '1'\n }\n initialUrl.search = queryString\n const url = initialUrl.toString()\n\n if (!url.startsWith('http')) {\n throw new Error(\n 'To use middleware you must provide a `hostname` and `port` to the Next.js Server'\n )\n }\n\n const { run } = require('./web/sandbox') as typeof import('./web/sandbox')\n const result = await run({\n distDir: this.distDir,\n name: edgeInfo.name,\n paths: edgeInfo.paths,\n edgeFunctionEntry: edgeInfo,\n request: {\n headers: params.req.headers,\n method: params.req.method,\n nextConfig: {\n basePath: this.nextConfig.basePath,\n i18n: this.nextConfig.i18n,\n trailingSlash: this.nextConfig.trailingSlash,\n },\n url,\n page: {\n name: params.page,\n ...(params.params && { params: params.params }),\n },\n body: getRequestMeta(params.req, 'clonableBody'),\n signal: signalFromNodeResponse(params.res.originalResponse),\n waitUntil: this.getWaitUntil(),\n },\n useCache: true,\n onError: params.onError,\n onWarning: params.onWarning,\n incrementalCache:\n (globalThis as any).__incrementalCache ||\n getRequestMeta(params.req, 'incrementalCache'),\n serverComponentsHmrCache: getRequestMeta(\n params.req,\n 'serverComponentsHmrCache'\n ),\n clientAssetToken: this.nextConfig.supportsImmutableAssets\n ? ''\n : this.deploymentId,\n })\n\n if (result.fetchMetrics) {\n params.req.fetchMetrics = result.fetchMetrics\n }\n\n if (!params.res.statusCode || params.res.statusCode < 400) {\n params.res.statusCode = result.response.status\n params.res.statusMessage = result.response.statusText\n }\n\n // TODO: (wyattjoh) investigate improving this\n\n result.response.headers.forEach((value, key) => {\n // The append handling is special cased for `set-cookie`.\n if (key.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of splitCookiesString(value)) {\n params.res.appendHeader(key, cookie)\n }\n } else {\n params.res.appendHeader(key, value)\n }\n })\n\n const { originalResponse } = params.res\n if (result.response.body) {\n await pipeToNodeResponse(result.response.body, originalResponse)\n } else {\n originalResponse.end()\n }\n\n return result\n }\n\n protected get serverDistDir(): string {\n if (this._serverDistDir) {\n return this._serverDistDir\n }\n const serverDistDir = join(\n /* turbopackIgnore: true */ this.distDir,\n SERVER_DIRECTORY\n )\n this._serverDistDir = serverDistDir\n return serverDistDir\n }\n\n protected async getFallbackErrorComponents(\n _url?: string\n ): Promise | null> {\n // Not implemented for production use cases, this is implemented on the\n // development server.\n return null\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters\n ) {\n await super.instrumentationOnRequestError(...args)\n\n // For Node.js runtime production logs, in dev it will be overridden by next-dev-server\n if (!this.dev) {\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logError(err)\n }\n }\n }\n\n protected onServerClose(listener: () => Promise) {\n this.cleanupListeners.add(listener)\n }\n\n async close(): Promise {\n await this.cleanupListeners.runAll()\n }\n\n protected getInternalWaitUntil(): WaitUntil {\n this.internalWaitUntil ??= this.createInternalWaitUntil()\n return this.internalWaitUntil\n }\n\n private createInternalWaitUntil() {\n if (this.minimalMode) {\n throw new InvariantError(\n 'createInternalWaitUntil should never be called in minimal mode'\n )\n }\n\n const awaiter = new AwaiterOnce({ onError: console.error })\n\n // TODO(after): warn if the process exits before these are awaited\n this.onServerClose(() => awaiter.awaiting())\n\n return awaiter.waitUntil\n }\n}\n"],"names":["NextNodeServer","dynamicImportEsmDefault","process","env","NEXT_MINIMAL","id","then","mod","default","MiddlewareMatcherCache","WeakMap","getMiddlewareMatcher","info","stored","get","Array","isArray","matchers","Error","JSON","stringify","matcher","getMiddlewareRouteMatcher","set","BaseServer","constructor","options","cleanupListeners","AsyncCallbackSet","handleNextImageRequest","req","res","parsedUrl","pathname","startsWith","getRequestMeta","minimalMode","nextConfig","output","statusCode","body","send","ImageOptimizerCache","require","imageCacheHandler","images","customCacheHandler","cacheHandler","CacheHandler","interopDefault","formatDynamicImportPath","distDir","dev","flushToDisk","experimental","isrFlushToDisk","serverDistDir","maxMemoryCacheSize","cacheMaxMemorySize","revalidatedTags","_requestHeaders","imageOptimizerCache","sendResponse","ImageError","imageResponseCache","imagesConfig","loader","unoptimized","render404","paramsResult","validateParams","originalRequest","query","errorMessage","cacheKey","getCacheKey","cacheEntry","getExtension","previousCacheEntry","buffer","contentType","maxAge","upstreamEtag","etag","imageOptimizer","value","kind","CachedRouteKind","IMAGE","extension","cacheControl","revalidate","expire","undefined","routeKind","RouteKind","incrementalCache","isFallback","error","originalResponse","href","isStatic","isMiss","isStale","Boolean","err","message","handleCatchallRenderRequest","addRequestMeta","routerServerGlobal","RouterServerContextSymbol","relativeProjectDir","relative","cwd","dir","existingServerContext","bind","getAssetPrefix","isWrappedByNextServer","removeTrailingSlash","match","localeAnalysisResult","i18nProvider","analyze","defaultLocale","routeMatch","getRouteMatch","render","edgeFunctionsPages","getEdgeFunctionsPages","edgeFunctionsPage","definition","page","NEXT_RSC_UNION_QUERY","handled","runEdgeFunction","params","appPaths","apiError","silenceLog","instrumentationOnRequestError","routePath","routerKind","routeType","revalidateReason","isPagesAPIRouteMatch","handleApiRequest","NoFallbackError","formatServerError","logErrorWithOriginalStack","logError","renderError","handleCatchallMiddlewareRequest","parsed","isMiddlewareInvoke","handleFinished","middleware","getMiddleware","initUrl","parseUrl","pathnameInfo","getNextPathnameInfo","normalizedPathname","maybeDecodedPathname","decodeURIComponent","result","bubblingResult","ensureMiddleware","url","runMiddleware","request","response","BubbledError","key","Object","entries","toNodeOutgoingHttpHeaders","headers","setHeader","status","pipeToNodeResponse","end","isError","code","DecodeError","getProperError","console","finished","installGlobalBehaviors","renderOpts","prefetchHints","getPrefetchHints","isDev","sriEnabled","conf","sri","algorithm","optimizeCss","__NEXT_OPTIMIZE_CSS","nextScriptWorkers","__NEXT_SCRIPT_WORKERS","__NEXT_DEV_SERVER","requestInsights","__NEXT_REQUEST_INSIGHTS","ResponseCache","route","preloadEntriesOnStart","unstable_preloadEntries","catch","Log","dynamicRoutes","getRoutesManifest","map","r","regex","getRouteRegex","getRouteMatcher","re","setHttpClientAndAgentOptions","serverOptions","experimentalTestProxy","NEXT_PRIVATE_TEST_PROXY","interceptTestApis","middlewareManifestPath","join","MIDDLEWARE_MANIFEST","prepare","isExperimentalCompile","populateStaticEnv","deploymentId","shouldRemoveUncaughtErrorAndRejectionListeners","removeUncaughtErrorAndRejectionListeners","installProcessErrorHandlers","appPathsManifest","getAppPathsManifest","pagesManifest","getPagesManifest","loadCustomCacheHandlers","keys","loadComponents","isAppPath","needsManifestsForLegacyReasons","_err","ComponentMod","patchFetch","handleUpgrade","loadInstrumentationModule","instrumentation","getInstrumentationModule","cause","prepareImpl","runInstrumentationHookIfAvailable","ensureInstrumentationRegistered","loadEnvConfig","forceReload","envFilePath","cacheHandlers","initializeCacheHandlers","registerCustomCacheHandlers","handler","setCacheHandler","getIncrementalCache","requestHeaders","IncrementalCache","fs","getCacheFilesystem","allowedRevalidateHeaderKeys","fetchCacheKeyPrefix","previewProps","getPreviewProps","prerenderManifest","getPrerenderManifest","locales","i18n","CurCacheHandler","getPublicDir","CLIENT_PUBLIC_FILES_PATH","getHasStaticDir","existsSync","loadManifest","PAGES_MANIFEST","enabledDirectories","app","APP_PATHS_MANIFEST","getinterceptionRoutePatterns","routesManifest","rewrites","beforeFiles","filter","isInterceptionRouteRewrite","rewrite","RegExp","hasPage","getMaybePagePath","getBuildId","buildIdFile","BUILD_ID_FILE","readFileSync","trim","getEnabledDirectories","findDir","pages","sendRenderResult","generateEtags","poweredByHeader","runApi","handledAsEdgeFunction","parsedInitUrl","search","NodeModuleLoader","modulePath","bundlePath","filename","module","load","waitUntil","getWaitUntil","requestMeta","renderHTML","getTracer","trace","NextNodeServerSpan","renderHTMLImpl","nextFontManifest","renderAppPage","supportsDynamicResponse","isDraftMode","isPossibleServerAction","lazyPrerenderAppPage","lazyRenderAppPage","createDevRenderContext","getServerComponentsHmrCache","parsedRequestHeaders","parseRequestHeaders","isRoutePPREnabled","previewModeId","buildId","clientAssetToken","supportsImmutableAssets","lazyRenderPagesPage","customServer","developmentNotFoundSourcePage","fetchExternalImage","fetchInternalImage","handleInternalReq","newReq","newRes","routerServerHandler","__NEXT_TEST_MODE","IS_TURBOPACK_TEST","isAbsolute","dpl","URL","searchParams","includes","imageUpstream","dangerouslyAllowLocalIP","maximumResponseBody","maximumRedirects","getPagePath","renderPageComponent","ctx","bubbleNoFallback","length","getOriginalAppPaths","selectAppPageEntry","findPageComponents","locale","spanName","attributes","normalizeAppPath","findPageComponentsImpl","_url","pagePaths","unshift","path","pagePath","components","Component","getStaticProps","PageNotFoundError","getNextFontManifest","NEXT_FONT_MANIFEST","_type","ensurePage","_opts","nodeFs","normalizeReq","NodeNextRequest","normalizeRes","NodeNextResponse","getRequestHandler","makeRequestHandler","wrapRequestHandlerNode","getRequestHandlerWithMetadata","meta","setRequestMeta","urlPath","opts","mocked","createRequestResponseMocks","hasStreamed","getHeader","unstable_onlyGenerated","internal","renderToHTML","normalizedRes","normalizedReq","formatUrl","clientOnly","mockedRes","MockedResponse","getHeaders","socket","isSent","mockedHeaders","String","buffers","Buffer","concat","toString","renderErrorToResponseImpl","is404","UNDERSCORE_NOT_FOUND_ROUTE_ENTRY","setHeaders","renderErrorToHTML","getMiddlewareManifest","manifest","middlewareModule","loadNodeMiddleware","config","regexp","originalSource","functions","getEdgeFunctionInfo","foundPage","denormalizePagePath","normalizePagePath","pageInfo","name","paths","files","file","wasm","binding","filePath","assets","functionsConfig","FUNCTIONS_CONFIG_MANIFEST","hasMiddleware","nodeMiddleware","ensureEdgeFunction","_params","checkIsOnDemandRevalidate","isOnDemandRevalidate","Response","skipProxyUrlNormalize","urlQueryToSearchParams","fetchHostname","port","middlewareInfo","method","toUpperCase","requestData","basePath","trailingSlash","signal","signalFromNodeResponse","MiddlewareNotFoundError","adapterFn","hasRequestBody","runWithDetachedContext","proxy","cloneBodyStream","finalize","run","edgeFunctionEntry","useCache","onWarning","has","cookies","getSetCookie","flatMap","maybeCompoundCookie","splitCookiesString","delete","cookie","append","_cachedPrerenderManifest","PRERENDER_MANIFEST","_cachedPreviewPropsManifest","PREVIEW_PROPS_MANIFEST","_cachedPrefetchHints","SERVER_DIRECTORY","PREFETCH_HINTS","ROUTES_MANIFEST","attachRequestMeta","isUpgradeReq","protocol","trustHostHeader","host","bodySizeLimit","proxyClientMaxBodySize","getCloneableBody","edgeInfo","isNextDataRequest","initialUrl","queryString","fromEntries","onError","globalThis","__incrementalCache","serverComponentsHmrCache","fetchMetrics","statusMessage","statusText","forEach","toLowerCase","appendHeader","_serverDistDir","getFallbackErrorComponents","args","onServerClose","listener","add","close","runAll","getInternalWaitUntil","internalWaitUntil","createInternalWaitUntil","InvariantError","awaiter","AwaiterOnce","awaiting"],"mappings":";;;;+BAqMA;;;eAAqBA;;;;QArMd;QACA;QACA;uBAOA;kCAsBgC;2DAWxB;sBACgB;qBACK;8BACJ;6BAC+B;2BAexD;8BACiB;sBAC0B;6BACjB;0BACR;6DACJ;gFAaE;yBACuB;qCACV;mCACF;0BACC;gCACJ;iEAES;wBACsB;wCACpB;qBACZ;6BACS;qCACH;qCACA;6BACH;0BACS;uEAInC;kCAIA;mCAGsC;oCAER;wBAEG;4BACL;+BACZ;4BACO;8BACK;6BACwB;kCACtB;6BACE;sCACV;8BAItB;qCAIA;+BAC6B;gCACL;yCACS;4CAEG;2BAGjB;gCACK;yBACH;kCACK;0BAK1B;2BAE2B;kCACD;yCACD;gDAIzB;qCAIA;iCACgC;sCACK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAK5C,yCAAyC;AACzC,MA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ACD,iBAAiB;IAC/B;IAEQC,0BAA0B;QAChC,IAAI,IAAI,CAAC7e,WAAW,EAAE;YACpB,MAAM,IAAI8e,8BAAc,CACtB;QAEJ;QAEA,MAAMC,UAAU,IAAIC,oBAAW,CAAC;YAAEvB,SAASnU,QAAQxF,KAAK;QAAC;QAEzD,kEAAkE;QAClE,IAAI,CAACwa,aAAa,CAAC,IAAMS,QAAQE,QAAQ;QAEzC,OAAOF,QAAQxN,SAAS;IAC1B;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/next-typescript.d.ts b/e-commerce/node_modules/next/dist/server/next-typescript.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a1b2711f90f49415b869973b4f1759e0293a963a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/next-typescript.d.ts @@ -0,0 +1 @@ +export { createTSPlugin } from './typescript'; diff --git a/e-commerce/node_modules/next/dist/server/next-typescript.js b/e-commerce/node_modules/next/dist/server/next-typescript.js new file mode 100644 index 0000000000000000000000000000000000000000..c9949554b9e5c0d6083b311c371db2cb0b6e258b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/next-typescript.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "createTSPlugin", { + enumerable: true, + get: function() { + return _typescript.createTSPlugin; + } +}); +const _typescript = require("./typescript"); + +//# sourceMappingURL=next-typescript.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/next-typescript.js.map b/e-commerce/node_modules/next/dist/server/next-typescript.js.map new file mode 100644 index 0000000000000000000000000000000000000000..754f632db1e2b93b237b4985157b97e462f47e2f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/next-typescript.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/next-typescript.ts"],"sourcesContent":["export { createTSPlugin } from './typescript'\n"],"names":["createTSPlugin"],"mappings":";;;;+BAASA;;;eAAAA,0BAAc;;;4BAAQ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/next.d.ts b/e-commerce/node_modules/next/dist/server/next.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad1e2ef0e1a6318bb56c76dc42c900b9fa34daca --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/next.d.ts @@ -0,0 +1,90 @@ +import type { Options as DevServerOptions } from './dev/next-dev-server'; +import type { Options as ServerOptions } from './next-server'; +import type { IncomingMessage, ServerResponse } from 'http'; +import type { Duplex } from 'stream'; +import type { NextUrlWithParsedQuery } from './request-meta'; +import './require-hook'; +import './node-polyfill-crypto'; +import type { default as NextNodeServer } from './next-server'; +import type { ServerFields } from './lib/router-utils/setup-dev-bundler'; +export type NextServerOptions = Omit & Partial>; +export type NextBundlerOptions = { + /** @deprecated Use `turbopack` instead */ + turbo?: boolean; + /** Selects Turbopack as the bundler */ + turbopack?: boolean; + /** Selects Webpack as the bundler */ + webpack?: boolean; +}; +export type RequestHandler = (req: IncomingMessage, res: ServerResponse, parsedUrl?: NextUrlWithParsedQuery | undefined) => Promise; +export type UpgradeHandler = (req: IncomingMessage, socket: Duplex, head: Buffer) => Promise; +declare const SYMBOL_LOAD_CONFIG: unique symbol; +interface NextWrapperServer { + options: NextServerOptions; + hostname: string | undefined; + port: number | undefined; + getRequestHandler(): RequestHandler; + prepare(serverFields?: ServerFields): Promise; + /** @deprecated Configure `assetPrefix` in `next.config.js` instead. */ + setAssetPrefix(assetPrefix: string): void; + close(): Promise; + getUpgradeHandler(): UpgradeHandler; + /** @deprecated Use application logging instead. */ + logError(...args: Parameters): void; + /** @deprecated Use documented application revalidation APIs instead. */ + revalidate(...args: Parameters): ReturnType; + /** @deprecated Use application logging instead. */ + logErrorWithOriginalStack(err: unknown, type: string): void; + /** + * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead. + */ + render(...args: Parameters): ReturnType; + /** + * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead. + */ + renderToHTML(...args: Parameters): ReturnType; + /** + * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead. + */ + renderError(...args: Parameters): ReturnType; + /** + * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead. + */ + renderErrorToHTML(...args: Parameters): ReturnType; + /** + * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead. + */ + render404(...args: Parameters): ReturnType; +} +/** The wrapper server used by `next start` */ +export declare class NextServer implements NextWrapperServer { + private serverPromise?; + private server?; + private reqHandler?; + private reqHandlerPromise?; + private preparedAssetPrefix?; + options: NextServerOptions; + constructor(options: NextServerOptions); + get hostname(): string | undefined; + get port(): number | undefined; + getRequestHandler(): RequestHandler; + getUpgradeHandler(): UpgradeHandler; + setAssetPrefix(assetPrefix: string): void; + getAssetPrefix(): string; + logError(...args: Parameters): void; + logErrorWithOriginalStack(err: unknown, type: string): Promise; + revalidate(...args: Parameters): Promise; + render(...args: Parameters): Promise; + renderToHTML(...args: Parameters): Promise; + renderError(...args: Parameters): Promise; + renderErrorToHTML(...args: Parameters): Promise; + render404(...args: Parameters): Promise; + prepare(serverFields?: ServerFields): Promise; + close(): Promise; + private createServer; + private [SYMBOL_LOAD_CONFIG]; + private getServer; + private getServerRequestHandler; +} +declare function createServer(options: NextServerOptions & NextBundlerOptions): NextWrapperServer; +export default createServer; diff --git a/e-commerce/node_modules/next/dist/server/next.js b/e-commerce/node_modules/next/dist/server/next.js new file mode 100644 index 0000000000000000000000000000000000000000..f6e77c1e4ba0fa60551d26d4dabf80ba61ede43e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/next.js @@ -0,0 +1,473 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + NextServer: null, + default: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + NextServer: function() { + return NextServer; + }, + // exports = module.exports + // Support `import next from 'next'` + default: function() { + return _default; + } +}); +require("./require-hook"); +require("./node-polyfill-crypto"); +const _log = /*#__PURE__*/ _interop_require_wildcard(require("../build/output/log")); +const _config = /*#__PURE__*/ _interop_require_default(require("./config")); +const _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path")); +const _constants = require("../lib/constants"); +const _constants1 = require("../shared/lib/constants"); +const _tracer = require("./lib/trace/tracer"); +const _constants2 = require("./lib/trace/constants"); +const _formaturl = require("../shared/lib/router/utils/format-url"); +const _asynccallbackset = require("./lib/async-callback-set"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +let ServerImpl; +const getServerImpl = async ()=>{ + if (ServerImpl === undefined) { + ServerImpl = (await Promise.resolve(require('./next-server'))).default; + } + return ServerImpl; +}; +const SYMBOL_LOAD_CONFIG = Symbol('next.load_config'); +const DEPRECATED_CUSTOM_SERVER_METHOD_GUIDANCE = { + setAssetPrefix: 'Please configure `assetPrefix` in `next.config.js` instead.', + logError: 'Please use application logging instead.', + logErrorWithOriginalStack: 'Please use application logging instead.', + revalidate: 'Please use documented application revalidation APIs instead.', + render: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', + renderToHTML: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', + renderError: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', + renderErrorToHTML: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', + render404: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.' +}; +function warnDeprecatedCustomServerMethod(method) { + _log.warnOnce(`The \`app.${method}()\` method is deprecated in custom servers. ${DEPRECATED_CUSTOM_SERVER_METHOD_GUIDANCE[method]}`); +} +class NextServer { + constructor(options){ + this.options = options; + } + get hostname() { + return this.options.hostname; + } + get port() { + return this.options.port; + } + getRequestHandler() { + return async (req, res, parsedUrl)=>{ + const tracer = (0, _tracer.getTracer)(); + return tracer.withPropagatedContext(req.headers, ()=>tracer.trace(_constants2.NextServerSpan.getRequestHandler, async ()=>{ + const requestHandler = await this.getServerRequestHandler(); + return requestHandler(req, res, parsedUrl); + })); + }; + } + /** + * @internal - this method is internal to Next.js and should not be used + * directly by end-users, only used in testing + */ getRequestHandlerWithMetadata(meta) { + return async (req, res, parsedUrl)=>{ + const tracer = (0, _tracer.getTracer)(); + return tracer.withPropagatedContext(req.headers, ()=>tracer.trace(_constants2.NextServerSpan.getRequestHandlerWithMetadata, async ()=>{ + const server = await this.getServer(); + const handler = server.getRequestHandlerWithMetadata(meta); + return handler(req, res, parsedUrl); + })); + }; + } + getUpgradeHandler() { + return async (req, socket, head)=>{ + const server = await this.getServer(); + // @ts-expect-error we mark this as protected so it + // causes an error here + return server.handleUpgrade.apply(server, [ + req, + socket, + head + ]); + }; + } + setAssetPrefix(assetPrefix) { + if (this.server) { + this.server.setAssetPrefix(assetPrefix); + } else { + this.preparedAssetPrefix = assetPrefix; + } + } + getAssetPrefix() { + if (!this.server) { + throw new Error('prepare() must be called before getting assetPrefix'); + } + return this.server.getAssetPrefix(); + } + logError(...args) { + if (this.server) { + this.server.logError(...args); + } + } + async logErrorWithOriginalStack(err, type) { + const server = await this.getServer(); + // this is only available on dev server + if (server.logErrorWithOriginalStack) { + return server.logErrorWithOriginalStack(err, type); + } + } + async revalidate(...args) { + const server = await this.getServer(); + return server.revalidate(...args); + } + async render(...args) { + const server = await this.getServer(); + return server.render(...args); + } + async renderToHTML(...args) { + const server = await this.getServer(); + return server.renderToHTML(...args); + } + async renderError(...args) { + const server = await this.getServer(); + return server.renderError(...args); + } + async renderErrorToHTML(...args) { + const server = await this.getServer(); + return server.renderErrorToHTML(...args); + } + async render404(...args) { + const server = await this.getServer(); + return server.render404(...args); + } + async prepare(serverFields) { + const server = await this.getServer(); + if (serverFields) { + Object.assign(server, serverFields); + } + // We shouldn't prepare the server in production, + // because this code won't be executed when deployed + if (this.options.dev) { + await server.prepare(); + } + } + async close() { + if (this.server) { + await this.server.close(); + } + } + async createServer(options) { + let ServerImplementation; + if (options.dev) { + ServerImplementation = require('./dev/next-dev-server').default; + } else { + ServerImplementation = await getServerImpl(); + } + const server = new ServerImplementation(options); + return server; + } + async [SYMBOL_LOAD_CONFIG]() { + const dir = _nodepath.default.resolve(/* turbopackIgnore: true */ this.options.dir || '.'); + const config = await (0, _config.default)(this.options.dev ? _constants1.PHASE_DEVELOPMENT_SERVER : _constants1.PHASE_PRODUCTION_SERVER, dir, { + customConfig: this.options.conf, + silent: true + }); + // check serialized build config when available + if (!this.options.dev) { + try { + const serializedConfig = require(/* turbopackIgnore: true */ _nodepath.default.join(/* turbopackIgnore: true */ dir, config.distDir, _constants1.SERVER_FILES_MANIFEST + '.json')).config; + return { + config, + compileMode: { + isExperimentalCompile: serializedConfig.experimental.isExperimentalCompile + } + }; + } catch (_) { + // if distDir is customized we don't know until we + // load the config so fallback to loading the config + // from next.config.js + } + } + return { + config, + compileMode: undefined + }; + } + async getServer() { + if (!this.serverPromise) { + this.serverPromise = this[SYMBOL_LOAD_CONFIG]().then(async (result)=>{ + const { config: conf, compileMode } = result; + if (!this.options.dev) { + if (conf.output === 'standalone') { + if (!process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) { + _log.warn(`"next start" does not work with "output: standalone" configuration. Use "node .next/standalone/server.js" instead.`); + } + } else if (conf.output === 'export') { + throw new Error(`"next start" does not work with "output: export" configuration. Use "npx serve@latest out" instead.`); + } + } + this.server = await this.createServer({ + ...this.options, + conf, + compileMode + }); + if (this.preparedAssetPrefix) { + this.server.setAssetPrefix(this.preparedAssetPrefix); + } + return this.server; + }); + } + return this.serverPromise; + } + async getServerRequestHandler() { + if (this.reqHandler) return this.reqHandler; + // Memoize request handler creation + if (!this.reqHandlerPromise) { + this.reqHandlerPromise = this.getServer().then((server)=>{ + this.reqHandler = (0, _tracer.getTracer)().wrap(_constants2.NextServerSpan.getServerRequestHandler, server.getRequestHandler().bind(server)); + delete this.reqHandlerPromise; + return this.reqHandler; + }); + } + return this.reqHandlerPromise; + } +} +/** The wrapper server used for `import next from "next" (in a custom server)` */ class NextCustomServer { + constructor(options){ + this.didWebSocketSetup = false; + this.options = options; + } + getInit() { + if (!this.init) { + throw new Error('prepare() must be called before performing this operation'); + } + return this.init; + } + get requestHandler() { + return this.getInit().requestHandler; + } + get upgradeHandler() { + return this.getInit().upgradeHandler; + } + get server() { + return this.getInit().server; + } + get hostname() { + return this.options.hostname; + } + get port() { + return this.options.port; + } + async prepare() { + if (this.options.dev) { + process.env.__NEXT_DEV_SERVER = '1'; + } + const { getRequestHandlers } = require('./lib/start-server'); + let onDevServerCleanup; + if (this.options.dev) { + this.cleanupListeners = new _asynccallbackset.AsyncCallbackSet(); + onDevServerCleanup = this.cleanupListeners.add.bind(this.cleanupListeners); + } + const initResult = await getRequestHandlers({ + dir: this.options.dir, + port: this.options.port || 3000, + isDev: !!this.options.dev, + onDevServerCleanup, + hostname: this.options.hostname || 'localhost', + minimalMode: this.options.minimalMode, + quiet: this.options.quiet + }); + this.init = initResult; + } + setupWebSocketHandler(customServer, _req) { + if (!this.didWebSocketSetup) { + var _req_socket; + this.didWebSocketSetup = true; + customServer = customServer || (_req == null ? void 0 : (_req_socket = _req.socket) == null ? void 0 : _req_socket.server); + if (customServer) { + customServer.on('upgrade', async (req, socket, head)=>{ + this.upgradeHandler(req, socket, head); + }); + } + } + } + getRequestHandler() { + return async (req, res, parsedUrl)=>{ + this.setupWebSocketHandler(this.options.httpServer, req); + if (parsedUrl) { + req.url = (0, _formaturl.formatUrl)(parsedUrl); + } + return this.requestHandler(req, res); + }; + } + async render(...args) { + warnDeprecatedCustomServerMethod('render'); + let [req, res, pathname, query, parsedUrl] = args; + this.setupWebSocketHandler(this.options.httpServer, req); + if (!pathname.startsWith('/')) { + console.error(`Cannot render page with path "${pathname}"`); + pathname = `/${pathname}`; + } + pathname = pathname === '/index' ? '/' : pathname; + req.url = (0, _formaturl.formatUrl)({ + ...parsedUrl, + pathname, + query + }); + await this.requestHandler(req, res); + return; + } + setAssetPrefix(assetPrefix) { + warnDeprecatedCustomServerMethod('setAssetPrefix'); + this.server.setAssetPrefix(assetPrefix); + } + getUpgradeHandler() { + return this.server.getUpgradeHandler(); + } + logError(...args) { + warnDeprecatedCustomServerMethod('logError'); + this.server.logError(...args); + } + logErrorWithOriginalStack(err, type) { + warnDeprecatedCustomServerMethod('logErrorWithOriginalStack'); + return this.server.logErrorWithOriginalStack(err, type); + } + async revalidate(...args) { + warnDeprecatedCustomServerMethod('revalidate'); + return this.server.revalidate(...args); + } + async renderToHTML(...args) { + warnDeprecatedCustomServerMethod('renderToHTML'); + return this.server.renderToHTML(...args); + } + async renderError(...args) { + warnDeprecatedCustomServerMethod('renderError'); + return this.server.renderError(...args); + } + async renderErrorToHTML(...args) { + warnDeprecatedCustomServerMethod('renderErrorToHTML'); + return this.server.renderErrorToHTML(...args); + } + async render404(...args) { + warnDeprecatedCustomServerMethod('render404'); + return this.server.render404(...args); + } + async close() { + var _this_init, _this_cleanupListeners; + await Promise.allSettled([ + (_this_init = this.init) == null ? void 0 : _this_init.server.close(), + (_this_cleanupListeners = this.cleanupListeners) == null ? void 0 : _this_cleanupListeners.runAll() + ]); + } +} +// This file is used for when users run `require('next')` +function createServer(options) { + // next sets customServer to false when calling this function, in that case we don't want to modify the environment variables + const isCustomServer = (options == null ? void 0 : options.customServer) ?? true; + if (isCustomServer) { + const selectTurbopack = options && (options.turbo || options.turbopack || process.env.IS_TURBOPACK_TEST); + const selectWebpack = options && (options.webpack || process.env.IS_WEBPACK_TEST); + // Rspack is selected through env/config side effects instead of a custom + // server option, so don't fall back to the default Turbopack auto mode. + const selectRspack = !!process.env.NEXT_RSPACK; + if (selectTurbopack && selectWebpack && selectRspack) { + throw new Error('Pass either `webpack` or `turbopack`, not both.'); + } + if (selectTurbopack) { + process.env.TURBOPACK ??= '1'; + } else if (!selectWebpack && !selectRspack) { + process.env.TURBOPACK ??= 'auto'; + } + } else { + if (options && (options.webpack || options.turbo || options.turbopack)) { + throw new Error('Only custom servers can pass `webpack`, `turbo`, or `turbopack`.'); + } + } + // The package is used as a TypeScript plugin. + if (options && 'typescript' in options && 'version' in options.typescript) { + const pluginMod = require('./next-typescript'); + return pluginMod.createTSPlugin(options); + } + if (options == null) { + throw new Error('The server has not been instantiated properly. https://nextjs.org/docs/messages/invalid-server-options'); + } + if (!('isNextDevCommand' in options) && process.env.NODE_ENV && ![ + 'production', + 'development', + 'test' + ].includes(process.env.NODE_ENV)) { + _log.warn(_constants.NON_STANDARD_NODE_ENV); + } + if (options.dev && typeof options.dev !== 'boolean') { + console.warn("Warning: 'dev' is not a boolean which could introduce unexpected behavior. https://nextjs.org/docs/messages/invalid-server-options"); + } + // When the caller is a custom server (using next()). + if (options.customServer !== false) { + const dir = _nodepath.default.resolve(/* turbopackIgnore: true */ options.dir || '.'); + return new NextCustomServer({ + ...options, + dir + }); + } + // When the caller is Next.js internals (i.e. render worker, start server, etc) + return new NextServer(options); +} +// Support commonjs `require('next')` +module.exports = createServer; +const _default = createServer; + +//# sourceMappingURL=next.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/next.js.map b/e-commerce/node_modules/next/dist/server/next.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4c3970d996266fe3ebe30c7e1cf9f5aa3af8b0b1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/next.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/next.ts"],"sourcesContent":["import type { Options as DevServerOptions } from './dev/next-dev-server'\nimport type {\n NodeRequestHandler,\n Options as ServerOptions,\n} from './next-server'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { Duplex } from 'stream'\nimport type { NextUrlWithParsedQuery, RequestMeta } from './request-meta'\n\nimport './require-hook'\nimport './node-polyfill-crypto'\n\nimport type { default as NextNodeServer } from './next-server'\nimport * as log from '../build/output/log'\nimport loadConfig from './config'\nimport path from 'node:path'\nimport { NON_STANDARD_NODE_ENV } from '../lib/constants'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n SERVER_FILES_MANIFEST,\n} from '../shared/lib/constants'\nimport { PHASE_PRODUCTION_SERVER } from '../shared/lib/constants'\nimport { getTracer } from './lib/trace/tracer'\nimport { NextServerSpan } from './lib/trace/constants'\nimport { formatUrl } from '../shared/lib/router/utils/format-url'\nimport type { ServerFields } from './lib/router-utils/setup-dev-bundler'\nimport type { ServerInitResult } from './lib/render-server'\nimport { AsyncCallbackSet } from './lib/async-callback-set'\n\nlet ServerImpl: typeof NextNodeServer\n\nconst getServerImpl = async () => {\n if (ServerImpl === undefined) {\n ServerImpl = (\n await Promise.resolve(\n require('./next-server') as typeof import('./next-server')\n )\n ).default\n }\n return ServerImpl\n}\n\nexport type NextServerOptions = Omit<\n ServerOptions | DevServerOptions,\n // This is assigned in this server abstraction.\n 'conf' | 'compileMode'\n> &\n Partial>\n\nexport type NextBundlerOptions = {\n /** @deprecated Use `turbopack` instead */\n turbo?: boolean\n /** Selects Turbopack as the bundler */\n turbopack?: boolean\n /** Selects Webpack as the bundler */\n webpack?: boolean\n}\n\nexport type RequestHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n parsedUrl?: NextUrlWithParsedQuery | undefined\n) => Promise\n\nexport type UpgradeHandler = (\n req: IncomingMessage,\n socket: Duplex,\n head: Buffer\n) => Promise\n\nconst SYMBOL_LOAD_CONFIG = Symbol('next.load_config')\n\ntype DeprecatedCustomServerMethod =\n | 'setAssetPrefix'\n | 'logError'\n | 'logErrorWithOriginalStack'\n | 'revalidate'\n | 'render'\n | 'renderToHTML'\n | 'renderError'\n | 'renderErrorToHTML'\n | 'render404'\n\nconst DEPRECATED_CUSTOM_SERVER_METHOD_GUIDANCE: Record<\n DeprecatedCustomServerMethod,\n string\n> = {\n setAssetPrefix: 'Please configure `assetPrefix` in `next.config.js` instead.',\n logError: 'Please use application logging instead.',\n logErrorWithOriginalStack: 'Please use application logging instead.',\n revalidate: 'Please use documented application revalidation APIs instead.',\n render:\n 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.',\n renderToHTML:\n 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.',\n renderError:\n 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.',\n renderErrorToHTML:\n 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.',\n render404:\n 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.',\n}\n\nfunction warnDeprecatedCustomServerMethod(\n method: DeprecatedCustomServerMethod\n) {\n log.warnOnce(\n `The \\`app.${method}()\\` method is deprecated in custom servers. ${DEPRECATED_CUSTOM_SERVER_METHOD_GUIDANCE[method]}`\n )\n}\n\ninterface NextWrapperServer {\n // NOTE: the methods/properties here are the public API for custom servers.\n // Consider backwards compatibilty when changing something here!\n\n options: NextServerOptions\n hostname: string | undefined\n port: number | undefined\n\n getRequestHandler(): RequestHandler\n prepare(serverFields?: ServerFields): Promise\n /** @deprecated Configure `assetPrefix` in `next.config.js` instead. */\n setAssetPrefix(assetPrefix: string): void\n close(): Promise\n\n // used internally\n getUpgradeHandler(): UpgradeHandler\n\n // legacy methods that we left exposed in the past\n\n /** @deprecated Use application logging instead. */\n logError(...args: Parameters): void\n\n /** @deprecated Use documented application revalidation APIs instead. */\n revalidate(\n ...args: Parameters\n ): ReturnType\n\n /** @deprecated Use application logging instead. */\n logErrorWithOriginalStack(err: unknown, type: string): void\n\n /**\n * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead.\n */\n render(\n ...args: Parameters\n ): ReturnType\n\n /**\n * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead.\n */\n renderToHTML(\n ...args: Parameters\n ): ReturnType\n\n /**\n * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead.\n */\n renderError(\n ...args: Parameters\n ): ReturnType\n\n /**\n * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead.\n */\n renderErrorToHTML(\n ...args: Parameters\n ): ReturnType\n\n /**\n * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead.\n */\n render404(\n ...args: Parameters\n ): ReturnType\n}\n\n/** The wrapper server used by `next start` */\nexport class NextServer implements NextWrapperServer {\n private serverPromise?: Promise\n private server?: NextNodeServer\n private reqHandler?: NodeRequestHandler\n private reqHandlerPromise?: Promise\n private preparedAssetPrefix?: string\n\n public options: NextServerOptions\n\n constructor(options: NextServerOptions) {\n this.options = options\n }\n\n get hostname() {\n return this.options.hostname\n }\n\n get port() {\n return this.options.port\n }\n\n getRequestHandler(): RequestHandler {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ) => {\n const tracer = getTracer()\n return tracer.withPropagatedContext(req.headers, () =>\n tracer.trace(NextServerSpan.getRequestHandler, async () => {\n const requestHandler = await this.getServerRequestHandler()\n return requestHandler(req, res, parsedUrl)\n })\n )\n }\n }\n\n /**\n * @internal - this method is internal to Next.js and should not be used\n * directly by end-users, only used in testing\n */\n getRequestHandlerWithMetadata(meta: RequestMeta): RequestHandler {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ) => {\n const tracer = getTracer()\n return tracer.withPropagatedContext(req.headers, () =>\n tracer.trace(NextServerSpan.getRequestHandlerWithMetadata, async () => {\n const server = await this.getServer()\n const handler = server.getRequestHandlerWithMetadata(meta)\n return handler(req, res, parsedUrl)\n })\n )\n }\n }\n\n getUpgradeHandler(): UpgradeHandler {\n return async (req: IncomingMessage, socket: any, head: any) => {\n const server = await this.getServer()\n // @ts-expect-error we mark this as protected so it\n // causes an error here\n return server.handleUpgrade.apply(server, [req, socket, head])\n }\n }\n\n setAssetPrefix(assetPrefix: string) {\n if (this.server) {\n this.server.setAssetPrefix(assetPrefix)\n } else {\n this.preparedAssetPrefix = assetPrefix\n }\n }\n\n getAssetPrefix(): string {\n if (!this.server) {\n throw new Error('prepare() must be called before getting assetPrefix')\n }\n return this.server.getAssetPrefix()\n }\n\n logError(...args: Parameters) {\n if (this.server) {\n this.server.logError(...args)\n }\n }\n\n async logErrorWithOriginalStack(err: unknown, type: string) {\n const server = await this.getServer()\n // this is only available on dev server\n if ((server as any).logErrorWithOriginalStack) {\n return (server as any).logErrorWithOriginalStack(err, type)\n }\n }\n\n async revalidate(...args: Parameters) {\n const server = await this.getServer()\n return server.revalidate(...args)\n }\n\n async render(...args: Parameters) {\n const server = await this.getServer()\n return server.render(...args)\n }\n\n async renderToHTML(...args: Parameters) {\n const server = await this.getServer()\n return server.renderToHTML(...args)\n }\n\n async renderError(...args: Parameters) {\n const server = await this.getServer()\n return server.renderError(...args)\n }\n\n async renderErrorToHTML(\n ...args: Parameters\n ) {\n const server = await this.getServer()\n return server.renderErrorToHTML(...args)\n }\n\n async render404(...args: Parameters) {\n const server = await this.getServer()\n return server.render404(...args)\n }\n\n async prepare(serverFields?: ServerFields) {\n const server = await this.getServer()\n\n if (serverFields) {\n Object.assign(server, serverFields)\n }\n // We shouldn't prepare the server in production,\n // because this code won't be executed when deployed\n if (this.options.dev) {\n await server.prepare()\n }\n }\n\n async close() {\n if (this.server) {\n await this.server.close()\n }\n }\n\n private async createServer(\n options: ServerOptions | DevServerOptions\n ): Promise {\n let ServerImplementation: typeof NextNodeServer\n if (options.dev) {\n ServerImplementation = (\n require('./dev/next-dev-server') as typeof import('./dev/next-dev-server')\n ).default as typeof import('./dev/next-dev-server').default\n } else {\n ServerImplementation = await getServerImpl()\n }\n const server = new ServerImplementation(options)\n\n return server\n }\n\n private async [SYMBOL_LOAD_CONFIG]() {\n const dir = path.resolve(\n /* turbopackIgnore: true */ this.options.dir || '.'\n )\n\n const config = await loadConfig(\n this.options.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,\n dir,\n {\n customConfig: this.options.conf,\n silent: true,\n }\n )\n\n // check serialized build config when available\n if (!this.options.dev) {\n try {\n const serializedConfig = require(\n /* turbopackIgnore: true */\n path.join(\n /* turbopackIgnore: true */ dir,\n config.distDir,\n SERVER_FILES_MANIFEST + '.json'\n )\n ).config\n\n return {\n config,\n compileMode: {\n isExperimentalCompile:\n serializedConfig.experimental.isExperimentalCompile,\n },\n }\n } catch (_) {\n // if distDir is customized we don't know until we\n // load the config so fallback to loading the config\n // from next.config.js\n }\n }\n\n return { config, compileMode: undefined }\n }\n\n private async getServer() {\n if (!this.serverPromise) {\n this.serverPromise = this[SYMBOL_LOAD_CONFIG]().then(async (result) => {\n const { config: conf, compileMode } = result\n if (!this.options.dev) {\n if (conf.output === 'standalone') {\n if (!process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) {\n log.warn(\n `\"next start\" does not work with \"output: standalone\" configuration. Use \"node .next/standalone/server.js\" instead.`\n )\n }\n } else if (conf.output === 'export') {\n throw new Error(\n `\"next start\" does not work with \"output: export\" configuration. Use \"npx serve@latest out\" instead.`\n )\n }\n }\n\n this.server = await this.createServer({\n ...this.options,\n conf,\n compileMode,\n })\n if (this.preparedAssetPrefix) {\n this.server.setAssetPrefix(this.preparedAssetPrefix)\n }\n return this.server\n })\n }\n return this.serverPromise\n }\n\n private async getServerRequestHandler() {\n if (this.reqHandler) return this.reqHandler\n\n // Memoize request handler creation\n if (!this.reqHandlerPromise) {\n this.reqHandlerPromise = this.getServer().then((server) => {\n this.reqHandler = getTracer().wrap(\n NextServerSpan.getServerRequestHandler,\n server.getRequestHandler().bind(server)\n )\n delete this.reqHandlerPromise\n return this.reqHandler\n })\n }\n return this.reqHandlerPromise\n }\n}\n\n/** The wrapper server used for `import next from \"next\" (in a custom server)` */\nclass NextCustomServer implements NextWrapperServer {\n private didWebSocketSetup: boolean = false\n protected cleanupListeners?: AsyncCallbackSet\n\n protected init?: ServerInitResult\n\n public options: NextServerOptions\n\n constructor(options: NextServerOptions) {\n this.options = options\n }\n\n protected getInit() {\n if (!this.init) {\n throw new Error(\n 'prepare() must be called before performing this operation'\n )\n }\n return this.init\n }\n\n protected get requestHandler() {\n return this.getInit().requestHandler\n }\n protected get upgradeHandler() {\n return this.getInit().upgradeHandler\n }\n protected get server() {\n return this.getInit().server\n }\n\n get hostname() {\n return this.options.hostname\n }\n\n get port() {\n return this.options.port\n }\n\n async prepare() {\n if (this.options.dev) {\n process.env.__NEXT_DEV_SERVER = '1'\n }\n\n const { getRequestHandlers } =\n require('./lib/start-server') as typeof import('./lib/start-server')\n\n let onDevServerCleanup: AsyncCallbackSet['add'] | undefined\n if (this.options.dev) {\n this.cleanupListeners = new AsyncCallbackSet()\n onDevServerCleanup = this.cleanupListeners.add.bind(this.cleanupListeners)\n }\n\n const initResult = await getRequestHandlers({\n dir: this.options.dir!,\n port: this.options.port || 3000,\n isDev: !!this.options.dev,\n onDevServerCleanup,\n hostname: this.options.hostname || 'localhost',\n minimalMode: this.options.minimalMode,\n quiet: this.options.quiet,\n })\n this.init = initResult\n }\n\n private setupWebSocketHandler(\n customServer?: import('http').Server,\n _req?: IncomingMessage\n ) {\n if (!this.didWebSocketSetup) {\n this.didWebSocketSetup = true\n customServer = customServer || (_req?.socket as any)?.server\n\n if (customServer) {\n customServer.on('upgrade', async (req, socket, head) => {\n this.upgradeHandler(req, socket, head)\n })\n }\n }\n }\n\n getRequestHandler(): RequestHandler {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ) => {\n this.setupWebSocketHandler(this.options.httpServer, req)\n\n if (parsedUrl) {\n req.url = formatUrl(parsedUrl)\n }\n\n return this.requestHandler(req, res)\n }\n }\n\n async render(...args: Parameters) {\n warnDeprecatedCustomServerMethod('render')\n let [req, res, pathname, query, parsedUrl] = args\n this.setupWebSocketHandler(this.options.httpServer, req as IncomingMessage)\n\n if (!pathname.startsWith('/')) {\n console.error(`Cannot render page with path \"${pathname}\"`)\n pathname = `/${pathname}`\n }\n pathname = pathname === '/index' ? '/' : pathname\n\n req.url = formatUrl({\n ...parsedUrl,\n pathname,\n query,\n })\n\n await this.requestHandler(req as IncomingMessage, res as ServerResponse)\n return\n }\n\n setAssetPrefix(assetPrefix: string): void {\n warnDeprecatedCustomServerMethod('setAssetPrefix')\n this.server.setAssetPrefix(assetPrefix)\n }\n\n getUpgradeHandler(): UpgradeHandler {\n return this.server.getUpgradeHandler()\n }\n\n logError(...args: Parameters) {\n warnDeprecatedCustomServerMethod('logError')\n this.server.logError(...args)\n }\n\n logErrorWithOriginalStack(err: unknown, type: string) {\n warnDeprecatedCustomServerMethod('logErrorWithOriginalStack')\n return this.server.logErrorWithOriginalStack(err, type)\n }\n\n async revalidate(...args: Parameters) {\n warnDeprecatedCustomServerMethod('revalidate')\n return this.server.revalidate(...args)\n }\n\n async renderToHTML(...args: Parameters) {\n warnDeprecatedCustomServerMethod('renderToHTML')\n return this.server.renderToHTML(...args)\n }\n\n async renderError(...args: Parameters) {\n warnDeprecatedCustomServerMethod('renderError')\n return this.server.renderError(...args)\n }\n\n async renderErrorToHTML(\n ...args: Parameters\n ) {\n warnDeprecatedCustomServerMethod('renderErrorToHTML')\n return this.server.renderErrorToHTML(...args)\n }\n\n async render404(...args: Parameters) {\n warnDeprecatedCustomServerMethod('render404')\n return this.server.render404(...args)\n }\n\n async close() {\n await Promise.allSettled([\n this.init?.server.close(),\n this.cleanupListeners?.runAll(),\n ])\n }\n}\n\n// This file is used for when users run `require('next')`\nfunction createServer(\n options: NextServerOptions & NextBundlerOptions\n): NextWrapperServer {\n // next sets customServer to false when calling this function, in that case we don't want to modify the environment variables\n const isCustomServer = options?.customServer ?? true\n if (isCustomServer) {\n const selectTurbopack =\n options &&\n (options.turbo || options.turbopack || process.env.IS_TURBOPACK_TEST)\n const selectWebpack =\n options && (options.webpack || process.env.IS_WEBPACK_TEST)\n // Rspack is selected through env/config side effects instead of a custom\n // server option, so don't fall back to the default Turbopack auto mode.\n const selectRspack = !!process.env.NEXT_RSPACK\n if (selectTurbopack && selectWebpack && selectRspack) {\n throw new Error('Pass either `webpack` or `turbopack`, not both.')\n }\n if (selectTurbopack) {\n process.env.TURBOPACK ??= '1'\n } else if (!selectWebpack && !selectRspack) {\n process.env.TURBOPACK ??= 'auto'\n }\n } else {\n if (options && (options.webpack || options.turbo || options.turbopack)) {\n throw new Error(\n 'Only custom servers can pass `webpack`, `turbo`, or `turbopack`.'\n )\n }\n }\n\n // The package is used as a TypeScript plugin.\n if (\n options &&\n 'typescript' in options &&\n 'version' in (options as any).typescript\n ) {\n const pluginMod: typeof import('./next-typescript') =\n require('./next-typescript') as typeof import('./next-typescript')\n return pluginMod.createTSPlugin(\n options as any\n ) as unknown as NextWrapperServer\n }\n\n if (options == null) {\n throw new Error(\n 'The server has not been instantiated properly. https://nextjs.org/docs/messages/invalid-server-options'\n )\n }\n\n if (\n !('isNextDevCommand' in options) &&\n process.env.NODE_ENV &&\n !['production', 'development', 'test'].includes(process.env.NODE_ENV)\n ) {\n log.warn(NON_STANDARD_NODE_ENV)\n }\n\n if (options.dev && typeof options.dev !== 'boolean') {\n console.warn(\n \"Warning: 'dev' is not a boolean which could introduce unexpected behavior. https://nextjs.org/docs/messages/invalid-server-options\"\n )\n }\n\n // When the caller is a custom server (using next()).\n if (options.customServer !== false) {\n const dir = path.resolve(/* turbopackIgnore: true */ options.dir || '.')\n\n return new NextCustomServer({\n ...options,\n dir,\n })\n }\n\n // When the caller is Next.js internals (i.e. render worker, start server, etc)\n return new NextServer(options)\n}\n\n// Support commonjs `require('next')`\nmodule.exports = createServer\n// exports = module.exports\n\n// Support `import next from 'next'`\nexport default createServer\n"],"names":["NextServer","ServerImpl","getServerImpl","undefined","Promise","resolve","require","default","SYMBOL_LOAD_CONFIG","Symbol","DEPRECATED_CUSTOM_SERVER_METHOD_GUIDANCE","setAssetPrefix","logError","logErrorWithOriginalStack","revalidate","render","renderToHTML","renderError","renderErrorToHTML","render404","warnDeprecatedCustomServerMethod","method","log","warnOnce","constructor","options","hostname","port","getRequestHandler","req","res","parsedUrl","tracer","getTracer","withPropagatedContext","headers","trace","NextServerSpan","requestHandler","getServerRequestHandler","getRequestHandlerWithMetadata","meta","server","getServer","handler","getUpgradeHandler","socket","head","handleUpgrade","apply","assetPrefix","preparedAssetPrefix","getAssetPrefix","Error","args","err","type","prepare","serverFields","Object","assign","dev","close","createServer","ServerImplementation","dir","path","config","loadConfig","PHASE_DEVELOPMENT_SERVER","PHASE_PRODUCTION_SERVER","customConfig","conf","silent","serializedConfig","join","distDir","SERVER_FILES_MANIFEST","compileMode","isExperimentalCompile","experimental","_","serverPromise","then","result","output","process","env","__NEXT_PRIVATE_STANDALONE_CONFIG","warn","reqHandler","reqHandlerPromise","wrap","bind","NextCustomServer","didWebSocketSetup","getInit","init","upgradeHandler","__NEXT_DEV_SERVER","getRequestHandlers","onDevServerCleanup","cleanupListeners","AsyncCallbackSet","add","initResult","isDev","minimalMode","quiet","setupWebSocketHandler","customServer","_req","on","httpServer","url","formatUrl","pathname","query","startsWith","console","error","allSettled","runAll","isCustomServer","selectTurbopack","turbo","turbopack","IS_TURBOPACK_TEST","selectWebpack","webpack","IS_WEBPACK_TEST","selectRspack","NEXT_RSPACK","TURBOPACK","typescript","pluginMod","createTSPlugin","NODE_ENV","includes","NON_STANDARD_NODE_ENV","module","exports"],"mappings":";;;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AAGoB,QAAQwC,GAAG,IAAI;QAEpE,OAAO,IAAI6B,iBAAiB;YAC1B,GAAGrE,OAAO;YACVwC;QACF;IACF;IAEA,+EAA+E;IAC/E,OAAO,IAAIjE,WAAWyB;AACxB;AAEA,qCAAqC;AACrCmH,OAAOC,OAAO,GAAG9E;MAIjB,WAAeA","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-baseline.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-baseline.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/node-environment-baseline.js b/e-commerce/node_modules/next/dist/server/node-environment-baseline.js new file mode 100644 index 0000000000000000000000000000000000000000..57c2d8ef8d36f6c3901f033f1e32d01b60cf70d8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-baseline.js @@ -0,0 +1,25 @@ +// This file should be imported before any others. It sets up the environment +// for later imports to work properly. +// expose AsyncLocalStorage on global for react usage if it isn't already provided by the environment +"use strict"; +if (typeof globalThis.AsyncLocalStorage !== 'function') { + const { AsyncLocalStorage } = require('async_hooks'); + globalThis.AsyncLocalStorage = AsyncLocalStorage; +} +if (typeof globalThis.WebSocket !== 'function') { + Object.defineProperty(globalThis, 'WebSocket', { + configurable: true, + get () { + return require('next/dist/compiled/ws').WebSocket; + }, + set (value) { + Object.defineProperty(globalThis, 'WebSocket', { + configurable: true, + writable: true, + value + }); + } + }); +} + +//# sourceMappingURL=node-environment-baseline.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-baseline.js.map b/e-commerce/node_modules/next/dist/server/node-environment-baseline.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6bcad91159d6f024ebae63abf0e5e4da1dc3bb58 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-baseline.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/node-environment-baseline.ts"],"sourcesContent":["// This file should be imported before any others. It sets up the environment\n// for later imports to work properly.\n\n// expose AsyncLocalStorage on global for react usage if it isn't already provided by the environment\nif (typeof (globalThis as any).AsyncLocalStorage !== 'function') {\n const { AsyncLocalStorage } =\n require('async_hooks') as typeof import('async_hooks')\n ;(globalThis as any).AsyncLocalStorage = AsyncLocalStorage\n}\n\nif (typeof (globalThis as any).WebSocket !== 'function') {\n Object.defineProperty(globalThis, 'WebSocket', {\n configurable: true,\n get() {\n return (\n require('next/dist/compiled/ws') as typeof import('next/dist/compiled/ws')\n ).WebSocket\n },\n set(value) {\n Object.defineProperty(globalThis, 'WebSocket', {\n configurable: true,\n writable: true,\n value,\n })\n },\n })\n}\n"],"names":["globalThis","AsyncLocalStorage","require","WebSocket","Object","defineProperty","configurable","get","set","value","writable"],"mappings":"AAAA,6EAA6E;AAC7E,sCAAsC;AAEtC,qGAAqG;;AACrG,IAAI,OAAO,AAACA,WAAmBC,iBAAiB,KAAK,YAAY;IAC/D,MAAM,EAAEA,iBAAiB,EAAE,GACzBC,QAAQ;IACRF,WAAmBC,iBAAiB,GAAGA;AAC3C;AAEA,IAAI,OAAO,AAACD,WAAmBG,SAAS,KAAK,YAAY;IACvDC,OAAOC,cAAc,CAACL,YAAY,aAAa;QAC7CM,cAAc;QACdC;YACE,OAAO,AACLL,QAAQ,yBACRC,SAAS;QACb;QACAK,KAAIC,KAAK;YACPL,OAAOC,cAAc,CAACL,YAAY,aAAa;gBAC7CM,cAAc;gBACdI,UAAU;gBACVD;YACF;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-dim.external.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-dim.external.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee6dd9690808baad1ec6ae3e2bd09978a2010427 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-dim.external.d.ts @@ -0,0 +1,5 @@ +declare const DIMMED_STYLE = "dimmed"; +declare const HIDDEN_STYLE = "hidden"; +type LogStyle = typeof DIMMED_STYLE | typeof HIDDEN_STYLE; +export declare function setAbortedLogsStyle(style: LogStyle): void; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js new file mode 100644 index 0000000000000000000000000000000000000000..5dfd28b88f7bcdbddf75182902261b1def52e400 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js @@ -0,0 +1,300 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "setAbortedLogsStyle", { + enumerable: true, + get: function() { + return setAbortedLogsStyle; + } +}); +const _nodeinspector = /*#__PURE__*/ _interop_require_wildcard(require("node:inspector")); +const _picocolors = require("../../lib/picocolors"); +const _consoleasyncstorageexternal = require("../app-render/console-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _runtimereactsexternal = require("../runtime-reacts.external"); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +// eslint-disable-next-line @typescript-eslint/no-unused-vars -- we may use later and want parity with the HIDDEN_STYLE value +const DIMMED_STYLE = 'dimmed'; +const HIDDEN_STYLE = 'hidden'; +let currentAbortedLogsStyle = 'dimmed'; +function setAbortedLogsStyle(style) { + currentAbortedLogsStyle = style; +} +const isColorSupported = (0, _picocolors.dim)('test') !== 'test'; +// 50% opacity for dimmed text +const dimStyle = 'color: color(from currentColor xyz x y z / 0.5);'; +const reactBadgeFormat = '\x1b[0m\x1b[7m%c%s\x1b[0m%c '; +function dimmedConsoleArgs(...inputArgs) { + if (!isColorSupported) { + return inputArgs; + } + const newArgs = inputArgs.slice(0); + let template = ''; + let argumentsPointer = 0; + if (typeof inputArgs[0] === 'string') { + const originalTemplateString = inputArgs[0]; + // Remove the original template string from the args. + newArgs.splice(argumentsPointer, 1); + argumentsPointer += 1; + let i = 0; + if (originalTemplateString.startsWith(reactBadgeFormat)) { + i = reactBadgeFormat.length; + // for `format` we already moved the pointer earlier + // style, badge, reset style + argumentsPointer += 3; + template += reactBadgeFormat; + // React's badge reset styles, reapply dimming + template += '\x1b[2m%c'; + // argumentsPointer includes template + newArgs.splice(argumentsPointer - 1, 0, dimStyle); + // dim the badge + newArgs[0] += `;${dimStyle}`; + } + for(i; i < originalTemplateString.length; i++){ + const currentChar = originalTemplateString[i]; + if (currentChar !== '%') { + template += currentChar; + continue; + } + const nextChar = originalTemplateString[i + 1]; + ++i; + switch(nextChar){ + case 'f': + case 'O': + case 'o': + case 'd': + case 's': + case 'i': + case 'c': + ++argumentsPointer; + template += `%${nextChar}`; + break; + default: + template += `%${nextChar}`; + } + } + } + for(argumentsPointer; argumentsPointer < inputArgs.length; ++argumentsPointer){ + const arg = inputArgs[argumentsPointer]; + const argType = typeof arg; + if (argumentsPointer > 0) { + template += ' '; + } + switch(argType){ + case 'boolean': + case 'string': + template += '%s'; + break; + case 'bigint': + template += '%s'; + break; + case 'number': + if (arg % 0) { + template += '%f'; + } else { + template += '%d'; + } + break; + case 'object': + template += '%O'; + break; + case 'symbol': + case 'undefined': + case 'function': + template += '%s'; + break; + default: + // deopt to string for new, unknown types + template += '%s'; + } + } + template += '\x1b[22m'; + return [ + (0, _picocolors.dim)(`%c${template}`), + dimStyle, + ...newArgs + ]; +} +function convertToDimmedArgs(methodName, args) { + // When the Node.js inspector is open (e.g. --inspect), skip dimming entirely. + // Dimming wraps arguments in a format string which defeats inspector + // affordances such as collapsible objects and clickable/linkified stack + // traces. Ideally we would only skip dimming when a debugger frontend is + // actually attached, but Node.js does not expose a synchronous API for that. + // Detecting would require async polling of the /json/list HTTP endpoint. + if (_nodeinspector.url() !== undefined) { + return args; + } + switch(methodName){ + case 'dir': + case 'dirxml': + case 'group': + case 'groupCollapsed': + case 'groupEnd': + case 'table': + { + // These methods cannot be colorized because they don't take a formatting string. + return args; + } + case 'assert': + { + // assert takes formatting options as the second argument. + return [ + args[0] + ].concat(...dimmedConsoleArgs(args[1], ...args.slice(2))); + } + case 'error': + case 'debug': + case 'info': + case 'log': + case 'trace': + case 'warn': + return dimmedConsoleArgs(args[0], ...args.slice(1)); + default: + return methodName; + } +} +// Based on https://github.com/facebook/react/blob/28dc0776be2e1370fe217549d32aee2519f0cf05/packages/react-server/src/ReactFlightServer.js#L248 +function patchConsoleMethod(methodName) { + const descriptor = Object.getOwnPropertyDescriptor(console, methodName); + if (descriptor && (descriptor.configurable || descriptor.writable) && typeof descriptor.value === 'function') { + const originalMethod = descriptor.value; + const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name'); + const wrapperMethod = function(...args) { + var _getClientReact, _getServerReact; + const consoleStore = _consoleasyncstorageexternal.consoleAsyncStorage.getStore(); + // First we see if there is a cache signal for our current scope. If we're in a client render it'll + // come from the client React cacheSignal implementation. If we are in a server render it'll come from + // the server React cacheSignal implementation. Any particular console call will be in one, the other, or neither + // scope and these signals return null if you are out of scope so this can be called from a single global patch + // and still work properly. + const signal = ((_getClientReact = (0, _runtimereactsexternal.getClientReact)()) == null ? void 0 : _getClientReact.cacheSignal()) ?? ((_getServerReact = (0, _runtimereactsexternal.getServerReact)()) == null ? void 0 : _getServerReact.cacheSignal()); + if (signal) { + // We are in a React Server render and can consult the React cache signal to determine if logs + // are now dimmable. + if (signal.aborted) { + if (currentAbortedLogsStyle === HIDDEN_STYLE) { + return; + } + return applyWithDimming.call(this, consoleStore, originalMethod, methodName, args); + } else if ((consoleStore == null ? void 0 : consoleStore.dim) === true) { + return applyWithDimming.call(this, consoleStore, originalMethod, methodName, args); + } else { + return originalMethod.apply(this, args); + } + } + // We need to fall back to checking the work unit store for two reasons. + // 1. Client React does not yet implement cacheSignal (it always returns null) + // 2. route.ts files aren't rendered with React but do have prerender semantics + // TODO in the future we should be able to remove this once there is a runnable cache + // scope independent of actual React rendering. + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + switch(workUnitStore == null ? void 0 : workUnitStore.type){ + case 'prerender': + case 'prerender-runtime': + // These can be hit in a route handler. In the future we can use potential React.createCache API + // to create a cache scope for arbitrary computation and can move over to cacheSignal exclusively. + // fallthrough + case 'prerender-client': + case 'validation-client': + { + // This is a react-dom/server render and won't have a cacheSignal until React adds this for the client world. + const renderSignal = workUnitStore.renderSignal; + if (renderSignal.aborted) { + if (currentAbortedLogsStyle === HIDDEN_STYLE) { + return; + } + return applyWithDimming.call(this, consoleStore, originalMethod, methodName, args); + } + } + // intentional fallthrough + case 'prerender-legacy': + case 'cache': + case 'unstable-cache': + case 'private-cache': + case 'request': + case 'build-time-generator': + case undefined: + if ((consoleStore == null ? void 0 : consoleStore.dim) === true) { + return applyWithDimming.call(this, consoleStore, originalMethod, methodName, args); + } else { + return originalMethod.apply(this, args); + } + default: + workUnitStore; + } + }; + if (originalName) { + Object.defineProperty(wrapperMethod, 'name', originalName); + } + Object.defineProperty(console, methodName, { + value: wrapperMethod + }); + } +} +function applyWithDimming(consoleStore, method, methodName, args) { + if ((consoleStore == null ? void 0 : consoleStore.dim) === true) { + return method.apply(this, convertToDimmedArgs(methodName, args)); + } else { + return _consoleasyncstorageexternal.consoleAsyncStorage.run(DIMMED_STORE, method.bind(this, ...convertToDimmedArgs(methodName, args))); + } +} +const DIMMED_STORE = { + dim: true +}; +patchConsoleMethod('error'); +patchConsoleMethod('assert'); +patchConsoleMethod('debug'); +patchConsoleMethod('dir'); +patchConsoleMethod('dirxml'); +patchConsoleMethod('group'); +patchConsoleMethod('groupCollapsed'); +patchConsoleMethod('groupEnd'); +patchConsoleMethod('info'); +patchConsoleMethod('log'); +patchConsoleMethod('table'); +patchConsoleMethod('trace'); +patchConsoleMethod('warn'); + +//# sourceMappingURL=console-dim.external.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0d15f01ca6dde909926f9e679d7eeedbd4a1abb8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/console-dim.external.tsx"],"sourcesContent":["import * as inspector from 'node:inspector'\nimport { dim } from '../../lib/picocolors'\nimport {\n consoleAsyncStorage,\n type ConsoleStore,\n} from '../app-render/console-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from '../runtime-reacts.external'\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- we may use later and want parity with the HIDDEN_STYLE value\nconst DIMMED_STYLE = 'dimmed'\nconst HIDDEN_STYLE = 'hidden'\n\ntype LogStyle = typeof DIMMED_STYLE | typeof HIDDEN_STYLE\n\nlet currentAbortedLogsStyle: LogStyle = 'dimmed'\nexport function setAbortedLogsStyle(style: LogStyle) {\n currentAbortedLogsStyle = style\n}\n\ntype InterceptableConsoleMethod =\n | 'error'\n | 'assert'\n | 'debug'\n | 'dir'\n | 'dirxml'\n | 'group'\n | 'groupCollapsed'\n | 'groupEnd'\n | 'info'\n | 'log'\n | 'table'\n | 'trace'\n | 'warn'\n\nconst isColorSupported = dim('test') !== 'test'\n\n// 50% opacity for dimmed text\nconst dimStyle = 'color: color(from currentColor xyz x y z / 0.5);'\nconst reactBadgeFormat = '\\x1b[0m\\x1b[7m%c%s\\x1b[0m%c '\n\nfunction dimmedConsoleArgs(...inputArgs: any[]): any[] {\n if (!isColorSupported) {\n return inputArgs\n }\n\n const newArgs = inputArgs.slice(0)\n let template = ''\n let argumentsPointer = 0\n if (typeof inputArgs[0] === 'string') {\n const originalTemplateString = inputArgs[0]\n // Remove the original template string from the args.\n newArgs.splice(argumentsPointer, 1)\n argumentsPointer += 1\n\n let i = 0\n if (originalTemplateString.startsWith(reactBadgeFormat)) {\n i = reactBadgeFormat.length\n // for `format` we already moved the pointer earlier\n // style, badge, reset style\n argumentsPointer += 3\n template += reactBadgeFormat\n // React's badge reset styles, reapply dimming\n template += '\\x1b[2m%c'\n // argumentsPointer includes template\n newArgs.splice(argumentsPointer - 1, 0, dimStyle)\n // dim the badge\n newArgs[0] += `;${dimStyle}`\n }\n\n for (i; i < originalTemplateString.length; i++) {\n const currentChar = originalTemplateString[i]\n if (currentChar !== '%') {\n template += currentChar\n continue\n }\n\n const nextChar = originalTemplateString[i + 1]\n ++i\n\n switch (nextChar) {\n case 'f':\n case 'O':\n case 'o':\n case 'd':\n case 's':\n case 'i':\n case 'c':\n ++argumentsPointer\n template += `%${nextChar}`\n break\n default:\n template += `%${nextChar}`\n }\n }\n }\n\n for (\n argumentsPointer;\n argumentsPointer < inputArgs.length;\n ++argumentsPointer\n ) {\n const arg = inputArgs[argumentsPointer]\n const argType = typeof arg\n if (argumentsPointer > 0) {\n template += ' '\n }\n switch (argType) {\n case 'boolean':\n case 'string':\n template += '%s'\n break\n case 'bigint':\n template += '%s'\n break\n case 'number':\n if (arg % 0) {\n template += '%f'\n } else {\n template += '%d'\n }\n break\n case 'object':\n template += '%O'\n break\n case 'symbol':\n case 'undefined':\n case 'function':\n template += '%s'\n break\n default:\n // deopt to string for new, unknown types\n template += '%s'\n }\n }\n\n template += '\\x1b[22m'\n\n return [dim(`%c${template}`), dimStyle, ...newArgs]\n}\n\nfunction convertToDimmedArgs(\n methodName: InterceptableConsoleMethod,\n args: any[]\n): any[] {\n // When the Node.js inspector is open (e.g. --inspect), skip dimming entirely.\n // Dimming wraps arguments in a format string which defeats inspector\n // affordances such as collapsible objects and clickable/linkified stack\n // traces. Ideally we would only skip dimming when a debugger frontend is\n // actually attached, but Node.js does not expose a synchronous API for that.\n // Detecting would require async polling of the /json/list HTTP endpoint.\n if (inspector.url() !== undefined) {\n return args\n }\n\n switch (methodName) {\n case 'dir':\n case 'dirxml':\n case 'group':\n case 'groupCollapsed':\n case 'groupEnd':\n case 'table': {\n // These methods cannot be colorized because they don't take a formatting string.\n return args\n }\n case 'assert': {\n // assert takes formatting options as the second argument.\n return [args[0]].concat(...dimmedConsoleArgs(args[1], ...args.slice(2)))\n }\n case 'error':\n case 'debug':\n case 'info':\n case 'log':\n case 'trace':\n case 'warn':\n return dimmedConsoleArgs(args[0], ...args.slice(1))\n default:\n return methodName satisfies never\n }\n}\n\n// Based on https://github.com/facebook/react/blob/28dc0776be2e1370fe217549d32aee2519f0cf05/packages/react-server/src/ReactFlightServer.js#L248\nfunction patchConsoleMethod(methodName: InterceptableConsoleMethod): void {\n const descriptor = Object.getOwnPropertyDescriptor(console, methodName)\n if (\n descriptor &&\n (descriptor.configurable || descriptor.writable) &&\n typeof descriptor.value === 'function'\n ) {\n const originalMethod = descriptor.value\n const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')\n const wrapperMethod = function (this: typeof console, ...args: any[]) {\n const consoleStore = consoleAsyncStorage.getStore()\n\n // First we see if there is a cache signal for our current scope. If we're in a client render it'll\n // come from the client React cacheSignal implementation. If we are in a server render it'll come from\n // the server React cacheSignal implementation. Any particular console call will be in one, the other, or neither\n // scope and these signals return null if you are out of scope so this can be called from a single global patch\n // and still work properly.\n const signal =\n getClientReact()?.cacheSignal() ?? getServerReact()?.cacheSignal()\n if (signal) {\n // We are in a React Server render and can consult the React cache signal to determine if logs\n // are now dimmable.\n if (signal.aborted) {\n if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n return\n }\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else if (consoleStore?.dim === true) {\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else {\n return originalMethod.apply(this, args)\n }\n }\n\n // We need to fall back to checking the work unit store for two reasons.\n // 1. Client React does not yet implement cacheSignal (it always returns null)\n // 2. route.ts files aren't rendered with React but do have prerender semantics\n // TODO in the future we should be able to remove this once there is a runnable cache\n // scope independent of actual React rendering.\n const workUnitStore = workUnitAsyncStorage.getStore()\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-runtime':\n // These can be hit in a route handler. In the future we can use potential React.createCache API\n // to create a cache scope for arbitrary computation and can move over to cacheSignal exclusively.\n // fallthrough\n case 'prerender-client':\n case 'validation-client': {\n // This is a react-dom/server render and won't have a cacheSignal until React adds this for the client world.\n const renderSignal = workUnitStore.renderSignal\n if (renderSignal.aborted) {\n if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n return\n }\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n }\n }\n // intentional fallthrough\n case 'prerender-legacy':\n case 'cache':\n case 'unstable-cache':\n case 'private-cache':\n case 'request':\n case 'build-time-generator':\n case undefined:\n if (consoleStore?.dim === true) {\n return applyWithDimming.call(\n this,\n consoleStore,\n originalMethod,\n methodName,\n args\n )\n } else {\n return originalMethod.apply(this, args)\n }\n default:\n workUnitStore satisfies never\n }\n }\n if (originalName) {\n Object.defineProperty(wrapperMethod, 'name', originalName)\n }\n Object.defineProperty(console, methodName, {\n value: wrapperMethod,\n })\n }\n}\n\nfunction applyWithDimming any>(\n this: Console,\n consoleStore: undefined | ConsoleStore,\n method: F,\n methodName: InterceptableConsoleMethod,\n args: Parameters\n): ReturnType {\n if (consoleStore?.dim === true) {\n return method.apply(this, convertToDimmedArgs(methodName, args))\n } else {\n return consoleAsyncStorage.run(\n DIMMED_STORE,\n method.bind(this, ...convertToDimmedArgs(methodName, args))\n )\n }\n}\n\nconst DIMMED_STORE = { dim: true }\n\npatchConsoleMethod('error')\npatchConsoleMethod('assert')\npatchConsoleMethod('debug')\npatchConsoleMethod('dir')\npatchConsoleMethod('dirxml')\npatchConsoleMethod('group')\npatchConsoleMethod('groupCollapsed')\npatchConsoleMethod('groupEnd')\npatchConsoleMethod('info')\npatchConsoleMethod('log')\npatchConsoleMethod('table')\npatchConsoleMethod('trace')\npatchConsoleMethod('warn')\n"],"names":["setAbortedLogsStyle","DIMMED_STYLE","HIDDEN_STYLE","currentAbortedLogsStyle","style","isColorSupported","dim","dimStyle","reactBadgeFormat","dimmedConsoleArgs","inputArgs","newArgs","slice","template","argumentsPointer","originalTemplateString","splice","i","startsWith","length","currentChar","nextChar","arg","argType","convertToDimmedArgs","methodName","args","inspector","url","undefined","concat","patchConsoleMethod","descriptor","Object","getOwnPropertyDescriptor","console","configurable","writable","value","originalMethod","originalName","wrapperMethod","getClientReact","getServerReact","consoleStore","consoleAsyncStorage","getStore","signal","cacheSignal","aborted","applyWithDimming","call","apply","workUnitStore","workUnitAsyncStorage","type","renderSignal","defineProperty","method","run","DIMMED_STORE","bind"],"mappings":";;;;+BAgBgBA;;;eAAAA;;;uEAhBW;4BACP;6CAIb;8CAC8B;uCACU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE/C,6HAA6H;AAC7H,MAAMC,eAAe;AACrB,MAAMC,eAAe;AAIrB,IAAIC,0BAAoC;AACjC,SAASH,oBAAoBI,KAAe;IACjDD,0BAA0BC;AAC5B;AAiBA,MA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,IAAIA,aAAaP,OAAO,EAAE;4BACxB,IAAI9C,4BAA4BD,cAAc;gCAC5C;4BACF;4BACA,OAAOgD,iBAAiBC,IAAI,CAC1B,IAAI,EACJP,cACAL,gBACAd,YACAC;wBAEJ;oBACF;gBACA,0BAA0B;gBAC1B,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAKG;oBACH,IAAIe,CAAAA,gCAAAA,aAActC,GAAG,MAAK,MAAM;wBAC9B,OAAO4C,iBAAiBC,IAAI,CAC1B,IAAI,EACJP,cACAL,gBACAd,YACAC;oBAEJ,OAAO;wBACL,OAAOa,eAAea,KAAK,CAAC,IAAI,EAAE1B;oBACpC;gBACF;oBACE2B;YACJ;QACF;QACA,IAAIb,cAAc;YAChBP,OAAOwB,cAAc,CAAChB,eAAe,QAAQD;QAC/C;QACAP,OAAOwB,cAAc,CAACtB,SAASV,YAAY;YACzCa,OAAOG;QACT;IACF;AACF;AAEA,SAASS,iBAEPN,YAAsC,EACtCc,MAAS,EACTjC,UAAsC,EACtCC,IAAmB;IAEnB,IAAIkB,CAAAA,gCAAAA,aAActC,GAAG,MAAK,MAAM;QAC9B,OAAOoD,OAAON,KAAK,CAAC,IAAI,EAAE5B,oBAAoBC,YAAYC;IAC5D,OAAO;QACL,OAAOmB,gDAAmB,CAACc,GAAG,CAC5BC,cACAF,OAAOG,IAAI,CAAC,IAAI,KAAKrC,oBAAoBC,YAAYC;IAEzD;AACF;AAEA,MAAMkC,eAAe;IAAEtD,KAAK;AAAK;AAEjCyB,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-exit.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-exit.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfafd0521fb21271f918c04d372f0c271c23d795 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-exit.d.ts @@ -0,0 +1,12 @@ +/** + * Patches console methods to exit the workUnitAsyncStorage so that inside the host implementation + * sync IO can be called. This is relevant for example with runtimes that patch console methods to + * prepend a timestamp to the log output. + * + * Note that this will only exit for already installed patched console methods. If you further patch + * the console method after this and add any sync IO there it will trigger sync IO warnings while prerendering. + * + * This is a pragmatic concession because layering the patches if you install your own log implementation + * after they are installed is very tricky to do correctly because the order matters + */ +export {}; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-exit.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-exit.js new file mode 100644 index 0000000000000000000000000000000000000000..185ebad3266d9728162cbed0a853a6fa7bf2d9d4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-exit.js @@ -0,0 +1,49 @@ +/** + * Patches console methods to exit the workUnitAsyncStorage so that inside the host implementation + * sync IO can be called. This is relevant for example with runtimes that patch console methods to + * prepend a timestamp to the log output. + * + * Note that this will only exit for already installed patched console methods. If you further patch + * the console method after this and add any sync IO there it will trigger sync IO warnings while prerendering. + * + * This is a pragmatic concession because layering the patches if you install your own log implementation + * after they are installed is very tricky to do correctly because the order matters + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +function patchConsoleMethod(methodName) { + const descriptor = Object.getOwnPropertyDescriptor(console, methodName); + if (descriptor && (descriptor.configurable || descriptor.writable) && typeof descriptor.value === 'function') { + const originalMethod = descriptor.value; + const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name'); + let wrapperMethod = function(...args) { + return _workunitasyncstorageexternal.workUnitAsyncStorage.exit(()=>originalMethod.apply(console, args)); + }; + if (originalName) { + Object.defineProperty(wrapperMethod, 'name', originalName); + } + Object.defineProperty(console, methodName, { + value: wrapperMethod + }); + } +} +// We patch the same methods that React and our dev patch do. +// We may find other methods that could benefit from patching but if +// they exist we ought to consider patching them in all three places +patchConsoleMethod('error'); +patchConsoleMethod('assert'); +patchConsoleMethod('debug'); +patchConsoleMethod('dir'); +patchConsoleMethod('dirxml'); +patchConsoleMethod('group'); +patchConsoleMethod('groupCollapsed'); +patchConsoleMethod('groupEnd'); +patchConsoleMethod('info'); +patchConsoleMethod('log'); +patchConsoleMethod('table'); +patchConsoleMethod('trace'); +patchConsoleMethod('warn'); + +//# sourceMappingURL=console-exit.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-exit.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-exit.js.map new file mode 100644 index 0000000000000000000000000000000000000000..29c2bc53adf13e2d4473356c41c7238dbec68146 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-exit.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/console-exit.tsx"],"sourcesContent":["/**\n * Patches console methods to exit the workUnitAsyncStorage so that inside the host implementation\n * sync IO can be called. This is relevant for example with runtimes that patch console methods to\n * prepend a timestamp to the log output.\n *\n * Note that this will only exit for already installed patched console methods. If you further patch\n * the console method after this and add any sync IO there it will trigger sync IO warnings while prerendering.\n *\n * This is a pragmatic concession because layering the patches if you install your own log implementation\n * after they are installed is very tricky to do correctly because the order matters\n */\n\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\n\ntype ConsoleMethodName = keyof Console\n\nfunction patchConsoleMethod(methodName: ConsoleMethodName): void {\n const descriptor = Object.getOwnPropertyDescriptor(console, methodName)\n if (\n descriptor &&\n (descriptor.configurable || descriptor.writable) &&\n typeof descriptor.value === 'function'\n ) {\n const originalMethod = descriptor.value\n const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')\n let wrapperMethod = function (...args: any[]) {\n return workUnitAsyncStorage.exit(() =>\n originalMethod.apply(console, args)\n )\n }\n if (originalName) {\n Object.defineProperty(wrapperMethod, 'name', originalName)\n }\n Object.defineProperty(console, methodName, {\n value: wrapperMethod,\n })\n }\n}\n\n// We patch the same methods that React and our dev patch do.\n// We may find other methods that could benefit from patching but if\n// they exist we ought to consider patching them in all three places\npatchConsoleMethod('error')\npatchConsoleMethod('assert')\npatchConsoleMethod('debug')\npatchConsoleMethod('dir')\npatchConsoleMethod('dirxml')\npatchConsoleMethod('group')\npatchConsoleMethod('groupCollapsed')\npatchConsoleMethod('groupEnd')\npatchConsoleMethod('info')\npatchConsoleMethod('log')\npatchConsoleMethod('table')\npatchConsoleMethod('trace')\npatchConsoleMethod('warn')\n"],"names":["patchConsoleMethod","methodName","descriptor","Object","getOwnPropertyDescriptor","console","configurable","writable","value","originalMethod","originalName","wrapperMethod","args","workUnitAsyncStorage","exit","apply","defineProperty"],"mappings":"AAAA;;;;;;;;;;CAUC;;;;8CAEoC;AAIrC,SAASA,mBAAmBC,UAA6B;IACvD,MAAMC,aAAaC,OAAOC,wBAAwB,CAACC,SAASJ;IAC5D,IACEC,cACCA,CAAAA,WAAWI,YAAY,IAAIJ,WAAWK,QAAQ,AAAD,KAC9C,OAAOL,WAAWM,KAAK,KAAK,YAC5B;QACA,MAAMC,iBAAiBP,WAAWM,KAAK;QACvC,MAAME,eAAeP,OAAOC,wBAAwB,CAACK,gBAAgB;QACrE,IAAIE,gBAAgB,SAAU,GAAGC,IAAW;YAC1C,OAAOC,kDAAoB,CAACC,IAAI,CAAC,IAC/BL,eAAeM,KAAK,CAACV,SAASO;QAElC;QACA,IAAIF,cAAc;YAChBP,OAAOa,cAAc,CAACL,eAAe,QAAQD;QAC/C;QACAP,OAAOa,cAAc,CAACX,SAASJ,YAAY;YACzCO,OAAOG;QACT;IACF;AACF;AAEA,6DAA6D;AAC7D,oEAAoE;AACpE,oEAAoE;AACpEX,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB;AACnBA,mBAAmB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-file.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-file.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-file.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-file.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-file.js new file mode 100644 index 0000000000000000000000000000000000000000..0096412f8c43fb4178942fd3a2d2aab6028f0223 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-file.js @@ -0,0 +1,56 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _consoleasyncstorageexternal = require("../app-render/console-async-storage.external"); +const _filelogger = require("../dev/browser-logs/file-logger"); +const _console = require("../../client/lib/console"); +// Based on https://github.com/facebook/react/blob/28dc0776be2e1370fe217549d32aee2519f0cf05/packages/react-server/src/ReactFlightServer.js#L248 +function patchConsoleMethodDEV(methodName) { + const descriptor = Object.getOwnPropertyDescriptor(console, methodName); + if (descriptor && (descriptor.configurable || descriptor.writable) && typeof descriptor.value === 'function') { + const originalMethod = descriptor.value; + const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name'); + const wrapperMethod = function(...args) { + const consoleStore = _consoleasyncstorageexternal.consoleAsyncStorage.getStore(); + if ((consoleStore == null ? void 0 : consoleStore.dim) === true) { + // In this context the log args are already dimmed. We use the console store + // to decide if this log is ignorable for reporting in our file logger. + return originalMethod.apply(this, args); + } else { + const ret = originalMethod.apply(this, args); + const fileLogger = (0, _filelogger.getFileLogger)(); + const message = (0, _console.formatConsoleArgs)(args); + // Strip ANSI escape codes for file logging + // eslint-disable-next-line no-control-regex + const ansiEscapeRegex = new RegExp('\u001b\\[[0-9;]*m', 'g'); + const cleanMessage = message.replace(ansiEscapeRegex, ''); + fileLogger.logServer(methodName.toUpperCase(), cleanMessage); + return ret; + } + }; + if (originalName) { + Object.defineProperty(wrapperMethod, 'name', originalName); + } + Object.defineProperty(console, methodName, { + value: wrapperMethod + }); + } +} +if (process.env.NODE_ENV === 'development') { + patchConsoleMethodDEV('error'); + patchConsoleMethodDEV('assert'); + patchConsoleMethodDEV('debug'); + patchConsoleMethodDEV('dir'); + patchConsoleMethodDEV('dirxml'); + patchConsoleMethodDEV('group'); + patchConsoleMethodDEV('groupCollapsed'); + patchConsoleMethodDEV('groupEnd'); + patchConsoleMethodDEV('info'); + patchConsoleMethodDEV('log'); + patchConsoleMethodDEV('table'); + patchConsoleMethodDEV('trace'); + patchConsoleMethodDEV('warn'); +} + +//# sourceMappingURL=console-file.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-file.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-file.js.map new file mode 100644 index 0000000000000000000000000000000000000000..41bef2e405b69d17d9119bf39b06d1203a3d0911 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/console-file.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/console-file.tsx"],"sourcesContent":["import { consoleAsyncStorage } from '../app-render/console-async-storage.external'\nimport { getFileLogger } from '../dev/browser-logs/file-logger'\nimport { formatConsoleArgs } from '../../client/lib/console'\n\ntype InterceptableConsoleMethod =\n | 'error'\n | 'assert'\n | 'debug'\n | 'dir'\n | 'dirxml'\n | 'group'\n | 'groupCollapsed'\n | 'groupEnd'\n | 'info'\n | 'log'\n | 'table'\n | 'trace'\n | 'warn'\n\n// Based on https://github.com/facebook/react/blob/28dc0776be2e1370fe217549d32aee2519f0cf05/packages/react-server/src/ReactFlightServer.js#L248\nfunction patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void {\n const descriptor = Object.getOwnPropertyDescriptor(console, methodName)\n if (\n descriptor &&\n (descriptor.configurable || descriptor.writable) &&\n typeof descriptor.value === 'function'\n ) {\n const originalMethod = descriptor.value\n const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')\n const wrapperMethod = function (this: typeof console, ...args: any[]) {\n const consoleStore = consoleAsyncStorage.getStore()\n\n if (consoleStore?.dim === true) {\n // In this context the log args are already dimmed. We use the console store\n // to decide if this log is ignorable for reporting in our file logger.\n return originalMethod.apply(this, args)\n } else {\n const ret = originalMethod.apply(this, args)\n\n const fileLogger = getFileLogger()\n const message = formatConsoleArgs(args)\n // Strip ANSI escape codes for file logging\n // eslint-disable-next-line no-control-regex\n const ansiEscapeRegex = new RegExp('\\u001b\\\\[[0-9;]*m', 'g')\n const cleanMessage = message.replace(ansiEscapeRegex, '')\n fileLogger.logServer(methodName.toUpperCase(), cleanMessage)\n return ret\n }\n }\n if (originalName) {\n Object.defineProperty(wrapperMethod, 'name', originalName)\n }\n Object.defineProperty(console, methodName, {\n value: wrapperMethod,\n })\n }\n}\n\nif (process.env.NODE_ENV === 'development') {\n patchConsoleMethodDEV('error')\n patchConsoleMethodDEV('assert')\n patchConsoleMethodDEV('debug')\n patchConsoleMethodDEV('dir')\n patchConsoleMethodDEV('dirxml')\n patchConsoleMethodDEV('group')\n patchConsoleMethodDEV('groupCollapsed')\n patchConsoleMethodDEV('groupEnd')\n patchConsoleMethodDEV('info')\n patchConsoleMethodDEV('log')\n patchConsoleMethodDEV('table')\n patchConsoleMethodDEV('trace')\n patchConsoleMethodDEV('warn')\n}\n"],"names":["patchConsoleMethodDEV","methodName","descriptor","Object","getOwnPropertyDescriptor","console","configurable","writable","value","originalMethod","originalName","wrapperMethod","args","consoleStore","consoleAsyncStorage","getStore","dim","apply","ret","fileLogger","getFileLogger","message","formatConsoleArgs","ansiEscapeRegex","RegExp","cleanMessage","replace","logServer","toUpperCase","defineProperty","process","env","NODE_ENV"],"mappings":";;;;6CAAoC;4BACN;yBACI;AAiBlC,+IAA+I;AAC/I,SAASA,sBAAsBC,UAAsC;IACnE,MAAMC,aAAaC,OAAOC,wBAAwB,CAACC,SAASJ;IAC5D,IACEC,cACCA,CAAAA,WAAWI,YAAY,IAAIJ,WAAWK,QAAQ,AAAD,KAC9C,OAAOL,WAAWM,KAAK,KAAK,YAC5B;QACA,MAAMC,iBAAiBP,WAAWM,KAAK;QACvC,MAAME,eAAeP,OAAOC,wBAAwB,CAACK,gBAAgB;QACrE,MAAME,gBAAgB,SAAgC,GAAGC,IAAW;YAClE,MAAMC,eAAeC,gDAAmB,CAACC,QAAQ;YAEjD,IAAIF,CAAAA,gCAAAA,aAAcG,GAAG,MAAK,MAAM;gBAC9B,4EAA4E;gBAC5E,uEAAuE;gBACvE,OAAOP,eAAeQ,KAAK,CAAC,IAAI,EAAEL;YACpC,OAAO;gBACL,MAAMM,MAAMT,eAAeQ,KAAK,CAAC,IAAI,EAAEL;gBAEvC,MAAMO,aAAaC,IAAAA,yBAAa;gBAChC,MAAMC,UAAUC,IAAAA,0BAAiB,EAACV;gBAClC,2CAA2C;gBAC3C,4CAA4C;gBAC5C,MAAMW,kBAAkB,IAAIC,OAAO,qBAAqB;gBACxD,MAAMC,eAAeJ,QAAQK,OAAO,CAACH,iBAAiB;gBACtDJ,WAAWQ,SAAS,CAAC1B,WAAW2B,WAAW,IAAIH;gBAC/C,OAAOP;YACT;QACF;QACA,IAAIR,cAAc;YAChBP,OAAO0B,cAAc,CAAClB,eAAe,QAAQD;QAC/C;QACAP,OAAO0B,cAAc,CAACxB,SAASJ,YAAY;YACzCO,OAAOG;QACT;IACF;AACF;AAEA,IAAImB,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;IAC1ChC,sBAAsB;IACtBA,sBAAsB;IACtBA,sBAAsB;IACtBA,sBAAsB;IACtBA,sBAAsB;IACtBA,sBAAsB;IACtBA,sBAAsB;IACtBA,sBAAsB;IACtBA,sBAAsB;IACtBA,sBAAsB;IACtBA,sBAAsB;IACtBA,sBAAsB;IACtBA,sBAAsB;AACxB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/date.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/date.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/date.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/date.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/date.js new file mode 100644 index 0000000000000000000000000000000000000000..b8ff756af49124c7a79fa3d6a380fe82ae30a2a1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/date.js @@ -0,0 +1,52 @@ +/** + * We extend `Date` during builds and revalidates to ensure that prerenders don't observe the clock as a source of IO + * When cacheComponents is enabled. The current time is a form of IO even though it resolves synchronously. When cacheComponents is + * enabled we need to ensure that clock time is excluded from prerenders unless it is cached. + * + * There is tension here because time is used for both output and introspection. While arbitrary we intend to reserve + * `Date` for output use cases and `performance` for introspection use cases. If you want to measure + * how long something takes use `performance.timeOrigin` and `performance.now()` rather than `Date.now()` for instance. + * + * The extensions here never error nor alter the underlying Date objects, strings, and numbers created and thus should be transparent to callers. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _ioutils = require("./io-utils"); +function createNow(originalNow) { + return ({ + now: function now() { + (0, _ioutils.io)('`Date.now()`', 'time'); + return originalNow(); + } + })['now'.slice()].bind(null); +} +function createDate(originalConstructor) { + const properties = Object.getOwnPropertyDescriptors(originalConstructor); + properties.now.value = createNow(originalConstructor.now); + const apply = Reflect.apply; + const construct = Reflect.construct; + const newConstructor = Object.defineProperties(// Ideally this should not minify the name. + function Date1() { + if (new.target === undefined) { + (0, _ioutils.io)('`Date()`', 'time'); + return apply(originalConstructor, undefined, arguments); + } + if (arguments.length === 0) { + (0, _ioutils.io)('`new Date()`', 'time'); + } + return construct(originalConstructor, arguments, new.target); + }, properties); + Object.defineProperty(originalConstructor.prototype, 'constructor', { + value: newConstructor + }); + return newConstructor; +} +try { + // eslint-disable-next-line no-native-reassign + Date = createDate(Date); +} catch { + console.error('Failed to install `Date` class extension. When using `cacheComponents`, APIs that read the current time will not correctly trigger dynamic behavior.'); +} + +//# sourceMappingURL=date.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/date.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/date.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ca7c1b53edfe49ae13b60a32b56c217d26fd2c8a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/date.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/date.tsx"],"sourcesContent":["/**\n * We extend `Date` during builds and revalidates to ensure that prerenders don't observe the clock as a source of IO\n * When cacheComponents is enabled. The current time is a form of IO even though it resolves synchronously. When cacheComponents is\n * enabled we need to ensure that clock time is excluded from prerenders unless it is cached.\n *\n * There is tension here because time is used for both output and introspection. While arbitrary we intend to reserve\n * `Date` for output use cases and `performance` for introspection use cases. If you want to measure\n * how long something takes use `performance.timeOrigin` and `performance.now()` rather than `Date.now()` for instance.\n *\n * The extensions here never error nor alter the underlying Date objects, strings, and numbers created and thus should be transparent to callers.\n */\nimport { io } from './io-utils'\n\nfunction createNow(originalNow: typeof Date.now) {\n return {\n now: function now() {\n io('`Date.now()`', 'time')\n return originalNow()\n },\n }['now'.slice() as 'now'].bind(null)\n}\n\nfunction createDate(originalConstructor: typeof Date): typeof Date {\n const properties = Object.getOwnPropertyDescriptors(originalConstructor)\n properties.now.value = createNow(originalConstructor.now)\n\n const apply = Reflect.apply\n const construct = Reflect.construct\n\n const newConstructor = Object.defineProperties(\n // Ideally this should not minify the name.\n function Date() {\n if (new.target === undefined) {\n io('`Date()`', 'time')\n return apply(originalConstructor, undefined, arguments)\n }\n if (arguments.length === 0) {\n io('`new Date()`', 'time')\n }\n return construct(originalConstructor, arguments, new.target)\n },\n properties\n )\n Object.defineProperty(originalConstructor.prototype, 'constructor', {\n value: newConstructor,\n })\n return newConstructor as typeof Date\n}\n\ntry {\n // eslint-disable-next-line no-native-reassign\n Date = createDate(Date)\n} catch {\n console.error(\n 'Failed to install `Date` class extension. When using `cacheComponents`, APIs that read the current time will not correctly trigger dynamic behavior.'\n )\n}\n"],"names":["createNow","originalNow","now","io","slice","bind","createDate","originalConstructor","properties","Object","getOwnPropertyDescriptors","value","apply","Reflect","construct","newConstructor","defineProperties","Date","undefined","arguments","length","defineProperty","prototype","console","error"],"mappings":"AAAA;;;;;;;;;;CAUC;;;;yBACkB;AAEnB,SAASA,UAAUC,WAA4B;IAC7C,OAAO,CAAA;QACLC,KAAK,SAASA;YACZC,IAAAA,WAAE,EAAC,gBAAgB;YACnB,OAAOF;QACT;IACF,CAAA,CAAC,CAAC,MAAMG,KAAK,GAAY,CAACC,IAAI,CAAC;AACjC;AAEA,SAASC,WAAWC,mBAAgC;IAClD,MAAMC,aAAaC,OAAOC,yBAAyB,CAACH;IACpDC,WAAWN,GAAG,CAACS,KAAK,GAAGX,UAAUO,oBAAoBL,GAAG;IAExD,MAAMU,QAAQC,QAAQD,KAAK;IAC3B,MAAME,YAAYD,QAAQC,SAAS;IAEnC,MAAMC,iBAAiBN,OAAOO,gBAAgB,CAC5C,2CAA2C;IAC3C,SAASC;QACP,IAAI,eAAeC,WAAW;YAC5Bf,IAAAA,WAAE,EAAC,YAAY;YACf,OAAOS,MAAML,qBAAqBW,WAAWC;QAC/C;QACA,IAAIA,UAAUC,MAAM,KAAK,GAAG;YAC1BjB,IAAAA,WAAE,EAAC,gBAAgB;QACrB;QACA,OAAOW,UAAUP,qBAAqBY,WAAW;IACnD,GACAX;IAEFC,OAAOY,cAAc,CAACd,oBAAoBe,SAAS,EAAE,eAAe;QAClEX,OAAOI;IACT;IACA,OAAOA;AACT;AAEA,IAAI;IACF,8CAA8C;IAC9CE,OAAOX,WAAWW;AACpB,EAAE,OAAM;IACNM,QAAQC,KAAK,CACX;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/error-inspect.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/error-inspect.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/error-inspect.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/error-inspect.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/error-inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..0ae3287dc02f23b11ba5f65caf7ac99baa303fb0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/error-inspect.js @@ -0,0 +1,8 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _patcherrorinspect = require("../patch-error-inspect"); +(0, _patcherrorinspect.patchErrorInspectNodeJS)(globalThis.Error); + +//# sourceMappingURL=error-inspect.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/error-inspect.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/error-inspect.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bf7015f0fad537c0b1d014dead0001f127aa0c6a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/error-inspect.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/error-inspect.tsx"],"sourcesContent":["import { patchErrorInspectNodeJS } from '../patch-error-inspect'\n\npatchErrorInspectNodeJS(globalThis.Error)\n"],"names":["patchErrorInspectNodeJS","globalThis","Error"],"mappings":";;;;mCAAwC;AAExCA,IAAAA,0CAAuB,EAACC,WAAWC,KAAK","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..26db0a67176db70a5bcb4c2db4e8a1a270e61507 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.d.ts @@ -0,0 +1,103 @@ +declare const originalSetImmediate: typeof setImmediate; +/** + * **WARNING: This function changes the usual behavior of the event loop!** + * **Be VERY careful about where you call it.** + * + * Starts capturing calls to `setImmediate` to run them as "fast immediates". + * All calls captured in this way will be executed after the current task + * (after callbacks from `process.nextTick()`, microtasks, and nextTicks scheduled from microtasks). + * This function needs to be called again in each task that needs the + * "fast immediates" behavior. + * + * ### Motivation + * + * We don't want `setImmediate` to be considered IO in Cache Components. + * To achieve this in a staged (pre)render, we want to allow immediates scheduled + * in stage N to run before stage N+1. + * Since we schedule stages using sequential `setTimeout`, this isn't possible without + * intercepting `setImmediate` and doing the scheduling on our own. + * We refer to this as a "fast immediate". + * + * Notably, this affects React's `scheduleWork` in render, which uses `setImmediate`. + * This is desirable -- if async work was scheduled during a stage, then it should + * get to run before we finish that stage. + * + * ### Example + * + * ```ts + * setTimeout(() => { + * runPendingImmediatesAfterCurrentTask() + * console.log("timeout 1") + * setImmediate(() => { + * console.log("immediate!!!") + * }) + * }) + * setTimeout(() => { + * console.log("timeout 2") + * }) + * ``` + * will print + * + * ``` + * timeout 1 + * immediate!!! + * timeout 2 + * ``` + * + * instead of the usual order + * ``` + * timeout 1 + * timeout 2 + * immediate!!! + * ``` + * > **NOTE** + * > The above is *most common* order, but it's not guaranteed. + * > Under some circumstances (e.g. when the event loop is blocked on CPU work), + * > Node will reorder things and run the immediate before timeout 2. + * > So, in a sense, we're just making this reordering happen consistently. + * + * Recursive `setImmediate` calls will also be executed as "fast immediates". + * If multiple immediates were scheduled, `process.nextTick()` (and associated microtasks) + * will be allowed to execute between them. + * See the unit tests for more examples. + * */ +export declare function DANGEROUSLY_runPendingImmediatesAfterCurrentTask(): void; +/** + * This should always be called a task after `DANGEROUSLY_runPendingImmediatesAfterCurrentTask` + * to make sure that everything executed as expected and we're not left in an inconsistent state. + * Ideally, this wouldn't be necessary, but we're not in control of the event loop + * and need to guard against unexpected behaviors not forseen in this implementation, + * so we have to be defensive. + */ +export declare function expectNoPendingImmediates(): void; +export { originalSetImmediate as unpatchedSetImmediate }; +/** + * Run a callback and its async work with this native-immediate tracker. + */ +export declare function runWithNativeImmediateTracking(tracker: ImmediateTracker, callback: (...args: TArgs) => TResult, ...args: TArgs): TResult; +/** + * Tracks native immediates for one render's async scope without changing their + * scheduling. + * + * A sentinel notifies idle subscribers after the last tracked immediate and its + * microtasks and nextTicks finish. New native immediates postpone notification. + * + * Subscribers can cancel their wait without stopping tracking. Tracking + * continues between subscriptions, including when asynchronous cache reads + * resume the render. + */ +export declare class ImmediateTracker { + private sentinel; + private needsAnotherCheck; + private listeners; + hasPendingImmediates(): boolean; + /** + * Calls `callback` asynchronously in a native immediate, even when no + * immediates are pending. The callback runs in the subscriber's async + * context. The returned function cancels the subscription without stopping + * tracking. + */ + onIdle(callback: () => void): () => void; + scheduleIdleCheck(): void; + private checkForIdle; +} diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.js new file mode 100644 index 0000000000000000000000000000000000000000..16ee3506512d04539bed8692eb8e3a731febe278 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.js @@ -0,0 +1,630 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + DANGEROUSLY_runPendingImmediatesAfterCurrentTask: null, + ImmediateTracker: null, + expectNoPendingImmediates: null, + runWithNativeImmediateTracking: null, + unpatchedSetImmediate: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + DANGEROUSLY_runPendingImmediatesAfterCurrentTask: function() { + return DANGEROUSLY_runPendingImmediatesAfterCurrentTask; + }, + ImmediateTracker: function() { + return ImmediateTracker; + }, + expectNoPendingImmediates: function() { + return expectNoPendingImmediates; + }, + runWithNativeImmediateTracking: function() { + return runWithNativeImmediateTracking; + }, + unpatchedSetImmediate: function() { + return originalSetImmediate; + } +}); +const _nodeutil = require("node:util"); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _asynclocalstorage = require("../app-render/async-local-storage"); +var ExecutionState = /*#__PURE__*/ function(ExecutionState) { + ExecutionState[ExecutionState["Waiting"] = 1] = "Waiting"; + ExecutionState[ExecutionState["Working"] = 2] = "Working"; + ExecutionState[ExecutionState["Finished"] = 3] = "Finished"; + ExecutionState[ExecutionState["Abandoned"] = 4] = "Abandoned"; + return ExecutionState; +}(ExecutionState || {}); +const FAST_SET_IMMEDIATE_ORIGINALS_KEY = Symbol.for('next.fast-set-immediate.originals'); +// Re-evaluations in dev should always use the same base/original functions. +const originals = globalThis[FAST_SET_IMMEDIATE_ORIGINALS_KEY] ?? (globalThis[FAST_SET_IMMEDIATE_ORIGINALS_KEY] = { + setImmediate: globalThis.setImmediate, + clearImmediate: globalThis.clearImmediate, + nextTick: process.nextTick +}); +let wasEnabledAtLeastOnce = false; +let pendingNextTicks = 0; +let currentExecution = null; +const originalSetImmediate = originals.setImmediate; +const originalClearImmediate = originals.clearImmediate; +const originalNextTick = originals.nextTick; +const originalSetImmediatePromisify = typeof originalSetImmediate === 'function' ? originalSetImmediate[_nodeutil.promisify.custom] : // and won't ever enable the patch, so this can be a dummy value +undefined; +function install() { + if (process.env.NEXT_RUNTIME === 'edge') { + // Nothing to patch. The exported functions all error if used in the edge runtime, + // so we're not going to violate any assumptions by not patching. + return; + } else { + debug == null ? void 0 : debug('installing fast setImmediate patch'); + const nodeTimers = require('node:timers'); + globalThis.setImmediate = nodeTimers.setImmediate = // Workaround for missing __promisify__ which is not a real property + patchedSetImmediate; + globalThis.clearImmediate = nodeTimers.clearImmediate = patchedClearImmediate; + const nodeTimersPromises = require('node:timers/promises'); + nodeTimersPromises.setImmediate = patchedSetImmediatePromise; + process.nextTick = patchedNextTick; + } +} +function DANGEROUSLY_runPendingImmediatesAfterCurrentTask() { + if (process.env.NEXT_RUNTIME === 'edge') { + throw new _invarianterror.InvariantError('DANGEROUSLY_runPendingImmediatesAfterCurrentTask cannot be called in the edge runtime'); + } else { + const execution = startCapturingImmediates(); + try { + scheduleWorkAfterNextTicksAndMicrotasks(execution); + } catch (err) { + // If this error comes from a bail() call, rethrow it. + if (execution.state === 4) { + throw err; + } + // Otherwise, bail out here. + bail(execution, new _invarianterror.InvariantError('An unexpected error occurred while starting to capture immediates', { + cause: err + })); + } + } +} +function expectNoPendingImmediates() { + if (process.env.NEXT_RUNTIME === 'edge') { + throw new _invarianterror.InvariantError('expectNoPendingImmediates cannot be called in the edge runtime'); + } else { + if (currentExecution !== null) { + bail(currentExecution, new _invarianterror.InvariantError(`Expected all captured immediates to have been executed (state: ${ExecutionState[currentExecution.state]})`)); + } + } +} +const immediateAsyncStorage = (0, _asynclocalstorage.getOrCreateGlobalAsyncLocalStorage)('immediate-async-storage'); +function runWithNativeImmediateTracking(tracker, callback, ...args) { + return immediateAsyncStorage.run(tracker, callback, ...args); +} +class ImmediateTracker { + hasPendingImmediates() { + return this.sentinel !== null; + } + /** + * Calls `callback` asynchronously in a native immediate, even when no + * immediates are pending. The callback runs in the subscriber's async + * context. The returned function cancels the subscription without stopping + * tracking. + */ onIdle(callback) { + const listeners = this.listeners; + const listener = (0, _asynclocalstorage.bindSnapshot)(callback); + listeners.add(listener); + if (this.sentinel === null) { + this.scheduleIdleCheck(); + } else { + this.sentinel.ref(); + } + return ()=>{ + listeners.delete(listener); + if (this.listeners.size === 0) { + var _this_sentinel; + (_this_sentinel = this.sentinel) == null ? void 0 : _this_sentinel.unref(); + } + }; + } + scheduleIdleCheck() { + if (this.sentinel !== null) { + // New immediates are queued after the pending sentinel. Record that + // `checkForIdle` must check again before notifying subscribers. Further + // scheduling calls reuse this flag and the pending sentinel. + // + // Node's uncaught-exception recovery can also reach this branch: + // + // 1. We queue immediate `A`, then sentinel `S`: `[A, S]`. + // 2. `A` throws and interrupts Node's immediate-processing loop, + // leaving `S` first in Node's outstanding queue. + // 3. An uncaughtException handler handles the error, so Node continues. + // 4. Node calls `timers.setImmediate(noop)` for another immediate cycle. + // 5. Our patch runs before async-context cleanup and sees `A`'s tracker. + // 6. The tracker finds `S` still pending. + // + // Node schedules this no-op after any handled uncaught exception so + // pending ticks get another chance to run. After exception handling + // returns, Node's C++ dispatcher retries the outstanding queue in the + // same check phase, before the no-op runs. + // + // On Node 20, clearing `S` here leaves the outstanding queue's head + // pointing to a destroyed immediate. When Node retries the queue, it + // tries to skip the cleared entry through its predecessor. The first + // entry has no predecessor, so recovery throws another exception. Keep + // `S` queued and record that another check is needed instead. + this.needsAnotherCheck = true; + return; + } + this.sentinel = originalSetImmediate(this.checkForIdle); + if (this.listeners.size === 0) { + this.sentinel.unref(); + } + } + constructor(){ + this.sentinel = null; + this.needsAnotherCheck = false; + this.listeners = new Set(); + this.checkForIdle = ()=>{ + this.sentinel = null; + if (this.needsAnotherCheck) { + // Schedule the next check after the immediates queued since this + // sentinel. Their callbacks and microtasks/nextTicks can then run before + // we notify idle subscribers. A synchronous burst shares this next check. + this.needsAnotherCheck = false; + this.scheduleIdleCheck(); + return; + } + const listeners = this.listeners; + this.listeners = new Set(); + for (const callback of listeners){ + listeners.delete(callback); + callback(); + } + }; + } +} +/** + * Wait until all nextTicks and microtasks spawned from the current task are done, + * then execute any immediates that they queued. + * */ function scheduleWorkAfterNextTicksAndMicrotasks(execution) { + if (execution.state !== 1) { + throw new _invarianterror.InvariantError(`scheduleWorkAfterTicksAndMicrotasks can only be called while waiting (state: ${ExecutionState[execution.state]})`); + } + // We want to execute "fast immediates" after all the nextTicks and microtasks + // spawned from the current task are done. + // The ordering here is: + // + // 1. sync code + // 2. process.nextTick (scheduled from sync code, or from one of these nextTicks) + // 3. microtasks + // 4. process.nextTick (scheduled from microtasks, e.g. `queueMicrotask(() => process.nextTick(callback))`) + // + // We want to run to run in step 4, because that's the latest point before the next tick. + // However, there might also be other callbacks scheduled to run in that step. + // But importantly, they had to be scheduled using a `process.nextTick`, + // so we can detect them by checking if `pendingNextTicks > 0`. + // In that case, we'll just reschedule ourselves in the same way again to let them run first. + // (this process can theoretically repeat multiple times, hence the recursion). + queueMicrotask(()=>{ + // (note that this call won't increment `pendingNextTicks`, + // only the patched `process.nextTick` does that, so this won't loop infinitely) + originalNextTick(()=>{ + // We're now in a nextTick, which means that we're executing inside `processTicksAndRejections`: + // https://github.com/nodejs/node/blob/d546e7fd0bc3cbb4bcc2baae6f3aa44d2e81a413/lib/internal/process/task_queues.js#L84 + // All the work scheduled here will happen within that `processTicksAndRejections` loop. + // Reading the source of `processTicksAndRejections` can help understand the timing here -- + // All we're really doing is strategically pushing callbacks into the two queues + // (nextTicks and microtasks) that that function is currently looping over. + try { + if (execution.state === 4 || currentExecution !== execution) { + debug == null ? void 0 : debug(`scheduler :: the execution was abandoned`); + return; + } + if (pendingNextTicks > 0) { + // Other nextTicks have been scheduled. Let those run first, then try again -- + // we're simulating a event loop task, so all nextTicks should be exhausted before we execute. + debug == null ? void 0 : debug(`scheduler :: yielding to ${pendingNextTicks} nextTicks`); + return scheduleWorkAfterNextTicksAndMicrotasks(execution); + } + // There's no other nextTicks, we're the last one, so we're about to move on to the next task (likely a timer). + // Now, we can try and execute any queued immediates. + return performWork(execution); + } catch (err) { + // If this error comes from a bail() call, rethrow it. + // typescript can't tell that the state might've been mutated + // and the narrowing from above is no longer valid + const executionAfterWork = execution; + if (executionAfterWork.state === 4) { + throw err; + } + // Otherwise, bail out here (which will trigger an uncaught exception) + // Note that we're using the same microtask trick as `safelyRunNextTickCallback`. + queueMicrotask(()=>{ + bail(execution, new _invarianterror.InvariantError('An unexpected error occurred while executing immediates', { + cause: err + })); + }); + } + }); + }); +} +/** Execute one immediate, and schedule a check for more (in case there's others in the queue) */ function performWork(execution) { + if (execution.state === 4) { + return; + } + debug == null ? void 0 : debug(`scheduler :: performing work`); + if (execution.state !== 1) { + throw new _invarianterror.InvariantError(`performWork can only be called while waiting (state: ${ExecutionState[execution.state]})`); + } + execution.state = 2; + const queueItem = takeNextActiveQueueItem(execution); + if (queueItem === null) { + debug == null ? void 0 : debug(`scheduler :: no immediates queued, exiting`); + stopCapturingImmediates(execution); + return; + } + debug == null ? void 0 : debug(`scheduler :: executing queued immediate`); + const { immediateObject, callback, args } = queueItem; + immediateObject[INTERNALS].queueItem = null; + clearQueueItem(queueItem); + // Execute the immediate. + // If a sync error was thrown in the immediate, we want to trigger a `uncaughtException`. + // However, we're executing in a nextTick, and if a nextTick callback errors, + // It'll break out of `processTicksAndRejections` (note the lack of a `catch` block): + // https://github.com/nodejs/node/blob/d546e7fd0bc3cbb4bcc2baae6f3aa44d2e81a413/lib/internal/process/task_queues.js#L81-L97 + // Meaning that the event loop will stop executing nextTicks and move on to the next timer + // (or other phase of the event loop, but we expect to be running in a sequence of timers here). + // Then, the remaining ticks will run after that timer, since they're still in the queue. + // + // This would completely break the timing we're trying to achieve here -- + // The point of this patch is to execute immediates before the next timer! + // So, we need to work around this behavior. (both here and in our `process.nextTick` patch). + // + // We can sidestep this by catching the synchronous error and rethrowing it in a microtask. + // (NOTE: if we use `queueMicrotask`, it'll trigger `uncaughtException`, not `unhandledRejection`, + // because there's no promise being rejected.) + // + // This will make `uncaughtException` happen: + // - Before the next fast immediate (`scheduleWorkAfterNextTicksAndMicrotasks` also uses `queueMicrotask`). + // This is good, and matches usual observable behavior of immediates. + // - AFTER nextTicks scheduled from the immediate itself. + // This deviates from native setImmediate, which would call `uncaughtException` first, + // and skip ahead to the next task as explained above. + // + // This is technically an observable difference in behavior, but it seems niche enough that + // it shouldn't cause problems -- we don't expect user code to use `uncaughtException` for control flow, + // only error reporting, so subtly changing the timing shouldn't matter. + let didThrow = false; + let thrownValue = undefined; + queueMicrotask(()=>{ + if (didThrow) { + debug == null ? void 0 : debug('scheduler :: rethrowing sync error from immediate in microtask'); + throw thrownValue; + } + }); + try { + if (args !== null) { + callback.apply(null, args); + } else { + callback(); + } + } catch (err) { + // We'll rethrow the error in the microtask above. + didThrow = true; + thrownValue = err; + } + // Schedule the loop again in case there's more immediates after this one. + // Note that we can't just check if the queue is empty now, because new immediates + // might still be scheduled asynchronously, from an upcoming nextTick or microtask. + execution.state = 1; + scheduleWorkAfterNextTicksAndMicrotasks(execution); +} +function takeNextActiveQueueItem(execution) { + // Find the first (if any) queued immediate that wasn't cleared. + // We don't remove immediates from the array when they're cleared, + // so this requires some legwork to exclude (and possibly drop) cleared items. + const { queuedImmediates } = execution; + let firstActiveItem = null; + let firstActiveItemIndex = -1; + for(let i = 0; i < queuedImmediates.length; i++){ + const item = queuedImmediates[i]; + if (!item.isCleared) { + firstActiveItem = item; + firstActiveItemIndex = i; + break; + } + } + if (firstActiveItem === null) { + // We didn't find an active item. + // If the queue isn't empty, then it must only contain cleared items. Empty it. + if (queuedImmediates.length > 0) { + queuedImmediates.length = 0; + } + return null; + } + // Remove all items up to and including `nextActiveItemIndex` from the queue. + // (if it's not the first item, then it must be preceded by cleared items, which we want to drop anyway) + if (firstActiveItemIndex === 0) { + // Fast path - drop the first item + // (`splice` creates a result array for the removed items, so this is more efficient) + queuedImmediates.shift(); + } else { + queuedImmediates.splice(0, firstActiveItemIndex + 1); + } + return firstActiveItem; +} +function startCapturingImmediates() { + if (currentExecution !== null) { + bail(currentExecution, new _invarianterror.InvariantError(`Cannot start capturing immediates again without finishing the previous task (state: ${ExecutionState[currentExecution.state]})`)); + } + wasEnabledAtLeastOnce = true; + const execution = { + state: 1, + queuedImmediates: [] + }; + currentExecution = execution; + return execution; +} +function stopCapturingImmediates(execution) { + if (execution.state === 4) { + return; + } + // This check enforces that we run performWork at least once before stopping + // to make sure that we've waited for all the nextTicks and microtasks + // that might've scheduled some immediates after sync code. + if (execution.state !== 2) { + throw new _invarianterror.InvariantError(`Cannot stop capturing immediates before execution is finished (state: ${ExecutionState[execution.state]})`); + } + execution.state = 3; + if (currentExecution === execution) { + currentExecution = null; + } +} +function bail(execution, error) { + // Reset the state as best we can to prevent further crashes. + // Otherwise, any subsequent call to `DANGEROUSLY_runPendingImmediatesAfterCurrentTask` + // would error, requiring a server restart to fix. + if (currentExecution === execution) { + currentExecution = null; + } + execution.state = 4; + // If we have any queued immediates, schedule them with native `setImmediate` and clear the queue. + // We don't want to skip running them altogether, because that could lead to + // e.g. hanging promises (for `new Promise((resolve) => setImmediate(resolve))`), + // but we're in an inconsistent state and can't run them as fast immediates, + // so this is the next best thing. + for (const queueItem of execution.queuedImmediates){ + if (queueItem.isCleared) { + continue; + } + scheduleQueuedImmediateAsNativeImmediate(queueItem); + } + execution.queuedImmediates.length = 0; + // Don't reset `pendingNextTicks` -- it will reset to 0 on its own as the nextTicks execute. + // If we set it to 0 here while we still have pending ticks, they'd decrement it below 0. + throw error; +} +function scheduleQueuedImmediateAsNativeImmediate(queueItem) { + const { callback, args, immediateObject } = queueItem; + const hasRef = immediateObject[INTERNALS].hasRef; + clearQueueItem(queueItem); + const nativeImmediate = args !== null ? originalSetImmediate(callback, ...args) : originalSetImmediate(callback); + if (!hasRef) { + nativeImmediate.unref(); + } + // Make our fake immediate object proxy all relevant operations + // (clearing, ref(), unref(), hasRef()) to the actual native immediate. + proxyQueuedImmediateToNativeImmediate(immediateObject, nativeImmediate); +} +function clearQueueItem(originalQueueItem) { + const queueItem = originalQueueItem; + queueItem.isCleared = true; + queueItem.callback = null; + queueItem.args = null; + queueItem.immediateObject = null; +} +function patchedNextTick() { + if (currentExecution === null) { + return originalNextTick.apply(null, // @ts-expect-error: this is valid, but typescript doesn't get it + arguments); + } + if (arguments.length === 0 || typeof arguments[0] !== 'function') { + // Let the original nextTick error for invalid arguments + // so that we don't have to mirror the error message. + originalNextTick.apply(null, // @ts-expect-error: explicitly passing arguments that we know are invalid + arguments); + // We expect the above call to throw. If it didn't, something's broken. + bail(currentExecution, new _invarianterror.InvariantError('Expected process.nextTick to reject invalid arguments')); + } + debug == null ? void 0 : debug(`scheduler :: process.nextTick called (previous pending: ${pendingNextTicks})`); + const callback = arguments[0]; + const args = arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : null; + pendingNextTicks += 1; + return originalNextTick(safelyRunNextTickCallback, callback, args); +} +function safelyRunNextTickCallback(callback, args) { + pendingNextTicks -= 1; + debug == null ? void 0 : debug(`scheduler :: process.nextTick executing (still pending: ${pendingNextTicks})`); + // Synchronous errors in nextTick break out of `processTicksAndRejections` and cause us + // to move on to the next timer without having executed the whole nextTick queue, + // which breaks our entire scheduling mechanism. See `performWork` for more details. + try { + if (args !== null) { + callback.apply(null, args); + } else { + callback(); + } + } catch (err) { + // We want to make sure `nextTick` is cheap, so unlike `performWork`, + // we only queue the microtask if an error actually occurs. + // This (observably) changes the timing of `uncaughtException` even more, + // because it'll run after microtasks queued from the nextTick, + // but hopefully this is niche enough to not affect any real world code. + queueMicrotask(()=>{ + debug == null ? void 0 : debug(`scheduler :: rethrowing sync error from nextTick in a microtask`); + throw err; + }); + } +} +function patchedSetImmediate() { + if (currentExecution === null) { + var _immediateAsyncStorage_getStore; + const immediate = originalSetImmediate.apply(null, // @ts-expect-error: this is valid, but typescript doesn't get it + arguments); + (_immediateAsyncStorage_getStore = immediateAsyncStorage.getStore()) == null ? void 0 : _immediateAsyncStorage_getStore.scheduleIdleCheck(); + return immediate; + } + if (arguments.length === 0 || typeof arguments[0] !== 'function') { + // Let the original setImmediate error for invalid arguments + // so that we don't have to mirror the error message. + originalSetImmediate.apply(null, // @ts-expect-error: explicitly passing arguments that we know are invalid + arguments); + // We expect the above call to throw. If it didn't, something's broken. + bail(currentExecution, new _invarianterror.InvariantError('Expected setImmediate to reject invalid arguments')); + } + const callback = arguments[0]; + const args = arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : null; + // Normally, Node would capture and propagate the async context to the immediate. + // We'll be running it on our own queue, so we need to propagate it ourselves. + const callbackWithAsyncContext = (0, _asynclocalstorage.bindSnapshot)(callback); + const immediateObject = new NextImmediate(); + const queueItem = { + isCleared: false, + callback: callbackWithAsyncContext, + args, + immediateObject + }; + currentExecution.queuedImmediates.push(queueItem); + immediateObject[INTERNALS].queueItem = queueItem; + return immediateObject; +} +function patchedSetImmediatePromise(value, options) { + if (currentExecution === null) { + var _immediateAsyncStorage_getStore; + const promise = originalSetImmediatePromisify(value, options); + (_immediateAsyncStorage_getStore = immediateAsyncStorage.getStore()) == null ? void 0 : _immediateAsyncStorage_getStore.scheduleIdleCheck(); + return promise; + } + return new Promise((resolve, reject)=>{ + // The abort signal makes the promise reject. + // If it is already aborted, we reject immediately. + const signal = options == null ? void 0 : options.signal; + if (signal && signal.aborted) { + return reject(signal.reason); + } + const immediate = patchedSetImmediate(resolve, value); + // Unref-ing only really has an observable effect if we bail out to a native immediate, + // but we do it for completeness + if ((options == null ? void 0 : options.ref) === false) { + immediate.unref(); + } + if (signal) { + signal.addEventListener('abort', ()=>{ + patchedClearImmediate(immediate); + reject(signal.reason); + }, { + once: true + }); + } + }); +} +patchedSetImmediate[_nodeutil.promisify.custom] = patchedSetImmediatePromise; +const patchedClearImmediate = (immediateObject)=>{ + // NOTE: we defensively check for patched immediates even if we're not + // currently capturing immediates, because the objects returned from + // the patched setImmediate can be kept around for arbitrarily long. + // As an optimization, we only do this if the patch was enabled at least once -- + // otherwise, no patched objects could've been created. + if (wasEnabledAtLeastOnce && immediateObject && typeof immediateObject === 'object' && INTERNALS in immediateObject) { + ; + immediateObject[Symbol.dispose](); + } else { + originalClearImmediate(immediateObject); + } +}; +//======================================================== +const INTERNALS = Symbol.for('next.Immediate.internals'); +function proxyQueuedImmediateToNativeImmediate(immediateObject, nativeImmediate) { + immediateObject[INTERNALS].hasRef = null; + immediateObject[INTERNALS].queueItem = null; + immediateObject[INTERNALS].nativeImmediate = nativeImmediate; +} +/** Implements a shim for the native `Immediate` class returned by `setImmediate` */ class NextImmediate { + hasRef() { + const internals = this[INTERNALS]; + if (internals.queueItem) { + return internals.hasRef; + } else if (internals.nativeImmediate) { + return internals.nativeImmediate.hasRef(); + } else { + // if we're no longer queued (cleared or executed), hasRef is always false + return false; + } + } + ref() { + const internals = this[INTERNALS]; + if (internals.queueItem) { + internals.hasRef = true; + } else if (internals.nativeImmediate) { + internals.nativeImmediate.ref(); + } + return this; + } + unref() { + const internals = this[INTERNALS]; + if (internals.queueItem) { + internals.hasRef = false; + } else if (internals.nativeImmediate) { + internals.nativeImmediate.unref(); + } + return this; + } + /** + * Node invokes `_onImmediate` when an immediate is executed: + * https://github.com/nodejs/node/blob/42d363205715ffa5a4a6d90f4be1311487053d65/lib/internal/timers.js#L504 + * It's visible on the public types, so we want to have it here for parity, but it's a noop. + * */ _onImmediate() {} + [Symbol.dispose]() { + // This is equivalent to `clearImmediate`. + const internals = this[INTERNALS]; + if (internals.queueItem) { + // this is still queued. drop it. + const queueItem = internals.queueItem; + internals.queueItem = null; + clearQueueItem(queueItem); + } else if (internals.nativeImmediate) { + internals.nativeImmediate[Symbol.dispose](); + } + } + constructor(){ + this[INTERNALS] = { + queueItem: null, + hasRef: true, + nativeImmediate: null + }; + } +} +// ========================================== +const debug = process.env.NEXT_DEBUG_IMMEDIATES !== '1' ? undefined : (...args)=>{ + if (process.env.NEXT_RUNTIME === 'edge') { + throw new _invarianterror.InvariantError('Fast setImmediate is not available in the edge runtime.'); + } else { + const { inspect } = require('node:util'); + const { writeFileSync } = require('node:fs'); + let logLine = args.map((arg)=>typeof arg === 'string' ? arg : inspect(arg, { + colors: true + })).join(' ') + '\n'; + logLine = '\x1B[2m' + logLine + '\x1B[22m' // styleText('dim', logLine) + ; + writeFileSync(process.stdout.fd, logLine); + } +}; +// ========================================== +install(); + +//# sourceMappingURL=fast-set-immediate.external.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1869f311b182b1bbbc019ed01a65ccf7bcb5d999 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/fast-set-immediate.external.ts"],"sourcesContent":["import { promisify } from 'node:util'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n bindSnapshot,\n getOrCreateGlobalAsyncLocalStorage,\n} from '../app-render/async-local-storage'\n\ntype Execution = {\n state: ExecutionState\n queuedImmediates: QueueItem[]\n}\n\nenum ExecutionState {\n Waiting = 1,\n Working = 2,\n Finished = 3,\n Abandoned = 4,\n}\n\ntype FastSetImmediateOriginals = {\n setImmediate: typeof globalThis.setImmediate\n clearImmediate: typeof globalThis.clearImmediate\n nextTick: typeof process.nextTick\n}\n\nconst FAST_SET_IMMEDIATE_ORIGINALS_KEY = Symbol.for(\n 'next.fast-set-immediate.originals'\n)\n\n// Re-evaluations in dev should always use the same base/original functions.\nconst originals = ((globalThis as any)[FAST_SET_IMMEDIATE_ORIGINALS_KEY] ??\n ((globalThis as any)[FAST_SET_IMMEDIATE_ORIGINALS_KEY] = {\n setImmediate: globalThis.setImmediate,\n clearImmediate: globalThis.clearImmediate,\n nextTick: process.nextTick,\n })) as FastSetImmediateOriginals\n\nlet wasEnabledAtLeastOnce = false\n\nlet pendingNextTicks = 0\nlet currentExecution: Execution | null = null\n\nconst originalSetImmediate = originals.setImmediate\nconst originalClearImmediate = originals.clearImmediate\nconst originalNextTick = originals.nextTick\nconst originalSetImmediatePromisify: (typeof setImmediate)['__promisify__'] =\n typeof originalSetImmediate === 'function'\n ? // @ts-expect-error: the types for `promisify.custom` are strange\n originalSetImmediate[promisify.custom]\n : // if setImmediate is not defined, we must be in the edge runtime,\n // and won't ever enable the patch, so this can be a dummy value\n undefined!\n\nfunction install() {\n if (process.env.NEXT_RUNTIME === 'edge') {\n // Nothing to patch. The exported functions all error if used in the edge runtime,\n // so we're not going to violate any assumptions by not patching.\n return\n } else {\n debug?.('installing fast setImmediate patch')\n\n const nodeTimers = require('node:timers') as typeof import('node:timers')\n globalThis.setImmediate = nodeTimers.setImmediate =\n // Workaround for missing __promisify__ which is not a real property\n patchedSetImmediate as unknown as typeof setImmediate\n globalThis.clearImmediate = nodeTimers.clearImmediate =\n patchedClearImmediate\n\n const nodeTimersPromises =\n require('node:timers/promises') as typeof import('node:timers/promises')\n nodeTimersPromises.setImmediate =\n patchedSetImmediatePromise as typeof import('node:timers/promises').setImmediate\n\n process.nextTick = patchedNextTick\n }\n}\n\n/**\n * **WARNING: This function changes the usual behavior of the event loop!**\n * **Be VERY careful about where you call it.**\n *\n * Starts capturing calls to `setImmediate` to run them as \"fast immediates\".\n * All calls captured in this way will be executed after the current task\n * (after callbacks from `process.nextTick()`, microtasks, and nextTicks scheduled from microtasks).\n * This function needs to be called again in each task that needs the\n * \"fast immediates\" behavior.\n *\n * ### Motivation\n *\n * We don't want `setImmediate` to be considered IO in Cache Components.\n * To achieve this in a staged (pre)render, we want to allow immediates scheduled\n * in stage N to run before stage N+1.\n * Since we schedule stages using sequential `setTimeout`, this isn't possible without\n * intercepting `setImmediate` and doing the scheduling on our own.\n * We refer to this as a \"fast immediate\".\n *\n * Notably, this affects React's `scheduleWork` in render, which uses `setImmediate`.\n * This is desirable -- if async work was scheduled during a stage, then it should\n * get to run before we finish that stage.\n *\n * ### Example\n *\n * ```ts\n * setTimeout(() => {\n * runPendingImmediatesAfterCurrentTask()\n * console.log(\"timeout 1\")\n * setImmediate(() => {\n * console.log(\"immediate!!!\")\n * })\n * })\n * setTimeout(() => {\n * console.log(\"timeout 2\")\n * })\n * ```\n * will print\n *\n * ```\n * timeout 1\n * immediate!!!\n * timeout 2\n * ```\n *\n * instead of the usual order\n * ```\n * timeout 1\n * timeout 2\n * immediate!!!\n * ```\n * > **NOTE**\n * > The above is *most common* order, but it's not guaranteed.\n * > Under some circumstances (e.g. when the event loop is blocked on CPU work),\n * > Node will reorder things and run the immediate before timeout 2.\n * > So, in a sense, we're just making this reordering happen consistently.\n *\n * Recursive `setImmediate` calls will also be executed as \"fast immediates\".\n * If multiple immediates were scheduled, `process.nextTick()` (and associated microtasks)\n * will be allowed to execute between them.\n * See the unit tests for more examples.\n * */\nexport function DANGEROUSLY_runPendingImmediatesAfterCurrentTask() {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n 'DANGEROUSLY_runPendingImmediatesAfterCurrentTask cannot be called in the edge runtime'\n )\n } else {\n const execution = startCapturingImmediates()\n\n try {\n scheduleWorkAfterNextTicksAndMicrotasks(execution)\n } catch (err) {\n // If this error comes from a bail() call, rethrow it.\n if (execution.state === ExecutionState.Abandoned) {\n throw err\n }\n // Otherwise, bail out here.\n bail(\n execution,\n new InvariantError(\n 'An unexpected error occurred while starting to capture immediates',\n {\n cause: err,\n }\n )\n )\n }\n }\n}\n\n/**\n * This should always be called a task after `DANGEROUSLY_runPendingImmediatesAfterCurrentTask`\n * to make sure that everything executed as expected and we're not left in an inconsistent state.\n * Ideally, this wouldn't be necessary, but we're not in control of the event loop\n * and need to guard against unexpected behaviors not forseen in this implementation,\n * so we have to be defensive.\n */\nexport function expectNoPendingImmediates() {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n 'expectNoPendingImmediates cannot be called in the edge runtime'\n )\n } else {\n if (currentExecution !== null) {\n bail(\n currentExecution,\n new InvariantError(\n `Expected all captured immediates to have been executed (state: ${ExecutionState[currentExecution.state]})`\n )\n )\n }\n }\n}\n\nexport { originalSetImmediate as unpatchedSetImmediate }\n\nconst immediateAsyncStorage =\n getOrCreateGlobalAsyncLocalStorage(\n 'immediate-async-storage'\n )\n\n/**\n * Run a callback and its async work with this native-immediate tracker.\n */\nexport function runWithNativeImmediateTracking(\n tracker: ImmediateTracker,\n callback: (...args: TArgs) => TResult,\n ...args: TArgs\n): TResult {\n return immediateAsyncStorage.run(tracker, callback, ...args)\n}\n\n/**\n * Tracks native immediates for one render's async scope without changing their\n * scheduling.\n *\n * A sentinel notifies idle subscribers after the last tracked immediate and its\n * microtasks and nextTicks finish. New native immediates postpone notification.\n *\n * Subscribers can cancel their wait without stopping tracking. Tracking\n * continues between subscriptions, including when asynchronous cache reads\n * resume the render.\n */\nexport class ImmediateTracker {\n private sentinel: NodeJS.Immediate | null = null\n private needsAnotherCheck = false\n private listeners = new Set<() => void>()\n\n hasPendingImmediates(): boolean {\n return this.sentinel !== null\n }\n\n /**\n * Calls `callback` asynchronously in a native immediate, even when no\n * immediates are pending. The callback runs in the subscriber's async\n * context. The returned function cancels the subscription without stopping\n * tracking.\n */\n onIdle(callback: () => void): () => void {\n const listeners = this.listeners\n const listener = bindSnapshot(callback)\n listeners.add(listener)\n if (this.sentinel === null) {\n this.scheduleIdleCheck()\n } else {\n this.sentinel.ref()\n }\n return () => {\n listeners.delete(listener)\n if (this.listeners.size === 0) {\n this.sentinel?.unref()\n }\n }\n }\n\n scheduleIdleCheck(): void {\n if (this.sentinel !== null) {\n // New immediates are queued after the pending sentinel. Record that\n // `checkForIdle` must check again before notifying subscribers. Further\n // scheduling calls reuse this flag and the pending sentinel.\n //\n // Node's uncaught-exception recovery can also reach this branch:\n //\n // 1. We queue immediate `A`, then sentinel `S`: `[A, S]`.\n // 2. `A` throws and interrupts Node's immediate-processing loop,\n // leaving `S` first in Node's outstanding queue.\n // 3. An uncaughtException handler handles the error, so Node continues.\n // 4. Node calls `timers.setImmediate(noop)` for another immediate cycle.\n // 5. Our patch runs before async-context cleanup and sees `A`'s tracker.\n // 6. The tracker finds `S` still pending.\n //\n // Node schedules this no-op after any handled uncaught exception so\n // pending ticks get another chance to run. After exception handling\n // returns, Node's C++ dispatcher retries the outstanding queue in the\n // same check phase, before the no-op runs.\n //\n // On Node 20, clearing `S` here leaves the outstanding queue's head\n // pointing to a destroyed immediate. When Node retries the queue, it\n // tries to skip the cleared entry through its predecessor. The first\n // entry has no predecessor, so recovery throws another exception. Keep\n // `S` queued and record that another check is needed instead.\n this.needsAnotherCheck = true\n return\n }\n\n this.sentinel = originalSetImmediate(this.checkForIdle)\n if (this.listeners.size === 0) {\n this.sentinel.unref()\n }\n }\n\n private checkForIdle = () => {\n this.sentinel = null\n if (this.needsAnotherCheck) {\n // Schedule the next check after the immediates queued since this\n // sentinel. Their callbacks and microtasks/nextTicks can then run before\n // we notify idle subscribers. A synchronous burst shares this next check.\n this.needsAnotherCheck = false\n this.scheduleIdleCheck()\n return\n }\n const listeners = this.listeners\n this.listeners = new Set()\n for (const callback of listeners) {\n listeners.delete(callback)\n callback()\n }\n }\n}\n\n/**\n * Wait until all nextTicks and microtasks spawned from the current task are done,\n * then execute any immediates that they queued.\n * */\nfunction scheduleWorkAfterNextTicksAndMicrotasks(execution: Execution) {\n if (execution.state !== ExecutionState.Waiting) {\n throw new InvariantError(\n `scheduleWorkAfterTicksAndMicrotasks can only be called while waiting (state: ${ExecutionState[execution.state]})`\n )\n }\n\n // We want to execute \"fast immediates\" after all the nextTicks and microtasks\n // spawned from the current task are done.\n // The ordering here is:\n //\n // 1. sync code\n // 2. process.nextTick (scheduled from sync code, or from one of these nextTicks)\n // 3. microtasks\n // 4. process.nextTick (scheduled from microtasks, e.g. `queueMicrotask(() => process.nextTick(callback))`)\n //\n // We want to run to run in step 4, because that's the latest point before the next tick.\n // However, there might also be other callbacks scheduled to run in that step.\n // But importantly, they had to be scheduled using a `process.nextTick`,\n // so we can detect them by checking if `pendingNextTicks > 0`.\n // In that case, we'll just reschedule ourselves in the same way again to let them run first.\n // (this process can theoretically repeat multiple times, hence the recursion).\n\n queueMicrotask(() => {\n // (note that this call won't increment `pendingNextTicks`,\n // only the patched `process.nextTick` does that, so this won't loop infinitely)\n originalNextTick(() => {\n // We're now in a nextTick, which means that we're executing inside `processTicksAndRejections`:\n // https://github.com/nodejs/node/blob/d546e7fd0bc3cbb4bcc2baae6f3aa44d2e81a413/lib/internal/process/task_queues.js#L84\n // All the work scheduled here will happen within that `processTicksAndRejections` loop.\n // Reading the source of `processTicksAndRejections` can help understand the timing here --\n // All we're really doing is strategically pushing callbacks into the two queues\n // (nextTicks and microtasks) that that function is currently looping over.\n\n try {\n if (\n execution.state === ExecutionState.Abandoned ||\n currentExecution !== execution\n ) {\n debug?.(`scheduler :: the execution was abandoned`)\n return\n }\n if (pendingNextTicks > 0) {\n // Other nextTicks have been scheduled. Let those run first, then try again --\n // we're simulating a event loop task, so all nextTicks should be exhausted before we execute.\n debug?.(`scheduler :: yielding to ${pendingNextTicks} nextTicks`)\n return scheduleWorkAfterNextTicksAndMicrotasks(execution)\n }\n\n // There's no other nextTicks, we're the last one, so we're about to move on to the next task (likely a timer).\n // Now, we can try and execute any queued immediates.\n return performWork(execution)\n } catch (err) {\n // If this error comes from a bail() call, rethrow it.\n\n // typescript can't tell that the state might've been mutated\n // and the narrowing from above is no longer valid\n const executionAfterWork = execution as Execution\n if (executionAfterWork.state === ExecutionState.Abandoned) {\n throw err\n }\n\n // Otherwise, bail out here (which will trigger an uncaught exception)\n // Note that we're using the same microtask trick as `safelyRunNextTickCallback`.\n queueMicrotask(() => {\n bail(\n execution,\n new InvariantError(\n 'An unexpected error occurred while executing immediates',\n { cause: err }\n )\n )\n })\n }\n })\n })\n}\n\n/** Execute one immediate, and schedule a check for more (in case there's others in the queue) */\nfunction performWork(execution: Execution) {\n if (execution.state === ExecutionState.Abandoned) {\n return\n }\n\n debug?.(`scheduler :: performing work`)\n\n if (execution.state !== ExecutionState.Waiting) {\n throw new InvariantError(\n `performWork can only be called while waiting (state: ${ExecutionState[execution.state]})`\n )\n }\n execution.state = ExecutionState.Working\n\n const queueItem = takeNextActiveQueueItem(execution)\n\n if (queueItem === null) {\n debug?.(`scheduler :: no immediates queued, exiting`)\n stopCapturingImmediates(execution)\n return\n }\n\n debug?.(`scheduler :: executing queued immediate`)\n\n const { immediateObject, callback, args } = queueItem\n\n immediateObject[INTERNALS].queueItem = null\n clearQueueItem(queueItem)\n\n // Execute the immediate.\n\n // If a sync error was thrown in the immediate, we want to trigger a `uncaughtException`.\n // However, we're executing in a nextTick, and if a nextTick callback errors,\n // It'll break out of `processTicksAndRejections` (note the lack of a `catch` block):\n // https://github.com/nodejs/node/blob/d546e7fd0bc3cbb4bcc2baae6f3aa44d2e81a413/lib/internal/process/task_queues.js#L81-L97\n // Meaning that the event loop will stop executing nextTicks and move on to the next timer\n // (or other phase of the event loop, but we expect to be running in a sequence of timers here).\n // Then, the remaining ticks will run after that timer, since they're still in the queue.\n //\n // This would completely break the timing we're trying to achieve here --\n // The point of this patch is to execute immediates before the next timer!\n // So, we need to work around this behavior. (both here and in our `process.nextTick` patch).\n //\n // We can sidestep this by catching the synchronous error and rethrowing it in a microtask.\n // (NOTE: if we use `queueMicrotask`, it'll trigger `uncaughtException`, not `unhandledRejection`,\n // because there's no promise being rejected.)\n //\n // This will make `uncaughtException` happen:\n // - Before the next fast immediate (`scheduleWorkAfterNextTicksAndMicrotasks` also uses `queueMicrotask`).\n // This is good, and matches usual observable behavior of immediates.\n // - AFTER nextTicks scheduled from the immediate itself.\n // This deviates from native setImmediate, which would call `uncaughtException` first,\n // and skip ahead to the next task as explained above.\n //\n // This is technically an observable difference in behavior, but it seems niche enough that\n // it shouldn't cause problems -- we don't expect user code to use `uncaughtException` for control flow,\n // only error reporting, so subtly changing the timing shouldn't matter.\n\n let didThrow = false\n let thrownValue: unknown = undefined\n queueMicrotask(() => {\n if (didThrow) {\n debug?.('scheduler :: rethrowing sync error from immediate in microtask')\n throw thrownValue\n }\n })\n\n try {\n if (args !== null) {\n callback.apply(null, args)\n } else {\n callback()\n }\n } catch (err) {\n // We'll rethrow the error in the microtask above.\n didThrow = true\n thrownValue = err\n }\n\n // Schedule the loop again in case there's more immediates after this one.\n // Note that we can't just check if the queue is empty now, because new immediates\n // might still be scheduled asynchronously, from an upcoming nextTick or microtask.\n execution.state = ExecutionState.Waiting\n scheduleWorkAfterNextTicksAndMicrotasks(execution)\n}\n\nfunction takeNextActiveQueueItem(execution: Execution): ActiveQueueItem | null {\n // Find the first (if any) queued immediate that wasn't cleared.\n // We don't remove immediates from the array when they're cleared,\n // so this requires some legwork to exclude (and possibly drop) cleared items.\n const { queuedImmediates } = execution\n\n let firstActiveItem: ActiveQueueItem | null = null\n let firstActiveItemIndex = -1\n for (let i = 0; i < queuedImmediates.length; i++) {\n const item = queuedImmediates[i]\n if (!item.isCleared) {\n firstActiveItem = item\n firstActiveItemIndex = i\n break\n }\n }\n\n if (firstActiveItem === null) {\n // We didn't find an active item.\n\n // If the queue isn't empty, then it must only contain cleared items. Empty it.\n if (queuedImmediates.length > 0) {\n queuedImmediates.length = 0\n }\n\n return null\n }\n\n // Remove all items up to and including `nextActiveItemIndex` from the queue.\n // (if it's not the first item, then it must be preceded by cleared items, which we want to drop anyway)\n if (firstActiveItemIndex === 0) {\n // Fast path - drop the first item\n // (`splice` creates a result array for the removed items, so this is more efficient)\n queuedImmediates.shift()\n } else {\n queuedImmediates.splice(0, firstActiveItemIndex + 1)\n }\n\n return firstActiveItem\n}\n\nfunction startCapturingImmediates(): Execution {\n if (currentExecution !== null) {\n bail(\n currentExecution,\n new InvariantError(\n `Cannot start capturing immediates again without finishing the previous task (state: ${ExecutionState[currentExecution.state]})`\n )\n )\n }\n wasEnabledAtLeastOnce = true\n\n const execution: Execution = {\n state: ExecutionState.Waiting,\n queuedImmediates: [],\n }\n currentExecution = execution\n\n return execution\n}\n\nfunction stopCapturingImmediates(execution: Execution) {\n if (execution.state === ExecutionState.Abandoned) {\n return\n }\n\n // This check enforces that we run performWork at least once before stopping\n // to make sure that we've waited for all the nextTicks and microtasks\n // that might've scheduled some immediates after sync code.\n if (execution.state !== ExecutionState.Working) {\n throw new InvariantError(\n `Cannot stop capturing immediates before execution is finished (state: ${ExecutionState[execution.state]})`\n )\n }\n\n execution.state = ExecutionState.Finished\n\n if (currentExecution === execution) {\n currentExecution = null\n }\n}\n\nfunction bail(execution: Execution, error: Error): never {\n // Reset the state as best we can to prevent further crashes.\n // Otherwise, any subsequent call to `DANGEROUSLY_runPendingImmediatesAfterCurrentTask`\n // would error, requiring a server restart to fix.\n\n if (currentExecution === execution) {\n currentExecution = null\n }\n\n execution.state = ExecutionState.Abandoned\n\n // If we have any queued immediates, schedule them with native `setImmediate` and clear the queue.\n // We don't want to skip running them altogether, because that could lead to\n // e.g. hanging promises (for `new Promise((resolve) => setImmediate(resolve))`),\n // but we're in an inconsistent state and can't run them as fast immediates,\n // so this is the next best thing.\n for (const queueItem of execution.queuedImmediates) {\n if (queueItem.isCleared) {\n continue\n }\n scheduleQueuedImmediateAsNativeImmediate(queueItem)\n }\n execution.queuedImmediates.length = 0\n\n // Don't reset `pendingNextTicks` -- it will reset to 0 on its own as the nextTicks execute.\n // If we set it to 0 here while we still have pending ticks, they'd decrement it below 0.\n\n throw error\n}\n\nfunction scheduleQueuedImmediateAsNativeImmediate(queueItem: ActiveQueueItem) {\n const { callback, args, immediateObject } = queueItem\n const hasRef = immediateObject[INTERNALS].hasRef\n\n clearQueueItem(queueItem)\n\n const nativeImmediate =\n args !== null\n ? originalSetImmediate(callback, ...args)\n : originalSetImmediate(callback)\n\n if (!hasRef) {\n nativeImmediate.unref()\n }\n\n // Make our fake immediate object proxy all relevant operations\n // (clearing, ref(), unref(), hasRef()) to the actual native immediate.\n proxyQueuedImmediateToNativeImmediate(immediateObject, nativeImmediate)\n}\n\ntype QueueItem = ActiveQueueItem | ClearedQueueItem\ntype ActiveQueueItem = {\n isCleared: false\n callback: (...args: any[]) => any\n args: any[] | null\n immediateObject: NextImmediate\n}\ntype ClearedQueueItem = {\n isCleared: true\n callback: null\n args: null\n immediateObject: null\n}\n\nfunction clearQueueItem(originalQueueItem: QueueItem) {\n const queueItem = originalQueueItem as ClearedQueueItem\n queueItem.isCleared = true\n queueItem.callback = null\n queueItem.args = null\n queueItem.immediateObject = null\n}\n\n//========================================================\n\nfunction patchedNextTick(\n callback: (...args: TArgs) => void,\n ...args: TArgs\n): void\nfunction patchedNextTick() {\n if (currentExecution === null) {\n return originalNextTick.apply(\n null,\n // @ts-expect-error: this is valid, but typescript doesn't get it\n arguments\n )\n }\n\n if (arguments.length === 0 || typeof arguments[0] !== 'function') {\n // Let the original nextTick error for invalid arguments\n // so that we don't have to mirror the error message.\n originalNextTick.apply(\n null,\n // @ts-expect-error: explicitly passing arguments that we know are invalid\n arguments\n )\n\n // We expect the above call to throw. If it didn't, something's broken.\n bail(\n currentExecution,\n new InvariantError(\n 'Expected process.nextTick to reject invalid arguments'\n )\n )\n }\n\n debug?.(\n `scheduler :: process.nextTick called (previous pending: ${pendingNextTicks})`\n )\n\n const callback: (...args: any[]) => any = arguments[0]\n const args: any[] | null =\n arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : null\n\n pendingNextTicks += 1\n return originalNextTick(safelyRunNextTickCallback, callback, args)\n}\n\nfunction safelyRunNextTickCallback(\n callback: (...args: any[]) => any,\n args: any[] | null\n) {\n pendingNextTicks -= 1\n debug?.(\n `scheduler :: process.nextTick executing (still pending: ${pendingNextTicks})`\n )\n\n // Synchronous errors in nextTick break out of `processTicksAndRejections` and cause us\n // to move on to the next timer without having executed the whole nextTick queue,\n // which breaks our entire scheduling mechanism. See `performWork` for more details.\n try {\n if (args !== null) {\n callback.apply(null, args)\n } else {\n callback()\n }\n } catch (err) {\n // We want to make sure `nextTick` is cheap, so unlike `performWork`,\n // we only queue the microtask if an error actually occurs.\n // This (observably) changes the timing of `uncaughtException` even more,\n // because it'll run after microtasks queued from the nextTick,\n // but hopefully this is niche enough to not affect any real world code.\n queueMicrotask(() => {\n debug?.(`scheduler :: rethrowing sync error from nextTick in a microtask`)\n throw err\n })\n }\n}\n\nfunction patchedSetImmediate(\n callback: (...args: TArgs) => void,\n ...args: TArgs\n): NodeJS.Immediate\nfunction patchedSetImmediate(callback: (args: void) => void): NodeJS.Immediate\nfunction patchedSetImmediate(): NodeJS.Immediate {\n if (currentExecution === null) {\n const immediate = originalSetImmediate.apply(\n null,\n // @ts-expect-error: this is valid, but typescript doesn't get it\n arguments\n )\n immediateAsyncStorage.getStore()?.scheduleIdleCheck()\n return immediate\n }\n\n if (arguments.length === 0 || typeof arguments[0] !== 'function') {\n // Let the original setImmediate error for invalid arguments\n // so that we don't have to mirror the error message.\n originalSetImmediate.apply(\n null,\n // @ts-expect-error: explicitly passing arguments that we know are invalid\n arguments\n )\n\n // We expect the above call to throw. If it didn't, something's broken.\n bail(\n currentExecution,\n new InvariantError('Expected setImmediate to reject invalid arguments')\n )\n }\n\n const callback: (...args: any[]) => any = arguments[0]\n const args: any[] | null =\n arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : null\n\n // Normally, Node would capture and propagate the async context to the immediate.\n // We'll be running it on our own queue, so we need to propagate it ourselves.\n const callbackWithAsyncContext = bindSnapshot(callback)\n\n const immediateObject = new NextImmediate()\n\n const queueItem: ActiveQueueItem = {\n isCleared: false,\n callback: callbackWithAsyncContext,\n args,\n immediateObject,\n }\n currentExecution.queuedImmediates.push(queueItem)\n\n immediateObject[INTERNALS].queueItem = queueItem\n\n return immediateObject\n}\n\nfunction patchedSetImmediatePromise(\n value: T,\n options?: import('node:timers').TimerOptions\n): Promise {\n if (currentExecution === null) {\n const promise = originalSetImmediatePromisify(value, options)\n immediateAsyncStorage.getStore()?.scheduleIdleCheck()\n return promise\n }\n\n return new Promise((resolve, reject) => {\n // The abort signal makes the promise reject.\n // If it is already aborted, we reject immediately.\n const signal = options?.signal\n if (signal && signal.aborted) {\n return reject(signal.reason)\n }\n\n const immediate = patchedSetImmediate(resolve, value)\n\n // Unref-ing only really has an observable effect if we bail out to a native immediate,\n // but we do it for completeness\n if (options?.ref === false) {\n immediate.unref()\n }\n\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n patchedClearImmediate(immediate)\n reject(signal.reason)\n },\n { once: true }\n )\n }\n })\n}\n\npatchedSetImmediate[promisify.custom] = patchedSetImmediatePromise\n\nconst patchedClearImmediate = (\n immediateObject: NodeJS.Immediate | undefined\n) => {\n // NOTE: we defensively check for patched immediates even if we're not\n // currently capturing immediates, because the objects returned from\n // the patched setImmediate can be kept around for arbitrarily long.\n // As an optimization, we only do this if the patch was enabled at least once --\n // otherwise, no patched objects could've been created.\n if (\n wasEnabledAtLeastOnce &&\n immediateObject &&\n typeof immediateObject === 'object' &&\n INTERNALS in immediateObject\n ) {\n ;(immediateObject as NextImmediate)[Symbol.dispose]()\n } else {\n originalClearImmediate(immediateObject)\n }\n}\n\n//========================================================\n\nconst INTERNALS: unique symbol = Symbol.for('next.Immediate.internals')\n\ntype NextImmediateInternals =\n | {\n /** Stored to reflect `ref()`/`unref()` calls, but has no effect otherwise */\n hasRef: boolean\n queueItem: ActiveQueueItem | null\n nativeImmediate: null\n }\n | {\n hasRef: null\n queueItem: null\n nativeImmediate: NodeJS.Immediate\n }\n\nfunction proxyQueuedImmediateToNativeImmediate(\n immediateObject: NextImmediate,\n nativeImmediate: NodeJS.Immediate\n) {\n immediateObject[INTERNALS].hasRef = null\n immediateObject[INTERNALS].queueItem = null\n immediateObject[INTERNALS].nativeImmediate = nativeImmediate\n}\n\n/** Makes sure that we're implementing all the public `Immediate` methods */\ninterface NativeImmediate extends NodeJS.Immediate {}\n\n/** Implements a shim for the native `Immediate` class returned by `setImmediate` */\nclass NextImmediate implements NativeImmediate {\n [INTERNALS]: NextImmediateInternals = {\n queueItem: null,\n hasRef: true,\n nativeImmediate: null,\n }\n hasRef() {\n const internals = this[INTERNALS]\n if (internals.queueItem) {\n return internals.hasRef\n } else if (internals.nativeImmediate) {\n return internals.nativeImmediate.hasRef()\n } else {\n // if we're no longer queued (cleared or executed), hasRef is always false\n return false\n }\n }\n ref() {\n const internals = this[INTERNALS]\n if (internals.queueItem) {\n internals.hasRef = true\n } else if (internals.nativeImmediate) {\n internals.nativeImmediate.ref()\n }\n return this\n }\n unref() {\n const internals = this[INTERNALS]\n if (internals.queueItem) {\n internals.hasRef = false\n } else if (internals.nativeImmediate) {\n internals.nativeImmediate.unref()\n }\n return this\n }\n\n /**\n * Node invokes `_onImmediate` when an immediate is executed:\n * https://github.com/nodejs/node/blob/42d363205715ffa5a4a6d90f4be1311487053d65/lib/internal/timers.js#L504\n * It's visible on the public types, so we want to have it here for parity, but it's a noop.\n * */\n _onImmediate() {}\n\n [Symbol.dispose]() {\n // This is equivalent to `clearImmediate`.\n const internals = this[INTERNALS]\n if (internals.queueItem) {\n // this is still queued. drop it.\n const queueItem = internals.queueItem\n internals.queueItem = null\n clearQueueItem(queueItem)\n } else if (internals.nativeImmediate) {\n internals.nativeImmediate[Symbol.dispose]()\n }\n }\n}\n\n// ==========================================\n\nconst debug =\n process.env.NEXT_DEBUG_IMMEDIATES !== '1'\n ? undefined\n : (...args: any[]) => {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n 'Fast setImmediate is not available in the edge runtime.'\n )\n } else {\n const { inspect } = require('node:util') as typeof import('node:util')\n const { writeFileSync } =\n require('node:fs') as typeof import('node:fs')\n\n let logLine =\n args\n .map((arg) =>\n typeof arg === 'string' ? arg : inspect(arg, { colors: true })\n )\n .join(' ') + '\\n'\n\n logLine = '\\x1B[2m' + logLine + '\\x1B[22m' // styleText('dim', logLine)\n writeFileSync(process.stdout.fd, logLine)\n }\n }\n\n// ==========================================\n\ninstall()\n"],"names":["DANGEROUSLY_runPendingImmediatesAfterCurrentTask","ImmediateTracker","expectNoPendingImmediates","runWithNativeImmediateTracking","unpatchedSetImmediate","originalSetImmediate","ExecutionState","FAST_SET_IMMEDIATE_ORIGINALS_KEY","Symbol","for","originals","globalThis","setImmediate","clearImmediate","nextTick","process","wasEnabledAtLeastOnce","pendingNextTicks","currentExecution","originalClearImmediate","originalNextTick","originalSetImmediatePromisify","promisify","custom","undefined","install","env","NEXT_RUNTIME","debug","nodeTimers","require","patchedSetImmediate","patchedClearImmediate","nodeTimersPromises","patchedSetImmediatePromise","patchedNextTick","InvariantError","execution","startCapturingImmediates","scheduleWorkAfterNextTicksAndMicrotasks","err","state","bail","cause","immediateAsyncStorage","getOrCreateGlobalAsyncLocalStorage","tracker","callback","args","run","hasPendingImmediates","sentinel","onIdle","listeners","listener","bindSnapshot","add","scheduleIdleCheck","ref","delete","size","unref","needsAnotherCheck","checkForIdle","Set","queueMicrotask","performWork","executionAfterWork","queueItem","takeNextActiveQueueItem","stopCapturingImmediates","immediateObject","INTERNALS","clearQueueItem","didThrow","thrownValue","apply","queuedImmediates","firstActiveItem","firstActiveItemIndex","i","length","item","isCleared","shift","splice","error","scheduleQueuedImmediateAsNativeImmediate","hasRef","nativeImmediate","proxyQueuedImmediateToNativeImmediate","originalQueueItem","arguments","Array","prototype","slice","call","safelyRunNextTickCallback","immediate","getStore","callbackWithAsyncContext","NextImmediate","push","value","options","promise","Promise","resolve","reject","signal","aborted","reason","addEventListener","once","dispose","internals","_onImmediate","NEXT_DEBUG_IMMEDIATES","inspect","writeFileSync","logLine","map","arg","colors","join","stdout","fd"],"mappings":";;;;;;;;;;;;;;;;;;IA2IgBA,gDAAgD;eAAhDA;;IAkFHC,gBAAgB;eAAhBA;;IA9CGC,yBAAyB;eAAzBA;;IA2BAC,8BAA8B;eAA9BA;;IAViBC,qBAAqB;eAA7CC;;;0BAhMiB;gCACK;mCAIxB;AAOP,IAAA,AAAKC,wCAAAA;;;;;WAAAA;EAAAA;AAaL,MAAMC,mCAAmCC,OAAOC,GAAG,CACjD;AAGF,4EAA4E;AAC5E,MAAMC,YAAa,AAACC,UAAkB,CAACJ,iCAAiC,IACrE,CAAA,AAACI,UAAkB,CAACJ,iCAAiC,GAAG;IACvDK,cAAcD,WAAWC,YAAY;IACrCC,gBAAgBF,WAAWE,cAAc;IACzCC,UAAUC,QAAQD,QAAQ;AAC5B,CAAA;AAEF,IAAIE,wBAAwB;AAE5B,IAAIC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F,IAAIjC,QAAQW,GAAG,CAACC,YAAY,KAAK,QAAQ;QACvC,MAAM,IAAIS,8BAAc,CACtB;IAEJ,OAAO;QACL,MAAM,EAAEkF,OAAO,EAAE,GAAGxF,QAAQ;QAC5B,MAAM,EAAEyF,aAAa,EAAE,GACrBzF,QAAQ;QAEV,IAAI0F,UACFxE,KACGyE,GAAG,CAAC,CAACC,MACJ,OAAOA,QAAQ,WAAWA,MAAMJ,QAAQI,KAAK;gBAAEC,QAAQ;YAAK,IAE7DC,IAAI,CAAC,OAAO;QAEjBJ,UAAU,YAAYA,UAAU,WAAW,4BAA4B;;QACvED,cAAcxG,QAAQ8G,MAAM,CAACC,EAAE,EAAEN;IACnC;AACF;AAEN,6CAA6C;AAE7C/F","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/global-behaviors.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/global-behaviors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..30ce524b29c2d4595f46df3dd5bc9eb6989cb198 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/global-behaviors.d.ts @@ -0,0 +1,5 @@ +export declare function installGlobalBehaviors(config: { + experimental?: { + hideLogsAfterAbort?: boolean; + }; +}): void; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/global-behaviors.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/global-behaviors.js new file mode 100644 index 0000000000000000000000000000000000000000..8eeb0eb09d140b9157edc8df7bb085db8e5eccb2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/global-behaviors.js @@ -0,0 +1,29 @@ +/** + * Unlike most files in the node-environment-extensions folder this one is not + * an extension itself but it exposes a function to install config based global + * behaviors that should be loaded whenever a Node Server or Node Worker are created. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "installGlobalBehaviors", { + enumerable: true, + get: function() { + return installGlobalBehaviors; + } +}); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _consoledimexternal = require("./console-dim.external"); +function installGlobalBehaviors(config) { + var _config_experimental; + if (process.env.NEXT_RUNTIME === 'edge') { + throw new _invarianterror.InvariantError('Expected not to install Node.js global behaviors in the edge runtime.'); + } + if (((_config_experimental = config.experimental) == null ? void 0 : _config_experimental.hideLogsAfterAbort) === true) { + (0, _consoledimexternal.setAbortedLogsStyle)('hidden'); + } else { + (0, _consoledimexternal.setAbortedLogsStyle)('dimmed'); + } +} + +//# sourceMappingURL=global-behaviors.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/global-behaviors.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/global-behaviors.js.map new file mode 100644 index 0000000000000000000000000000000000000000..147f8ba44fd4ee78460d995cac072df11c4a1131 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/global-behaviors.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/global-behaviors.tsx"],"sourcesContent":["/**\n * Unlike most files in the node-environment-extensions folder this one is not\n * an extension itself but it exposes a function to install config based global\n * behaviors that should be loaded whenever a Node Server or Node Worker are created.\n */\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nimport { setAbortedLogsStyle } from './console-dim.external'\n\nexport function installGlobalBehaviors(config: {\n experimental?: { hideLogsAfterAbort?: boolean }\n}) {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n 'Expected not to install Node.js global behaviors in the edge runtime.'\n )\n }\n\n if (config.experimental?.hideLogsAfterAbort === true) {\n setAbortedLogsStyle('hidden')\n } else {\n setAbortedLogsStyle('dimmed')\n }\n}\n"],"names":["installGlobalBehaviors","config","process","env","NEXT_RUNTIME","InvariantError","experimental","hideLogsAfterAbort","setAbortedLogsStyle"],"mappings":"AAAA;;;;CAIC;;;;+BAKeA;;;eAAAA;;;gCAJe;oCAEK;AAE7B,SAASA,uBAAuBC,MAEtC;QAOKA;IANJ,IAAIC,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;QACvC,MAAM,IAAIC,8BAAc,CACtB;IAEJ;IAEA,IAAIJ,EAAAA,uBAAAA,OAAOK,YAAY,qBAAnBL,qBAAqBM,kBAAkB,MAAK,MAAM;QACpDC,IAAAA,uCAAmB,EAAC;IACtB,OAAO;QACLA,IAAAA,uCAAmB,EAAC;IACtB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/io-utils.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/io-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..48bccf319a1a3eb864061a5e37ce293a8221a45c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/io-utils.d.ts @@ -0,0 +1,2 @@ +import { type SyncIOApiType } from '../app-render/sync-io-messages'; +export declare function io(expression: string, type: SyncIOApiType): void; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/io-utils.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/io-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..c748261df9e71415159749d4eac29a434d8c9c14 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/io-utils.js @@ -0,0 +1,103 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "io", { + enumerable: true, + get: function() { + return io; + } +}); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _dynamicrendering = require("../app-render/dynamic-rendering"); +const _stagedrendering = require("../app-render/staged-rendering"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _synciomessages = require("../app-render/sync-io-messages"); +const _invarianterror = require("../../shared/lib/invariant-error"); +function io(expression, type) { + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workUnitStore || !workStore) { + return; + } + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-runtime': + { + const prerenderSignal = workUnitStore.controller.signal; + if (prerenderSignal.aborted === false) { + // If the prerender signal is already aborted we don't need to construct + // any stacks because something else actually terminated the prerender. + // TODO: synchronize this with `stageController` + (0, _dynamicrendering.abortOnSynchronousPlatformIOAccess)(workStore.route, expression, (0, _dynamicrenderingutils.applyOwnerStack)((0, _synciomessages.createSyncIOError)(workStore.route, expression, type)), workUnitStore); + } + break; + } + case 'prerender-client': + { + const prerenderSignal = workUnitStore.controller.signal; + if (prerenderSignal.aborted === false) { + // If the prerender signal is already aborted we don't need to construct + // any stacks because something else actually terminated the prerender. + (0, _dynamicrendering.abortOnSynchronousPlatformIOAccess)(workStore.route, expression, (0, _dynamicrenderingutils.applyOwnerStack)((0, _synciomessages.createSyncIOClientError)(workStore.route, expression, type)), workUnitStore); + } + break; + } + case 'request': + { + const stageController = workUnitStore.stagedRendering; + if (stageController && stageController.shouldTrackSyncInterrupt()) { + let syncIOError; + // NOTE: keep stages where we can interrupt in sync with + // `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason` + switch(stageController.currentStage){ + case _stagedrendering.RenderStage.ShellStatic: + case _stagedrendering.RenderStage.PrefetchStatic_prefetchApi: + case _stagedrendering.RenderStage.PrefetchStatic: + case _stagedrendering.RenderStage.NavigationStatic: + case _stagedrendering.RenderStage.Static: + { + syncIOError = (0, _synciomessages.createSyncIOError)(workStore.route, expression, type); + break; + } + case _stagedrendering.RenderStage.ShellRuntime: + case _stagedrendering.RenderStage.PrefetchRuntime_prefetchApi: + case _stagedrendering.RenderStage.PrefetchRuntime: + case _stagedrendering.RenderStage.NavigationRuntime: + { + // We're in a runtime stage. + // We only error for Sync IO in runtime stages if the route has partialPrefetching enabled. + syncIOError = (0, _synciomessages.createSyncIORuntimeError)(workStore.route, expression, type); + break; + } + case _stagedrendering.RenderStage.Before: + case _stagedrendering.RenderStage.Dynamic: + case _stagedrendering.RenderStage.Abandoned: + { + throw new _invarianterror.InvariantError(`shouldTrackSyncInterrupt allowed a sync IO interrupt in an unexpected stage: ${_stagedrendering.RenderStage[stageController.currentStage]}`); + } + } + syncIOError = (0, _dynamicrenderingutils.applyOwnerStack)(syncIOError); + stageController.syncInterruptCurrentStageWithReason(syncIOError); + // A validation render uses a 'request' store type, but may be abortable. + // If we're rendering with filled caches, Sync IO is an error and should trigger an abort. + if (workUnitStore.controller && !workUnitStore.controller.signal.aborted) { + workUnitStore.controller.abort(syncIOError); + } + } + break; + } + case 'validation-client': + case 'prerender-legacy': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } +} + +//# sourceMappingURL=io-utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/io-utils.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/io-utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9630fe18a4163473af1954de760fa8439b71f481 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/io-utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/io-utils.tsx"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport {\n createSyncIOClientError,\n createSyncIOError,\n createSyncIORuntimeError,\n type SyncIOApiType,\n} from '../app-render/sync-io-messages'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function io(expression: string, type: SyncIOApiType) {\n const workUnitStore = workUnitAsyncStorage.getStore()\n const workStore = workAsyncStorage.getStore()\n\n if (!workUnitStore || !workStore) {\n return\n }\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n // TODO: synchronize this with `stageController`\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(createSyncIOError(workStore.route, expression, type)),\n workUnitStore\n )\n }\n break\n }\n case 'prerender-client': {\n const prerenderSignal = workUnitStore.controller.signal\n\n if (prerenderSignal.aborted === false) {\n // If the prerender signal is already aborted we don't need to construct\n // any stacks because something else actually terminated the prerender.\n abortOnSynchronousPlatformIOAccess(\n workStore.route,\n expression,\n applyOwnerStack(\n createSyncIOClientError(workStore.route, expression, type)\n ),\n workUnitStore\n )\n }\n break\n }\n case 'request': {\n const stageController = workUnitStore.stagedRendering\n if (stageController && stageController.shouldTrackSyncInterrupt()) {\n let syncIOError: Error\n // NOTE: keep stages where we can interrupt in sync with\n // `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason`\n switch (stageController.currentStage) {\n case RenderStage.ShellStatic:\n case RenderStage.PrefetchStatic_prefetchApi:\n case RenderStage.PrefetchStatic:\n case RenderStage.NavigationStatic:\n case RenderStage.Static: {\n syncIOError = createSyncIOError(workStore.route, expression, type)\n break\n }\n case RenderStage.ShellRuntime:\n case RenderStage.PrefetchRuntime_prefetchApi:\n case RenderStage.PrefetchRuntime:\n case RenderStage.NavigationRuntime: {\n // We're in a runtime stage.\n // We only error for Sync IO in runtime stages if the route has partialPrefetching enabled.\n syncIOError = createSyncIORuntimeError(\n workStore.route,\n expression,\n type\n )\n break\n }\n case RenderStage.Before:\n case RenderStage.Dynamic:\n case RenderStage.Abandoned: {\n throw new InvariantError(\n `shouldTrackSyncInterrupt allowed a sync IO interrupt in an unexpected stage: ${RenderStage[stageController.currentStage]}`\n )\n }\n }\n\n syncIOError = applyOwnerStack(syncIOError)\n stageController.syncInterruptCurrentStageWithReason(syncIOError)\n\n // A validation render uses a 'request' store type, but may be abortable.\n // If we're rendering with filled caches, Sync IO is an error and should trigger an abort.\n if (\n workUnitStore.controller &&\n !workUnitStore.controller.signal.aborted\n ) {\n workUnitStore.controller.abort(syncIOError)\n }\n }\n break\n }\n case 'validation-client':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n}\n"],"names":["io","expression","type","workUnitStore","workUnitAsyncStorage","getStore","workStore","workAsyncStorage","prerenderSignal","controller","signal","aborted","abortOnSynchronousPlatformIOAccess","route","applyOwnerStack","createSyncIOError","createSyncIOClientError","stageController","stagedRendering","shouldTrackSyncInterrupt","syncIOError","currentStage","RenderStage","ShellStatic","PrefetchStatic_prefetchApi","PrefetchStatic","NavigationStatic","Static","ShellRuntime","PrefetchRuntime_prefetchApi","PrefetchRuntime","NavigationRuntime","createSyncIORuntimeError","Before","Dynamic","Abandoned","InvariantError","syncInterruptCurrentStageWithReason","abort"],"mappings":";;;;+BAagBA;;;eAAAA;;;0CAbiB;8CACI;kCACc;iCACvB;uCACI;gCAMzB;gCACwB;AAExB,SAASA,GAAGC,UAAkB,EAAEC,IAAmB;IACxD,MAAMC,gBAAgBC,kDAAoB,CAACC,QAAQ;IACnD,MAAMC,YAAYC,0CAAgB,CAACF,QAAQ;IAE3C,IAAI,CAACF,iBAAiB,CAACG,WAAW;QAChC;IACF;IAEA,OAAQH,cAAcD,IAAI;QACxB,KAAK;QACL,KAAK;YAAqB;gBACxB,MAAMM,kBAAkBL,cAAcM,UAAU,CAACC,MAAM;gBAEvD,IAAIF,gBAAgBG,OAAO,KAAK,OAAO;oBACrC,wEAAwE;oBACxE,uEAAuE;oBACvE,gDAAgD;oBAChDC,IAAAA,oDAAkC,EAChCN,UAAUO,KAAK,EACfZ,YACAa,IAAAA,sCAAe,EAACC,IAAAA,iCAAiB,EAACT,UAAUO,KAAK,EAAEZ,YAAYC,QAC/DC;gBAEJ;gBACA;YACF;QACA,KAAK;YAAoB;gBACvB,MAAMK,kBAA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gBAAgBoB,mCAAmC,CAACjB;oBAEpD,yEAAyE;oBACzE,0FAA0F;oBAC1F,IACEjB,cAAcM,UAAU,IACxB,CAACN,cAAcM,UAAU,CAACC,MAAM,CAACC,OAAO,EACxC;wBACAR,cAAcM,UAAU,CAAC6B,KAAK,CAAClB;oBACjC;gBACF;gBACA;YACF;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH;QACF;YACEjB;IACJ;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/node-crypto.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/node-crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..284c055bb3ca018ab55d8107fb65548c73406d4e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/node-crypto.d.ts @@ -0,0 +1,9 @@ +/** + * We extend node:crypto APIs during builds and revalidates to ensure that prerenders don't observe random bytes + * When cacheComponents is enabled. Random bytes are a form of IO even if they resolve synchronously. When cacheComponents is + * enabled we need to ensure that random bytes are excluded from prerenders unless they are cached. + * + * + * The extensions here never error nor alter the underlying return values and thus should be transparent to callers. + */ +export {}; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/node-crypto.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/node-crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..8caa0a546b4c312345778f64f2a9d2253919a115 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/node-crypto.js @@ -0,0 +1,103 @@ +/** + * We extend node:crypto APIs during builds and revalidates to ensure that prerenders don't observe random bytes + * When cacheComponents is enabled. Random bytes are a form of IO even if they resolve synchronously. When cacheComponents is + * enabled we need to ensure that random bytes are excluded from prerenders unless they are cached. + * + * + * The extensions here never error nor alter the underlying return values and thus should be transparent to callers. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _ioutils = require("./io-utils"); +if (process.env.NEXT_RUNTIME === 'edge') { +// nothing to patch +} else { + const nodeCrypto = require('node:crypto'); + // require('node:crypto').getRandomValues is an alias for + // crypto.getRandomValues which is extended in web-crypto.tsx + // require('node:crypto').randomUUID is not an alias for crypto.randomUUID + const randomUUIDExpression = "`require('node:crypto').randomUUID()`"; + try { + const _randomUUID = nodeCrypto.randomUUID; + nodeCrypto.randomUUID = function randomUUID() { + (0, _ioutils.io)(randomUUIDExpression, 'random'); + return _randomUUID.apply(this, arguments); + }; + } catch { + console.error(`Failed to install ${randomUUIDExpression} extension. When using \`cacheComponents\` calling this function will not correctly trigger dynamic behavior.`); + } + const randomBytesExpression = "`require('node:crypto').randomBytes(size)`"; + try { + const _randomBytes = nodeCrypto.randomBytes; + // @ts-expect-error -- TODO: tell TS the overloads are preserved + nodeCrypto.randomBytes = function randomBytes() { + if (typeof arguments[1] !== 'function') { + // randomBytes is sync if the second arg is undefined + (0, _ioutils.io)(randomBytesExpression, 'random'); + } + return _randomBytes.apply(this, arguments); + }; + } catch { + console.error(`Failed to install ${randomBytesExpression} extension. When using \`cacheComponents\` calling this function without a callback argument will not correctly trigger dynamic behavior.`); + } + const randomFillSyncExpression = "`require('node:crypto').randomFillSync(...)`"; + try { + const _randomFillSync = nodeCrypto.randomFillSync; + // @ts-expect-error -- TODO: tell TS the overloads are preserved + nodeCrypto.randomFillSync = function randomFillSync() { + (0, _ioutils.io)(randomFillSyncExpression, 'random'); + return _randomFillSync.apply(this, arguments); + }; + } catch { + console.error(`Failed to install ${randomFillSyncExpression} extension. When using \`cacheComponents\` calling this function will not correctly trigger dynamic behavior.`); + } + const randomIntExpression = "`require('node:crypto').randomInt(min, max)`"; + try { + const _randomInt = nodeCrypto.randomInt; + // @ts-expect-error -- TODO: tell TS the overloads are preserved + nodeCrypto.randomInt = function randomInt() { + if (typeof arguments[2] !== 'function') { + // randomInt is sync if the third arg is undefined + (0, _ioutils.io)(randomIntExpression, 'random'); + } + return _randomInt.apply(this, arguments); + }; + } catch { + console.error(`Failed to install ${randomBytesExpression} extension. When using \`cacheComponents\` calling this function without a callback argument will not correctly trigger dynamic behavior.`); + } + const generatePrimeSyncExpression = "`require('node:crypto').generatePrimeSync(...)`"; + try { + const _generatePrimeSync = nodeCrypto.generatePrimeSync; + // @ts-expect-error -- TODO: tell TS the overloads are preserved + nodeCrypto.generatePrimeSync = function generatePrimeSync() { + (0, _ioutils.io)(generatePrimeSyncExpression, 'random'); + return _generatePrimeSync.apply(this, arguments); + }; + } catch { + console.error(`Failed to install ${generatePrimeSyncExpression} extension. When using \`cacheComponents\` calling this function will not correctly trigger dynamic behavior.`); + } + const generateKeyPairSyncExpression = "`require('node:crypto').generateKeyPairSync(...)`"; + try { + const _generateKeyPairSync = nodeCrypto.generateKeyPairSync; + // @ts-expect-error -- TODO: tell TS the overloads are preserved + nodeCrypto.generateKeyPairSync = function generateKeyPairSync() { + (0, _ioutils.io)(generateKeyPairSyncExpression, 'random'); + return _generateKeyPairSync.apply(this, arguments); + }; + } catch { + console.error(`Failed to install ${generateKeyPairSyncExpression} extension. When using \`cacheComponents\` calling this function will not correctly trigger dynamic behavior.`); + } + const generateKeySyncExpression = "`require('node:crypto').generateKeySync(...)`"; + try { + const _generateKeySync = nodeCrypto.generateKeySync; + nodeCrypto.generateKeySync = function generateKeySync() { + (0, _ioutils.io)(generateKeySyncExpression, 'random'); + return _generateKeySync.apply(this, arguments); + }; + } catch { + console.error(`Failed to install ${generateKeySyncExpression} extension. When using \`cacheComponents\` calling this function will not correctly trigger dynamic behavior.`); + } +} + +//# sourceMappingURL=node-crypto.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/node-crypto.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/node-crypto.js.map new file mode 100644 index 0000000000000000000000000000000000000000..916e28eafa84a3691663f92b88633d2d9d76c502 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/node-crypto.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/node-crypto.tsx"],"sourcesContent":["/**\n * We extend node:crypto APIs during builds and revalidates to ensure that prerenders don't observe random bytes\n * When cacheComponents is enabled. Random bytes are a form of IO even if they resolve synchronously. When cacheComponents is\n * enabled we need to ensure that random bytes are excluded from prerenders unless they are cached.\n *\n *\n * The extensions here never error nor alter the underlying return values and thus should be transparent to callers.\n */\n\nimport { io } from './io-utils'\n\nif (process.env.NEXT_RUNTIME === 'edge') {\n // nothing to patch\n} else {\n const nodeCrypto = require('node:crypto') as typeof import('node:crypto')\n\n // require('node:crypto').getRandomValues is an alias for\n // crypto.getRandomValues which is extended in web-crypto.tsx\n\n // require('node:crypto').randomUUID is not an alias for crypto.randomUUID\n\n const randomUUIDExpression = \"`require('node:crypto').randomUUID()`\"\n try {\n const _randomUUID = nodeCrypto.randomUUID\n nodeCrypto.randomUUID = function randomUUID() {\n io(randomUUIDExpression, 'random')\n return _randomUUID.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${randomUUIDExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n }\n\n const randomBytesExpression = \"`require('node:crypto').randomBytes(size)`\"\n try {\n const _randomBytes = nodeCrypto.randomBytes\n // @ts-expect-error -- TODO: tell TS the overloads are preserved\n nodeCrypto.randomBytes = function randomBytes() {\n if (typeof arguments[1] !== 'function') {\n // randomBytes is sync if the second arg is undefined\n io(randomBytesExpression, 'random')\n }\n return _randomBytes.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${randomBytesExpression} extension. When using \\`cacheComponents\\` calling this function without a callback argument will not correctly trigger dynamic behavior.`\n )\n }\n\n const randomFillSyncExpression =\n \"`require('node:crypto').randomFillSync(...)`\"\n try {\n const _randomFillSync = nodeCrypto.randomFillSync\n // @ts-expect-error -- TODO: tell TS the overloads are preserved\n nodeCrypto.randomFillSync = function randomFillSync() {\n io(randomFillSyncExpression, 'random')\n return _randomFillSync.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${randomFillSyncExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n }\n\n const randomIntExpression = \"`require('node:crypto').randomInt(min, max)`\"\n try {\n const _randomInt = nodeCrypto.randomInt\n // @ts-expect-error -- TODO: tell TS the overloads are preserved\n nodeCrypto.randomInt = function randomInt() {\n if (typeof arguments[2] !== 'function') {\n // randomInt is sync if the third arg is undefined\n io(randomIntExpression, 'random')\n }\n return _randomInt.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${randomBytesExpression} extension. When using \\`cacheComponents\\` calling this function without a callback argument will not correctly trigger dynamic behavior.`\n )\n }\n\n const generatePrimeSyncExpression =\n \"`require('node:crypto').generatePrimeSync(...)`\"\n try {\n const _generatePrimeSync = nodeCrypto.generatePrimeSync\n // @ts-expect-error -- TODO: tell TS the overloads are preserved\n nodeCrypto.generatePrimeSync = function generatePrimeSync() {\n io(generatePrimeSyncExpression, 'random')\n return _generatePrimeSync.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${generatePrimeSyncExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n }\n\n const generateKeyPairSyncExpression =\n \"`require('node:crypto').generateKeyPairSync(...)`\"\n try {\n const _generateKeyPairSync = nodeCrypto.generateKeyPairSync\n // @ts-expect-error -- TODO: tell TS the overloads are preserved\n nodeCrypto.generateKeyPairSync = function generateKeyPairSync() {\n io(generateKeyPairSyncExpression, 'random')\n return _generateKeyPairSync.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${generateKeyPairSyncExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n }\n\n const generateKeySyncExpression =\n \"`require('node:crypto').generateKeySync(...)`\"\n try {\n const _generateKeySync = nodeCrypto.generateKeySync\n nodeCrypto.generateKeySync = function generateKeySync() {\n io(generateKeySyncExpression, 'random')\n return _generateKeySync.apply(this, arguments as any)\n }\n } catch {\n console.error(\n `Failed to install ${generateKeySyncExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n }\n}\n"],"names":["process","env","NEXT_RUNTIME","nodeCrypto","require","randomUUIDExpression","_randomUUID","randomUUID","io","apply","arguments","console","error","randomBytesExpression","_randomBytes","randomBytes","randomFillSyncExpression","_randomFillSync","randomFillSync","randomIntExpression","_randomInt","randomInt","generatePrimeSyncExpression","_generatePrimeSync","generatePrimeSync","generateKeyPairSyncExpression","_generateKeyPairSync","generateKeyPairSync","generateKeySyncExpression","_generateKeySync","generateKeySync"],"mappings":"AAAA;;;;;;;CAOC;;;;yBAEkB;AAEnB,IAAIA,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;AACvC,mBAAmB;AACrB,OAAO;IACL,MAAMC,aAAaC,QAAQ;IAE3B,yDAAyD;IACzD,6DAA6D;IAE7D,0EAA0E;IAE1E,MAAMC,uBAAuB;IAC7B,IAAI;QACF,MAAMC,cAAcH,WAAWI,UAAU;QACzCJ,WAAWI,UAAU,GAAG,SAASA;YAC/BC,IAAAA,WAAE,EAACH,sBAAsB;YACzB,OAAOC,YAAYG,KAAK,CAAC,IAAI,EAAEC;QACjC;IACF,EAAE,OAAM;QACNC,QAAQC,KAAK,CACX,CAAC,kBAAkB,EAAEP,qBAAqB,6GAA6G,CAAC;IAE5J;IAEA,MAAMQ,wBAAwB;IAC9B,IAAI;QACF,MAAMC,eAAeX,WAAWY,WAAW;QAC3C,gEAAgE;QAChEZ,WAAWY,WAAW,GAAG,SAASA;YAChC,IAAI,OAAOL,SAAS,CAAC,EAAE,KAAK,YAAY;gBACtC,qDAAqD;gBACrDF,IAAAA,WAAE,EAACK,uBAAuB;YAC5B;YACA,OAAOC,aAAaL,KAAK,CAAC,IAAI,EAAEC;QAClC;IACF,EAAE,OAAM;QACNC,QAAQC,KAAK,CACX,CAAC,kBAAkB,EAAEC,sBAAsB,yIAAyI,CAAC;IAEzL;IAEA,MAA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EAAEa,8BAA8B,6GAA6G,CAAC;IAErK;IAEA,MAAMG,4BACJ;IACF,IAAI;QACF,MAAMC,mBAAmB1B,WAAW2B,eAAe;QACnD3B,WAAW2B,eAAe,GAAG,SAASA;YACpCtB,IAAAA,WAAE,EAACoB,2BAA2B;YAC9B,OAAOC,iBAAiBpB,KAAK,CAAC,IAAI,EAAEC;QACtC;IACF,EAAE,OAAM;QACNC,QAAQC,KAAK,CACX,CAAC,kBAAkB,EAAEgB,0BAA0B,6GAA6G,CAAC;IAEjK;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/process-error-handlers.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/process-error-handlers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1315ee1d82fe637fbe8aeecd561b931e8f10012a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/process-error-handlers.d.ts @@ -0,0 +1,15 @@ +/** + * Checks if the Next.js unhandled rejection listener is currently attached. + * This queries the actual process listeners instead of relying on a module + * global, so it stays accurate even if the listener was removed externally, + * e.g. via `process.removeAllListeners('unhandledRejection')`. + */ +export declare function isUnhandledRejectionListenerRegistered(): boolean; +/** + * Registers the Next.js unhandled rejection listener, which logs unhandled + * rejections and prevents them from crashing the process. Safe to call + * unconditionally: if the listener is already attached, this is a no-op, so it + * never registers a duplicate. + */ +export declare function registerUnhandledRejectionListener(): void; +export declare function installProcessErrorHandlers(shouldRemoveUncaughtErrorAndRejectionListeners: boolean): void; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/process-error-handlers.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/process-error-handlers.js new file mode 100644 index 0000000000000000000000000000000000000000..22fd7e32903e2f62c1c564ecadddb079ecdabb22 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/process-error-handlers.js @@ -0,0 +1,161 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + installProcessErrorHandlers: null, + isUnhandledRejectionListenerRegistered: null, + registerUnhandledRejectionListener: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + installProcessErrorHandlers: function() { + return installProcessErrorHandlers; + }, + isUnhandledRejectionListenerRegistered: function() { + return isUnhandledRejectionListenerRegistered; + }, + registerUnhandledRejectionListener: function() { + return registerUnhandledRejectionListener; + } +}); +const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log")); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +let _global = globalThis; +// The listener function is shared via globalThis so that multiple copies of +// this module (e.g. in the pre-compiled server bundle and in a route module +// bundle) still register and detect a single listener instance. +const UNHANDLED_REJECTION_LISTENER_KEY = Symbol.for('next.unhandledRejectionListener'); +function unhandledRejectionListener(reason) { + // Immediately log the error. + // TODO: Ideally, if we knew that this error was triggered by application + // code, we would suppress it entirely without logging. We can't reliably + // detect all of these, but when cacheComponents is enabled, we could suppress + // at least some of them by waiting to log the error until after all in- + // progress renders have completed. Then, only log errors for which there + // was not a corresponding "rejectionHandled" event. + _log.error('unhandledRejection:', reason); +} +function isUnhandledRejectionListenerRegistered() { + const listener = _global[UNHANDLED_REJECTION_LISTENER_KEY]; + return listener !== undefined && process.listeners('unhandledRejection').includes(listener); +} +function registerUnhandledRejectionListener() { + if (isUnhandledRejectionListenerRegistered()) { + return; + } + const listener = _global[UNHANDLED_REJECTION_LISTENER_KEY] ??= unhandledRejectionListener; + process.on('unhandledRejection', listener); +} +function installProcessErrorHandlers(shouldRemoveUncaughtErrorAndRejectionListeners) { + if (!_global.nextInitializedProcessErrorHandlers) { + _global.nextInitializedProcessErrorHandlers = true; + // The conventional wisdom of Node.js and other runtimes is to treat + // unhandled errors as fatal and exit the process. + // + // But Next.js is not a generic JS runtime — it's a specialized runtime for + // React Server Components. + // + // Many unhandled rejections are due to the late-awaiting pattern for + // prefetching data. In Next.js it's OK to call an async function without + // immediately awaiting it, to start the request as soon as possible + // without blocking unncessarily on the result. These can end up + // triggering an "unhandledRejection" if it later turns out that the + // data is not needed to render the page. Example: + // + // const promise = fetchData() + // const shouldShow = await checkCondition() + // if (shouldShow) { + // return + // } + // + // In this example, `fetchData` is called immediately to start the request + // as soon as possible, but if `shouldShow` is false, then it will be + // discarded without unwrapping its result. If it errors, it will trigger + // an "unhandledRejection" event. + // + // Ideally, we would suppress these rejections completely without warning, + // because we don't consider them real errors. (TODO: Currently we do warn.) + // + // But regardless of whether we do or don't warn, we definitely shouldn't + // crash the entire process. + // + // Even a "legit" unhandled error unrelated to prefetching shouldn't + // prevent the rest of the page from rendering. + // + // So, we're going to intentionally override the default error handling + // behavior of the outer JS runtime to be more forgiving + // Remove any existing "unhandledRejection" and "uncaughtException" handlers. + // This is gated behind an experimental flag until we've considered the impact + // in various deployment environments. It's possible this may always need to + // be configurable. + if (shouldRemoveUncaughtErrorAndRejectionListeners) { + process.removeAllListeners('uncaughtException'); + process.removeAllListeners('unhandledRejection'); + } + process.on('rejectionHandled', ()=>{ + // TODO: See note in the unhandledRejection listener above. In the + // future, we may use the "rejectionHandled" event to de-queue an error + // from being logged. + }); + // Unhandled exceptions are errors triggered by non-async functions, so this + // is unrelated to the late-awaiting pattern. However, for similar reasons, + // we still shouldn't crash the process. Just log it. + process.on('uncaughtException', (reason)=>{ + console.error(reason); + }); + } + // Register the listener unconditionally, and not only during the guarded + // initialization above: a previous registration may have been undone by the + // `removeAllListeners` call of a later `installProcessErrorHandlers` call + // (or by external code), and registering is a no-op if the listener is + // still attached. + registerUnhandledRejectionListener(); +} + +//# sourceMappingURL=process-error-handlers.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/process-error-handlers.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/process-error-handlers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..451e1219e5112439e088e426e3c5e16400f7fc21 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/process-error-handlers.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/process-error-handlers.ts"],"sourcesContent":["import * as Log from '../../build/output/log'\n\nlet _global = globalThis as typeof globalThis & {\n nextInitializedProcessErrorHandlers?: boolean\n [UNHANDLED_REJECTION_LISTENER_KEY]?: NodeJS.UnhandledRejectionListener\n}\n\n// The listener function is shared via globalThis so that multiple copies of\n// this module (e.g. in the pre-compiled server bundle and in a route module\n// bundle) still register and detect a single listener instance.\nconst UNHANDLED_REJECTION_LISTENER_KEY = Symbol.for(\n 'next.unhandledRejectionListener'\n)\n\nfunction unhandledRejectionListener(reason: unknown) {\n // Immediately log the error.\n // TODO: Ideally, if we knew that this error was triggered by application\n // code, we would suppress it entirely without logging. We can't reliably\n // detect all of these, but when cacheComponents is enabled, we could suppress\n // at least some of them by waiting to log the error until after all in-\n // progress renders have completed. Then, only log errors for which there\n // was not a corresponding \"rejectionHandled\" event.\n Log.error('unhandledRejection:', reason)\n}\n\n/**\n * Checks if the Next.js unhandled rejection listener is currently attached.\n * This queries the actual process listeners instead of relying on a module\n * global, so it stays accurate even if the listener was removed externally,\n * e.g. via `process.removeAllListeners('unhandledRejection')`.\n */\nexport function isUnhandledRejectionListenerRegistered(): boolean {\n const listener = _global[UNHANDLED_REJECTION_LISTENER_KEY]\n\n return (\n listener !== undefined &&\n process.listeners('unhandledRejection').includes(listener)\n )\n}\n\n/**\n * Registers the Next.js unhandled rejection listener, which logs unhandled\n * rejections and prevents them from crashing the process. Safe to call\n * unconditionally: if the listener is already attached, this is a no-op, so it\n * never registers a duplicate.\n */\nexport function registerUnhandledRejectionListener(): void {\n if (isUnhandledRejectionListenerRegistered()) {\n return\n }\n\n const listener = (_global[UNHANDLED_REJECTION_LISTENER_KEY] ??=\n unhandledRejectionListener)\n\n process.on('unhandledRejection', listener)\n}\n\nexport function installProcessErrorHandlers(\n shouldRemoveUncaughtErrorAndRejectionListeners: boolean\n) {\n if (!_global.nextInitializedProcessErrorHandlers) {\n _global.nextInitializedProcessErrorHandlers = true\n // The conventional wisdom of Node.js and other runtimes is to treat\n // unhandled errors as fatal and exit the process.\n //\n // But Next.js is not a generic JS runtime — it's a specialized runtime for\n // React Server Components.\n //\n // Many unhandled rejections are due to the late-awaiting pattern for\n // prefetching data. In Next.js it's OK to call an async function without\n // immediately awaiting it, to start the request as soon as possible\n // without blocking unncessarily on the result. These can end up\n // triggering an \"unhandledRejection\" if it later turns out that the\n // data is not needed to render the page. Example:\n //\n // const promise = fetchData()\n // const shouldShow = await checkCondition()\n // if (shouldShow) {\n // return \n // }\n //\n // In this example, `fetchData` is called immediately to start the request\n // as soon as possible, but if `shouldShow` is false, then it will be\n // discarded without unwrapping its result. If it errors, it will trigger\n // an \"unhandledRejection\" event.\n //\n // Ideally, we would suppress these rejections completely without warning,\n // because we don't consider them real errors. (TODO: Currently we do warn.)\n //\n // But regardless of whether we do or don't warn, we definitely shouldn't\n // crash the entire process.\n //\n // Even a \"legit\" unhandled error unrelated to prefetching shouldn't\n // prevent the rest of the page from rendering.\n //\n // So, we're going to intentionally override the default error handling\n // behavior of the outer JS runtime to be more forgiving\n\n // Remove any existing \"unhandledRejection\" and \"uncaughtException\" handlers.\n // This is gated behind an experimental flag until we've considered the impact\n // in various deployment environments. It's possible this may always need to\n // be configurable.\n if (shouldRemoveUncaughtErrorAndRejectionListeners) {\n process.removeAllListeners('uncaughtException')\n process.removeAllListeners('unhandledRejection')\n }\n\n process.on('rejectionHandled', () => {\n // TODO: See note in the unhandledRejection listener above. In the\n // future, we may use the \"rejectionHandled\" event to de-queue an error\n // from being logged.\n })\n\n // Unhandled exceptions are errors triggered by non-async functions, so this\n // is unrelated to the late-awaiting pattern. However, for similar reasons,\n // we still shouldn't crash the process. Just log it.\n process.on('uncaughtException', (reason: unknown) => {\n console.error(reason)\n })\n }\n\n // Register the listener unconditionally, and not only during the guarded\n // initialization above: a previous registration may have been undone by the\n // `removeAllListeners` call of a later `installProcessErrorHandlers` call\n // (or by external code), and registering is a no-op if the listener is\n // still attached.\n registerUnhandledRejectionListener()\n}\n"],"names":["installProcessErrorHandlers","isUnhandledRejectionListenerRegistered","registerUnhandledRejectionListener","_global","globalThis","UNHANDLED_REJECTION_LISTENER_KEY","Symbol","for","unhandledRejectionListener","reason","Log","error","listener","undefined","process","listeners","includes","on","shouldRemoveUncaughtErrorAndRejectionListeners","nextInitializedProcessErrorHandlers","removeAllListeners","console"],"mappings":";;;;;;;;;;;;;;;;IAyDgBA,2BAA2B;eAA3BA;;IA1BAC,sCAAsC;eAAtCA;;IAeAC,kCAAkC;eAAlCA;;;6DA9CK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErB,IAAIC,UAAUC;AAKd,4EAA4E;AAC5E,4EAA4E;AAC5E,gEAAgE;AAChE,MAAMC,mCAAmCC,OAAOC,GAAG,CACjD;AAGF,SAASC,2BAA2BC,MAAe;IACjD,6BAA6B;IAC7B,yEAAyE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AC3E,qDAAqD;QACrDH,QAAQG,EAAE,CAAC,qBAAqB,CAACR;YAC/BY,QAAQV,KAAK,CAACF;QAChB;IACF;IAEA,yEAAyE;IACzE,4EAA4E;IAC5E,0EAA0E;IAC1E,uEAAuE;IACvE,kBAAkB;IAClBP;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/random.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/random.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6147ba7c624e6048638b98fbfbb38c26d0227658 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/random.d.ts @@ -0,0 +1,8 @@ +/** + * We extend Math.random() during builds and revalidates to ensure that prerenders don't observe randomness + * When cacheComponents is enabled. randomness is a form of IO even though it resolves synchronously. When cacheComponents is + * enabled we need to ensure that randomness is excluded from prerenders. + * + * The extensions here never error nor alter the random generation itself and thus should be transparent to callers. + */ +export {}; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/random.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/random.js new file mode 100644 index 0000000000000000000000000000000000000000..ed236a0535428e8181c28df6ecd21db2ca835419 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/random.js @@ -0,0 +1,28 @@ +/** + * We extend Math.random() during builds and revalidates to ensure that prerenders don't observe randomness + * When cacheComponents is enabled. randomness is a form of IO even though it resolves synchronously. When cacheComponents is + * enabled we need to ensure that randomness is excluded from prerenders. + * + * The extensions here never error nor alter the random generation itself and thus should be transparent to callers. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _ioutils = require("./io-utils"); +const expression = '`Math.random()`'; +try { + const _random = Math.random; + Math.random = (function random() { + (0, _ioutils.io)(expression, 'random'); + return _random.apply(null, arguments); + // We bind here to alter the `toString` printing to match `Math.random`'s native `toString`. + // eslint-disable-next-line no-extra-bind + }).bind(null); + Object.defineProperty(Math.random, 'name', { + value: 'random' + }); +} catch { + console.error(`Failed to install ${expression} extension. When using \`cacheComponents\` calling this function will not correctly trigger dynamic behavior.`); +} + +//# sourceMappingURL=random.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/random.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/random.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5b255ab8823c4239556f6e3a5094415c0f950fdd --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/random.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/random.tsx"],"sourcesContent":["/**\n * We extend Math.random() during builds and revalidates to ensure that prerenders don't observe randomness\n * When cacheComponents is enabled. randomness is a form of IO even though it resolves synchronously. When cacheComponents is\n * enabled we need to ensure that randomness is excluded from prerenders.\n *\n * The extensions here never error nor alter the random generation itself and thus should be transparent to callers.\n */\n\nimport { io } from './io-utils'\n\nconst expression = '`Math.random()`'\ntry {\n const _random = Math.random\n Math.random = function random() {\n io(expression, 'random')\n return _random.apply(null, arguments as any)\n\n // We bind here to alter the `toString` printing to match `Math.random`'s native `toString`.\n // eslint-disable-next-line no-extra-bind\n }.bind(null)\n Object.defineProperty(Math.random, 'name', { value: 'random' })\n} catch {\n console.error(\n `Failed to install ${expression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n}\n"],"names":["expression","_random","Math","random","io","apply","arguments","bind","Object","defineProperty","value","console","error"],"mappings":"AAAA;;;;;;CAMC;;;;yBAEkB;AAEnB,MAAMA,aAAa;AACnB,IAAI;IACF,MAAMC,UAAUC,KAAKC,MAAM;IAC3BD,KAAKC,MAAM,GAAG,CAAA,SAASA;QACrBC,IAAAA,WAAE,EAACJ,YAAY;QACf,OAAOC,QAAQI,KAAK,CAAC,MAAMC;IAE3B,4FAA4F;IAC5F,yCAAyC;IAC3C,CAAA,EAAEC,IAAI,CAAC;IACPC,OAAOC,cAAc,CAACP,KAAKC,MAAM,EAAE,QAAQ;QAAEO,OAAO;IAAS;AAC/D,EAAE,OAAM;IACNC,QAAQC,KAAK,CACX,CAAC,kBAAkB,EAAEZ,WAAW,6GAA6G,CAAC;AAElJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82efe3a680b04c6da58d3335f95269cde5f0a3b4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.d.ts @@ -0,0 +1,21 @@ +/** + * Manages unhandled rejection listeners to intelligently filter rejections + * from aborted prerenders when cache components are enabled. + * + * THE PROBLEM: + * When we abort prerenders we expect to find numerous unhandled promise rejections due to + * things like awaiting Request data like `headers()`. The rejections are fine and should + * not be construed as problematic so we need to avoid the appearance of a problem by + * omitting them from the logged output. + * + * THE STRATEGY: + * 1. Install a filtering unhandled rejection handler + * 2. Intercept process event methods to capture new handlers in our internal queue + * 3. For each rejection, check if it comes from an aborted prerender context + * 4. If yes, suppress it. If no, delegate to all handlers in our queue + * 5. This provides precise filtering without time-based windows + * + * This ensures we suppress noisy prerender-related rejections while preserving + * normal error logging for genuine unhandled rejections. + */ +export {}; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.js new file mode 100644 index 0000000000000000000000000000000000000000..2452a9cf7194dbfebb24a93eb7b14baf1dd98c32 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.js @@ -0,0 +1,507 @@ +/** + * Manages unhandled rejection listeners to intelligently filter rejections + * from aborted prerenders when cache components are enabled. + * + * THE PROBLEM: + * When we abort prerenders we expect to find numerous unhandled promise rejections due to + * things like awaiting Request data like `headers()`. The rejections are fine and should + * not be construed as problematic so we need to avoid the appearance of a problem by + * omitting them from the logged output. + * + * THE STRATEGY: + * 1. Install a filtering unhandled rejection handler + * 2. Intercept process event methods to capture new handlers in our internal queue + * 3. For each rejection, check if it comes from an aborted prerender context + * 4. If yes, suppress it. If no, delegate to all handlers in our queue + * 5. This provides precise filtering without time-based windows + * + * This ensures we suppress noisy prerender-related rejections while preserving + * normal error logging for genuine unhandled rejections. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const MODE = process.env.NEXT_UNHANDLED_REJECTION_FILTER; +let ENABLE_UHR_FILTER = true; +let UHR_FILTER_LOG_LEVEL = 'warn'; +switch(MODE){ + case 'silent': + UHR_FILTER_LOG_LEVEL = 'silent'; + break; + case 'debug': + UHR_FILTER_LOG_LEVEL = 'debug'; + break; + case 'false': + case 'disabled': + case '0': + ENABLE_UHR_FILTER = false; + break; + case '': + case undefined: + case 'enabled': + case 'true': + case '1': + break; + default: + if (typeof MODE === 'string') { + console.error(`NEXT_UNHANDLED_REJECTION_FILTER has an unrecognized value: ${JSON.stringify(MODE)}. Use "enabled", "disabled", "silent", or "debug", or omit the environment variable altogether`); + } +} +let debug; +let debugWithTrace; +let warn; +let warnWithTrace; +switch(UHR_FILTER_LOG_LEVEL){ + case 'debug': + debug = (message)=>console.log('[Next.js Unhandled Rejection Filter]: ' + message); + debugWithTrace = (message)=>{ + console.log(new DebugWithStack(message)); + }; + // Intentional fallthrough + case 'warn': + warn = (message)=>{ + console.warn('[Next.js Unhandled Rejection Filter]: ' + message); + }; + warnWithTrace = (message)=>{ + console.warn(new WarnWithStack(message)); + }; + break; + case 'silent': + default: +} +class DebugWithStack extends Error { + constructor(message){ + super(message); + this.name = '[Next.js Unhandled Rejection Filter]'; + } +} +class WarnWithStack extends Error { + constructor(message){ + super(message); + this.name = '[Next.js Unhandled Rejection Filter]'; + } +} +let didWarnUninstalled = false; +const warnUninstalledOnce = warn ? function warnUninstalledOnce(...args) { + if (!didWarnUninstalled) { + didWarnUninstalled = true; + warn(...args); + } +} : undefined; +// We use a global symbol to detect if the filter has already been installed. +// If two instances of this module are loaded, each captures the other's handler +// as an underlying listener, creating mutual recursion that overflows the stack. +// We error defensively rather than silently degrading. +const FILTER_INSTALLED_KEY = Symbol.for('next.unhandledRejectionFilter'); +let filterInstalled = false; +// We store the proxied listeners for unhandled rejections here. +let underlyingListeners = []; +// We store a unique pointer to each event listener registration to track +// details like whether the listener is a once listener. +let listenerMetadata = []; +// These methods are used to restore the original implementations when uninstalling the patch +let originalProcessAddListener; +let originalProcessRemoveListener; +let originalProcessOn; +let originalProcessOff; +let originalProcessPrependListener; +let originalProcessOnce; +let originalProcessPrependOnceListener; +let originalProcessRemoveAllListeners; +let originalProcessListeners; +// Some of these base methods call others and we don't want them to call the patched version so we +// need a way to synchronously disable the patch temporarily. +let bypassPatch = false; +// This patch ensures that if any patched methods end up calling other methods internally they will +// bypass the patch during their execution. This is important for removeAllListeners in particular +// because it calls removeListener internally and we want to ensure it actually clears the listeners +// from the process queue and not our private queue. +function patchWithoutReentrancy(original, patchedImpl) { + // Produce a function which has the correct name + const patched = { + [original.name]: function(...args) { + if (bypassPatch) { + return Reflect.apply(original, process, args); + } + const previousBypassPatch = bypassPatch; + bypassPatch = true; + try { + return Reflect.apply(patchedImpl, process, args); + } finally{ + bypassPatch = previousBypassPatch; + } + } + }[original.name]; + // Preserve the original toString behavior + Object.defineProperty(patched, 'toString', { + value: original.toString.bind(original), + writable: true, + configurable: true + }); + return patched; +} +const MACGUFFIN_EVENT = 'Next.UnhandledRejectionFilter.MacguffinEvent'; +/** + * Installs a filtering unhandled rejection handler that intelligently suppresses + * rejections from aborted prerender contexts. + * + * This should be called once during server startup to install the global filter. + */ function installUnhandledRejectionFilter() { + if (globalThis[FILTER_INSTALLED_KEY] || filterInstalled) { + // Already installed by another evaluation of this module in the same + // process (e.g., Jest's module system re-evaluating an already-loaded + // module). Safe to skip since the filter is already active. + return; + } + debug == null ? void 0 : debug('Installing Filter'); + // Capture existing handlers + underlyingListeners = Array.from(process.listeners('unhandledRejection')); + // We assume all existing handlers are not "once" + listenerMetadata = underlyingListeners.map((l)=>({ + listener: l, + once: false + })); + // Remove all existing handlers + process.removeAllListeners('unhandledRejection'); + // Install our filtering handler + process.addListener('unhandledRejection', filteringUnhandledRejectionHandler); + // Store the original process methods + originalProcessAddListener = process.addListener; + originalProcessRemoveListener = process.removeListener; + originalProcessOn = process.on; + originalProcessOff = process.off; + originalProcessPrependListener = process.prependListener; + originalProcessOnce = process.once; + originalProcessPrependOnceListener = process.prependOnceListener; + originalProcessRemoveAllListeners = process.removeAllListeners; + originalProcessListeners = process.listeners; + process.addListener = patchWithoutReentrancy(originalProcessAddListener, function(event, listener) { + if (event === 'unhandledRejection') { + debugWithTrace == null ? void 0 : debugWithTrace(`Appending 'unhandledRejection' listener with name \`${listener.name}\`.`); + // We add the listener to a dummy event in case it throws. We don't catch it intentionally + try { + originalProcessAddListener.call(process, MACGUFFIN_EVENT, listener); + } finally{ + // We clean up the added event + originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT); + } + // Add new handlers to our internal queue instead of the process + underlyingListeners.push(listener); + listenerMetadata.push({ + listener, + once: false + }); + return process; + } + // For other events, use the original method + return originalProcessAddListener.call(process, event, listener); + }); + // Intercept process.removeListener (alias for process.off) + process.removeListener = patchWithoutReentrancy(originalProcessRemoveListener, function(event, listener) { + if (event === 'unhandledRejection') { + // Check if they're trying to remove our filtering handler + if (listener === filteringUnhandledRejectionHandler) { + warnUninstalledOnce == null ? void 0 : warnUninstalledOnce(`Uninstalling filter because \`process.removeListener('unhandledRejection', listener)\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders. + +You can silence warnings related to this behavior by running Next.js with \`NEXT_UNHANDLED_REJECTION_FILTER=silent\` environment variable. + +You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED_REJECTION_FILTER=debug\` environment variable.`); + uninstallUnhandledRejectionFilter(); + return process; + } + debugWithTrace == null ? void 0 : debugWithTrace(`Removing 'unhandledRejection' listener with name \`${listener.name}\`.`); + // We remove the listener on a dummy event in case it throws. We don't catch it intentionally + originalProcessRemoveListener.call(process, MACGUFFIN_EVENT, listener); + const index = underlyingListeners.lastIndexOf(listener); + if (index > -1) { + debug == null ? void 0 : debug(`listener found index ${index} and removed.`); + underlyingListeners.splice(index, 1); + listenerMetadata.splice(index, 1); + } else { + debug == null ? void 0 : debug(`listener not found.`); + } + return process; + } + // For other events, use the original method + return originalProcessRemoveListener.call(process, event, listener); + }); + // If the process.on is referentially process.addListener then share the patched version as well + if (originalProcessOn === originalProcessAddListener) { + process.on = process.addListener; + } else { + process.on = patchWithoutReentrancy(originalProcessOn, function(event, listener) { + if (event === 'unhandledRejection') { + debugWithTrace == null ? void 0 : debugWithTrace(`Appending 'unhandledRejection' listener with name \`${listener.name}\`.`); + // We add the listener to a dummy event in case it throws. We don't catch it intentionally + try { + originalProcessOn.call(process, MACGUFFIN_EVENT, listener); + } finally{ + // We clean up the added event + originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT); + } + // Add new handlers to our internal queue instead of the process + underlyingListeners.push(listener); + listenerMetadata.push({ + listener, + once: false + }); + return process; + } + // For other events, use the original method + return originalProcessOn.call(process, event, listener); + }); + } + // If the process.off is referentially process.addListener then share the patched version as well + if (originalProcessOff === originalProcessRemoveListener) { + process.off = process.removeListener; + } else { + process.off = patchWithoutReentrancy(originalProcessOff, function(event, listener) { + if (event === 'unhandledRejection') { + // Check if they're trying to remove our filtering handler + if (listener === filteringUnhandledRejectionHandler) { + warnUninstalledOnce == null ? void 0 : warnUninstalledOnce(`Uninstalling filter because \`process.off('unhandledRejection', listener)\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders. + +You can silence warnings related to this behavior by running Next.js with \`NEXT_UNHANDLED_REJECTION_FILTER=silent\` environment variable. + +You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED_REJECTION_FILTER=debug\` environment variable.`); + uninstallUnhandledRejectionFilter(); + return process; + } + debugWithTrace == null ? void 0 : debugWithTrace(`Removing 'unhandledRejection' listener with name \`${listener.name}\`.`); + // We remove the listener on a dummy event in case it throws. We don't catch it intentionally + originalProcessOff.call(process, MACGUFFIN_EVENT, listener); + const index = underlyingListeners.lastIndexOf(listener); + if (index > -1) { + debug == null ? void 0 : debug(`listener found index ${index} and removed.`); + underlyingListeners.splice(index, 1); + listenerMetadata.splice(index, 1); + } else { + debug == null ? void 0 : debug(`listener not found.`); + } + return process; + } + // For other events, use the original method + return originalProcessOff.call(process, event, listener); + }); + } + // Intercept process.prependListener for handlers that should go first + process.prependListener = patchWithoutReentrancy(originalProcessPrependListener, function(event, listener) { + if (event === 'unhandledRejection') { + debugWithTrace == null ? void 0 : debugWithTrace(`(Prepending) Inserting 'unhandledRejection' listener with name \`${listener.name}\` immediately following the Next.js 'unhandledRejection' filter listener.`); + // We add the listener to a dummy event in case it throws. We don't catch it intentionally + try { + originalProcessPrependListener.call(process, MACGUFFIN_EVENT, listener); + } finally{ + // We clean up the added event + originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT); + } + // Add new handlers to the beginning of our internal queue + underlyingListeners.unshift(listener); + listenerMetadata.unshift({ + listener, + once: false + }); + return process; + } + // For other events, use the original method + return originalProcessPrependListener.call(process, event, listener); + }); + // Intercept process.once for one-time handlers + process.once = patchWithoutReentrancy(originalProcessOnce, function(event, listener) { + if (event === 'unhandledRejection') { + debugWithTrace == null ? void 0 : debugWithTrace(`Appending 'unhandledRejection' once-listener with name \`${listener.name}\`.`); + // We add the listener to a dummy event in case it throws. We don't catch it intentionally + try { + originalProcessOnce.call(process, MACGUFFIN_EVENT, listener); + } finally{ + // We clean up the added event + originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT); + } + underlyingListeners.push(listener); + listenerMetadata.push({ + listener: listener, + once: true + }); + return process; + } + // For other events, use the original method + return originalProcessOnce.call(process, event, listener); + }); + // Intercept process.prependOnceListener for one-time handlers that should go first + process.prependOnceListener = patchWithoutReentrancy(originalProcessPrependOnceListener, function(event, listener) { + if (event === 'unhandledRejection') { + debugWithTrace == null ? void 0 : debugWithTrace(`(Prepending) Inserting 'unhandledRejection' once-listener with name \`${listener.name}\` immediately following the Next.js 'unhandledRejection' filter listener.`); + // We add the listener to a dummy event in case it throws. We don't catch it intentionally + try { + originalProcessPrependOnceListener.call(process, MACGUFFIN_EVENT, listener); + } finally{ + // We clean up the added event + originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT); + } + // Add to the beginning of our internal queue + underlyingListeners.unshift(listener); + listenerMetadata.unshift({ + listener: listener, + once: true + }); + return process; + } + // For other events, use the original method + return originalProcessPrependOnceListener.call(process, event, listener); + }); + // Intercept process.removeAllListeners + process.removeAllListeners = patchWithoutReentrancy(originalProcessRemoveAllListeners, function(event) { + if (event === 'unhandledRejection') { + // TODO add warning for this case once we stop importing this in test scopes automatically. Currently + // we pull this file in whenever build/utils.tsx is imported which is not the right layering. + // The extensions should be loaded from entrypoints like build/index or next-server + // warnRemoveAllOnce?.( + // `\`process.removeAllListeners('unhandledRejection')\` was called. Next.js maintains the first 'unhandledRejection' listener to filter out unnecessary rejection warnings caused by aborting prerenders early. It is not recommended that you uninstall this behavior, but if you want to you must you can acquire the listener with \`process.listeners('unhandledRejection')[0]\` and remove it with \`process.removeListener('unhandledRejection', listener)\`. + // You can silence warnings related to this behavior by running Next.js with \`NEXT_UNHANDLED_REJECTION_FILTER=silent\` environment variable. + // You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED_REJECTION_FILTER=debug\` environment variable.` + // ) + debugWithTrace == null ? void 0 : debugWithTrace(`Removing all 'unhandledRejection' listeners except for the Next.js filter.`); + underlyingListeners.length = 0; + listenerMetadata.length = 0; + return process; + } + // For other specific events, use the original method + if (event !== undefined) { + return originalProcessRemoveAllListeners.call(process, event); + } + // If no event specified (removeAllListeners()), uninstall our patch completely + warnUninstalledOnce == null ? void 0 : warnUninstalledOnce(`Uninstalling filter because \`process.removeAllListeners()\` was called. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders. + +You can silence warnings related to this behavior by running Next.js with \`NEXT_UNHANDLED_REJECTION_FILTER=silent\` environment variable. + +You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED_REJECTION_FILTER=debug\` environment variable.`); + uninstallUnhandledRejectionFilter(); + return originalProcessRemoveAllListeners.call(process); + }); + // Intercept process.listeners to return our internal handlers for unhandled rejection + process.listeners = patchWithoutReentrancy(originalProcessListeners, function(event) { + if (event === 'unhandledRejection') { + debugWithTrace == null ? void 0 : debugWithTrace(`Retrieving all 'unhandledRejection' listeners.`); + return [ + filteringUnhandledRejectionHandler, + ...underlyingListeners + ]; + } + return originalProcessListeners.call(process, event); + }); + filterInstalled = true; + globalThis[FILTER_INSTALLED_KEY] = true; +} +/** + * Uninstalls the unhandled rejection filter and restores original process methods. + * This is called when someone explicitly removes our filtering handler. + * @internal + */ function uninstallUnhandledRejectionFilter() { + if (!filterInstalled) { + warnWithTrace == null ? void 0 : warnWithTrace('Unexpected subsequent filter uninstallation. This is a bug in Next.js'); + return; + } + debug == null ? void 0 : debug('Uninstalling Filter'); + // Restore original process methods + process.on = originalProcessOn; + process.addListener = originalProcessAddListener; + process.once = originalProcessOnce; + process.prependListener = originalProcessPrependListener; + process.prependOnceListener = originalProcessPrependOnceListener; + process.removeListener = originalProcessRemoveListener; + process.off = originalProcessOff; + process.removeAllListeners = originalProcessRemoveAllListeners; + process.listeners = originalProcessListeners; + // Remove our filtering handler + process.removeListener('unhandledRejection', filteringUnhandledRejectionHandler); + // Re-register all the handlers that were in our internal queue + for (const meta of listenerMetadata){ + if (meta.once) { + process.once('unhandledRejection', meta.listener); + } else { + process.addListener('unhandledRejection', meta.listener); + } + } + // Reset state + filterInstalled = false; + underlyingListeners.length = 0; + listenerMetadata.length = 0; +} +/** + * The filtering handler that decides whether to suppress or delegate unhandled rejections. + */ let handlingRejection = false; +function filteringUnhandledRejectionHandler(reason, promise) { + if (handlingRejection) { + // An underlying listener synchronously re-emitted 'unhandledRejection'. + // Re-entering the listener loop would overflow the stack. + return; + } + const capturedListenerMetadata = Array.from(listenerMetadata); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore) { + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-client': + case 'validation-client': + case 'prerender-runtime': + case 'request': + { + const signal = workUnitStore.renderSignal; + if (signal && signal.aborted) { + // This unhandledRejection is from async work spawned in a now + // aborted prerender. We don't need to report this. + return; + } + break; + } + case 'prerender-legacy': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + } + // Not from an aborted prerender, delegate to original handlers + if (capturedListenerMetadata.length === 0) { + // We need to log something because the default behavior when there is + // no event handler installed is to trigger an Unhandled Exception. + // We don't do that here b/c we don't want to rely on this implicit default + // to kill the process since it can be disabled by installing a userland listener + // and you may also choose to run Next.js with args such that unhandled rejections + // do not automatically terminate the process. + console.error('Unhandled Rejection:', reason); + } else { + handlingRejection = true; + try { + for (const meta of capturedListenerMetadata){ + if (meta.once) { + // This is a once listener. we remove it from our set before we call it + const index = listenerMetadata.indexOf(meta); + if (index !== -1) { + underlyingListeners.splice(index, 1); + listenerMetadata.splice(index, 1); + } + } + const listener = meta.listener; + listener(reason, promise); + } + } catch (error) { + // If any handlers error we produce an Uncaught Exception + setImmediate(()=>{ + throw error; + }); + } finally{ + handlingRejection = false; + } + } +} +// Install the filter when this module is imported +if (ENABLE_UHR_FILTER) { + installUnhandledRejectionFilter(); +} + +//# sourceMappingURL=unhandled-rejection.external.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.js.map new file mode 100644 index 0000000000000000000000000000000000000000..025ed58563a2be03395435df21ef43069d7ba2e9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/unhandled-rejection.external.tsx"],"sourcesContent":["/**\n * Manages unhandled rejection listeners to intelligently filter rejections\n * from aborted prerenders when cache components are enabled.\n *\n * THE PROBLEM:\n * When we abort prerenders we expect to find numerous unhandled promise rejections due to\n * things like awaiting Request data like `headers()`. The rejections are fine and should\n * not be construed as problematic so we need to avoid the appearance of a problem by\n * omitting them from the logged output.\n *\n * THE STRATEGY:\n * 1. Install a filtering unhandled rejection handler\n * 2. Intercept process event methods to capture new handlers in our internal queue\n * 3. For each rejection, check if it comes from an aborted prerender context\n * 4. If yes, suppress it. If no, delegate to all handlers in our queue\n * 5. This provides precise filtering without time-based windows\n *\n * This ensures we suppress noisy prerender-related rejections while preserving\n * normal error logging for genuine unhandled rejections.\n */\n\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\n\nconst MODE:\n | 'enabled'\n | 'debug'\n | 'silent'\n | 'true'\n | 'false'\n | '1'\n | '0'\n | ''\n | string\n | undefined = process.env.NEXT_UNHANDLED_REJECTION_FILTER\n\nlet ENABLE_UHR_FILTER = true\nlet UHR_FILTER_LOG_LEVEL: 'debug' | 'warn' | 'silent' = 'warn'\n\nswitch (MODE) {\n case 'silent':\n UHR_FILTER_LOG_LEVEL = 'silent'\n break\n case 'debug':\n UHR_FILTER_LOG_LEVEL = 'debug'\n break\n case 'false':\n case 'disabled':\n case '0':\n ENABLE_UHR_FILTER = false\n break\n case '':\n case undefined:\n case 'enabled':\n case 'true':\n case '1':\n break\n default:\n if (typeof MODE === 'string') {\n console.error(\n `NEXT_UNHANDLED_REJECTION_FILTER has an unrecognized value: ${JSON.stringify(MODE)}. Use \"enabled\", \"disabled\", \"silent\", or \"debug\", or omit the environment variable altogether`\n )\n }\n}\n\nlet debug: typeof console.debug | undefined\nlet debugWithTrace: typeof console.debug | undefined\nlet warn: typeof console.warn | undefined\nlet warnWithTrace: typeof console.warn | undefined\n\nswitch (UHR_FILTER_LOG_LEVEL) {\n case 'debug':\n debug = (message: string) =>\n console.log('[Next.js Unhandled Rejection Filter]: ' + message)\n debugWithTrace = (message: string) => {\n console.log(new DebugWithStack(message))\n }\n // Intentional fallthrough\n case 'warn':\n warn = (message: string) => {\n console.warn('[Next.js Unhandled Rejection Filter]: ' + message)\n }\n warnWithTrace = (message: string) => {\n console.warn(new WarnWithStack(message))\n }\n break\n case 'silent':\n default:\n}\n\nclass DebugWithStack extends Error {\n constructor(message: string) {\n super(message)\n this.name = '[Next.js Unhandled Rejection Filter]'\n }\n}\n\nclass WarnWithStack extends Error {\n constructor(message: string) {\n super(message)\n this.name = '[Next.js Unhandled Rejection Filter]'\n }\n}\n\nlet didWarnUninstalled = false\nconst warnUninstalledOnce = warn\n ? function warnUninstalledOnce(...args: any[]) {\n if (!didWarnUninstalled) {\n didWarnUninstalled = true\n warn(...args)\n }\n }\n : undefined\n\ntype ListenerMetadata = {\n listener: NodeJS.UnhandledRejectionListener\n once: boolean\n}\n\n// We use a global symbol to detect if the filter has already been installed.\n// If two instances of this module are loaded, each captures the other's handler\n// as an underlying listener, creating mutual recursion that overflows the stack.\n// We error defensively rather than silently degrading.\nconst FILTER_INSTALLED_KEY = Symbol.for('next.unhandledRejectionFilter')\nlet filterInstalled = false\n\n// We store the proxied listeners for unhandled rejections here.\nlet underlyingListeners: Array = []\n// We store a unique pointer to each event listener registration to track\n// details like whether the listener is a once listener.\nlet listenerMetadata: Array = []\n\n// These methods are used to restore the original implementations when uninstalling the patch\nlet originalProcessAddListener: typeof process.addListener\nlet originalProcessRemoveListener: typeof process.removeListener\nlet originalProcessOn: typeof process.on\nlet originalProcessOff: typeof process.off\nlet originalProcessPrependListener: typeof process.prependListener\nlet originalProcessOnce: typeof process.once\nlet originalProcessPrependOnceListener: typeof process.prependOnceListener\nlet originalProcessRemoveAllListeners: typeof process.removeAllListeners\nlet originalProcessListeners: typeof process.listeners\n\ntype UnderlyingMethod =\n | typeof originalProcessAddListener\n | typeof originalProcessRemoveListener\n | typeof originalProcessOn\n | typeof originalProcessOff\n | typeof originalProcessPrependListener\n | typeof originalProcessOnce\n | typeof originalProcessPrependOnceListener\n | typeof originalProcessRemoveAllListeners\n | typeof originalProcessListeners\n\n// Some of these base methods call others and we don't want them to call the patched version so we\n// need a way to synchronously disable the patch temporarily.\nlet bypassPatch = false\n\n// This patch ensures that if any patched methods end up calling other methods internally they will\n// bypass the patch during their execution. This is important for removeAllListeners in particular\n// because it calls removeListener internally and we want to ensure it actually clears the listeners\n// from the process queue and not our private queue.\nfunction patchWithoutReentrancy(\n original: T,\n patchedImpl: T\n): T {\n // Produce a function which has the correct name\n const patched = {\n [original.name]: function (...args: Parameters) {\n if (bypassPatch) {\n return Reflect.apply(original, process, args)\n }\n\n const previousBypassPatch = bypassPatch\n bypassPatch = true\n try {\n return Reflect.apply(patchedImpl, process, args)\n } finally {\n bypassPatch = previousBypassPatch\n }\n } as any,\n }[original.name]\n\n // Preserve the original toString behavior\n Object.defineProperty(patched, 'toString', {\n value: original.toString.bind(original),\n writable: true,\n configurable: true,\n })\n\n return patched\n}\n\nconst MACGUFFIN_EVENT = 'Next.UnhandledRejectionFilter.MacguffinEvent'\n\n/**\n * Installs a filtering unhandled rejection handler that intelligently suppresses\n * rejections from aborted prerender contexts.\n *\n * This should be called once during server startup to install the global filter.\n */\nfunction installUnhandledRejectionFilter(): void {\n if ((globalThis as any)[FILTER_INSTALLED_KEY] || filterInstalled) {\n // Already installed by another evaluation of this module in the same\n // process (e.g., Jest's module system re-evaluating an already-loaded\n // module). Safe to skip since the filter is already active.\n return\n }\n\n debug?.('Installing Filter')\n\n // Capture existing handlers\n underlyingListeners = Array.from(process.listeners('unhandledRejection'))\n // We assume all existing handlers are not \"once\"\n listenerMetadata = underlyingListeners.map((l) => ({\n listener: l,\n once: false,\n }))\n\n // Remove all existing handlers\n process.removeAllListeners('unhandledRejection')\n\n // Install our filtering handler\n process.addListener('unhandledRejection', filteringUnhandledRejectionHandler)\n\n // Store the original process methods\n originalProcessAddListener = process.addListener\n originalProcessRemoveListener = process.removeListener\n originalProcessOn = process.on\n originalProcessOff = process.off\n originalProcessPrependListener = process.prependListener\n originalProcessOnce = process.once\n originalProcessPrependOnceListener = process.prependOnceListener\n originalProcessRemoveAllListeners = process.removeAllListeners\n originalProcessListeners = process.listeners\n\n process.addListener = patchWithoutReentrancy(\n originalProcessAddListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessAddListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n // Add new handlers to our internal queue instead of the process\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessAddListener.call(process, event as any, listener)\n } as typeof process.addListener\n )\n\n // Intercept process.removeListener (alias for process.off)\n process.removeListener = patchWithoutReentrancy(\n originalProcessRemoveListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n // Check if they're trying to remove our filtering handler\n if (listener === filteringUnhandledRejectionHandler) {\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.removeListener('unhandledRejection', listener)\\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return process\n }\n\n debugWithTrace?.(\n `Removing 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We remove the listener on a dummy event in case it throws. We don't catch it intentionally\n originalProcessRemoveListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n const index = underlyingListeners.lastIndexOf(listener)\n if (index > -1) {\n debug?.(`listener found index ${index} and removed.`)\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n } else {\n debug?.(`listener not found.`)\n }\n return process\n }\n // For other events, use the original method\n return originalProcessRemoveListener.call(process, event, listener)\n } as typeof process.removeListener\n )\n\n // If the process.on is referentially process.addListener then share the patched version as well\n if (originalProcessOn === originalProcessAddListener) {\n process.on = process.addListener\n } else {\n process.on = patchWithoutReentrancy(originalProcessOn, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessOn.call(process, MACGUFFIN_EVENT as any, listener)\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n // Add new handlers to our internal queue instead of the process\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessOn.call(process, event, listener)\n } as typeof process.on)\n }\n\n // If the process.off is referentially process.addListener then share the patched version as well\n if (originalProcessOff === originalProcessRemoveListener) {\n process.off = process.removeListener\n } else {\n process.off = patchWithoutReentrancy(originalProcessOff, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n // Check if they're trying to remove our filtering handler\n if (listener === filteringUnhandledRejectionHandler) {\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.off('unhandledRejection', listener)\\` was called with the filter listener. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return process\n }\n\n debugWithTrace?.(\n `Removing 'unhandledRejection' listener with name \\`${listener.name}\\`.`\n )\n // We remove the listener on a dummy event in case it throws. We don't catch it intentionally\n originalProcessOff.call(process, MACGUFFIN_EVENT as any, listener)\n const index = underlyingListeners.lastIndexOf(listener)\n if (index > -1) {\n debug?.(`listener found index ${index} and removed.`)\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n } else {\n debug?.(`listener not found.`)\n }\n return process\n }\n // For other events, use the original method\n return originalProcessOff.call(process, event, listener)\n } as typeof process.off)\n }\n\n // Intercept process.prependListener for handlers that should go first\n process.prependListener = patchWithoutReentrancy(\n originalProcessPrependListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `(Prepending) Inserting 'unhandledRejection' listener with name \\`${listener.name}\\` immediately following the Next.js 'unhandledRejection' filter listener.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessPrependListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n\n // Add new handlers to the beginning of our internal queue\n underlyingListeners.unshift(\n listener as NodeJS.UnhandledRejectionListener\n )\n listenerMetadata.unshift({ listener, once: false })\n return process\n }\n // For other events, use the original method\n return originalProcessPrependListener.call(\n process,\n event as any,\n listener\n )\n } as typeof process.prependListener\n )\n\n // Intercept process.once for one-time handlers\n process.once = patchWithoutReentrancy(originalProcessOnce, function (\n event: string | symbol,\n listener: (...args: any[]) => void\n ) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `Appending 'unhandledRejection' once-listener with name \\`${listener.name}\\`.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessOnce.call(process, MACGUFFIN_EVENT as any, listener)\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n underlyingListeners.push(listener as NodeJS.UnhandledRejectionListener)\n listenerMetadata.push({\n listener: listener as NodeJS.UnhandledRejectionListener,\n once: true,\n })\n return process\n }\n // For other events, use the original method\n return originalProcessOnce.call(process, event, listener)\n } as typeof process.once)\n\n // Intercept process.prependOnceListener for one-time handlers that should go first\n process.prependOnceListener = patchWithoutReentrancy(\n originalProcessPrependOnceListener,\n function (event: string | symbol, listener: (...args: any[]) => void) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(\n `(Prepending) Inserting 'unhandledRejection' once-listener with name \\`${listener.name}\\` immediately following the Next.js 'unhandledRejection' filter listener.`\n )\n // We add the listener to a dummy event in case it throws. We don't catch it intentionally\n try {\n originalProcessPrependOnceListener.call(\n process,\n MACGUFFIN_EVENT as any,\n listener\n )\n } finally {\n // We clean up the added event\n originalProcessRemoveAllListeners.call(process, MACGUFFIN_EVENT)\n }\n\n // Add to the beginning of our internal queue\n underlyingListeners.unshift(\n listener as NodeJS.UnhandledRejectionListener\n )\n listenerMetadata.unshift({\n listener: listener as NodeJS.UnhandledRejectionListener,\n once: true,\n })\n return process\n }\n // For other events, use the original method\n return originalProcessPrependOnceListener.call(\n process,\n event as any,\n listener\n )\n } as typeof process.prependOnceListener\n )\n\n // Intercept process.removeAllListeners\n process.removeAllListeners = patchWithoutReentrancy(\n originalProcessRemoveAllListeners,\n function (event?: string | symbol) {\n if (event === 'unhandledRejection') {\n // TODO add warning for this case once we stop importing this in test scopes automatically. Currently\n // we pull this file in whenever build/utils.tsx is imported which is not the right layering.\n // The extensions should be loaded from entrypoints like build/index or next-server\n // warnRemoveAllOnce?.(\n // `\\`process.removeAllListeners('unhandledRejection')\\` was called. Next.js maintains the first 'unhandledRejection' listener to filter out unnecessary rejection warnings caused by aborting prerenders early. It is not recommended that you uninstall this behavior, but if you want to you must you can acquire the listener with \\`process.listeners('unhandledRejection')[0]\\` and remove it with \\`process.removeListener('unhandledRejection', listener)\\`.\n\n // You can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\n // You can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n // )\n debugWithTrace?.(\n `Removing all 'unhandledRejection' listeners except for the Next.js filter.`\n )\n\n underlyingListeners.length = 0\n listenerMetadata.length = 0\n return process\n }\n\n // For other specific events, use the original method\n if (event !== undefined) {\n return originalProcessRemoveAllListeners.call(process, event)\n }\n\n // If no event specified (removeAllListeners()), uninstall our patch completely\n warnUninstalledOnce?.(\n `Uninstalling filter because \\`process.removeAllListeners()\\` was called. Uninstalling this filter is not recommended and will cause you to observe 'unhandledRejection' events related to intentionally aborted prerenders.\n\nYou can silence warnings related to this behavior by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=silent\\` environment variable.\n\nYou can debug event listener operations by running Next.js with \\`NEXT_UNHANDLED_REJECTION_FILTER=debug\\` environment variable.`\n )\n uninstallUnhandledRejectionFilter()\n return originalProcessRemoveAllListeners.call(process)\n } as typeof process.removeAllListeners\n )\n\n // Intercept process.listeners to return our internal handlers for unhandled rejection\n process.listeners = patchWithoutReentrancy(\n originalProcessListeners,\n function (event: string | symbol) {\n if (event === 'unhandledRejection') {\n debugWithTrace?.(`Retrieving all 'unhandledRejection' listeners.`)\n return [filteringUnhandledRejectionHandler, ...underlyingListeners]\n }\n return originalProcessListeners.call(process, event as any)\n } as typeof process.listeners\n )\n\n filterInstalled = true\n ;(globalThis as any)[FILTER_INSTALLED_KEY] = true\n}\n\n/**\n * Uninstalls the unhandled rejection filter and restores original process methods.\n * This is called when someone explicitly removes our filtering handler.\n * @internal\n */\nfunction uninstallUnhandledRejectionFilter(): void {\n if (!filterInstalled) {\n warnWithTrace?.(\n 'Unexpected subsequent filter uninstallation. This is a bug in Next.js'\n )\n return\n }\n\n debug?.('Uninstalling Filter')\n\n // Restore original process methods\n process.on = originalProcessOn\n process.addListener = originalProcessAddListener\n process.once = originalProcessOnce\n process.prependListener = originalProcessPrependListener\n process.prependOnceListener = originalProcessPrependOnceListener\n process.removeListener = originalProcessRemoveListener\n process.off = originalProcessOff\n process.removeAllListeners = originalProcessRemoveAllListeners\n process.listeners = originalProcessListeners\n\n // Remove our filtering handler\n process.removeListener(\n 'unhandledRejection',\n filteringUnhandledRejectionHandler\n )\n\n // Re-register all the handlers that were in our internal queue\n for (const meta of listenerMetadata) {\n if (meta.once) {\n process.once('unhandledRejection', meta.listener)\n } else {\n process.addListener('unhandledRejection', meta.listener)\n }\n }\n\n // Reset state\n filterInstalled = false\n underlyingListeners.length = 0\n listenerMetadata.length = 0\n}\n\n/**\n * The filtering handler that decides whether to suppress or delegate unhandled rejections.\n */\nlet handlingRejection = false\n\nfunction filteringUnhandledRejectionHandler(\n reason: any,\n promise: Promise\n): void {\n if (handlingRejection) {\n // An underlying listener synchronously re-emitted 'unhandledRejection'.\n // Re-entering the listener loop would overflow the stack.\n return\n }\n\n const capturedListenerMetadata = Array.from(listenerMetadata)\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'request': {\n const signal = workUnitStore.renderSignal\n if (signal && signal.aborted) {\n // This unhandledRejection is from async work spawned in a now\n // aborted prerender. We don't need to report this.\n return\n }\n break\n }\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n // Not from an aborted prerender, delegate to original handlers\n if (capturedListenerMetadata.length === 0) {\n // We need to log something because the default behavior when there is\n // no event handler installed is to trigger an Unhandled Exception.\n // We don't do that here b/c we don't want to rely on this implicit default\n // to kill the process since it can be disabled by installing a userland listener\n // and you may also choose to run Next.js with args such that unhandled rejections\n // do not automatically terminate the process.\n console.error('Unhandled Rejection:', reason)\n } else {\n handlingRejection = true\n try {\n for (const meta of capturedListenerMetadata) {\n if (meta.once) {\n // This is a once listener. we remove it from our set before we call it\n const index = listenerMetadata.indexOf(meta)\n if (index !== -1) {\n underlyingListeners.splice(index, 1)\n listenerMetadata.splice(index, 1)\n }\n }\n const listener = meta.listener\n listener(reason, promise)\n }\n } catch (error) {\n // If any handlers error we produce an Uncaught Exception\n setImmediate(() => {\n throw error\n })\n } finally {\n handlingRejection = false\n }\n }\n}\n\n// Install the filter when this module is imported\nif (ENABLE_UHR_FILTER) {\n installUnhandledRejectionFilter()\n}\n"],"names":["MODE","process","env","NEXT_UNHANDLED_REJECTION_FILTER","ENABLE_UHR_FILTER","UHR_FILTER_LOG_LEVEL","undefined","console","error","JSON","stringify","debug","debugWithTrace","warn","warnWithTrace","message","log","DebugWithStack","WarnWithStack","Error","constructor","name","didWarnUninstalled","warnUninstalledOnce","args","FILTER_INSTALLED_KEY","Symbol","for","filterInstalled","underlyingListeners","listenerMetadata","originalProcessAddListener","originalProcessRemoveListener","originalProcessOn","originalProcessOff","originalProcessPrependListener","originalProcessOnce","originalProcessPrependOnceListener","originalProcessRemoveAllListeners","originalProcessListeners","bypassPatch","patchWithoutReentrancy","original","patchedImpl","patched","Reflect","apply","previousBypassPatch","Object","defineProperty","value","toString","bind","writable","configurable","MACGUFFIN_EVENT","installUnhandledRejectionFilter","globalThis","Array","from","listeners","map","l","listener","once","removeAllListeners","addListener","filteringUnhandledRejectionHandler","removeListener","on","off","prependListener","prependOnceListener","event","call","push","uninstallUnhandledRejectionFilter","index","lastIndexOf","splice","unshift","length","meta","handlingRejection","reason","promise","capturedListenerMetadata","workUnitStore","workUnitAsyncStorage","getStore","type","signal","renderSignal","aborted","indexOf","setImmediate"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;CAmBC;;;;8CAEoC;AAErC,M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AI;YACF,KAAK,MAAMD,QAAQI,yBAA0B;gBAC3C,IAAIJ,KAAKlB,IAAI,EAAE;oBACb,uEAAuE;oBACvE,MAAMa,QAAQ/C,iBAAiBgE,OAAO,CAACZ;oBACvC,IAAIL,UAAU,CAAC,GAAG;wBAChBhD,oBAAoBkD,MAAM,CAACF,OAAO;wBAClC/C,iBAAiBiD,MAAM,CAACF,OAAO;oBACjC;gBACF;gBACA,MAAMd,WAAWmB,KAAKnB,QAAQ;gBAC9BA,SAASqB,QAAQC;YACnB;QACF,EAAE,OAAO7E,OAAO;YACd,yDAAyD;YACzDuF,aAAa;gBACX,MAAMvF;YACR;QACF,SAAU;YACR2E,oBAAoB;QACtB;IACF;AACF;AAEA,kDAAkD;AAClD,IAAI/E,mBAAmB;IACrBoD;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/web-crypto.d.ts b/e-commerce/node_modules/next/dist/server/node-environment-extensions/web-crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..842cba0bcf1a3f80fca8a81df4be89f6ba2cebe7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/web-crypto.d.ts @@ -0,0 +1,9 @@ +/** + * We extend Web Crypto APIs during builds and revalidates to ensure that prerenders don't observe random bytes + * When cacheComponents is enabled. Random bytes are a form of IO even if they resolve synchronously. When cacheComponents is + * enabled we need to ensure that random bytes are excluded from prerenders unless they are cached. + * + * + * The extensions here never error nor alter the underlying return values and thus should be transparent to callers. + */ +export {}; diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/web-crypto.js b/e-commerce/node_modules/next/dist/server/node-environment-extensions/web-crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..6f00b75a1a9b75e1be6321619d527a218e1a0e4e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/web-crypto.js @@ -0,0 +1,45 @@ +/** + * We extend Web Crypto APIs during builds and revalidates to ensure that prerenders don't observe random bytes + * When cacheComponents is enabled. Random bytes are a form of IO even if they resolve synchronously. When cacheComponents is + * enabled we need to ensure that random bytes are excluded from prerenders unless they are cached. + * + * + * The extensions here never error nor alter the underlying return values and thus should be transparent to callers. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _ioutils = require("./io-utils"); +let webCrypto; +if (process.env.NEXT_RUNTIME === 'edge') { + webCrypto = crypto; +} else { + if (typeof crypto === 'undefined') { + // @ts-expect-error -- TODO: Is this actually safe? + webCrypto = require('node:crypto').webcrypto; + } else { + webCrypto = crypto; + } +} +const getRandomValuesExpression = '`crypto.getRandomValues()`'; +try { + const _getRandomValues = webCrypto.getRandomValues; + webCrypto.getRandomValues = function getRandomValues() { + (0, _ioutils.io)(getRandomValuesExpression, 'crypto'); + return _getRandomValues.apply(webCrypto, arguments); + }; +} catch { + console.error(`Failed to install ${getRandomValuesExpression} extension. When using \`cacheComponents\` calling this function will not correctly trigger dynamic behavior.`); +} +const randomUUIDExpression = '`crypto.randomUUID()`'; +try { + const _randomUUID = webCrypto.randomUUID; + webCrypto.randomUUID = function randomUUID() { + (0, _ioutils.io)(randomUUIDExpression, 'crypto'); + return _randomUUID.apply(webCrypto, arguments); + }; +} catch { + console.error(`Failed to install ${getRandomValuesExpression} extension. When using \`cacheComponents\` calling this function will not correctly trigger dynamic behavior.`); +} + +//# sourceMappingURL=web-crypto.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment-extensions/web-crypto.js.map b/e-commerce/node_modules/next/dist/server/node-environment-extensions/web-crypto.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3a111a2d823b35872ea871eaf9e4f7eb2cfb116f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment-extensions/web-crypto.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/node-environment-extensions/web-crypto.tsx"],"sourcesContent":["/**\n * We extend Web Crypto APIs during builds and revalidates to ensure that prerenders don't observe random bytes\n * When cacheComponents is enabled. Random bytes are a form of IO even if they resolve synchronously. When cacheComponents is\n * enabled we need to ensure that random bytes are excluded from prerenders unless they are cached.\n *\n *\n * The extensions here never error nor alter the underlying return values and thus should be transparent to callers.\n */\n\nimport { io } from './io-utils'\n\nlet webCrypto: typeof crypto\nif (process.env.NEXT_RUNTIME === 'edge') {\n webCrypto = crypto\n} else {\n if (typeof crypto === 'undefined') {\n // @ts-expect-error -- TODO: Is this actually safe?\n webCrypto = (require('node:crypto') as typeof import('node:crypto'))\n .webcrypto\n } else {\n webCrypto = crypto\n }\n}\n\nconst getRandomValuesExpression = '`crypto.getRandomValues()`'\ntry {\n const _getRandomValues = webCrypto.getRandomValues\n webCrypto.getRandomValues = function getRandomValues() {\n io(getRandomValuesExpression, 'crypto')\n return _getRandomValues.apply(webCrypto, arguments as any)\n }\n} catch {\n console.error(\n `Failed to install ${getRandomValuesExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n}\n\nconst randomUUIDExpression = '`crypto.randomUUID()`'\ntry {\n const _randomUUID = webCrypto.randomUUID\n webCrypto.randomUUID = function randomUUID() {\n io(randomUUIDExpression, 'crypto')\n return _randomUUID.apply(webCrypto, arguments as any)\n } as typeof _randomUUID\n} catch {\n console.error(\n `Failed to install ${getRandomValuesExpression} extension. When using \\`cacheComponents\\` calling this function will not correctly trigger dynamic behavior.`\n )\n}\n"],"names":["webCrypto","process","env","NEXT_RUNTIME","crypto","require","webcrypto","getRandomValuesExpression","_getRandomValues","getRandomValues","io","apply","arguments","console","error","randomUUIDExpression","_randomUUID","randomUUID"],"mappings":"AAAA;;;;;;;CAOC;;;;yBAEkB;AAEnB,IAAIA;AACJ,IAAIC,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCH,YAAYI;AACd,OAAO;IACL,IAAI,OAAOA,WAAW,aAAa;QACjC,mDAAmD;QACnDJ,YAAY,AAACK,QAAQ,eAClBC,SAAS;IACd,OAAO;QACLN,YAAYI;IACd;AACF;AAEA,MAAMG,4BAA4B;AAClC,IAAI;IACF,MAAMC,mBAAmBR,UAAUS,eAAe;IAClDT,UAAUS,eAAe,GAAG,SAASA;QACnCC,IAAAA,WAAE,EAACH,2BAA2B;QAC9B,OAAOC,iBAAiBG,KAAK,CAACX,WAAWY;IAC3C;AACF,EAAE,OAAM;IACNC,QAAQC,KAAK,CACX,CAAC,kBAAkB,EAAEP,0BAA0B,6GAA6G,CAAC;AAEjK;AAEA,MAAMQ,uBAAuB;AAC7B,IAAI;IACF,MAAMC,cAAchB,UAAUiB,UAAU;IACxCjB,UAAUiB,UAAU,GAAG,SAASA;QAC9BP,IAAAA,WAAE,EAACK,sBAAsB;QACzB,OAAOC,YAAYL,KAAK,CAACX,WAAWY;IACtC;AACF,EAAE,OAAM;IACNC,QAAQC,KAAK,CACX,CAAC,kBAAkB,EAAEP,0BAA0B,6GAA6G,CAAC;AAEjK","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment.d.ts b/e-commerce/node_modules/next/dist/server/node-environment.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dec5b01e6bd992f113cf744b43ad7e6497231a3e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment.d.ts @@ -0,0 +1,11 @@ +import './node-environment-baseline'; +import './node-environment-extensions/error-inspect'; +import './node-environment-extensions/console-file'; +import './node-environment-extensions/console-exit'; +import './node-environment-extensions/console-dim.external'; +import './node-environment-extensions/unhandled-rejection.external'; +import './node-environment-extensions/random'; +import './node-environment-extensions/date'; +import './node-environment-extensions/web-crypto'; +import './node-environment-extensions/node-crypto'; +import './node-environment-extensions/fast-set-immediate.external'; diff --git a/e-commerce/node_modules/next/dist/server/node-environment.js b/e-commerce/node_modules/next/dist/server/node-environment.js new file mode 100644 index 0000000000000000000000000000000000000000..e8492daffdb8bbc1f0bcd6d847f7956fbabc4211 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment.js @@ -0,0 +1,19 @@ +// This file should be imported before any others. It sets up the environment +// for later imports to work properly. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +require("./node-environment-baseline"); +require("./node-environment-extensions/error-inspect"); +require("./node-environment-extensions/console-file"); +require("./node-environment-extensions/console-exit"); +require("./node-environment-extensions/console-dim.external"); +require("./node-environment-extensions/unhandled-rejection.external"); +require("./node-environment-extensions/random"); +require("./node-environment-extensions/date"); +require("./node-environment-extensions/web-crypto"); +require("./node-environment-extensions/node-crypto"); +require("./node-environment-extensions/fast-set-immediate.external"); + +//# sourceMappingURL=node-environment.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-environment.js.map b/e-commerce/node_modules/next/dist/server/node-environment.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b22bb2b9a89be731e8611380580eb0c159f38dba --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-environment.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/node-environment.ts"],"sourcesContent":["// This file should be imported before any others. It sets up the environment\n// for later imports to work properly.\n\nimport './node-environment-baseline'\n// Import as early as possible so that unexpected errors in other extensions are properly formatted.\n// Has to come after baseline since error-inspect requires AsyncLocalStorage that baseline provides.\nimport './node-environment-extensions/error-inspect'\n\n// console file needs to go first because we want to be in a dimmed scope before\n// deciding if we ought to write the log to file.\nimport './node-environment-extensions/console-file'\nimport './node-environment-extensions/console-exit'\nimport './node-environment-extensions/console-dim.external'\n\nimport './node-environment-extensions/unhandled-rejection.external'\nimport './node-environment-extensions/random'\nimport './node-environment-extensions/date'\nimport './node-environment-extensions/web-crypto'\nimport './node-environment-extensions/node-crypto'\nimport './node-environment-extensions/fast-set-immediate.external'\n"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,sCAAsC;;;;;QAE/B;QAGA;QAIA;QACA;QACA;QAEA;QACA;QACA;QACA;QACA;QACA","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-polyfill-crypto.d.ts b/e-commerce/node_modules/next/dist/server/node-polyfill-crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/node-polyfill-crypto.js b/e-commerce/node_modules/next/dist/server/node-polyfill-crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..2b8e3f41206f2c78f72ce41a511bfd8a4289a5ca --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-polyfill-crypto.js @@ -0,0 +1,21 @@ +// Polyfill crypto() in the Node.js environment +"use strict"; +if (!global.crypto) { + let webcrypto; + Object.defineProperty(global, 'crypto', { + enumerable: false, + configurable: true, + get () { + if (!webcrypto) { + // @ts-expect-error -- TODO: Is this actually safe? + webcrypto = require('node:crypto').webcrypto; + } + return webcrypto; + }, + set (value) { + webcrypto = value; + } + }); +} + +//# sourceMappingURL=node-polyfill-crypto.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/node-polyfill-crypto.js.map b/e-commerce/node_modules/next/dist/server/node-polyfill-crypto.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1d6b6b63c9183f61ae85eb785fe8277b1956c2cc --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/node-polyfill-crypto.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/node-polyfill-crypto.ts"],"sourcesContent":["// Polyfill crypto() in the Node.js environment\n\nif (!global.crypto) {\n let webcrypto: Crypto | undefined\n\n Object.defineProperty(global, 'crypto', {\n enumerable: false,\n configurable: true,\n get() {\n if (!webcrypto) {\n // @ts-expect-error -- TODO: Is this actually safe?\n webcrypto = (require('node:crypto') as typeof import('node:crypto'))\n .webcrypto\n }\n return webcrypto\n },\n set(value: Crypto) {\n webcrypto = value\n },\n })\n}\n"],"names":["global","crypto","webcrypto","Object","defineProperty","enumerable","configurable","get","require","set","value"],"mappings":"AAAA,+CAA+C;;AAE/C,IAAI,CAACA,OAAOC,MAAM,EAAE;IAClB,IAAIC;IAEJC,OAAOC,cAAc,CAACJ,QAAQ,UAAU;QACtCK,YAAY;QACZC,cAAc;QACdC;YACE,IAAI,CAACL,WAAW;gBACd,mDAAmD;gBACnDA,YAAY,AAACM,QAAQ,eAClBN,SAAS;YACd;YACA,OAAOA;QACT;QACAO,KAAIC,KAAa;YACfR,YAAYQ;QACd;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/absolute-filename-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/absolute-filename-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d8b57dbadae439e2bb38fd31b48cec47b2a5496 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/absolute-filename-normalizer.d.ts @@ -0,0 +1,19 @@ +import type { PAGE_TYPES } from '../../lib/page-types'; +import type { Normalizer } from './normalizer'; +/** + * Normalizes a given filename so that it's relative to the provided directory. + * It will also strip the extension (if provided) and the trailing `/index`. + */ +export declare class AbsoluteFilenameNormalizer implements Normalizer { + private readonly dir; + private readonly extensions; + private readonly pagesType; + /** + * + * @param dir the directory for which the files should be made relative to + * @param extensions the extensions the file could have + * @param keepIndex when `true` the trailing `/index` is _not_ removed + */ + constructor(dir: string, extensions: ReadonlyArray, pagesType: PAGE_TYPES); + normalize(filename: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/absolute-filename-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/absolute-filename-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..0c7d142a9516a1a41e102573142ff78aff63488a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/absolute-filename-normalizer.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "AbsoluteFilenameNormalizer", { + enumerable: true, + get: function() { + return AbsoluteFilenameNormalizer; + } +}); +const _absolutepathtopage = require("../../shared/lib/page-path/absolute-path-to-page"); +class AbsoluteFilenameNormalizer { + /** + * + * @param dir the directory for which the files should be made relative to + * @param extensions the extensions the file could have + * @param keepIndex when `true` the trailing `/index` is _not_ removed + */ constructor(dir, extensions, pagesType){ + this.dir = dir; + this.extensions = extensions; + this.pagesType = pagesType; + } + normalize(filename) { + return (0, _absolutepathtopage.absolutePathToPage)(filename, { + extensions: this.extensions, + keepIndex: false, + dir: this.dir, + pagesType: this.pagesType + }); + } +} + +//# sourceMappingURL=absolute-filename-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/absolute-filename-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/absolute-filename-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0e500056f00d622fda129a54098403adf9e6333b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/absolute-filename-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/normalizers/absolute-filename-normalizer.ts"],"sourcesContent":["import type { PAGE_TYPES } from '../../lib/page-types'\nimport { absolutePathToPage } from '../../shared/lib/page-path/absolute-path-to-page'\nimport type { Normalizer } from './normalizer'\n\n/**\n * Normalizes a given filename so that it's relative to the provided directory.\n * It will also strip the extension (if provided) and the trailing `/index`.\n */\nexport class AbsoluteFilenameNormalizer implements Normalizer {\n /**\n *\n * @param dir the directory for which the files should be made relative to\n * @param extensions the extensions the file could have\n * @param keepIndex when `true` the trailing `/index` is _not_ removed\n */\n constructor(\n private readonly dir: string,\n private readonly extensions: ReadonlyArray,\n private readonly pagesType: PAGE_TYPES\n ) {}\n\n public normalize(filename: string): string {\n return absolutePathToPage(filename, {\n extensions: this.extensions,\n keepIndex: false,\n dir: this.dir,\n pagesType: this.pagesType,\n })\n }\n}\n"],"names":["AbsoluteFilenameNormalizer","constructor","dir","extensions","pagesType","normalize","filename","absolutePathToPage","keepIndex"],"mappings":";;;;+BAQaA;;;eAAAA;;;oCAPsB;AAO5B,MAAMA;IACX;;;;;GAKC,GACDC,YACE,AAAiBC,GAAW,EAC5B,AAAiBC,UAAiC,EAClD,AAAiBC,SAAqB,CACtC;aAHiBF,MAAAA;aACAC,aAAAA;aACAC,YAAAA;IAChB;IAEIC,UAAUC,QAAgB,EAAU;QACzC,OAAOC,IAAAA,sCAAkB,EAACD,UAAU;YAClCH,YAAY,IAAI,CAACA,UAAU;YAC3BK,WAAW;YACXN,KAAK,IAAI,CAACA,GAAG;YACbE,WAAW,IAAI,CAACA,SAAS;QAC3B;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-bundle-path-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-bundle-path-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..70edf62ac24ea0ca2082f7611b4d4ac288d903cb --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-bundle-path-normalizer.d.ts @@ -0,0 +1,11 @@ +import { Normalizers } from '../../normalizers'; +import type { Normalizer } from '../../normalizer'; +import { PrefixingNormalizer } from '../../prefixing-normalizer'; +export declare class AppBundlePathNormalizer extends PrefixingNormalizer { + constructor(); + normalize(page: string): string; +} +export declare class DevAppBundlePathNormalizer extends Normalizers { + constructor(pageNormalizer: Normalizer, isTurbopack: boolean); + normalize(filename: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-bundle-path-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-bundle-path-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..3ef12f9d1bdad69757eae6c2fbf6918307c9ecf6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-bundle-path-normalizer.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + AppBundlePathNormalizer: null, + DevAppBundlePathNormalizer: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + AppBundlePathNormalizer: function() { + return AppBundlePathNormalizer; + }, + DevAppBundlePathNormalizer: function() { + return DevAppBundlePathNormalizer; + } +}); +const _normalizers = require("../../normalizers"); +const _prefixingnormalizer = require("../../prefixing-normalizer"); +const _normalizepagepath = require("../../../../shared/lib/page-path/normalize-page-path"); +const _underscorenormalizer = require("../../underscore-normalizer"); +class AppBundlePathNormalizer extends _prefixingnormalizer.PrefixingNormalizer { + constructor(){ + super('app'); + } + normalize(page) { + return super.normalize((0, _normalizepagepath.normalizePagePath)(page)); + } +} +class DevAppBundlePathNormalizer extends _normalizers.Normalizers { + constructor(pageNormalizer, isTurbopack){ + const normalizers = [ + // This should normalize the filename to a page. + pageNormalizer, + // Normalize the app page to a pathname. + new AppBundlePathNormalizer() + ]; + // %5F to _ replacement should only happen with Turbopack. + if (isTurbopack) { + normalizers.unshift(new _underscorenormalizer.UnderscoreNormalizer()); + } + super(normalizers); + } + normalize(filename) { + return super.normalize(filename); + } +} + +//# sourceMappingURL=app-bundle-path-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-bundle-path-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-bundle-path-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d9a9ba3c530e7fe70aa7c6eb64fe498af5a87bfa --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-bundle-path-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/normalizers/built/app/app-bundle-path-normalizer.ts"],"sourcesContent":["import { Normalizers } from '../../normalizers'\nimport type { Normalizer } from '../../normalizer'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\nimport { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path'\nimport { UnderscoreNormalizer } from '../../underscore-normalizer'\n\nexport class AppBundlePathNormalizer extends PrefixingNormalizer {\n constructor() {\n super('app')\n }\n\n public normalize(page: string): string {\n return super.normalize(normalizePagePath(page))\n }\n}\n\nexport class DevAppBundlePathNormalizer extends Normalizers {\n constructor(pageNormalizer: Normalizer, isTurbopack: boolean) {\n const normalizers = [\n // This should normalize the filename to a page.\n pageNormalizer,\n // Normalize the app page to a pathname.\n new AppBundlePathNormalizer(),\n ]\n\n // %5F to _ replacement should only happen with Turbopack.\n if (isTurbopack) {\n normalizers.unshift(new UnderscoreNormalizer())\n }\n super(normalizers)\n }\n\n public normalize(filename: string): string {\n return super.normalize(filename)\n }\n}\n"],"names":["AppBundlePathNormalizer","DevAppBundlePathNormalizer","PrefixingNormalizer","constructor","normalize","page","normalizePagePath","Normalizers","pageNormalizer","isTurbopack","normalizers","unshift","UnderscoreNormalizer","filename"],"mappings":";;;;;;;;;;;;;;;IAMaA,uBAAuB;eAAvBA;;IAUAC,0BAA0B;eAA1BA;;;6BAhBe;qCAEQ;mCACF;sCACG;AAE9B,MAAMD,gCAAgCE,wCAAmB;IAC9DC,aAAc;QACZ,KAAK,CAAC;IACR;IAEOC,UAAUC,IAAY,EAAU;QACrC,OAAO,KAAK,CAACD,UAAUE,IAAAA,oCAAiB,EAACD;IAC3C;AACF;AAEO,MAAMJ,mCAAmCM,wBAAW;IACzDJ,YAAYK,cAA0B,EAAEC,WAAoB,CAAE;QAC5D,MAAMC,cAAc;YAClB,gDAAgD;YAChDF;YACA,wCAAwC;YACxC,IAAIR;SACL;QAED,0DAA0D;QAC1D,IAAIS,aAAa;YACfC,YAAYC,OAAO,CAAC,IAAIC,0CAAoB;QAC9C;QACA,KAAK,CAACF;IACR;IAEON,UAAUS,QAAgB,EAAU;QACzC,OAAO,KAAK,CAACT,UAAUS;IACzB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-filename-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-filename-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4baa168653593dc2cdd87f85f8fd5aad341ff72 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-filename-normalizer.d.ts @@ -0,0 +1,5 @@ +import { PrefixingNormalizer } from '../../prefixing-normalizer'; +export declare class AppFilenameNormalizer extends PrefixingNormalizer { + constructor(distDir: string); + normalize(manifestFilename: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-filename-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-filename-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..96853750b4a445907ce5ff8a0ce8b124c3e7b6d1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-filename-normalizer.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "AppFilenameNormalizer", { + enumerable: true, + get: function() { + return AppFilenameNormalizer; + } +}); +const _constants = require("../../../../shared/lib/constants"); +const _prefixingnormalizer = require("../../prefixing-normalizer"); +class AppFilenameNormalizer extends _prefixingnormalizer.PrefixingNormalizer { + constructor(distDir){ + super(distDir, _constants.SERVER_DIRECTORY); + } + normalize(manifestFilename) { + return super.normalize(manifestFilename); + } +} + +//# sourceMappingURL=app-filename-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-filename-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-filename-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7a45088db8f5c3f1697d58cd92283b4a47b898a4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-filename-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/normalizers/built/app/app-filename-normalizer.ts"],"sourcesContent":["import { SERVER_DIRECTORY } from '../../../../shared/lib/constants'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\n\nexport class AppFilenameNormalizer extends PrefixingNormalizer {\n constructor(distDir: string) {\n super(distDir, SERVER_DIRECTORY)\n }\n\n public normalize(manifestFilename: string): string {\n return super.normalize(manifestFilename)\n }\n}\n"],"names":["AppFilenameNormalizer","PrefixingNormalizer","constructor","distDir","SERVER_DIRECTORY","normalize","manifestFilename"],"mappings":";;;;+BAGaA;;;eAAAA;;;2BAHoB;qCACG;AAE7B,MAAMA,8BAA8BC,wCAAmB;IAC5DC,YAAYC,OAAe,CAAE;QAC3B,KAAK,CAACA,SAASC,2BAAgB;IACjC;IAEOC,UAAUC,gBAAwB,EAAU;QACjD,OAAO,KAAK,CAACD,UAAUC;IACzB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-page-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-page-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca909c4c929b46ffec0d7ca22f5893fca6bc500f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-page-normalizer.d.ts @@ -0,0 +1,4 @@ +import { Normalizers } from '../../normalizers'; +export declare class DevAppPageNormalizer extends Normalizers { + constructor(appDir: string, extensions: ReadonlyArray, _isTurbopack: boolean); +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-page-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-page-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..8177bde18aa54d3cfe73625d1c1463fbf373ad4a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-page-normalizer.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "DevAppPageNormalizer", { + enumerable: true, + get: function() { + return DevAppPageNormalizer; + } +}); +const _pagetypes = require("../../../../lib/page-types"); +const _absolutefilenamenormalizer = require("../../absolute-filename-normalizer"); +const _normalizers = require("../../normalizers"); +/** + * DevAppPageNormalizer is a normalizer that is used to normalize a pathname + * to a page in the `app` directory. + */ class DevAppPageNormalizerInternal extends _absolutefilenamenormalizer.AbsoluteFilenameNormalizer { + constructor(appDir, extensions){ + super(appDir, extensions, _pagetypes.PAGE_TYPES.APP); + } +} +class DevAppPageNormalizer extends _normalizers.Normalizers { + constructor(appDir, extensions, _isTurbopack){ + const normalizer = new DevAppPageNormalizerInternal(appDir, extensions); + super(// %5F to _ replacement should only happen with Turbopack. + // TODO: enable when the dev app file classifier's `/_` check is moved. + // isTurbopack + // ? [ + // // The page should have the `%5F` characters replaced with `_` characters. + // new UnderscoreNormalizer(), + // normalizer, + // ] + // : [normalizer] + [ + normalizer + ]); + } +} + +//# sourceMappingURL=app-page-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-page-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-page-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cfe327a6fdbf50182e485b6521ce85def8b17c46 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-page-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/normalizers/built/app/app-page-normalizer.ts"],"sourcesContent":["import { PAGE_TYPES } from '../../../../lib/page-types'\nimport { AbsoluteFilenameNormalizer } from '../../absolute-filename-normalizer'\nimport { Normalizers } from '../../normalizers'\n\n/**\n * DevAppPageNormalizer is a normalizer that is used to normalize a pathname\n * to a page in the `app` directory.\n */\nclass DevAppPageNormalizerInternal extends AbsoluteFilenameNormalizer {\n constructor(appDir: string, extensions: ReadonlyArray) {\n super(appDir, extensions, PAGE_TYPES.APP)\n }\n}\n\nexport class DevAppPageNormalizer extends Normalizers {\n constructor(\n appDir: string,\n extensions: ReadonlyArray,\n _isTurbopack: boolean\n ) {\n const normalizer = new DevAppPageNormalizerInternal(appDir, extensions)\n super(\n // %5F to _ replacement should only happen with Turbopack.\n // TODO: enable when the dev app file classifier's `/_` check is moved.\n // isTurbopack\n // ? [\n // // The page should have the `%5F` characters replaced with `_` characters.\n // new UnderscoreNormalizer(),\n // normalizer,\n // ]\n // : [normalizer]\n [normalizer]\n )\n }\n}\n"],"names":["DevAppPageNormalizer","DevAppPageNormalizerInternal","AbsoluteFilenameNormalizer","constructor","appDir","extensions","PAGE_TYPES","APP","Normalizers","_isTurbopack","normalizer"],"mappings":";;;;+BAcaA;;;eAAAA;;;2BAdc;4CACgB;6BACf;AAE5B;;;CAGC,GACD,MAAMC,qCAAqCC,sDAA0B;IACnEC,YAAYC,MAAc,EAAEC,UAAiC,CAAE;QAC7D,KAAK,CAACD,QAAQC,YAAYC,qBAAU,CAACC,GAAG;IAC1C;AACF;AAEO,MAAMP,6BAA6BQ,wBAAW;IACnDL,YACEC,MAAc,EACdC,UAAiC,EACjCI,YAAqB,CACrB;QACA,MAAMC,aAAa,IAAIT,6BAA6BG,QAAQC;QAC5D,KAAK,CACH,0DAA0D;QAC1D,uEAAuE;QACvE,cAAc;QACd,QAAQ;QACR,mFAAmF;QACnF,oCAAoC;QACpC,oBAAoB;QACpB,QAAQ;QACR,mBAAmB;QACnB;YAACK;SAAW;IAEhB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-pathname-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-pathname-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c64b541d35ef364ed19df05919fcaf0e0fa6fdc6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-pathname-normalizer.d.ts @@ -0,0 +1,10 @@ +import { Normalizers } from '../../normalizers'; +import type { Normalizer } from '../../normalizer'; +export declare class AppPathnameNormalizer extends Normalizers { + constructor(); + normalize(page: string): string; +} +export declare class DevAppPathnameNormalizer extends Normalizers { + constructor(pageNormalizer: Normalizer); + normalize(filename: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-pathname-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-pathname-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..f5b43e8faf2ee30fb01fd7dc5f8e4af75376560e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-pathname-normalizer.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + AppPathnameNormalizer: null, + DevAppPathnameNormalizer: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + AppPathnameNormalizer: function() { + return AppPathnameNormalizer; + }, + DevAppPathnameNormalizer: function() { + return DevAppPathnameNormalizer; + } +}); +const _apppaths = require("../../../../shared/lib/router/utils/app-paths"); +const _normalizers = require("../../normalizers"); +const _wrapnormalizerfn = require("../../wrap-normalizer-fn"); +const _underscorenormalizer = require("../../underscore-normalizer"); +class AppPathnameNormalizer extends _normalizers.Normalizers { + constructor(){ + super([ + // The pathname to match should have the trailing `/page` and other route + // group information stripped from it. + (0, _wrapnormalizerfn.wrapNormalizerFn)(_apppaths.normalizeAppPath), + // The page should have the `%5F` characters replaced with `_` characters. + new _underscorenormalizer.UnderscoreNormalizer() + ]); + } + normalize(page) { + return super.normalize(page); + } +} +class DevAppPathnameNormalizer extends _normalizers.Normalizers { + constructor(pageNormalizer){ + super([ + // This should normalize the filename to a page. + pageNormalizer, + // Normalize the app page to a pathname. + new AppPathnameNormalizer() + ]); + } + normalize(filename) { + return super.normalize(filename); + } +} + +//# sourceMappingURL=app-pathname-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-pathname-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-pathname-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..db93429a8d8a8245ba9ff757e364f45f97103b91 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/app-pathname-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/normalizers/built/app/app-pathname-normalizer.ts"],"sourcesContent":["import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths'\nimport { Normalizers } from '../../normalizers'\nimport { wrapNormalizerFn } from '../../wrap-normalizer-fn'\nimport { UnderscoreNormalizer } from '../../underscore-normalizer'\nimport type { Normalizer } from '../../normalizer'\n\nexport class AppPathnameNormalizer extends Normalizers {\n constructor() {\n super([\n // The pathname to match should have the trailing `/page` and other route\n // group information stripped from it.\n wrapNormalizerFn(normalizeAppPath),\n // The page should have the `%5F` characters replaced with `_` characters.\n new UnderscoreNormalizer(),\n ])\n }\n\n public normalize(page: string): string {\n return super.normalize(page)\n }\n}\n\nexport class DevAppPathnameNormalizer extends Normalizers {\n constructor(pageNormalizer: Normalizer) {\n super([\n // This should normalize the filename to a page.\n pageNormalizer,\n // Normalize the app page to a pathname.\n new AppPathnameNormalizer(),\n ])\n }\n\n public normalize(filename: string): string {\n return super.normalize(filename)\n }\n}\n"],"names":["AppPathnameNormalizer","DevAppPathnameNormalizer","Normalizers","constructor","wrapNormalizerFn","normalizeAppPath","UnderscoreNormalizer","normalize","page","pageNormalizer","filename"],"mappings":";;;;;;;;;;;;;;;IAMaA,qBAAqB;eAArBA;;IAgBAC,wBAAwB;eAAxBA;;;0BAtBoB;6BACL;kCACK;sCACI;AAG9B,MAAMD,8BAA8BE,wBAAW;IACpDC,aAAc;QACZ,KAAK,CAAC;YACJ,yEAAyE;YACzE,sCAAsC;YACtCC,IAAAA,kCAAgB,EAACC,0BAAgB;YACjC,0EAA0E;YAC1E,IAAIC,0CAAoB;SACzB;IACH;IAEOC,UAAUC,IAAY,EAAU;QACrC,OAAO,KAAK,CAACD,UAAUC;IACzB;AACF;AAEO,MAAMP,iCAAiCC,wBAAW;IACvDC,YAAYM,cAA0B,CAAE;QACtC,KAAK,CAAC;YACJ,gDAAgD;YAChDA;YACA,wCAAwC;YACxC,IAAIT;SACL;IACH;IAEOO,UAAUG,QAAgB,EAAU;QACzC,OAAO,KAAK,CAACH,UAAUG;IACzB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/index.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/built/app/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..477272be92ddc8b0a2f9c181beb940a2119274a6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/index.d.ts @@ -0,0 +1,16 @@ +import { AppBundlePathNormalizer, DevAppBundlePathNormalizer } from './app-bundle-path-normalizer'; +import { AppFilenameNormalizer } from './app-filename-normalizer'; +import { DevAppPageNormalizer } from './app-page-normalizer'; +import { AppPathnameNormalizer, DevAppPathnameNormalizer } from './app-pathname-normalizer'; +export declare class AppNormalizers { + readonly filename: AppFilenameNormalizer; + readonly pathname: AppPathnameNormalizer; + readonly bundlePath: AppBundlePathNormalizer; + constructor(distDir: string); +} +export declare class DevAppNormalizers { + readonly page: DevAppPageNormalizer; + readonly pathname: DevAppPathnameNormalizer; + readonly bundlePath: DevAppBundlePathNormalizer; + constructor(appDir: string, extensions: ReadonlyArray, isTurbopack: boolean); +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/index.js b/e-commerce/node_modules/next/dist/server/normalizers/built/app/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a88cfe1bb47e29e85a1a671a5bacc345931e27f3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/index.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + AppNormalizers: null, + DevAppNormalizers: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + AppNormalizers: function() { + return AppNormalizers; + }, + DevAppNormalizers: function() { + return DevAppNormalizers; + } +}); +const _appbundlepathnormalizer = require("./app-bundle-path-normalizer"); +const _appfilenamenormalizer = require("./app-filename-normalizer"); +const _apppagenormalizer = require("./app-page-normalizer"); +const _apppathnamenormalizer = require("./app-pathname-normalizer"); +class AppNormalizers { + constructor(distDir){ + this.filename = new _appfilenamenormalizer.AppFilenameNormalizer(distDir); + this.pathname = new _apppathnamenormalizer.AppPathnameNormalizer(); + this.bundlePath = new _appbundlepathnormalizer.AppBundlePathNormalizer(); + } +} +class DevAppNormalizers { + constructor(appDir, extensions, isTurbopack){ + this.page = new _apppagenormalizer.DevAppPageNormalizer(appDir, extensions, isTurbopack); + this.pathname = new _apppathnamenormalizer.DevAppPathnameNormalizer(this.page); + this.bundlePath = new _appbundlepathnormalizer.DevAppBundlePathNormalizer(this.page, isTurbopack); + } +} + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/app/index.js.map b/e-commerce/node_modules/next/dist/server/normalizers/built/app/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5e309058197a8343a81c8cd263a3205d9fbdca72 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/app/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/normalizers/built/app/index.ts"],"sourcesContent":["import {\n AppBundlePathNormalizer,\n DevAppBundlePathNormalizer,\n} from './app-bundle-path-normalizer'\nimport { AppFilenameNormalizer } from './app-filename-normalizer'\nimport { DevAppPageNormalizer } from './app-page-normalizer'\nimport {\n AppPathnameNormalizer,\n DevAppPathnameNormalizer,\n} from './app-pathname-normalizer'\n\nexport class AppNormalizers {\n public readonly filename: AppFilenameNormalizer\n public readonly pathname: AppPathnameNormalizer\n public readonly bundlePath: AppBundlePathNormalizer\n\n constructor(distDir: string) {\n this.filename = new AppFilenameNormalizer(distDir)\n this.pathname = new AppPathnameNormalizer()\n this.bundlePath = new AppBundlePathNormalizer()\n }\n}\n\nexport class DevAppNormalizers {\n public readonly page: DevAppPageNormalizer\n public readonly pathname: DevAppPathnameNormalizer\n public readonly bundlePath: DevAppBundlePathNormalizer\n\n constructor(\n appDir: string,\n extensions: ReadonlyArray,\n isTurbopack: boolean\n ) {\n this.page = new DevAppPageNormalizer(appDir, extensions, isTurbopack)\n this.pathname = new DevAppPathnameNormalizer(this.page)\n this.bundlePath = new DevAppBundlePathNormalizer(this.page, isTurbopack)\n }\n}\n"],"names":["AppNormalizers","DevAppNormalizers","constructor","distDir","filename","AppFilenameNormalizer","pathname","AppPathnameNormalizer","bundlePath","AppBundlePathNormalizer","appDir","extensions","isTurbopack","page","DevAppPageNormalizer","DevAppPathnameNormalizer","DevAppBundlePathNormalizer"],"mappings":";;;;;;;;;;;;;;;IAWaA,cAAc;eAAdA;;IAYAC,iBAAiB;eAAjBA;;;yCApBN;uCAC+B;mCACD;uCAI9B;AAEA,MAAMD;IAKXE,YAAYC,OAAe,CAAE;QAC3B,IAAI,CAACC,QAAQ,GAAG,IAAIC,4CAAqB,CAACF;QAC1C,IAAI,CAACG,QAAQ,GAAG,IAAIC,4CAAqB;QACzC,IAAI,CAACC,UAAU,GAAG,IAAIC,gDAAuB;IAC/C;AACF;AAEO,MAAMR;IAKXC,YACEQ,MAAc,EACdC,UAAiC,EACjCC,WAAoB,CACpB;QACA,IAAI,CAACC,IAAI,GAAG,IAAIC,uCAAoB,CAACJ,QAAQC,YAAYC;QACzD,IAAI,CAACN,QAAQ,GAAG,IAAIS,+CAAwB,CAAC,IAAI,CAACF,IAAI;QACtD,IAAI,CAACL,UAAU,GAAG,IAAIQ,mDAA0B,CAAC,IAAI,CAACH,IAAI,EAAED;IAC9D;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/index.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1739c78fd29861db8916ca3f5e3268bdb6469fc9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/index.d.ts @@ -0,0 +1,15 @@ +import { DevPagesBundlePathNormalizer, PagesBundlePathNormalizer } from './pages-bundle-path-normalizer'; +import { PagesFilenameNormalizer } from './pages-filename-normalizer'; +import { DevPagesPageNormalizer } from './pages-page-normalizer'; +import { DevPagesPathnameNormalizer } from './pages-pathname-normalizer'; +export declare class PagesNormalizers { + readonly filename: PagesFilenameNormalizer; + readonly bundlePath: PagesBundlePathNormalizer; + constructor(distDir: string); +} +export declare class DevPagesNormalizers { + readonly page: DevPagesPageNormalizer; + readonly pathname: DevPagesPathnameNormalizer; + readonly bundlePath: DevPagesBundlePathNormalizer; + constructor(pagesDir: string, extensions: ReadonlyArray); +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/index.js b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/index.js new file mode 100644 index 0000000000000000000000000000000000000000..28b5a853c4eb57e943bda3c1f3462d1506c5f4be --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/index.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + DevPagesNormalizers: null, + PagesNormalizers: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + DevPagesNormalizers: function() { + return DevPagesNormalizers; + }, + PagesNormalizers: function() { + return PagesNormalizers; + } +}); +const _pagesbundlepathnormalizer = require("./pages-bundle-path-normalizer"); +const _pagesfilenamenormalizer = require("./pages-filename-normalizer"); +const _pagespagenormalizer = require("./pages-page-normalizer"); +const _pagespathnamenormalizer = require("./pages-pathname-normalizer"); +class PagesNormalizers { + constructor(distDir){ + this.filename = new _pagesfilenamenormalizer.PagesFilenameNormalizer(distDir); + this.bundlePath = new _pagesbundlepathnormalizer.PagesBundlePathNormalizer(); + // You'd think that we'd require a `pathname` normalizer here, but for + // `/pages` we have to handle i18n routes, which means that we need to + // analyze the page path to determine the locale prefix and it's locale. + } +} +class DevPagesNormalizers { + constructor(pagesDir, extensions){ + this.page = new _pagespagenormalizer.DevPagesPageNormalizer(pagesDir, extensions); + this.pathname = new _pagespathnamenormalizer.DevPagesPathnameNormalizer(pagesDir, extensions); + this.bundlePath = new _pagesbundlepathnormalizer.DevPagesBundlePathNormalizer(this.page); + } +} + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/index.js.map b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7c3fe8ec985b0920a45646199b7fb6b70e1ea2a9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/normalizers/built/pages/index.ts"],"sourcesContent":["import {\n DevPagesBundlePathNormalizer,\n PagesBundlePathNormalizer,\n} from './pages-bundle-path-normalizer'\nimport { PagesFilenameNormalizer } from './pages-filename-normalizer'\nimport { DevPagesPageNormalizer } from './pages-page-normalizer'\nimport { DevPagesPathnameNormalizer } from './pages-pathname-normalizer'\n\nexport class PagesNormalizers {\n public readonly filename: PagesFilenameNormalizer\n public readonly bundlePath: PagesBundlePathNormalizer\n\n constructor(distDir: string) {\n this.filename = new PagesFilenameNormalizer(distDir)\n this.bundlePath = new PagesBundlePathNormalizer()\n\n // You'd think that we'd require a `pathname` normalizer here, but for\n // `/pages` we have to handle i18n routes, which means that we need to\n // analyze the page path to determine the locale prefix and it's locale.\n }\n}\n\nexport class DevPagesNormalizers {\n public readonly page: DevPagesPageNormalizer\n public readonly pathname: DevPagesPathnameNormalizer\n public readonly bundlePath: DevPagesBundlePathNormalizer\n\n constructor(pagesDir: string, extensions: ReadonlyArray) {\n this.page = new DevPagesPageNormalizer(pagesDir, extensions)\n this.pathname = new DevPagesPathnameNormalizer(pagesDir, extensions)\n this.bundlePath = new DevPagesBundlePathNormalizer(this.page)\n }\n}\n"],"names":["DevPagesNormalizers","PagesNormalizers","constructor","distDir","filename","PagesFilenameNormalizer","bundlePath","PagesBundlePathNormalizer","pagesDir","extensions","page","DevPagesPageNormalizer","pathname","DevPagesPathnameNormalizer","DevPagesBundlePathNormalizer"],"mappings":";;;;;;;;;;;;;;;IAsBaA,mBAAmB;eAAnBA;;IAdAC,gBAAgB;eAAhBA;;;2CALN;yCACiC;qCACD;yCACI;AAEpC,MAAMA;IAIXC,YAAYC,OAAe,CAAE;QAC3B,IAAI,CAACC,QAAQ,GAAG,IAAIC,gDAAuB,CAACF;QAC5C,IAAI,CAACG,UAAU,GAAG,IAAIC,oDAAyB;IAE/C,sEAAsE;IACtE,sEAAsE;IACtE,wEAAwE;IAC1E;AACF;AAEO,MAAMP;IAKXE,YAAYM,QAAgB,EAAEC,UAAiC,CAAE;QAC/D,IAAI,CAACC,IAAI,GAAG,IAAIC,2CAAsB,CAACH,UAAUC;QACjD,IAAI,CAACG,QAAQ,GAAG,IAAIC,mDAA0B,CAACL,UAAUC;QACzD,IAAI,CAACH,UAAU,GAAG,IAAIQ,uDAA4B,CAAC,IAAI,CAACJ,IAAI;IAC9D;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-bundle-path-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-bundle-path-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..229f075a588836e135b5c1bc99673badd510b1d5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-bundle-path-normalizer.d.ts @@ -0,0 +1,10 @@ +import type { Normalizer } from '../../normalizer'; +import { Normalizers } from '../../normalizers'; +export declare class PagesBundlePathNormalizer extends Normalizers { + constructor(); + normalize(page: string): string; +} +export declare class DevPagesBundlePathNormalizer extends Normalizers { + constructor(pagesNormalizer: Normalizer); + normalize(filename: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-bundle-path-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-bundle-path-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..9ccc043de4419d0fe0d290e326a94254ab5fdee1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-bundle-path-normalizer.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + DevPagesBundlePathNormalizer: null, + PagesBundlePathNormalizer: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + DevPagesBundlePathNormalizer: function() { + return DevPagesBundlePathNormalizer; + }, + PagesBundlePathNormalizer: function() { + return PagesBundlePathNormalizer; + } +}); +const _normalizepagepath = require("../../../../shared/lib/page-path/normalize-page-path"); +const _normalizers = require("../../normalizers"); +const _prefixingnormalizer = require("../../prefixing-normalizer"); +const _wrapnormalizerfn = require("../../wrap-normalizer-fn"); +class PagesBundlePathNormalizer extends _normalizers.Normalizers { + constructor(){ + super([ + // The bundle path should have the trailing `/index` stripped from + // it. + (0, _wrapnormalizerfn.wrapNormalizerFn)(_normalizepagepath.normalizePagePath), + // The page should prefixed with `pages/`. + new _prefixingnormalizer.PrefixingNormalizer('pages') + ]); + } + normalize(page) { + return super.normalize(page); + } +} +class DevPagesBundlePathNormalizer extends _normalizers.Normalizers { + constructor(pagesNormalizer){ + super([ + // This should normalize the filename to a page. + pagesNormalizer, + // Normalize the app page to a pathname. + new PagesBundlePathNormalizer() + ]); + } + normalize(filename) { + return super.normalize(filename); + } +} + +//# sourceMappingURL=pages-bundle-path-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-bundle-path-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-bundle-path-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e6c754a3abdd4b21e24cc3faf6466803526eaab2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-bundle-path-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts"],"sourcesContent":["import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path'\nimport type { Normalizer } from '../../normalizer'\nimport { Normalizers } from '../../normalizers'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\nimport { wrapNormalizerFn } from '../../wrap-normalizer-fn'\n\nexport class PagesBundlePathNormalizer extends Normalizers {\n constructor() {\n super([\n // The bundle path should have the trailing `/index` stripped from\n // it.\n wrapNormalizerFn(normalizePagePath),\n // The page should prefixed with `pages/`.\n new PrefixingNormalizer('pages'),\n ])\n }\n\n public normalize(page: string): string {\n return super.normalize(page)\n }\n}\n\nexport class DevPagesBundlePathNormalizer extends Normalizers {\n constructor(pagesNormalizer: Normalizer) {\n super([\n // This should normalize the filename to a page.\n pagesNormalizer,\n // Normalize the app page to a pathname.\n new PagesBundlePathNormalizer(),\n ])\n }\n\n public normalize(filename: string): string {\n return super.normalize(filename)\n }\n}\n"],"names":["DevPagesBundlePathNormalizer","PagesBundlePathNormalizer","Normalizers","constructor","wrapNormalizerFn","normalizePagePath","PrefixingNormalizer","normalize","page","pagesNormalizer","filename"],"mappings":";;;;;;;;;;;;;;;IAsBaA,4BAA4B;eAA5BA;;IAhBAC,yBAAyB;eAAzBA;;;mCANqB;6BAEN;qCACQ;kCACH;AAE1B,MAAMA,kCAAkCC,wBAAW;IACxDC,aAAc;QACZ,KAAK,CAAC;YACJ,kEAAkE;YAClE,MAAM;YACNC,IAAAA,kCAAgB,EAACC,oCAAiB;YAClC,0CAA0C;YAC1C,IAAIC,wCAAmB,CAAC;SACzB;IACH;IAEOC,UAAUC,IAAY,EAAU;QACrC,OAAO,KAAK,CAACD,UAAUC;IACzB;AACF;AAEO,MAAMR,qCAAqCE,wBAAW;IAC3DC,YAAYM,eAA2B,CAAE;QACvC,KAAK,CAAC;YACJ,gDAAgD;YAChDA;YACA,wCAAwC;YACxC,IAAIR;SACL;IACH;IAEOM,UAAUG,QAAgB,EAAU;QACzC,OAAO,KAAK,CAACH,UAAUG;IACzB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-filename-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-filename-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f97e3cb95d21a08576221a7b2a527e996230956 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-filename-normalizer.d.ts @@ -0,0 +1,5 @@ +import { PrefixingNormalizer } from '../../prefixing-normalizer'; +export declare class PagesFilenameNormalizer extends PrefixingNormalizer { + constructor(distDir: string); + normalize(manifestFilename: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-filename-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-filename-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..eed594d7286093478809fcfc9a71b5ad8d6e872e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-filename-normalizer.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "PagesFilenameNormalizer", { + enumerable: true, + get: function() { + return PagesFilenameNormalizer; + } +}); +const _constants = require("../../../../shared/lib/constants"); +const _prefixingnormalizer = require("../../prefixing-normalizer"); +class PagesFilenameNormalizer extends _prefixingnormalizer.PrefixingNormalizer { + constructor(distDir){ + super(distDir, _constants.SERVER_DIRECTORY); + } + normalize(manifestFilename) { + return super.normalize(manifestFilename); + } +} + +//# sourceMappingURL=pages-filename-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-filename-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-filename-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5e4a63b7c772f54611107b84b22c68d52303eaf8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-filename-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/normalizers/built/pages/pages-filename-normalizer.ts"],"sourcesContent":["import { SERVER_DIRECTORY } from '../../../../shared/lib/constants'\nimport { PrefixingNormalizer } from '../../prefixing-normalizer'\n\nexport class PagesFilenameNormalizer extends PrefixingNormalizer {\n constructor(distDir: string) {\n super(distDir, SERVER_DIRECTORY)\n }\n\n public normalize(manifestFilename: string): string {\n return super.normalize(manifestFilename)\n }\n}\n"],"names":["PagesFilenameNormalizer","PrefixingNormalizer","constructor","distDir","SERVER_DIRECTORY","normalize","manifestFilename"],"mappings":";;;;+BAGaA;;;eAAAA;;;2BAHoB;qCACG;AAE7B,MAAMA,gCAAgCC,wCAAmB;IAC9DC,YAAYC,OAAe,CAAE;QAC3B,KAAK,CAACA,SAASC,2BAAgB;IACjC;IAEOC,UAAUC,gBAAwB,EAAU;QACjD,OAAO,KAAK,CAACD,UAAUC;IACzB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-page-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-page-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a57252637ae68dd009d299c9781043a78b5c7aa --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-page-normalizer.d.ts @@ -0,0 +1,4 @@ +import { AbsoluteFilenameNormalizer } from '../../absolute-filename-normalizer'; +export declare class DevPagesPageNormalizer extends AbsoluteFilenameNormalizer { + constructor(pagesDir: string, extensions: ReadonlyArray); +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-page-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-page-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..c2dd3557003247f88de7fdd9b5dfd6ac3df491ec --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-page-normalizer.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "DevPagesPageNormalizer", { + enumerable: true, + get: function() { + return DevPagesPageNormalizer; + } +}); +const _pagetypes = require("../../../../lib/page-types"); +const _absolutefilenamenormalizer = require("../../absolute-filename-normalizer"); +class DevPagesPageNormalizer extends _absolutefilenamenormalizer.AbsoluteFilenameNormalizer { + constructor(pagesDir, extensions){ + super(pagesDir, extensions, _pagetypes.PAGE_TYPES.PAGES); + } +} + +//# sourceMappingURL=pages-page-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-page-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-page-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7041026734078680a4e86a9bd8295387f989a723 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-page-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/normalizers/built/pages/pages-page-normalizer.ts"],"sourcesContent":["import { PAGE_TYPES } from '../../../../lib/page-types'\nimport { AbsoluteFilenameNormalizer } from '../../absolute-filename-normalizer'\n\nexport class DevPagesPageNormalizer extends AbsoluteFilenameNormalizer {\n constructor(pagesDir: string, extensions: ReadonlyArray) {\n super(pagesDir, extensions, PAGE_TYPES.PAGES)\n }\n}\n"],"names":["DevPagesPageNormalizer","AbsoluteFilenameNormalizer","constructor","pagesDir","extensions","PAGE_TYPES","PAGES"],"mappings":";;;;+BAGaA;;;eAAAA;;;2BAHc;4CACgB;AAEpC,MAAMA,+BAA+BC,sDAA0B;IACpEC,YAAYC,QAAgB,EAAEC,UAAiC,CAAE;QAC/D,KAAK,CAACD,UAAUC,YAAYC,qBAAU,CAACC,KAAK;IAC9C;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-pathname-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-pathname-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b15ec17946d9cec2c2e6b4fd359ff9bb56d8138 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-pathname-normalizer.d.ts @@ -0,0 +1,4 @@ +import { AbsoluteFilenameNormalizer } from '../../absolute-filename-normalizer'; +export declare class DevPagesPathnameNormalizer extends AbsoluteFilenameNormalizer { + constructor(pagesDir: string, extensions: ReadonlyArray); +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-pathname-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-pathname-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..3c3e79da9881b73f356fa28633aa825eac104fef --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-pathname-normalizer.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "DevPagesPathnameNormalizer", { + enumerable: true, + get: function() { + return DevPagesPathnameNormalizer; + } +}); +const _pagetypes = require("../../../../lib/page-types"); +const _absolutefilenamenormalizer = require("../../absolute-filename-normalizer"); +class DevPagesPathnameNormalizer extends _absolutefilenamenormalizer.AbsoluteFilenameNormalizer { + constructor(pagesDir, extensions){ + super(pagesDir, extensions, _pagetypes.PAGE_TYPES.PAGES); + } +} + +//# sourceMappingURL=pages-pathname-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-pathname-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-pathname-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..74de0bec7dd14d43b4d7a318808c36bfd1671daa --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/built/pages/pages-pathname-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/normalizers/built/pages/pages-pathname-normalizer.ts"],"sourcesContent":["import { PAGE_TYPES } from '../../../../lib/page-types'\nimport { AbsoluteFilenameNormalizer } from '../../absolute-filename-normalizer'\n\nexport class DevPagesPathnameNormalizer extends AbsoluteFilenameNormalizer {\n constructor(pagesDir: string, extensions: ReadonlyArray) {\n super(pagesDir, extensions, PAGE_TYPES.PAGES)\n }\n}\n"],"names":["DevPagesPathnameNormalizer","AbsoluteFilenameNormalizer","constructor","pagesDir","extensions","PAGE_TYPES","PAGES"],"mappings":";;;;+BAGaA;;;eAAAA;;;2BAHc;4CACgB;AAEpC,MAAMA,mCAAmCC,sDAA0B;IACxEC,YAAYC,QAAgB,EAAEC,UAAiC,CAAE;QAC/D,KAAK,CAACD,UAAUC,YAAYC,qBAAU,CAACC,KAAK;IAC9C;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/locale-route-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/locale-route-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..805345b73be725b479d0a10f0308046a5472a006 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/locale-route-normalizer.d.ts @@ -0,0 +1,16 @@ +import type { I18NProvider } from '../lib/i18n-provider'; +import type { Normalizer } from './normalizer'; +/** + * Normalizes the pathname by removing the locale prefix if any. + */ +export declare class LocaleRouteNormalizer implements Normalizer { + private readonly provider; + constructor(provider: I18NProvider); + /** + * Normalizes the pathname by removing the locale prefix if any. + * + * @param pathname The pathname to normalize. + * @returns The pathname without the locale prefix (if any). + */ + normalize(pathname: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/locale-route-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/locale-route-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..8885c7518a34e0c413f2832e5e2d53dffd7d7408 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/locale-route-normalizer.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "LocaleRouteNormalizer", { + enumerable: true, + get: function() { + return LocaleRouteNormalizer; + } +}); +class LocaleRouteNormalizer { + constructor(provider){ + this.provider = provider; + } + /** + * Normalizes the pathname by removing the locale prefix if any. + * + * @param pathname The pathname to normalize. + * @returns The pathname without the locale prefix (if any). + */ normalize(pathname) { + const match = this.provider.analyze(pathname); + return match.pathname; + } +} + +//# sourceMappingURL=locale-route-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/locale-route-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/locale-route-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a3bc0c112a90f4a1ddb5780949848b31f035f945 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/locale-route-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/normalizers/locale-route-normalizer.ts"],"sourcesContent":["import type { I18NProvider } from '../lib/i18n-provider'\nimport type { Normalizer } from './normalizer'\n\n/**\n * Normalizes the pathname by removing the locale prefix if any.\n */\nexport class LocaleRouteNormalizer implements Normalizer {\n constructor(private readonly provider: I18NProvider) {}\n\n /**\n * Normalizes the pathname by removing the locale prefix if any.\n *\n * @param pathname The pathname to normalize.\n * @returns The pathname without the locale prefix (if any).\n */\n public normalize(pathname: string): string {\n const match = this.provider.analyze(pathname)\n return match.pathname\n }\n}\n"],"names":["LocaleRouteNormalizer","constructor","provider","normalize","pathname","match","analyze"],"mappings":";;;;+BAMaA;;;eAAAA;;;AAAN,MAAMA;IACXC,YAAY,AAAiBC,QAAsB,CAAE;aAAxBA,WAAAA;IAAyB;IAEtD;;;;;GAKC,GACD,AAAOC,UAAUC,QAAgB,EAAU;QACzC,MAAMC,QAAQ,IAAI,CAACH,QAAQ,CAACI,OAAO,CAACF;QACpC,OAAOC,MAAMD,QAAQ;IACvB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f379cf0120e3707c25a7bd509f4f44bb502a53c5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/normalizer.d.ts @@ -0,0 +1,3 @@ +export interface Normalizer { + normalize(pathname: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..27d0d35922a7ceb9a2336560ff2233c5ecafec6b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/normalizer.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/normalizers.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/normalizers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd030e38e9b263fbc59db4b2aaf98e72b5a7511a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/normalizers.d.ts @@ -0,0 +1,11 @@ +import type { Normalizer } from './normalizer'; +/** + * Normalizers combines many normalizers into a single normalizer interface that + * will normalize the inputted pathname with each normalizer in order. + */ +export declare class Normalizers implements Normalizer { + private readonly normalizers; + constructor(normalizers?: Array); + push(normalizer: Normalizer): void; + normalize(pathname: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/normalizers.js b/e-commerce/node_modules/next/dist/server/normalizers/normalizers.js new file mode 100644 index 0000000000000000000000000000000000000000..d8f52c2781f46f2e63b182e46e9c567e7c0bbe5e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/normalizers.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "Normalizers", { + enumerable: true, + get: function() { + return Normalizers; + } +}); +class Normalizers { + constructor(normalizers = []){ + this.normalizers = normalizers; + } + push(normalizer) { + this.normalizers.push(normalizer); + } + normalize(pathname) { + return this.normalizers.reduce((normalized, normalizer)=>normalizer.normalize(normalized), pathname); + } +} + +//# sourceMappingURL=normalizers.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/normalizers.js.map b/e-commerce/node_modules/next/dist/server/normalizers/normalizers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0d3378e9118170cf2564b04db01d9eaa4cacb89e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/normalizers.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/normalizers/normalizers.ts"],"sourcesContent":["import type { Normalizer } from './normalizer'\n\n/**\n * Normalizers combines many normalizers into a single normalizer interface that\n * will normalize the inputted pathname with each normalizer in order.\n */\nexport class Normalizers implements Normalizer {\n constructor(private readonly normalizers: Array = []) {}\n\n public push(normalizer: Normalizer) {\n this.normalizers.push(normalizer)\n }\n\n public normalize(pathname: string): string {\n return this.normalizers.reduce(\n (normalized, normalizer) => normalizer.normalize(normalized),\n pathname\n )\n }\n}\n"],"names":["Normalizers","constructor","normalizers","push","normalizer","normalize","pathname","reduce","normalized"],"mappings":";;;;+BAMaA;;;eAAAA;;;AAAN,MAAMA;IACXC,YAAY,AAAiBC,cAAiC,EAAE,CAAE;aAArCA,cAAAA;IAAsC;IAE5DC,KAAKC,UAAsB,EAAE;QAClC,IAAI,CAACF,WAAW,CAACC,IAAI,CAACC;IACxB;IAEOC,UAAUC,QAAgB,EAAU;QACzC,OAAO,IAAI,CAACJ,WAAW,CAACK,MAAM,CAC5B,CAACC,YAAYJ,aAAeA,WAAWC,SAAS,CAACG,aACjDF;IAEJ;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/prefixing-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/prefixing-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b974d18e2a64a9177c3c2a5b5fd932400a442da3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/prefixing-normalizer.d.ts @@ -0,0 +1,6 @@ +import type { Normalizer } from './normalizer'; +export declare class PrefixingNormalizer implements Normalizer { + private readonly prefix; + constructor(...prefixes: ReadonlyArray); + normalize(pathname: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/prefixing-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/prefixing-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..26b7e8b01985d0483e46411b7cf0423bedcea712 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/prefixing-normalizer.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "PrefixingNormalizer", { + enumerable: true, + get: function() { + return PrefixingNormalizer; + } +}); +const _path = /*#__PURE__*/ _interop_require_default(require("../../shared/lib/isomorphic/path")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +class PrefixingNormalizer { + constructor(...prefixes){ + this.prefix = _path.default.posix.join(...prefixes); + } + normalize(pathname) { + return _path.default.posix.join(this.prefix, pathname); + } +} + +//# sourceMappingURL=prefixing-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/prefixing-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/prefixing-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..51737cc79a76edfa3d22911704c68d46fba705af --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/prefixing-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/normalizers/prefixing-normalizer.ts"],"sourcesContent":["import path from '../../shared/lib/isomorphic/path'\nimport type { Normalizer } from './normalizer'\n\nexport class PrefixingNormalizer implements Normalizer {\n private readonly prefix: string\n\n constructor(...prefixes: ReadonlyArray) {\n this.prefix = path.posix.join(...prefixes)\n }\n\n public normalize(pathname: string): string {\n return path.posix.join(this.prefix, pathname)\n }\n}\n"],"names":["PrefixingNormalizer","constructor","prefixes","prefix","path","posix","join","normalize","pathname"],"mappings":";;;;+BAGaA;;;eAAAA;;;6DAHI;;;;;;AAGV,MAAMA;IAGXC,YAAY,GAAGC,QAA+B,CAAE;QAC9C,IAAI,CAACC,MAAM,GAAGC,aAAI,CAACC,KAAK,CAACC,IAAI,IAAIJ;IACnC;IAEOK,UAAUC,QAAgB,EAAU;QACzC,OAAOJ,aAAI,CAACC,KAAK,CAACC,IAAI,CAAC,IAAI,CAACH,MAAM,EAAEK;IACtC;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/base-path.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/request/base-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..87e5484ca5174a66061648d3b48a929833a0df43 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/base-path.d.ts @@ -0,0 +1,5 @@ +import type { PathnameNormalizer } from './pathname-normalizer'; +import { PrefixPathnameNormalizer } from './prefix'; +export declare class BasePathPathnameNormalizer extends PrefixPathnameNormalizer implements PathnameNormalizer { + constructor(basePath: string); +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/base-path.js b/e-commerce/node_modules/next/dist/server/normalizers/request/base-path.js new file mode 100644 index 0000000000000000000000000000000000000000..5e222bea6c5e08e37d8f5dbe48a692f3e1e5f18b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/base-path.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "BasePathPathnameNormalizer", { + enumerable: true, + get: function() { + return BasePathPathnameNormalizer; + } +}); +const _prefix = require("./prefix"); +class BasePathPathnameNormalizer extends _prefix.PrefixPathnameNormalizer { + constructor(basePath){ + if (!basePath || basePath === '/') { + throw new Error('Invariant: basePath must be set and cannot be "/"'); + } + super(basePath); + } +} + +//# sourceMappingURL=base-path.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/base-path.js.map b/e-commerce/node_modules/next/dist/server/normalizers/request/base-path.js.map new file mode 100644 index 0000000000000000000000000000000000000000..86bfee1e1bab0a9cfeb36414db9f8880ebf68a06 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/base-path.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/normalizers/request/base-path.ts"],"sourcesContent":["import type { PathnameNormalizer } from './pathname-normalizer'\n\nimport { PrefixPathnameNormalizer } from './prefix'\n\nexport class BasePathPathnameNormalizer\n extends PrefixPathnameNormalizer\n implements PathnameNormalizer\n{\n constructor(basePath: string) {\n if (!basePath || basePath === '/') {\n throw new Error('Invariant: basePath must be set and cannot be \"/\"')\n }\n\n super(basePath)\n }\n}\n"],"names":["BasePathPathnameNormalizer","PrefixPathnameNormalizer","constructor","basePath","Error"],"mappings":";;;;+BAIaA;;;eAAAA;;;wBAF4B;AAElC,MAAMA,mCACHC,gCAAwB;IAGhCC,YAAYC,QAAgB,CAAE;QAC5B,IAAI,CAACA,YAAYA,aAAa,KAAK;YACjC,MAAM,IAAIC,MAAM;QAClB;QAEA,KAAK,CAACD;IACR;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/next-data.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/request/next-data.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..41f1bad1219316c6b7ba3156c9e4d82cf28260d6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/next-data.d.ts @@ -0,0 +1,8 @@ +import type { PathnameNormalizer } from './pathname-normalizer'; +export declare class NextDataPathnameNormalizer implements PathnameNormalizer { + private readonly prefix; + private readonly suffix; + constructor(buildID: string); + match(pathname: string): boolean; + normalize(pathname: string, matched?: boolean): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/next-data.js b/e-commerce/node_modules/next/dist/server/normalizers/request/next-data.js new file mode 100644 index 0000000000000000000000000000000000000000..f94c6f1a582ad0bbaa535993253266db088e30fe --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/next-data.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NextDataPathnameNormalizer", { + enumerable: true, + get: function() { + return NextDataPathnameNormalizer; + } +}); +const _denormalizepagepath = require("../../../shared/lib/page-path/denormalize-page-path"); +const _prefix = require("./prefix"); +const _suffix = require("./suffix"); +class NextDataPathnameNormalizer { + constructor(buildID){ + this.suffix = new _suffix.SuffixPathnameNormalizer('.json'); + if (!buildID) { + throw new Error('Invariant: buildID is required'); + } + this.prefix = new _prefix.PrefixPathnameNormalizer(`/_next/data/${buildID}`); + } + match(pathname) { + return this.prefix.match(pathname) && this.suffix.match(pathname); + } + normalize(pathname, matched) { + // If we're not matched and we don't match, we don't need to normalize. + if (!matched && !this.match(pathname)) return pathname; + pathname = this.prefix.normalize(pathname, true); + pathname = this.suffix.normalize(pathname, true); + return (0, _denormalizepagepath.denormalizePagePath)(pathname); + } +} + +//# sourceMappingURL=next-data.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/next-data.js.map b/e-commerce/node_modules/next/dist/server/normalizers/request/next-data.js.map new file mode 100644 index 0000000000000000000000000000000000000000..765217d88e0dd03cf9515f235e6cfdf06d9be437 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/next-data.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/normalizers/request/next-data.ts"],"sourcesContent":["import type { PathnameNormalizer } from './pathname-normalizer'\n\nimport { denormalizePagePath } from '../../../shared/lib/page-path/denormalize-page-path'\nimport { PrefixPathnameNormalizer } from './prefix'\nimport { SuffixPathnameNormalizer } from './suffix'\n\nexport class NextDataPathnameNormalizer implements PathnameNormalizer {\n private readonly prefix: PrefixPathnameNormalizer\n private readonly suffix = new SuffixPathnameNormalizer('.json')\n constructor(buildID: string) {\n if (!buildID) {\n throw new Error('Invariant: buildID is required')\n }\n\n this.prefix = new PrefixPathnameNormalizer(`/_next/data/${buildID}`)\n }\n\n public match(pathname: string) {\n return this.prefix.match(pathname) && this.suffix.match(pathname)\n }\n\n public normalize(pathname: string, matched?: boolean): string {\n // If we're not matched and we don't match, we don't need to normalize.\n if (!matched && !this.match(pathname)) return pathname\n\n pathname = this.prefix.normalize(pathname, true)\n pathname = this.suffix.normalize(pathname, true)\n\n return denormalizePagePath(pathname)\n }\n}\n"],"names":["NextDataPathnameNormalizer","constructor","buildID","suffix","SuffixPathnameNormalizer","Error","prefix","PrefixPathnameNormalizer","match","pathname","normalize","matched","denormalizePagePath"],"mappings":";;;;+BAMaA;;;eAAAA;;;qCAJuB;wBACK;wBACA;AAElC,MAAMA;IAGXC,YAAYC,OAAe,CAAE;aADZC,SAAS,IAAIC,gCAAwB,CAAC;QAErD,IAAI,CAACF,SAAS;YACZ,MAAM,IAAIG,MAAM;QAClB;QAEA,IAAI,CAACC,MAAM,GAAG,IAAIC,gCAAwB,CAAC,CAAC,YAAY,EAAEL,SAAS;IACrE;IAEOM,MAAMC,QAAgB,EAAE;QAC7B,OAAO,IAAI,CAACH,MAAM,CAACE,KAAK,CAACC,aAAa,IAAI,CAACN,MAAM,CAACK,KAAK,CAACC;IAC1D;IAEOC,UAAUD,QAAgB,EAAEE,OAAiB,EAAU;QAC5D,uEAAuE;QACvE,IAAI,CAACA,WAAW,CAAC,IAAI,CAACH,KAAK,CAACC,WAAW,OAAOA;QAE9CA,WAAW,IAAI,CAACH,MAAM,CAACI,SAAS,CAACD,UAAU;QAC3CA,WAAW,IAAI,CAACN,MAAM,CAACO,SAAS,CAACD,UAAU;QAE3C,OAAOG,IAAAA,wCAAmB,EAACH;IAC7B;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/pathname-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/request/pathname-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..906e7d3053642048f635dfe7301cdfb747a05367 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/pathname-normalizer.d.ts @@ -0,0 +1,5 @@ +import type { Normalizer } from '../normalizer'; +export interface PathnameNormalizer extends Normalizer { + match(pathname: string): boolean; + normalize(pathname: string, matched?: boolean): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/pathname-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/request/pathname-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..68cb656849a7561dca166b6402d5d87fd02d30cc --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/pathname-normalizer.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=pathname-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/pathname-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/request/pathname-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/pathname-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/prefix.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/request/prefix.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0e28bedf2438d8c10352c61b48441a869cf3dee --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/prefix.d.ts @@ -0,0 +1,7 @@ +import type { Normalizer } from '../normalizer'; +export declare class PrefixPathnameNormalizer implements Normalizer { + private readonly prefix; + constructor(prefix: string); + match(pathname: string): boolean; + normalize(pathname: string, matched?: boolean): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/prefix.js b/e-commerce/node_modules/next/dist/server/normalizers/request/prefix.js new file mode 100644 index 0000000000000000000000000000000000000000..18b74887c35737c23da333d655e4d3143270ac03 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/prefix.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "PrefixPathnameNormalizer", { + enumerable: true, + get: function() { + return PrefixPathnameNormalizer; + } +}); +class PrefixPathnameNormalizer { + constructor(prefix){ + this.prefix = prefix; + if (prefix.endsWith('/')) { + throw new Error(`PrefixPathnameNormalizer: prefix "${prefix}" should not end with a slash`); + } + } + match(pathname) { + // If the pathname doesn't start with the prefix, we don't match. + if (pathname !== this.prefix && !pathname.startsWith(this.prefix + '/')) { + return false; + } + return true; + } + normalize(pathname, matched) { + // If we're not matched and we don't match, we don't need to normalize. + if (!matched && !this.match(pathname)) return pathname; + if (pathname.length === this.prefix.length) { + return '/'; + } + return pathname.substring(this.prefix.length); + } +} + +//# sourceMappingURL=prefix.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/prefix.js.map b/e-commerce/node_modules/next/dist/server/normalizers/request/prefix.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8daa46fe3ca654020455d15660e37f61e217e896 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/prefix.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/normalizers/request/prefix.ts"],"sourcesContent":["import type { Normalizer } from '../normalizer'\n\nexport class PrefixPathnameNormalizer implements Normalizer {\n constructor(private readonly prefix: string) {\n if (prefix.endsWith('/')) {\n throw new Error(\n `PrefixPathnameNormalizer: prefix \"${prefix}\" should not end with a slash`\n )\n }\n }\n\n public match(pathname: string) {\n // If the pathname doesn't start with the prefix, we don't match.\n if (pathname !== this.prefix && !pathname.startsWith(this.prefix + '/')) {\n return false\n }\n\n return true\n }\n\n public normalize(pathname: string, matched?: boolean): string {\n // If we're not matched and we don't match, we don't need to normalize.\n if (!matched && !this.match(pathname)) return pathname\n\n if (pathname.length === this.prefix.length) {\n return '/'\n }\n\n return pathname.substring(this.prefix.length)\n }\n}\n"],"names":["PrefixPathnameNormalizer","constructor","prefix","endsWith","Error","match","pathname","startsWith","normalize","matched","length","substring"],"mappings":";;;;+BAEaA;;;eAAAA;;;AAAN,MAAMA;IACXC,YAAY,AAAiBC,MAAc,CAAE;aAAhBA,SAAAA;QAC3B,IAAIA,OAAOC,QAAQ,CAAC,MAAM;YACxB,MAAM,IAAIC,MACR,CAAC,kCAAkC,EAAEF,OAAO,6BAA6B,CAAC;QAE9E;IACF;IAEOG,MAAMC,QAAgB,EAAE;QAC7B,iEAAiE;QACjE,IAAIA,aAAa,IAAI,CAACJ,MAAM,IAAI,CAACI,SAASC,UAAU,CAAC,IAAI,CAACL,MAAM,GAAG,MAAM;YACvE,OAAO;QACT;QAEA,OAAO;IACT;IAEOM,UAAUF,QAAgB,EAAEG,OAAiB,EAAU;QAC5D,uEAAuE;QACvE,IAAI,CAACA,WAAW,CAAC,IAAI,CAACJ,KAAK,CAACC,WAAW,OAAOA;QAE9C,IAAIA,SAASI,MAAM,KAAK,IAAI,CAACR,MAAM,CAACQ,MAAM,EAAE;YAC1C,OAAO;QACT;QAEA,OAAOJ,SAASK,SAAS,CAAC,IAAI,CAACT,MAAM,CAACQ,MAAM;IAC9C;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/rsc.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/request/rsc.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc80582f5870d35dd4a3107aa5bb404c44945584 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/rsc.d.ts @@ -0,0 +1,5 @@ +import type { PathnameNormalizer } from './pathname-normalizer'; +import { SuffixPathnameNormalizer } from './suffix'; +export declare class RSCPathnameNormalizer extends SuffixPathnameNormalizer implements PathnameNormalizer { + constructor(); +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/rsc.js b/e-commerce/node_modules/next/dist/server/normalizers/request/rsc.js new file mode 100644 index 0000000000000000000000000000000000000000..f9eefc692a66f75a11f123102f3e2bae9df4c8fb --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/rsc.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "RSCPathnameNormalizer", { + enumerable: true, + get: function() { + return RSCPathnameNormalizer; + } +}); +const _constants = require("../../../lib/constants"); +const _suffix = require("./suffix"); +class RSCPathnameNormalizer extends _suffix.SuffixPathnameNormalizer { + constructor(){ + super(_constants.RSC_SUFFIX); + } +} + +//# sourceMappingURL=rsc.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/rsc.js.map b/e-commerce/node_modules/next/dist/server/normalizers/request/rsc.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3951ca25ad938b7ed799f4bfb2d6fea166c18796 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/rsc.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/normalizers/request/rsc.ts"],"sourcesContent":["import type { PathnameNormalizer } from './pathname-normalizer'\n\nimport { RSC_SUFFIX } from '../../../lib/constants'\nimport { SuffixPathnameNormalizer } from './suffix'\n\nexport class RSCPathnameNormalizer\n extends SuffixPathnameNormalizer\n implements PathnameNormalizer\n{\n constructor() {\n super(RSC_SUFFIX)\n }\n}\n"],"names":["RSCPathnameNormalizer","SuffixPathnameNormalizer","constructor","RSC_SUFFIX"],"mappings":";;;;+BAKaA;;;eAAAA;;;2BAHc;wBACc;AAElC,MAAMA,8BACHC,gCAAwB;IAGhCC,aAAc;QACZ,KAAK,CAACC,qBAAU;IAClB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/segment-prefix-rsc.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/request/segment-prefix-rsc.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e3d10cd3fa9dcaedf36eb84bc828f66564567a3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/segment-prefix-rsc.d.ts @@ -0,0 +1,9 @@ +import type { PathnameNormalizer } from './pathname-normalizer'; +export declare class SegmentPrefixRSCPathnameNormalizer implements PathnameNormalizer { + match(pathname: string): boolean; + extract(pathname: string): { + originalPathname: string; + segmentPath: string; + } | null; + normalize(pathname: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/segment-prefix-rsc.js b/e-commerce/node_modules/next/dist/server/normalizers/request/segment-prefix-rsc.js new file mode 100644 index 0000000000000000000000000000000000000000..514d37495327ef89bc47e1578221ff2aa80c82da --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/segment-prefix-rsc.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "SegmentPrefixRSCPathnameNormalizer", { + enumerable: true, + get: function() { + return SegmentPrefixRSCPathnameNormalizer; + } +}); +const _constants = require("../../../lib/constants"); +const _escaperegexp = require("../../../shared/lib/escape-regexp"); +const PATTERN = new RegExp(`^(/.*)${(0, _escaperegexp.escapeStringRegexp)(_constants.RSC_SEGMENTS_DIR_SUFFIX)}(/.*)${(0, _escaperegexp.escapeStringRegexp)(_constants.RSC_SEGMENT_SUFFIX)}$`); +class SegmentPrefixRSCPathnameNormalizer { + match(pathname) { + return PATTERN.test(pathname); + } + extract(pathname) { + const match = pathname.match(PATTERN); + if (!match) return null; + return { + originalPathname: match[1], + segmentPath: match[2] + }; + } + normalize(pathname) { + const match = this.extract(pathname); + if (!match) return pathname; + return match.originalPathname; + } +} + +//# sourceMappingURL=segment-prefix-rsc.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/segment-prefix-rsc.js.map b/e-commerce/node_modules/next/dist/server/normalizers/request/segment-prefix-rsc.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a7712b6d2840fe524a3261a47905e847513a1df7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/segment-prefix-rsc.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/normalizers/request/segment-prefix-rsc.ts"],"sourcesContent":["import type { PathnameNormalizer } from './pathname-normalizer'\n\nimport {\n RSC_SEGMENT_SUFFIX,\n RSC_SEGMENTS_DIR_SUFFIX,\n} from '../../../lib/constants'\nimport { escapeStringRegexp } from '../../../shared/lib/escape-regexp'\n\nconst PATTERN = new RegExp(\n `^(/.*)${escapeStringRegexp(RSC_SEGMENTS_DIR_SUFFIX)}(/.*)${escapeStringRegexp(RSC_SEGMENT_SUFFIX)}$`\n)\n\nexport class SegmentPrefixRSCPathnameNormalizer implements PathnameNormalizer {\n public match(pathname: string): boolean {\n return PATTERN.test(pathname)\n }\n\n public extract(pathname: string) {\n const match = pathname.match(PATTERN)\n if (!match) return null\n\n return { originalPathname: match[1], segmentPath: match[2] }\n }\n\n public normalize(pathname: string): string {\n const match = this.extract(pathname)\n if (!match) return pathname\n\n return match.originalPathname\n }\n}\n"],"names":["SegmentPrefixRSCPathnameNormalizer","PATTERN","RegExp","escapeStringRegexp","RSC_SEGMENTS_DIR_SUFFIX","RSC_SEGMENT_SUFFIX","match","pathname","test","extract","originalPathname","segmentPath","normalize"],"mappings":";;;;+BAYaA;;;eAAAA;;;2BAPN;8BAC4B;AAEnC,MAAMC,UAAU,IAAIC,OAClB,CAAC,MAAM,EAAEC,IAAAA,gCAAkB,EAACC,kCAAuB,EAAE,KAAK,EAAED,IAAAA,gCAAkB,EAACE,6BAAkB,EAAE,CAAC,CAAC;AAGhG,MAAML;IACJM,MAAMC,QAAgB,EAAW;QACtC,OAAON,QAAQO,IAAI,CAACD;IACtB;IAEOE,QAAQF,QAAgB,EAAE;QAC/B,MAAMD,QAAQC,SAASD,KAAK,CAACL;QAC7B,IAAI,CAACK,OAAO,OAAO;QAEnB,OAAO;YAAEI,kBAAkBJ,KAAK,CAAC,EAAE;YAAEK,aAAaL,KAAK,CAAC,EAAE;QAAC;IAC7D;IAEOM,UAAUL,QAAgB,EAAU;QACzC,MAAMD,QAAQ,IAAI,CAACG,OAAO,CAACF;QAC3B,IAAI,CAACD,OAAO,OAAOC;QAEnB,OAAOD,MAAMI,gBAAgB;IAC/B;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/suffix.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/request/suffix.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..62ef50fcdfd1c008f79301a489f89b387e0a6e51 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/suffix.d.ts @@ -0,0 +1,7 @@ +import type { Normalizer } from '../normalizer'; +export declare class SuffixPathnameNormalizer implements Normalizer { + private readonly suffix; + constructor(suffix: string); + match(pathname: string): boolean; + normalize(pathname: string, matched?: boolean): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/suffix.js b/e-commerce/node_modules/next/dist/server/normalizers/request/suffix.js new file mode 100644 index 0000000000000000000000000000000000000000..5cd6daccf85cab77f2314c4ac078856e745d100b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/suffix.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "SuffixPathnameNormalizer", { + enumerable: true, + get: function() { + return SuffixPathnameNormalizer; + } +}); +class SuffixPathnameNormalizer { + constructor(suffix){ + this.suffix = suffix; + } + match(pathname) { + // If the pathname doesn't end in the suffix, we don't match. + if (!pathname.endsWith(this.suffix)) return false; + return true; + } + normalize(pathname, matched) { + // If we're not matched and we don't match, we don't need to normalize. + if (!matched && !this.match(pathname)) return pathname; + return pathname.substring(0, pathname.length - this.suffix.length); + } +} + +//# sourceMappingURL=suffix.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/request/suffix.js.map b/e-commerce/node_modules/next/dist/server/normalizers/request/suffix.js.map new file mode 100644 index 0000000000000000000000000000000000000000..96ec7693c9703fd66a22b66f68feb29ee0abf4d5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/request/suffix.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/normalizers/request/suffix.ts"],"sourcesContent":["import type { Normalizer } from '../normalizer'\n\nexport class SuffixPathnameNormalizer implements Normalizer {\n constructor(private readonly suffix: string) {}\n\n public match(pathname: string) {\n // If the pathname doesn't end in the suffix, we don't match.\n if (!pathname.endsWith(this.suffix)) return false\n\n return true\n }\n\n public normalize(pathname: string, matched?: boolean): string {\n // If we're not matched and we don't match, we don't need to normalize.\n if (!matched && !this.match(pathname)) return pathname\n\n return pathname.substring(0, pathname.length - this.suffix.length)\n }\n}\n"],"names":["SuffixPathnameNormalizer","constructor","suffix","match","pathname","endsWith","normalize","matched","substring","length"],"mappings":";;;;+BAEaA;;;eAAAA;;;AAAN,MAAMA;IACXC,YAAY,AAAiBC,MAAc,CAAE;aAAhBA,SAAAA;IAAiB;IAEvCC,MAAMC,QAAgB,EAAE;QAC7B,6DAA6D;QAC7D,IAAI,CAACA,SAASC,QAAQ,CAAC,IAAI,CAACH,MAAM,GAAG,OAAO;QAE5C,OAAO;IACT;IAEOI,UAAUF,QAAgB,EAAEG,OAAiB,EAAU;QAC5D,uEAAuE;QACvE,IAAI,CAACA,WAAW,CAAC,IAAI,CAACJ,KAAK,CAACC,WAAW,OAAOA;QAE9C,OAAOA,SAASI,SAAS,CAAC,GAAGJ,SAASK,MAAM,GAAG,IAAI,CAACP,MAAM,CAACO,MAAM;IACnE;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/underscore-normalizer.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/underscore-normalizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e8860f0860f901295bcdd88d1affe5a26a9662e3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/underscore-normalizer.d.ts @@ -0,0 +1,7 @@ +import type { Normalizer } from './normalizer'; +/** + * UnderscoreNormalizer replaces all instances of %5F with _. + */ +export declare class UnderscoreNormalizer implements Normalizer { + normalize(pathname: string): string; +} diff --git a/e-commerce/node_modules/next/dist/server/normalizers/underscore-normalizer.js b/e-commerce/node_modules/next/dist/server/normalizers/underscore-normalizer.js new file mode 100644 index 0000000000000000000000000000000000000000..d7997687b84279119e4e594074bec7f90bdb13c7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/underscore-normalizer.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "UnderscoreNormalizer", { + enumerable: true, + get: function() { + return UnderscoreNormalizer; + } +}); +class UnderscoreNormalizer { + normalize(pathname) { + return pathname.replace(/%5F/g, '_'); + } +} + +//# sourceMappingURL=underscore-normalizer.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/underscore-normalizer.js.map b/e-commerce/node_modules/next/dist/server/normalizers/underscore-normalizer.js.map new file mode 100644 index 0000000000000000000000000000000000000000..71ced79828567f2ddf9283db67c83c26cba1e5a1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/underscore-normalizer.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/normalizers/underscore-normalizer.ts"],"sourcesContent":["import type { Normalizer } from './normalizer'\n\n/**\n * UnderscoreNormalizer replaces all instances of %5F with _.\n */\nexport class UnderscoreNormalizer implements Normalizer {\n public normalize(pathname: string): string {\n return pathname.replace(/%5F/g, '_')\n }\n}\n"],"names":["UnderscoreNormalizer","normalize","pathname","replace"],"mappings":";;;;+BAKaA;;;eAAAA;;;AAAN,MAAMA;IACJC,UAAUC,QAAgB,EAAU;QACzC,OAAOA,SAASC,OAAO,CAAC,QAAQ;IAClC;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/wrap-normalizer-fn.d.ts b/e-commerce/node_modules/next/dist/server/normalizers/wrap-normalizer-fn.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..136ca836bcb6adf02adb2807384aeb9eb7a69ce4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/wrap-normalizer-fn.d.ts @@ -0,0 +1,2 @@ +import type { Normalizer } from './normalizer'; +export declare function wrapNormalizerFn(fn: (pathname: string) => string): Normalizer; diff --git a/e-commerce/node_modules/next/dist/server/normalizers/wrap-normalizer-fn.js b/e-commerce/node_modules/next/dist/server/normalizers/wrap-normalizer-fn.js new file mode 100644 index 0000000000000000000000000000000000000000..262af718f8b60b6329850672fb8131543c912da9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/wrap-normalizer-fn.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "wrapNormalizerFn", { + enumerable: true, + get: function() { + return wrapNormalizerFn; + } +}); +function wrapNormalizerFn(fn) { + return { + normalize: fn + }; +} + +//# sourceMappingURL=wrap-normalizer-fn.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/normalizers/wrap-normalizer-fn.js.map b/e-commerce/node_modules/next/dist/server/normalizers/wrap-normalizer-fn.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8944c8c91da85b09520dd2ba8804323755a3e26b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/normalizers/wrap-normalizer-fn.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/normalizers/wrap-normalizer-fn.ts"],"sourcesContent":["import type { Normalizer } from './normalizer'\n\nexport function wrapNormalizerFn(fn: (pathname: string) => string): Normalizer {\n return { normalize: fn }\n}\n"],"names":["wrapNormalizerFn","fn","normalize"],"mappings":";;;;+BAEgBA;;;eAAAA;;;AAAT,SAASA,iBAAiBC,EAAgC;IAC/D,OAAO;QAAEC,WAAWD;IAAG;AACzB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/og/cache-image-response.d.ts b/e-commerce/node_modules/next/dist/server/og/cache-image-response.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..864d1d9343a42b7067b5170f8d21949408364625 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/og/cache-image-response.d.ts @@ -0,0 +1,22 @@ +type OgModule = typeof import('next/dist/compiled/@vercel/og'); +type ImageResponseArgs = ConstructorParameters; +/** + * Builds the body for a Cache Components `ImageResponse`. The rendered image is + * cached in the Resume Data Cache during a prerender, so the prospective + * prerender renders it once and the final prerender retrieves it from memory + * within microtasks. This lets metadata image routes be statically prerendered + * under Cache Components instead of being treated as dynamic. + * + * The cache boundary is drawn around only the deterministic rasterization of + * the element tree into an image. The `ImageResponse` element tree is rendered + * with React Flight once, inside the prerender work-unit store, so any + * user-space I/O (e.g. `cookies()` or an uncached `fetch`) runs in the correct + * scope and is subject to the normal Cache Components rules. If that tree + * needs dynamic input the serialization can't complete, and the route falls + * back to dynamic. Otherwise the fully resolved tree is handed to satori, + * which never re-runs the user's components. + * + * Outside of a prerender (normal requests) this just renders. + */ +export declare function getCachedImageResponseBody(args: ImageResponseArgs): ReadableStream; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/og/cache-image-response.js b/e-commerce/node_modules/next/dist/server/og/cache-image-response.js new file mode 100644 index 0000000000000000000000000000000000000000..992b40184ed300c414b7a22543d3faac56ef055b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/og/cache-image-response.js @@ -0,0 +1,336 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getCachedImageResponseBody", { + enumerable: true, + get: function() { + return getCachedImageResponseBody; + } +}); +const _nodestream = require("node:stream"); +const _nodecrypto = require("node:crypto"); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _dynamicrendering = require("../app-render/dynamic-rendering"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _manifestssingleton = require("../app-render/manifests-singleton"); +const _static = require("react-server-dom-webpack/static"); +const _client = require("react-server-dom-webpack/client"); +function importOgModule() { + // Cache Components is Node-only (rejected for the edge runtime at compile + // time), so we always load the Node build. Loading it dynamically keeps the + // heavy `@vercel/og` renderer (satori + WASM) off the module-load path, so + // it's pulled in only when an image is actually rendered. + return import('next/dist/compiled/@vercel/og/index.node.js'); +} +function getCachedImageResponseBody(args) { + return new ReadableStream({ + async start (controller) { + const arrayBuffer = await getCachedImageResponseArrayBuffer(args); + if (arrayBuffer.byteLength > 0) { + controller.enqueue(new Uint8Array(arrayBuffer)); + } + controller.close(); + } + }); +} +async function getCachedImageResponseArrayBuffer(args) { + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + switch(workUnitStore == null ? void 0 : workUnitStore.type){ + case 'prerender': + break; + case undefined: + case 'request': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'prerender-runtime': + case 'prerender-client': + case 'validation-client': + case 'prerender-legacy': + case 'build-time-generator': + return renderImageResponseArrayBuffer(args); + default: + return workUnitStore; + } + const { cacheSignal, resumeDataCache, renderSignal } = workUnitStore; + if (!resumeDataCache) { + return renderImageResponseArrayBuffer(args); + } + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new _invarianterror.InvariantError('Expected a work store while caching an `ImageResponse` during prerendering.'); + } + const [element, options] = args; + // `createHangingInputAbortSignal` aborts once the prerender's cache-sourced + // input is ready, so anything the serialization below is still awaiting past + // that point can be treated as dynamic (non-cache) input. In the prospective + // pass it aborts when `cacheSignal.inputReady()` resolves (no cache reads + // in progress); in the final pass the caches are already filled, so it just + // aborts on the next tick. + const hangingInputAbortSignal = (0, _dynamicrendering.createHangingInputAbortSignal)(workUnitStore); + // We open the cache read lazily, once we know the serialization completed and + // we're about to render and store the image. Opening it before serializing + // would keep `cacheSignal.inputReady()` from resolving and thus prevent the + // abort signal from ever firing, deadlocking the prospective prerender. + let readState = 'ready'; + function beginReadOnce() { + if (readState === 'ready') { + readState = 'pending'; + cacheSignal == null ? void 0 : cacheSignal.beginRead(); + } + } + function endReadIfStarted() { + if (readState === 'pending') { + cacheSignal == null ? void 0 : cacheSignal.endRead(); + } + readState = 'done'; + } + // We serialize the element tree with `prerenderToNodeStream` rather than + // `renderToPipeableStream`. It's the right fit for prerendering, and it + // schedules work deferred for size (`deferTask`) on microtasks, so a fully + // static tree finishes flushing before the abort signal fires; a tree still + // pending at abort time is then genuinely waiting on dynamic input rather + // than just deferred. + // + // `renderToPipeableStream` would schedule that deferred work on + // `setImmediate` instead, which isn't necessarily a deal-breaker: the + // sequential-task scheme page rendering uses (`runInSequentialTasks`) drains + // pending immediates at each task boundary, so deferred work still runs in + // time. But route handler prerendering doesn't use that scheme, so here the + // deferred immediates would race the abort. + // + // The prerender halts silently on abort, leaving unfulfilled references in + // place rather than reporting through `onError`. So to tell a halt (the tree + // needed dynamic input) apart from a normal completion, we record whether the + // abort fired before the serialization finished. `abort()` runs this listener + // synchronously, well before we read `resultIsPartial` below. + let prerenderCompleted = false; + let resultIsPartial = false; + let serializationError; + hangingInputAbortSignal.addEventListener('abort', ()=>{ + if (!prerenderCompleted) { + resultIsPartial = true; + } + }, { + once: true + }); + const { clientModules, rscModuleMapping } = (0, _manifestssingleton.getClientReferenceManifest)(); + try { + // We serialize only the `element`. It's the part that needs Flight, to run + // its async Server Components once and to surface any dynamic input. The + // `options` are already-resolved plain data; they're folded into the cache + // key directly and passed to satori as-is below. + const { prelude } = await (0, _static.prerenderToNodeStream)(element, clientModules, { + signal: hangingInputAbortSignal, + filterStackFrame: undefined, + onError (error) { + // A halt (our deliberate abort) emits nothing, so this is only called + // for genuine serialization errors. We surface the first one. + if (serializationError === undefined && !resultIsPartial) { + serializationError = error; + } + } + }); + prerenderCompleted = true; + if (serializationError !== undefined) { + throw serializationError; + } + if (resultIsPartial) { + // The element tree needed dynamic input (e.g. `cookies()` or an uncached + // `fetch`), so the image can't be produced statically. Return a hanging + // promise: the body never resolves, and the final prerender's macrotask + // budget then classifies the route as dynamic. + // Whatever dynamic input made the element partial already classified + // itself when it created its own hanging promise (cookies() creates a + // runtime hanging promise, an uncached fetch creates a dynamic one, + // ...), so this wrapper adds no new information and can use the + // non-recording dynamic variant. + return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(renderSignal, workStore.route, 'dynamic `ImageResponse`'); + } + // The serialization finished before any dynamic input was needed, so we + // will render and cache the image. Hold the cache read now, before the + // stream is buffered and deserialized below, so that the prospective + // prerender's `cacheReady()` waits for the image to be stored. + beginReadOnce(); + const chunks = []; + for await (const chunk of prelude){ + chunks.push(chunk); + } + const elementBuffer = Buffer.concat(chunks); + // Derive a stable cache key from the serialized element plus the options. + // We hash rather than reuse the raw serialized bytes so the key stays + // compact even for large inputs (e.g. embedded fonts), and we fold the + // options in by content so two images that differ only in their options + // (size, fonts, ...) don't collide. The options are hashed directly here, + // never serialized through Flight, which would both bloat the key and apply + // `Buffer.prototype .toJSON` to font data. + const hash = (0, _nodecrypto.createHash)('sha256'); + hash.update(elementBuffer); + updateHashWithOptions(hash, options); + const cacheKey = hash.digest('base64'); + const cached = resumeDataCache.imageResponses.get(cacheKey); + if (cached) { + return await cached; + } + // Deserialize the element and hand it to satori. Because the user's + // components already ran during serialization, satori only walks resolved + // host elements and never re-runs them, confining user-space I/O to the + // in-store serialization above. + const deserializedElement = await (0, _client.createFromNodeStream)(_nodestream.Readable.from([ + elementBuffer + ]), { + // We don't want to trigger preloads of client references here. + moduleLoading: null, + moduleMap: rscModuleMapping, + serverModuleMap: (0, _manifestssingleton.getServerModuleMap)() + }, { + findSourceMapURL: undefined + }); + // The Flight client hands back the output of an async Server Component as + // a `React.lazy` (sync components and plain host elements are inlined). + // satori can't unwrap lazies, so we resolve them into plain elements first. + // We only reach here once the serialization completed, so every lazy is + // already resolved and `_init` returns synchronously. + const resolvedElement = resolveFlightLazies(deserializedElement); + // Pair the resolved element with the original, in-memory `options`, which + // never went through Flight. This keeps the font `Buffer` intact: had it + // been serialized, Flight would apply the `toJSON` method that Node's + // `Buffer` carries, turning it into a `{ type: 'Buffer', data: [...] }` + // object that satori's font parser rejects (it needs an `ArrayBuffer` or a + // typed array). + const resolvedArgs = [ + resolvedElement, + options + ]; + // Render satori outside the prerender work-unit store. It does uncached + // `fetch` calls (e.g. loading a font), and inside a Cache Components + // prerender an uncached `fetch` outside a cache scope becomes a hanging + // promise. Those are framework fetches, not user I/O, so we let them + // resolve normally with no store. + const arrayBufferPromise = _workunitasyncstorageexternal.workUnitAsyncStorage.exit(()=>renderImageResponseArrayBuffer(resolvedArgs)); + if (resumeDataCache.mutable) { + resumeDataCache.imageResponses.set(cacheKey, arrayBufferPromise); + } + return await arrayBufferPromise; + } finally{ + endReadIfStarted(); + } +} +/** + * Updates a hash with a stable encoding of the `ImageResponse` options so they + * can participate in the cache key without being serialized through Flight. + * Binary values (font `Buffer`s, `ArrayBuffer`s, typed arrays) are hashed by + * their raw bytes; objects are walked in sorted-key order. + * + * `ImageResponse` options are plain data: numbers, strings, booleans, nested + * plain objects/arrays, and binary font data. Exotic objects such as `Map` or + * `Date` keep their state outside their enumerable own keys, so the key walk + * below would hash them incorrectly. Options never contain these, but we warn + * if one ever shows up so a mis-keyed cache can be reported. + * + * The encoding is self-delimiting: every node starts with a type tag, and + * variable-length parts (byte runs, primitives, keys) are length-prefixed, + * while arrays and objects are count-prefixed. This makes it injective, so no + * concatenation of values can be mistaken for a differently shaped input. + */ function updateHashWithOptions(hash, value) { + if (value === undefined) { + hash.update('u'); + return; + } + if (value === null) { + hash.update('n'); + return; + } + const type = typeof value; + if (type !== 'object') { + // Tag with the primitive type so e.g. the number `1` and the string `'1'` + // don't hash the same. + updateHashWithBytes(hash, 'p', Buffer.from(`${type}:${String(value)}`)); + return; + } + if (value instanceof ArrayBuffer) { + updateHashWithBytes(hash, 'a', new Uint8Array(value)); + return; + } + if (ArrayBuffer.isView(value)) { + updateHashWithBytes(hash, 'v', new Uint8Array(value.buffer, value.byteOffset, value.byteLength)); + return; + } + if (Array.isArray(value)) { + hash.update(`[${value.length},`); + for (const item of value){ + updateHashWithOptions(hash, item); + } + return; + } + // The key walk below captures a plain object faithfully, but an exotic object + // keeps its state elsewhere (a `Map`'s/`Set`'s entries, a `Date`'s time), so + // two different values would hash the same and could return the wrong cached + // image. This shouldn't happen for `ImageResponse` options, so we warn rather + // than fail, then hash best-effort, so it can be reported. Not gated on + // `NODE_ENV`: this runs during the production `next build` prerender, where + // the warning is most useful. + const prototype = Object.getPrototypeOf(value); + if (prototype !== Object.prototype && prototype !== null) { + var _value_constructor; + const typeName = ((_value_constructor = value.constructor) == null ? void 0 : _value_constructor.name) ?? 'object'; + console.warn(`Cannot reliably include an \`ImageResponse\` option of type ` + `\`${typeName}\` in the cache key, so different images may collide and ` + `return an incorrect cached result. Please report this to the Next.js ` + `team.`); + } + const keys = Object.keys(value).sort(); + hash.update(`{${keys.length},`); + for (const key of keys){ + updateHashWithBytes(hash, 'k', Buffer.from(key)); + updateHashWithOptions(hash, value[key]); + } +} +/** + * Hashes a length-prefixed, tagged byte run: `:`. The + * length prefix keeps the run self-delimiting so it can't blend into adjacent + * nodes. + */ function updateHashWithBytes(hash, tag, bytes) { + hash.update(`${tag}${bytes.byteLength}:`); + hash.update(bytes); +} +async function renderImageResponseArrayBuffer(args) { + const OGImageResponse = (await importOgModule()).ImageResponse; + const imageResponse = new OGImageResponse(...args); + if (!imageResponse.body) { + return new ArrayBuffer(0); + } + return imageResponse.arrayBuffer(); +} +const REACT_LAZY_TYPE = Symbol.for('react.lazy'); +/** + * Recursively replaces the `React.lazy` references that Flight emits for + * resolved async Server Components with the elements they resolve to, so that + * satori (which doesn't understand lazy nodes) can walk the tree. This must + * only be called on a fully resolved (completed) Flight result, where each + * lazy's `_init` returns synchronously rather than suspending. + */ function resolveFlightLazies(node) { + if (node === null || typeof node !== 'object') { + return node; + } + if (node.$$typeof === REACT_LAZY_TYPE) { + const lazy = node; + return resolveFlightLazies(lazy._init(lazy._payload)); + } + if (Array.isArray(node)) { + return node.map(resolveFlightLazies); + } + const element = node; + if (element.props && 'children' in element.props) { + return { + ...element, + props: { + ...element.props, + children: resolveFlightLazies(element.props.children) + } + }; + } + return node; +} + +//# sourceMappingURL=cache-image-response.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/og/cache-image-response.js.map b/e-commerce/node_modules/next/dist/server/og/cache-image-response.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3f1fd9687cb63b23c5448b514feafe590c5aa3a7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/og/cache-image-response.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/og/cache-image-response.ts"],"sourcesContent":["import { Readable } from 'node:stream'\nimport { createHash, type Hash } from 'node:crypto'\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from '../app-render/dynamic-rendering'\nimport { makeDynamicHangingPromise } from '../dynamic-rendering-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from '../app-render/manifests-singleton'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { prerenderToNodeStream } from 'react-server-dom-webpack/static'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromNodeStream } from 'react-server-dom-webpack/client'\n\ntype OgModule = typeof import('next/dist/compiled/@vercel/og')\n\ntype ImageResponseArgs = ConstructorParameters\n\nfunction importOgModule(): Promise {\n // Cache Components is Node-only (rejected for the edge runtime at compile\n // time), so we always load the Node build. Loading it dynamically keeps the\n // heavy `@vercel/og` renderer (satori + WASM) off the module-load path, so\n // it's pulled in only when an image is actually rendered.\n return import('next/dist/compiled/@vercel/og/index.node.js')\n}\n\n/**\n * Builds the body for a Cache Components `ImageResponse`. The rendered image is\n * cached in the Resume Data Cache during a prerender, so the prospective\n * prerender renders it once and the final prerender retrieves it from memory\n * within microtasks. This lets metadata image routes be statically prerendered\n * under Cache Components instead of being treated as dynamic.\n *\n * The cache boundary is drawn around only the deterministic rasterization of\n * the element tree into an image. The `ImageResponse` element tree is rendered\n * with React Flight once, inside the prerender work-unit store, so any\n * user-space I/O (e.g. `cookies()` or an uncached `fetch`) runs in the correct\n * scope and is subject to the normal Cache Components rules. If that tree\n * needs dynamic input the serialization can't complete, and the route falls\n * back to dynamic. Otherwise the fully resolved tree is handed to satori,\n * which never re-runs the user's components.\n *\n * Outside of a prerender (normal requests) this just renders.\n */\nexport function getCachedImageResponseBody(\n args: ImageResponseArgs\n): ReadableStream {\n return new ReadableStream({\n async start(controller) {\n const arrayBuffer = await getCachedImageResponseArrayBuffer(args)\n if (arrayBuffer.byteLength > 0) {\n controller.enqueue(new Uint8Array(arrayBuffer))\n }\n controller.close()\n },\n })\n}\n\nasync function getCachedImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n // We only cache during a prerender. Metadata image routes compile to\n // route handlers, which use the `prerender` store.\n break\n case undefined:\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'build-time-generator':\n return renderImageResponseArrayBuffer(args)\n default:\n return workUnitStore satisfies never\n }\n\n const { cacheSignal, resumeDataCache, renderSignal } = workUnitStore\n\n if (!resumeDataCache) {\n return renderImageResponseArrayBuffer(args)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n if (!workStore) {\n throw new InvariantError(\n 'Expected a work store while caching an `ImageResponse` during prerendering.'\n )\n }\n\n const [element, options] = args\n\n // `createHangingInputAbortSignal` aborts once the prerender's cache-sourced\n // input is ready, so anything the serialization below is still awaiting past\n // that point can be treated as dynamic (non-cache) input. In the prospective\n // pass it aborts when `cacheSignal.inputReady()` resolves (no cache reads\n // in progress); in the final pass the caches are already filled, so it just\n // aborts on the next tick.\n const hangingInputAbortSignal = createHangingInputAbortSignal(workUnitStore)\n\n // We open the cache read lazily, once we know the serialization completed and\n // we're about to render and store the image. Opening it before serializing\n // would keep `cacheSignal.inputReady()` from resolving and thus prevent the\n // abort signal from ever firing, deadlocking the prospective prerender.\n let readState: 'ready' | 'pending' | 'done' = 'ready'\n\n function beginReadOnce() {\n if (readState === 'ready') {\n readState = 'pending'\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readState === 'pending') {\n cacheSignal?.endRead()\n }\n readState = 'done'\n }\n\n // We serialize the element tree with `prerenderToNodeStream` rather than\n // `renderToPipeableStream`. It's the right fit for prerendering, and it\n // schedules work deferred for size (`deferTask`) on microtasks, so a fully\n // static tree finishes flushing before the abort signal fires; a tree still\n // pending at abort time is then genuinely waiting on dynamic input rather\n // than just deferred.\n //\n // `renderToPipeableStream` would schedule that deferred work on\n // `setImmediate` instead, which isn't necessarily a deal-breaker: the\n // sequential-task scheme page rendering uses (`runInSequentialTasks`) drains\n // pending immediates at each task boundary, so deferred work still runs in\n // time. But route handler prerendering doesn't use that scheme, so here the\n // deferred immediates would race the abort.\n //\n // The prerender halts silently on abort, leaving unfulfilled references in\n // place rather than reporting through `onError`. So to tell a halt (the tree\n // needed dynamic input) apart from a normal completion, we record whether the\n // abort fired before the serialization finished. `abort()` runs this listener\n // synchronously, well before we read `resultIsPartial` below.\n let prerenderCompleted = false\n let resultIsPartial = false\n let serializationError: unknown\n\n hangingInputAbortSignal.addEventListener(\n 'abort',\n () => {\n if (!prerenderCompleted) {\n resultIsPartial = true\n }\n },\n { once: true }\n )\n\n const { clientModules, rscModuleMapping } = getClientReferenceManifest()\n\n try {\n // We serialize only the `element`. It's the part that needs Flight, to run\n // its async Server Components once and to surface any dynamic input. The\n // `options` are already-resolved plain data; they're folded into the cache\n // key directly and passed to satori as-is below.\n const { prelude } = await prerenderToNodeStream(element, clientModules, {\n signal: hangingInputAbortSignal,\n filterStackFrame: undefined,\n onError(error) {\n // A halt (our deliberate abort) emits nothing, so this is only called\n // for genuine serialization errors. We surface the first one.\n if (serializationError === undefined && !resultIsPartial) {\n serializationError = error\n }\n },\n })\n\n prerenderCompleted = true\n\n if (serializationError !== undefined) {\n throw serializationError\n }\n\n if (resultIsPartial) {\n // The element tree needed dynamic input (e.g. `cookies()` or an uncached\n // `fetch`), so the image can't be produced statically. Return a hanging\n // promise: the body never resolves, and the final prerender's macrotask\n // budget then classifies the route as dynamic.\n // Whatever dynamic input made the element partial already classified\n // itself when it created its own hanging promise (cookies() creates a\n // runtime hanging promise, an uncached fetch creates a dynamic one,\n // ...), so this wrapper adds no new information and can use the\n // non-recording dynamic variant.\n return makeDynamicHangingPromise(\n renderSignal,\n workStore.route,\n 'dynamic `ImageResponse`'\n )\n }\n\n // The serialization finished before any dynamic input was needed, so we\n // will render and cache the image. Hold the cache read now, before the\n // stream is buffered and deserialized below, so that the prospective\n // prerender's `cacheReady()` waits for the image to be stored.\n beginReadOnce()\n\n const chunks: Buffer[] = []\n for await (const chunk of prelude) {\n chunks.push(chunk)\n }\n\n const elementBuffer = Buffer.concat(chunks)\n\n // Derive a stable cache key from the serialized element plus the options.\n // We hash rather than reuse the raw serialized bytes so the key stays\n // compact even for large inputs (e.g. embedded fonts), and we fold the\n // options in by content so two images that differ only in their options\n // (size, fonts, ...) don't collide. The options are hashed directly here,\n // never serialized through Flight, which would both bloat the key and apply\n // `Buffer.prototype .toJSON` to font data.\n const hash = createHash('sha256')\n hash.update(elementBuffer)\n updateHashWithOptions(hash, options)\n const cacheKey = hash.digest('base64')\n\n const cached = resumeDataCache.imageResponses.get(cacheKey)\n\n if (cached) {\n return await cached\n }\n\n // Deserialize the element and hand it to satori. Because the user's\n // components already ran during serialization, satori only walks resolved\n // host elements and never re-runs them, confining user-space I/O to the\n // in-store serialization above.\n const deserializedElement = await createFromNodeStream(\n Readable.from([elementBuffer]),\n {\n // We don't want to trigger preloads of client references here.\n moduleLoading: null,\n moduleMap: rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n { findSourceMapURL: undefined }\n )\n\n // The Flight client hands back the output of an async Server Component as\n // a `React.lazy` (sync components and plain host elements are inlined).\n // satori can't unwrap lazies, so we resolve them into plain elements first.\n // We only reach here once the serialization completed, so every lazy is\n // already resolved and `_init` returns synchronously.\n const resolvedElement = resolveFlightLazies(deserializedElement)\n\n // Pair the resolved element with the original, in-memory `options`, which\n // never went through Flight. This keeps the font `Buffer` intact: had it\n // been serialized, Flight would apply the `toJSON` method that Node's\n // `Buffer` carries, turning it into a `{ type: 'Buffer', data: [...] }`\n // object that satori's font parser rejects (it needs an `ArrayBuffer` or a\n // typed array).\n const resolvedArgs = [resolvedElement, options] as ImageResponseArgs\n\n // Render satori outside the prerender work-unit store. It does uncached\n // `fetch` calls (e.g. loading a font), and inside a Cache Components\n // prerender an uncached `fetch` outside a cache scope becomes a hanging\n // promise. Those are framework fetches, not user I/O, so we let them\n // resolve normally with no store.\n const arrayBufferPromise = workUnitAsyncStorage.exit(() =>\n renderImageResponseArrayBuffer(resolvedArgs)\n )\n\n if (resumeDataCache.mutable) {\n resumeDataCache.imageResponses.set(cacheKey, arrayBufferPromise)\n }\n\n return await arrayBufferPromise\n } finally {\n endReadIfStarted()\n }\n}\n\n/**\n * Updates a hash with a stable encoding of the `ImageResponse` options so they\n * can participate in the cache key without being serialized through Flight.\n * Binary values (font `Buffer`s, `ArrayBuffer`s, typed arrays) are hashed by\n * their raw bytes; objects are walked in sorted-key order.\n *\n * `ImageResponse` options are plain data: numbers, strings, booleans, nested\n * plain objects/arrays, and binary font data. Exotic objects such as `Map` or\n * `Date` keep their state outside their enumerable own keys, so the key walk\n * below would hash them incorrectly. Options never contain these, but we warn\n * if one ever shows up so a mis-keyed cache can be reported.\n *\n * The encoding is self-delimiting: every node starts with a type tag, and\n * variable-length parts (byte runs, primitives, keys) are length-prefixed,\n * while arrays and objects are count-prefixed. This makes it injective, so no\n * concatenation of values can be mistaken for a differently shaped input.\n */\nfunction updateHashWithOptions(hash: Hash, value: unknown): void {\n if (value === undefined) {\n hash.update('u')\n return\n }\n\n if (value === null) {\n hash.update('n')\n return\n }\n\n const type = typeof value\n\n if (type !== 'object') {\n // Tag with the primitive type so e.g. the number `1` and the string `'1'`\n // don't hash the same.\n updateHashWithBytes(hash, 'p', Buffer.from(`${type}:${String(value)}`))\n return\n }\n\n if (value instanceof ArrayBuffer) {\n updateHashWithBytes(hash, 'a', new Uint8Array(value))\n return\n }\n\n if (ArrayBuffer.isView(value)) {\n updateHashWithBytes(\n hash,\n 'v',\n new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n )\n return\n }\n\n if (Array.isArray(value)) {\n hash.update(`[${value.length},`)\n for (const item of value) {\n updateHashWithOptions(hash, item)\n }\n return\n }\n\n // The key walk below captures a plain object faithfully, but an exotic object\n // keeps its state elsewhere (a `Map`'s/`Set`'s entries, a `Date`'s time), so\n // two different values would hash the same and could return the wrong cached\n // image. This shouldn't happen for `ImageResponse` options, so we warn rather\n // than fail, then hash best-effort, so it can be reported. Not gated on\n // `NODE_ENV`: this runs during the production `next build` prerender, where\n // the warning is most useful.\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n const typeName =\n (value as { constructor?: { name?: string } }).constructor?.name ??\n 'object'\n console.warn(\n `Cannot reliably include an \\`ImageResponse\\` option of type ` +\n `\\`${typeName}\\` in the cache key, so different images may collide and ` +\n `return an incorrect cached result. Please report this to the Next.js ` +\n `team.`\n )\n }\n\n const keys = Object.keys(value).sort()\n hash.update(`{${keys.length},`)\n for (const key of keys) {\n updateHashWithBytes(hash, 'k', Buffer.from(key))\n updateHashWithOptions(hash, (value as Record)[key])\n }\n}\n\n/**\n * Hashes a length-prefixed, tagged byte run: `:`. The\n * length prefix keeps the run self-delimiting so it can't blend into adjacent\n * nodes.\n */\nfunction updateHashWithBytes(hash: Hash, tag: string, bytes: Uint8Array): void {\n hash.update(`${tag}${bytes.byteLength}:`)\n hash.update(bytes)\n}\n\nasync function renderImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise {\n const OGImageResponse = (await importOgModule()).ImageResponse\n const imageResponse = new OGImageResponse(...args)\n\n if (!imageResponse.body) {\n return new ArrayBuffer(0)\n }\n\n return imageResponse.arrayBuffer()\n}\n\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy')\n\n/**\n * Recursively replaces the `React.lazy` references that Flight emits for\n * resolved async Server Components with the elements they resolve to, so that\n * satori (which doesn't understand lazy nodes) can walk the tree. This must\n * only be called on a fully resolved (completed) Flight result, where each\n * lazy's `_init` returns synchronously rather than suspending.\n */\nfunction resolveFlightLazies(node: unknown): unknown {\n if (node === null || typeof node !== 'object') {\n return node\n }\n\n if ((node as { $$typeof?: symbol }).$$typeof === REACT_LAZY_TYPE) {\n const lazy = node as {\n _init: (payload: unknown) => unknown\n _payload: unknown\n }\n return resolveFlightLazies(lazy._init(lazy._payload))\n }\n\n if (Array.isArray(node)) {\n return node.map(resolveFlightLazies)\n }\n\n const element = node as { props?: { children?: unknown } }\n if (element.props && 'children' in element.props) {\n return {\n ...element,\n props: {\n ...element.props,\n children: resolveFlightLazies(element.props.children),\n },\n }\n }\n\n return node\n}\n"],"names":["getCachedImageResponseBody","importOgModule","args","ReadableStream","start","controller","arrayBuffer","getCachedImageResponseArrayBuffer","byteLength","enqueue","Uint8Array","close","workUnitStore","workUnitAsyncStorage","getStore","type","undefined","renderImageResponseArrayBuffer","cacheSignal","resumeDataCache","renderSignal","workStore","workAsyncStorage","InvariantError","element","options","hangingInputAbortSignal","createHangingInputAbortSignal","readState","beginReadOnce","beginRead","endReadIfStarted","endRead","prerenderCompleted","resultIsPartial","serializationError","addEventListener","once","clientModules","rscModuleMapping","getClientReferenceManifest","prelude","prerenderToNodeStream","signal","filterStackFrame","onError","error","makeDynamicHangingPromise","route","chunks","chunk","push","elementBuffer","Buffer","concat","hash","createHash","update","updateHashWithOptions","cacheKey","digest","cached","imageResponses","get","deserializedElement","createFromNodeStream","Readable","from","moduleLoading","moduleMap","serverModuleMap","getServerModuleMap","findSourceMapURL","resolvedElement","resolveFlightLazies","resolvedArgs","arrayBufferPromise","exit","mutable","set","value","updateHashWithBytes","String","ArrayBuffer","isView","buffer","byteOffset","Array","isArray","length","item","prototype","Object","getPrototypeOf","typeName","constructor","name","console","warn","keys","sort","key","tag","bytes","OGImageResponse","ImageResponse","imageResponse","body","REACT_LAZY_TYPE","Symbol","for","node","$$typeof","lazy","_init","_payload","map","props","children"],"mappings":";;;;+BA+CgBA;;;eAAAA;;;4BA/CS;4BACa;gCAEP;0CACE;8CACI;kCACS;uCACJ;oCAInC;wBAE+B;wBAED;AAMrC,SAASC;IACP,0EAA0E;IAC1E,4EAA4E;IAC5E,2EAA2E;IAC3E,0DAA0D;IAC1D,OAAO,MAAM,CAAC;AAChB;AAoBO,SAASD,2BACdE,IAAuB;IAEvB,OAAO,IAAIC,eAA2B;QACpC,MAAMC,OAAMC,UAAU;YACpB,MAAMC,cAAc,MAAMC,kCAAkCL;YAC5D,IAAII,YAAYE,UAAU,GAAG,GAAG;gBAC9BH,WAAWI,OAAO,CAAC,IAAIC,WAAWJ;YACpC;YACAD,WAAWM,KAAK;QAClB;IACF;AACF;AAEA,eAAeJ,kCACbL,IAAuB;IAEvB,MAAMU,gBAAgBC,kDAAoB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F;AAEA;;;;CAIC,GACD,SAASpB,oBAAoB1B,IAAU,EAAE+C,GAAW,EAAEC,KAAiB;IACrEhD,KAAKE,MAAM,CAAC,GAAG6C,MAAMC,MAAM/F,UAAU,CAAC,CAAC,CAAC;IACxC+C,KAAKE,MAAM,CAAC8C;AACd;AAEA,eAAetF,+BACbf,IAAuB;IAEvB,MAAMsG,kBAAkB,AAAC,CAAA,MAAMvG,gBAAe,EAAGwG,aAAa;IAC9D,MAAMC,gBAAgB,IAAIF,mBAAmBtG;IAE7C,IAAI,CAACwG,cAAcC,IAAI,EAAE;QACvB,OAAO,IAAIxB,YAAY;IACzB;IAEA,OAAOuB,cAAcpG,WAAW;AAClC;AAEA,MAAMsG,kBAAkBC,OAAOC,GAAG,CAAC;AAEnC;;;;;;CAMC,GACD,SAASpC,oBAAoBqC,IAAa;IACxC,IAAIA,SAAS,QAAQ,OAAOA,SAAS,UAAU;QAC7C,OAAOA;IACT;IAEA,IAAI,AAACA,KAA+BC,QAAQ,KAAKJ,iBAAiB;QAChE,MAAMK,OAAOF;QAIb,OAAOrC,oBAAoBuC,KAAKC,KAAK,CAACD,KAAKE,QAAQ;IACrD;IAEA,IAAI5B,MAAMC,OAAO,CAACuB,OAAO;QACvB,OAAOA,KAAKK,GAAG,CAAC1C;IAClB;IAEA,MAAMlD,UAAUuF;IAChB,IAAIvF,QAAQ6F,KAAK,IAAI,cAAc7F,QAAQ6F,KAAK,EAAE;QAChD,OAAO;YACL,GAAG7F,OAAO;YACV6F,OAAO;gBACL,GAAG7F,QAAQ6F,KAAK;gBAChBC,UAAU5C,oBAAoBlD,QAAQ6F,KAAK,CAACC,QAAQ;YACtD;QACF;IACF;IAEA,OAAOP;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/og/image-response.d.ts b/e-commerce/node_modules/next/dist/server/og/image-response.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a561f8aad1d4593a0517ef02327e6d559e666e2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/og/image-response.d.ts @@ -0,0 +1,12 @@ +type OgModule = typeof import('next/dist/compiled/@vercel/og'); +/** + * The ImageResponse class allows you to generate dynamic images using JSX and CSS. + * This is useful for generating social media images such as Open Graph images, Twitter cards, and more. + * + * Read more: [Next.js Docs: `ImageResponse`](https://nextjs.org/docs/app/api-reference/functions/image-response) + */ +export declare class ImageResponse extends Response { + static displayName: string; + constructor(...args: ConstructorParameters); +} +export {}; diff --git a/e-commerce/node_modules/next/dist/server/og/image-response.js b/e-commerce/node_modules/next/dist/server/og/image-response.js new file mode 100644 index 0000000000000000000000000000000000000000..09f2e84e3767bfd35569a347571e90987f310b97 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/og/image-response.js @@ -0,0 +1,72 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ImageResponse", { + enumerable: true, + get: function() { + return ImageResponse; + } +}); +function importModule() { + return import(process.env.NEXT_RUNTIME === 'edge' ? 'next/dist/compiled/@vercel/og/index.edge.js' : 'next/dist/compiled/@vercel/og/index.node.js'); +} +// The Cache Components-specific caching path (and its React Flight and Node +// stream dependencies) lives in a separate module that is only required for +// Node.js Cache Components builds. The `NEXT_RUNTIME` guard matters because +// `__NEXT_CACHE_COMPONENTS` is derived from config, not the per-route runtime, +// so it stays `true` in edge bundles too. A Pages Router edge route that +// renders an `ImageResponse` is valid under Cache Components, and without the +// guard this node-only module would be pulled into that edge bundle and fail to +// compile. (App Router edge routes, including metadata routes, are +// independently rejected at compile time under Cache Components.) Both checks +// fold to constants at build time, so the `require` is eliminated as dead code +// for edge builds and for apps without Cache Components, which keep +// ImageResponse's original streaming behavior. +let getCachedImageResponseBody; +if (process.env.NEXT_RUNTIME !== 'edge' && process.env.__NEXT_CACHE_COMPONENTS) { + getCachedImageResponseBody = require('./cache-image-response').getCachedImageResponseBody; +} +class ImageResponse extends Response { + static #_ = this.displayName = 'ImageResponse'; + constructor(...args){ + // Under Cache Components, route the render through the cache so metadata + // image routes can be statically prerendered. Otherwise stream the rendered + // image directly from the underlying `@vercel/og` response. + const readable = getCachedImageResponseBody ? getCachedImageResponseBody(args) : new ReadableStream({ + async start (controller) { + const OGImageResponse = // So far we have to manually determine which build to use, as the + // auto resolving is not working + (await importModule()).ImageResponse; + const imageResponse = new OGImageResponse(...args); + if (!imageResponse.body) { + return controller.close(); + } + const reader = imageResponse.body.getReader(); + while(true){ + const { done, value } = await reader.read(); + if (done) { + return controller.close(); + } + controller.enqueue(value); + } + } + }); + const options = args[1] || {}; + const headers = new Headers({ + 'content-type': 'image/png', + 'cache-control': process.env.NODE_ENV === 'development' ? 'no-cache, no-store' : 'public, max-age=0, must-revalidate' + }); + if (options.headers) { + const newHeaders = new Headers(options.headers); + newHeaders.forEach((value, key)=>headers.set(key, value)); + } + super(readable, { + headers, + status: options.status, + statusText: options.statusText + }); + } +} + +//# sourceMappingURL=image-response.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/og/image-response.js.map b/e-commerce/node_modules/next/dist/server/og/image-response.js.map new file mode 100644 index 0000000000000000000000000000000000000000..330a225eacc6a8d3e0fdc08d2203bb81c55e0e89 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/og/image-response.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/og/image-response.ts"],"sourcesContent":["type OgModule = typeof import('next/dist/compiled/@vercel/og')\n\nfunction importModule(): Promise<\n typeof import('next/dist/compiled/@vercel/og')\n> {\n return import(\n process.env.NEXT_RUNTIME === 'edge'\n ? 'next/dist/compiled/@vercel/og/index.edge.js'\n : 'next/dist/compiled/@vercel/og/index.node.js'\n )\n}\n\n// The Cache Components-specific caching path (and its React Flight and Node\n// stream dependencies) lives in a separate module that is only required for\n// Node.js Cache Components builds. The `NEXT_RUNTIME` guard matters because\n// `__NEXT_CACHE_COMPONENTS` is derived from config, not the per-route runtime,\n// so it stays `true` in edge bundles too. A Pages Router edge route that\n// renders an `ImageResponse` is valid under Cache Components, and without the\n// guard this node-only module would be pulled into that edge bundle and fail to\n// compile. (App Router edge routes, including metadata routes, are\n// independently rejected at compile time under Cache Components.) Both checks\n// fold to constants at build time, so the `require` is eliminated as dead code\n// for edge builds and for apps without Cache Components, which keep\n// ImageResponse's original streaming behavior.\nlet getCachedImageResponseBody:\n | typeof import('./cache-image-response').getCachedImageResponseBody\n | undefined\nif (\n process.env.NEXT_RUNTIME !== 'edge' &&\n process.env.__NEXT_CACHE_COMPONENTS\n) {\n getCachedImageResponseBody = (\n require('./cache-image-response') as typeof import('./cache-image-response')\n ).getCachedImageResponseBody\n}\n\n/**\n * The ImageResponse class allows you to generate dynamic images using JSX and CSS.\n * This is useful for generating social media images such as Open Graph images, Twitter cards, and more.\n *\n * Read more: [Next.js Docs: `ImageResponse`](https://nextjs.org/docs/app/api-reference/functions/image-response)\n */\nexport class ImageResponse extends Response {\n public static displayName = 'ImageResponse'\n constructor(...args: ConstructorParameters) {\n // Under Cache Components, route the render through the cache so metadata\n // image routes can be statically prerendered. Otherwise stream the rendered\n // image directly from the underlying `@vercel/og` response.\n const readable = getCachedImageResponseBody\n ? getCachedImageResponseBody(args)\n : new ReadableStream({\n async start(controller) {\n const OGImageResponse: typeof import('next/dist/compiled/@vercel/og').ImageResponse =\n // So far we have to manually determine which build to use, as the\n // auto resolving is not working\n (await importModule()).ImageResponse\n const imageResponse = new OGImageResponse(...args) as Response\n\n if (!imageResponse.body) {\n return controller.close()\n }\n\n const reader = imageResponse.body.getReader()\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n return controller.close()\n }\n controller.enqueue(value)\n }\n },\n })\n\n const options = args[1] || {}\n\n const headers = new Headers({\n 'content-type': 'image/png',\n 'cache-control':\n process.env.NODE_ENV === 'development'\n ? 'no-cache, no-store'\n : 'public, max-age=0, must-revalidate',\n })\n if (options.headers) {\n const newHeaders = new Headers(options.headers)\n newHeaders.forEach((value, key) => headers.set(key, value))\n }\n super(readable, {\n headers,\n status: options.status,\n statusText: options.statusText,\n })\n }\n}\n"],"names":["ImageResponse","importModule","process","env","NEXT_RUNTIME","getCachedImageResponseBody","__NEXT_CACHE_COMPONENTS","require","Response","displayName","constructor","args","readable","ReadableStream","start","controller","OGImageResponse","imageResponse","body","close","reader","getReader","done","value","read","enqueue","options","headers","Headers","NODE_ENV","newHeaders","forEach","key","set","status","statusText"],"mappings":";;;;+BA0CaA;;;eAAAA;;;AAxCb,SAASC;IAGP,OAAO,MAAM,CACXC,QAAQC,GAAG,CAACC,YAAY,KAAK,SACzB,gDACA;AAER;AAEA,4EAA4E;AAC5E,4EAA4E;AAC5E,4EAA4E;AAC5E,+EAA+E;AAC/E,yEAAyE;AACzE,8EAA8E;AAC9E,gFAAgF;AAChF,mEAAmE;AACnE,8EAA8E;AAC9E,+EAA+E;AAC/E,oEAAoE;AACpE,+CAA+C;AAC/C,IAAIC;AAGJ,IACEH,QAAQC,GAAG,CAACC,YAAY,KAAK,UAC7BF,QAAQC,GAAG,CAACG,uBAAuB,EACnC;IACAD,6BAA6B,AAC3BE,QAAQ,0BACRF,0BAA0B;AAC9B;AAQO,MAAML,sBAAsBQ;qBACnBC,cAAc;IAC5BC,YAAY,GAAGC,IAAsD,CAAE;QACrE,yEAAyE;QACzE,4EAA4E;QAC5E,4DAA4D;QAC5D,MAAMC,WAAWP,6BACbA,2BAA2BM,QAC3B,IAAIE,eAAe;YACjB,MAAMC,OAAMC,UAAU;gBACpB,MAAMC,kBAGJ,AAFA,kEAAkE;gBAClE,gCAAgC;gBAC/B,CAAA,MAAMf,cAAa,EAAGD,aAAa;gBACtC,MAAMiB,gBAAgB,IAAID,mBAAmBL;gBAE7C,IAAI,CAACM,cAAcC,IAAI,EAAE;oBACvB,OAAOH,WAAWI,KAAK;gBACzB;gBAEA,MAAMC,SAASH,cAAcC,IAAI,CAACG,SAAS;gBAC3C,MAAO,KAAM;oBACX,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAE,GAAG,MAAMH,OAAOI,IAAI;oBACzC,IAAIF,MAAM;wBACR,OAAOP,WAAWI,KAAK;oBACzB;oBACAJ,WAAWU,OAAO,CAACF;gBACrB;YACF;QACF;QAEJ,MAAMG,UAAUf,IAAI,CAAC,EAAE,IAAI,CAAC;QAE5B,MAAMgB,UAAU,IAAIC,QAAQ;YAC1B,gBAAgB;YAChB,iBACE1B,QAAQC,GAAG,CAAC0B,QAAQ,KAAK,gBACrB,uBACA;QACR;QACA,IAAIH,QAAQC,OAAO,EAAE;YACnB,MAAMG,aAAa,IAAIF,QAAQF,QAAQC,OAAO;YAC9CG,WAAWC,OAAO,CAAC,CAACR,OAAOS,MAAQL,QAAQM,GAAG,CAACD,KAAKT;QACtD;QACA,KAAK,CAACX,UAAU;YACde;YACAO,QAAQR,QAAQQ,MAAM;YACtBC,YAAYT,QAAQS,UAAU;QAChC;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/patch-error-inspect.d.ts b/e-commerce/node_modules/next/dist/server/patch-error-inspect.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f1229394414d5cacc7cc33ea7d53f8d8a094bbd5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/patch-error-inspect.d.ts @@ -0,0 +1,9 @@ +import { type ModernSourceMapPayload } from './lib/source-maps'; +import type { IgnorableStackFrame } from '../next-devtools/server/shared'; +type FindSourceMapPayload = (sourceURL: string) => ModernSourceMapPayload | undefined; +export declare function setBundlerFindSourceMapImplementation(findSourceMapImplementation: FindSourceMapPayload): void; +type CodeFrameRenderer = (frame: IgnorableStackFrame, source: string | null, colors: boolean) => string | null; +export declare function setCodeFrameRenderer(renderer: CodeFrameRenderer): void; +export declare function patchErrorInspectNodeJS(errorConstructor: ErrorConstructor): void; +export declare function patchErrorInspectEdgeLite(errorConstructor: ErrorConstructor): void; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/patch-error-inspect.js b/e-commerce/node_modules/next/dist/server/patch-error-inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..9ab08f77999256651be54273e1dbdb82e88c59c7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/patch-error-inspect.js @@ -0,0 +1,515 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + patchErrorInspectEdgeLite: null, + patchErrorInspectNodeJS: null, + setBundlerFindSourceMapImplementation: null, + setCodeFrameRenderer: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + patchErrorInspectEdgeLite: function() { + return patchErrorInspectEdgeLite; + }, + patchErrorInspectNodeJS: function() { + return patchErrorInspectNodeJS; + }, + setBundlerFindSourceMapImplementation: function() { + return setBundlerFindSourceMapImplementation; + }, + setCodeFrameRenderer: function() { + return setCodeFrameRenderer; + } +}); +const _path = /*#__PURE__*/ _interop_require_wildcard(require("path")); +const _url = /*#__PURE__*/ _interop_require_wildcard(require("url")); +const _sourcemap = require("next/dist/compiled/source-map"); +const _sourcemaps = require("./lib/source-maps"); +const _parsestack = require("./lib/parse-stack"); +const _workunitasyncstorageexternal = require("./app-render/work-unit-async-storage.external"); +const _picocolors = require("../lib/picocolors"); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +// Find a source map using the bundler's API. +// This is only a fallback for when Node.js fails to due to bugs e.g. https://github.com/nodejs/node/issues/52102 +// TODO: Remove once all supported Node.js versions are fixed. +// TODO(veil): Set from Webpack as well +// +// 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) { + ; + globalThis[BUNDLER_FIND_SOURCE_MAP] = findSourceMapImplementation; +} +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) { + ; + globalThis[CODE_FRAME_RENDERER] = renderer; +} +function getOriginalCodeFrame(frame, source, colors = _picocolors.stdoutIsTerminal) { + const codeFrameRenderer = globalThis[CODE_FRAME_RENDERER]; + if (!codeFrameRenderer) { + // No renderer available - gracefully degrade + return null; + } + return codeFrameRenderer(frame, source, colors); +} +// 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) { + let sourceLocation = line1 !== null ? `:${line1}` : ''; + if (column1 !== null && sourceLocation !== '') { + sourceLocation += `:${column1}`; + } + let fileLocation; + if (sourceURL !== null && sourceURL.startsWith('file://') && URL.canParse(sourceURL)) { + // If not relative to CWD, the path is ambiguous to IDEs and clicking will prompt to select the file first. + // In a multi-app repo, this leads to potentially larger file names but will make clicking snappy. + // There's no tradeoff for the cases where `dir` in `next dev [dir]` is omitted + // since relative to cwd is both the shortest and snappiest. + fileLocation = _path.relative(process.cwd(), _url.fileURLToPath(sourceURL)); + } else if (sourceURL !== null && sourceURL.startsWith('/')) { + fileLocation = _path.relative(process.cwd(), sourceURL); + } else { + fileLocation = sourceURL; + } + return methodName ? ` at ${methodName} (${fileLocation}${sourceLocation})` : ` at ${fileLocation}${sourceLocation}`; +} +function computeErrorName(error) { + // TODO: Node.js seems to use a different algorithm + // class ReadonlyRequestCookiesError extends Error {}` would read `ReadonlyRequestCookiesError: [...]` + // in the stack i.e. seems like under certain conditions it favors the constructor name. + return error.name || 'Error'; +} +function prepareUnsourcemappedStackTrace(error, structuredStackTrace) { + const name = computeErrorName(error); + const message = error.message || ''; + let stack = name + ': ' + message; + for(let i = 0; i < structuredStackTrace.length; i++){ + stack += '\n at ' + structuredStackTrace[i].toString(); + } + return stack; +} +function shouldIgnoreListGeneratedFrame(file) { + return file.startsWith('node:') || file.includes('node_modules'); +} +function shouldIgnoreListOriginalFrame(file) { + return file.includes('node_modules'); +} +function createUnsourcemappedFrame(frame) { + return { + stack: { + file: frame.file, + line1: frame.line1, + column1: frame.column1, + methodName: frame.methodName, + arguments: frame.arguments, + ignored: shouldIgnoreListGeneratedFrame(frame.file) + }, + code: null + }; +} +function ignoreListAnonymousStackFramesIfSandwiched(sourceMappedFrames) { + return (0, _sourcemaps.ignoreListAnonymousStackFramesIfSandwiched)(sourceMappedFrames, (frame)=>frame.stack.file === '', (frame)=>frame.stack.ignored, (frame)=>frame.stack.methodName, (frame)=>{ + frame.stack.ignored = true; + }); +} +/** + * @param frame + * @param sourceMapCache + * @returns The original frame if not sourcemapped. + */ function getSourcemappedFrameIfPossible(frame, sourceMapCache, inspectOptions) { + var _frame_methodName_replace, _frame_methodName; + const sourceMapCacheEntry = sourceMapCache.get(frame.file); + let sourceMapConsumer; + let sourceMapPayload; + if (sourceMapCacheEntry === undefined) { + // Fake frame scripts (`about://React/Server/file:///path/to/chunk.js?42`) + // have their positions padded to match the underlying chunk, so they + // resolve via the chunk's source map. + let sourceURL = (0, _sourcemaps.devirtualizeReactServerURL)(frame.file); + // e.g. "/Users/foo/APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js" + // or "C:\Users\foo\APP\.next\server\chunks\ssr\[root-of-the-server]__2934a0._.js" + // will be keyed by Node.js as "file:///APP/.next/server/chunks/ssr/[root-of-the-server]__2934a0._.js". + // This is likely caused by `callsite.toString()` in `Error.prepareStackTrace converting file URLs to paths. + // + // But frame.file might also be "webpack-internal:///(rsc)/./app/bad-sourcemap/page.js" or + // "" or "node:internal/process/task_queues" here + if (_path.isAbsolute(sourceURL)) { + sourceURL = _url.pathToFileURL(sourceURL).toString(); + } + let maybeSourceMapPayload; + try { + 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) { + // We should not log an actual error instance here because that will re-enter + // this codepath during error inspection and could lead to infinite recursion. + console.error(`${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`); + // If loading fails once, it'll fail every time. + // So set the cache to avoid duplicate errors. + sourceMapCache.set(frame.file, null); + // Don't even fall back to the bundler because it might be not as strict + // with regards to parsing and then we fail later once we consume the + // source map payload. + // This essentially avoids a redundant error where we fail here and then + // later on consumption because the bundler just handed back an invalid + // source map. + return createUnsourcemappedFrame(frame); + } + if (maybeSourceMapPayload === undefined) { + maybeSourceMapPayload = bundlerFindSourceMapPayload(sourceURL); + } + if (maybeSourceMapPayload === undefined) { + return createUnsourcemappedFrame(frame); + } + sourceMapPayload = maybeSourceMapPayload; + try { + // Pass the source map URL as the second parameter so that the consumer + // can resolve relative paths in the source map's `sources` array. This is + // a guess! Turbopack places .map files as siblings to the chunks so this + // is sufficient to compute relative paths but is actually wrong (the + // chunk and sourcemap have different content hashes). We are using the + // node API to read the sourcemap and it doesn't give us access to the + // URI. `sourceURL` is already devirtualized so that relative `sources` + // resolve against the real chunk URL, not React's virtual one. + const sourceMapURL = sourceURL + '.map'; + sourceMapConsumer = getOrCreateSourceMapConsumer(sourceMapPayload, sourceMapURL); + } catch (cause) { + // We should not log an actual error instance here because that will re-enter + // this codepath during error inspection and could lead to infinite recursion. + console.error(`${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`); + // If creating the consumer fails once, it'll fail every time. + // So set the cache to avoid duplicate errors. + sourceMapCache.set(frame.file, null); + return createUnsourcemappedFrame(frame); + } + sourceMapCache.set(frame.file, { + map: sourceMapConsumer, + payload: sourceMapPayload + }); + } else if (sourceMapCacheEntry === null) { + // We failed earlier getting the payload or consumer. + // Just return an unsourcemapped frame. + // Errors will already be logged. + return createUnsourcemappedFrame(frame); + } else { + sourceMapConsumer = sourceMapCacheEntry.map; + sourceMapPayload = sourceMapCacheEntry.payload; + } + const sourcePosition = sourceMapConsumer.originalPositionFor({ + column: (frame.column1 ?? 1) - 1, + line: frame.line1 ?? 1 + }); + const applicableSourceMap = (0, _sourcemaps.findApplicableSourceMapPayload)((frame.line1 ?? 1) - 1, (frame.column1 ?? 1) - 1, sourceMapPayload); + let ignored = applicableSourceMap !== undefined && (0, _sourcemaps.sourceMapIgnoreListsEverything)(applicableSourceMap); + if (sourcePosition.source === null) { + return { + stack: { + arguments: frame.arguments, + file: frame.file, + line1: frame.line1, + column1: frame.column1, + methodName: frame.methodName, + ignored: ignored || shouldIgnoreListGeneratedFrame(frame.file) + }, + code: null + }; + } + // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not. + if (applicableSourceMap === undefined) { + console.error('No applicable source map found in sections for frame', frame); + } else if (!ignored && shouldIgnoreListOriginalFrame(sourcePosition.source)) { + // Externals may be libraries that don't ship ignoreLists. + // This is really taking control away from libraries. + // They should still ship `ignoreList` so that attached debuggers ignore-list their frames. + // TODO: Maybe only ignore library sourcemaps if `ignoreList` is absent? + // Though keep in mind that Turbopack omits empty `ignoreList`. + // So if we establish this convention, we should communicate it to the ecosystem. + ignored = true; + } else if (!ignored) { + var _applicableSourceMap_ignoreList; + // TODO: O(n^2). Consider moving `ignoreList` into a Set + const sourceIndex = applicableSourceMap.sources.indexOf(sourcePosition.source); + ignored = ((_applicableSourceMap_ignoreList = applicableSourceMap.ignoreList) == null ? void 0 : _applicableSourceMap_ignoreList.includes(sourceIndex)) ?? false; + } + const originalFrame = { + // We ignore the sourcemapped name since it won't be the correct name. + // The callsite will point to the column of the variable name instead of the + // name of the enclosing function. + // TODO(NDX-531): Spy on prepareStackTrace to get the enclosing line number for method name mapping. + methodName: (_frame_methodName = frame.methodName) == null ? void 0 : (_frame_methodName_replace = _frame_methodName.replace('__WEBPACK_DEFAULT_EXPORT__', 'default')) == null ? void 0 : _frame_methodName_replace.replace('__webpack_exports__.', ''), + file: sourcePosition.source, + line1: sourcePosition.line, + column1: sourcePosition.column + 1, + // TODO: c&p from async createOriginalStackFrame but why not frame.arguments? + arguments: [], + ignored + }; + /** undefined = not yet computed */ let codeFrame; + return { + stack: originalFrame, + get code () { + if (codeFrame === undefined) { + const sourceContent = sourceMapConsumer.sourceContentFor(sourcePosition.source, /* returnNullOnMissing */ true) ?? null; + codeFrame = getOriginalCodeFrame(originalFrame, sourceContent, inspectOptions.colors); + } + return codeFrame; + } + }; +} +function parseAndSourceMap(error, inspectOptions) { + const showIgnoreListed = process.env.__NEXT_SHOW_IGNORE_LISTED === 'true'; + // We overwrote Error.prepareStackTrace earlier so error.stack is not sourcemapped. + let unparsedStack = String(error.stack); + // We could just read it from `error.stack`. + // This works around cases where a 3rd party `Error.prepareStackTrace` implementation + // doesn't implement the name computation correctly. + const errorName = computeErrorName(error); + let idx = unparsedStack.indexOf('react_stack_bottom_frame'); + if (idx !== -1) { + idx = unparsedStack.lastIndexOf('\n', idx); + } else { + idx = unparsedStack.indexOf('react-stack-bottom-frame'); + if (idx !== -1) { + idx = unparsedStack.lastIndexOf('\n', idx); + } + } + if (idx !== -1 && !showIgnoreListed) { + // Cut off everything after the bottom frame since it'll be React internals. + unparsedStack = unparsedStack.slice(0, idx); + } + const unsourcemappedStack = (0, _parsestack.parseStack)(unparsedStack); + const sourceMapCache = new Map(); + const sourceMappedFrames = []; + let sourceFrame = null; + for (const frame of unsourcemappedStack){ + if (frame.file === null) { + sourceMappedFrames.push({ + code: null, + stack: { + file: frame.file, + line1: frame.line1, + column1: frame.column1, + methodName: frame.methodName, + arguments: frame.arguments, + ignored: false + } + }); + } else { + const sourcemappedFrame = getSourcemappedFrameIfPossible(// We narrowed this earlier by bailing if `frame.file` is null. + frame, sourceMapCache, inspectOptions); + sourceMappedFrames.push(sourcemappedFrame); + // We can determine the sourceframe here. + // anonymous frames won't have a sourceframe so we don't need to scan + // all stacks again to check if they are sandwiched between ignored frames. + if (sourceFrame === null && // TODO: Is this the right choice? + !sourcemappedFrame.stack.ignored && sourcemappedFrame.code !== null) { + sourceFrame = sourcemappedFrame.code; + } + } + } + ignoreListAnonymousStackFramesIfSandwiched(sourceMappedFrames); + let sourceMappedStack = ''; + for(let i = 0; i < sourceMappedFrames.length; i++){ + const frame = sourceMappedFrames[i]; + if (!frame.stack.ignored) { + sourceMappedStack += '\n' + frameToString(frame.stack.methodName, frame.stack.file, frame.stack.line1, frame.stack.column1); + } else if (showIgnoreListed) { + sourceMappedStack += '\n' + (0, _picocolors.dim)(frameToString(frame.stack.methodName, frame.stack.file, frame.stack.line1, frame.stack.column1)); + } + } + if (sourceMappedStack === '' && sourceMappedFrames.length > 0) { + // The `at` marker is important so that Node.js doesn't add square brackets + // around the stringified error i.e. this results in + // Error: message + // at + // instead of + // [Error: message + // at ] + sourceMappedStack = '\n at ' + (0, _picocolors.italic)('ignore-listed frames'); + } + return errorName + ': ' + error.message + sourceMappedStack + (sourceFrame !== null ? '\n' + sourceFrame : ''); +} +function sourceMapError(error, inspectOptions) { + // Setting an undefined `cause` would print `[cause]: undefined` + const options = error.cause !== undefined ? { + cause: error.cause + } : undefined; + // Create a new Error object with the source mapping applied and then use native + // Node.js formatting on the result. + const newError = error instanceof AggregateError ? new AggregateError(error.errors, error.message, options) : new Error(error.message, options); + // TODO: Ensure `class MyError extends Error {}` prints `MyError` as the name + newError.stack = parseAndSourceMap(error, inspectOptions); + for(const key in error){ + if (!Object.prototype.hasOwnProperty.call(newError, key)) { + // @ts-expect-error -- We're copying all enumerable properties. + // So they definitely exist on `this` and obviously have no type on `newError` (yet) + newError[key] = error[key]; + } + } + return newError; +} +/** + * Node.js passes the remaining depth in `depth`. An `AggregateError` keeps its + * errors in an array. Node.js spends one level of the depth on that array, and + * one more level on each error in the array. A `cause` costs one level only. + * This function adds the missing level back, so an `AggregateError` prints its + * errors at the same nesting as a `cause`. Without it, a `fetch` failure logs + * `[errors]: [ [Error], [Error] ]` and hides the address and the port of every + * refused connection. + * + * A `depth` of `null` means unlimited, so this function returns it unchanged. + */ function getInspectDepth(error, depth) { + if (depth === null || !(error instanceof AggregateError)) { + return depth; + } + return depth + 1; +} +function patchErrorInspectNodeJS(errorConstructor) { + const inspectSymbol = Symbol.for('nodejs.util.inspect.custom'); + errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace; + // @ts-expect-error -- TODO upstream types + errorConstructor.prototype[inspectSymbol] = function(depth, inspectOptions, inspect) { + // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`. + return _workunitasyncstorageexternal.workUnitAsyncStorage.exit(()=>{ + const newError = sourceMapError(this, inspectOptions); + const originalCustomInspect = newError[inspectSymbol]; + // Prevent infinite recursion. + // { customInspect: false } would result in `error.cause` not using our inspect. + Object.defineProperty(newError, inspectSymbol, { + value: undefined, + enumerable: false, + writable: true + }); + try { + return inspect(newError, { + ...inspectOptions, + depth: getInspectDepth(newError, depth) + }); + } finally{ + ; + newError[inspectSymbol] = originalCustomInspect; + } + }); + }; +} +function patchErrorInspectEdgeLite(errorConstructor) { + const inspectSymbol = Symbol.for('edge-runtime.inspect.custom'); + errorConstructor.prepareStackTrace = prepareUnsourcemappedStackTrace; + // @ts-expect-error -- TODO upstream types + errorConstructor.prototype[inspectSymbol] = function({ format }) { + // avoid false-positive dynamic i/o warnings e.g. due to usage of `Math.random` in `source-map`. + return _workunitasyncstorageexternal.workUnitAsyncStorage.exit(()=>{ + const newError = sourceMapError(this, {}); + const originalCustomInspect = newError[inspectSymbol]; + // Prevent infinite recursion. + Object.defineProperty(newError, inspectSymbol, { + value: undefined, + enumerable: false, + writable: true + }); + try { + return format(newError); + } finally{ + ; + newError[inspectSymbol] = originalCustomInspect; + } + }); + }; +} + +//# sourceMappingURL=patch-error-inspect.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/patch-error-inspect.js.map b/e-commerce/node_modules/next/dist/server/patch-error-inspect.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cbb4dd519be39e4b4d36caddaabb41d8b41a8974 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/patch-error-inspect.js.map @@ -0,0 +1 @@ +{"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, stdoutIsTerminal } 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 = stdoutIsTerminal\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\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\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 === '',\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 // \"\" 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 \n // instead of\n // [Error: message\n // at ]\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\n/**\n * Node.js passes the remaining depth in `depth`. An `AggregateError` keeps its\n * errors in an array. Node.js spends one level of the depth on that array, and\n * one more level on each error in the array. A `cause` costs one level only.\n * This function adds the missing level back, so an `AggregateError` prints its\n * errors at the same nesting as a `cause`. Without it, a `fetch` failure logs\n * `[errors]: [ [Error], [Error] ]` and hides the address and the port of every\n * refused connection.\n *\n * A `depth` of `null` means unlimited, so this function returns it unchanged.\n */\nfunction getInspectDepth(error: Error, depth: number | null): number | null {\n if (depth === null || !(error instanceof AggregateError)) {\n return depth\n }\n\n return depth + 1\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 | null,\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: getInspectDepth(newError, 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","stdoutIsTerminal","codeFrameRenderer","sourceMapConsumers","WeakMap","getOrCreateSourceMapConsumer","payload","sourceMapURL","consumersByURL","get","consumer","undefined","SyncSourceMapConsumer","Map","set","frameToString","methodName","line1","column1","sourceLocation","fileLocation","startsWith","URL","canParse","path","relative","process","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","getInspectDepth","depth","errorConstructor","inspectSymbol","prepareStackTrace","inspect","workUnitAsyncStorage","exit","originalCustomInspect","defineProperty","value","enumerable","writable","format"],"mappings":";;;;;;;;;;;;;;;;;IA6nBgBA,yBAAyB;eAAzBA;;IArCAC,uBAAuB;eAAvBA;;IApjBAC,qCAAqC;eAArCA;;IAkCAC,oBAAoB;eAApBA;;;8DAtEM;6DACD;2BAEsC;4BAQpD;4BACqC;8CAEP;4BACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAK9C,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,4BAAgB;IAElC,MAAMC,oBAAoB,AAACV,UAA0C,CACnEG,oBACD;IACD,IAAI,CAACO,mBAAmB;QACtB,6CAA6C;QAC7C,OAAO;IACT;IACA,OAAOA,kBAAkBJ,OAAOC,QAAQC;AAC1C;AAOA,0EAA0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AAEO,SAAStI,0BACdgI,gBAAkC;IAElC,MAAMC,gBAAgB5H,OAAOC,GAAG,CAAC;IAEjC0H,iBAAiBE,iBAAiB,GAAGjF;IAErC,0CAA0C;IAC1C+E,iBAAiBL,SAAS,CAACM,cAAc,GAAG,SAAU,EACpDU,MAAM,EAGP;QACC,gGAAgG;QAChG,OAAOP,kDAAoB,CAACC,IAAI,CAAC;YAC/B,MAAMhB,WAAWF,eAAe,IAAI,EAAE,CAAC;YAEvC,MAAMmB,wBAAwB,AAACjB,QAAgB,CAACY,cAAc;YAC9D,8BAA8B;YAC9BP,OAAOa,cAAc,CAAClB,UAAUY,eAAe;gBAC7CO,OAAO7G;gBACP8G,YAAY;gBACZC,UAAU;YACZ;YACA,IAAI;gBACF,OAAOC,OAAOtB;YAChB,SAAU;;gBACNA,QAAgB,CAACY,cAAc,GAAGK;YACtC;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/pipe-readable.d.ts b/e-commerce/node_modules/next/dist/server/pipe-readable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..615faa59bedc21e53c77f89857c6ae4086cabcb9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/pipe-readable.d.ts @@ -0,0 +1,8 @@ +import type { ServerResponse } from 'node:http'; +import type { Readable } from 'node:stream'; +import type { ClientComponentLoadTracker } from './client-component-renderer-logger'; +export declare function isAbortError(e: any): e is Error & { + name: 'AbortError'; +}; +export declare function pipeToNodeResponse(readable: ReadableStream, res: ServerResponse, waitUntilForEnd?: Promise, clientComponentLoadTracker?: ClientComponentLoadTracker): Promise; +export declare function pipeNodeReadableToNodeResponse(readable: Readable, res: ServerResponse, waitUntilForEnd?: Promise, clientComponentLoadTracker?: ClientComponentLoadTracker): Promise; diff --git a/e-commerce/node_modules/next/dist/server/pipe-readable.js b/e-commerce/node_modules/next/dist/server/pipe-readable.js new file mode 100644 index 0000000000000000000000000000000000000000..a622f5e22d857d5edaf571e2577ba2caf58ed8e4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/pipe-readable.js @@ -0,0 +1,224 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + isAbortError: null, + pipeNodeReadableToNodeResponse: null, + pipeToNodeResponse: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + isAbortError: function() { + return isAbortError; + }, + pipeNodeReadableToNodeResponse: function() { + return pipeNodeReadableToNodeResponse; + }, + pipeToNodeResponse: function() { + return pipeToNodeResponse; + } +}); +const _nextrequest = require("./web/spec-extension/adapters/next-request"); +const _promisewithresolvers = require("../shared/lib/promise-with-resolvers"); +const _tracer = require("./lib/trace/tracer"); +const _constants = require("./lib/trace/constants"); +function isAbortError(e) { + return (e == null ? void 0 : e.name) === 'AbortError' || (e == null ? void 0 : e.name) === _nextrequest.ResponseAbortedName; +} +const HAS_CLIENT_COMPONENT_METRICS_ENABLED = 'performance' in globalThis && process.env.NEXT_OTEL_PERFORMANCE_PREFIX; +function createWriterFromResponse(res, waitUntilForEnd, clientComponentLoadTracker) { + let started = false; + // Create a promise that will resolve once the response has drained. See + // https://nodejs.org/api/stream.html#stream_event_drain + let drained = (0, _promisewithresolvers.createPromiseWithResolvers)(); + function onDrain() { + drained.resolve(); + } + res.on('drain', onDrain); + // If the finish event fires, it means we shouldn't block and wait for the + // drain event. + res.once('close', ()=>{ + res.off('drain', onDrain); + drained.resolve(); + }); + // Create a promise that will resolve once the response has finished. See + // https://nodejs.org/api/http.html#event-finish_1 + const finished = (0, _promisewithresolvers.createPromiseWithResolvers)(); + res.once('finish', ()=>{ + finished.resolve(); + }); + // Create a writable stream that will write to the response. + return new WritableStream({ + write: async (chunk)=>{ + // You'd think we'd want to use `start` instead of placing this in `write` + // but this ensures that we don't actually flush the headers until we've + // started writing chunks. + if (!started) { + started = true; + if (HAS_CLIENT_COMPONENT_METRICS_ENABLED) { + const metrics = clientComponentLoadTracker == null ? void 0 : clientComponentLoadTracker.snapshot(); + if (metrics) { + performance.measure(`${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-client-component-loading`, { + start: metrics.clientComponentLoadStart, + end: metrics.clientComponentLoadStart + metrics.clientComponentLoadTimes + }); + } + } + res.flushHeaders(); + (0, _tracer.getTracer)().trace(_constants.NextNodeServerSpan.startResponse, { + spanName: 'start response' + }, ()=>undefined); + } + try { + const ok = res.write(chunk); + // Added by the `compression` middleware, this is a function that will + // flush the partially-compressed response to the client. + if ('flush' in res && typeof res.flush === 'function') { + res.flush(); + } + // If the write returns false, it means there's some backpressure, so + // wait until it's streamed before continuing. + if (!ok) { + await drained.promise; + // Reset the drained promise so that we can wait for the next drain event. + drained = (0, _promisewithresolvers.createPromiseWithResolvers)(); + } + } catch (err) { + res.end(); + throw new Error('failed to write chunk to response', { + cause: err + }); + } + }, + abort: (err)=>{ + if (res.writableFinished) return; + res.destroy(err); + }, + close: async ()=>{ + // if a waitUntil promise was passed, wait for it to resolve before + // ending the response. + if (waitUntilForEnd) { + await waitUntilForEnd; + } + if (res.writableFinished) return; + res.end(); + return finished.promise; + } + }); +} +async function pipeToNodeResponse(readable, res, waitUntilForEnd, clientComponentLoadTracker) { + try { + // If the response has already errored, then just return now. + const { errored, destroyed } = res; + if (errored || destroyed) return; + // Create a new AbortController so that we can abort the readable if the + // client disconnects. + const controller = (0, _nextrequest.createAbortController)(res); + const writer = createWriterFromResponse(res, waitUntilForEnd, clientComponentLoadTracker); + await readable.pipeTo(writer, { + signal: controller.signal + }); + } catch (err) { + // If this isn't related to an abort error, re-throw it. + if (isAbortError(err)) return; + throw new Error('failed to pipe response', { + cause: err + }); + } +} +async function pipeNodeReadableToNodeResponse(readable, res, waitUntilForEnd, clientComponentLoadTracker) { + try { + const { errored, destroyed } = res; + if (errored || destroyed) return; + let started = false; + const finished = (0, _promisewithresolvers.createPromiseWithResolvers)(); + // One `drain` listener for the whole response, as in + // `createWriterFromResponse` above. It must not be `res.once('drain')` per + // backpressured write: the `compression` middleware forwards `res.on` to + // its zlib stream but leaves `removeListener` pointing at the response, so + // a `once` listener is never removed from the stream it was added to. Each + // backpressured write would leak one, and past ten Node reports the stream + // as a probable leak via `MaxListenersExceededWarning`. + // + // TODO: the upstream fix for that asymmetry is + // https://github.com/expressjs/compression/pull/153, which intercepts + // `removeListener` so it reaches the zlib stream. It has been open since + // 2019 and is not in upstream 1.8.1; we vendor 1.7.4. If it ever lands and + // we upgrade, `res.off('drain', onDrain)` below would start working with + // compression active and the caveat on the `close` handler could go away. + let paused = false; + const onDrain = ()=>{ + // The listener outlives the readable: `off` below cannot reach the zlib + // stream either, so a late drain can arrive after teardown. + if (!paused || readable.destroyed) return; + paused = false; + readable.resume(); + }; + res.on('drain', onDrain); + res.once('close', ()=>{ + // Only removes the listener when compression is inactive, which is the + // case where it was added to the response itself. Otherwise it lives on + // the zlib stream, which is released with the response. + res.off('drain', onDrain); + readable.destroy(); + finished.resolve(); + }); + readable.on('data', (chunk)=>{ + if (!started) { + started = true; + if ('performance' in globalThis && process.env.NEXT_OTEL_PERFORMANCE_PREFIX) { + const metrics = clientComponentLoadTracker == null ? void 0 : clientComponentLoadTracker.snapshot(); + if (metrics) { + performance.measure(`${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-client-component-loading`, { + start: metrics.clientComponentLoadStart, + end: metrics.clientComponentLoadStart + metrics.clientComponentLoadTimes + }); + } + } + res.flushHeaders(); + (0, _tracer.getTracer)().trace(_constants.NextNodeServerSpan.startResponse, { + spanName: 'start response' + }, ()=>undefined); + } + const ok = res.write(chunk); + if ('flush' in res && typeof res.flush === 'function') { + res.flush(); + } + if (!ok) { + paused = true; + readable.pause(); + } + }); + readable.on('end', async ()=>{ + if (waitUntilForEnd) { + await waitUntilForEnd; + } + if (!res.writableFinished) { + res.end(); + } + finished.resolve(); + }); + readable.on('error', (err)=>{ + if (isAbortError(err)) { + finished.resolve(); + return; + } + res.destroy(err); + finished.resolve(); + }); + await finished.promise; + } catch (err) { + if (isAbortError(err)) return; + throw new Error('failed to pipe response', { + cause: err + }); + } +} + +//# sourceMappingURL=pipe-readable.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/pipe-readable.js.map b/e-commerce/node_modules/next/dist/server/pipe-readable.js.map new file mode 100644 index 0000000000000000000000000000000000000000..586061857070e618878831296eba7af2bee2b54d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/pipe-readable.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/pipe-readable.ts"],"sourcesContent":["import type { ServerResponse } from 'node:http'\nimport type { Readable } from 'node:stream'\n\nimport {\n ResponseAbortedName,\n createAbortController,\n} from './web/spec-extension/adapters/next-request'\nimport { createPromiseWithResolvers } from '../shared/lib/promise-with-resolvers'\nimport { getTracer } from './lib/trace/tracer'\nimport { NextNodeServerSpan } from './lib/trace/constants'\nimport type { ClientComponentLoadTracker } from './client-component-renderer-logger'\n\nexport function isAbortError(e: any): e is Error & { name: 'AbortError' } {\n return e?.name === 'AbortError' || e?.name === ResponseAbortedName\n}\n\nconst HAS_CLIENT_COMPONENT_METRICS_ENABLED =\n 'performance' in globalThis && process.env.NEXT_OTEL_PERFORMANCE_PREFIX\n\nfunction createWriterFromResponse(\n res: ServerResponse,\n waitUntilForEnd?: Promise,\n clientComponentLoadTracker?: ClientComponentLoadTracker\n): WritableStream {\n let started = false\n\n // Create a promise that will resolve once the response has drained. See\n // https://nodejs.org/api/stream.html#stream_event_drain\n let drained = createPromiseWithResolvers()\n function onDrain() {\n drained.resolve()\n }\n res.on('drain', onDrain)\n\n // If the finish event fires, it means we shouldn't block and wait for the\n // drain event.\n res.once('close', () => {\n res.off('drain', onDrain)\n drained.resolve()\n })\n\n // Create a promise that will resolve once the response has finished. See\n // https://nodejs.org/api/http.html#event-finish_1\n const finished = createPromiseWithResolvers()\n res.once('finish', () => {\n finished.resolve()\n })\n\n // Create a writable stream that will write to the response.\n return new WritableStream({\n write: async (chunk) => {\n // You'd think we'd want to use `start` instead of placing this in `write`\n // but this ensures that we don't actually flush the headers until we've\n // started writing chunks.\n if (!started) {\n started = true\n\n if (HAS_CLIENT_COMPONENT_METRICS_ENABLED) {\n const metrics = clientComponentLoadTracker?.snapshot()\n if (metrics) {\n performance.measure(\n `${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-client-component-loading`,\n {\n start: metrics.clientComponentLoadStart,\n end:\n metrics.clientComponentLoadStart +\n metrics.clientComponentLoadTimes,\n }\n )\n }\n }\n\n res.flushHeaders()\n getTracer().trace(\n NextNodeServerSpan.startResponse,\n {\n spanName: 'start response',\n },\n () => undefined\n )\n }\n\n try {\n const ok = res.write(chunk)\n\n // Added by the `compression` middleware, this is a function that will\n // flush the partially-compressed response to the client.\n if ('flush' in res && typeof res.flush === 'function') {\n res.flush()\n }\n\n // If the write returns false, it means there's some backpressure, so\n // wait until it's streamed before continuing.\n if (!ok) {\n await drained.promise\n\n // Reset the drained promise so that we can wait for the next drain event.\n drained = createPromiseWithResolvers()\n }\n } catch (err) {\n res.end()\n throw new Error('failed to write chunk to response', { cause: err })\n }\n },\n abort: (err) => {\n if (res.writableFinished) return\n\n res.destroy(err)\n },\n close: async () => {\n // if a waitUntil promise was passed, wait for it to resolve before\n // ending the response.\n if (waitUntilForEnd) {\n await waitUntilForEnd\n }\n\n if (res.writableFinished) return\n\n res.end()\n return finished.promise\n },\n })\n}\n\nexport async function pipeToNodeResponse(\n readable: ReadableStream,\n res: ServerResponse,\n waitUntilForEnd?: Promise,\n clientComponentLoadTracker?: ClientComponentLoadTracker\n) {\n try {\n // If the response has already errored, then just return now.\n const { errored, destroyed } = res\n if (errored || destroyed) return\n\n // Create a new AbortController so that we can abort the readable if the\n // client disconnects.\n const controller = createAbortController(res)\n\n const writer = createWriterFromResponse(\n res,\n waitUntilForEnd,\n clientComponentLoadTracker\n )\n\n await readable.pipeTo(writer, { signal: controller.signal })\n } catch (err: any) {\n // If this isn't related to an abort error, re-throw it.\n if (isAbortError(err)) return\n\n throw new Error('failed to pipe response', { cause: err })\n }\n}\n\nexport async function pipeNodeReadableToNodeResponse(\n readable: Readable,\n res: ServerResponse,\n waitUntilForEnd?: Promise,\n clientComponentLoadTracker?: ClientComponentLoadTracker\n) {\n try {\n const { errored, destroyed } = res\n if (errored || destroyed) return\n\n let started = false\n\n const finished = createPromiseWithResolvers()\n\n // One `drain` listener for the whole response, as in\n // `createWriterFromResponse` above. It must not be `res.once('drain')` per\n // backpressured write: the `compression` middleware forwards `res.on` to\n // its zlib stream but leaves `removeListener` pointing at the response, so\n // a `once` listener is never removed from the stream it was added to. Each\n // backpressured write would leak one, and past ten Node reports the stream\n // as a probable leak via `MaxListenersExceededWarning`.\n //\n // TODO: the upstream fix for that asymmetry is\n // https://github.com/expressjs/compression/pull/153, which intercepts\n // `removeListener` so it reaches the zlib stream. It has been open since\n // 2019 and is not in upstream 1.8.1; we vendor 1.7.4. If it ever lands and\n // we upgrade, `res.off('drain', onDrain)` below would start working with\n // compression active and the caveat on the `close` handler could go away.\n let paused = false\n const onDrain = () => {\n // The listener outlives the readable: `off` below cannot reach the zlib\n // stream either, so a late drain can arrive after teardown.\n if (!paused || readable.destroyed) return\n\n paused = false\n readable.resume()\n }\n res.on('drain', onDrain)\n\n res.once('close', () => {\n // Only removes the listener when compression is inactive, which is the\n // case where it was added to the response itself. Otherwise it lives on\n // the zlib stream, which is released with the response.\n res.off('drain', onDrain)\n readable.destroy()\n finished.resolve()\n })\n\n readable.on('data', (chunk: Buffer) => {\n if (!started) {\n started = true\n\n if (\n 'performance' in globalThis &&\n process.env.NEXT_OTEL_PERFORMANCE_PREFIX\n ) {\n const metrics = clientComponentLoadTracker?.snapshot()\n if (metrics) {\n performance.measure(\n `${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-client-component-loading`,\n {\n start: metrics.clientComponentLoadStart,\n end:\n metrics.clientComponentLoadStart +\n metrics.clientComponentLoadTimes,\n }\n )\n }\n }\n\n res.flushHeaders()\n getTracer().trace(\n NextNodeServerSpan.startResponse,\n {\n spanName: 'start response',\n },\n () => undefined\n )\n }\n\n const ok = res.write(chunk)\n\n if ('flush' in res && typeof res.flush === 'function') {\n res.flush()\n }\n\n if (!ok) {\n paused = true\n readable.pause()\n }\n })\n\n readable.on('end', async () => {\n if (waitUntilForEnd) {\n await waitUntilForEnd\n }\n\n if (!res.writableFinished) {\n res.end()\n }\n\n finished.resolve()\n })\n\n readable.on('error', (err) => {\n if (isAbortError(err)) {\n finished.resolve()\n return\n }\n\n res.destroy(err)\n finished.resolve()\n })\n\n await finished.promise\n } catch (err: any) {\n if (isAbortError(err)) return\n\n throw new Error('failed to pipe response', { cause: err })\n }\n}\n"],"names":["isAbortError","pipeNodeReadableToNodeResponse","pipeToNodeResponse","e","name","ResponseAbortedName","HAS_CLIENT_COMPONENT_METRICS_ENABLED","globalThis","process","env","NEXT_OTEL_PERFORMANCE_PREFIX","createWriterFromResponse","res","waitUntilForEnd","clientComponentLoadTracker","started","drained","createPromiseWithResolvers","onDrain","resolve","on","once","off","finished","WritableStream","write","chunk","metrics","snapshot","performance","measure","start","clientComponentLoadStart","end","clientComponentLoadTimes","flushHeaders","getTracer","trace","NextNodeServerSpan","startResponse","spanName","undefined","ok","flush","promise","err","Error","cause","abort","writableFinished","destroy","close","readable","errored","destroyed","controller","createAbortController","writer","pipeTo","signal","paused","resume","pause"],"mappings":";;;;;;;;;;;;;;;;IAYgBA,YAAY;eAAZA;;IA8IMC,8BAA8B;eAA9BA;;IA9BAC,kBAAkB;eAAlBA;;;6BAtHf;sCACoC;wBACjB;2BACS;AAG5B,SAASF,aAAaG,CAAM;IACjC,OAAOA,CAAAA,qBAAAA,EAAGC,IAAI,MAAK,gBAAgBD,CAAAA,qBAAAA,EAAGC,IAAI,MAAKC,gCAAmB;AACpE;AAEA,MAAMC,uCACJ,iBAAiBC,cAAcC,QAAQC,GAAG,CAACC,4BAA4B;AAEzE,SAASC,yBACPC,GAAmB,EACnBC,eAAkC,EAClCC,0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,KAAK;YAChB;QACF;QAEAV,SAAShC,EAAE,CAAC,OAAO;YACjB,IAAIP,iBAAiB;gBACnB,MAAMA;YACR;YAEA,IAAI,CAACD,IAAIqC,gBAAgB,EAAE;gBACzBrC,IAAIqB,GAAG;YACT;YAEAV,SAASJ,OAAO;QAClB;QAEAiC,SAAShC,EAAE,CAAC,SAAS,CAACyB;YACpB,IAAI7C,aAAa6C,MAAM;gBACrBtB,SAASJ,OAAO;gBAChB;YACF;YAEAP,IAAIsC,OAAO,CAACL;YACZtB,SAASJ,OAAO;QAClB;QAEA,MAAMI,SAASqB,OAAO;IACxB,EAAE,OAAOC,KAAU;QACjB,IAAI7C,aAAa6C,MAAM;QAEvB,MAAM,IAAIC,MAAM,2BAA2B;YAAEC,OAAOF;QAAI;IAC1D;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/post-process.d.ts b/e-commerce/node_modules/next/dist/server/post-process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..06d77652b999ba310d34be816c510192cc3c4381 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/post-process.d.ts @@ -0,0 +1,3 @@ +import type { RenderOpts } from './render'; +declare function postProcessHTML(content: string, renderOpts: Pick): Promise; +export { postProcessHTML }; diff --git a/e-commerce/node_modules/next/dist/server/post-process.js b/e-commerce/node_modules/next/dist/server/post-process.js new file mode 100644 index 0000000000000000000000000000000000000000..bff02e8e0fe5b0b6266d41934ef6bd169b66c8e2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/post-process.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "postProcessHTML", { + enumerable: true, + get: function() { + return postProcessHTML; + } +}); +const _nonnullable = require("../lib/non-nullable"); +async function postProcessHTML(content, renderOpts) { + const postProcessors = [ + process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeCss ? async (html)=>{ + // eslint-disable-next-line import/no-extraneous-dependencies + const Critters = require('critters'); + // @ts-expect-error -- interopRequireDefault + const cssOptimizer = new Critters({ + ssrMode: true, + reduceInlineStyles: false, + path: renderOpts.distDir, + publicPath: `${renderOpts.assetPrefix}/_next/`, + preload: 'media', + fonts: false, + logLevel: process.env.CRITTERS_LOG_LEVEL || (process.env.NODE_ENV === 'production' ? 'warn' : 'info'), + ...renderOpts.optimizeCss + }); + return await cssOptimizer.process(html); + } : null + ].filter(_nonnullable.nonNullable); + for (const postProcessor of postProcessors){ + if (postProcessor) { + content = await postProcessor(content); + } + } + return content; +} + +//# sourceMappingURL=post-process.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/post-process.js.map b/e-commerce/node_modules/next/dist/server/post-process.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3ecd7e5929fcaed1c073eb3728157dd715b79984 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/post-process.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/post-process.ts"],"sourcesContent":["import type { RenderOpts } from './render'\n\nimport { nonNullable } from '../lib/non-nullable'\n\ntype PostProcessorFunction =\n | ((html: string) => Promise)\n | ((html: string) => string)\n\nasync function postProcessHTML(\n content: string,\n renderOpts: Pick\n) {\n const postProcessors: Array = [\n process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeCss\n ? async (html: string) => {\n // eslint-disable-next-line import/no-extraneous-dependencies\n const Critters = require('critters') as typeof import('critters')\n // @ts-expect-error -- interopRequireDefault\n const cssOptimizer = new Critters({\n ssrMode: true,\n reduceInlineStyles: false,\n path: renderOpts.distDir,\n publicPath: `${renderOpts.assetPrefix}/_next/`,\n preload: 'media',\n fonts: false,\n logLevel:\n process.env.CRITTERS_LOG_LEVEL ||\n (process.env.NODE_ENV === 'production' ? 'warn' : 'info'),\n ...renderOpts.optimizeCss,\n })\n return await cssOptimizer.process(html)\n }\n : null,\n ].filter(nonNullable)\n\n for (const postProcessor of postProcessors) {\n if (postProcessor) {\n content = await postProcessor(content)\n }\n }\n return content\n}\n\nexport { postProcessHTML }\n"],"names":["postProcessHTML","content","renderOpts","postProcessors","process","env","NEXT_RUNTIME","optimizeCss","html","Critters","require","cssOptimizer","ssrMode","reduceInlineStyles","path","distDir","publicPath","assetPrefix","preload","fonts","logLevel","CRITTERS_LOG_LEVEL","NODE_ENV","filter","nonNullable","postProcessor"],"mappings":";;;;+BA2CSA;;;eAAAA;;;6BAzCmB;AAM5B,eAAeA,gBACbC,OAAe,EACfC,UAAuE;IAEvE,MAAMC,iBAA+C;QACnDC,QAAQC,GAAG,CAACC,YAAY,KAAK,UAAUJ,WAAWK,WAAW,GACzD,OAAOC;YACL,6DAA6D;YAC7D,MAAMC,WAAWC,QAAQ;YACzB,4CAA4C;YAC5C,MAAMC,eAAe,IAAIF,SAAS;gBAChCG,SAAS;gBACTC,oBAAoB;gBACpBC,MAAMZ,WAAWa,OAAO;gBACxBC,YAAY,GAAGd,WAAWe,WAAW,CAAC,OAAO,CAAC;gBAC9CC,SAAS;gBACTC,OAAO;gBACPC,UACEhB,QAAQC,GAAG,CAACgB,kBAAkB,IAC7BjB,CAAAA,QAAQC,GAAG,CAACiB,QAAQ,KAAK,eAAe,SAAS,MAAK;gBACzD,GAAGpB,WAAWK,WAAW;YAC3B;YACA,OAAO,MAAMI,aAAaP,OAAO,CAACI;QACpC,IACA;KACL,CAACe,MAAM,CAACC,wBAAW;IAEpB,KAAK,MAAMC,iBAAiBtB,eAAgB;QAC1C,IAAIsB,eAAe;YACjBxB,UAAU,MAAMwB,cAAcxB;QAChC;IACF;IACA,OAAOA;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/render-result.d.ts b/e-commerce/node_modules/next/dist/server/render-result.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..31f2f0b97d12f3d16cbea0874138c11be59199cd --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/render-result.d.ts @@ -0,0 +1,177 @@ +import type { OutgoingHttpHeaders, ServerResponse } from 'http'; +import type { Readable } from 'stream'; +import type { CacheControl } from './lib/cache-control'; +import type { FetchMetrics } from './base-http'; +import type { PrefetchHints } from '../shared/lib/app-router-types'; +import type { ClientComponentLoadTracker } from './client-component-renderer-logger'; +import type { RenderResumeDataCache } from './resume-data-cache/resume-data-cache'; +import type { HTML_CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE_HEADER, TEXT_PLAIN_CONTENT_TYPE_HEADER } from '../lib/constants'; +import type { RSC_CONTENT_TYPE_HEADER } from '../client/components/app-router-headers'; +type ContentTypeOption = typeof RSC_CONTENT_TYPE_HEADER | typeof HTML_CONTENT_TYPE_HEADER | typeof JSON_CONTENT_TYPE_HEADER | typeof TEXT_PLAIN_CONTENT_TYPE_HEADER; +export type AppPageRenderResultMetadata = { + /** Request-local metrics for the first response write. Never cache this. */ + clientComponentLoadTracker?: ClientComponentLoadTracker; + flightData?: Buffer; + cacheControl?: CacheControl; + staticBailoutInfo?: { + stack?: string; + description?: string; + }; + /** + * The postponed state if the render had postponed and needs to be resumed. + */ + postponed?: string; + /** + * Whether the prerender left any UI pending in a Suspense boundary. This is + * reported directly by React's prerender result before Next.js resumes + * client-only boundaries. + */ + hasPendingUi?: boolean; + /** + * The headers to set on the response that were added by the render. + */ + headers?: OutgoingHttpHeaders; + statusCode?: number; + fetchTags?: string; + fetchMetrics?: FetchMetrics; + segmentData?: Map; + /** + * Per-route prefetch hints computed at build time (e.g. segment inlining + * decisions based on gzip sizes). Written to prefetch-hints.json by the + * build pipeline. + */ + prefetchHints?: PrefetchHints; + /** + * In development, the resume data cache is warmed up before the render. This + * is attached to the metadata so that it can be used during the render. When + * prerendering, the filled resume data cache is also attached to the metadata + * so that it can be used when prerendering matching fallback shells. + */ + renderResumeDataCache?: RenderResumeDataCache; +}; +export type PrerenderFailure = { + readonly error: Error; + readonly result: RenderResult>; +}; +export type PrerenderResult = RenderResult | PrerenderFailure; +export type PagesRenderResultMetadata = { + pageData?: any; + cacheControl?: CacheControl; + isNotFound?: boolean; + isRedirect?: boolean; +}; +export type StaticRenderResultMetadata = {}; +export type RenderResultMetadata = AppPageRenderResultMetadata & PagesRenderResultMetadata & StaticRenderResultMetadata; +export type RenderResultResponse = ReadableStream[] | ReadableStream | Readable | string | Buffer | null; +export type RenderResultOptions = { + contentType: ContentTypeOption | null; + waitUntil?: Promise; + metadata: Metadata; +}; +export default class RenderResult { + /** + * The detected content type for the response. This is used to set the + * `Content-Type` header. + */ + readonly contentType: ContentTypeOption | null; + /** + * The metadata for the response. This is used to set the revalidation times + * and other metadata. + */ + readonly metadata: Readonly; + /** + * The response itself. This can be a string, a stream, or null. If it's a + * string, then it's a static response. If it's a stream, then it's a + * dynamic response. If it's null, then the response was not found or was + * already sent. + */ + private response; + /** + * A render result that represents an empty response. This is used to + * represent a response that was not found or was already sent. + */ + static readonly EMPTY: RenderResult; + /** + * Creates a new RenderResult instance from a static response. + * + * @param value the static response value + * @param contentType the content type of the response + * @returns a new RenderResult instance + */ + static fromStatic(value: string | Buffer, contentType: ContentTypeOption): RenderResult; + private readonly waitUntil?; + constructor(response: RenderResultResponse, { contentType, waitUntil, metadata }: RenderResultOptions); + assignMetadata(metadata: Metadata): void; + /** + * Returns true if the response is null. It can be null if the response was + * not found or was already sent. + */ + get isNull(): boolean; + /** + * Returns false if the response is a string. It can be a string if the page + * was prerendered. If it's not, then it was generated dynamically. + */ + get isDynamic(): boolean; + /** + * Returns the response if it is a string. If the page was dynamic, this will + * return a promise if the `stream` option is true, or it will throw an error. + * + * @param stream Whether or not to return a promise if the response is dynamic + * @returns The response as a string + */ + toUnchunkedString(stream?: false): string; + toUnchunkedString(stream: true): Promise; + /** + * Returns a readable stream of the response. + */ + private get readable(); + /** + * Coerces the response to an array of streams. This will convert the response + * to an array of streams if it is not already one. + * + * @returns An array of streams + */ + private coerce; + /** + * Pipes the response through a transform stream. This converts the response + * to a single readable stream (chaining if needed) and pipes it through the + * provided transform. + * + * @param transform The transform stream to pipe through + */ + pipeThrough(transform: TransformStream): void; + /** + * Unshifts a new stream to the response. This will convert the response to an + * array of streams if it is not already one and will add the new stream to + * the start of the array. When this response is piped, all of the streams + * will be piped one after the other. + * + * @param readable The new stream to unshift + */ + unshift(readable: ReadableStream): void; + /** + * Chains a new stream to the response. This will convert the response to an + * array of streams if it is not already one and will add the new stream to + * the end. When this response is piped, all of the streams will be piped + * one after the other. + * + * @param readable The new stream to chain + */ + push(readable: ReadableStream): void; + /** + * Pipes the response to a writable stream. This will close/cancel the + * writable stream if an error is encountered. If this doesn't throw, then + * the writable stream will be closed or aborted. + * + * @param writable Writable stream to pipe the response to + */ + pipeTo(writable: WritableStream): Promise; + /** + * Pipes the response to a node response. This will close/cancel the node + * response if an error is encountered. + * + * @param res + */ + pipeToNodeResponse(res: ServerResponse): Promise; +} +export {}; diff --git a/e-commerce/node_modules/next/dist/server/render-result.js b/e-commerce/node_modules/next/dist/server/render-result.js new file mode 100644 index 0000000000000000000000000000000000000000..720a142a63bffb939a360c9c610b7b602af4057e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/render-result.js @@ -0,0 +1,234 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return RenderResult; + } +}); +const _nodewebstreamshelper = require("./stream-utils/node-web-streams-helper"); +const _pipereadable = require("./pipe-readable"); +const _invarianterror = require("../shared/lib/invariant-error"); +function isNodeReadable(value) { + return value !== null && typeof value === 'object' && typeof value.pipe === 'function' && typeof value.on === 'function' && !(value instanceof ReadableStream); +} +class RenderResult { + static #_ = /** + * A render result that represents an empty response. This is used to + * represent a response that was not found or was already sent. + */ this.EMPTY = new RenderResult(null, { + metadata: {}, + contentType: null + }); + /** + * Creates a new RenderResult instance from a static response. + * + * @param value the static response value + * @param contentType the content type of the response + * @returns a new RenderResult instance + */ static fromStatic(value, contentType) { + return new RenderResult(value, { + metadata: {}, + contentType + }); + } + constructor(response, { contentType, waitUntil, metadata }){ + this.response = response; + this.contentType = contentType; + this.metadata = metadata; + this.waitUntil = waitUntil; + } + assignMetadata(metadata) { + Object.assign(this.metadata, metadata); + } + /** + * Returns true if the response is null. It can be null if the response was + * not found or was already sent. + */ get isNull() { + return this.response === null; + } + /** + * Returns false if the response is a string. It can be a string if the page + * was prerendered. If it's not, then it was generated dynamically. + */ get isDynamic() { + return typeof this.response !== 'string'; + } + toUnchunkedString(stream = false) { + if (this.response === null) { + // If the response is null, return an empty string. This behavior is + // intentional as we're now providing the `RenderResult.EMPTY` value. + return ''; + } + if (typeof this.response !== 'string') { + if (!stream) { + throw new _invarianterror.InvariantError('dynamic responses cannot be unchunked. This is a bug in Next.js'); + } + return (0, _nodewebstreamshelper.streamToString)(this.readable); + } + return this.response; + } + /** + * Returns a readable stream of the response. + */ get readable() { + if (this.response === null) { + // If the response is null, return an empty stream. This behavior is + // intentional as we're now providing the `RenderResult.EMPTY` value. + return new ReadableStream({ + start (controller) { + controller.close(); + } + }); + } + if (typeof this.response === 'string') { + return (0, _nodewebstreamshelper.streamFromString)(this.response); + } + if (Buffer.isBuffer(this.response)) { + return (0, _nodewebstreamshelper.streamFromBuffer)(this.response); + } + // If the response is an array of streams, then chain them together. + if (Array.isArray(this.response)) { + return (0, _nodewebstreamshelper.chainStreams)(...this.response); + } + if (isNodeReadable(this.response)) { + if (process.env.NEXT_RUNTIME === 'edge') { + throw new _invarianterror.InvariantError('Node.js Readable cannot be converted to a web stream in the edge runtime'); + } else { + let Readable; + if (process.env.TURBOPACK) { + Readable = require('node:stream').Readable; + } else { + Readable = __non_webpack_require__('node:stream').Readable; + } + return Readable.toWeb(this.response); + } + } + return this.response; + } + /** + * Coerces the response to an array of streams. This will convert the response + * to an array of streams if it is not already one. + * + * @returns An array of streams + */ coerce() { + if (this.response === null) { + // If the response is null, return an empty stream. This behavior is + // intentional as we're now providing the `RenderResult.EMPTY` value. + return []; + } + if (typeof this.response === 'string') { + return [ + (0, _nodewebstreamshelper.streamFromString)(this.response) + ]; + } else if (Array.isArray(this.response)) { + return this.response; + } else if (Buffer.isBuffer(this.response)) { + return [ + (0, _nodewebstreamshelper.streamFromBuffer)(this.response) + ]; + } else if (isNodeReadable(this.response)) { + if (process.env.NEXT_RUNTIME === 'edge') { + throw new _invarianterror.InvariantError('Node.js Readable cannot be converted to a web stream in the edge runtime'); + } else { + let Readable; + if (process.env.TURBOPACK) { + Readable = require('node:stream').Readable; + } else { + Readable = __non_webpack_require__('node:stream').Readable; + } + return [ + Readable.toWeb(this.response) + ]; + } + } else { + return [ + this.response + ]; + } + } + /** + * Pipes the response through a transform stream. This converts the response + * to a single readable stream (chaining if needed) and pipes it through the + * provided transform. + * + * @param transform The transform stream to pipe through + */ pipeThrough(transform) { + this.response = this.readable.pipeThrough(transform); + } + /** + * Unshifts a new stream to the response. This will convert the response to an + * array of streams if it is not already one and will add the new stream to + * the start of the array. When this response is piped, all of the streams + * will be piped one after the other. + * + * @param readable The new stream to unshift + */ unshift(readable) { + // Coerce the response to an array of streams. + this.response = this.coerce(); + // Add the new stream to the start of the array. + this.response.unshift(readable); + } + /** + * Chains a new stream to the response. This will convert the response to an + * array of streams if it is not already one and will add the new stream to + * the end. When this response is piped, all of the streams will be piped + * one after the other. + * + * @param readable The new stream to chain + */ push(readable) { + // Coerce the response to an array of streams. + this.response = this.coerce(); + // Add the new stream to the end of the array. + this.response.push(readable); + } + /** + * Pipes the response to a writable stream. This will close/cancel the + * writable stream if an error is encountered. If this doesn't throw, then + * the writable stream will be closed or aborted. + * + * @param writable Writable stream to pipe the response to + */ async pipeTo(writable) { + try { + await this.readable.pipeTo(writable, { + // We want to close the writable stream ourselves so that we can wait + // for the waitUntil promise to resolve before closing it. If an error + // is encountered, we'll abort the writable stream if we swallowed the + // error. + preventClose: true + }); + // If there is a waitUntil promise, wait for it to resolve before + // closing the writable stream. + if (this.waitUntil) await this.waitUntil; + // Close the writable stream. + await writable.close(); + } catch (err) { + // If this is an abort error, we should abort the writable stream (as we + // took ownership of it when we started piping). We don't need to re-throw + // because we handled the error. + if ((0, _pipereadable.isAbortError)(err)) { + // Abort the writable stream if an error is encountered. + await writable.abort(err); + return; + } + // We're not aborting the writer here as when this method throws it's not + // clear as to how so the caller should assume it's their responsibility + // to clean up the writer. + throw err; + } + } + /** + * Pipes the response to a node response. This will close/cancel the node + * response if an error is encountered. + * + * @param res + */ async pipeToNodeResponse(res) { + if (this.response !== null && typeof this.response !== 'string' && !Buffer.isBuffer(this.response) && !Array.isArray(this.response) && isNodeReadable(this.response)) { + await (0, _pipereadable.pipeNodeReadableToNodeResponse)(this.response, res, this.waitUntil, this.metadata.clientComponentLoadTracker); + return; + } + await (0, _pipereadable.pipeToNodeResponse)(this.readable, res, this.waitUntil, this.metadata.clientComponentLoadTracker); + } +} + +//# sourceMappingURL=render-result.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/render-result.js.map b/e-commerce/node_modules/next/dist/server/render-result.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4a7c00c432077879a0774b47a7962a109ef7d646 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/render-result.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/render-result.ts"],"sourcesContent":["import type { OutgoingHttpHeaders, ServerResponse } from 'http'\nimport type { Readable } from 'stream'\nimport type { CacheControl } from './lib/cache-control'\nimport type { FetchMetrics } from './base-http'\nimport type { PrefetchHints } from '../shared/lib/app-router-types'\nimport type { ClientComponentLoadTracker } from './client-component-renderer-logger'\n\nimport {\n chainStreams,\n streamFromBuffer,\n streamFromString,\n streamToString,\n} from './stream-utils/node-web-streams-helper'\nimport {\n isAbortError,\n pipeToNodeResponse,\n pipeNodeReadableToNodeResponse,\n} from './pipe-readable'\nimport type { RenderResumeDataCache } from './resume-data-cache/resume-data-cache'\nimport { InvariantError } from '../shared/lib/invariant-error'\nimport type {\n HTML_CONTENT_TYPE_HEADER,\n JSON_CONTENT_TYPE_HEADER,\n TEXT_PLAIN_CONTENT_TYPE_HEADER,\n} from '../lib/constants'\nimport type { RSC_CONTENT_TYPE_HEADER } from '../client/components/app-router-headers'\n\ntype ContentTypeOption =\n | typeof RSC_CONTENT_TYPE_HEADER // For App Page RSC responses\n | typeof HTML_CONTENT_TYPE_HEADER // For App Page, Pages HTML responses\n | typeof JSON_CONTENT_TYPE_HEADER // For API routes, Next.js data requests\n | typeof TEXT_PLAIN_CONTENT_TYPE_HEADER // For simplified errors\n\nexport type AppPageRenderResultMetadata = {\n /** Request-local metrics for the first response write. Never cache this. */\n clientComponentLoadTracker?: ClientComponentLoadTracker\n flightData?: Buffer\n cacheControl?: CacheControl\n staticBailoutInfo?: {\n stack?: string\n description?: string\n }\n\n /**\n * The postponed state if the render had postponed and needs to be resumed.\n */\n postponed?: string\n\n /**\n * Whether the prerender left any UI pending in a Suspense boundary. This is\n * reported directly by React's prerender result before Next.js resumes\n * client-only boundaries.\n */\n hasPendingUi?: boolean\n\n /**\n * The headers to set on the response that were added by the render.\n */\n headers?: OutgoingHttpHeaders\n statusCode?: number\n fetchTags?: string\n fetchMetrics?: FetchMetrics\n\n segmentData?: Map\n\n /**\n * Per-route prefetch hints computed at build time (e.g. segment inlining\n * decisions based on gzip sizes). Written to prefetch-hints.json by the\n * build pipeline.\n */\n prefetchHints?: PrefetchHints\n\n /**\n * In development, the resume data cache is warmed up before the render. This\n * is attached to the metadata so that it can be used during the render. When\n * prerendering, the filled resume data cache is also attached to the metadata\n * so that it can be used when prerendering matching fallback shells.\n */\n renderResumeDataCache?: RenderResumeDataCache\n}\n\nexport type PrerenderFailure = {\n readonly error: Error\n readonly result: RenderResult<\n Pick<\n AppPageRenderResultMetadata,\n 'headers' | 'flightData' | 'fetchMetrics' | 'postponed'\n >\n >\n}\n\nexport type PrerenderResult =\n | RenderResult\n | PrerenderFailure\n\nexport type PagesRenderResultMetadata = {\n pageData?: any\n cacheControl?: CacheControl\n isNotFound?: boolean\n isRedirect?: boolean\n}\n\nexport type StaticRenderResultMetadata = {}\n\nexport type RenderResultMetadata = AppPageRenderResultMetadata &\n PagesRenderResultMetadata &\n StaticRenderResultMetadata\n\nexport type RenderResultResponse =\n | ReadableStream[]\n | ReadableStream\n | Readable\n | string\n | Buffer\n | null\n\nexport type RenderResultOptions<\n Metadata extends RenderResultMetadata = RenderResultMetadata,\n> = {\n contentType: ContentTypeOption | null\n waitUntil?: Promise\n metadata: Metadata\n}\n\nfunction isNodeReadable(value: unknown): value is Readable {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as Record).pipe === 'function' &&\n typeof (value as Record).on === 'function' &&\n !(value instanceof ReadableStream)\n )\n}\n\nexport default class RenderResult<\n Metadata extends RenderResultMetadata = RenderResultMetadata,\n> {\n /**\n * The detected content type for the response. This is used to set the\n * `Content-Type` header.\n */\n public readonly contentType: ContentTypeOption | null\n\n /**\n * The metadata for the response. This is used to set the revalidation times\n * and other metadata.\n */\n public readonly metadata: Readonly\n\n /**\n * The response itself. This can be a string, a stream, or null. If it's a\n * string, then it's a static response. If it's a stream, then it's a\n * dynamic response. If it's null, then the response was not found or was\n * already sent.\n */\n private response: RenderResultResponse\n\n /**\n * A render result that represents an empty response. This is used to\n * represent a response that was not found or was already sent.\n */\n public static readonly EMPTY = new RenderResult(\n null,\n { metadata: {}, contentType: null }\n )\n\n /**\n * Creates a new RenderResult instance from a static response.\n *\n * @param value the static response value\n * @param contentType the content type of the response\n * @returns a new RenderResult instance\n */\n public static fromStatic(\n value: string | Buffer,\n contentType: ContentTypeOption\n ) {\n return new RenderResult(value, {\n metadata: {},\n contentType,\n })\n }\n\n private readonly waitUntil?: Promise\n\n constructor(\n response: RenderResultResponse,\n { contentType, waitUntil, metadata }: RenderResultOptions\n ) {\n this.response = response\n this.contentType = contentType\n this.metadata = metadata\n this.waitUntil = waitUntil\n }\n\n public assignMetadata(metadata: Metadata) {\n Object.assign(this.metadata, metadata)\n }\n\n /**\n * Returns true if the response is null. It can be null if the response was\n * not found or was already sent.\n */\n public get isNull(): boolean {\n return this.response === null\n }\n\n /**\n * Returns false if the response is a string. It can be a string if the page\n * was prerendered. If it's not, then it was generated dynamically.\n */\n public get isDynamic(): boolean {\n return typeof this.response !== 'string'\n }\n\n /**\n * Returns the response if it is a string. If the page was dynamic, this will\n * return a promise if the `stream` option is true, or it will throw an error.\n *\n * @param stream Whether or not to return a promise if the response is dynamic\n * @returns The response as a string\n */\n public toUnchunkedString(stream?: false): string\n public toUnchunkedString(stream: true): Promise\n public toUnchunkedString(stream = false): Promise | string {\n if (this.response === null) {\n // If the response is null, return an empty string. This behavior is\n // intentional as we're now providing the `RenderResult.EMPTY` value.\n return ''\n }\n\n if (typeof this.response !== 'string') {\n if (!stream) {\n throw new InvariantError(\n 'dynamic responses cannot be unchunked. This is a bug in Next.js'\n )\n }\n\n return streamToString(this.readable)\n }\n\n return this.response\n }\n\n /**\n * Returns a readable stream of the response.\n */\n private get readable(): ReadableStream {\n if (this.response === null) {\n // If the response is null, return an empty stream. This behavior is\n // intentional as we're now providing the `RenderResult.EMPTY` value.\n return new ReadableStream({\n start(controller) {\n controller.close()\n },\n })\n }\n\n if (typeof this.response === 'string') {\n return streamFromString(this.response)\n }\n\n if (Buffer.isBuffer(this.response)) {\n return streamFromBuffer(this.response)\n }\n\n // If the response is an array of streams, then chain them together.\n if (Array.isArray(this.response)) {\n return chainStreams(...this.response)\n }\n\n if (isNodeReadable(this.response)) {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n 'Node.js Readable cannot be converted to a web stream in the edge runtime'\n )\n } else {\n let Readable: typeof import('node:stream').Readable\n if (process.env.TURBOPACK) {\n Readable = (require('node:stream') as typeof import('node:stream'))\n .Readable\n } else {\n Readable = (\n __non_webpack_require__(\n 'node:stream'\n ) as typeof import('node:stream')\n ).Readable\n }\n return Readable.toWeb(this.response) as ReadableStream\n }\n }\n\n return this.response\n }\n\n /**\n * Coerces the response to an array of streams. This will convert the response\n * to an array of streams if it is not already one.\n *\n * @returns An array of streams\n */\n private coerce(): ReadableStream[] {\n if (this.response === null) {\n // If the response is null, return an empty stream. This behavior is\n // intentional as we're now providing the `RenderResult.EMPTY` value.\n return []\n }\n\n if (typeof this.response === 'string') {\n return [streamFromString(this.response)]\n } else if (Array.isArray(this.response)) {\n return this.response\n } else if (Buffer.isBuffer(this.response)) {\n return [streamFromBuffer(this.response)]\n } else if (isNodeReadable(this.response)) {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n 'Node.js Readable cannot be converted to a web stream in the edge runtime'\n )\n } else {\n let Readable: typeof import('node:stream').Readable\n if (process.env.TURBOPACK) {\n Readable = (require('node:stream') as typeof import('node:stream'))\n .Readable\n } else {\n Readable = (\n __non_webpack_require__(\n 'node:stream'\n ) as typeof import('node:stream')\n ).Readable\n }\n return [Readable.toWeb(this.response) as ReadableStream]\n }\n } else {\n return [this.response]\n }\n }\n\n /**\n * Pipes the response through a transform stream. This converts the response\n * to a single readable stream (chaining if needed) and pipes it through the\n * provided transform.\n *\n * @param transform The transform stream to pipe through\n */\n public pipeThrough(transform: TransformStream): void {\n this.response = this.readable.pipeThrough(transform)\n }\n\n /**\n * Unshifts a new stream to the response. This will convert the response to an\n * array of streams if it is not already one and will add the new stream to\n * the start of the array. When this response is piped, all of the streams\n * will be piped one after the other.\n *\n * @param readable The new stream to unshift\n */\n public unshift(readable: ReadableStream): void {\n // Coerce the response to an array of streams.\n this.response = this.coerce()\n\n // Add the new stream to the start of the array.\n this.response.unshift(readable)\n }\n\n /**\n * Chains a new stream to the response. This will convert the response to an\n * array of streams if it is not already one and will add the new stream to\n * the end. When this response is piped, all of the streams will be piped\n * one after the other.\n *\n * @param readable The new stream to chain\n */\n public push(readable: ReadableStream): void {\n // Coerce the response to an array of streams.\n this.response = this.coerce()\n\n // Add the new stream to the end of the array.\n this.response.push(readable)\n }\n\n /**\n * Pipes the response to a writable stream. This will close/cancel the\n * writable stream if an error is encountered. If this doesn't throw, then\n * the writable stream will be closed or aborted.\n *\n * @param writable Writable stream to pipe the response to\n */\n public async pipeTo(writable: WritableStream): Promise {\n try {\n await this.readable.pipeTo(writable, {\n // We want to close the writable stream ourselves so that we can wait\n // for the waitUntil promise to resolve before closing it. If an error\n // is encountered, we'll abort the writable stream if we swallowed the\n // error.\n preventClose: true,\n })\n\n // If there is a waitUntil promise, wait for it to resolve before\n // closing the writable stream.\n if (this.waitUntil) await this.waitUntil\n\n // Close the writable stream.\n await writable.close()\n } catch (err) {\n // If this is an abort error, we should abort the writable stream (as we\n // took ownership of it when we started piping). We don't need to re-throw\n // because we handled the error.\n if (isAbortError(err)) {\n // Abort the writable stream if an error is encountered.\n await writable.abort(err)\n\n return\n }\n\n // We're not aborting the writer here as when this method throws it's not\n // clear as to how so the caller should assume it's their responsibility\n // to clean up the writer.\n throw err\n }\n }\n\n /**\n * Pipes the response to a node response. This will close/cancel the node\n * response if an error is encountered.\n *\n * @param res\n */\n public async pipeToNodeResponse(res: ServerResponse) {\n if (\n this.response !== null &&\n typeof this.response !== 'string' &&\n !Buffer.isBuffer(this.response) &&\n !Array.isArray(this.response) &&\n isNodeReadable(this.response)\n ) {\n await pipeNodeReadableToNodeResponse(\n this.response,\n res,\n this.waitUntil,\n this.metadata.clientComponentLoadTracker\n )\n return\n }\n await pipeToNodeResponse(\n this.readable,\n res,\n this.waitUntil,\n this.metadata.clientComponentLoadTracker\n )\n }\n}\n"],"names":["RenderResult","isNodeReadable","value","pipe","on","ReadableStream","EMPTY","metadata","contentType","fromStatic","constructor","response","waitUntil","assignMetadata","Object","assign","isNull","isDynamic","toUnchunkedString","stream","InvariantError","streamToString","readable","start","controller","close","streamFromString","Buffer","isBuffer","streamFromBuffer","Array","isArray","chainStreams","process","env","NEXT_RUNTIME","Readable","TURBOPACK","require","__non_webpack_require__","toWeb","coerce","pipeThrough","transform","unshift","push","pipeTo","writable","preventClose","err","isAbortError","abort","pipeToNodeResponse","res","pipeNodeReadableToNodeResponse","clientComponentLoadTracker"],"mappings":";;;;+BAsIA;;;eAAqBA;;;sCA1Hd;8BAKA;gCAEwB;AAyG/B,SAASC,eAAeC,KAAc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AI,CAACzB,QAAQ,CAACwB,MAAM,CAACC,UAAU;gBACnC,qEAAqE;gBACrE,sEAAsE;gBACtE,sEAAsE;gBACtE,SAAS;gBACTC,cAAc;YAChB;YAEA,iEAAiE;YACjE,+BAA+B;YAC/B,IAAI,IAAI,CAACpC,SAAS,EAAE,MAAM,IAAI,CAACA,SAAS;YAExC,6BAA6B;YAC7B,MAAMmC,SAAStB,KAAK;QACtB,EAAE,OAAOwB,KAAK;YACZ,wEAAwE;YACxE,0EAA0E;YAC1E,gCAAgC;YAChC,IAAIC,IAAAA,0BAAY,EAACD,MAAM;gBACrB,wDAAwD;gBACxD,MAAMF,SAASI,KAAK,CAACF;gBAErB;YACF;YAEA,yEAAyE;YACzE,wEAAwE;YACxE,0BAA0B;YAC1B,MAAMA;QACR;IACF;IAEA;;;;;GAKC,GACD,MAAaG,mBAAmBC,GAAmB,EAAE;QACnD,IACE,IAAI,CAAC1C,QAAQ,KAAK,QAClB,OAAO,IAAI,CAACA,QAAQ,KAAK,YACzB,CAACgB,OAAOC,QAAQ,CAAC,IAAI,CAACjB,QAAQ,KAC9B,CAACmB,MAAMC,OAAO,CAAC,IAAI,CAACpB,QAAQ,KAC5BV,eAAe,IAAI,CAACU,QAAQ,GAC5B;YACA,MAAM2C,IAAAA,4CAA8B,EAClC,IAAI,CAAC3C,QAAQ,EACb0C,KACA,IAAI,CAACzC,SAAS,EACd,IAAI,CAACL,QAAQ,CAACgD,0BAA0B;YAE1C;QACF;QACA,MAAMH,IAAAA,gCAAkB,EACtB,IAAI,CAAC9B,QAAQ,EACb+B,KACA,IAAI,CAACzC,SAAS,EACd,IAAI,CAACL,QAAQ,CAACgD,0BAA0B;IAE5C;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/render.d.ts b/e-commerce/node_modules/next/dist/server/render.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..243537ed7694cfaf4d49ec65483890184ae3647a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/render.d.ts @@ -0,0 +1,121 @@ +import type { IncomingMessage, ServerResponse } from 'http'; +import type { ParsedUrlQuery } from 'querystring'; +import type { DomainLocale } from './config'; +import type { AppType, DocumentType } from '../shared/lib/utils'; +import type { ImageConfigComplete } from '../shared/lib/image-config'; +import { type __ApiPreviewProps } from './api-utils'; +import type { LoadComponentsReturnType } from './load-components'; +import type { ServerRuntime, SizeLimit } from '../types'; +import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'; +import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'; +import type { PagesModule } from './route-modules/pages/module'; +import type { NextParsedUrlQuery } from './request-meta'; +import RenderResult from './render-result'; +import type { DeepReadonly } from '../shared/lib/deep-readonly'; +import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'; +export type RenderOptsPartial = { + assetPrefix?: string; + err?: Error | null; + isBuildTimePrerendering?: boolean; + ErrorDebug?: PagesDevOverlayBridgeType; + isNextDataRequest?: boolean; + params?: ParsedUrlQuery; + previewProps: __ApiPreviewProps | undefined; + basePath: string; + unstable_runtimeJS?: false; + unstable_JsPreload?: false; + optimizeCss: any; + nextConfigOutput?: 'standalone' | 'export'; + nextScriptWorkers: any; + resolvedUrl?: string; + resolvedAsPath?: string; + setIsrStatus?: (key: string, value: boolean | undefined) => void; + clientReferenceManifest?: DeepReadonly; + nextFontManifest?: DeepReadonly; + distDir?: string; + locale?: string; + locales?: readonly string[]; + defaultLocale?: string; + domainLocales?: readonly DomainLocale[]; + disableOptimizedLoading?: boolean; + supportsDynamicResponse: boolean; + botType?: 'dom' | 'html' | undefined; + serveStreamingMetadata?: boolean; + runtime?: ServerRuntime; + serverComponents?: boolean; + serverActions?: { + bodySizeLimit?: SizeLimit; + allowedOrigins?: string[]; + }; + crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined; + images: ImageConfigComplete; + largePageDataBytes?: number; + isOnDemandRevalidate?: boolean; + isPossibleServerAction?: boolean; + isExperimentalCompile?: boolean; + isPrefetch?: boolean; + isBot?: boolean; + expireTime?: number; + experimental: { + clientTraceMetadata?: string[]; + }; +}; +export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial; +/** + * Shared context used for all page renders. + */ +export type PagesSharedContext = { + /** + * Used to facilitate caching of page bundles, we send it to the client so + * that pageloader knows where to load bundles. + */ + buildId: string; + /** + * See NextConfig.deploymentId + */ + deploymentId: string | undefined; + /** + * NextConfig.deploymentId if supportsImmutableAssets is not true, otherwise undefined. + */ + clientAssetToken: string | undefined; + /** + * True if the user is using a custom server. + */ + customServer: true | undefined; +}; +/** + * The context for the given request. + */ +export type PagesRenderContext = { + /** + * Whether this should be rendered as a fallback page. + */ + isFallback: boolean; + /** + * Whether this is in draft mode. + */ + isDraftMode: boolean | undefined; + /** + * In development, the original source page that returned a 404. + */ + developmentNotFoundSourcePage: string | undefined; +}; +/** + * RenderOptsExtra is being used to split away functionality that's within the + * renderOpts. Eventually we can have more explicit render options for each + * route kind. + */ +export type RenderOptsExtra = { + App: AppType; + Document: DocumentType; +}; +export declare function errorToJSON(err: Error): { + name: string; + source: "server" | "edge-server"; + message: string; + stack: string | undefined; + digest: any; +}; +export declare function renderToHTMLImpl(req: IncomingMessage, res: ServerResponse, pathname: string, query: NextParsedUrlQuery, renderOpts: Omit, extra: RenderOptsExtra, sharedContext: PagesSharedContext, renderContext: PagesRenderContext): Promise; +export type PagesRender = (req: IncomingMessage, res: ServerResponse, pathname: string, query: NextParsedUrlQuery, renderOpts: RenderOpts, sharedContext: PagesSharedContext, renderContext: PagesRenderContext) => Promise; +export declare const renderToHTML: PagesRender; diff --git a/e-commerce/node_modules/next/dist/server/render.js b/e-commerce/node_modules/next/dist/server/render.js new file mode 100644 index 0000000000000000000000000000000000000000..b672588ef94e65b8e4e3060e0d4d46acabb14da9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/render.js @@ -0,0 +1,1004 @@ +/* eslint-disable @next/internal/no-ambiguous-jsx -- Pages router doesn't use react-server */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + errorToJSON: null, + renderToHTML: null, + renderToHTMLImpl: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + errorToJSON: function() { + return errorToJSON; + }, + renderToHTML: function() { + return renderToHTML; + }, + renderToHTMLImpl: function() { + return renderToHTMLImpl; + } +}); +const _jsxruntime = require("react/jsx-runtime"); +const _apiutils = require("./api-utils"); +const _getcookieparser = require("./api-utils/get-cookie-parser"); +const _react = /*#__PURE__*/ _interop_require_default(require("react")); +const _ReactDOMServerPages = /*#__PURE__*/ _interop_require_default(require("next/dist/server/ReactDOMServerPages")); +const _styledjsx = require("styled-jsx"); +const _constants = require("../lib/constants"); +const _constants1 = require("../shared/lib/constants"); +const _isserializableprops = require("../lib/is-serializable-props"); +const _head = require("../shared/lib/head"); +const _headmanagercontextsharedruntime = require("../shared/lib/head-manager-context.shared-runtime"); +const _loadablesharedruntime = /*#__PURE__*/ _interop_require_default(require("../shared/lib/loadable.shared-runtime")); +const _loadablecontextsharedruntime = require("../shared/lib/loadable-context.shared-runtime"); +const _routercontextsharedruntime = require("../shared/lib/router-context.shared-runtime"); +const _isdynamic = require("../shared/lib/router/utils/is-dynamic"); +const _utils = require("../shared/lib/utils"); +const _htmlcontextsharedruntime = require("../shared/lib/html-context.shared-runtime"); +const _normalizepagepath = require("../shared/lib/page-path/normalize-page-path"); +const _denormalizepagepath = require("../shared/lib/page-path/denormalize-page-path"); +const _requestmeta = require("./request-meta"); +const _redirectstatus = require("../lib/redirect-status"); +const _renderresult = /*#__PURE__*/ _interop_require_default(require("./render-result")); +const _iserror = /*#__PURE__*/ _interop_require_default(require("../lib/is-error")); +const _nodewebstreamshelper = require("./stream-utils/node-web-streams-helper"); +const _imageconfigcontextsharedruntime = require("../shared/lib/image-config-context.shared-runtime"); +const _stripansi = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/strip-ansi")); +const _internalutils = require("./internal-utils"); +const _adapters = require("../shared/lib/router/adapters"); +const _approutercontextsharedruntime = require("../shared/lib/app-router-context.shared-runtime"); +const _hooksclientcontextsharedruntime = require("../shared/lib/hooks-client-context.shared-runtime"); +const _tracer = require("./lib/trace/tracer"); +const _constants2 = require("./lib/trace/constants"); +const _reflect = require("./web/spec-extension/adapters/reflect"); +const _cachecontrol = require("./lib/cache-control"); +const _errorsource = require("../shared/lib/error-source"); +const _getscriptnoncefromheader = require("./app-render/get-script-nonce-from-header"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +let tryGetPreviewData; +let warn; +let postProcessHTML; +const DOCTYPE = ''; +if (process.env.NEXT_RUNTIME !== 'edge') { + tryGetPreviewData = require('./api-utils/node/try-get-preview-data').tryGetPreviewData; + warn = require('../build/output/log').warn; + postProcessHTML = require('./post-process').postProcessHTML; +} else { + warn = console.warn.bind(console); + postProcessHTML = async (html)=>html; +} +function noRouter() { + const message = 'No router instance found. you should only use "next/router" inside the client side of your app. https://nextjs.org/docs/messages/no-router-instance'; + throw new Error(message); +} +async function renderToString(element) { + const renderStream = await _ReactDOMServerPages.default.renderToReadableStream(element); + await renderStream.allReady; + return (0, _nodewebstreamshelper.streamToString)(renderStream); +} +class ServerRouter { + constructor(pathname, query, as, { isFallback }, isReady, basePath, locale, locales, defaultLocale, domainLocales, isPreview, isLocaleDomain){ + this.route = pathname.replace(/\/$/, '') || '/'; + this.pathname = pathname; + this.query = query; + this.asPath = as; + this.isFallback = isFallback; + this.basePath = basePath; + this.locale = locale; + this.locales = locales; + this.defaultLocale = defaultLocale; + this.isReady = isReady; + this.domainLocales = domainLocales; + this.isPreview = !!isPreview; + this.isLocaleDomain = !!isLocaleDomain; + } + push() { + noRouter(); + } + replace() { + noRouter(); + } + reload() { + noRouter(); + } + back() { + noRouter(); + } + forward() { + noRouter(); + } + prefetch() { + noRouter(); + } + beforePopState() { + noRouter(); + } +} +function enhanceComponents(options, App, Component) { + // For backwards compatibility + if (typeof options === 'function') { + return { + App, + Component: options(Component) + }; + } + return { + App: options.enhanceApp ? options.enhanceApp(App) : App, + Component: options.enhanceComponent ? options.enhanceComponent(Component) : Component + }; +} +function renderPageTree(App, Component, props) { + return /*#__PURE__*/ (0, _jsxruntime.jsx)(App, { + Component: Component, + ...props + }); +} +const invalidKeysMsg = (methodName, invalidKeys)=>{ + const docsPathname = `invalid-${methodName.toLocaleLowerCase()}-value`; + return `Additional keys were returned from \`${methodName}\`. Properties intended for your component must be nested under the \`props\` key, e.g.:` + `\n\n\treturn { props: { title: 'My Title', content: '...' } }` + `\n\nKeys that need to be moved: ${invalidKeys.join(', ')}.` + `\nRead more: https://nextjs.org/docs/messages/${docsPathname}`; +}; +function checkRedirectValues(redirect, req, method) { + const { destination, permanent, statusCode, basePath } = redirect; + let errors = []; + const hasStatusCode = typeof statusCode !== 'undefined'; + const hasPermanent = typeof permanent !== 'undefined'; + if (hasPermanent && hasStatusCode) { + errors.push(`\`permanent\` and \`statusCode\` can not both be provided`); + } else if (hasPermanent && typeof permanent !== 'boolean') { + errors.push(`\`permanent\` must be \`true\` or \`false\``); + } else if (hasStatusCode && !_redirectstatus.allowedStatusCodes.has(statusCode)) { + errors.push(`\`statusCode\` must undefined or one of ${[ + ..._redirectstatus.allowedStatusCodes + ].join(', ')}`); + } + const destinationType = typeof destination; + if (destinationType !== 'string') { + errors.push(`\`destination\` should be string but received ${destinationType}`); + } + const basePathType = typeof basePath; + if (basePathType !== 'undefined' && basePathType !== 'boolean') { + errors.push(`\`basePath\` should be undefined or a false, received ${basePathType}`); + } + if (errors.length > 0) { + throw new Error(`Invalid redirect object returned from ${method} for ${req.url}\n` + errors.join(' and ') + '\n' + `See more info here: https://nextjs.org/docs/messages/invalid-redirect-gssp`); + } +} +function errorToJSON(err) { + let source = 'server'; + if (process.env.NEXT_RUNTIME !== 'edge') { + source = (0, _errorsource.getErrorSource)(err) || 'server'; + } + return { + name: err.name, + source, + message: (0, _stripansi.default)(err.message), + stack: err.stack, + digest: err.digest + }; +} +function serializeError(dev, err) { + if (dev) { + return errorToJSON(err); + } + return { + name: 'Internal Server Error.', + message: '500 - Internal Server Error.', + statusCode: 500 + }; +} +function getSafariCacheBusterQueryString(req) { + if (process.env.__NEXT_DEV_SERVER) { + const userAgent = (req.headers['user-agent'] || '').toLowerCase(); + if (userAgent.includes('safari') && !userAgent.includes('chrome')) { + return `?ts=${Date.now()}`; + } + } + return ''; +} +async function renderToHTMLImpl(req, res, pathname, query, renderOpts, extra, sharedContext, renderContext) { + // Adds support for reading `cookies` in `getServerSideProps` when SSR. + (0, _apiutils.setLazyProp)({ + req: req + }, 'cookies', (0, _getcookieparser.getCookieParser)(req.headers)); + // cssCacheBuster is a workaround for a Safari bug + // (https://bugs.webkit.org/show_bug.cgi?id=187726) where preloaded CSS + // resources are cached and not re-fetched on HMR. It must only be applied + // to CSS and font assets — not to script tags — because the Turbopack + // runtime infers ASSET_SUFFIX from the executing script's query string and + // leaks it onto all static asset URLs (including images), causing + // next/image validation errors. + // See https://github.com/vercel/next.js/issues/92118. + const cssCacheBuster = getSafariCacheBusterQueryString(req); + const mutableAssetQueryString = sharedContext.deploymentId ? `?dpl=${sharedContext.deploymentId}` : ''; + const assetQueryString = sharedContext.clientAssetToken ? `?dpl=${sharedContext.clientAssetToken}` : ''; + // cssAssetQueryString is assetQueryString with the cacheBuster prepended. + // Use this for CSS and font URLs; use assetQueryString for script URLs. + const cssAssetQueryString = cssCacheBuster + (sharedContext.clientAssetToken ? `${cssCacheBuster ? '&' : '?'}dpl=${sharedContext.clientAssetToken}` : ''); + const metadata = {}; + // don't modify original query object + query = Object.assign({}, query); + const { err, pageConfig = {}, buildManifest, reactLoadableManifest, ErrorDebug, getStaticProps, getStaticPaths, getServerSideProps, isNextDataRequest, params, previewProps, basePath, images, runtime: globalRuntime, isExperimentalCompile, expireTime } = renderOpts; + const { App } = extra; + let Document = extra.Document; + let Component = renderOpts.Component; + const OriginComponent = Component; + const isFallback = renderContext.isFallback ?? false; + const notFoundSrcPage = renderContext.developmentNotFoundSourcePage; + // next internal queries should be stripped out + (0, _internalutils.stripInternalQueries)(query); + const isSSG = !!getStaticProps; + const isBuildTimeSSG = isSSG && renderOpts.isBuildTimePrerendering; + const defaultAppGetInitialProps = App.getInitialProps === App.origGetInitialProps; + const hasPageGetInitialProps = !!(Component == null ? void 0 : Component.getInitialProps); + const hasPageScripts = Component == null ? void 0 : Component.unstable_scriptLoader; + const pageIsDynamic = (0, _isdynamic.isDynamicRoute)(pathname); + const defaultErrorGetInitialProps = pathname === '/_error' && Component.getInitialProps === Component.origGetInitialProps; + if (renderOpts.isBuildTimePrerendering && hasPageGetInitialProps && !defaultErrorGetInitialProps) { + warn(`Detected getInitialProps on page '${pathname}'` + ` while running export. It's recommended to use getStaticProps` + ` which has a more correct behavior for static exporting.` + `\nRead more: https://nextjs.org/docs/messages/get-initial-props-export`); + } + let isAutoExport = !hasPageGetInitialProps && defaultAppGetInitialProps && !isSSG && !getServerSideProps; + // if we are running from experimental compile and the page + // would normally be automatically statically optimized + // ensure we set cache header so it's not rendered on-demand + // every request + if (isAutoExport && !process.env.__NEXT_DEV_SERVER && isExperimentalCompile) { + res.setHeader('Cache-Control', (0, _cachecontrol.getCacheControlHeader)({ + revalidate: false, + expire: expireTime + })); + isAutoExport = false; + } + if (hasPageGetInitialProps && isSSG) { + throw new Error(_constants.SSG_GET_INITIAL_PROPS_CONFLICT + ` ${pathname}`); + } + if (hasPageGetInitialProps && getServerSideProps) { + throw new Error(_constants.SERVER_PROPS_GET_INIT_PROPS_CONFLICT + ` ${pathname}`); + } + if (getServerSideProps && isSSG) { + throw new Error(_constants.SERVER_PROPS_SSG_CONFLICT + ` ${pathname}`); + } + if (getServerSideProps && renderOpts.nextConfigOutput === 'export') { + throw new Error('getServerSideProps cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'); + } + if (getStaticPaths && !pageIsDynamic) { + throw new Error(`getStaticPaths is only allowed for dynamic SSG pages and was found on '${pathname}'.` + `\nRead more: https://nextjs.org/docs/messages/non-dynamic-getstaticpaths-usage`); + } + if (!!getStaticPaths && !isSSG) { + throw new Error(`getStaticPaths was added without a getStaticProps in ${pathname}. Without getStaticProps, getStaticPaths does nothing`); + } + if (isSSG && pageIsDynamic && !getStaticPaths) { + throw new Error(`getStaticPaths is required for dynamic SSG pages and is missing for '${pathname}'.` + `\nRead more: https://nextjs.org/docs/messages/invalid-getstaticpaths-value`); + } + let asPath = renderOpts.resolvedAsPath || req.url; + if (process.env.__NEXT_DEV_SERVER) { + const { isValidElementType } = require('next/dist/compiled/react-is'); + if (!isValidElementType(Component)) { + throw new Error(`The default export is not a React Component in page: "${pathname}"`); + } + if (!isValidElementType(App)) { + throw new Error(`The default export is not a React Component in page: "/_app"`); + } + if (!isValidElementType(Document)) { + throw new Error(`The default export is not a React Component in page: "/_document"`); + } + if (isAutoExport || isFallback) { + // remove query values except ones that will be set during export + query = {}; + asPath = `${pathname}${// ensure trailing slash is present for non-dynamic auto-export pages + req.url.endsWith('/') && pathname !== '/' && !pageIsDynamic ? '/' : ''}`; + req.url = pathname; + } + if (pathname === '/404' && (hasPageGetInitialProps || getServerSideProps)) { + throw new Error(`\`pages/404\` ${_constants.STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`); + } + if (_constants1.STATIC_STATUS_PAGES.includes(pathname) && (hasPageGetInitialProps || getServerSideProps)) { + throw new Error(`\`pages${pathname}\` ${_constants.STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`); + } + if (renderOpts == null ? void 0 : renderOpts.setIsrStatus) { + renderOpts.setIsrStatus(asPath, isSSG || isAutoExport); + } + } + for (const methodName of [ + 'getStaticProps', + 'getServerSideProps', + 'getStaticPaths' + ]){ + if (Component == null ? void 0 : Component[methodName]) { + throw new Error(`page ${pathname} ${methodName} ${_constants.GSSP_COMPONENT_MEMBER_ERROR}`); + } + } + await _loadablesharedruntime.default.preloadAll() // Make sure all dynamic imports are loaded + ; + let isPreview = undefined; + let previewData; + if ((isSSG || getServerSideProps) && !isFallback && process.env.NEXT_RUNTIME !== 'edge' && previewProps) { + // Reads of this are cached on the `req` object, so this should resolve + // instantly. There's no need to pass this data down from a previous + // invoke. + previewData = tryGetPreviewData(req, res, previewProps, !!renderOpts.multiZoneDraftMode); + isPreview = previewData !== false; + } + // url will always be set + const routerIsReady = !!(getServerSideProps || hasPageGetInitialProps || !defaultAppGetInitialProps && !isSSG || isExperimentalCompile); + const router = new ServerRouter(pathname, query, asPath, { + isFallback: isFallback + }, routerIsReady, basePath, renderOpts.locale, renderOpts.locales, renderOpts.defaultLocale, renderOpts.domainLocales, isPreview, (0, _requestmeta.getRequestMeta)(req, 'isLocaleDomain')); + const appRouter = (0, _adapters.adaptForAppRouterInstance)(router); + let scriptLoader = {}; + const jsxStyleRegistry = (0, _styledjsx.createStyleRegistry)(); + let head = (0, _head.defaultHead)(); + const reactLoadableModules = []; + let initialScripts = {}; + if (hasPageScripts) { + initialScripts.beforeInteractive = [].concat(hasPageScripts()).filter((script)=>script.props.strategy === 'beforeInteractive').map((script)=>script.props); + } + const csp = req.headers['content-security-policy'] || req.headers['content-security-policy-report-only']; + const nonce = typeof csp === 'string' ? (0, _getscriptnoncefromheader.getScriptNonceFromHeader)(csp) : undefined; + const AppContainer = ({ children })=>/*#__PURE__*/ (0, _jsxruntime.jsx)(_approutercontextsharedruntime.AppRouterContext.Provider, { + value: appRouter, + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_hooksclientcontextsharedruntime.SearchParamsContext.Provider, { + value: (0, _adapters.adaptForSearchParams)(router), + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_adapters.PathnameContextProviderAdapter, { + router: router, + isAutoExport: isAutoExport, + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_hooksclientcontextsharedruntime.PathParamsContext.Provider, { + value: (0, _adapters.adaptForPathParams)(router), + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_routercontextsharedruntime.RouterContext.Provider, { + value: router, + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_headmanagercontextsharedruntime.HeadManagerContext.Provider, { + value: { + updateHead: (state)=>{ + head = state; + }, + updateScripts: (scripts)=>{ + scriptLoader = scripts; + }, + scripts: initialScripts, + mountedInstances: new Set(), + nonce + }, + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_loadablecontextsharedruntime.LoadableContext.Provider, { + value: (moduleName)=>reactLoadableModules.push(moduleName), + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_styledjsx.StyleRegistry, { + registry: jsxStyleRegistry, + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_imageconfigcontextsharedruntime.ImageConfigContext.Provider, { + value: images, + children: children + }) + }) + }) + }) + }) + }) + }) + }) + }); + // The `useId` API uses the path indexes to generate an ID for each node. + // To guarantee the match of hydration, we need to ensure that the structure + // of wrapper nodes is isomorphic in server and client. + // TODO: With `enhanceApp` and `enhanceComponents` options, this approach may + // not be useful. + // https://github.com/facebook/react/pull/22644 + const Noop = ()=>null; + const AppContainerWithIsomorphicFiberStructure = ({ children })=>{ + return /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, { + children: [ + /*#__PURE__*/ (0, _jsxruntime.jsx)(Noop, {}), + /*#__PURE__*/ (0, _jsxruntime.jsx)(AppContainer, { + children: /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, { + children: [ + children, + /*#__PURE__*/ (0, _jsxruntime.jsx)(Noop, {}) + ] + }) + }) + ] + }); + }; + const ctx = { + err, + req: isAutoExport ? undefined : req, + res: isAutoExport ? undefined : res, + pathname, + query, + asPath, + locale: renderOpts.locale, + locales: renderOpts.locales, + defaultLocale: renderOpts.defaultLocale, + AppTree: (props)=>{ + return /*#__PURE__*/ (0, _jsxruntime.jsx)(AppContainerWithIsomorphicFiberStructure, { + children: renderPageTree(App, OriginComponent, { + ...props, + router + }) + }); + }, + defaultGetInitialProps: async (docCtx, options = {})=>{ + const enhanceApp = (AppComp)=>{ + return (props)=>/*#__PURE__*/ (0, _jsxruntime.jsx)(AppComp, { + ...props + }); + }; + const { html, head: renderPageHead } = await docCtx.renderPage({ + enhanceApp + }); + const styles = jsxStyleRegistry.styles({ + nonce: options.nonce || nonce + }); + jsxStyleRegistry.flush(); + return { + html, + head: renderPageHead, + styles + }; + } + }; + let props; + const nextExport = !isSSG && (renderOpts.isBuildTimePrerendering || process.env.__NEXT_DEV_SERVER && (isAutoExport || isFallback)); + const styledJsxInsertedHTML = ()=>{ + const styles = jsxStyleRegistry.styles(); + jsxStyleRegistry.flush(); + return /*#__PURE__*/ (0, _jsxruntime.jsx)(_jsxruntime.Fragment, { + children: styles + }); + }; + props = await (0, _utils.loadGetInitialProps)(App, { + AppTree: ctx.AppTree, + Component, + router, + ctx + }); + if ((isSSG || getServerSideProps) && isPreview) { + props.__N_PREVIEW = true; + } + if (isSSG) { + props[_constants1.STATIC_PROPS_ID] = true; + } + if (isSSG && !isFallback) { + let data; + try { + data = await (0, _tracer.getTracer)().trace(_constants2.RenderSpan.getStaticProps, { + spanName: `getStaticProps ${pathname}`, + attributes: { + 'next.route': pathname + } + }, ()=>getStaticProps({ + ...pageIsDynamic ? { + params + } : undefined, + ...isPreview ? { + draftMode: true, + preview: true, + previewData: previewData + } : undefined, + locales: [ + ...renderOpts.locales ?? [] + ], + locale: renderOpts.locale, + defaultLocale: renderOpts.defaultLocale, + revalidateReason: renderOpts.isOnDemandRevalidate ? 'on-demand' : isBuildTimeSSG ? 'build' : 'stale' + })); + } catch (staticPropsError) { + // remove not found error code to prevent triggering legacy + // 404 rendering + if (staticPropsError && staticPropsError.code === 'ENOENT') { + delete staticPropsError.code; + } + throw staticPropsError; + } + if (data == null) { + throw new Error(_constants.GSP_NO_RETURNED_VALUE); + } + const invalidKeys = Object.keys(data).filter((key)=>key !== 'revalidate' && key !== 'props' && key !== 'redirect' && key !== 'notFound'); + if (invalidKeys.includes('unstable_revalidate')) { + throw new Error(_constants.UNSTABLE_REVALIDATE_RENAME_ERROR); + } + if (invalidKeys.length) { + throw new Error(invalidKeysMsg('getStaticProps', invalidKeys)); + } + if (process.env.NODE_ENV !== 'production') { + if (typeof data.notFound !== 'undefined' && typeof data.redirect !== 'undefined') { + throw new Error(`\`redirect\` and \`notFound\` can not both be returned from ${isSSG ? 'getStaticProps' : 'getServerSideProps'} at the same time. Page: ${pathname}\nSee more info here: https://nextjs.org/docs/messages/gssp-mixed-not-found-redirect`); + } + } + if ('notFound' in data && data.notFound) { + if (pathname === '/404') { + throw new Error(`The /404 page can not return notFound in "getStaticProps", please remove it to continue!`); + } + metadata.isNotFound = true; + } + if ('redirect' in data && data.redirect && typeof data.redirect === 'object') { + checkRedirectValues(data.redirect, req, 'getStaticProps'); + if (isBuildTimeSSG) { + throw new Error(`\`redirect\` can not be returned from getStaticProps during prerendering (${req.url})\n` + `See more info here: https://nextjs.org/docs/messages/gsp-redirect-during-prerender`); + } + ; + data.props = { + __N_REDIRECT: data.redirect.destination, + __N_REDIRECT_STATUS: (0, _redirectstatus.getRedirectStatus)(data.redirect) + }; + if (typeof data.redirect.basePath !== 'undefined') { + ; + data.props.__N_REDIRECT_BASE_PATH = data.redirect.basePath; + } + metadata.isRedirect = true; + } + if ((process.env.__NEXT_DEV_SERVER || isBuildTimeSSG) && !metadata.isNotFound && !(0, _isserializableprops.isSerializableProps)(pathname, 'getStaticProps', data.props)) { + // this fn should throw an error instead of ever returning `false` + throw new Error('invariant: getStaticProps did not return valid props. Please report this.'); + } + let revalidate; + if ('revalidate' in data) { + if (data.revalidate && renderOpts.nextConfigOutput === 'export') { + throw new Error('ISR cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'); + } + if (typeof data.revalidate === 'number') { + if (!Number.isInteger(data.revalidate)) { + throw new Error(`A page's revalidate option must be seconds expressed as a natural number for ${req.url}. Mixed numbers, such as '${data.revalidate}', cannot be used.` + `\nTry changing the value to '${Math.ceil(data.revalidate)}' or using \`Math.ceil()\` if you're computing the value.`); + } else if (data.revalidate <= 0) { + throw new Error(`A page's revalidate option can not be less than or equal to zero for ${req.url}. A revalidate option of zero means to revalidate after _every_ request, and implies stale data cannot be tolerated.` + `\n\nTo never revalidate, you can set revalidate to \`false\` (only ran once at build-time).` + `\nTo revalidate as soon as possible, you can set the value to \`1\`.`); + } else { + if (data.revalidate > 31536000) { + // if it's greater than a year for some reason error + console.warn(`Warning: A page's revalidate option was set to more than a year for ${req.url}. This may have been done in error.` + `\nTo only run getStaticProps at build-time and not revalidate at runtime, you can set \`revalidate\` to \`false\`!`); + } + revalidate = data.revalidate; + } + } else if (data.revalidate === true) { + // When enabled, revalidate after 1 second. This value is optimal for + // the most up-to-date page possible, but without a 1-to-1 + // request-refresh ratio. + revalidate = 1; + } else if (data.revalidate === false || typeof data.revalidate === 'undefined') { + // By default, we never revalidate. + revalidate = false; + } else { + throw new Error(`A page's revalidate option must be seconds expressed as a natural number. Mixed numbers and strings cannot be used. Received '${JSON.stringify(data.revalidate)}' for ${req.url}`); + } + } else { + // By default, we never revalidate. + revalidate = false; + } + props.pageProps = Object.assign({}, props.pageProps, 'props' in data ? data.props : undefined); + // pass up cache control and props for export + metadata.cacheControl = { + revalidate, + expire: undefined + }; + metadata.pageData = props; + // this must come after revalidate is added to renderResultMeta + if (metadata.isNotFound) { + return new _renderresult.default(null, { + metadata, + contentType: null + }); + } + } + if (getServerSideProps) { + props[_constants1.SERVER_PROPS_ID] = true; + } + if (getServerSideProps && !isFallback) { + let data; + let canAccessRes = true; + let resOrProxy = res; + let deferredContent = false; + if (process.env.NODE_ENV !== 'production') { + resOrProxy = new Proxy(res, { + get: function(obj, prop) { + if (!canAccessRes) { + const message = `You should not access 'res' after getServerSideProps resolves.` + `\nRead more: https://nextjs.org/docs/messages/gssp-no-mutating-res`; + if (deferredContent) { + throw new Error(message); + } else { + warn(message); + } + } + if (typeof prop === 'symbol') { + return _reflect.ReflectAdapter.get(obj, prop, res); + } + return _reflect.ReflectAdapter.get(obj, prop, res); + } + }); + } + try { + data = await (0, _tracer.getTracer)().trace(_constants2.RenderSpan.getServerSideProps, { + spanName: `getServerSideProps ${pathname}`, + attributes: { + 'next.route': pathname + } + }, async ()=>getServerSideProps({ + req: req, + res: resOrProxy, + query, + resolvedUrl: renderOpts.resolvedUrl, + ...pageIsDynamic ? { + params + } : undefined, + ...previewData !== false ? { + draftMode: true, + preview: true, + previewData: previewData + } : undefined, + // We create a copy here to avoid having the types of + // `getServerSideProps` change. This ensures that users can't + // mutate this array and have it poison the reference. + locales: [ + ...renderOpts.locales ?? [] + ], + locale: renderOpts.locale, + defaultLocale: renderOpts.defaultLocale + })); + canAccessRes = false; + metadata.cacheControl = { + revalidate: 0, + expire: undefined + }; + } catch (serverSidePropsError) { + // remove not found error code to prevent triggering legacy + // 404 rendering + if ((0, _iserror.default)(serverSidePropsError) && serverSidePropsError.code === 'ENOENT') { + delete serverSidePropsError.code; + } + throw serverSidePropsError; + } + if (data == null) { + throw new Error(_constants.GSSP_NO_RETURNED_VALUE); + } + if (data.props instanceof Promise) { + deferredContent = true; + } + const invalidKeys = Object.keys(data).filter((key)=>key !== 'props' && key !== 'redirect' && key !== 'notFound'); + if (data.unstable_notFound) { + throw new Error(`unstable_notFound has been renamed to notFound, please update the field to continue. Page: ${pathname}`); + } + if (data.unstable_redirect) { + throw new Error(`unstable_redirect has been renamed to redirect, please update the field to continue. Page: ${pathname}`); + } + if (invalidKeys.length) { + throw new Error(invalidKeysMsg('getServerSideProps', invalidKeys)); + } + if ('notFound' in data && data.notFound) { + if (pathname === '/404') { + throw new Error(`The /404 page can not return notFound in "getStaticProps", please remove it to continue!`); + } + metadata.isNotFound = true; + return new _renderresult.default(null, { + metadata, + contentType: null + }); + } + if ('redirect' in data && typeof data.redirect === 'object') { + checkRedirectValues(data.redirect, req, 'getServerSideProps'); + data.props = { + __N_REDIRECT: data.redirect.destination, + __N_REDIRECT_STATUS: (0, _redirectstatus.getRedirectStatus)(data.redirect) + }; + if (typeof data.redirect.basePath !== 'undefined') { + ; + data.props.__N_REDIRECT_BASE_PATH = data.redirect.basePath; + } + metadata.isRedirect = true; + } + if (deferredContent) { + ; + data.props = await data.props; + } + if ((process.env.__NEXT_DEV_SERVER || isBuildTimeSSG) && !(0, _isserializableprops.isSerializableProps)(pathname, 'getServerSideProps', data.props)) { + // this fn should throw an error instead of ever returning `false` + throw new Error('invariant: getServerSideProps did not return valid props. Please report this.'); + } + props.pageProps = Object.assign({}, props.pageProps, data.props); + metadata.pageData = props; + } + if (!isSSG && // we only show this warning for legacy pages + !getServerSideProps && process.env.NODE_ENV !== 'production' && Object.keys((props == null ? void 0 : props.pageProps) || {}).includes('url')) { + console.warn(`The prop \`url\` is a reserved prop in Next.js for legacy reasons and will be overridden on page ${pathname}\n` + `See more info here: https://nextjs.org/docs/messages/reserved-page-prop`); + } + // Avoid rendering page un-necessarily for getServerSideProps data request + // and getServerSideProps/getStaticProps redirects + if (isNextDataRequest && !isSSG || metadata.isRedirect) { + return new _renderresult.default(JSON.stringify(props), { + metadata, + contentType: _constants.JSON_CONTENT_TYPE_HEADER + }); + } + // We don't call getStaticProps or getServerSideProps while generating + // the fallback so make sure to set pageProps to an empty object + if (isFallback) { + props.pageProps = {}; + } + // the response might be finished on the getInitialProps call + if ((0, _utils.isResSent)(res) && !isSSG) return _renderresult.default.EMPTY; + // we preload the buildManifest for auto-export dynamic pages + // to speed up hydrating query values + let filteredBuildManifest = buildManifest; + if (isAutoExport && pageIsDynamic) { + const page = (0, _denormalizepagepath.denormalizePagePath)((0, _normalizepagepath.normalizePagePath)(pathname)); + // This code would be much cleaner using `immer` and directly pushing into + // the result from `getPageFiles`, we could maybe consider that in the + // future. + if (page in filteredBuildManifest.pages) { + filteredBuildManifest = { + ...filteredBuildManifest, + pages: { + ...filteredBuildManifest.pages, + [page]: [ + ...filteredBuildManifest.pages[page], + ...filteredBuildManifest.lowPriorityFiles.filter((f)=>f.includes('_buildManifest')) + ] + }, + lowPriorityFiles: filteredBuildManifest.lowPriorityFiles.filter((f)=>!f.includes('_buildManifest')) + }; + } + } + const Body = ({ children })=>{ + return /*#__PURE__*/ (0, _jsxruntime.jsx)("div", { + id: "__next", + children: children + }); + }; + const renderDocument = async ()=>{ + // For `Document`, there are two cases that we don't support: + // 1. Using `Document.getInitialProps` in the Edge runtime. + // 2. Using the class component `Document` with concurrent features. + const BuiltinFunctionalDocument = Document[_constants1.NEXT_BUILTIN_DOCUMENT]; + if (process.env.NEXT_RUNTIME === 'edge' && Document.getInitialProps) { + // In the Edge runtime, `Document.getInitialProps` isn't supported. + // We throw an error here if it's customized. + if (BuiltinFunctionalDocument) { + Document = BuiltinFunctionalDocument; + } else { + throw new Error('`getInitialProps` in Document component is not supported with the Edge Runtime.'); + } + } + async function loadDocumentInitialProps(renderShell) { + const renderPage = async (options = {})=>{ + if (ctx.err && ErrorDebug) { + // Always start rendering the shell even if there's an error. + if (renderShell) { + renderShell(App, Component); + } + const html = await renderToString(/*#__PURE__*/ (0, _jsxruntime.jsx)(Body, { + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(ErrorDebug, {}) + })); + return { + html, + head + }; + } + if (process.env.__NEXT_DEV_SERVER && (props.router || props.Component)) { + throw new Error(`'router' and 'Component' can not be returned in getInitialProps from _app.js https://nextjs.org/docs/messages/cant-override-next-props`); + } + const { App: EnhancedApp, Component: EnhancedComponent } = enhanceComponents(options, App, Component); + const stream = await renderShell(EnhancedApp, EnhancedComponent); + await stream.allReady; + const html = await (0, _nodewebstreamshelper.streamToString)(stream); + return { + html, + head + }; + }; + const documentCtx = { + ...ctx, + renderPage + }; + const docProps = await (0, _utils.loadGetInitialProps)(Document, documentCtx); + // the response might be finished on the getInitialProps call + if ((0, _utils.isResSent)(res) && !isSSG) return null; + if (!docProps || typeof docProps.html !== 'string') { + const message = `"${(0, _utils.getDisplayName)(Document)}.getInitialProps()" should resolve to an object with a "html" prop set with a valid html string`; + throw new Error(message); + } + return { + docProps, + documentCtx + }; + } + const renderContent = (_App, _Component)=>{ + const EnhancedApp = _App || App; + const EnhancedComponent = _Component || Component; + return ctx.err && ErrorDebug ? /*#__PURE__*/ (0, _jsxruntime.jsx)(Body, { + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(ErrorDebug, {}) + }) : /*#__PURE__*/ (0, _jsxruntime.jsx)(Body, { + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(AppContainerWithIsomorphicFiberStructure, { + children: renderPageTree(EnhancedApp, EnhancedComponent, { + ...props, + router + }) + }) + }); + }; + // Always using react concurrent rendering mode with required react version 18.x + const renderShell = async (EnhancedApp, EnhancedComponent)=>{ + const content = renderContent(EnhancedApp, EnhancedComponent); + return await (0, _nodewebstreamshelper.renderToInitialFizzStream)({ + ReactDOMServer: _ReactDOMServerPages.default, + element: content + }); + }; + const hasDocumentGetInitialProps = process.env.NEXT_RUNTIME !== 'edge' && !!Document.getInitialProps; + // If it has getInitialProps, we will render the shell in `renderPage`. + // Otherwise we do it right now. + let documentInitialPropsRes; + let content; + if (hasDocumentGetInitialProps) { + documentInitialPropsRes = await loadDocumentInitialProps(renderShell); + if (documentInitialPropsRes === null) { + content = null; + } else { + const { docProps } = documentInitialPropsRes; + content = docProps.html; + } + } else { + documentInitialPropsRes = {}; + const stream = await renderShell(App, Component); + await stream.allReady; + content = await (0, _nodewebstreamshelper.streamToString)(stream); + } + // @ts-ignore: documentInitialPropsRes is set + const { docProps } = documentInitialPropsRes || {}; + const documentElement = (htmlProps)=>{ + if (process.env.NEXT_RUNTIME === 'edge') { + return Document(); + } else { + return /*#__PURE__*/ (0, _jsxruntime.jsx)(Document, { + ...htmlProps, + ...docProps + }); + } + }; + let styles; + if (hasDocumentGetInitialProps) { + styles = docProps.styles; + head = docProps.head; + } else { + styles = jsxStyleRegistry.styles(); + jsxStyleRegistry.flush(); + } + // Registry is now flushed; rawStyledJsxInsertedHTML will be empty. + const rawStyledJsxInsertedHTML = await renderToString(styledJsxInsertedHTML()); + if (content === null) { + return null; + } + const contentHTML = rawStyledJsxInsertedHTML + content; + return { + contentHTML, + documentElement, + head, + headTags: [], + styles + }; + }; + (0, _tracer.getTracer)().setRootSpanAttribute('next.route', renderOpts.page); + const documentResult = await (0, _tracer.getTracer)().trace(_constants2.RenderSpan.renderDocument, { + spanName: `render route (pages) ${renderOpts.page}`, + attributes: { + 'next.route': renderOpts.page + } + }, async ()=>renderDocument()); + if (!documentResult) { + return new _renderresult.default(null, { + metadata, + contentType: _constants.HTML_CONTENT_TYPE_HEADER + }); + } + const dynamicImportsIds = new Set(); + const dynamicImports = new Set(); + for (const mod of reactLoadableModules){ + const manifestItem = reactLoadableManifest[mod]; + if (manifestItem) { + dynamicImportsIds.add(manifestItem.id); + manifestItem.files.forEach((item)=>{ + dynamicImports.add(item); + }); + } + } + const docComponentsRendered = {}; + const { assetPrefix, defaultLocale, disableOptimizedLoading, domainLocales, locale, locales } = renderOpts; + const htmlProps = { + __NEXT_DATA__: { + props, + page: pathname, + query, + buildId: sharedContext.buildId, + assetPrefix: assetPrefix === '' ? undefined : assetPrefix, + nextExport: nextExport === true ? true : undefined, + autoExport: isAutoExport === true ? true : undefined, + isFallback, + isExperimentalCompile, + dynamicIds: dynamicImportsIds.size === 0 ? undefined : Array.from(dynamicImportsIds), + err: renderOpts.err ? serializeError(!!process.env.__NEXT_DEV_SERVER, renderOpts.err) : undefined, + gsp: !!getStaticProps ? true : undefined, + gssp: !!getServerSideProps ? true : undefined, + customServer: sharedContext.customServer, + gip: hasPageGetInitialProps ? true : undefined, + appGip: !defaultAppGetInitialProps ? true : undefined, + locale, + locales, + defaultLocale, + domainLocales, + isPreview: isPreview === true ? true : undefined, + notFoundSrcPage: notFoundSrcPage && process.env.__NEXT_DEV_SERVER ? notFoundSrcPage : undefined + }, + nonce, + buildManifest: filteredBuildManifest, + docComponentsRendered, + dangerousAsPath: router.asPath, + isDevelopment: !!process.env.__NEXT_DEV_SERVER, + deploymentId: sharedContext.deploymentId, + dynamicImports: Array.from(dynamicImports), + dynamicCssManifest: new Set(renderOpts.dynamicCssManifest || []), + assetPrefix, + // Only enabled in production as development mode has features relying on HMR (style injection for example) + unstable_runtimeJS: process.env.NODE_ENV === 'production' ? pageConfig.unstable_runtimeJS : undefined, + unstable_JsPreload: pageConfig.unstable_JsPreload, + assetQueryString, + cssAssetQueryString, + mutableAssetQueryString, + scriptLoader, + locale, + disableOptimizedLoading, + head: documentResult.head, + headTags: documentResult.headTags, + styles: documentResult.styles, + crossOrigin: renderOpts.crossOrigin, + optimizeCss: renderOpts.optimizeCss, + nextConfigOutput: renderOpts.nextConfigOutput, + nextScriptWorkers: renderOpts.nextScriptWorkers, + runtime: globalRuntime, + largePageDataBytes: renderOpts.largePageDataBytes, + nextFontManifest: renderOpts.nextFontManifest, + experimentalClientTraceMetadata: renderOpts.experimental.clientTraceMetadata + }; + const document = /*#__PURE__*/ (0, _jsxruntime.jsx)(_htmlcontextsharedruntime.HtmlContext.Provider, { + value: htmlProps, + children: documentResult.documentElement(htmlProps) + }); + const documentHTML = await (0, _tracer.getTracer)().trace(_constants2.RenderSpan.renderToString, async ()=>renderToString(document)); + if (process.env.NODE_ENV !== 'production') { + const nonRenderedComponents = []; + const expectedDocComponents = [ + 'Main', + 'Head', + 'NextScript', + 'Html' + ]; + for (const comp of expectedDocComponents){ + if (!docComponentsRendered[comp]) { + nonRenderedComponents.push(comp); + } + } + if (nonRenderedComponents.length) { + const missingComponentList = nonRenderedComponents.map((e)=>`<${e} />`).join(', '); + const plural = nonRenderedComponents.length !== 1 ? 's' : ''; + console.warn(`Your custom Document (pages/_document) did not render all the required subcomponent${plural}.\n` + `Missing component${plural}: ${missingComponentList}\n` + 'Read how to fix here: https://nextjs.org/docs/messages/missing-document-component'); + } + } + const [renderTargetPrefix, renderTargetSuffix] = documentHTML.split('', 2); + let prefix = ''; + if (!documentHTML.startsWith(DOCTYPE)) { + prefix += DOCTYPE; + } + prefix += renderTargetPrefix; + const content = prefix + documentResult.contentHTML + renderTargetSuffix; + const optimizedHtml = await postProcessHTML(content, renderOpts); + return new _renderresult.default(optimizedHtml, { + metadata, + contentType: _constants.HTML_CONTENT_TYPE_HEADER + }); +} +const renderToHTML = (req, res, pathname, query, renderOpts, sharedContext, renderContext)=>{ + return renderToHTMLImpl(req, res, pathname, query, renderOpts, renderOpts, sharedContext, renderContext); +}; + +//# sourceMappingURL=render.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/render.js.map b/e-commerce/node_modules/next/dist/server/render.js.map new file mode 100644 index 0000000000000000000000000000000000000000..80ef017301e2f10ad8e3068166c3fc1484731bb5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/render.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/render.tsx"],"sourcesContent":["/* eslint-disable @next/internal/no-ambiguous-jsx -- Pages router doesn't use react-server */\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { ReactDOMServerReadableStream } from 'react-dom/server'\nimport type { NextRouter } from '../shared/lib/router/router'\nimport type { HtmlProps } from '../shared/lib/html-context.shared-runtime'\nimport type { DomainLocale } from './config'\nimport type {\n AppType,\n DocumentInitialProps,\n DocumentType,\n DocumentProps,\n DocumentContext,\n NextComponentType,\n RenderPage,\n RenderPageResult,\n} from '../shared/lib/utils'\nimport type { ImageConfigComplete } from '../shared/lib/image-config'\nimport type { Redirect } from '../lib/load-custom-routes'\nimport {\n type NextApiRequestCookies,\n type __ApiPreviewProps,\n setLazyProp,\n} from './api-utils'\nimport { getCookieParser } from './api-utils/get-cookie-parser'\nimport type { LoadComponentsReturnType } from './load-components'\nimport type {\n GetServerSideProps,\n GetStaticProps,\n PreviewData,\n ServerRuntime,\n SizeLimit,\n} from '../types'\nimport type { UnwrapPromise } from '../lib/coalesced-function'\nimport type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'\nimport type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'\nimport type { PagesModule } from './route-modules/pages/module'\nimport type { ComponentsEnhancer } from '../shared/lib/utils'\nimport type { NextParsedUrlQuery } from './request-meta'\nimport type { Revalidate } from './lib/cache-control'\nimport type { COMPILER_NAMES } from '../shared/lib/constants'\n\nimport React, { type JSX } from 'react'\nimport ReactDOMServerPages from 'next/dist/server/ReactDOMServerPages'\nimport { StyleRegistry, createStyleRegistry } from 'styled-jsx'\nimport {\n GSP_NO_RETURNED_VALUE,\n GSSP_COMPONENT_MEMBER_ERROR,\n GSSP_NO_RETURNED_VALUE,\n STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR,\n SERVER_PROPS_GET_INIT_PROPS_CONFLICT,\n SERVER_PROPS_SSG_CONFLICT,\n SSG_GET_INITIAL_PROPS_CONFLICT,\n UNSTABLE_REVALIDATE_RENAME_ERROR,\n HTML_CONTENT_TYPE_HEADER,\n JSON_CONTENT_TYPE_HEADER,\n} from '../lib/constants'\nimport {\n NEXT_BUILTIN_DOCUMENT,\n SERVER_PROPS_ID,\n STATIC_PROPS_ID,\n STATIC_STATUS_PAGES,\n} from '../shared/lib/constants'\nimport { isSerializableProps } from '../lib/is-serializable-props'\nimport { defaultHead } from '../shared/lib/head'\nimport { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime'\nimport Loadable from '../shared/lib/loadable.shared-runtime'\nimport { LoadableContext } from '../shared/lib/loadable-context.shared-runtime'\nimport { RouterContext } from '../shared/lib/router-context.shared-runtime'\nimport { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'\nimport {\n getDisplayName,\n isResSent,\n loadGetInitialProps,\n} from '../shared/lib/utils'\nimport { HtmlContext } from '../shared/lib/html-context.shared-runtime'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'\nimport { getRequestMeta } from './request-meta'\nimport { allowedStatusCodes, getRedirectStatus } from '../lib/redirect-status'\nimport RenderResult, { type PagesRenderResultMetadata } from './render-result'\nimport isError from '../lib/is-error'\nimport {\n streamToString,\n renderToInitialFizzStream,\n} from './stream-utils/node-web-streams-helper'\nimport { ImageConfigContext } from '../shared/lib/image-config-context.shared-runtime'\nimport stripAnsi from 'next/dist/compiled/strip-ansi'\nimport { stripInternalQueries } from './internal-utils'\nimport {\n adaptForAppRouterInstance,\n adaptForPathParams,\n adaptForSearchParams,\n PathnameContextProviderAdapter,\n} from '../shared/lib/router/adapters'\nimport { AppRouterContext } from '../shared/lib/app-router-context.shared-runtime'\nimport {\n SearchParamsContext,\n PathParamsContext,\n} from '../shared/lib/hooks-client-context.shared-runtime'\nimport { getTracer } from './lib/trace/tracer'\nimport { RenderSpan } from './lib/trace/constants'\nimport { ReflectAdapter } from './web/spec-extension/adapters/reflect'\nimport { getCacheControlHeader } from './lib/cache-control'\nimport { getErrorSource } from '../shared/lib/error-source'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport { getScriptNonceFromHeader } from './app-render/get-script-nonce-from-header'\n\nlet tryGetPreviewData: typeof import('./api-utils/node/try-get-preview-data').tryGetPreviewData\nlet warn: typeof import('../build/output/log').warn\nlet postProcessHTML: typeof import('./post-process').postProcessHTML\n\nconst DOCTYPE = ''\n\nif (process.env.NEXT_RUNTIME !== 'edge') {\n tryGetPreviewData = (\n require('./api-utils/node/try-get-preview-data') as typeof import('./api-utils/node/try-get-preview-data')\n ).tryGetPreviewData\n warn = (\n require('../build/output/log') as typeof import('../build/output/log')\n ).warn\n postProcessHTML = (\n require('./post-process') as typeof import('./post-process')\n ).postProcessHTML\n} else {\n warn = console.warn.bind(console)\n postProcessHTML = async (html: string) => html\n}\n\nfunction noRouter() {\n const message =\n 'No router instance found. you should only use \"next/router\" inside the client side of your app. https://nextjs.org/docs/messages/no-router-instance'\n throw new Error(message)\n}\n\nasync function renderToString(element: React.ReactElement) {\n const renderStream = await ReactDOMServerPages.renderToReadableStream(element)\n await renderStream.allReady\n return streamToString(renderStream)\n}\n\nclass ServerRouter implements NextRouter {\n route: string\n pathname: string\n query: ParsedUrlQuery\n asPath: string\n basePath: string\n events: any\n isFallback: boolean\n locale?: string\n isReady: boolean\n locales?: readonly string[]\n defaultLocale?: string\n domainLocales?: readonly DomainLocale[]\n isPreview: boolean\n isLocaleDomain: boolean\n\n constructor(\n pathname: string,\n query: ParsedUrlQuery,\n as: string,\n { isFallback }: { isFallback: boolean },\n isReady: boolean,\n basePath: string,\n locale?: string,\n locales?: readonly string[],\n defaultLocale?: string,\n domainLocales?: readonly DomainLocale[],\n isPreview?: boolean,\n isLocaleDomain?: boolean\n ) {\n this.route = pathname.replace(/\\/$/, '') || '/'\n this.pathname = pathname\n this.query = query\n this.asPath = as\n this.isFallback = isFallback\n this.basePath = basePath\n this.locale = locale\n this.locales = locales\n this.defaultLocale = defaultLocale\n this.isReady = isReady\n this.domainLocales = domainLocales\n this.isPreview = !!isPreview\n this.isLocaleDomain = !!isLocaleDomain\n }\n\n push(): any {\n noRouter()\n }\n replace(): any {\n noRouter()\n }\n reload() {\n noRouter()\n }\n back() {\n noRouter()\n }\n forward(): void {\n noRouter()\n }\n prefetch(): any {\n noRouter()\n }\n beforePopState() {\n noRouter()\n }\n}\n\nfunction enhanceComponents(\n options: ComponentsEnhancer,\n App: AppType,\n Component: NextComponentType\n): {\n App: AppType\n Component: NextComponentType\n} {\n // For backwards compatibility\n if (typeof options === 'function') {\n return {\n App,\n Component: options(Component),\n }\n }\n\n return {\n App: options.enhanceApp ? options.enhanceApp(App) : App,\n Component: options.enhanceComponent\n ? options.enhanceComponent(Component)\n : Component,\n }\n}\n\nfunction renderPageTree(\n App: AppType,\n Component: NextComponentType,\n props: any\n) {\n return \n}\n\nexport type RenderOptsPartial = {\n assetPrefix?: string\n err?: Error | null\n isBuildTimePrerendering?: boolean\n ErrorDebug?: PagesDevOverlayBridgeType\n isNextDataRequest?: boolean\n params?: ParsedUrlQuery\n previewProps: __ApiPreviewProps | undefined\n basePath: string\n unstable_runtimeJS?: false\n unstable_JsPreload?: false\n optimizeCss: any\n nextConfigOutput?: 'standalone' | 'export'\n nextScriptWorkers: any\n resolvedUrl?: string\n resolvedAsPath?: string\n setIsrStatus?: (key: string, value: boolean | undefined) => void\n clientReferenceManifest?: DeepReadonly\n nextFontManifest?: DeepReadonly\n distDir?: string\n locale?: string\n locales?: readonly string[]\n defaultLocale?: string\n domainLocales?: readonly DomainLocale[]\n disableOptimizedLoading?: boolean\n supportsDynamicResponse: boolean\n botType?: 'dom' | 'html' | undefined\n serveStreamingMetadata?: boolean\n runtime?: ServerRuntime\n serverComponents?: boolean\n serverActions?: {\n bodySizeLimit?: SizeLimit\n allowedOrigins?: string[]\n }\n crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined\n images: ImageConfigComplete\n largePageDataBytes?: number\n isOnDemandRevalidate?: boolean\n isPossibleServerAction?: boolean\n isExperimentalCompile?: boolean\n isPrefetch?: boolean\n isBot?: boolean\n expireTime?: number\n experimental: {\n clientTraceMetadata?: string[]\n }\n}\n\nexport type RenderOpts = LoadComponentsReturnType &\n RenderOptsPartial\n\n/**\n * Shared context used for all page renders.\n */\nexport type PagesSharedContext = {\n /**\n * Used to facilitate caching of page bundles, we send it to the client so\n * that pageloader knows where to load bundles.\n */\n buildId: string\n\n /**\n * See NextConfig.deploymentId\n */\n deploymentId: string | undefined\n\n /**\n * NextConfig.deploymentId if supportsImmutableAssets is not true, otherwise undefined.\n */\n clientAssetToken: string | undefined\n\n /**\n * True if the user is using a custom server.\n */\n customServer: true | undefined\n}\n\n/**\n * The context for the given request.\n */\nexport type PagesRenderContext = {\n /**\n * Whether this should be rendered as a fallback page.\n */\n isFallback: boolean\n\n /**\n * Whether this is in draft mode.\n */\n isDraftMode: boolean | undefined\n\n /**\n * In development, the original source page that returned a 404.\n */\n developmentNotFoundSourcePage: string | undefined\n}\n\n/**\n * RenderOptsExtra is being used to split away functionality that's within the\n * renderOpts. Eventually we can have more explicit render options for each\n * route kind.\n */\nexport type RenderOptsExtra = {\n App: AppType\n Document: DocumentType\n}\n\nconst invalidKeysMsg = (\n methodName: 'getServerSideProps' | 'getStaticProps',\n invalidKeys: string[]\n) => {\n const docsPathname = `invalid-${methodName.toLocaleLowerCase()}-value`\n\n return (\n `Additional keys were returned from \\`${methodName}\\`. Properties intended for your component must be nested under the \\`props\\` key, e.g.:` +\n `\\n\\n\\treturn { props: { title: 'My Title', content: '...' } }` +\n `\\n\\nKeys that need to be moved: ${invalidKeys.join(', ')}.` +\n `\\nRead more: https://nextjs.org/docs/messages/${docsPathname}`\n )\n}\n\nfunction checkRedirectValues(\n redirect: Redirect,\n req: IncomingMessage,\n method: 'getStaticProps' | 'getServerSideProps'\n) {\n const { destination, permanent, statusCode, basePath } = redirect\n let errors: string[] = []\n\n const hasStatusCode = typeof statusCode !== 'undefined'\n const hasPermanent = typeof permanent !== 'undefined'\n\n if (hasPermanent && hasStatusCode) {\n errors.push(`\\`permanent\\` and \\`statusCode\\` can not both be provided`)\n } else if (hasPermanent && typeof permanent !== 'boolean') {\n errors.push(`\\`permanent\\` must be \\`true\\` or \\`false\\``)\n } else if (hasStatusCode && !allowedStatusCodes.has(statusCode!)) {\n errors.push(\n `\\`statusCode\\` must undefined or one of ${[...allowedStatusCodes].join(\n ', '\n )}`\n )\n }\n const destinationType = typeof destination\n\n if (destinationType !== 'string') {\n errors.push(\n `\\`destination\\` should be string but received ${destinationType}`\n )\n }\n\n const basePathType = typeof basePath\n\n if (basePathType !== 'undefined' && basePathType !== 'boolean') {\n errors.push(\n `\\`basePath\\` should be undefined or a false, received ${basePathType}`\n )\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid redirect object returned from ${method} for ${req.url}\\n` +\n errors.join(' and ') +\n '\\n' +\n `See more info here: https://nextjs.org/docs/messages/invalid-redirect-gssp`\n )\n }\n}\n\nexport function errorToJSON(err: Error) {\n let source: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer =\n 'server'\n\n if (process.env.NEXT_RUNTIME !== 'edge') {\n source = getErrorSource(err) || 'server'\n }\n\n return {\n name: err.name,\n source,\n message: stripAnsi(err.message),\n stack: err.stack,\n digest: (err as any).digest,\n }\n}\n\nfunction serializeError(\n dev: boolean | undefined,\n err: Error\n): Error & {\n statusCode?: number\n source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer\n} {\n if (dev) {\n return errorToJSON(err)\n }\n\n return {\n name: 'Internal Server Error.',\n message: '500 - Internal Server Error.',\n statusCode: 500,\n }\n}\n\nfunction getSafariCacheBusterQueryString(req: IncomingMessage): string {\n if (process.env.__NEXT_DEV_SERVER) {\n const userAgent = (req.headers['user-agent'] || '').toLowerCase()\n if (userAgent.includes('safari') && !userAgent.includes('chrome')) {\n return `?ts=${Date.now()}`\n }\n }\n return ''\n}\n\nexport async function renderToHTMLImpl(\n req: IncomingMessage,\n res: ServerResponse,\n pathname: string,\n query: NextParsedUrlQuery,\n renderOpts: Omit,\n extra: RenderOptsExtra,\n sharedContext: PagesSharedContext,\n renderContext: PagesRenderContext\n): Promise {\n // Adds support for reading `cookies` in `getServerSideProps` when SSR.\n setLazyProp({ req: req as any }, 'cookies', getCookieParser(req.headers))\n\n // cssCacheBuster is a workaround for a Safari bug\n // (https://bugs.webkit.org/show_bug.cgi?id=187726) where preloaded CSS\n // resources are cached and not re-fetched on HMR. It must only be applied\n // to CSS and font assets — not to script tags — because the Turbopack\n // runtime infers ASSET_SUFFIX from the executing script's query string and\n // leaks it onto all static asset URLs (including images), causing\n // next/image validation errors.\n // See https://github.com/vercel/next.js/issues/92118.\n const cssCacheBuster = getSafariCacheBusterQueryString(req)\n\n const mutableAssetQueryString = sharedContext.deploymentId\n ? `?dpl=${sharedContext.deploymentId}`\n : ''\n const assetQueryString = sharedContext.clientAssetToken\n ? `?dpl=${sharedContext.clientAssetToken}`\n : ''\n // cssAssetQueryString is assetQueryString with the cacheBuster prepended.\n // Use this for CSS and font URLs; use assetQueryString for script URLs.\n const cssAssetQueryString =\n cssCacheBuster +\n (sharedContext.clientAssetToken\n ? `${cssCacheBuster ? '&' : '?'}dpl=${sharedContext.clientAssetToken}`\n : '')\n const metadata: PagesRenderResultMetadata = {}\n\n // don't modify original query object\n query = Object.assign({}, query)\n\n const {\n err,\n pageConfig = {},\n buildManifest,\n reactLoadableManifest,\n ErrorDebug,\n getStaticProps,\n getStaticPaths,\n getServerSideProps,\n isNextDataRequest,\n params,\n previewProps,\n basePath,\n images,\n runtime: globalRuntime,\n isExperimentalCompile,\n expireTime,\n } = renderOpts\n const { App } = extra\n\n let Document = extra.Document\n\n let Component: React.ComponentType<{}> | ((props: any) => JSX.Element) =\n renderOpts.Component\n const OriginComponent = Component\n\n const isFallback = renderContext.isFallback ?? false\n const notFoundSrcPage = renderContext.developmentNotFoundSourcePage\n\n // next internal queries should be stripped out\n stripInternalQueries(query)\n\n const isSSG = !!getStaticProps\n const isBuildTimeSSG = isSSG && renderOpts.isBuildTimePrerendering\n const defaultAppGetInitialProps =\n App.getInitialProps === (App as any).origGetInitialProps\n\n const hasPageGetInitialProps = !!(Component as any)?.getInitialProps\n const hasPageScripts = (Component as any)?.unstable_scriptLoader\n\n const pageIsDynamic = isDynamicRoute(pathname)\n\n const defaultErrorGetInitialProps =\n pathname === '/_error' &&\n (Component as any).getInitialProps ===\n (Component as any).origGetInitialProps\n\n if (\n renderOpts.isBuildTimePrerendering &&\n hasPageGetInitialProps &&\n !defaultErrorGetInitialProps\n ) {\n warn(\n `Detected getInitialProps on page '${pathname}'` +\n ` while running export. It's recommended to use getStaticProps` +\n ` which has a more correct behavior for static exporting.` +\n `\\nRead more: https://nextjs.org/docs/messages/get-initial-props-export`\n )\n }\n\n let isAutoExport =\n !hasPageGetInitialProps &&\n defaultAppGetInitialProps &&\n !isSSG &&\n !getServerSideProps\n\n // if we are running from experimental compile and the page\n // would normally be automatically statically optimized\n // ensure we set cache header so it's not rendered on-demand\n // every request\n if (isAutoExport && !process.env.__NEXT_DEV_SERVER && isExperimentalCompile) {\n res.setHeader(\n 'Cache-Control',\n getCacheControlHeader({ revalidate: false, expire: expireTime })\n )\n isAutoExport = false\n }\n\n if (hasPageGetInitialProps && isSSG) {\n throw new Error(SSG_GET_INITIAL_PROPS_CONFLICT + ` ${pathname}`)\n }\n\n if (hasPageGetInitialProps && getServerSideProps) {\n throw new Error(SERVER_PROPS_GET_INIT_PROPS_CONFLICT + ` ${pathname}`)\n }\n\n if (getServerSideProps && isSSG) {\n throw new Error(SERVER_PROPS_SSG_CONFLICT + ` ${pathname}`)\n }\n\n if (getServerSideProps && renderOpts.nextConfigOutput === 'export') {\n throw new Error(\n 'getServerSideProps cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n\n if (getStaticPaths && !pageIsDynamic) {\n throw new Error(\n `getStaticPaths is only allowed for dynamic SSG pages and was found on '${pathname}'.` +\n `\\nRead more: https://nextjs.org/docs/messages/non-dynamic-getstaticpaths-usage`\n )\n }\n\n if (!!getStaticPaths && !isSSG) {\n throw new Error(\n `getStaticPaths was added without a getStaticProps in ${pathname}. Without getStaticProps, getStaticPaths does nothing`\n )\n }\n\n if (isSSG && pageIsDynamic && !getStaticPaths) {\n throw new Error(\n `getStaticPaths is required for dynamic SSG pages and is missing for '${pathname}'.` +\n `\\nRead more: https://nextjs.org/docs/messages/invalid-getstaticpaths-value`\n )\n }\n\n let asPath: string = renderOpts.resolvedAsPath || (req.url as string)\n\n if (process.env.__NEXT_DEV_SERVER) {\n const { isValidElementType } =\n require('next/dist/compiled/react-is') as typeof import('next/dist/compiled/react-is')\n if (!isValidElementType(Component)) {\n throw new Error(\n `The default export is not a React Component in page: \"${pathname}\"`\n )\n }\n\n if (!isValidElementType(App)) {\n throw new Error(\n `The default export is not a React Component in page: \"/_app\"`\n )\n }\n\n if (!isValidElementType(Document)) {\n throw new Error(\n `The default export is not a React Component in page: \"/_document\"`\n )\n }\n\n if (isAutoExport || isFallback) {\n // remove query values except ones that will be set during export\n query = {}\n asPath = `${pathname}${\n // ensure trailing slash is present for non-dynamic auto-export pages\n req.url!.endsWith('/') && pathname !== '/' && !pageIsDynamic ? '/' : ''\n }`\n req.url = pathname\n }\n\n if (pathname === '/404' && (hasPageGetInitialProps || getServerSideProps)) {\n throw new Error(\n `\\`pages/404\\` ${STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`\n )\n }\n if (\n STATIC_STATUS_PAGES.includes(pathname) &&\n (hasPageGetInitialProps || getServerSideProps)\n ) {\n throw new Error(\n `\\`pages${pathname}\\` ${STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`\n )\n }\n\n if (renderOpts?.setIsrStatus) {\n renderOpts.setIsrStatus(asPath, isSSG || isAutoExport)\n }\n }\n\n for (const methodName of [\n 'getStaticProps',\n 'getServerSideProps',\n 'getStaticPaths',\n ]) {\n if ((Component as any)?.[methodName]) {\n throw new Error(\n `page ${pathname} ${methodName} ${GSSP_COMPONENT_MEMBER_ERROR}`\n )\n }\n }\n\n await Loadable.preloadAll() // Make sure all dynamic imports are loaded\n\n let isPreview: boolean | undefined = undefined\n let previewData: PreviewData\n\n if (\n (isSSG || getServerSideProps) &&\n !isFallback &&\n process.env.NEXT_RUNTIME !== 'edge' &&\n previewProps\n ) {\n // Reads of this are cached on the `req` object, so this should resolve\n // instantly. There's no need to pass this data down from a previous\n // invoke.\n previewData = tryGetPreviewData(\n req,\n res,\n previewProps,\n !!renderOpts.multiZoneDraftMode\n )\n isPreview = previewData !== false\n }\n\n // url will always be set\n const routerIsReady = !!(\n getServerSideProps ||\n hasPageGetInitialProps ||\n (!defaultAppGetInitialProps && !isSSG) ||\n isExperimentalCompile\n )\n const router = new ServerRouter(\n pathname,\n query,\n asPath,\n {\n isFallback: isFallback,\n },\n routerIsReady,\n basePath,\n renderOpts.locale,\n renderOpts.locales,\n renderOpts.defaultLocale,\n renderOpts.domainLocales,\n isPreview,\n getRequestMeta(req, 'isLocaleDomain')\n )\n\n const appRouter = adaptForAppRouterInstance(router)\n\n let scriptLoader: any = {}\n const jsxStyleRegistry = createStyleRegistry()\n\n let head: JSX.Element[] = defaultHead()\n const reactLoadableModules: string[] = []\n\n let initialScripts: any = {}\n if (hasPageScripts) {\n initialScripts.beforeInteractive = []\n .concat(hasPageScripts())\n .filter((script: any) => script.props.strategy === 'beforeInteractive')\n .map((script: any) => script.props)\n }\n\n const csp =\n req.headers['content-security-policy'] ||\n req.headers['content-security-policy-report-only']\n\n const nonce =\n typeof csp === 'string' ? getScriptNonceFromHeader(csp) : undefined\n\n const AppContainer = ({ children }: { children: JSX.Element }) => (\n \n \n \n \n \n {\n head = state\n },\n updateScripts: (scripts) => {\n scriptLoader = scripts\n },\n scripts: initialScripts,\n mountedInstances: new Set(),\n nonce,\n }}\n >\n reactLoadableModules.push(moduleName)}\n >\n \n \n {children}\n \n \n \n \n \n \n \n \n \n )\n\n // The `useId` API uses the path indexes to generate an ID for each node.\n // To guarantee the match of hydration, we need to ensure that the structure\n // of wrapper nodes is isomorphic in server and client.\n // TODO: With `enhanceApp` and `enhanceComponents` options, this approach may\n // not be useful.\n // https://github.com/facebook/react/pull/22644\n const Noop = () => null\n const AppContainerWithIsomorphicFiberStructure: React.FC<{\n children: JSX.Element\n }> = ({ children }) => {\n return (\n <>\n {/* */}\n \n \n <>\n {children}\n {/* */}\n \n \n \n \n )\n }\n\n const ctx = {\n err,\n req: isAutoExport ? undefined : req,\n res: isAutoExport ? undefined : res,\n pathname,\n query,\n asPath,\n locale: renderOpts.locale,\n locales: renderOpts.locales,\n defaultLocale: renderOpts.defaultLocale,\n AppTree: (props: any) => {\n return (\n \n {renderPageTree(App, OriginComponent, { ...props, router })}\n \n )\n },\n defaultGetInitialProps: async (\n docCtx: DocumentContext,\n options: { nonce?: string } = {}\n ): Promise => {\n const enhanceApp = (AppComp: any) => {\n return (props: any) => \n }\n\n const { html, head: renderPageHead } = await docCtx.renderPage({\n enhanceApp,\n })\n const styles = jsxStyleRegistry.styles({ nonce: options.nonce || nonce })\n jsxStyleRegistry.flush()\n return { html, head: renderPageHead, styles }\n },\n }\n let props: any\n\n const nextExport =\n !isSSG &&\n (renderOpts.isBuildTimePrerendering ||\n (process.env.__NEXT_DEV_SERVER && (isAutoExport || isFallback)))\n\n const styledJsxInsertedHTML = () => {\n const styles = jsxStyleRegistry.styles()\n jsxStyleRegistry.flush()\n return <>{styles}\n }\n\n props = await loadGetInitialProps(App, {\n AppTree: ctx.AppTree,\n Component,\n router,\n ctx,\n })\n\n if ((isSSG || getServerSideProps) && isPreview) {\n props.__N_PREVIEW = true\n }\n\n if (isSSG) {\n props[STATIC_PROPS_ID] = true\n }\n\n if (isSSG && !isFallback) {\n let data: Readonly>>\n\n try {\n data = await getTracer().trace(\n RenderSpan.getStaticProps,\n {\n spanName: `getStaticProps ${pathname}`,\n attributes: {\n 'next.route': pathname,\n },\n },\n () =>\n getStaticProps({\n ...(pageIsDynamic ? { params } : undefined),\n ...(isPreview\n ? { draftMode: true, preview: true, previewData: previewData }\n : undefined),\n locales: [...(renderOpts.locales ?? [])],\n locale: renderOpts.locale,\n defaultLocale: renderOpts.defaultLocale,\n revalidateReason: renderOpts.isOnDemandRevalidate\n ? 'on-demand'\n : isBuildTimeSSG\n ? 'build'\n : 'stale',\n })\n )\n } catch (staticPropsError: any) {\n // remove not found error code to prevent triggering legacy\n // 404 rendering\n if (staticPropsError && staticPropsError.code === 'ENOENT') {\n delete staticPropsError.code\n }\n throw staticPropsError\n }\n\n if (data == null) {\n throw new Error(GSP_NO_RETURNED_VALUE)\n }\n\n const invalidKeys = Object.keys(data).filter(\n (key) =>\n key !== 'revalidate' &&\n key !== 'props' &&\n key !== 'redirect' &&\n key !== 'notFound'\n )\n\n if (invalidKeys.includes('unstable_revalidate')) {\n throw new Error(UNSTABLE_REVALIDATE_RENAME_ERROR)\n }\n\n if (invalidKeys.length) {\n throw new Error(invalidKeysMsg('getStaticProps', invalidKeys))\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (\n typeof (data as any).notFound !== 'undefined' &&\n typeof (data as any).redirect !== 'undefined'\n ) {\n throw new Error(\n `\\`redirect\\` and \\`notFound\\` can not both be returned from ${\n isSSG ? 'getStaticProps' : 'getServerSideProps'\n } at the same time. Page: ${pathname}\\nSee more info here: https://nextjs.org/docs/messages/gssp-mixed-not-found-redirect`\n )\n }\n }\n\n if ('notFound' in data && data.notFound) {\n if (pathname === '/404') {\n throw new Error(\n `The /404 page can not return notFound in \"getStaticProps\", please remove it to continue!`\n )\n }\n\n metadata.isNotFound = true\n }\n\n if (\n 'redirect' in data &&\n data.redirect &&\n typeof data.redirect === 'object'\n ) {\n checkRedirectValues(data.redirect as Redirect, req, 'getStaticProps')\n\n if (isBuildTimeSSG) {\n throw new Error(\n `\\`redirect\\` can not be returned from getStaticProps during prerendering (${req.url})\\n` +\n `See more info here: https://nextjs.org/docs/messages/gsp-redirect-during-prerender`\n )\n }\n\n ;(data as any).props = {\n __N_REDIRECT: data.redirect.destination,\n __N_REDIRECT_STATUS: getRedirectStatus(data.redirect),\n }\n if (typeof data.redirect.basePath !== 'undefined') {\n ;(data as any).props.__N_REDIRECT_BASE_PATH = data.redirect.basePath\n }\n metadata.isRedirect = true\n }\n\n if (\n (process.env.__NEXT_DEV_SERVER || isBuildTimeSSG) &&\n !metadata.isNotFound &&\n !isSerializableProps(pathname, 'getStaticProps', (data as any).props)\n ) {\n // this fn should throw an error instead of ever returning `false`\n throw new Error(\n 'invariant: getStaticProps did not return valid props. Please report this.'\n )\n }\n\n let revalidate: Revalidate\n if ('revalidate' in data) {\n if (data.revalidate && renderOpts.nextConfigOutput === 'export') {\n throw new Error(\n 'ISR cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n if (typeof data.revalidate === 'number') {\n if (!Number.isInteger(data.revalidate)) {\n throw new Error(\n `A page's revalidate option must be seconds expressed as a natural number for ${req.url}. Mixed numbers, such as '${data.revalidate}', cannot be used.` +\n `\\nTry changing the value to '${Math.ceil(\n data.revalidate\n )}' or using \\`Math.ceil()\\` if you're computing the value.`\n )\n } else if (data.revalidate <= 0) {\n throw new Error(\n `A page's revalidate option can not be less than or equal to zero for ${req.url}. A revalidate option of zero means to revalidate after _every_ request, and implies stale data cannot be tolerated.` +\n `\\n\\nTo never revalidate, you can set revalidate to \\`false\\` (only ran once at build-time).` +\n `\\nTo revalidate as soon as possible, you can set the value to \\`1\\`.`\n )\n } else {\n if (data.revalidate > 31536000) {\n // if it's greater than a year for some reason error\n console.warn(\n `Warning: A page's revalidate option was set to more than a year for ${req.url}. This may have been done in error.` +\n `\\nTo only run getStaticProps at build-time and not revalidate at runtime, you can set \\`revalidate\\` to \\`false\\`!`\n )\n }\n\n revalidate = data.revalidate\n }\n } else if (data.revalidate === true) {\n // When enabled, revalidate after 1 second. This value is optimal for\n // the most up-to-date page possible, but without a 1-to-1\n // request-refresh ratio.\n revalidate = 1\n } else if (\n data.revalidate === false ||\n typeof data.revalidate === 'undefined'\n ) {\n // By default, we never revalidate.\n revalidate = false\n } else {\n throw new Error(\n `A page's revalidate option must be seconds expressed as a natural number. Mixed numbers and strings cannot be used. Received '${JSON.stringify(\n data.revalidate\n )}' for ${req.url}`\n )\n }\n } else {\n // By default, we never revalidate.\n revalidate = false\n }\n\n props.pageProps = Object.assign(\n {},\n props.pageProps,\n 'props' in data ? data.props : undefined\n )\n\n // pass up cache control and props for export\n metadata.cacheControl = { revalidate, expire: undefined }\n metadata.pageData = props\n\n // this must come after revalidate is added to renderResultMeta\n if (metadata.isNotFound) {\n return new RenderResult(null, {\n metadata,\n contentType: null,\n })\n }\n }\n\n if (getServerSideProps) {\n props[SERVER_PROPS_ID] = true\n }\n\n if (getServerSideProps && !isFallback) {\n let data: UnwrapPromise>\n\n let canAccessRes = true\n let resOrProxy = res\n let deferredContent = false\n if (process.env.NODE_ENV !== 'production') {\n resOrProxy = new Proxy(res, {\n get: function (obj, prop) {\n if (!canAccessRes) {\n const message =\n `You should not access 'res' after getServerSideProps resolves.` +\n `\\nRead more: https://nextjs.org/docs/messages/gssp-no-mutating-res`\n\n if (deferredContent) {\n throw new Error(message)\n } else {\n warn(message)\n }\n }\n\n if (typeof prop === 'symbol') {\n return ReflectAdapter.get(obj, prop, res)\n }\n\n return ReflectAdapter.get(obj, prop, res)\n },\n })\n }\n\n try {\n data = await getTracer().trace(\n RenderSpan.getServerSideProps,\n {\n spanName: `getServerSideProps ${pathname}`,\n attributes: {\n 'next.route': pathname,\n },\n },\n async () =>\n getServerSideProps({\n req: req as IncomingMessage & {\n cookies: NextApiRequestCookies\n },\n res: resOrProxy,\n query,\n resolvedUrl: renderOpts.resolvedUrl as string,\n ...(pageIsDynamic ? { params } : undefined),\n ...(previewData !== false\n ? { draftMode: true, preview: true, previewData: previewData }\n : undefined),\n // We create a copy here to avoid having the types of\n // `getServerSideProps` change. This ensures that users can't\n // mutate this array and have it poison the reference.\n locales: [...(renderOpts.locales ?? [])],\n locale: renderOpts.locale,\n defaultLocale: renderOpts.defaultLocale,\n })\n )\n canAccessRes = false\n metadata.cacheControl = { revalidate: 0, expire: undefined }\n } catch (serverSidePropsError: any) {\n // remove not found error code to prevent triggering legacy\n // 404 rendering\n if (\n isError(serverSidePropsError) &&\n serverSidePropsError.code === 'ENOENT'\n ) {\n delete serverSidePropsError.code\n }\n throw serverSidePropsError\n }\n\n if (data == null) {\n throw new Error(GSSP_NO_RETURNED_VALUE)\n }\n\n if ((data as any).props instanceof Promise) {\n deferredContent = true\n }\n\n const invalidKeys = Object.keys(data).filter(\n (key) => key !== 'props' && key !== 'redirect' && key !== 'notFound'\n )\n\n if ((data as any).unstable_notFound) {\n throw new Error(\n `unstable_notFound has been renamed to notFound, please update the field to continue. Page: ${pathname}`\n )\n }\n if ((data as any).unstable_redirect) {\n throw new Error(\n `unstable_redirect has been renamed to redirect, please update the field to continue. Page: ${pathname}`\n )\n }\n\n if (invalidKeys.length) {\n throw new Error(invalidKeysMsg('getServerSideProps', invalidKeys))\n }\n\n if ('notFound' in data && data.notFound) {\n if (pathname === '/404') {\n throw new Error(\n `The /404 page can not return notFound in \"getStaticProps\", please remove it to continue!`\n )\n }\n\n metadata.isNotFound = true\n return new RenderResult(null, {\n metadata,\n contentType: null,\n })\n }\n\n if ('redirect' in data && typeof data.redirect === 'object') {\n checkRedirectValues(data.redirect as Redirect, req, 'getServerSideProps')\n ;(data as any).props = {\n __N_REDIRECT: data.redirect.destination,\n __N_REDIRECT_STATUS: getRedirectStatus(data.redirect),\n }\n if (typeof data.redirect.basePath !== 'undefined') {\n ;(data as any).props.__N_REDIRECT_BASE_PATH = data.redirect.basePath\n }\n metadata.isRedirect = true\n }\n\n if (deferredContent) {\n ;(data as any).props = await (data as any).props\n }\n\n if (\n (process.env.__NEXT_DEV_SERVER || isBuildTimeSSG) &&\n !isSerializableProps(pathname, 'getServerSideProps', (data as any).props)\n ) {\n // this fn should throw an error instead of ever returning `false`\n throw new Error(\n 'invariant: getServerSideProps did not return valid props. Please report this.'\n )\n }\n\n props.pageProps = Object.assign({}, props.pageProps, (data as any).props)\n metadata.pageData = props\n }\n\n if (\n !isSSG && // we only show this warning for legacy pages\n !getServerSideProps &&\n process.env.NODE_ENV !== 'production' &&\n Object.keys(props?.pageProps || {}).includes('url')\n ) {\n console.warn(\n `The prop \\`url\\` is a reserved prop in Next.js for legacy reasons and will be overridden on page ${pathname}\\n` +\n `See more info here: https://nextjs.org/docs/messages/reserved-page-prop`\n )\n }\n\n // Avoid rendering page un-necessarily for getServerSideProps data request\n // and getServerSideProps/getStaticProps redirects\n if ((isNextDataRequest && !isSSG) || metadata.isRedirect) {\n return new RenderResult(JSON.stringify(props), {\n metadata,\n contentType: JSON_CONTENT_TYPE_HEADER,\n })\n }\n\n // We don't call getStaticProps or getServerSideProps while generating\n // the fallback so make sure to set pageProps to an empty object\n if (isFallback) {\n props.pageProps = {}\n }\n\n // the response might be finished on the getInitialProps call\n if (isResSent(res) && !isSSG) return RenderResult.EMPTY\n\n // we preload the buildManifest for auto-export dynamic pages\n // to speed up hydrating query values\n let filteredBuildManifest = buildManifest\n if (isAutoExport && pageIsDynamic) {\n const page = denormalizePagePath(normalizePagePath(pathname))\n // This code would be much cleaner using `immer` and directly pushing into\n // the result from `getPageFiles`, we could maybe consider that in the\n // future.\n if (page in filteredBuildManifest.pages) {\n filteredBuildManifest = {\n ...filteredBuildManifest,\n pages: {\n ...filteredBuildManifest.pages,\n [page]: [\n ...filteredBuildManifest.pages[page],\n ...filteredBuildManifest.lowPriorityFiles.filter((f) =>\n f.includes('_buildManifest')\n ),\n ],\n },\n lowPriorityFiles: filteredBuildManifest.lowPriorityFiles.filter(\n (f) => !f.includes('_buildManifest')\n ),\n }\n }\n }\n\n const Body = ({ children }: { children: JSX.Element }) => {\n return
{children}
\n }\n\n const renderDocument = async () => {\n // For `Document`, there are two cases that we don't support:\n // 1. Using `Document.getInitialProps` in the Edge runtime.\n // 2. Using the class component `Document` with concurrent features.\n\n const BuiltinFunctionalDocument: DocumentType | undefined = (\n Document as any\n )[NEXT_BUILTIN_DOCUMENT]\n\n if (process.env.NEXT_RUNTIME === 'edge' && Document.getInitialProps) {\n // In the Edge runtime, `Document.getInitialProps` isn't supported.\n // We throw an error here if it's customized.\n if (BuiltinFunctionalDocument) {\n Document = BuiltinFunctionalDocument\n } else {\n throw new Error(\n '`getInitialProps` in Document component is not supported with the Edge Runtime.'\n )\n }\n }\n\n async function loadDocumentInitialProps(\n renderShell: (\n _App: AppType,\n _Component: NextComponentType\n ) => Promise\n ) {\n const renderPage: RenderPage = async (\n options: ComponentsEnhancer = {}\n ): Promise => {\n if (ctx.err && ErrorDebug) {\n // Always start rendering the shell even if there's an error.\n if (renderShell) {\n renderShell(App, Component)\n }\n\n const html = await renderToString(\n \n \n \n )\n return { html, head }\n }\n\n if (\n process.env.__NEXT_DEV_SERVER &&\n (props.router || props.Component)\n ) {\n throw new Error(\n `'router' and 'Component' can not be returned in getInitialProps from _app.js https://nextjs.org/docs/messages/cant-override-next-props`\n )\n }\n\n const { App: EnhancedApp, Component: EnhancedComponent } =\n enhanceComponents(options, App, Component)\n\n const stream = await renderShell(EnhancedApp, EnhancedComponent)\n await stream.allReady\n const html = await streamToString(stream)\n\n return { html, head }\n }\n const documentCtx = { ...ctx, renderPage }\n const docProps: DocumentInitialProps = await loadGetInitialProps(\n Document,\n documentCtx\n )\n // the response might be finished on the getInitialProps call\n if (isResSent(res) && !isSSG) return null\n\n if (!docProps || typeof docProps.html !== 'string') {\n const message = `\"${getDisplayName(\n Document\n )}.getInitialProps()\" should resolve to an object with a \"html\" prop set with a valid html string`\n throw new Error(message)\n }\n\n return { docProps, documentCtx }\n }\n\n const renderContent = (_App: AppType, _Component: NextComponentType) => {\n const EnhancedApp = _App || App\n const EnhancedComponent = _Component || Component\n\n return ctx.err && ErrorDebug ? (\n \n \n \n ) : (\n \n \n {renderPageTree(EnhancedApp, EnhancedComponent, {\n ...props,\n router,\n })}\n \n \n )\n }\n\n // Always using react concurrent rendering mode with required react version 18.x\n const renderShell = async (\n EnhancedApp: AppType,\n EnhancedComponent: NextComponentType\n ) => {\n const content = renderContent(EnhancedApp, EnhancedComponent)\n return await renderToInitialFizzStream({\n ReactDOMServer: ReactDOMServerPages,\n element: content,\n })\n }\n\n const hasDocumentGetInitialProps =\n process.env.NEXT_RUNTIME !== 'edge' && !!Document.getInitialProps\n\n // If it has getInitialProps, we will render the shell in `renderPage`.\n // Otherwise we do it right now.\n let documentInitialPropsRes:\n | {}\n | Awaited>\n\n let content: string | null\n if (hasDocumentGetInitialProps) {\n documentInitialPropsRes = await loadDocumentInitialProps(renderShell)\n if (documentInitialPropsRes === null) {\n content = null\n } else {\n const { docProps } = documentInitialPropsRes as any\n content = docProps.html\n }\n } else {\n documentInitialPropsRes = {}\n const stream = await renderShell(App, Component)\n await stream.allReady\n content = await streamToString(stream)\n }\n\n // @ts-ignore: documentInitialPropsRes is set\n const { docProps } = (documentInitialPropsRes as any) || {}\n const documentElement = (htmlProps: any) => {\n if (process.env.NEXT_RUNTIME === 'edge') {\n return (Document as any)()\n } else {\n return \n }\n }\n\n let styles\n if (hasDocumentGetInitialProps) {\n styles = docProps.styles\n head = docProps.head\n } else {\n styles = jsxStyleRegistry.styles()\n jsxStyleRegistry.flush()\n }\n\n // Registry is now flushed; rawStyledJsxInsertedHTML will be empty.\n const rawStyledJsxInsertedHTML = await renderToString(\n styledJsxInsertedHTML()\n )\n\n if (content === null) {\n return null\n }\n\n const contentHTML = rawStyledJsxInsertedHTML + content\n\n return {\n contentHTML,\n documentElement,\n head,\n headTags: [],\n styles,\n }\n }\n\n getTracer().setRootSpanAttribute('next.route', renderOpts.page)\n const documentResult = await getTracer().trace(\n RenderSpan.renderDocument,\n {\n spanName: `render route (pages) ${renderOpts.page}`,\n attributes: {\n 'next.route': renderOpts.page,\n },\n },\n async () => renderDocument()\n )\n if (!documentResult) {\n return new RenderResult(null, {\n metadata,\n contentType: HTML_CONTENT_TYPE_HEADER,\n })\n }\n\n const dynamicImportsIds = new Set()\n const dynamicImports = new Set()\n\n for (const mod of reactLoadableModules) {\n const manifestItem = reactLoadableManifest[mod]\n\n if (manifestItem) {\n dynamicImportsIds.add(manifestItem.id)\n manifestItem.files.forEach((item) => {\n dynamicImports.add(item)\n })\n }\n }\n\n const docComponentsRendered: DocumentProps['docComponentsRendered'] = {}\n\n const {\n assetPrefix,\n defaultLocale,\n disableOptimizedLoading,\n domainLocales,\n locale,\n locales,\n } = renderOpts\n const htmlProps: HtmlProps = {\n __NEXT_DATA__: {\n props, // The result of getInitialProps\n page: pathname, // The rendered page\n query, // querystring parsed / passed by the user\n buildId: sharedContext.buildId,\n assetPrefix: assetPrefix === '' ? undefined : assetPrefix, // send assetPrefix to the client side when configured, otherwise don't sent in the resulting HTML\n nextExport: nextExport === true ? true : undefined, // If this is a page exported by `next export`\n autoExport: isAutoExport === true ? true : undefined, // If this is an auto exported page\n isFallback,\n isExperimentalCompile,\n dynamicIds:\n dynamicImportsIds.size === 0\n ? undefined\n : Array.from(dynamicImportsIds),\n err: renderOpts.err\n ? serializeError(!!process.env.__NEXT_DEV_SERVER, renderOpts.err)\n : undefined, // Error if one happened, otherwise don't sent in the resulting HTML\n gsp: !!getStaticProps ? true : undefined, // whether the page is getStaticProps\n gssp: !!getServerSideProps ? true : undefined, // whether the page is getServerSideProps\n customServer: sharedContext.customServer,\n gip: hasPageGetInitialProps ? true : undefined, // whether the page has getInitialProps\n appGip: !defaultAppGetInitialProps ? true : undefined, // whether the _app has getInitialProps\n locale,\n locales,\n defaultLocale,\n domainLocales,\n isPreview: isPreview === true ? true : undefined,\n notFoundSrcPage:\n notFoundSrcPage && process.env.__NEXT_DEV_SERVER\n ? notFoundSrcPage\n : undefined,\n },\n nonce,\n buildManifest: filteredBuildManifest,\n docComponentsRendered,\n dangerousAsPath: router.asPath,\n isDevelopment: !!process.env.__NEXT_DEV_SERVER,\n deploymentId: sharedContext.deploymentId,\n dynamicImports: Array.from(dynamicImports),\n dynamicCssManifest: new Set(renderOpts.dynamicCssManifest || []),\n assetPrefix,\n // Only enabled in production as development mode has features relying on HMR (style injection for example)\n unstable_runtimeJS:\n process.env.NODE_ENV === 'production'\n ? pageConfig.unstable_runtimeJS\n : undefined,\n unstable_JsPreload: pageConfig.unstable_JsPreload,\n assetQueryString,\n cssAssetQueryString,\n mutableAssetQueryString,\n scriptLoader,\n locale,\n disableOptimizedLoading,\n head: documentResult.head,\n headTags: documentResult.headTags,\n styles: documentResult.styles,\n crossOrigin: renderOpts.crossOrigin,\n optimizeCss: renderOpts.optimizeCss,\n nextConfigOutput: renderOpts.nextConfigOutput,\n nextScriptWorkers: renderOpts.nextScriptWorkers,\n runtime: globalRuntime,\n largePageDataBytes: renderOpts.largePageDataBytes,\n nextFontManifest: renderOpts.nextFontManifest,\n experimentalClientTraceMetadata:\n renderOpts.experimental.clientTraceMetadata,\n }\n\n const document = (\n \n {documentResult.documentElement(htmlProps)}\n \n )\n\n const documentHTML = await getTracer().trace(\n RenderSpan.renderToString,\n async () => renderToString(document)\n )\n\n if (process.env.NODE_ENV !== 'production') {\n const nonRenderedComponents = []\n const expectedDocComponents = ['Main', 'Head', 'NextScript', 'Html']\n\n for (const comp of expectedDocComponents) {\n if (!(docComponentsRendered as any)[comp]) {\n nonRenderedComponents.push(comp)\n }\n }\n\n if (nonRenderedComponents.length) {\n const missingComponentList = nonRenderedComponents\n .map((e) => `<${e} />`)\n .join(', ')\n const plural = nonRenderedComponents.length !== 1 ? 's' : ''\n console.warn(\n `Your custom Document (pages/_document) did not render all the required subcomponent${plural}.\\n` +\n `Missing component${plural}: ${missingComponentList}\\n` +\n 'Read how to fix here: https://nextjs.org/docs/messages/missing-document-component'\n )\n }\n }\n\n const [renderTargetPrefix, renderTargetSuffix] = documentHTML.split(\n '',\n 2\n )\n\n let prefix = ''\n if (!documentHTML.startsWith(DOCTYPE)) {\n prefix += DOCTYPE\n }\n prefix += renderTargetPrefix\n\n const content = prefix + documentResult.contentHTML + renderTargetSuffix\n\n const optimizedHtml = await postProcessHTML(content, renderOpts)\n\n return new RenderResult(optimizedHtml, {\n metadata,\n contentType: HTML_CONTENT_TYPE_HEADER,\n })\n}\n\nexport type PagesRender = (\n req: IncomingMessage,\n res: ServerResponse,\n pathname: string,\n query: NextParsedUrlQuery,\n renderOpts: RenderOpts,\n sharedContext: PagesSharedContext,\n renderContext: PagesRenderContext\n) => Promise\n\nexport const renderToHTML: PagesRender = (\n req,\n res,\n pathname,\n query,\n renderOpts,\n sharedContext,\n renderContext\n) => {\n return renderToHTMLImpl(\n req,\n res,\n pathname,\n query,\n renderOpts,\n renderOpts,\n sharedContext,\n renderContext\n )\n}\n"],"names":["errorToJSON","renderToHTML","renderToHTMLImpl","tryGetPreviewData","warn","postProcessHTML","DOCTYPE","process","env","NEXT_RUNTIME","require","console","bind","html","noRouter","message","Error","renderToString","element","renderStream","ReactDOMServerPages","renderToReadableStream","allReady","streamToString","ServerRouter","constructor","pathname","query","as","isFallback","isReady","basePath","locale","locales","defaultLocale","domainLocales","isPreview","isLocaleDomain","route","replace","asPath","push","reload","back","forward","prefetch","beforePopState","enhanceComponents","options","App","Component","enhanceApp","enhanceComponent","renderPageTree","props","invalidKeysMsg","methodName","invalidKeys","docsPathname","toLocaleLowerCase","join","checkRedirectValues","redirect","req","method","destination","permanent","statusCode","errors","hasStatusCode","hasPermanent","allowedStatusCodes","has","destinationType","basePathType","length","url","err","source","getErrorSource","name","stripAnsi","stack","digest","serializeError","dev","getSafariCacheBusterQueryString","__NEXT_DEV_SERVER","userAgent","headers","toLowerCase","includes","Date","now","res","renderOpts","extra","sharedContext","renderContext","setLazyProp","getCookieParser","cssCacheBuster","mutableAssetQueryString","deploymentId","assetQueryString","clientAssetToken","cssAssetQueryString","metadata","Object","assign","pageConfig","buildManifest","reactLoadableManifest","ErrorDebug","getStaticProps","getStaticPaths","getServerSideProps","isNextDataRequest","params","previewProps","images","runtime","globalRuntime","isExperimentalCompile","expireTime","Document","OriginComponent","notFoundSrcPage","developmentNotFoundSourcePage","stripInternalQueries","isSSG","isBuildTimeSSG","isBuildTimePrerendering","defaultAppGetInitialProps","getInitialProps","origGetInitialProps","hasPageGetInitialProps","hasPageScripts","unstable_scriptLoader","pageIsDynamic","isDynamicRoute","defaultErrorGetInitialProps","isAutoExport","setHeader","getCacheControlHeader","revalidate","expire","SSG_GET_INITIAL_PROPS_CONFLICT","SERVER_PROPS_GET_INIT_PROPS_CONFLICT","SERVER_PROPS_SSG_CONFLICT","nextConfigOutput","resolvedAsPath","isValidElementType","endsWith","STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR","STATIC_STATUS_PAGES","setIsrStatus","GSSP_COMPONENT_MEMBER_ERROR","Loadable","preloadAll","undefined","previewData","multiZoneDraftMode","routerIsReady","router","getRequestMeta","appRouter","adaptForAppRouterInstance","scriptLoader","jsxStyleRegistry","createStyleRegistry","head","defaultHead","reactLoadableModules","initialScripts","beforeInteractive","concat","filter","script","strategy","map","csp","nonce","getScriptNonceFromHeader","AppContainer","children","AppRouterContext","Provider","value","SearchParamsContext","adaptForSearchParams","PathnameContextProviderAdapter","PathParamsContext","adaptForPathParams","RouterContext","HeadManagerContext","updateHead","state","updateScripts","scripts","mountedInstances","Set","LoadableContext","moduleName","StyleRegistry","registry","ImageConfigContext","Noop","AppContainerWithIsomorphicFiberStructure","ctx","AppTree","defaultGetInitialProps","docCtx","AppComp","renderPageHead","renderPage","styles","flush","nextExport","styledJsxInsertedHTML","loadGetInitialProps","__N_PREVIEW","STATIC_PROPS_ID","data","getTracer","trace","RenderSpan","spanName","attributes","draftMode","preview","revalidateReason","isOnDemandRevalidate","staticPropsError","code","GSP_NO_RETURNED_VALUE","keys","key","UNSTABLE_REVALIDATE_RENAME_ERROR","NODE_ENV","notFound","isNotFound","__N_REDIRECT","__N_REDIRECT_STATUS","getRedirectStatus","__N_REDIRECT_BASE_PATH","isRedirect","isSerializableProps","Number","isInteger","Math","ceil","JSON","stringify","pageProps","cacheControl","pageData","RenderResult","contentType","SERVER_PROPS_ID","canAccessRes","resOrProxy","deferredContent","Proxy","get","obj","prop","ReflectAdapter","resolvedUrl","serverSidePropsError","isError","GSSP_NO_RETURNED_VALUE","Promise","unstable_notFound","unstable_redirect","JSON_CONTENT_TYPE_HEADER","isResSent","EMPTY","filteredBuildManifest","page","denormalizePagePath","normalizePagePath","pages","lowPriorityFiles","f","Body","div","id","renderDocument","BuiltinFunctionalDocument","NEXT_BUILTIN_DOCUMENT","loadDocumentInitialProps","renderShell","EnhancedApp","EnhancedComponent","stream","documentCtx","docProps","getDisplayName","renderContent","_App","_Component","content","renderToInitialFizzStream","ReactDOMServer","hasDocumentGetInitialProps","documentInitialPropsRes","documentElement","htmlProps","rawStyledJsxInsertedHTML","contentHTML","headTags","setRootSpanAttribute","documentResult","HTML_CONTENT_TYPE_HEADER","dynamicImportsIds","dynamicImports","mod","manifestItem","add","files","forEach","item","docComponentsRendered","assetPrefix","disableOptimizedLoading","__NEXT_DATA__","buildId","autoExport","dynamicIds","size","Array","from","gsp","gssp","customServer","gip","appGip","dangerousAsPath","isDevelopment","dynamicCssManifest","unstable_runtimeJS","unstable_JsPreload","crossOrigin","optimizeCss","nextScriptWorkers","largePageDataBytes","nextFontManifest","experimentalClientTraceMetadata","experimental","clientTraceMetadata","document","HtmlContext","documentHTML","nonRenderedComponents","expectedDocComponents","comp","missingComponentList","e","plural","renderTargetPrefix","renderTargetSuffix","split","prefix","startsWith","optimizedHtml"],"mappings":"AAAA,2FAA2F;;;;;;;;;;;;;;;;IA2Z3EA,WAAW;eAAXA;;IA0rCHC,YAAY;eAAZA;;IA7oCSC,gBAAgB;eAAhBA;;;;0BAjbf;iCACyB;8DAkBA;4EACA;2BACmB;2BAY5C;4BAMA;qCAC6B;sBACR;iDACO;8EACd;8CACW;4CACF;2BACC;uBAKxB;0CACqB;mCACM;qCACE;6BACL;gCACuB;qEACO;gEACzC;sCAIb;iDAC4B;kEACb;+BACe;0BAM9B;+CAC0B;iDAI1B;wBACmB;4BACC;yBACI;8BACO;6BACP;0CAGU;;;;;;AAEzC,IAAIC;AACJ,IAAIC;AACJ,IAAIC;AAEJ,MAAMC,UAAU;AAEhB,IAAIC,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCN,oBAAoB,AAClBO,QAAQ,yCACRP,iBAAiB;IACnBC,OAAO,AACLM,QAAQ,uBACRN,IAAI;IACNC,kBAAkB,AAChBK,QAAQ,kBACRL,eAAe;AACnB,OAAO;IACLD,OAAOO,QAAQP,IAAI,CAACQ,IAAI,CAACD;IACzBN,kBAAkB,OAAOQ,OAAiBA;AAC5C;AAEA,SAASC;IACP,MAAMC,UACJ;IACF,MAAM,IAAIC,MAAMD;AAClB;AAEA,eAAeE,eAAeC,OAA2B;IACvD,MAAMC,eAAe,MAAMC,4BAAmB,CAACC,sBAAsB,CAACH;IACtE,MAAMC,aAAaG,QAAQ;IAC3B,OAAOC,IAAAA,oCAAc,EAACJ;AACxB;AAEA,MAAMK;IAgBJC,YACEC,QAAgB,EAChBC,KAAqB,EACrBC,EAAU,EACV,EAAEC,UAAU,EAA2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,sBAC1B9K,GAAG,CAAC,CAACkL,IAAM,CAAC,CAAC,EAAEA,EAAE,GAAG,CAAC,EACrB1S,IAAI,CAAC;YACR,MAAM2S,SAASL,sBAAsBvR,MAAM,KAAK,IAAI,MAAM;YAC1DhE,QAAQP,IAAI,CACV,CAAC,mFAAmF,EAAEmW,OAAO,GAAG,CAAC,GAC/F,CAAC,iBAAiB,EAAEA,OAAO,EAAE,EAAEF,qBAAqB,EAAE,CAAC,GACvD;QAEN;IACF;IAEA,MAAM,CAACG,oBAAoBC,mBAAmB,GAAGR,aAAaS,KAAK,CACjE,+EACA;IAGF,IAAIC,SAAS;IACb,IAAI,CAACV,aAAaW,UAAU,CAACtW,UAAU;QACrCqW,UAAUrW;IACZ;IACAqW,UAAUH;IAEV,MAAM1D,UAAU6D,SAASlD,eAAeH,WAAW,GAAGmD;IAEtD,MAAMI,gBAAgB,MAAMxW,gBAAgByS,SAAS/M;IAErD,OAAO,IAAIkK,qBAAY,CAAC4G,eAAe;QACrClQ;QACAuJ,aAAawD,mCAAwB;IACvC;AACF;AAYO,MAAMzT,eAA4B,CACvC8D,KACA+B,KACApE,UACAC,OACAoE,YACAE,eACAC;IAEA,OAAOhG,iBACL6D,KACA+B,KACApE,UACAC,OACAoE,YACAA,YACAE,eACAC;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request-meta.d.ts b/e-commerce/node_modules/next/dist/server/request-meta.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..926aafccece01021fdd18170c9d0a839ba6012bb --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request-meta.d.ts @@ -0,0 +1,370 @@ +import type { IncomingMessage, ServerResponse } from 'http'; +import type { ParsedUrlQuery } from 'querystring'; +import type { UrlWithParsedQuery } from 'url'; +import type { BaseNextRequest } from './base-http'; +import type { CloneableBody } from './body-streams'; +import type { RouteMatch } from './route-matches/route-match'; +import type { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'; +import type { ResponseCacheEntry, ServerComponentsHmrCache } from './response-cache'; +import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'; +import type { OpaqueFallbackRouteParams } from './request/fallback-params'; +import type { IncrementalCache } from './lib/incremental-cache'; +import type { RevalidateFn } from './lib/router-utils/router-server-context'; +import type { NextRequest } from './web/exports'; +export declare const NEXT_REQUEST_META: unique symbol; +export type NextIncomingMessage = (BaseNextRequest | IncomingMessage | NextRequest) & { + [NEXT_REQUEST_META]?: RequestMeta; +}; +/** + * The callback function to call when a response cache entry was generated or + * looked up in the cache. When it returns true, the server assumes that the + * handler has already responded to the request and will not do so itself. + */ +export type OnCacheEntryHandler = ( +/** + * The response cache entry that was generated or looked up in the cache. + */ +cacheEntry: ResponseCacheEntry, +/** + * The request metadata. + */ +requestMeta: { + /** + * The URL that was used to make the request. + */ + url: string | undefined; +}) => Promise | boolean | void; +export interface RequestMeta { + /** + * The query that was used to make the request. + */ + initQuery?: ParsedUrlQuery; + /** + * The URL that was used to make the request. + */ + initURL?: string; + /** + * The protocol that was used to make the request. + */ + initProtocol?: string; + /** + * The body that was read from the request. This is used to allow the body to + * be read multiple times. + */ + clonableBody?: CloneableBody; + /** + * True when the request matched a locale domain that was configured in the + * next.config.js file. + */ + isLocaleDomain?: boolean; + /** + * True when the request had locale information stripped from the pathname + * part of the URL. + */ + didStripLocale?: boolean; + /** + * If the request had its URL rewritten, this is the pathname it was rewritten + * to (not a full URL, just the pathname). + */ + rewrittenPathname?: string; + /** + * The cookies that were added by middleware and were added to the response. + */ + middlewareCookie?: string[]; + /** + * The match on the request for a given route. + */ + match?: RouteMatch; + /** + * The incremental cache to use for the request. + */ + incrementalCache?: IncrementalCache; + /** + * The server components HMR cache, only for dev. + */ + serverComponentsHmrCache?: ServerComponentsHmrCache; + /** + * The hash of the most recent server component change (dev only), set by the + * router-server from the hot-reloader. Included in `"use cache"` cache keys + * so that cached entries are revalidated after an edit, for every client, + * regardless of whether it runs the HMR client. + */ + hmrRefreshHash?: string; + /** + * Equals the segment path that was used for the prefetch RSC request. + */ + segmentPrefetchRSCRequest?: string; + /** + * True when the request is for the prefetch flight data. + */ + isPrefetchRSCRequest?: true; + /** + * True when the request is for the flight data. + */ + isRSCRequest?: true; + /** + * A search param set by the Next.js client when performing RSC requests. + * Because some CDNs do not vary their cache entries on our custom headers, + * this search param represents a hash of the header values. For any cached + * RSC request, we should verify that the hash matches before responding. + * Otherwise this can lead to cache poisoning. + * TODO: Consider not using custom request headers at all, and instead encode + * everything into the search param. + */ + cacheBustingSearchParam?: string; + /** + * True when the request is for the `/_next/data` route using the pages + * router. + */ + isNextDataReq?: true; + /** + * Postponed state to use for resumption. When absent, the request is not a + * resume request. A non-empty string contains the state to resume, while an + * empty string represents a resume request without postponed state and + * signals that the renderer should perform a full dynamic render. + * + * There are no guarantees that the page actually postponed, as verifying + * that would incur an additional cache lookup. + */ + postponed?: string; + /** + * The action body extracted from a server action request when the postponed + * state was prepended to the body by the proxy. This allows the action + * handler to read the action payload without re-reading the consumed stream. + */ + actionBody?: Buffer; + /** + * If provided, this will be called when a response cache entry was generated + * or looked up in the cache. + * + * @deprecated Use `onCacheEntryV2` instead. + */ + onCacheEntry?: OnCacheEntryHandler; + /** + * If provided, this will be called when a response cache entry was generated + * or looked up in the cache. + */ + onCacheEntryV2?: OnCacheEntryHandler; + /** + * The previous revalidate before rendering 404 page for notFound: true + */ + notFoundRevalidate?: number | false; + /** + * In development, the original source page that returned a 404. + */ + developmentNotFoundSourcePage?: string; + /** + * The path we routed to and should be invoked + */ + invokePath?: string; + /** + * The specific page output we should be matching + */ + invokeOutput?: string; + /** + * The status we are invoking the request with from routing + */ + invokeStatus?: number; + /** + * The routing error we are invoking with + */ + invokeError?: Error; + /** + * The query parsed for the invocation + */ + invokeQuery?: Record; + /** + * Whether the request is a middleware invocation + */ + middlewareInvoke?: boolean; + /** + * Whether the request should render the fallback shell or not. + */ + renderFallbackShell?: boolean; + /** + * Route param keys that were explicitly resolved from partial nxtP* + * query params during background revalidation. Used by app-page.ts to + * determine which fallback params should remain deferred vs resolved + * in intermediate PPR shells. + */ + resolvedRouteParamKeys?: Set; + /** + * Whether the request is for the custom error page. + */ + customErrorRender?: true; + /** + * Whether to bubble up the NoFallbackError to the caller when a 404 is + * returned. + */ + bubbleNoFallback?: true; + /** + * True when the request had locale information inferred from the default + * locale. + */ + localeInferredFromDefault?: true; + /** + * The locale that was inferred or explicitly set for the request. + */ + locale?: string; + /** + * The default locale that was inferred or explicitly set for the request. + */ + defaultLocale?: string; + /** + * The relative project dir the server is running in from project root + */ + relativeProjectDir?: string; + /** + * The dist directory the server is currently using + */ + distDir?: string; + /** + Optional hostname used by route handlers when constructing absolute URLs. + hostname: '127.0.0.1', + */ + hostname?: string; + /** + Optional internal revalidate function to avoid revalidating over the network + */ + revalidate?: RevalidateFn; + /** + Optional function to render the 404 page for pages router `notFound: true` + */ + render404?: (req: IncomingMessage, res: ServerResponse, parsedUrl?: UrlWithParsedQuery, setHeaders?: boolean) => Promise; + /** + * The query after resolving routes + */ + query?: ParsedUrlQuery; + /** + * The params after resolving routes + */ + params?: ParsedUrlQuery; + /** + * ErrorOverlay component to use in development for pages router + */ + PagesErrorDebug?: PagesDevOverlayBridgeType; + /** + * Whether server is in minimal mode (this will be replaced with more + * specific flags in future) + */ + minimalMode?: boolean; + /** + * Staged renders defer these route params until after the static stage. They + * keep their concrete request values instead of replacing them with + * placeholders. Dev static-shell validation uses the same set for the + * selected shell. + * + * For `/t2/items/b2` with selected shell `/t2/items/[bottom]`, this map + * contains only `bottom`: + * - A layout's `params` containing only `top` can resolve statically. + * - A page's `params` containing `bottom` waits until after the static stage. + * + * A set recorded in postponed state overrides this metadata on a resume, + * including an explicitly empty set. + */ + stagedFallbackParams?: OpaqueFallbackRouteParams | null; + /** + * Dev static-shell debug renders use these params to prerender the matched + * source shell. The Instant Navigation Testing API uses this path too. The + * prerender substitutes opaque placeholders for these params rather than + * using their request values. + * + * Suppose `generateStaticParams` returns `[{ top: 't1' }]` for + * `/[top]/items/[bottom]`. A request for `/t2/items/b2` has: + * - Source `/[top]/items/[bottom]`: `top` and `bottom` are unresolved. + * - Completed shell `/t2/items/[bottom]`: only `bottom` is unresolved. + * + * This map contains the source's `top` and `bottom`. A debug render of that + * source also uses this map as `stagedFallbackParams`. + */ + fallbackRouteParams?: OpaqueFallbackRouteParams | null; + /** DEV only: parameter matching rejected this request as not found. */ + devParamMatchingRejected?: boolean; + /** DEV only: closed parameters, including for successful allowed values. */ + devNotFoundParams?: readonly string[]; + /** + * DEV only: Request timings in process.hrtime.bigint() + */ + devRequestTimingStart?: bigint; + devRequestTimingMiddlewareStart?: bigint; + devRequestTimingMiddlewareEnd?: bigint; + devRequestTimingInternalsEnd?: bigint; + /** + * DEV only: The duration of getStaticPaths/generateStaticParams in process.hrtime.bigint() + */ + devGenerateStaticParamsDuration?: bigint; + /** + * DEV only: Server action log info to be logged after the request log + */ + devServerActionLog?: { + functionName: string; + args: unknown[]; + location: string; + duration: number; + }; +} +/** + * Gets the request metadata. If no key is provided, the entire metadata object + * is returned. + * + * @param req the request to get the metadata from + * @param key the key to get from the metadata (optional) + * @returns the value for the key or the entire metadata object + */ +export declare function getRequestMeta(req: NextIncomingMessage, key?: undefined): RequestMeta; +export declare function getRequestMeta(req: NextIncomingMessage, key: K): RequestMeta[K]; +/** + * Sets the request metadata. + * + * @param req the request to set the metadata on + * @param meta the metadata to set + * @returns the mutated request metadata + */ +export declare function setRequestMeta(req: NextIncomingMessage, meta: RequestMeta): RequestMeta; +/** + * Adds a value to the request metadata. + * + * @param request the request to mutate + * @param key the key to set + * @param value the value to set + * @returns the mutated request metadata + */ +export declare function addRequestMeta(request: NextIncomingMessage, key: K, value: RequestMeta[K]): RequestMeta; +/** + * Removes a key from the request metadata. + * + * @param request the request to mutate + * @param key the key to remove + * @returns the mutated request metadata + */ +export declare function removeRequestMeta(request: NextIncomingMessage, key: K): RequestMeta; +type NextQueryMetadata = { + /** + * The `_rsc` query parameter used for cache busting to ensure that the RSC + * requests do not get cached by the browser explicitly. + */ + [NEXT_RSC_UNION_QUERY]?: string; +}; +export type NextParsedUrlQuery = ParsedUrlQuery & NextQueryMetadata; +/** + * subset of `url.parse` return value + */ +interface LegacyUrl { + auth?: string | null; + hash: string | null; + hostname: string | null; + href: string; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; +} +interface LegacyUrlWithParsedQuery extends LegacyUrl { + query: ParsedUrlQuery; +} +export interface NextUrlWithParsedQuery extends LegacyUrlWithParsedQuery { + query: NextParsedUrlQuery; +} +export {}; diff --git a/e-commerce/node_modules/next/dist/server/request-meta.js b/e-commerce/node_modules/next/dist/server/request-meta.js new file mode 100644 index 0000000000000000000000000000000000000000..a06ec6b899b7e92b50bb2b409b3ad94bcc7b661f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request-meta.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + NEXT_REQUEST_META: null, + addRequestMeta: null, + getRequestMeta: null, + removeRequestMeta: null, + setRequestMeta: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + NEXT_REQUEST_META: function() { + return NEXT_REQUEST_META; + }, + addRequestMeta: function() { + return addRequestMeta; + }, + getRequestMeta: function() { + return getRequestMeta; + }, + removeRequestMeta: function() { + return removeRequestMeta; + }, + setRequestMeta: function() { + return setRequestMeta; + } +}); +const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta'); +function getRequestMeta(req, key) { + const meta = req[NEXT_REQUEST_META] || {}; + return typeof key === 'string' ? meta[key] : meta; +} +function setRequestMeta(req, meta) { + req[NEXT_REQUEST_META] = meta; + return meta; +} +function addRequestMeta(request, key, value) { + const meta = getRequestMeta(request); + meta[key] = value; + return setRequestMeta(request, meta); +} +function removeRequestMeta(request, key) { + const meta = getRequestMeta(request); + delete meta[key]; + return setRequestMeta(request, meta); +} + +//# sourceMappingURL=request-meta.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request-meta.js.map b/e-commerce/node_modules/next/dist/server/request-meta.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e4b5177d770250da13cf3f54fa125abfd4351b95 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request-meta.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/request-meta.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { BaseNextRequest } from './base-http'\nimport type { CloneableBody } from './body-streams'\nimport type { RouteMatch } from './route-matches/route-match'\nimport type { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'\nimport type {\n ResponseCacheEntry,\n ServerComponentsHmrCache,\n} from './response-cache'\nimport type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport type { OpaqueFallbackRouteParams } from './request/fallback-params'\nimport type { IncrementalCache } from './lib/incremental-cache'\nimport type { RevalidateFn } from './lib/router-utils/router-server-context'\nimport type { NextRequest } from './web/exports'\n\n// FIXME: (wyattjoh) this is a temporary solution to allow us to pass data between bundled modules\nexport const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta')\n\nexport type NextIncomingMessage = (\n | BaseNextRequest\n | IncomingMessage\n | NextRequest\n) & {\n [NEXT_REQUEST_META]?: RequestMeta\n}\n\n/**\n * The callback function to call when a response cache entry was generated or\n * looked up in the cache. When it returns true, the server assumes that the\n * handler has already responded to the request and will not do so itself.\n */\nexport type OnCacheEntryHandler = (\n /**\n * The response cache entry that was generated or looked up in the cache.\n */\n cacheEntry: ResponseCacheEntry,\n\n /**\n * The request metadata.\n */\n requestMeta: {\n /**\n * The URL that was used to make the request.\n */\n url: string | undefined\n }\n) => Promise | boolean | void\n\nexport interface RequestMeta {\n /**\n * The query that was used to make the request.\n */\n initQuery?: ParsedUrlQuery\n\n /**\n * The URL that was used to make the request.\n */\n initURL?: string\n\n /**\n * The protocol that was used to make the request.\n */\n initProtocol?: string\n\n /**\n * The body that was read from the request. This is used to allow the body to\n * be read multiple times.\n */\n clonableBody?: CloneableBody\n\n /**\n * True when the request matched a locale domain that was configured in the\n * next.config.js file.\n */\n isLocaleDomain?: boolean\n\n /**\n * True when the request had locale information stripped from the pathname\n * part of the URL.\n */\n didStripLocale?: boolean\n\n /**\n * If the request had its URL rewritten, this is the pathname it was rewritten\n * to (not a full URL, just the pathname).\n */\n rewrittenPathname?: string\n\n /**\n * The cookies that were added by middleware and were added to the response.\n */\n middlewareCookie?: string[]\n\n /**\n * The match on the request for a given route.\n */\n match?: RouteMatch\n\n /**\n * The incremental cache to use for the request.\n */\n incrementalCache?: IncrementalCache\n\n /**\n * The server components HMR cache, only for dev.\n */\n serverComponentsHmrCache?: ServerComponentsHmrCache\n\n /**\n * The hash of the most recent server component change (dev only), set by the\n * router-server from the hot-reloader. Included in `\"use cache\"` cache keys\n * so that cached entries are revalidated after an edit, for every client,\n * regardless of whether it runs the HMR client.\n */\n hmrRefreshHash?: string\n\n /**\n * Equals the segment path that was used for the prefetch RSC request.\n */\n segmentPrefetchRSCRequest?: string\n\n /**\n * True when the request is for the prefetch flight data.\n */\n isPrefetchRSCRequest?: true\n\n /**\n * True when the request is for the flight data.\n */\n isRSCRequest?: true\n\n /**\n * A search param set by the Next.js client when performing RSC requests.\n * Because some CDNs do not vary their cache entries on our custom headers,\n * this search param represents a hash of the header values. For any cached\n * RSC request, we should verify that the hash matches before responding.\n * Otherwise this can lead to cache poisoning.\n * TODO: Consider not using custom request headers at all, and instead encode\n * everything into the search param.\n */\n cacheBustingSearchParam?: string\n\n /**\n * True when the request is for the `/_next/data` route using the pages\n * router.\n */\n isNextDataReq?: true\n\n /**\n * Postponed state to use for resumption. When absent, the request is not a\n * resume request. A non-empty string contains the state to resume, while an\n * empty string represents a resume request without postponed state and\n * signals that the renderer should perform a full dynamic render.\n *\n * There are no guarantees that the page actually postponed, as verifying\n * that would incur an additional cache lookup.\n */\n postponed?: string\n\n /**\n * The action body extracted from a server action request when the postponed\n * state was prepended to the body by the proxy. This allows the action\n * handler to read the action payload without re-reading the consumed stream.\n */\n actionBody?: Buffer\n\n /**\n * If provided, this will be called when a response cache entry was generated\n * or looked up in the cache.\n *\n * @deprecated Use `onCacheEntryV2` instead.\n */\n onCacheEntry?: OnCacheEntryHandler\n\n /**\n * If provided, this will be called when a response cache entry was generated\n * or looked up in the cache.\n */\n onCacheEntryV2?: OnCacheEntryHandler\n\n /**\n * The previous revalidate before rendering 404 page for notFound: true\n */\n notFoundRevalidate?: number | false\n\n /**\n * In development, the original source page that returned a 404.\n */\n developmentNotFoundSourcePage?: string\n\n /**\n * The path we routed to and should be invoked\n */\n invokePath?: string\n\n /**\n * The specific page output we should be matching\n */\n invokeOutput?: string\n\n /**\n * The status we are invoking the request with from routing\n */\n invokeStatus?: number\n\n /**\n * The routing error we are invoking with\n */\n invokeError?: Error\n\n /**\n * The query parsed for the invocation\n */\n invokeQuery?: Record\n\n /**\n * Whether the request is a middleware invocation\n */\n middlewareInvoke?: boolean\n\n /**\n * Whether the request should render the fallback shell or not.\n */\n renderFallbackShell?: boolean\n\n /**\n * Route param keys that were explicitly resolved from partial nxtP*\n * query params during background revalidation. Used by app-page.ts to\n * determine which fallback params should remain deferred vs resolved\n * in intermediate PPR shells.\n */\n resolvedRouteParamKeys?: Set\n\n /**\n * Whether the request is for the custom error page.\n */\n customErrorRender?: true\n\n /**\n * Whether to bubble up the NoFallbackError to the caller when a 404 is\n * returned.\n */\n bubbleNoFallback?: true\n\n /**\n * True when the request had locale information inferred from the default\n * locale.\n */\n localeInferredFromDefault?: true\n\n /**\n * The locale that was inferred or explicitly set for the request.\n */\n locale?: string\n\n /**\n * The default locale that was inferred or explicitly set for the request.\n */\n defaultLocale?: string\n\n /**\n * The relative project dir the server is running in from project root\n */\n relativeProjectDir?: string\n\n /**\n * The dist directory the server is currently using\n */\n distDir?: string\n\n /**\n Optional hostname used by route handlers when constructing absolute URLs.\n hostname: '127.0.0.1',\n */\n hostname?: string\n\n /**\n Optional internal revalidate function to avoid revalidating over the network\n */\n revalidate?: RevalidateFn\n\n /**\n Optional function to render the 404 page for pages router `notFound: true`\n */\n render404?: (\n req: IncomingMessage,\n res: ServerResponse,\n parsedUrl?: UrlWithParsedQuery,\n setHeaders?: boolean\n ) => Promise\n\n /**\n * The query after resolving routes\n */\n query?: ParsedUrlQuery\n\n /**\n * The params after resolving routes\n */\n params?: ParsedUrlQuery\n\n /**\n * ErrorOverlay component to use in development for pages router\n */\n PagesErrorDebug?: PagesDevOverlayBridgeType\n\n /**\n * Whether server is in minimal mode (this will be replaced with more\n * specific flags in future)\n */\n minimalMode?: boolean\n\n /**\n * Staged renders defer these route params until after the static stage. They\n * keep their concrete request values instead of replacing them with\n * placeholders. Dev static-shell validation uses the same set for the\n * selected shell.\n *\n * For `/t2/items/b2` with selected shell `/t2/items/[bottom]`, this map\n * contains only `bottom`:\n * - A layout's `params` containing only `top` can resolve statically.\n * - A page's `params` containing `bottom` waits until after the static stage.\n *\n * A set recorded in postponed state overrides this metadata on a resume,\n * including an explicitly empty set.\n */\n stagedFallbackParams?: OpaqueFallbackRouteParams | null\n\n /**\n * Dev static-shell debug renders use these params to prerender the matched\n * source shell. The Instant Navigation Testing API uses this path too. The\n * prerender substitutes opaque placeholders for these params rather than\n * using their request values.\n *\n * Suppose `generateStaticParams` returns `[{ top: 't1' }]` for\n * `/[top]/items/[bottom]`. A request for `/t2/items/b2` has:\n * - Source `/[top]/items/[bottom]`: `top` and `bottom` are unresolved.\n * - Completed shell `/t2/items/[bottom]`: only `bottom` is unresolved.\n *\n * This map contains the source's `top` and `bottom`. A debug render of that\n * source also uses this map as `stagedFallbackParams`.\n */\n fallbackRouteParams?: OpaqueFallbackRouteParams | null\n\n /** DEV only: parameter matching rejected this request as not found. */\n devParamMatchingRejected?: boolean\n\n /** DEV only: closed parameters, including for successful allowed values. */\n devNotFoundParams?: readonly string[]\n\n /**\n * DEV only: Request timings in process.hrtime.bigint()\n */\n devRequestTimingStart?: bigint\n devRequestTimingMiddlewareStart?: bigint\n devRequestTimingMiddlewareEnd?: bigint\n devRequestTimingInternalsEnd?: bigint\n\n /**\n * DEV only: The duration of getStaticPaths/generateStaticParams in process.hrtime.bigint()\n */\n devGenerateStaticParamsDuration?: bigint\n\n /**\n * DEV only: Server action log info to be logged after the request log\n */\n devServerActionLog?: {\n functionName: string\n args: unknown[]\n location: string\n duration: number\n }\n}\n\n/**\n * Gets the request metadata. If no key is provided, the entire metadata object\n * is returned.\n *\n * @param req the request to get the metadata from\n * @param key the key to get from the metadata (optional)\n * @returns the value for the key or the entire metadata object\n */\nexport function getRequestMeta(\n req: NextIncomingMessage,\n key?: undefined\n): RequestMeta\nexport function getRequestMeta(\n req: NextIncomingMessage,\n key: K\n): RequestMeta[K]\nexport function getRequestMeta(\n req: NextIncomingMessage,\n key?: K\n): RequestMeta | RequestMeta[K] {\n const meta = req[NEXT_REQUEST_META] || {}\n return typeof key === 'string' ? meta[key] : meta\n}\n\n/**\n * Sets the request metadata.\n *\n * @param req the request to set the metadata on\n * @param meta the metadata to set\n * @returns the mutated request metadata\n */\nexport function setRequestMeta(req: NextIncomingMessage, meta: RequestMeta) {\n req[NEXT_REQUEST_META] = meta\n return meta\n}\n\n/**\n * Adds a value to the request metadata.\n *\n * @param request the request to mutate\n * @param key the key to set\n * @param value the value to set\n * @returns the mutated request metadata\n */\nexport function addRequestMeta(\n request: NextIncomingMessage,\n key: K,\n value: RequestMeta[K]\n) {\n const meta = getRequestMeta(request)\n meta[key] = value\n return setRequestMeta(request, meta)\n}\n\n/**\n * Removes a key from the request metadata.\n *\n * @param request the request to mutate\n * @param key the key to remove\n * @returns the mutated request metadata\n */\nexport function removeRequestMeta(\n request: NextIncomingMessage,\n key: K\n) {\n const meta = getRequestMeta(request)\n delete meta[key]\n return setRequestMeta(request, meta)\n}\n\ntype NextQueryMetadata = {\n /**\n * The `_rsc` query parameter used for cache busting to ensure that the RSC\n * requests do not get cached by the browser explicitly.\n */\n [NEXT_RSC_UNION_QUERY]?: string\n}\n\nexport type NextParsedUrlQuery = ParsedUrlQuery & NextQueryMetadata\n\n/**\n * subset of `url.parse` return value\n */\ninterface LegacyUrl {\n auth?: string | null\n hash: string | null\n hostname: string | null\n href: string\n pathname: string | null\n protocol: string | null\n search: string | null\n slashes: boolean | null\n port: string | null\n query: string | null | ParsedUrlQuery\n}\ninterface LegacyUrlWithParsedQuery extends LegacyUrl {\n query: ParsedUrlQuery\n}\n\n// TODO: Remove in favor of WHATWG URLs\nexport interface NextUrlWithParsedQuery extends LegacyUrlWithParsedQuery {\n query: NextParsedUrlQuery\n}\n"],"names":["NEXT_REQUEST_META","addRequestMeta","getRequestMeta","removeRequestMeta","setRequestMeta","Symbol","for","req","key","meta","request","value"],"mappings":";;;;;;;;;;;;;;;;;;IAkBaA,iBAAiB;eAAjBA;;IAkZGC,cAAc;eAAdA;;IA5BAC,cAAc;eAAdA;;IA6CAC,iBAAiB;eAAjBA;;IA9BAC,cAAc;eAAdA;;;AArYT,MAAMJ,oBAAoBK,OAAOC,GAAG,CAAC;AAsXrC,SAASJ,eACdK,GAAwB,EACxBC,GAAO;IAEP,MAAMC,OAAOF,GAAG,CAACP,kBAAkB,IAAI,CAAC;IACxC,OAAO,OAAOQ,QAAQ,WAAWC,IAAI,CAACD,IAAI,GAAGC;AAC/C;AASO,SAASL,eAAeG,GAAwB,EAAEE,IAAiB;IACxEF,GAAG,CAACP,kBAAkB,GAAGS;IACzB,OAAOA;AACT;AAUO,SAASR,eACdS,OAA4B,EAC5BF,GAAM,EACNG,KAAqB;IAErB,MAAMF,OAAOP,eAAeQ;IAC5BD,IAAI,CAACD,IAAI,GAAGG;IACZ,OAAOP,eAAeM,SAASD;AACjC;AASO,SAASN,kBACdO,OAA4B,EAC5BF,GAAM;IAEN,MAAMC,OAAOP,eAAeQ;IAC5B,OAAOD,IAAI,CAACD,IAAI;IAChB,OAAOJ,eAAeM,SAASD;AACjC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/cache-stages.d.ts b/e-commerce/node_modules/next/dist/server/request/cache-stages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7766a2936181dbbd4a516a60f76e0028abdd9239 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/cache-stages.d.ts @@ -0,0 +1,28 @@ +/** + * When `partialPrefetching` is enabled, this function allows you to indicate + * that the subsequent code should be excluded from the shell. It will be deferred until + * a prefetch (i.e. when using ``) or a navigation. + * + * It has no effect during static prerendering — static output is computed + * once and shared across many clients, so there's no per-request cost to + * save — and no effect on the initial load of a page. + * + * Unlike `connection()`, it does not mark the subtree as request-dependent — + * content below `await prefetch()` remains fully cacheable. + */ +export declare function prefetch(): Promise; +/** + * This function allows you to indicate that the subsequent code should be + * deferred to the actual navigation instead of rendering during a runtime + * prefetch. Runtime prefetches are rendered per-user, per-link, so deferring + * content below `await navigation()` saves that per-request + * rendering cost. + * + * It has no effect during static prerendering — static output is computed + * once and shared across many clients, so there's no per-request cost to + * save — and no effect on the initial load of a page. + * + * Unlike `connection()`, it does not mark the subtree as request-dependent — + * content below `await navigation()` remains fully cacheable. + */ +export declare function navigation(): Promise; diff --git a/e-commerce/node_modules/next/dist/server/request/cache-stages.js b/e-commerce/node_modules/next/dist/server/request/cache-stages.js new file mode 100644 index 0000000000000000000000000000000000000000..5da02a9369c944d0f1bfb8b5ba6a44bf4339d2bb --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/cache-stages.js @@ -0,0 +1,250 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + navigation: null, + prefetch: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + navigation: function() { + return navigation; + }, + prefetch: function() { + return prefetch; + } +}); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _utils = require("./utils"); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _stagedrendering = require("../app-render/staged-rendering"); +function prefetch() { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (!workStore || !workUnitStore) { + const callingExpression = 'prefetch'; + (0, _workunitasyncstorageexternal.throwForMissingRequestStore)(callingExpression); + } + if (!process.env.__NEXT_CACHE_COMPONENTS) { + throw new Error(`Route ${workStore.route} used \`prefetch()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`); + } + if (!(0, _utils.isRequestApiAllowedInCurrentPhase)(workUnitStore)) { + throw new Error(`Route ${workStore.route} used \`prefetch()\` inside \`after()\` while rendering. The \`prefetch()\` function is used to indicate the subsequent code must not run in the app shell, but \`after()\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`); + } + const stageVariants = _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.staticUrlData.prefetchApi; + switch(workUnitStore.type){ + case 'prerender': + { + // Content below `prefetch()` is excluded from the shell, but it's + // deliberately included in the static output (and thus in static + // prefetches), so we only delay it until the static prefetch stage. + // It resolves in `PrefetchStatic_prefetchApi`, one stage ahead of URL data, + // so validation can attribute a blocking hole to `prefetch()`. + const { stagedRendering } = workUnitStore; + if (!stagedRendering) { + // Prospective prerender + // `prefetch()` will resolve in the final prerender, so resolve it here as well. + return Promise.resolve(undefined); + } else { + // Final prerender + return stagedRendering.delayUntilStage(stageVariants.static, 'prefetch', undefined); + } + } + case 'prerender-runtime': + { + // In a shell render, prefetch() doesn't resolve, because it doesn't reach + // `PrefetchRuntime`. It'll resolve in a runtime prefetch, and in a runtime + // prerender produced during a navigation. + // Note that this does not mark the subtree as dynamic -- content guarded by + // prefetch() is still considered cacheable. + const { stagedRendering } = workUnitStore; + const prefetchStage = stageVariants.runtime; + if (!stagedRendering) { + // Prospective prerender + // Make sure we don't unblock content that won't be reached in the final prerender. + if (workUnitStore.finalStage < prefetchStage) { + return (0, _dynamicrenderingutils.makePrefetchHangingPromise)(workUnitStore.renderSignal, workStore.route, '`prefetch()`'); + } else { + return Promise.resolve(undefined); + } + } else { + // Final prerender + return stagedRendering.delayUntilStage(prefetchStage, 'prefetch', undefined); + } + } + case 'request': + { + const { stagedRendering } = workUnitStore; + if (stagedRendering) { + // We can either recover a static shell or a runtime shell, but not both. + (0, _dynamicrenderingutils.trackIncompatibleShellContent)(workUnitStore, '`prefetch()`'); + const stage = stageVariants[workUnitStore.needsRuntimeShell ? 'runtime' // Match the timing of 'prerender-runtime'. + : 'static' // Match the timing of 'prerender'. + ]; + return stagedRendering.delayUntilStage(stage, 'prefetch', undefined); + } + return Promise.resolve(undefined); + } + case 'cache': + { + const error = new Error(`Route ${workStore.route} used \`prefetch()\` inside "use cache". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await prefetch()\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`); + Error.captureStackTrace(error, prefetch); + (0, _dynamicrenderingutils.applyOwnerStack)(error); + workStore.invalidDynamicUsageError ??= error; + throw error; + } + case 'private-cache': + { + const error = new Error(`Route ${workStore.route} used \`prefetch()\` inside "use cache: private". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await prefetch()\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`); + Error.captureStackTrace(error, prefetch); + (0, _dynamicrenderingutils.applyOwnerStack)(error); + workStore.invalidDynamicUsageError ??= error; + throw error; + } + case 'unstable-cache': + { + throw new Error(`Route ${workStore.route} used \`prefetch()\` inside a function cached with \`unstable_cache()\`. The \`prefetch()\` function is used to indicate the subsequent code must not run in the app shell, but \`unstable_cache()\` caches must be able to be produced before a prefetch, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`); + } + case 'build-time-generator': + { + throw new Error(`Route ${workStore.route} used \`prefetch()\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without a prefetch. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`); + } + case 'prerender-client': + case 'validation-client': + { + const exportName = '`prefetch`'; + throw new _invarianterror.InvariantError(`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`); + } + case 'prerender-legacy': + { + // NOTE: Should not be reachable, because we don't use this mode in cacheComponents, + // which we require at the top + throw new Error(`Route ${workStore.route} used \`prefetch()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`); + } + default: + { + workUnitStore; + return Promise.resolve(undefined); + } + } +} +function navigation() { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (!workStore || !workUnitStore) { + const callingExpression = 'navigation'; + (0, _workunitasyncstorageexternal.throwForMissingRequestStore)(callingExpression); + } + if (!process.env.__NEXT_CACHE_COMPONENTS) { + throw new Error(`Route ${workStore.route} used \`navigation()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`); + } + if (!(0, _utils.isRequestApiAllowedInCurrentPhase)(workUnitStore)) { + throw new Error(`Route ${workStore.route} used \`navigation()\` inside \`after()\` while rendering. The \`navigation()\` function is used to indicate the subsequent code must only run during an actual navigation, but \`after()\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`); + } + switch(workUnitStore.type){ + case 'prerender': + { + // Static prerenders are computed once and shared across many + // clients, so there's no per-request prefetch cost to save by + // deferring the content — it's deliberately included in the static + // output (and thus in static prefetches). + // However, it's excluded from the shell, and has to be separated from + // prefetch(), so we have to delay it. + const { stagedRendering } = workUnitStore; + if (!stagedRendering) { + // Prospective prerender + // `navigation()` will resolve in the final prerender, so resolve it here as well. + return Promise.resolve(undefined); + } else { + // Final prerender + return stagedRendering.delayUntilStage(_stagedrendering.RenderStage.NavigationStatic, 'navigation', undefined); + } + } + case 'prerender-runtime': + { + // In a shell or runtime prefetch, navigation() doesn't resolve, + // because they don't reach `NavigationRuntime`. + // It'll only resolve in a runtime prerender produced during a navigation. + // Note that this does not mark the subtree as dynamic -- content guarded by + // navigation() is still considered cacheable. + const { stagedRendering } = workUnitStore; + const navigationStage = _stagedrendering.RenderStage.NavigationRuntime; + if (!stagedRendering) { + // Prospective prerender + // Make sure we don't unblock content that won't be reached in the final prerender. + if (workUnitStore.finalStage < navigationStage) { + return (0, _dynamicrenderingutils.makeUntrackedHangingPromise)(workUnitStore.renderSignal, workStore.route, '`navigation()`'); + } else { + return Promise.resolve(undefined); + } + } else { + // Final prerender + return stagedRendering.delayUntilStage(navigationStage, 'navigation', undefined); + } + } + case 'request': + { + const { stagedRendering } = workUnitStore; + if (stagedRendering) { + // We can either recover a static shell or a runtime shell, but not both. + (0, _dynamicrenderingutils.trackIncompatibleShellContent)(workUnitStore, '`navigation()`'); + const stage = workUnitStore.needsRuntimeShell ? _stagedrendering.RenderStage.NavigationRuntime // Match the timing of 'prerender-runtime'. + : _stagedrendering.RenderStage.NavigationStatic // Match the timing of 'prerender'. + ; + return stagedRendering.delayUntilStage(stage, 'navigation', undefined); + } + return Promise.resolve(undefined); + } + case 'cache': + { + const error = new Error(`Route ${workStore.route} used \`navigation()\` inside "use cache". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await navigation()\`, so that the cached content is deferred to the navigation without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`); + Error.captureStackTrace(error, navigation); + (0, _dynamicrenderingutils.applyOwnerStack)(error); + workStore.invalidDynamicUsageError ??= error; + throw error; + } + case 'private-cache': + { + const error = new Error(`Route ${workStore.route} used \`navigation()\` inside "use cache: private". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await navigation()\`, so that the cached content is deferred to the navigation without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`); + Error.captureStackTrace(error, navigation); + (0, _dynamicrenderingutils.applyOwnerStack)(error); + workStore.invalidDynamicUsageError ??= error; + throw error; + } + case 'unstable-cache': + { + throw new Error(`Route ${workStore.route} used \`navigation()\` inside a function cached with \`unstable_cache()\`. The \`navigation()\` function is used to indicate the subsequent code must only run during an actual navigation, but \`unstable_cache()\` caches must be able to be produced before a navigation, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`); + } + case 'build-time-generator': + { + throw new Error(`Route ${workStore.route} used \`navigation()\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without a navigation. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`); + } + case 'prerender-client': + case 'validation-client': + { + const exportName = '`navigation`'; + throw new _invarianterror.InvariantError(`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`); + } + case 'prerender-legacy': + { + // NOTE: Should not be reachable, because we don't use this mode in cacheComponents, + // which we require at the top + throw new Error(`Route ${workStore.route} used \`navigation()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`); + } + default: + { + workUnitStore; + return Promise.resolve(undefined); + } + } +} + +//# sourceMappingURL=cache-stages.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/cache-stages.js.map b/e-commerce/node_modules/next/dist/server/request/cache-stages.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6dc3a3bdce4477d1c9fdd50a0467d2a9c4db5870 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/cache-stages.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/cache-stages.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n applyOwnerStack,\n makePrefetchHangingPromise,\n makeUntrackedHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n trackIncompatibleShellContent,\n} from '../dynamic-rendering-utils'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { RenderStage } from '../app-render/staged-rendering'\n\n/**\n * When `partialPrefetching` is enabled, this function allows you to indicate\n * that the subsequent code should be excluded from the shell. It will be deferred until\n * a prefetch (i.e. when using ``) or a navigation.\n *\n * It has no effect during static prerendering — static output is computed\n * once and shared across many clients, so there's no per-request cost to\n * save — and no effect on the initial load of a page.\n *\n * Unlike `connection()`, it does not mark the subtree as request-dependent —\n * content below `await prefetch()` remains fully cacheable.\n */\nexport function prefetch(): Promise {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workStore || !workUnitStore) {\n const callingExpression = 'prefetch'\n throwForMissingRequestStore(callingExpression)\n }\n if (!process.env.__NEXT_CACHE_COMPONENTS) {\n throw new Error(\n `Route ${workStore.route} used \\`prefetch()\\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`\n )\n }\n\n if (!isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`prefetch()\\` inside \\`after()\\` while rendering. The \\`prefetch()\\` function is used to indicate the subsequent code must not run in the app shell, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n const stageVariants = RENDER_STAGES_BY_DATA_KIND.staticUrlData.prefetchApi\n switch (workUnitStore.type) {\n case 'prerender': {\n // Content below `prefetch()` is excluded from the shell, but it's\n // deliberately included in the static output (and thus in static\n // prefetches), so we only delay it until the static prefetch stage.\n // It resolves in `PrefetchStatic_prefetchApi`, one stage ahead of URL data,\n // so validation can attribute a blocking hole to `prefetch()`.\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // Prospective prerender\n // `prefetch()` will resolve in the final prerender, so resolve it here as well.\n return Promise.resolve(undefined)\n } else {\n // Final prerender\n return stagedRendering.delayUntilStage(\n stageVariants.static,\n 'prefetch',\n undefined\n )\n }\n }\n case 'prerender-runtime': {\n // In a shell render, prefetch() doesn't resolve, because it doesn't reach\n // `PrefetchRuntime`. It'll resolve in a runtime prefetch, and in a runtime\n // prerender produced during a navigation.\n // Note that this does not mark the subtree as dynamic -- content guarded by\n // prefetch() is still considered cacheable.\n const { stagedRendering } = workUnitStore\n const prefetchStage = stageVariants.runtime\n if (!stagedRendering) {\n // Prospective prerender\n // Make sure we don't unblock content that won't be reached in the final prerender.\n if (workUnitStore.finalStage < prefetchStage) {\n return makePrefetchHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`prefetch()`'\n )\n } else {\n return Promise.resolve(undefined)\n }\n } else {\n // Final prerender\n return stagedRendering.delayUntilStage(\n prefetchStage,\n 'prefetch',\n undefined\n )\n }\n }\n case 'request': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n // We can either recover a static shell or a runtime shell, but not both.\n trackIncompatibleShellContent(workUnitStore, '`prefetch()`')\n const stage =\n stageVariants[\n workUnitStore.needsRuntimeShell\n ? 'runtime' // Match the timing of 'prerender-runtime'.\n : 'static' // Match the timing of 'prerender'.\n ]\n\n return stagedRendering.delayUntilStage(stage, 'prefetch', undefined)\n }\n return Promise.resolve(undefined)\n }\n\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`prefetch()\\` inside \"use cache\". This is not currently supported. Instead, move the \"use cache\" directive to a function that's called below \\`await prefetch()\\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, prefetch)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'private-cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`prefetch()\\` inside \"use cache: private\". This is not currently supported. Instead, move the \"use cache\" directive to a function that's called below \\`await prefetch()\\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, prefetch)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache': {\n throw new Error(\n `Route ${workStore.route} used \\`prefetch()\\` inside a function cached with \\`unstable_cache()\\`. The \\`prefetch()\\` function is used to indicate the subsequent code must not run in the app shell, but \\`unstable_cache()\\` caches must be able to be produced before a prefetch, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n }\n case 'build-time-generator': {\n throw new Error(\n `Route ${workStore.route} used \\`prefetch()\\` inside \\`${workUnitStore.functionName}\\`. This is not supported because \\`${workUnitStore.functionName}\\` runs at build time without a prefetch. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n }\n case 'prerender-client':\n case 'validation-client': {\n const exportName = '`prefetch`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'prerender-legacy': {\n // NOTE: Should not be reachable, because we don't use this mode in cacheComponents,\n // which we require at the top\n throw new Error(\n `Route ${workStore.route} used \\`prefetch()\\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`\n )\n }\n\n default: {\n workUnitStore satisfies never\n return Promise.resolve(undefined)\n }\n }\n}\n\n/**\n * This function allows you to indicate that the subsequent code should be\n * deferred to the actual navigation instead of rendering during a runtime\n * prefetch. Runtime prefetches are rendered per-user, per-link, so deferring\n * content below `await navigation()` saves that per-request\n * rendering cost.\n *\n * It has no effect during static prerendering — static output is computed\n * once and shared across many clients, so there's no per-request cost to\n * save — and no effect on the initial load of a page.\n *\n * Unlike `connection()`, it does not mark the subtree as request-dependent —\n * content below `await navigation()` remains fully cacheable.\n */\nexport function navigation(): Promise {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workStore || !workUnitStore) {\n const callingExpression = 'navigation'\n throwForMissingRequestStore(callingExpression)\n }\n if (!process.env.__NEXT_CACHE_COMPONENTS) {\n throw new Error(\n `Route ${workStore.route} used \\`navigation()\\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`\n )\n }\n\n if (!isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`navigation()\\` inside \\`after()\\` while rendering. The \\`navigation()\\` function is used to indicate the subsequent code must only run during an actual navigation, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n switch (workUnitStore.type) {\n case 'prerender': {\n // Static prerenders are computed once and shared across many\n // clients, so there's no per-request prefetch cost to save by\n // deferring the content — it's deliberately included in the static\n // output (and thus in static prefetches).\n // However, it's excluded from the shell, and has to be separated from\n // prefetch(), so we have to delay it.\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // Prospective prerender\n // `navigation()` will resolve in the final prerender, so resolve it here as well.\n return Promise.resolve(undefined)\n } else {\n // Final prerender\n return stagedRendering.delayUntilStage(\n RenderStage.NavigationStatic,\n 'navigation',\n undefined\n )\n }\n }\n case 'prerender-runtime': {\n // In a shell or runtime prefetch, navigation() doesn't resolve,\n // because they don't reach `NavigationRuntime`.\n // It'll only resolve in a runtime prerender produced during a navigation.\n // Note that this does not mark the subtree as dynamic -- content guarded by\n // navigation() is still considered cacheable.\n const { stagedRendering } = workUnitStore\n const navigationStage = RenderStage.NavigationRuntime\n if (!stagedRendering) {\n // Prospective prerender\n // Make sure we don't unblock content that won't be reached in the final prerender.\n if (workUnitStore.finalStage < navigationStage) {\n return makeUntrackedHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`navigation()`'\n )\n } else {\n return Promise.resolve(undefined)\n }\n } else {\n // Final prerender\n return stagedRendering.delayUntilStage(\n navigationStage,\n 'navigation',\n undefined\n )\n }\n }\n case 'request': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n // We can either recover a static shell or a runtime shell, but not both.\n trackIncompatibleShellContent(workUnitStore, '`navigation()`')\n const stage = workUnitStore.needsRuntimeShell\n ? RenderStage.NavigationRuntime // Match the timing of 'prerender-runtime'.\n : RenderStage.NavigationStatic // Match the timing of 'prerender'.\n\n return stagedRendering.delayUntilStage(stage, 'navigation', undefined)\n }\n return Promise.resolve(undefined)\n }\n\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`navigation()\\` inside \"use cache\". This is not currently supported. Instead, move the \"use cache\" directive to a function that's called below \\`await navigation()\\`, so that the cached content is deferred to the navigation without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, navigation)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'private-cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`navigation()\\` inside \"use cache: private\". This is not currently supported. Instead, move the \"use cache\" directive to a function that's called below \\`await navigation()\\`, so that the cached content is deferred to the navigation without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, navigation)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache': {\n throw new Error(\n `Route ${workStore.route} used \\`navigation()\\` inside a function cached with \\`unstable_cache()\\`. The \\`navigation()\\` function is used to indicate the subsequent code must only run during an actual navigation, but \\`unstable_cache()\\` caches must be able to be produced before a navigation, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n }\n case 'build-time-generator': {\n throw new Error(\n `Route ${workStore.route} used \\`navigation()\\` inside \\`${workUnitStore.functionName}\\`. This is not supported because \\`${workUnitStore.functionName}\\` runs at build time without a navigation. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n }\n case 'prerender-client':\n case 'validation-client': {\n const exportName = '`navigation`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'prerender-legacy': {\n // NOTE: Should not be reachable, because we don't use this mode in cacheComponents,\n // which we require at the top\n throw new Error(\n `Route ${workStore.route} used \\`navigation()\\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`\n )\n }\n\n default: {\n workUnitStore satisfies never\n return Promise.resolve(undefined)\n }\n }\n}\n"],"names":["navigation","prefetch","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","callingExpression","throwForMissingRequestStore","process","env","__NEXT_CACHE_COMPONENTS","Error","route","isRequestApiAllowedInCurrentPhase","stageVariants","RENDER_STAGES_BY_DATA_KIND","staticUrlData","prefetchApi","type","stagedRendering","Promise","resolve","undefined","delayUntilStage","static","prefetchStage","runtime","finalStage","makePrefetchHangingPromise","renderSignal","trackIncompatibleShellContent","stage","needsRuntimeShell","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","functionName","exportName","InvariantError","RenderStage","NavigationStatic","navigationStage","NavigationRuntime","makeUntrackedHangingPromise"],"mappings":";;;;;;;;;;;;;;;IAoLgBA,UAAU;eAAVA;;IAxJAC,QAAQ;eAARA;;;0CA5BiB;8CAI1B;uCAOA;uBAC2C;gCACnB;iCACH;AAcrB,SAASA;IACd,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAI,CAACF,aAAa,CAACG,eAAe;QA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EV,UAAUW,KAAK,CAAC,kZAAkZ,CAAC;YAEhb;QACA,KAAK;YAAwB;gBAC3B,MAAM,IAAID,MACR,CAAC,MAAM,EAAEV,UAAUW,KAAK,CAAC,gCAAgC,EAAER,cAAciC,YAAY,CAAC,oCAAoC,EAAEjC,cAAciC,YAAY,CAAC,sHAAsH,CAAC;YAElR;QACA,KAAK;QACL,KAAK;YAAqB;gBACxB,MAAMC,aAAa;gBACnB,MAAM,IAAIC,8BAAc,CACtB,GAAGD,WAAW,0EAA0E,EAAEA,WAAW,+EAA+E,CAAC;YAEzL;QACA,KAAK;YAAoB;gBACvB,oFAAoF;gBACpF,8BAA8B;gBAC9B,MAAM,IAAI3B,MACR,CAAC,MAAM,EAAEV,UAAUW,KAAK,CAAC,kKAAkK,CAAC;YAEhM;QAEA;YAAS;gBACPR;gBACA,OAAOgB,QAAQC,OAAO,CAACC;YACzB;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/connection.d.ts b/e-commerce/node_modules/next/dist/server/request/connection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d44dc1b92c8d9b43b51256772ca546f6548af724 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/connection.d.ts @@ -0,0 +1,6 @@ +/** + * This function allows you to indicate that you require an actual user Request before continuing. + * + * During prerendering it will never resolve and during rendering it resolves immediately. + */ +export declare function connection(): Promise; diff --git a/e-commerce/node_modules/next/dist/server/request/connection.js b/e-commerce/node_modules/next/dist/server/request/connection.js new file mode 100644 index 0000000000000000000000000000000000000000..8a5ab4e6361c63a440eb4ac60bb18f069cc9a887 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/connection.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "connection", { + enumerable: true, + get: function() { + return connection; + } +}); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _dynamicrendering = require("../app-render/dynamic-rendering"); +const _staticgenerationbailout = require("../../client/components/static-generation-bailout"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _utils = require("./utils"); +const _stagedrendering = require("../app-render/staged-rendering"); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _usecachemessages = require("../use-cache/use-cache-messages"); +function connection() { + const callingExpression = 'connection'; + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workStore) { + if (workUnitStore && !(0, _utils.isRequestApiAllowedInCurrentPhase)(workUnitStore)) { + throw new Error(`Route ${workStore.route} used \`connection()\` inside \`after()\` while rendering. The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but \`after()\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`); + } + if (workStore.forceStatic) { + // When using forceStatic, we override all other logic and always just + // return a resolving promise without tracking. + return Promise.resolve(undefined); + } + if (workStore.dynamicShouldError) { + throw new _staticgenerationbailout.StaticGenBailoutError(`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection()\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`); + } + if (workUnitStore) { + switch(workUnitStore.type){ + case 'cache': + { + const error = (0, _usecachemessages.createConnectionInPublicUseCacheError)(workStore.route); + Error.captureStackTrace(error, connection); + (0, _dynamicrenderingutils.applyOwnerStack)(error); + workStore.invalidDynamicUsageError ??= error; + throw error; + } + case 'private-cache': + { + // It might not be intuitive to throw for private caches as well, but + // we don't consider runtime prefetches as "actual requests" (in the + // navigation sense), despite allowing them to read cookies. + const error = (0, _usecachemessages.createConnectionInPrivateUseCacheError)(workStore.route); + Error.captureStackTrace(error, connection); + (0, _dynamicrenderingutils.applyOwnerStack)(error); + workStore.invalidDynamicUsageError ??= error; + throw error; + } + case 'unstable-cache': + throw (0, _usecachemessages.createConnectionInUnstableCacheError)(workStore.route); + case 'build-time-generator': + throw new Error(`Route ${workStore.route} used \`connection()\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`); + case 'prerender': + case 'prerender-client': + case 'prerender-runtime': + // We return a promise that never resolves to allow the prerender to + // stall at this point. + return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(workUnitStore.renderSignal, workStore.route, '`connection()`'); + case 'validation-client': + { + // TODO(NAR-789): make this consistent with the actual browser behavior when we change it. + // Until then, erroring is fine. + const exportName = '`connection`'; + throw new _invarianterror.InvariantError(`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`); + } + case 'prerender-legacy': + // We throw an error here to interrupt prerendering to mark the route + // as dynamic + return (0, _dynamicrendering.throwToInterruptStaticGeneration)('connection', workStore, workUnitStore); + case 'request': + (0, _dynamicrendering.trackDynamicDataInDynamicRender)(workUnitStore); + if (process.env.NODE_ENV === 'development') { + // Semantically we only need the dev tracking when running in `next dev` + // but since you would never use next dev with production NODE_ENV we use this + // as a proxy so we can statically exclude this code from production builds. + if (workUnitStore.asyncApiPromises) { + return workUnitStore.asyncApiPromises.connection; + } + return (0, _dynamicrenderingutils.makeDevtoolsIOAwarePromise)(undefined, workUnitStore, _stagedrendering.RenderStage.Dynamic); + } else if (workUnitStore.asyncApiPromises) { + return workUnitStore.asyncApiPromises.connection; + } else { + return Promise.resolve(undefined); + } + default: + workUnitStore; + } + } + } + // If we end up here, there was no work store or work unit store present. + // TODO(NAR-789): connection() is not currently statically prevented from being imported in client components, + // so we always error about a missing work unit store. + (0, _workunitasyncstorageexternal.throwForMissingRequestStore)(callingExpression); +} + +//# sourceMappingURL=connection.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/connection.js.map b/e-commerce/node_modules/next/dist/server/request/connection.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6748f9873bde2ee81b7dcf7c4d8d52ef91b0f5f7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/connection.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/connection.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n createConnectionInPublicUseCacheError,\n createConnectionInPrivateUseCacheError,\n createConnectionInUnstableCacheError,\n} from '../use-cache/use-cache-messages'\n\n/**\n * This function allows you to indicate that you require an actual user Request before continuing.\n *\n * During prerendering it will never resolve and during rendering it resolves immediately.\n */\nexport function connection(): Promise {\n const callingExpression = 'connection'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`after()\\` while rendering. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic, we override all other logic and always just\n // return a resolving promise without tracking.\n return Promise.resolve(undefined)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`connection()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = createConnectionInPublicUseCacheError(workStore.route)\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'private-cache': {\n // It might not be intuitive to throw for private caches as well, but\n // we don't consider runtime prefetches as \"actual requests\" (in the\n // navigation sense), despite allowing them to read cookies.\n const error = createConnectionInPrivateUseCacheError(workStore.route)\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw createConnectionInUnstableCacheError(workStore.route)\n case 'build-time-generator':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`${workUnitStore.functionName}\\`. This is not supported because \\`${workUnitStore.functionName}\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // We return a promise that never resolves to allow the prerender to\n // stall at this point.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`connection()`'\n )\n case 'validation-client': {\n // TODO(NAR-789): make this consistent with the actual browser behavior when we change it.\n // Until then, erroring is fine.\n const exportName = '`connection`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'prerender-legacy':\n // We throw an error here to interrupt prerendering to mark the route\n // as dynamic\n return throwToInterruptStaticGeneration(\n 'connection',\n workStore,\n workUnitStore\n )\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n } else {\n return Promise.resolve(undefined)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n // TODO(NAR-789): connection() is not currently statically prevented from being imported in client components,\n // so we always error about a missing work unit store.\n throwForMissingRequestStore(callingExpression)\n}\n"],"names":["connection","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","Promise","resolve","undefined","dynamicShouldError","StaticGenBailoutError","type","error","createConnectionInPublicUseCacheError","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","createConnectionInPrivateUseCacheError","createConnectionInUnstableCacheError","functionName","makeDynamicHangingPromise","renderSignal","exportName","InvariantError","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","process","env","NODE_ENV","asyncApiPromises","makeDevtoolsIOAwarePromise","RenderStage","Dynamic","throwForMissingRequestStore"],"mappings":";;;;+BA6BgBA;;;eAAAA;;;0CA7BiB;8CAI1B;kCAIA;yCAC+B;uCAI/B;uBAC2C;iCAEtB;gCACG;kCAKxB;AAOA,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,wVAAwV,CAAC;QAEtX;QAEA,IAAIP,UAAUQ,WAAW,EAAE;YACzB,sEAAsE;YACtE,+CAA+C;YAC/C,OAAOC,QAAQC,OAAO,CAACC;QACzB;QAEA,IAAIX,UAAUY,kBAAkB,EAAE;YAChC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;oBACHyB,IAAAA,iDAA+B,EAACzB;oBAChC,IAAI0B,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;wBAC1C,wEAAwE;wBACxE,8EAA8E;wBAC9E,4EAA4E;wBAC5E,IAAI5B,cAAc6B,gBAAgB,EAAE;4BAClC,OAAO7B,cAAc6B,gBAAgB,CAAClC,UAAU;wBAClD;wBACA,OAAOmC,IAAAA,iDAA0B,EAC/BtB,WACAR,eACA+B,4BAAW,CAACC,OAAO;oBAEvB,OAAO,IAAIhC,cAAc6B,gBAAgB,EAAE;wBACzC,OAAO7B,cAAc6B,gBAAgB,CAAClC,UAAU;oBAClD,OAAO;wBACL,OAAOW,QAAQC,OAAO,CAACC;oBACzB;gBACF;oBACER;YACJ;QACF;IACF;IAEA,yEAAyE;IACzE,8GAA8G;IAC9G,sDAAsD;IACtDiC,IAAAA,yDAA2B,EAACrC;AAC9B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/cookies.d.ts b/e-commerce/node_modules/next/dist/server/request/cookies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..843d73e324f29e1fc95d612abae37490c3b34cd0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/cookies.d.ts @@ -0,0 +1,2 @@ +import { type ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'; +export declare function cookies(): Promise; diff --git a/e-commerce/node_modules/next/dist/server/request/cookies.js b/e-commerce/node_modules/next/dist/server/request/cookies.js new file mode 100644 index 0000000000000000000000000000000000000000..89e1a2f63b4ee20adb0057fe997e2563ff95325a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/cookies.js @@ -0,0 +1,204 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "cookies", { + enumerable: true, + get: function() { + return cookies; + } +}); +const _requestcookies = require("../web/spec-extension/adapters/request-cookies"); +const _cookies = require("../web/spec-extension/cookies"); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _dynamicrendering = require("../app-render/dynamic-rendering"); +const _staticgenerationbailout = require("../../client/components/static-generation-bailout"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _creatededupedbycallsiteservererrorlogger = require("../create-deduped-by-callsite-server-error-logger"); +const _utils = require("./utils"); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _usecachemessages = require("../use-cache/use-cache-messages"); +function cookies() { + const callingExpression = 'cookies'; + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workStore) { + if (workUnitStore && !(0, _utils.isRequestApiAllowedInCurrentPhase)(workUnitStore)) { + throw new Error(`Route ${workStore.route} used \`cookies()\` inside \`after()\` while rendering. This is not supported. If you need this data inside an \`after()\` callback, use \`cookies()\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`); + } + if (workStore.forceStatic) { + // When using forceStatic we override all other logic and always just return an empty + // cookies object without tracking + const underlyingCookies = createEmptyCookies(); + return makeUntrackedCookies(underlyingCookies); + } + if (workStore.dynamicShouldError) { + throw new _staticgenerationbailout.StaticGenBailoutError(`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies()\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`); + } + if (workUnitStore) { + switch(workUnitStore.type){ + case 'cache': + const error = (0, _usecachemessages.createCookiesInUseCacheError)(workStore.route); + Error.captureStackTrace(error, cookies); + (0, _dynamicrenderingutils.applyOwnerStack)(error); + workStore.invalidDynamicUsageError ??= error; + throw error; + case 'unstable-cache': + throw (0, _usecachemessages.createCookiesInUnstableCacheError)(workStore.route); + case 'build-time-generator': + throw new Error(`Route ${workStore.route} used \`cookies()\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`); + case 'prerender': + return makeHangingCookies(workStore, workUnitStore); + case 'prerender-client': + case 'validation-client': + const exportName = '`cookies`'; + throw new _invarianterror.InvariantError(`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`); + case 'prerender-legacy': + // We track dynamic access here so we don't need to wrap the cookies + // in individual property access tracking. + return (0, _dynamicrendering.throwToInterruptStaticGeneration)(callingExpression, workStore, workUnitStore); + case 'prerender-runtime': + { + const { stagedRendering } = workUnitStore; + if (stagedRendering) { + return stagedRendering.delayUntilStage(_dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.sessionData, 'cookies', workUnitStore.cookies); + } else { + return makeUntrackedCookies(workUnitStore.cookies); + } + } + case 'private-cache': + // Private caches are delayed until the runtime stage in use-cache-wrapper, + // so we don't need an additional delay here. + return makeUntrackedCookies(workUnitStore.cookies); + case 'request': + (0, _dynamicrendering.trackDynamicDataInDynamicRender)(workUnitStore); + let underlyingCookies; + if ((0, _requestcookies.areCookiesMutableInCurrentPhase)(workUnitStore)) { + // We can't conditionally return different types here based on the context. + // To avoid confusion, we always return the readonly type here. + underlyingCookies = workUnitStore.userspaceMutableCookies; + } else { + underlyingCookies = workUnitStore.cookies; + } + if (process.env.NODE_ENV === 'development') { + // Semantically we only need the dev tracking when running in `next dev` + // but since you would never use next dev with production NODE_ENV we use this + // as a proxy so we can statically exclude this code from production builds. + return makeUntrackedCookiesWithDevWarnings(workUnitStore, underlyingCookies, workStore == null ? void 0 : workStore.route); + } else if (workUnitStore.asyncApiPromises) { + if (underlyingCookies === workUnitStore.mutableCookies) { + return workUnitStore.asyncApiPromises.mutableCookies; + } else { + return workUnitStore.asyncApiPromises.cookies; + } + } else { + return makeUntrackedCookies(underlyingCookies); + } + default: + workUnitStore; + } + } + } + // If we end up here, there was no work store or work unit store present. + (0, _workunitasyncstorageexternal.throwForMissingRequestStore)(callingExpression); +} +function createEmptyCookies() { + return _requestcookies.RequestCookiesAdapter.seal(new _cookies.RequestCookies(new Headers({}))); +} +const CachedCookies = new WeakMap(); +function makeHangingCookies(workStore, prerenderStore) { + const cachedPromise = CachedCookies.get(prerenderStore); + if (cachedPromise) { + return cachedPromise; + } + const promise = (0, _dynamicrenderingutils.makeSessionDataHangingPromise)(prerenderStore.renderSignal, workStore.route, '`cookies()`', prerenderStore); + CachedCookies.set(prerenderStore, promise); + return promise; +} +function makeUntrackedCookies(underlyingCookies) { + const cachedCookies = CachedCookies.get(underlyingCookies); + if (cachedCookies) { + return cachedCookies; + } + const promise = Promise.resolve(underlyingCookies); + CachedCookies.set(underlyingCookies, promise); + return promise; +} +function makeUntrackedCookiesWithDevWarnings(requestStore, underlyingCookies, route) { + if (requestStore.asyncApiPromises) { + let promise; + if (underlyingCookies === requestStore.mutableCookies) { + promise = requestStore.asyncApiPromises.mutableCookies; + } else if (underlyingCookies === requestStore.cookies) { + promise = requestStore.asyncApiPromises.cookies; + } else { + throw new _invarianterror.InvariantError('Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'); + } + return instrumentCookiesPromiseWithDevWarnings(promise, route); + } + const cachedCookies = CachedCookies.get(underlyingCookies); + if (cachedCookies) { + return cachedCookies; + } + const promise = (0, _dynamicrenderingutils.makeDevtoolsIOAwarePromise)(underlyingCookies, requestStore, _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.sessionData); + const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route); + CachedCookies.set(underlyingCookies, proxiedPromise); + return proxiedPromise; +} +const warnForSyncAccess = (0, _creatededupedbycallsiteservererrorlogger.createDedupedByCallsiteServerErrorLoggerDev)(createCookiesAccessError); +function instrumentCookiesPromiseWithDevWarnings(promise, route) { + Object.defineProperties(promise, { + [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(promise, route), + size: replaceableWarningDescriptor(promise, 'size', route), + get: replaceableWarningDescriptor(promise, 'get', route), + getAll: replaceableWarningDescriptor(promise, 'getAll', route), + has: replaceableWarningDescriptor(promise, 'has', route), + set: replaceableWarningDescriptor(promise, 'set', route), + delete: replaceableWarningDescriptor(promise, 'delete', route), + clear: replaceableWarningDescriptor(promise, 'clear', route), + toString: replaceableWarningDescriptor(promise, 'toString', route) + }); + return promise; +} +function replaceableWarningDescriptor(target, prop, route) { + return { + enumerable: false, + get () { + warnForSyncAccess(route, `\`cookies().${prop}\``); + return undefined; + }, + set (value) { + Object.defineProperty(target, prop, { + value, + writable: true, + configurable: true + }); + }, + configurable: true + }; +} +function replaceableWarningDescriptorForSymbolIterator(target, route) { + return { + enumerable: false, + get () { + warnForSyncAccess(route, '`...cookies()` or similar iteration'); + return undefined; + }, + set (value) { + Object.defineProperty(target, Symbol.iterator, { + value, + writable: true, + enumerable: true, + configurable: true + }); + }, + configurable: true + }; +} +function createCookiesAccessError(route, expression) { + const prefix = route ? `Route "${route}" ` : 'This route '; + return new Error(`${prefix}used ${expression}. ` + `\`cookies()\` returns a Promise and must be unwrapped with \`await\` or \`React.use()\` before accessing its properties. ` + `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`); +} + +//# sourceMappingURL=cookies.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/cookies.js.map b/e-commerce/node_modules/next/dist/server/request/cookies.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4ea841ff951d20aa52eb6f744f5fe1c1a9c3bca8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/cookies.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/cookies.ts"],"sourcesContent":["import {\n type ReadonlyRequestCookies,\n areCookiesMutableInCurrentPhase,\n RequestCookiesAdapter,\n} from '../web/spec-extension/adapters/request-cookies'\nimport { RequestCookies } from '../web/spec-extension/cookies'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeSessionDataHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n createCookiesInUseCacheError,\n createCookiesInUnstableCacheError,\n} from '../use-cache/use-cache-messages'\n\nexport function cookies(): Promise {\n const callingExpression = 'cookies'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // cookies object without tracking\n const underlyingCookies = createEmptyCookies()\n return makeUntrackedCookies(underlyingCookies)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`cookies()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n const error = createCookiesInUseCacheError(workStore.route)\n Error.captureStackTrace(error, cookies)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n case 'unstable-cache':\n throw createCookiesInUnstableCacheError(workStore.route)\n case 'build-time-generator':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`${workUnitStore.functionName}\\`. This is not supported because \\`${workUnitStore.functionName}\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n return makeHangingCookies(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`cookies`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n // We track dynamic access here so we don't need to wrap the cookies\n // in individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'cookies',\n workUnitStore.cookies\n )\n } else {\n return makeUntrackedCookies(workUnitStore.cookies)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedCookies(workUnitStore.cookies)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n let underlyingCookies: ReadonlyRequestCookies\n\n if (areCookiesMutableInCurrentPhase(workUnitStore)) {\n // We can't conditionally return different types here based on the context.\n // To avoid confusion, we always return the readonly type here.\n underlyingCookies =\n workUnitStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies\n } else {\n underlyingCookies = workUnitStore.cookies\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedCookiesWithDevWarnings(\n workUnitStore,\n underlyingCookies,\n workStore?.route\n )\n } else if (workUnitStore.asyncApiPromises) {\n if (underlyingCookies === workUnitStore.mutableCookies) {\n return workUnitStore.asyncApiPromises.mutableCookies\n } else {\n return workUnitStore.asyncApiPromises.cookies\n }\n } else {\n return makeUntrackedCookies(underlyingCookies)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\nfunction createEmptyCookies(): ReadonlyRequestCookies {\n return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))\n}\n\ninterface CacheLifetime {}\nconst CachedCookies = new WeakMap<\n CacheLifetime,\n Promise\n>()\n\nfunction makeHangingCookies(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise {\n const cachedPromise = CachedCookies.get(prerenderStore)\n if (cachedPromise) {\n return cachedPromise\n }\n\n const promise = makeSessionDataHangingPromise(\n prerenderStore.renderSignal,\n workStore.route,\n '`cookies()`',\n prerenderStore\n )\n CachedCookies.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookies(\n underlyingCookies: ReadonlyRequestCookies\n): Promise {\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = Promise.resolve(underlyingCookies)\n CachedCookies.set(underlyingCookies, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookiesWithDevWarnings(\n requestStore: RequestStore,\n underlyingCookies: ReadonlyRequestCookies,\n route?: string\n): Promise {\n if (requestStore.asyncApiPromises) {\n let promise: Promise\n if (underlyingCookies === requestStore.mutableCookies) {\n promise = requestStore.asyncApiPromises.mutableCookies\n } else if (underlyingCookies === requestStore.cookies) {\n promise = requestStore.asyncApiPromises.cookies\n } else {\n throw new InvariantError(\n 'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'\n )\n }\n return instrumentCookiesPromiseWithDevWarnings(promise, route)\n }\n\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingCookies,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)\n\n CachedCookies.set(underlyingCookies, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createCookiesAccessError\n)\n\nfunction instrumentCookiesPromiseWithDevWarnings(\n promise: Promise,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n size: replaceableWarningDescriptor(promise, 'size', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n getAll: replaceableWarningDescriptor(promise, 'getAll', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n clear: replaceableWarningDescriptor(promise, 'clear', route),\n toString: replaceableWarningDescriptor(promise, 'toString', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`cookies().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...cookies()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createCookiesAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`cookies()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["cookies","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","underlyingCookies","createEmptyCookies","makeUntrackedCookies","dynamicShouldError","StaticGenBailoutError","type","error","createCookiesInUseCacheError","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","createCookiesInUnstableCacheError","functionName","makeHangingCookies","exportName","InvariantError","throwToInterruptStaticGeneration","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","trackDynamicDataInDynamicRender","areCookiesMutableInCurrentPhase","userspaceMutableCookies","process","env","NODE_ENV","makeUntrackedCookiesWithDevWarnings","asyncApiPromises","mutableCookies","throwForMissingRequestStore","RequestCookiesAdapter","seal","RequestCookies","Headers","CachedCookies","WeakMap","prerenderStore","cachedPromise","get","promise","makeSessionDataHangingPromise","renderSignal","set","cachedCookies","Promise","resolve","requestStore","instrumentCookiesPromiseWithDevWarnings","makeDevtoolsIOAwarePromise","proxiedPromise","warnForSyncAccess","createDedupedByCallsiteServerErrorLoggerDev","createCookiesAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","size","replaceableWarningDescriptor","getAll","has","delete","clear","toString","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":";;;;+BAmCgBA;;;eAAAA;;;gCA/BT;yBACwB;0CAIxB;8CAMA;kCAIA;yCAC+B;uCAK/B;0DACqD;uBACV;gCAEnB;kCAIxB;AAEA,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,6PAA6P,CAAC;QAE3R;QAEA,IAAIP,UAAUQ,WAAW,EAAE;YACzB,qFAAqF;YACrF,kC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QACtDmE,UAAUL,6BAA6BpB,SAAS,YAAY1C;IAC9D;IACA,OAAO0C;AACT;AAEA,SAASoB,6BACPM,MAAe,EACfC,IAAY,EACZrE,KAAyB;IAEzB,OAAO;QACLsE,YAAY;QACZ7B;YACEY,kBAAkBrD,OAAO,CAAC,YAAY,EAAEqE,KAAK,EAAE,CAAC;YAChD,OAAOE;QACT;QACA1B,KAAI2B,KAAc;YAChBhB,OAAOiB,cAAc,CAACL,QAAQC,MAAM;gBAClCG;gBACAE,UAAU;gBACVC,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASf,8CACPQ,MAAe,EACfpE,KAAyB;IAEzB,OAAO;QACLsE,YAAY;QACZ7B;YACEY,kBAAkBrD,OAAO;YACzB,OAAOuE;QACT;QACA1B,KAAI2B,KAAc;YAChBhB,OAAOiB,cAAc,CAACL,QAAQV,OAAOC,QAAQ,EAAE;gBAC7Ca;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASpB,yBACPvD,KAAyB,EACzB4E,UAAkB;IAElB,MAAMC,SAAS7E,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,IAAID,MACT,GAAG8E,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC;AAEtE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/draft-mode.d.ts b/e-commerce/node_modules/next/dist/server/request/draft-mode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..46f3a87c5bda91c1c997746000eb213eed10e832 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/draft-mode.d.ts @@ -0,0 +1,9 @@ +import type { DraftModeProvider } from '../async-storage/draft-mode-provider'; +export declare function draftMode(): Promise; +declare class DraftMode { + constructor(provider: null | DraftModeProvider); + get isEnabled(): boolean; + enable(): void; + disable(): void; +} +export {}; diff --git a/e-commerce/node_modules/next/dist/server/request/draft-mode.js b/e-commerce/node_modules/next/dist/server/request/draft-mode.js new file mode 100644 index 0000000000000000000000000000000000000000..98e710154224ea3c594e07ffada1d6382e86cbe8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/draft-mode.js @@ -0,0 +1,192 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "draftMode", { + enumerable: true, + get: function() { + return draftMode; + } +}); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _dynamicrendering = require("../app-render/dynamic-rendering"); +const _creatededupedbycallsiteservererrorlogger = require("../create-deduped-by-callsite-server-error-logger"); +const _staticgenerationbailout = require("../../client/components/static-generation-bailout"); +const _hooksservercontext = require("../../client/components/hooks-server-context"); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _usecachemessages = require("../use-cache/use-cache-messages"); +const _reflect = require("../web/spec-extension/adapters/reflect"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +function draftMode() { + const callingExpression = 'draftMode'; + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (!workStore || !workUnitStore) { + (0, _workunitasyncstorageexternal.throwForMissingRequestStore)(callingExpression); + } + switch(workUnitStore.type){ + case 'prerender-runtime': + { + // TODO(runtime-ppr): does it make sense to delay this? normally it's always microtasky + const { stagedRendering } = workUnitStore; + if (stagedRendering) { + return stagedRendering.delayUntilStage(_dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.sessionData, 'draftMode', new DraftMode(workUnitStore.draftMode)); + } else { + return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore); + } + } + case 'request': + return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore); + case 'cache': + case 'private-cache': + case 'unstable-cache': + // Inside of `"use cache"` or `unstable_cache`, draft mode is available if + // the outmost work unit store is a request store (or a runtime prerender), + // and if draft mode is enabled. + const draftModeProvider = (0, _workunitasyncstorageexternal.getDraftModeProviderForCacheScope)(workStore, workUnitStore); + if (draftModeProvider) { + return createOrGetCachedDraftMode(draftModeProvider, workStore); + } + // Otherwise, we fall through to providing an empty draft mode. + // eslint-disable-next-line no-fallthrough + case 'prerender': + case 'prerender-legacy': + // Return empty draft mode + return createOrGetCachedDraftMode(null, workStore); + case 'prerender-client': + case 'validation-client': + { + const exportName = '`draftMode`'; + throw new _invarianterror.InvariantError(`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`); + } + case 'build-time-generator': + throw new Error(`Route ${workStore.route} used \`${callingExpression}()\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`); + default: + return workUnitStore; + } +} +function createOrGetCachedDraftMode(draftModeProvider, workStore) { + const cacheKey = draftModeProvider ?? NullDraftMode; + const cachedDraftMode = CachedDraftModes.get(cacheKey); + if (cachedDraftMode) { + return cachedDraftMode; + } + if (process.env.NODE_ENV === 'development' && !(workStore == null ? void 0 : workStore.isPrefetchRequest)) { + const route = workStore == null ? void 0 : workStore.route; + return createDraftModeWithDevWarnings(draftModeProvider, route); + } else { + return Promise.resolve(new DraftMode(draftModeProvider)); + } +} +const NullDraftMode = {}; +const CachedDraftModes = new WeakMap(); +function createDraftModeWithDevWarnings(underlyingProvider, route) { + const instance = new DraftMode(underlyingProvider); + const promise = Promise.resolve(instance); + const proxiedPromise = new Proxy(promise, { + get (target, prop, receiver) { + switch(prop){ + case 'isEnabled': + warnForSyncAccess(route, `\`draftMode().${prop}\``); + break; + case 'enable': + case 'disable': + { + warnForSyncAccess(route, `\`draftMode().${prop}()\``); + break; + } + default: + { + // We only warn for well-defined properties of the draftMode object. + } + } + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + }); + return proxiedPromise; +} +class DraftMode { + constructor(provider){ + this._provider = provider; + } + get isEnabled() { + if (this._provider !== null) { + return this._provider.isEnabled; + } + return false; + } + enable() { + // We have a store we want to track dynamic data access to ensure we + // don't statically generate routes that manipulate draft mode. + trackDynamicDraftMode('draftMode().enable()', this.enable); + if (this._provider !== null) { + this._provider.enable(); + } + } + disable() { + trackDynamicDraftMode('draftMode().disable()', this.disable); + if (this._provider !== null) { + this._provider.disable(); + } + } +} +const warnForSyncAccess = (0, _creatededupedbycallsiteservererrorlogger.createDedupedByCallsiteServerErrorLoggerDev)(createDraftModeAccessError); +function createDraftModeAccessError(route, expression) { + const prefix = route ? `Route "${route}" ` : 'This route '; + return new Error(`${prefix}used ${expression}. ` + `\`draftMode()\` returns a Promise and must be unwrapped with \`await\` or \`React.use()\` before accessing its properties. ` + `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`); +} +function trackDynamicDraftMode(expression, constructorOpt) { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workStore) { + // We have a store we want to track dynamic data access to ensure we + // don't statically generate routes that manipulate draft mode. + if ((workUnitStore == null ? void 0 : workUnitStore.phase) === 'after') { + throw new Error(`Route ${workStore.route} used "${expression}" inside \`after()\`. The enabled status of \`draftMode()\` can be read inside \`after()\` but you cannot enable or disable \`draftMode()\`. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`); + } + if (workStore.dynamicShouldError) { + throw new _staticgenerationbailout.StaticGenBailoutError(`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`); + } + if (workUnitStore) { + switch(workUnitStore.type){ + case 'cache': + case 'private-cache': + { + const error = (0, _usecachemessages.createDraftModeMutationInUseCacheError)(workStore.route, expression); + Error.captureStackTrace(error, constructorOpt); + (0, _dynamicrenderingutils.applyOwnerStack)(error); + workStore.invalidDynamicUsageError ??= error; + throw error; + } + case 'unstable-cache': + throw (0, _usecachemessages.createDraftModeMutationInUnstableCacheError)(workStore.route, expression); + case 'prerender': + case 'prerender-runtime': + { + const error = new Error(`Route ${workStore.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`); + return (0, _dynamicrendering.abortAndThrowOnSynchronousRequestDataAccess)(workStore.route, expression, error, workUnitStore); + } + case 'prerender-client': + case 'validation-client': + const exportName = '`draftMode`'; + throw new _invarianterror.InvariantError(`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`); + case 'prerender-legacy': + workUnitStore.revalidate = 0; + const err = new _hooksservercontext.DynamicServerError(`Route ${workStore.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`); + workStore.dynamicUsageDescription = expression; + workStore.dynamicUsageStack = err.stack; + throw err; + case 'request': + (0, _dynamicrendering.trackDynamicDataInDynamicRender)(workUnitStore); + break; + case 'build-time-generator': + throw new Error(`Route ${workStore.route} used \`${expression}\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`); + default: + workUnitStore; + } + } + } +} + +//# sourceMappingURL=draft-mode.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/draft-mode.js.map b/e-commerce/node_modules/next/dist/server/request/draft-mode.js.map new file mode 100644 index 0000000000000000000000000000000000000000..aab2769e8a97c1d49311ee1babc566bcc8a89901 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/draft-mode.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/draft-mode.ts"],"sourcesContent":["import {\n getDraftModeProviderForCacheScope,\n throwForMissingRequestStore,\n} from '../app-render/work-unit-async-storage.external'\n\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\n\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n abortAndThrowOnSynchronousRequestDataAccess,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport { DynamicServerError } from '../../client/components/hooks-server-context'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n createDraftModeMutationInUseCacheError,\n createDraftModeMutationInUnstableCacheError,\n} from '../use-cache/use-cache-messages'\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n applyOwnerStack,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\n\nexport function draftMode(): Promise {\n const callingExpression = 'draftMode'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workStore || !workUnitStore) {\n throwForMissingRequestStore(callingExpression)\n }\n\n switch (workUnitStore.type) {\n case 'prerender-runtime': {\n // TODO(runtime-ppr): does it make sense to delay this? normally it's always microtasky\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'draftMode',\n new DraftMode(workUnitStore.draftMode)\n )\n } else {\n return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)\n }\n }\n case 'request':\n return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)\n\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside of `\"use cache\"` or `unstable_cache`, draft mode is available if\n // the outmost work unit store is a request store (or a runtime prerender),\n // and if draft mode is enabled.\n const draftModeProvider = getDraftModeProviderForCacheScope(\n workStore,\n workUnitStore\n )\n\n if (draftModeProvider) {\n return createOrGetCachedDraftMode(draftModeProvider, workStore)\n }\n\n // Otherwise, we fall through to providing an empty draft mode.\n // eslint-disable-next-line no-fallthrough\n case 'prerender':\n case 'prerender-legacy':\n // Return empty draft mode\n return createOrGetCachedDraftMode(null, workStore)\n case 'prerender-client':\n case 'validation-client': {\n const exportName = '`draftMode`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'build-time-generator':\n throw new Error(\n `Route ${workStore.route} used \\`${callingExpression}()\\` inside \\`${workUnitStore.functionName}\\`. This is not supported because \\`${workUnitStore.functionName}\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n\n default:\n return workUnitStore satisfies never\n }\n}\n\nfunction createOrGetCachedDraftMode(\n draftModeProvider: DraftModeProvider | null,\n workStore: WorkStore | undefined\n): Promise {\n const cacheKey = draftModeProvider ?? NullDraftMode\n const cachedDraftMode = CachedDraftModes.get(cacheKey)\n\n if (cachedDraftMode) {\n return cachedDraftMode\n }\n\n if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {\n const route = workStore?.route\n return createDraftModeWithDevWarnings(draftModeProvider, route)\n } else {\n return Promise.resolve(new DraftMode(draftModeProvider))\n }\n}\n\ninterface CacheLifetime {}\nconst NullDraftMode = {}\nconst CachedDraftModes = new WeakMap>()\n\nfunction createDraftModeWithDevWarnings(\n underlyingProvider: null | DraftModeProvider,\n route: undefined | string\n): Promise {\n const instance = new DraftMode(underlyingProvider)\n const promise = Promise.resolve(instance)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'isEnabled':\n warnForSyncAccess(route, `\\`draftMode().${prop}\\``)\n break\n case 'enable':\n case 'disable': {\n warnForSyncAccess(route, `\\`draftMode().${prop}()\\``)\n break\n }\n default: {\n // We only warn for well-defined properties of the draftMode object.\n }\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n return proxiedPromise\n}\n\nclass DraftMode {\n /**\n * @internal - this declaration is stripped via `tsc --stripInternal`\n */\n private readonly _provider: null | DraftModeProvider\n\n constructor(provider: null | DraftModeProvider) {\n this._provider = provider\n }\n get isEnabled() {\n if (this._provider !== null) {\n return this._provider.isEnabled\n }\n return false\n }\n public enable() {\n // We have a store we want to track dynamic data access to ensure we\n // don't statically generate routes that manipulate draft mode.\n trackDynamicDraftMode('draftMode().enable()', this.enable)\n if (this._provider !== null) {\n this._provider.enable()\n }\n }\n public disable() {\n trackDynamicDraftMode('draftMode().disable()', this.disable)\n if (this._provider !== null) {\n this._provider.disable()\n }\n }\n}\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createDraftModeAccessError\n)\n\nfunction createDraftModeAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`draftMode()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction trackDynamicDraftMode(expression: string, constructorOpt: Function) {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n // We have a store we want to track dynamic data access to ensure we\n // don't statically generate routes that manipulate draft mode.\n if (workUnitStore?.phase === 'after') {\n throw new Error(\n `Route ${workStore.route} used \"${expression}\" inside \\`after()\\`. The enabled status of \\`draftMode()\\` can be read inside \\`after()\\` but you cannot enable or disable \\`draftMode()\\`. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache': {\n const error = createDraftModeMutationInUseCacheError(\n workStore.route,\n expression\n )\n Error.captureStackTrace(error, constructorOpt)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw createDraftModeMutationInUnstableCacheError(\n workStore.route,\n expression\n )\n\n case 'prerender':\n case 'prerender-runtime': {\n const error = new Error(\n `Route ${workStore.route} used ${expression} without first calling \\`await connection()\\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n workStore.route,\n expression,\n error,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`draftMode`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${workStore.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n workStore.dynamicUsageDescription = expression\n workStore.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n break\n case 'build-time-generator':\n throw new Error(\n `Route ${workStore.route} used \\`${expression}\\` inside \\`${workUnitStore.functionName}\\`. This is not supported because \\`${workUnitStore.functionName}\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n default:\n workUnitStore satisfies never\n }\n }\n }\n}\n"],"names":["draftMode","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","throwForMissingRequestStore","type","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","DraftMode","createOrGetCachedDraftMode","draftModeProvider","getDraftModeProviderForCacheScope","exportName","InvariantError","Error","route","functionName","cacheKey","NullDraftMode","cachedDraftMode","CachedDraftModes","get","process","env","NODE_ENV","isPrefetchRequest","createDraftModeWithDevWarnings","Promise","resolve","WeakMap","underlyingProvider","instance","promise","proxiedPromise","Proxy","target","prop","receiver","warnForSyncAccess","ReflectAdapter","constructor","provider","_provider","isEnabled","enable","trackDynamicDraftMode","disable","createDedupedByCallsiteServerErrorLoggerDev","createDraftModeAccessError","expression","prefix","constructorOpt","phase","dynamicShouldError","StaticGenBailoutError","error","createDraftModeMutationInUseCacheError","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","createDraftModeMutationInUnstableCacheError","abortAndThrowOnSynchronousRequestDataAccess","revalidate","err","DynamicServerError","dynamicUsageDescription","dynamicUsageStack","stack","trackDynamicDataInDynamicRender"],"mappings":";;;;+BA8BgBA;;;eAAAA;;;8CA3BT;0CAOA;kCAKA;0DACqD;yCACtB;oCACH;gCACJ;kCAIxB;yBACwB;uCAIxB;AAEA,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAI,CAACF,aAAa,CAACG,eAAe;QAChCE,IAAAA,yDAA2B,EAACN;IAC9B;IAEA,OAAQI,cAAcG,IAAI;QACxB,KAAK;YAAqB;gBACxB,uFAAuF;gBACvF,MAAM,EAAEC,eAAe,EAAE,GAAGJ;gBAC5B,IAAII,iBAAiB;oBACnB,OAAOA,gBAAgBC,eAAe,CACpCC,iDAA0B,CAACC,WAAW,EACtC,aACA,IAAIC,UAAUR,cAAcL,SAAS;gBAEzC,OAAO;oBACL,OAAOc,2BAA2BT,cAAcL,SAAS,EAAEE;gBAC7D;YACF;QACA,KAAK;YACH,OAAOY,2BAA2BT,cAAcL,SAAS,EAAEE;QAE7D,KAAK;QACL,KAAK;QACL,KAAK;YACH,0EAA0E;YAC1E,2EAA2E;YAC3E,gCAAgC;YAChC,MAAMa,oBAAoBC,IAAAA,+DAAiC,EACzDd,WACAG;YAGF,IAAIU,mBAAmB;gBACrB,OAAOD,2BAA2BC,mBAAmBb;YACvD;QAEF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AAUqE,iBAAiB,GAAGH,IAAII,KAAK;oBAEvC,MAAMJ;gBACR,KAAK;oBACHK,IAAAA,iDAA+B,EAACpE;oBAChC;gBACF,KAAK;oBACH,MAAM,IAAIc,MACR,CAAC,MAAM,EAAEjB,UAAUkB,KAAK,CAAC,QAAQ,EAAEkC,WAAW,YAAY,EAAEjD,cAAcgB,YAAY,CAAC,oCAAoC,EAAEhB,cAAcgB,YAAY,CAAC,yHAAyH,CAAC;gBAEtR;oBACEhB;YACJ;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/fallback-params.d.ts b/e-commerce/node_modules/next/dist/server/request/fallback-params.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..04be88b05399ca74d4c6c979a156b058229e1b40 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/fallback-params.d.ts @@ -0,0 +1,44 @@ +import type { FallbackRouteParam } from '../../build/static-paths/types'; +import type AppPageRouteModule from '../route-modules/app-page/module'; +/** + * Maps unknown param names to internal placeholders. The parameter wrappers + * control when reads suspend; these placeholders must not become rendered UI. + */ +export type OpaqueFallbackRouteParams = ReadonlyMap; +/** + * Creates an opaque fallback route params object from the fallback route params. + * + * @param fallbackRouteParams the fallback route params + * @returns the opaque fallback route params + */ +export declare function createOpaqueFallbackRouteParams(fallbackRouteParams: readonly FallbackRouteParam[]): OpaqueFallbackRouteParams | null; +/** + * Selects the params that a staged render defers for the shell target that a + * request selects. Dev static-shell validation stages the same set, so it + * checks the shell that the build validates. + * + * The set derives from the build's shell metadata, not from the serving mode. A + * required shell (`throwOnEmptyStaticShell`) is the most specific shell the + * build generated for its params, and the build fails when its prelude is + * empty. Staging defers all of its fallback params, because the build validated + * exactly that shape. Any other shell may be empty, and a request completes it + * with the params that `generateStaticParams` can still supply. Only the params + * that completion never resolves stay deferred. + */ +export declare function getStagedFallbackParams(route: { + fallbackRouteParams: readonly FallbackRouteParam[] | undefined; + remainingPrerenderableParams?: readonly FallbackRouteParam[]; + throwOnEmptyStaticShell?: boolean; +}): OpaqueFallbackRouteParams | null; +export declare function buildDynamicSegmentPlaceholder(param: Pick): string; +export declare function getPlaceholderFallbackRouteParams(params: Record | undefined, fallbackRouteParams: readonly FallbackRouteParam[]): FallbackRouteParam[]; +/** + * Gets the fallback route params for a given page. This is an expensive + * operation because it requires parsing the loader tree to extract the fallback + * route params. + * + * @param page the page + * @param routeModule the route module + * @returns the opaque fallback route params + */ +export declare function getFallbackRouteParams(page: string, routeModule: AppPageRouteModule): OpaqueFallbackRouteParams | null; diff --git a/e-commerce/node_modules/next/dist/server/request/fallback-params.js b/e-commerce/node_modules/next/dist/server/request/fallback-params.js new file mode 100644 index 0000000000000000000000000000000000000000..7d3ca4993ee38e5c3d8289bb80498a595d1dbb4a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/fallback-params.js @@ -0,0 +1,109 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + buildDynamicSegmentPlaceholder: null, + createOpaqueFallbackRouteParams: null, + getFallbackRouteParams: null, + getPlaceholderFallbackRouteParams: null, + getStagedFallbackParams: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + buildDynamicSegmentPlaceholder: function() { + return buildDynamicSegmentPlaceholder; + }, + createOpaqueFallbackRouteParams: function() { + return createOpaqueFallbackRouteParams; + }, + getFallbackRouteParams: function() { + return getFallbackRouteParams; + }, + getPlaceholderFallbackRouteParams: function() { + return getPlaceholderFallbackRouteParams; + }, + getStagedFallbackParams: function() { + return getStagedFallbackParams; + } +}); +const _utils = require("../../build/static-paths/utils"); +const _app = require("../../shared/lib/router/routes/app"); +const _extractpathnamerouteparamsegmentsfromloadertree = require("../../build/static-paths/app/extract-pathname-route-param-segments-from-loader-tree"); +const _getsegmentparam = require("../../shared/lib/router/utils/get-segment-param"); +const _invarianterror = require("../../shared/lib/invariant-error"); +function createOpaqueFallbackRouteParams(fallbackRouteParams) { + // If there are no fallback route params, we can return early. + if (fallbackRouteParams.length === 0) return null; + // As we're creating unique keys for each of the dynamic route params, we only + // need to generate a unique ID once per request because each of the keys will + // be also be unique. + const uniqueID = Math.random().toString(16).slice(2); + const keys = new Map(); + // Generate a unique key for the fallback route param, if this key is found + // in the static output, it represents a bug in cache components. + for (const { paramName } of fallbackRouteParams){ + keys.set(paramName, `%%drp:${paramName}:${uniqueID}%%`); + } + return keys; +} +function getStagedFallbackParams(route) { + const { fallbackRouteParams, remainingPrerenderableParams } = route; + if (!(fallbackRouteParams == null ? void 0 : fallbackRouteParams.length)) { + return null; + } + if (route.throwOnEmptyStaticShell === undefined) { + throw new _invarianterror.InvariantError('Expected throwOnEmptyStaticShell for a route with fallback params'); + } + // A required shell keeps all of its fallback params deferred. + if (route.throwOnEmptyStaticShell || !(remainingPrerenderableParams == null ? void 0 : remainingPrerenderableParams.length)) { + return createOpaqueFallbackRouteParams(fallbackRouteParams); + } + return createOpaqueFallbackRouteParams(fallbackRouteParams.filter((param)=>!remainingPrerenderableParams.some((prerenderableParam)=>prerenderableParam.paramName === param.paramName))); +} +function buildDynamicSegmentPlaceholder(param) { + const { repeat, optional } = (0, _getsegmentparam.getParamProperties)(param.paramType); + if (optional) { + return `[[...${param.paramName}]]`; + } + if (repeat) { + return `[...${param.paramName}]`; + } + return `[${param.paramName}]`; +} +function getPlaceholderFallbackRouteParams(params, fallbackRouteParams) { + return fallbackRouteParams.filter((param)=>{ + const placeholder = buildDynamicSegmentPlaceholder(param); + const value = params == null ? void 0 : params[param.paramName]; + return value === placeholder || Array.isArray(value) && value.length === 1 && value[0] === placeholder; + }); +} +function getFallbackRouteParams(page, routeModule) { + const route = (0, _app.parseNormalizedAppRoute)(page); + // Extract the pathname-contributing segments from the loader tree. This + // mirrors the logic in buildAppStaticPaths where we determine which segments + // actually contribute to the pathname. + const { pathnameRouteParamSegments, params } = (0, _extractpathnamerouteparamsegmentsfromloadertree.extractPathnameRouteParamSegmentsFromLoaderTree)(routeModule.userland.loaderTree, route); + // Create fallback route params for the pathname segments. + const fallbackRouteParams = pathnameRouteParamSegments.map(({ paramName, paramType })=>({ + paramName, + paramType + })); + // Resolve route params from the loader tree. This mutates the + // fallbackRouteParams array to add any route params that are + // unknown at request time. + // + // The page parameter contains placeholders like [slug], which helps + // resolveRouteParamsFromTree determine which params are unknown. + (0, _utils.resolveRouteParamsFromTree)(routeModule.userland.loaderTree, params, route, fallbackRouteParams // Will be mutated to add route params + ); + // Track the unknown params using the same opaque placeholders as prerenders. + return createOpaqueFallbackRouteParams(fallbackRouteParams); +} + +//# sourceMappingURL=fallback-params.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/fallback-params.js.map b/e-commerce/node_modules/next/dist/server/request/fallback-params.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5a49169bf3beaa223271d492773a18aeaa066da7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/fallback-params.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/fallback-params.ts"],"sourcesContent":["import { resolveRouteParamsFromTree } from '../../build/static-paths/utils'\nimport type { FallbackRouteParam } from '../../build/static-paths/types'\nimport type AppPageRouteModule from '../route-modules/app-page/module'\nimport { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'\nimport { extractPathnameRouteParamSegmentsFromLoaderTree } from '../../build/static-paths/app/extract-pathname-route-param-segments-from-loader-tree'\nimport { getParamProperties } from '../../shared/lib/router/utils/get-segment-param'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * Maps unknown param names to internal placeholders. The parameter wrappers\n * control when reads suspend; these placeholders must not become rendered UI.\n */\nexport type OpaqueFallbackRouteParams = ReadonlyMap\n\n/**\n * Creates an opaque fallback route params object from the fallback route params.\n *\n * @param fallbackRouteParams the fallback route params\n * @returns the opaque fallback route params\n */\nexport function createOpaqueFallbackRouteParams(\n fallbackRouteParams: readonly FallbackRouteParam[]\n): OpaqueFallbackRouteParams | null {\n // If there are no fallback route params, we can return early.\n if (fallbackRouteParams.length === 0) return null\n\n // As we're creating unique keys for each of the dynamic route params, we only\n // need to generate a unique ID once per request because each of the keys will\n // be also be unique.\n const uniqueID = Math.random().toString(16).slice(2)\n\n const keys = new Map()\n\n // Generate a unique key for the fallback route param, if this key is found\n // in the static output, it represents a bug in cache components.\n for (const { paramName } of fallbackRouteParams) {\n keys.set(paramName, `%%drp:${paramName}:${uniqueID}%%`)\n }\n\n return keys\n}\n\n/**\n * Selects the params that a staged render defers for the shell target that a\n * request selects. Dev static-shell validation stages the same set, so it\n * checks the shell that the build validates.\n *\n * The set derives from the build's shell metadata, not from the serving mode. A\n * required shell (`throwOnEmptyStaticShell`) is the most specific shell the\n * build generated for its params, and the build fails when its prelude is\n * empty. Staging defers all of its fallback params, because the build validated\n * exactly that shape. Any other shell may be empty, and a request completes it\n * with the params that `generateStaticParams` can still supply. Only the params\n * that completion never resolves stay deferred.\n */\nexport function getStagedFallbackParams(route: {\n fallbackRouteParams: readonly FallbackRouteParam[] | undefined\n remainingPrerenderableParams?: readonly FallbackRouteParam[]\n throwOnEmptyStaticShell?: boolean\n}): OpaqueFallbackRouteParams | null {\n const { fallbackRouteParams, remainingPrerenderableParams } = route\n if (!fallbackRouteParams?.length) {\n return null\n }\n\n if (route.throwOnEmptyStaticShell === undefined) {\n throw new InvariantError(\n 'Expected throwOnEmptyStaticShell for a route with fallback params'\n )\n }\n\n // A required shell keeps all of its fallback params deferred.\n if (route.throwOnEmptyStaticShell || !remainingPrerenderableParams?.length) {\n return createOpaqueFallbackRouteParams(fallbackRouteParams)\n }\n\n return createOpaqueFallbackRouteParams(\n fallbackRouteParams.filter(\n (param) =>\n !remainingPrerenderableParams.some(\n (prerenderableParam) =>\n prerenderableParam.paramName === param.paramName\n )\n )\n )\n}\n\nexport function buildDynamicSegmentPlaceholder(\n param: Pick\n): string {\n const { repeat, optional } = getParamProperties(param.paramType)\n\n if (optional) {\n return `[[...${param.paramName}]]`\n }\n\n if (repeat) {\n return `[...${param.paramName}]`\n }\n\n return `[${param.paramName}]`\n}\n\nexport function getPlaceholderFallbackRouteParams(\n params: Record | undefined,\n fallbackRouteParams: readonly FallbackRouteParam[]\n): FallbackRouteParam[] {\n return fallbackRouteParams.filter((param) => {\n const placeholder = buildDynamicSegmentPlaceholder(param)\n const value = params?.[param.paramName]\n\n return (\n value === placeholder ||\n (Array.isArray(value) && value.length === 1 && value[0] === placeholder)\n )\n })\n}\n\n/**\n * Gets the fallback route params for a given page. This is an expensive\n * operation because it requires parsing the loader tree to extract the fallback\n * route params.\n *\n * @param page the page\n * @param routeModule the route module\n * @returns the opaque fallback route params\n */\nexport function getFallbackRouteParams(\n page: string,\n routeModule: AppPageRouteModule\n) {\n const route = parseNormalizedAppRoute(page)\n\n // Extract the pathname-contributing segments from the loader tree. This\n // mirrors the logic in buildAppStaticPaths where we determine which segments\n // actually contribute to the pathname.\n const { pathnameRouteParamSegments, params } =\n extractPathnameRouteParamSegmentsFromLoaderTree(\n routeModule.userland.loaderTree,\n route\n )\n\n // Create fallback route params for the pathname segments.\n const fallbackRouteParams: FallbackRouteParam[] =\n pathnameRouteParamSegments.map(({ paramName, paramType }) => ({\n paramName,\n paramType,\n }))\n\n // Resolve route params from the loader tree. This mutates the\n // fallbackRouteParams array to add any route params that are\n // unknown at request time.\n //\n // The page parameter contains placeholders like [slug], which helps\n // resolveRouteParamsFromTree determine which params are unknown.\n resolveRouteParamsFromTree(\n routeModule.userland.loaderTree,\n params, // Static params extracted from the page\n route, // The page pattern with placeholders\n fallbackRouteParams // Will be mutated to add route params\n )\n\n // Track the unknown params using the same opaque placeholders as prerenders.\n return createOpaqueFallbackRouteParams(fallbackRouteParams)\n}\n"],"names":["buildDynamicSegmentPlaceholder","createOpaqueFallbackRouteParams","getFallbackRouteParams","getPlaceholderFallbackRouteParams","getStagedFallbackParams","fallbackRouteParams","length","uniqueID","Math","random","toString","slice","keys","Map","paramName","set","route","remainingPrerenderableParams","throwOnEmptyStaticShell","undefined","InvariantError","filter","param","some","prerenderableParam","repeat","optional","getParamProperties","paramType","params","placeholder","value","Array","isArray","page","routeModule","parseNormalizedAppRoute","pathnameRouteParamSegments","extractPathnameRouteParamSegmentsFromLoaderTree","userland","loaderTree","map","resolveRouteParamsFromTree"],"mappings":";;;;;;;;;;;;;;;;;;IAuFgBA,8BAA8B;eAA9BA;;IAnEAC,+BAA+B;eAA/BA;;IA2GAC,sBAAsB;eAAtBA;;IAxBAC,iCAAiC;eAAjCA;;IAhDAC,uBAAuB;eAAvBA;;;uBAvD2B;qBAGH;iEACwB;iCAC7B;gCACJ;AAcxB,SAASH,gCACdI,mBAAkD;IAElD,8DAA8D;IAC9D,IAAIA,oBAAoBC,MAAM,KAAK,GAAG,OAAO;IAE7C,8EAA8E;IAC9E,8EAA8E;IAC9E,qBAAqB;IACrB,MAAMC,WAAWC,KAAKC,MAAM,GAAGC,QAAQ,CAAC,IAAIC,KAAK,CAAC;IAElD,MAAMC,OAAO,IAAIC;IAEjB,2EAA2E;IAC3E,iEAAiE;IACjE,KAAK,MAAM,EAAEC,SAAS,EAAE,IAAIT,oBAAqB;QAC/CO,KAAKG,GAAG,CAACD,WAAW,CAAC,MAAM,EAAEA,UAAU,CAAC,EAAEP,SAAS,EAAE,CAAC;IACxD;IAEA,OAAOK;AACT;AAeO,SAASR,wBAAwBY,KAIvC;IACC,MAAM,EAAEX,mBAAmB,EAAEY,4BAA4B,EAAE,GAAGD;IAC9D,IAAI,EAACX,uCAAAA,oBAAqBC,MAAM,GAAE;QAChC,OAAO;IACT;IAEA,IAAIU,MAAME,uBAAuB,KAAKC,WAAW;QAC/C,MAAM,IAAIC,8BAAc,CACtB;IAEJ;IAEA,8DAA8D;IAC9D,IAAIJ,MAAME,uBAAuB,IAAI,EAACD,gDAAAA,6BAA8BX,MAAM,GAAE;QAC1E,OAAOL,gCAAgCI;IACzC;IAEA,OAAOJ,gCACLI,oBAAoBgB,MAAM,CACxB,CAACC,QACC,C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AAAA,iCAA0B,EACxBP,YAAYI,QAAQ,CAACC,UAAU,EAC/BX,QACAb,OACAX,oBAAoB,sCAAsC;;IAG5D,6EAA6E;IAC7E,OAAOJ,gCAAgCI;AACzC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/headers.d.ts b/e-commerce/node_modules/next/dist/server/request/headers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..690c83ac97e62f6a1a8d03f37c73088cfce06e3c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/headers.d.ts @@ -0,0 +1,11 @@ +import { type ReadonlyHeaders } from '../web/spec-extension/adapters/headers'; +/** + * This function allows you to read the HTTP incoming request headers in + * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components), + * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations), + * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and + * [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware). + * + * Read more: [Next.js Docs: `headers`](https://nextjs.org/docs/app/api-reference/functions/headers) + */ +export declare function headers(): Promise; diff --git a/e-commerce/node_modules/next/dist/server/request/headers.js b/e-commerce/node_modules/next/dist/server/request/headers.js new file mode 100644 index 0000000000000000000000000000000000000000..fb55e3282a43deec901aafcb8cba3a617cce0ddf --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/headers.js @@ -0,0 +1,201 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "headers", { + enumerable: true, + get: function() { + return headers; + } +}); +const _headers = require("../web/spec-extension/adapters/headers"); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _dynamicrendering = require("../app-render/dynamic-rendering"); +const _staticgenerationbailout = require("../../client/components/static-generation-bailout"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _creatededupedbycallsiteservererrorlogger = require("../create-deduped-by-callsite-server-error-logger"); +const _utils = require("./utils"); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _usecachemessages = require("../use-cache/use-cache-messages"); +function headers() { + const callingExpression = 'headers'; + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workStore) { + if (workUnitStore && !(0, _utils.isRequestApiAllowedInCurrentPhase)(workUnitStore)) { + throw new Error(`Route ${workStore.route} used \`headers()\` inside \`after()\` while rendering. This is not supported. If you need this data inside an \`after()\` callback, use \`headers()\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`); + } + if (workStore.forceStatic) { + // When using forceStatic we override all other logic and always just return an empty + // headers object without tracking + const underlyingHeaders = _headers.HeadersAdapter.seal(new Headers({})); + return makeUntrackedHeaders(underlyingHeaders); + } + if (workUnitStore) { + switch(workUnitStore.type){ + case 'cache': + { + const error = (0, _usecachemessages.createHeadersInUseCacheError)(workStore.route); + Error.captureStackTrace(error, headers); + (0, _dynamicrenderingutils.applyOwnerStack)(error); + workStore.invalidDynamicUsageError ??= error; + throw error; + } + case 'unstable-cache': + throw (0, _usecachemessages.createHeadersInUnstableCacheError)(workStore.route); + case 'build-time-generator': + throw new Error(`Route ${workStore.route} used \`headers()\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`); + case 'prerender': + case 'prerender-client': + case 'validation-client': + case 'private-cache': + case 'prerender-runtime': + case 'prerender-legacy': + case 'request': + break; + default: + workUnitStore; + } + } + if (workStore.dynamicShouldError) { + throw new _staticgenerationbailout.StaticGenBailoutError(`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers()\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`); + } + if (workUnitStore) { + switch(workUnitStore.type){ + case 'prerender': + return makeHangingHeaders(workStore, workUnitStore); + case 'prerender-client': + case 'validation-client': + const exportName = '`headers`'; + throw new _invarianterror.InvariantError(`${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`); + case 'prerender-legacy': + // Legacy Prerender + // We are in a legacy static generation mode while prerendering + // We track dynamic access here so we don't need to wrap the headers in + // individual property access tracking. + return (0, _dynamicrendering.throwToInterruptStaticGeneration)(callingExpression, workStore, workUnitStore); + case 'prerender-runtime': + { + const { stagedRendering } = workUnitStore; + if (stagedRendering) { + return stagedRendering.delayUntilStage(_dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.sessionData, 'headers', workUnitStore.headers); + } else { + return makeUntrackedHeaders(workUnitStore.headers); + } + } + case 'private-cache': + // Private caches are delayed until the runtime stage in use-cache-wrapper, + // so we don't need an additional delay here. + return makeUntrackedHeaders(workUnitStore.headers); + case 'request': + (0, _dynamicrendering.trackDynamicDataInDynamicRender)(workUnitStore); + if (process.env.NODE_ENV === 'development') { + // Semantically we only need the dev tracking when running in `next dev` + // but since you would never use next dev with production NODE_ENV we use this + // as a proxy so we can statically exclude this code from production builds. + return makeUntrackedHeadersWithDevWarnings(workUnitStore.headers, workStore == null ? void 0 : workStore.route, workUnitStore); + } else if (workUnitStore.asyncApiPromises) { + return workUnitStore.asyncApiPromises.headers; + } else { + return makeUntrackedHeaders(workUnitStore.headers); + } + break; + default: + workUnitStore; + } + } + } + // If we end up here, there was no work store or work unit store present. + (0, _workunitasyncstorageexternal.throwForMissingRequestStore)(callingExpression); +} +const CachedHeaders = new WeakMap(); +function makeHangingHeaders(workStore, prerenderStore) { + const cachedHeaders = CachedHeaders.get(prerenderStore); + if (cachedHeaders) { + return cachedHeaders; + } + const promise = (0, _dynamicrenderingutils.makeSessionDataHangingPromise)(prerenderStore.renderSignal, workStore.route, '`headers()`', prerenderStore); + CachedHeaders.set(prerenderStore, promise); + return promise; +} +function makeUntrackedHeaders(underlyingHeaders) { + const cachedHeaders = CachedHeaders.get(underlyingHeaders); + if (cachedHeaders) { + return cachedHeaders; + } + const promise = Promise.resolve(underlyingHeaders); + CachedHeaders.set(underlyingHeaders, promise); + return promise; +} +function makeUntrackedHeadersWithDevWarnings(underlyingHeaders, route, requestStore) { + if (requestStore.asyncApiPromises) { + return instrumentHeadersPromiseWithDevWarnings(requestStore.asyncApiPromises.headers, route); + } + const cachedHeaders = CachedHeaders.get(underlyingHeaders); + if (cachedHeaders) { + return cachedHeaders; + } + const promise = (0, _dynamicrenderingutils.makeDevtoolsIOAwarePromise)(underlyingHeaders, requestStore, _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.sessionData); + const proxiedPromise = instrumentHeadersPromiseWithDevWarnings(promise, route); + CachedHeaders.set(underlyingHeaders, proxiedPromise); + return proxiedPromise; +} +const warnForSyncAccess = (0, _creatededupedbycallsiteservererrorlogger.createDedupedByCallsiteServerErrorLoggerDev)(createHeadersAccessError); +function instrumentHeadersPromiseWithDevWarnings(promise, route) { + Object.defineProperties(promise, { + [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(promise, route), + append: replaceableWarningDescriptor(promise, 'append', route), + delete: replaceableWarningDescriptor(promise, 'delete', route), + get: replaceableWarningDescriptor(promise, 'get', route), + has: replaceableWarningDescriptor(promise, 'has', route), + set: replaceableWarningDescriptor(promise, 'set', route), + getSetCookie: replaceableWarningDescriptor(promise, 'getSetCookie', route), + forEach: replaceableWarningDescriptor(promise, 'forEach', route), + keys: replaceableWarningDescriptor(promise, 'keys', route), + values: replaceableWarningDescriptor(promise, 'values', route), + entries: replaceableWarningDescriptor(promise, 'entries', route) + }); + return promise; +} +function replaceableWarningDescriptor(target, prop, route) { + return { + enumerable: false, + get () { + warnForSyncAccess(route, `\`headers().${prop}\``); + return undefined; + }, + set (value) { + Object.defineProperty(target, prop, { + value, + writable: true, + configurable: true + }); + }, + configurable: true + }; +} +function replaceableWarningDescriptorForSymbolIterator(target, route) { + return { + enumerable: false, + get () { + warnForSyncAccess(route, '`...headers()` or similar iteration'); + return undefined; + }, + set (value) { + Object.defineProperty(target, Symbol.iterator, { + value, + writable: true, + enumerable: true, + configurable: true + }); + }, + configurable: true + }; +} +function createHeadersAccessError(route, expression) { + const prefix = route ? `Route "${route}" ` : 'This route '; + return new Error(`${prefix}used ${expression}. ` + `\`headers()\` returns a Promise and must be unwrapped with \`await\` or \`React.use()\` before accessing its properties. ` + `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`); +} + +//# sourceMappingURL=headers.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/headers.js.map b/e-commerce/node_modules/next/dist/server/request/headers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7a9c5043eedda93cff4877f02668ce3ac66e4a04 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/headers.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/headers.ts"],"sourcesContent":["import {\n HeadersAdapter,\n type ReadonlyHeaders,\n} from '../web/spec-extension/adapters/headers'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeSessionDataHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n createHeadersInUseCacheError,\n createHeadersInUnstableCacheError,\n} from '../use-cache/use-cache-messages'\n\n/**\n * This function allows you to read the HTTP incoming request headers in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and\n * [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware).\n *\n * Read more: [Next.js Docs: `headers`](https://nextjs.org/docs/app/api-reference/functions/headers)\n */\nexport function headers(): Promise {\n const callingExpression = 'headers'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // headers object without tracking\n const underlyingHeaders = HeadersAdapter.seal(new Headers({}))\n return makeUntrackedHeaders(underlyingHeaders)\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = createHeadersInUseCacheError(workStore.route)\n Error.captureStackTrace(error, headers)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw createHeadersInUnstableCacheError(workStore.route)\n case 'build-time-generator':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`${workUnitStore.functionName}\\`. This is not supported because \\`${workUnitStore.functionName}\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'private-cache':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`headers()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n return makeHangingHeaders(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`headers`'\n throw new InvariantError(\n `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n // Legacy Prerender\n // We are in a legacy static generation mode while prerendering\n // We track dynamic access here so we don't need to wrap the headers in\n // individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'headers',\n workUnitStore.headers\n )\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedHeaders(workUnitStore.headers)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedHeadersWithDevWarnings(\n workUnitStore.headers,\n workStore?.route,\n workUnitStore\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.headers\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\ninterface CacheLifetime {}\nconst CachedHeaders = new WeakMap>()\n\nfunction makeHangingHeaders(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise {\n const cachedHeaders = CachedHeaders.get(prerenderStore)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeSessionDataHangingPromise(\n prerenderStore.renderSignal,\n workStore.route,\n '`headers()`',\n prerenderStore\n )\n CachedHeaders.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeaders(\n underlyingHeaders: ReadonlyHeaders\n): Promise {\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = Promise.resolve(underlyingHeaders)\n CachedHeaders.set(underlyingHeaders, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeadersWithDevWarnings(\n underlyingHeaders: ReadonlyHeaders,\n route: string | undefined,\n requestStore: RequestStore\n): Promise {\n if (requestStore.asyncApiPromises) {\n return instrumentHeadersPromiseWithDevWarnings(\n requestStore.asyncApiPromises.headers,\n route\n )\n }\n\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingHeaders,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentHeadersPromiseWithDevWarnings(promise, route)\n\n CachedHeaders.set(underlyingHeaders, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createHeadersAccessError\n)\n\nfunction instrumentHeadersPromiseWithDevWarnings(\n promise: Promise,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n append: replaceableWarningDescriptor(promise, 'append', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n getSetCookie: replaceableWarningDescriptor(promise, 'getSetCookie', route),\n forEach: replaceableWarningDescriptor(promise, 'forEach', route),\n keys: replaceableWarningDescriptor(promise, 'keys', route),\n values: replaceableWarningDescriptor(promise, 'values', route),\n entries: replaceableWarningDescriptor(promise, 'entries', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`headers().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...headers()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createHeadersAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`headers()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["headers","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","underlyingHeaders","HeadersAdapter","seal","Headers","makeUntrackedHeaders","type","error","createHeadersInUseCacheError","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","createHeadersInUnstableCacheError","functionName","dynamicShouldError","StaticGenBailoutError","makeHangingHeaders","exportName","InvariantError","throwToInterruptStaticGeneration","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","trackDynamicDataInDynamicRender","process","env","NODE_ENV","makeUntrackedHeadersWithDevWarnings","asyncApiPromises","throwForMissingRequestStore","CachedHeaders","WeakMap","prerenderStore","cachedHeaders","get","promise","makeSessionDataHangingPromise","renderSignal","set","Promise","resolve","requestStore","instrumentHeadersPromiseWithDevWarnings","makeDevtoolsIOAwarePromise","proxiedPromise","warnForSyncAccess","createDedupedByCallsiteServerErrorLoggerDev","createHeadersAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","append","replaceableWarningDescriptor","delete","has","getSetCookie","forEach","keys","values","entries","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":";;;;+BA0CgBA;;;eAAAA;;;yBAvCT;0CAIA;8CAMA;kCAIA;yCAC+B;uCAK/B;0DACqD;uBACV;gCAEnB;kCAIxB;AAWA,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,6PAA6P,CAAC;QAE3R;QAEA,IAAIP,UAAUQ,WAAW,EAAE;YACzB,qFAAqF;YACrF,kCAAkC;YAClC,MAAMC,oBAAoBC,uBAAc,CAACC,IAAI,CAAC,IAAIC,QAAQ,CAAC;YAC3D,OAAOC,qBAAqBJ;QAC9B;QAEA,IAAIN,eAAe;YACjB,OAAQA,cAAcW,IAAI;gBACxB,KAAK;oBAAS;wBACZ,MAAMC,QAAQC,IAAAA,8CAA4B,EAAChB,UAAUO,KAAK;wBAC1DD,MAAMW,iBAAiB,CAACF,OAAOjB;wBAC/BoB,IAAAA,sCAAe,EAACH;wBAChBf,UAAUmB,wBAAwB,KAAKJ;wBACvC,MAAMA;oBACR;gBACA,KAAK;oBACH,MAAMK,IAAAA,mDAAiC,EAACpB,UAAUO,KAAK;gBACzD,KAAK;oBACH,MAAM,IAAID,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,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,EAAE,CAAC,GAAG;IAC7C,OAAO,IAAID,MACT,GAAG0E,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC;AAEtE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/io.d.ts b/e-commerce/node_modules/next/dist/server/request/io.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7517691460968176ca89308ef0a8cd7918bf7646 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/io.d.ts @@ -0,0 +1,12 @@ +/** + * This function allows you to indicate that the code following it performs + * I/O or accesses dynamic data sources such as `new Date()` or `Math.random()`. + * + * During prerendering it will prevent the prerender from continuing past this + * point, creating a dynamic boundary. Inside `"use cache"` scopes or during + * a real request it resolves immediately. + * + * Unlike `connection()`, `io()` does not require an actual HTTP request and + * can be used freely inside cache scopes and client components. + */ +export declare function io(): Promise; diff --git a/e-commerce/node_modules/next/dist/server/request/io.js b/e-commerce/node_modules/next/dist/server/request/io.js new file mode 100644 index 0000000000000000000000000000000000000000..c3cd0cf11d7dba01350aec6ef52b0edcc953caf8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/io.js @@ -0,0 +1,87 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "io", { + enumerable: true, + get: function() { + return io; + } +}); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _stagedrendering = require("../app-render/staged-rendering"); +const _utils = require("./utils"); +// A fulfilled thenable that React can unwrap synchronously via `use()` without +// ever suspending. Reusing a single instance avoids allocating on every call. +const resolvedIOPromise = Promise.resolve(undefined); +resolvedIOPromise.status = 'fulfilled'; +resolvedIOPromise.value = undefined; +function io() { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workStore && workUnitStore) { + if (workUnitStore && !(0, _utils.isRequestApiAllowedInCurrentPhase)(workUnitStore)) { + throw new Error(`Route ${workStore.route} used \`io()\` inside \`after()\` while rendering. The \`io()\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`); + } + switch(workUnitStore.type){ + case 'request': + // For dev renders we instrument the promise so it will show up in + // React Suspense Devtools and, if also doing `instant` validation, + // ensure it resolves in the right stage for staged rendering + // In production we just let it resolve immediately because we're doing + // a dynamic SSR or resume render and have no need to delay anything + // after this call + if (process.env.NODE_ENV === 'development') { + if (workUnitStore.asyncApiPromises) { + return workUnitStore.asyncApiPromises.io; + } + return (0, _dynamicrenderingutils.makeDevtoolsIOAwarePromise)(undefined, workUnitStore, _stagedrendering.RenderStage.Dynamic); + } else if (workUnitStore.asyncApiPromises) { + return workUnitStore.asyncApiPromises.io; + } + return resolvedIOPromise; + case 'prerender': + case 'prerender-client': + case 'prerender-runtime': + // When prerendering with Cache Components we consider `io()` to be + // actual IO if not in a cache scope and we can avoid actually executing + // anything after it by making it return a hanging promise. + return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(workUnitStore.renderSignal, workStore.route, '`io()`'); + case 'cache': + case 'private-cache': + case 'unstable-cache': + // Inside cache scopes, io() resolves immediately. + // Caches can contain IO-dependent code like new Date() — it will + // simply return the value at cache-fill time. + // ... + // intentional fallthrough + case 'build-time-generator': + // generateStaticParams runs at build time. There is no prerender + // to stall so we resolve immediately. + // ... + // intentional fallthrough + case 'validation-client': + // io() is usable in client components, resolve immediately. + // The reason we take this position is most io shielding you would do + // in a browser is for sync IO as there aren't many non-fetch based IO + // operations you can do in the browser that have meaningful latency. + // So while you might use + // ... + // intentional fallthrough + case 'prerender-legacy': + // Without cache components, IO is not inherently dynamic. + // Resolve immediately rather than interrupting static generation. + return resolvedIOPromise; + default: + workUnitStore; + } + } + // No work store — we're outside the Next.js rendering context (e.g. in + // a client component on the browser or in a standalone script). Resolve + // immediately. + return resolvedIOPromise; +} + +//# sourceMappingURL=io.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/io.js.map b/e-commerce/node_modules/next/dist/server/request/io.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c7911afba3f738c2e1945f530575f8041e5f0fb9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/io.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/io.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\n\n// A fulfilled thenable that React can unwrap synchronously via `use()` without\n// ever suspending. Reusing a single instance avoids allocating on every call.\nconst resolvedIOPromise: Promise = Promise.resolve(undefined)\n;(resolvedIOPromise as any).status = 'fulfilled'\n;(resolvedIOPromise as any).value = undefined\n\n/**\n * This function allows you to indicate that the code following it performs\n * I/O or accesses dynamic data sources such as `new Date()` or `Math.random()`.\n *\n * During prerendering it will prevent the prerender from continuing past this\n * point, creating a dynamic boundary. Inside `\"use cache\"` scopes or during\n * a real request it resolves immediately.\n *\n * Unlike `connection()`, `io()` does not require an actual HTTP request and\n * can be used freely inside cache scopes and client components.\n */\nexport function io(): Promise {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore && workUnitStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`io()\\` inside \\`after()\\` while rendering. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n switch (workUnitStore.type) {\n case 'request':\n // For dev renders we instrument the promise so it will show up in\n // React Suspense Devtools and, if also doing `instant` validation,\n // ensure it resolves in the right stage for staged rendering\n // In production we just let it resolve immediately because we're doing\n // a dynamic SSR or resume render and have no need to delay anything\n // after this call\n if (process.env.NODE_ENV === 'development') {\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return resolvedIOPromise\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // When prerendering with Cache Components we consider `io()` to be\n // actual IO if not in a cache scope and we can avoid actually executing\n // anything after it by making it return a hanging promise.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`io()`'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside cache scopes, io() resolves immediately.\n // Caches can contain IO-dependent code like new Date() — it will\n // simply return the value at cache-fill time.\n // ...\n // intentional fallthrough\n case 'build-time-generator':\n // generateStaticParams runs at build time. There is no prerender\n // to stall so we resolve immediately.\n // ...\n // intentional fallthrough\n case 'validation-client':\n // io() is usable in client components, resolve immediately.\n // The reason we take this position is most io shielding you would do\n // in a browser is for sync IO as there aren't many non-fetch based IO\n // operations you can do in the browser that have meaningful latency.\n // So while you might use\n // ...\n // intentional fallthrough\n case 'prerender-legacy':\n // Without cache components, IO is not inherently dynamic.\n // Resolve immediately rather than interrupting static generation.\n return resolvedIOPromise\n default:\n workUnitStore satisfies never\n }\n }\n\n // No work store — we're outside the Next.js rendering context (e.g. in\n // a client component on the browser or in a standalone script). Resolve\n // immediately.\n return resolvedIOPromise\n}\n"],"names":["io","resolvedIOPromise","Promise","resolve","undefined","status","value","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","type","process","env","NODE_ENV","asyncApiPromises","makeDevtoolsIOAwarePromise","RenderStage","Dynamic","makeDynamicHangingPromise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YACjE,sCAAsC;YACtC,MAAM;YACN,0BAA0B;YAC1B,KAAK;YACL,4DAA4D;YAC5D,qEAAqE;YACrE,sEAAsE;YACtE,qEAAqE;YACrE,yBAAyB;YACzB,MAAM;YACN,0BAA0B;YAC1B,KAAK;gBACH,0DAA0D;gBAC1D,kEAAkE;gBAClE,OAAOb;YACT;gBACES;QACJ;IACF;IAEA,uEAAuE;IACvE,wEAAwE;IACxE,eAAe;IACf,OAAOT;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/params.d.ts b/e-commerce/node_modules/next/dist/server/request/params.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ef6165f2f9672d3bd1a1df15d9fc251cb5487bf --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/params.d.ts @@ -0,0 +1,9 @@ +import type { VaryParamsAccumulator } from '../app-render/vary-params'; +export type ParamValue = string | Array | undefined; +export type Params = Record; +export declare function createParamsFromClient(underlyingParams: Params): Promise; +export type CreateServerParamsForMetadata = typeof createServerParamsForMetadata; +export declare function createServerParamsForMetadata(underlyingParams: Params, optionalCatchAllParamName: string | null): Promise; +export declare function createServerParamsForRoute(underlyingParams: Params, varyParamsAccumulator?: VaryParamsAccumulator | null): Promise; +export declare function createServerParamsForServerSegment(underlyingParams: Params, optionalCatchAllParamName: string | null, varyParamsAccumulator: VaryParamsAccumulator | null): Promise; +export declare function createPrerenderParamsForClientSegment(underlyingParams: Params): Promise; diff --git a/e-commerce/node_modules/next/dist/server/request/params.js b/e-commerce/node_modules/next/dist/server/request/params.js new file mode 100644 index 0000000000000000000000000000000000000000..af937898a8cfa795649630385277ed197d132401 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/params.js @@ -0,0 +1,500 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + createParamsFromClient: null, + createPrerenderParamsForClientSegment: null, + createServerParamsForMetadata: null, + createServerParamsForRoute: null, + createServerParamsForServerSegment: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + createParamsFromClient: function() { + return createParamsFromClient; + }, + createPrerenderParamsForClientSegment: function() { + return createPrerenderParamsForClientSegment; + }, + createServerParamsForMetadata: function() { + return createServerParamsForMetadata; + }, + createServerParamsForRoute: function() { + return createServerParamsForRoute; + }, + createServerParamsForServerSegment: function() { + return createServerParamsForServerSegment; + } +}); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _varyparams = require("../app-render/vary-params"); +const _reflect = require("../web/spec-extension/adapters/reflect"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _reflectutils = require("../../shared/lib/utils/reflect-utils"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _creatededupedbycallsiteservererrorlogger = require("../create-deduped-by-callsite-server-error-logger"); +const _dynamicaccessasyncstorageexternal = require("../app-render/dynamic-access-async-storage.external"); +const _paramsutils = require("../lib/params-utils"); +function createParamsFromClient(underlyingParams) { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new _invarianterror.InvariantError('Expected workStore to be initialized'); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore) { + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-client': + case 'prerender-legacy': + // Client params don't need additional vary tracking because by the + // time they reach the client, the access would have already been + // tracked by the server. + const varyParamsAccumulator = null; + return createStaticPrerenderParams(underlyingParams, null, workStore, workUnitStore, varyParamsAccumulator); + case 'cache': + case 'private-cache': + case 'unstable-cache': + throw new _invarianterror.InvariantError('createParamsFromClient should not be called in cache contexts.'); + case 'prerender-runtime': + throw new _invarianterror.InvariantError('createParamsFromClient should not be called in a runtime prerender.'); + case 'build-time-generator': + throw new _invarianterror.InvariantError(`createParamsFromClient should not be called inside ${workUnitStore.functionName}.`); + case 'validation-client': + { + if (workUnitStore.validationSamples) { + return createClientParamsInInstantValidation(underlyingParams, workStore, workUnitStore.validationSamples); + } + return makeUntrackedParams(underlyingParams); + } + case 'request': + { + if (workUnitStore.validationSamples) { + return createClientParamsInInstantValidation(underlyingParams, workStore, workUnitStore.validationSamples); + } + if (process.env.NODE_ENV === 'development') { + const stagedFallbackParams = workUnitStore.stagedFallbackParams; + const userspaceParams = underlyingParams; + return createRenderParamsInDev(underlyingParams, userspaceParams, stagedFallbackParams, workStore, workUnitStore); + } else { + return createRenderParamsInProd(underlyingParams); + } + } + default: + workUnitStore; + } + } + (0, _workunitasyncstorageexternal.throwInvariantForMissingStore)(); +} +function createServerParamsForMetadata(underlyingParams, optionalCatchAllParamName) { + const metadataVaryParamsAccumulator = (0, _varyparams.getMetadataVaryParamsAccumulator)(); + return createServerParamsForServerSegment(underlyingParams, optionalCatchAllParamName, metadataVaryParamsAccumulator); +} +function createServerParamsForRoute(underlyingParams, varyParamsAccumulator = null) { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new _invarianterror.InvariantError('Expected workStore to be initialized'); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore) { + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-legacy': + return createStaticPrerenderParams(underlyingParams, null, workStore, workUnitStore, varyParamsAccumulator); + case 'prerender-client': + case 'validation-client': + throw new _invarianterror.InvariantError('createServerParamsForRoute should not be called in client contexts.'); + case 'cache': + case 'private-cache': + case 'unstable-cache': + throw new _invarianterror.InvariantError('createServerParamsForRoute should not be called in cache contexts.'); + case 'build-time-generator': + throw new _invarianterror.InvariantError(`createServerParamsForRoute should not be called inside ${workUnitStore.functionName}.`); + case 'prerender-runtime': + { + throw new _invarianterror.InvariantError('createServerParamsForRoute should not be called in runtime prerenders.'); + } + case 'request': + if (process.env.NODE_ENV === 'development') { + const stagedFallbackParams = workUnitStore.stagedFallbackParams; + const userspaceParams = underlyingParams; + return createRenderParamsInDev(underlyingParams, userspaceParams, stagedFallbackParams, workStore, workUnitStore); + } else { + return createRenderParamsInProd(underlyingParams); + } + default: + workUnitStore; + } + } + (0, _workunitasyncstorageexternal.throwInvariantForMissingStore)(); +} +function createServerParamsForServerSegment(underlyingParams, optionalCatchAllParamName, varyParamsAccumulator) { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new _invarianterror.InvariantError('Expected workStore to be initialized'); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore) { + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-client': + case 'prerender-legacy': + return createStaticPrerenderParams(underlyingParams, optionalCatchAllParamName, workStore, workUnitStore, varyParamsAccumulator); + case 'validation-client': + throw new _invarianterror.InvariantError('createServerParamsForServerSegment should not be called in client contexts.'); + case 'cache': + case 'private-cache': + case 'unstable-cache': + throw new _invarianterror.InvariantError('createServerParamsForServerSegment should not be called in cache contexts.'); + case 'build-time-generator': + throw new _invarianterror.InvariantError(`createServerParamsForServerSegment should not be called inside ${workUnitStore.functionName}.`); + case 'prerender-runtime': + return createRuntimePrerenderParams(underlyingParams, optionalCatchAllParamName, workStore, workUnitStore, varyParamsAccumulator); + case 'request': + { + return createRenderParamsForPage(workStore, workUnitStore, underlyingParams, optionalCatchAllParamName, varyParamsAccumulator); + } + default: + workUnitStore; + } + } + (0, _workunitasyncstorageexternal.throwInvariantForMissingStore)(); +} +function createPrerenderParamsForClientSegment(underlyingParams) { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new _invarianterror.InvariantError('Missing workStore in createPrerenderParamsForClientSegment'); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore) { + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-client': + const fallbackParams = workUnitStore.fallbackRouteParams; + if (fallbackParams) { + for(let key in underlyingParams){ + if (fallbackParams.has(key)) { + // This params object has one or more fallback params, so we need + // to consider the awaiting of this params object "dynamic". Since + // we are in cacheComponents mode we encode this as a promise that never + // resolves. + return (0, _dynamicrenderingutils.makeFallbackParamsHangingPromise)(workUnitStore.renderSignal, workStore.route, '`params`', workUnitStore); + } + } + } + break; + case 'validation-client': + throw new _invarianterror.InvariantError('createPrerenderParamsForClientSegment should not be called in validation contexts.'); + break; + case 'cache': + case 'private-cache': + case 'unstable-cache': + throw new _invarianterror.InvariantError('createPrerenderParamsForClientSegment should not be called in cache contexts.'); + case 'build-time-generator': + throw new _invarianterror.InvariantError(`createPrerenderParamsForClientSegment should not be called inside ${workUnitStore.functionName}.`); + case 'prerender-runtime': + case 'prerender-legacy': + case 'request': + break; + default: + workUnitStore; + } + } + // We're prerendering in a mode that does not abort. We resolve the promise without + // any tracking because we're just transporting a value from server to client where the tracking + // will be applied. + return Promise.resolve(underlyingParams); +} +function createStaticPrerenderParams(underlyingParams, optionalCatchAllParamName, workStore, prerenderStore, varyParamsAccumulator) { + switch(prerenderStore.type){ + case 'prerender': + { + let userspaceParams = underlyingParams; + if (varyParamsAccumulator !== null) { + userspaceParams = (0, _varyparams.createVaryingParams)(varyParamsAccumulator, underlyingParams, optionalCatchAllParamName); + } + if ((0, _paramsutils.isEmptyParams)(underlyingParams)) { + // This route has no params. + return makeUntrackedParams(userspaceParams); + } + const fallbackParams = prerenderStore.fallbackRouteParams; + if ((0, _paramsutils.hasFallbackRouteParams)(underlyingParams, fallbackParams)) { + // This params object has one or more fallback params, so we need + // to consider the awaiting of this params object dynamic. + return makeHangingParams(underlyingParams, workStore, prerenderStore); + } + // All params are static. + const { stagedRendering } = prerenderStore; + if (stagedRendering) { + // Even if all params are static, we need to exclude them from the app shell + // by delaying them to the static stage. However, root params are allowed in shells, + // so if all the params are root params, they can be included as well. + if (!(0, _paramsutils.allParamsAreRootParams)(underlyingParams, prerenderStore.rootParams)) { + const staticParamsStage = _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.staticUrlData.static; + return stagedRendering.delayUntilStage(staticParamsStage, 'params', userspaceParams); + } + } + return makeUntrackedParams(userspaceParams); + } + case 'prerender-client': + { + const fallbackParams = prerenderStore.fallbackRouteParams; + if (fallbackParams) { + for(const key in underlyingParams){ + if (fallbackParams.has(key)) { + // This params object has one or more fallback params, so we need + // to consider the awaiting of this params object "dynamic". Since + // we are in cacheComponents mode we encode this as a promise that never + // resolves. + return makeHangingParams(underlyingParams, workStore, prerenderStore); + } + } + } + break; + } + case 'prerender-legacy': + break; + default: + prerenderStore; + } + let userspaceParams = underlyingParams; + if (varyParamsAccumulator !== null) { + userspaceParams = (0, _varyparams.createVaryingParams)(varyParamsAccumulator, underlyingParams, optionalCatchAllParamName); + } + return makeUntrackedParams(userspaceParams); +} +function createRuntimePrerenderParams(underlyingParams, optionalCatchAllParamName, workStore, workUnitStore, varyParamsAccumulator) { + let userspaceParams = underlyingParams; + if (varyParamsAccumulator !== null) { + userspaceParams = (0, _varyparams.createVaryingParams)(varyParamsAccumulator, underlyingParams, optionalCatchAllParamName); + } + if ((0, _paramsutils.isEmptyParams)(underlyingParams)) { + // This route has no params. + return makeUntrackedParams(userspaceParams); + } + // Root params are allowed in shells, so we allow them to resolve without a delay. + if ((0, _paramsutils.allParamsAreRootParams)(underlyingParams, workUnitStore.rootParams)) { + return makeUntrackedParams(userspaceParams); + } + // Non-root params are URL data, and we need to recover a param-less session shell, + // so we delay all params until the PrefetchRuntime stage (even if they're static) + const paramsStage = _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.runtimeUrlData; + const { stagedRendering } = workUnitStore; + if (!stagedRendering) { + // If there's no stage controller, we're in a prospective runtime prerender. + // Make sure we don't unblock content that won't be reached in the final prerender. + if (workUnitStore.finalStage < paramsStage) { + return makeHangingParams(underlyingParams, workStore, workUnitStore); + } else { + return makeUntrackedParams(userspaceParams); + } + } + // If params don't resolve in this prerender, caches need to treat them as a hanging input. + if (stagedRendering.finalStage && stagedRendering.finalStage < paramsStage) { + return makeHangingParams(underlyingParams, workStore, workUnitStore); + } else { + return stagedRendering.delayUntilStage(paramsStage, 'params', userspaceParams); + } +} +function createRenderParamsForPage(workStore, workUnitStore, underlyingParams, optionalCatchAllParamName, varyParamsAccumulator) { + const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore; + // Distinguish the params that we expose to userspace (potentially wrapped in proxies) + // and the underlying object containing params values. We do this because wrappers + // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names + // without triggering other wrapper proxies. + let userspaceParams = underlyingParams; + if (validationSamples) { + userspaceParams = createServerParamsProxyForInstantValidation(underlyingParams, workStore, validationSamples); + } + if (varyParamsAccumulator) { + userspaceParams = (0, _varyparams.createVaryingParams)(varyParamsAccumulator, userspaceParams, optionalCatchAllParamName); + } + if (stagedRendering && asyncApiPromises) { + return createStagedRenderParams(workStore, workUnitStore, stagedRendering, asyncApiPromises, underlyingParams, userspaceParams); + } + // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations + if (process.env.NODE_ENV === 'development') { + const stagedFallbackParams = workUnitStore.stagedFallbackParams; + return createRenderParamsInDev(underlyingParams, userspaceParams, stagedFallbackParams, workStore, workUnitStore); + } else { + return createRenderParamsInProd(userspaceParams); + } +} +function createStagedRenderParams(workStore, workUnitStore, stagedRendering, asyncApiPromises, underlyingParams, userspaceParams) { + const promise = createStagedRenderParamsImpl(workUnitStore, stagedRendering, asyncApiPromises, underlyingParams, userspaceParams); + if (process.env.NODE_ENV === 'development') { + return instrumentParamsPromiseWithDevWarnings(underlyingParams, promise, workStore); + } else { + return promise; + } +} +function createStagedRenderParamsImpl(workUnitStore, stagedRendering, asyncApiPromises, /** The actual param values, without any instrumentation */ underlyingParams, /** The params object to return to userspace, possibly wrapped in a proxy */ userspaceParams) { + // If the route has no params, they should resolve immediately. + if ((0, _paramsutils.isEmptyParams)(underlyingParams)) { + return makeUntrackedParams(userspaceParams); + } + // If we have fallback params, then they should always resolve in the runtime link data stage. + // We do this indirectly via the shared params parent for better debug info. + if ((0, _paramsutils.hasFallbackRouteParams)(underlyingParams, workUnitStore.stagedFallbackParams)) { + return createParamsPromiseFromTrigger(asyncApiPromises.sharedParamsParent, userspaceParams); + } + // All params are static. + // If we're rendering with shells, even static params must be delayed to exclude them from the shell. + // However, root params are allowed in shells, so if all the params are root params, they can be included as well. + if (!(0, _paramsutils.allParamsAreRootParams)(underlyingParams, workUnitStore.rootParams)) { + // For a dynamic request we generally want to recover a static shell, + // so static params can resolve in the static stage, because session + // shells are handled with a separate render. + // However, in dev we might need to recover a session shell for instant validation. + // This is indicated by `needsRuntimeShell`. + const staticParamsStage = _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.staticUrlData[workUnitStore.needsRuntimeShell ? 'runtime' : 'static']; + const promise = stagedRendering.delayUntilStage(staticParamsStage, 'params', userspaceParams); + if (process.env.__NEXT_DEV_SERVER) { + // If static params are accessed, we can recover a static shell or a session shell, but not both. + return (0, _dynamicrenderingutils.trackPromiseUsed)(promise, _dynamicrenderingutils.trackIncompatibleShellContent.bind(null, workUnitStore, 'static `params`')); + } else { + return promise; + } + } + return makeUntrackedParams(userspaceParams); +} +function createParamsPromiseFromTrigger(trigger, userspaceParams) { + if (process.env.NODE_ENV === 'development') { + // We wrap each instance of params in a `new Promise()`, which lets us show each + // await a different set of values. This is important when all awaits + // are in third party which would otherwise track all the way to the + // internal params. + const promise = new Promise((resolve, reject)=>{ + trigger.then(()=>resolve(userspaceParams), reject); + }); + promise.catch(noop); + // @ts-expect-error + promise.displayName = 'params'; + return promise; + } else { + return (0, _dynamicrenderingutils.makePromiseFromTrigger)(trigger, userspaceParams); + } +} +function noop() {} +function createServerParamsProxyForInstantValidation(underlyingParams, workStore, validationSamples) { + const { createExhaustiveParamsProxy } = require('../app-render/instant-validation/instant-samples'); + const declaredParams = new Set(Object.keys(validationSamples.params ?? {})); + return createExhaustiveParamsProxy(underlyingParams, declaredParams, workStore.route); +} +function createClientParamsInInstantValidation(underlyingParams, workStore, validationSamples) { + const { createExhaustiveParamsProxy } = require('../app-render/instant-validation/instant-samples'); + const declaredParams = new Set(Object.keys((validationSamples == null ? void 0 : validationSamples.params) ?? {})); + const proxiedUnderlying = createExhaustiveParamsProxy(underlyingParams, declaredParams, workStore.route); + return Promise.resolve(proxiedUnderlying); +} +function createRenderParamsInProd(userspaceParams) { + return makeUntrackedParams(userspaceParams); +} +function createRenderParamsInDev(underlyingParams, userpaceParams, stagedFallbackParams, workStore, requestStore) { + return makeDynamicallyTrackedParamsWithDevWarnings(underlyingParams, userpaceParams, (0, _paramsutils.hasFallbackRouteParams)(underlyingParams, stagedFallbackParams), workStore, requestStore); +} +const CachedParams = new WeakMap(); +const fallbackParamsProxyHandler = { + get: function get(target, prop, receiver) { + if (prop === 'then' || prop === 'catch' || prop === 'finally') { + const originalMethod = _reflect.ReflectAdapter.get(target, prop, receiver); + return ({ + [prop]: (...args)=>{ + // Record against the store that's active at access time: the + // hanging promise is cached by params object across prerender + // stores, so the store that created it may not be the one that's + // rendering when it's finally awaited. + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore !== undefined) { + (0, _dynamicrenderingutils.trackFallbackParamsAccessed)(workUnitStore, '`params`'); + } + (0, _dynamicaccessasyncstorageexternal.abortOnDynamicAccess)('fallback-params', new Error(`Accessed fallback \`params\` during prerendering.`)); + return new Proxy(originalMethod.apply(target, args), fallbackParamsProxyHandler); + } + })[prop]; + } + return _reflect.ReflectAdapter.get(target, prop, receiver); + } +}; +function makeHangingParams(underlyingParams, workStore, prerenderStore) { + const cachedParams = CachedParams.get(underlyingParams); + if (cachedParams) { + return cachedParams; + } + const promise = new Proxy((0, _dynamicrenderingutils.makeFallbackParamsHangingPromise)(prerenderStore.renderSignal, workStore.route, '`params`', // Passing `null` for the store disables tracking of params usage. + // Caches need the additional logic from `fallbackParamsProxyHandler`, + // so we track params usage there instead. + null), fallbackParamsProxyHandler); + CachedParams.set(underlyingParams, promise); + return promise; +} +function makeUntrackedParams(underlyingParams) { + const cachedParams = CachedParams.get(underlyingParams); + if (cachedParams) { + return cachedParams; + } + const promise = Promise.resolve(underlyingParams); + CachedParams.set(underlyingParams, promise); + return promise; +} +function makeDynamicallyTrackedParamsWithDevWarnings(underlyingParams, userspaceParams, hasFallbackParams, workStore, requestStore) { + const cachedParams = CachedParams.get(underlyingParams); + if (cachedParams) { + return cachedParams; + } + // We don't use makeResolvedReactPromise here because params + // supports copying with spread and we don't want to unnecessarily + // instrument the promise with spreadable properties of ReactPromise. + const promise = hasFallbackParams ? (0, _dynamicrenderingutils.makeDevtoolsIOAwarePromise)(userspaceParams, requestStore, _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.runtimeUrlData) : Promise.resolve(userspaceParams); + const proxiedPromise = instrumentParamsPromiseWithDevWarnings(underlyingParams, promise, workStore); + CachedParams.set(underlyingParams, proxiedPromise); + return proxiedPromise; +} +function instrumentParamsPromiseWithDevWarnings(underlyingParams, promise, workStore) { + // Track which properties we should warn for. + const proxiedProperties = new Set(); + Object.keys(underlyingParams).forEach((prop)=>{ + if (_reflectutils.wellKnownProperties.has(prop)) { + // These properties cannot be shadowed because they need to be the + // true underlying value for Promises to work correctly at runtime + } else { + proxiedProperties.add(prop); + } + }); + return new Proxy(promise, { + get (target, prop, receiver) { + if (typeof prop === 'string') { + if (// We are accessing a property that was proxied to the promise instance + proxiedProperties.has(prop)) { + const expression = (0, _reflectutils.describeStringPropertyAccess)('params', prop); + warnForSyncAccess(workStore.route, expression); + } + } + return _reflect.ReflectAdapter.get(target, prop, receiver); + }, + set (target, prop, value, receiver) { + if (typeof prop === 'string') { + proxiedProperties.delete(prop); + } + return _reflect.ReflectAdapter.set(target, prop, value, receiver); + }, + ownKeys (target) { + const expression = '`...params` or similar expression'; + warnForSyncAccess(workStore.route, expression); + return Reflect.ownKeys(target); + } + }); +} +const warnForSyncAccess = (0, _creatededupedbycallsiteservererrorlogger.createDedupedByCallsiteServerErrorLoggerDev)(createParamsAccessError); +function createParamsAccessError(route, expression) { + const prefix = route ? `Route "${route}" ` : 'This route '; + return new Error(`${prefix}used ${expression}. ` + `\`params\` is a Promise and must be unwrapped with \`await\` or \`React.use()\` before accessing its properties. ` + `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`); +} + +//# sourceMappingURL=params.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/params.js.map b/e-commerce/node_modules/next/dist/server/request/params.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a032274ba8fab67eddbcc873aeebfe1742494105 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/params.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n workUnitAsyncStorage,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeFallbackParamsHangingPromise,\n makePromiseFromTrigger,\n trackFallbackParamsAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n trackPromiseUsed,\n trackIncompatibleShellContent,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { abortOnDynamicAccess } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array | undefined\nexport type Params = Record\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'build-time-generator':\n throw new InvariantError(\n `createParamsFromClient should not be called inside ${workUnitStore.functionName}.`\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const stagedFallbackParams = workUnitStore.stagedFallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n stagedFallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'build-time-generator':\n throw new InvariantError(\n `createServerParamsForRoute should not be called inside ${workUnitStore.functionName}.`\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const stagedFallbackParams = workUnitStore.stagedFallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n stagedFallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'build-time-generator':\n throw new InvariantError(\n `createServerParamsForServerSegment should not be called inside ${workUnitStore.functionName}.`\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`',\n workUnitStore\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'build-time-generator':\n throw new InvariantError(\n `createPrerenderParamsForClientSegment should not be called inside ${workUnitStore.functionName}.`\n )\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage =\n RENDER_STAGES_BY_DATA_KIND.staticUrlData.static\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n // Root params are allowed in shells, so we allow them to resolve without a delay.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Non-root params are URL data, and we need to recover a param-less session shell,\n // so we delay all params until the PrefetchRuntime stage (even if they're static)\n const paramsStage = RENDER_STAGES_BY_DATA_KIND.runtimeUrlData\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no stage controller, we're in a prospective runtime prerender.\n // Make sure we don't unblock content that won't be reached in the final prerender.\n if (workUnitStore.finalStage < paramsStage) {\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // If params don't resolve in this prerender, caches need to treat them as a hanging input.\n if (stagedRendering.finalStage && stagedRendering.finalStage < paramsStage) {\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return stagedRendering.delayUntilStage(\n paramsStage,\n 'params',\n userspaceParams\n )\n }\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const stagedFallbackParams = workUnitStore.stagedFallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n stagedFallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable,\n asyncApiPromises: NonNullable,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable,\n asyncApiPromises: NonNullable,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (\n hasFallbackRouteParams(underlyingParams, workUnitStore.stagedFallbackParams)\n ) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsRuntimeShell`.\n const staticParamsStage =\n RENDER_STAGES_BY_DATA_KIND.staticUrlData[\n workUnitStore.needsRuntimeShell ? 'runtime' : 'static'\n ]\n\n const promise = stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n if (process.env.__NEXT_DEV_SERVER) {\n // If static params are accessed, we can recover a static shell or a session shell, but not both.\n return trackPromiseUsed(\n promise,\n trackIncompatibleShellContent.bind(\n null,\n workUnitStore,\n 'static `params`'\n )\n )\n } else {\n return promise\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n stagedFallbackParams: ReadonlySet | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, stagedFallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap>()\n\nconst fallbackParamsProxyHandler: ProxyHandler> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore, '`params`')\n }\n\n abortOnDynamicAccess(\n 'fallback-params',\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeFallbackParamsHangingPromise(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`',\n // Passing `null` for the store disables tracking of params usage.\n // Caches need the additional logic from `fallbackParamsProxyHandler`,\n // so we track params usage there instead.\n null\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeUrlData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise,\n workStore: WorkStore\n): Promise {\n // Track which properties we should warn for.\n const proxiedProperties = new Set()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["createParamsFromClient","createPrerenderParamsForClientSegment","createServerParamsForMetadata","createServerParamsForRoute","createServerParamsForServerSegment","underlyingParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","varyParamsAccumulator","createStaticPrerenderParams","functionName","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","stagedFallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","throwInvariantForMissingStore","optionalCatchAllParamName","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","createRuntimePrerenderParams","createRenderParamsForPage","fallbackParams","fallbackRouteParams","key","has","makeFallbackParamsHangingPromise","renderSignal","route","Promise","resolve","prerenderStore","createVaryingParams","isEmptyParams","hasFallbackRouteParams","makeHangingParams","stagedRendering","allParamsAreRootParams","rootParams","staticParamsStage","RENDER_STAGES_BY_DATA_KIND","staticUrlData","static","delayUntilStage","paramsStage","runtimeUrlData","finalStage","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsRuntimeShell","__NEXT_DEV_SERVER","trackPromiseUsed","trackIncompatibleShellContent","bind","trigger","reject","then","catch","noop","displayName","makePromiseFromTrigger","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","ReflectAdapter","args","undefined","trackFallbackParamsAccessed","abortOnDynamicAccess","Error","Proxy","apply","cachedParams","set","hasFallbackParams","makeDevtoolsIOAwarePromise","proxiedPromise","proxiedProperties","forEach","wellKnownProperties","add","expression","describeStringPropertyAccess","warnForSyncAccess","value","delete","ownKeys","Reflect","createDedupedByCallsiteServerErrorLoggerDev","createParamsAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IA6CgBA,sBAAsB;eAAtBA;;IAqNAC,qCAAqC;eAArCA;;IAtIAC,6BAA6B;eAA7BA;;IAaAC,0BAA0B;eAA1BA;;IA6DAC,kCAAkC;eAAlCA;;;0CAnMT;4BAKA;yBAEwB;8CASxB;gCACwB;8BAIxB;uCASA;0DACqD;mDACvB;6BAK9B;AAKA,SAASJ,uBACdK,gBAAwB;IAExB,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,IAAIG,8BAAc,CAAC;IAC3B;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,c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B;QACxB;IACF;IAEA,OAAO,IAAIS,MAAM1C,SAAS;QACxB+B,KAAIC,MAAM,EAAEC,IAAI,EAAEC,QAAQ;YACxB,IAAI,OAAOD,SAAS,UAAU;gBAC5B,IACE,uEAAuE;gBACvEgB,kBAAkB1E,GAAG,CAAC0D,OACtB;oBACA,MAAMoB,aAAaC,IAAAA,0CAA4B,EAAC,UAAUrB;oBAC1DsB,kBAAkB7G,UAAUgC,KAAK,EAAE2E;gBACrC;YACF;YACA,OAAOjB,uBAAc,CAACL,GAAG,CAACC,QAAQC,MAAMC;QAC1C;QACAW,KAAIb,MAAM,EAAEC,IAAI,EAAEuB,KAAK,EAAEtB,QAAQ;YAC/B,IAAI,OAAOD,SAAS,UAAU;gBAC5BgB,kBAAkBQ,MAAM,CAACxB;YAC3B;YACA,OAAOG,uBAAc,CAACS,GAAG,CAACb,QAAQC,MAAMuB,OAAOtB;QACjD;QACAwB,SAAQ1B,MAAM;YACZ,MAAMqB,aAAa;YACnBE,kBAAkB7G,UAAUgC,KAAK,EAAE2E;YACnC,OAAOM,QAAQD,OAAO,CAAC1B;QACzB;IACF;AACF;AAEA,MAAMuB,oBAAoBK,IAAAA,qFAA2C,EACnEC;AAGF,SAASA,wBACPnF,KAAyB,EACzB2E,UAAkB;IAElB,MAAMS,SAASpF,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,IAAI+D,MACT,GAAGqB,OAAO,KAAK,EAAET,WAAW,EAAE,CAAC,GAC7B,CAAC,iHAAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC;AAEtE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/pathname.d.ts b/e-commerce/node_modules/next/dist/server/request/pathname.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e3ca03f6ccf79222a49e0f98ba064dc6135ce99 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/pathname.d.ts @@ -0,0 +1 @@ +export declare function createServerPathnameForMetadata(underlyingPathname: string): Promise; diff --git a/e-commerce/node_modules/next/dist/server/request/pathname.js b/e-commerce/node_modules/next/dist/server/request/pathname.js new file mode 100644 index 0000000000000000000000000000000000000000..9d608eb9f1cfb7e2f4c511136fac6425158345ae --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/pathname.js @@ -0,0 +1,89 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "createServerPathnameForMetadata", { + enumerable: true, + get: function() { + return createServerPathnameForMetadata; + } +}); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _invarianterror = require("../../shared/lib/invariant-error"); +function createServerPathnameForMetadata(underlyingPathname) { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new _invarianterror.InvariantError('Expected workStore to be initialized'); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore) { + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-legacy': + { + return createPrerenderPathname(underlyingPathname, workStore, workUnitStore); + } + case 'prerender-client': + case 'validation-client': + throw new _invarianterror.InvariantError('createServerPathnameForMetadata should not be called in client contexts.'); + case 'cache': + case 'private-cache': + case 'unstable-cache': + throw new _invarianterror.InvariantError('createServerPathnameForMetadata should not be called in cache contexts.'); + case 'build-time-generator': + throw new _invarianterror.InvariantError(`createServerPathnameForMetadata should not be called inside ${workUnitStore.functionName}.`); + case 'prerender-runtime': + { + // TODO(app-shells): whether or not this is included in the shell + // should depend on whether this route has params. + // if there's no params, it can be included. + // for now, we defensively exclude it to match the earlier pessimistic + // behavior of always resolving in the PrefetchRuntime stage + // (i.e. assuming that we have non-static params in the pathname) + const { stagedRendering } = workUnitStore; + const pathnameStage = _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.runtimeUrlData; + if (stagedRendering) { + return stagedRendering.delayUntilStage(pathnameStage, undefined, underlyingPathname); + } else { + if (workUnitStore.finalStage < pathnameStage) { + return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(workUnitStore.renderSignal, workStore.route, '`pathname`'); + } else { + return createRenderPathname(underlyingPathname); + } + } + } + case 'request': + // TODO(app-shells): this should be delayed if there's non-static params + return createRenderPathname(underlyingPathname); + default: + workUnitStore; + } + } + (0, _workunitasyncstorageexternal.throwInvariantForMissingStore)(); +} +function createPrerenderPathname(underlyingPathname, workStore, prerenderStore) { + switch(prerenderStore.type){ + case 'prerender': + { + const fallbackParams = prerenderStore.fallbackRouteParams; + if (fallbackParams && fallbackParams.size > 0) { + // The pathname depends on params, so we track it like a fallback params access. + return (0, _dynamicrenderingutils.makeFallbackParamsHangingPromise)(prerenderStore.renderSignal, workStore.route, '`pathname`', prerenderStore); + } + break; + } + case 'prerender-legacy': + break; + default: + prerenderStore; + } + // We don't have any fallback params so we have an entirely static safe params object + return Promise.resolve(underlyingPathname); +} +function createRenderPathname(underlyingPathname) { + return Promise.resolve(underlyingPathname); +} + +//# sourceMappingURL=pathname.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/pathname.js.map b/e-commerce/node_modules/next/dist/server/request/pathname.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d46f2ab4c75830f652996320539c6604a77ff0e8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/pathname.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/pathname.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\n\nimport {\n throwInvariantForMissingStore,\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeFallbackParamsHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function createServerPathnameForMetadata(\n underlyingPathname: string\n): Promise {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-legacy': {\n return createPrerenderPathname(\n underlyingPathname,\n workStore,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in cache contexts.'\n )\n case 'build-time-generator':\n throw new InvariantError(\n `createServerPathnameForMetadata should not be called inside ${workUnitStore.functionName}.`\n )\n case 'prerender-runtime': {\n // TODO(app-shells): whether or not this is included in the shell\n // should depend on whether this route has params.\n // if there's no params, it can be included.\n // for now, we defensively exclude it to match the earlier pessimistic\n // behavior of always resolving in the PrefetchRuntime stage\n // (i.e. assuming that we have non-static params in the pathname)\n const { stagedRendering } = workUnitStore\n const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeUrlData\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n pathnameStage,\n undefined,\n underlyingPathname\n )\n } else {\n if (workUnitStore.finalStage < pathnameStage) {\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`pathname`'\n )\n } else {\n return createRenderPathname(underlyingPathname)\n }\n }\n }\n case 'request':\n // TODO(app-shells): this should be delayed if there's non-static params\n return createRenderPathname(underlyingPathname)\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createPrerenderPathname(\n underlyingPathname: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStoreModernServer\n): Promise {\n switch (prerenderStore.type) {\n case 'prerender': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n // The pathname depends on params, so we track it like a fallback params access.\n return makeFallbackParamsHangingPromise(\n prerenderStore.renderSignal,\n workStore.route,\n '`pathname`',\n prerenderStore\n )\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n // We don't have any fallback params so we have an entirely static safe params object\n return Promise.resolve(underlyingPathname)\n}\n\nfunction createRenderPathname(underlyingPathname: string): Promise {\n return Promise.resolve(underlyingPathname)\n}\n"],"names":["createServerPathnameForMetadata","underlyingPathname","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","createPrerenderPathname","functionName","stagedRendering","pathnameStage","RENDER_STAGES_BY_DATA_KIND","runtimeUrlData","delayUntilStage","undefined","finalStage","makeDynamicHangingPromise","renderSignal","route","createRenderPathname","throwInvariantForMissingStore","prerenderStore","fallbackParams","fallbackRouteParams","size","makeFallbackParamsHangingPromise","Promise","resolve"],"mappings":";;;;+BAkBgBA;;;eAAAA;;;0CAfT;8CAOA;uCAKA;gCACwB;AAExB,SAASA,gCACdC,kBAA0B;IAE1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,IAAIG,8BAAc,CAAC;IAC3B;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;gBAAoB;oBACvB,OAAOC,wBACLR,oBACAC,WACAI;gBAEJ;YACA,KAAK;YACL,KAAK;gBACH,MAAM,IAAID,8BAAc,CACtB;YAEJ,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,IAAIA,8BAAc,CACtB;YAEJ,KAAK;gBACH,MAAM,IAAIA,8BAAc,CACtB,CAAC,4DAA4D,EAAEC,cAAcI,YAAY,CAAC,CAAC,CAAC;YAEhG,KAAK;gBAAqB;oBACxB,iEAAiE;oBACjE,kDAAkD;oBAClD,4CAA4C;oBAC5C,sEAAsE;oBACtE,4DAA4D;oBAC5D,iEAAiE;oBACjE,MAAM,EAAEC,eAAe,EAAE,GAAGL;oBAC5B,MAAMM,gBAAgBC,iDAA0B,CAACC,cAAc;oBAC/D,IAAIH,iBAAiB;wBACnB,OAAOA,gBAAgBI,eAAe,CACpCH,eACAI,WACAf;oBAEJ,OAAO;wBACL,IAAIK,cAAcW,UAAU,GAAGL,eAAe;4BAC5C,OAAOM,IAAAA,gDAAyB,EAC9BZ,cAAca,YAAY,EAC1BjB,UAAUkB,KAAK,EACf;wBAEJ,OAAO;4BACL,OAAOC,qBAAqBpB;wBAC9B;oBACF;gBACF;YACA,KAAK;gBACH,wEAAwE;gBACxE,OAAOoB,qBAAqBpB;YAC9B;gBACEK;QACJ;IACF;IACAgB,IAAAA,2DAA6B;AAC/B;AAEA,SAASb,wBACPR,kBAA0B,EAC1BC,SAAoB,EACpBqB,cAAiE;IAEjE,OAAQA,eAAef,IAAI;QACzB,KAAK;YAAa;gBAChB,MAAMgB,iBAAiBD,eAAeE,mBAAmB;gBACzD,IAAID,kBAAkBA,eAAeE,IAAI,GAAG,GAAG;oBAC7C,gFAAgF;oBAChF,OAAOC,IAAAA,uDAAgC,EACrCJ,eAAeJ,YAAY,EAC3BjB,UAAUkB,KAAK,EACf,cACAG;gBAEJ;gBACA;YACF;QACA,KAAK;YACH;QACF;YACEA;IACJ;IAEA,qFAAqF;IACrF,OAAOK,QAAQC,OAAO,CAAC5B;AACzB;AAEA,SAASoB,qBAAqBpB,kBAA0B;IACtD,OAAO2B,QAAQC,OAAO,CAAC5B;AACzB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/root-params.d.ts b/e-commerce/node_modules/next/dist/server/request/root-params.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/root-params.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/e-commerce/node_modules/next/dist/server/request/root-params.js b/e-commerce/node_modules/next/dist/server/request/root-params.js new file mode 100644 index 0000000000000000000000000000000000000000..332af48ed4a84b166da1890c45f80b1901d6b6ee --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/root-params.js @@ -0,0 +1,146 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getRootParam", { + enumerable: true, + get: function() { + return getRootParam; + } +}); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _dynamicaccessasyncstorageexternal = require("../app-render/dynamic-access-async-storage.external"); +const _actionasyncstorageexternal = require("../app-render/action-async-storage.external"); +const _varyparams = require("../app-render/vary-params"); +function getRootParam(paramName) { + const apiName = `\`import('next/root-params').${paramName}()\``; + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new _invarianterror.InvariantError(`Missing workStore in ${apiName}`); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (!workUnitStore) { + throw new Error(`Route ${workStore.route} used ${apiName} outside of a Server Component. This is not allowed.`); + } + const actionStore = _actionasyncstorageexternal.actionAsyncStorage.getStore(); + if (actionStore) { + if (actionStore.isAppRoute) { + // TODO(root-params): add support for route handlers + throw new Error(`Route ${workStore.route} used ${apiName} inside a Route Handler. Support for this API in Route Handlers is planned for a future version of Next.js.`); + } + if (actionStore.isAction && workUnitStore.phase === 'action') { + // Actions are not fundamentally tied to a route (even if they're always submitted from some page), + // so root params would be inconsistent if an action is called from multiple roots. + // Make sure we check if the phase is "action" - we should not error in the rerender + // after an action revalidates or updates cookies (which will still have `actionStore.isAction === true`) + throw new Error(`${apiName} was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route.`); + } + } + switch(workUnitStore.type){ + case 'unstable-cache': + { + throw new Error(`Route ${workStore.route} used ${apiName} inside \`unstable_cache\`. This is not supported. Use \`"use cache"\` instead.`); + } + case 'cache': + { + if (!workUnitStore.rootParams) { + throw new Error(`Route ${workStore.route} used ${apiName} inside \`"use cache"\` nested within \`unstable_cache\`. Root params are not available in this context.`); + } + workUnitStore.readRootParamNames.add(paramName); + const prerenderStore = workUnitStore.fallbackRootParamsPrerender; + if (prerenderStore !== null && prerenderStore.fallbackRouteParams !== null && prerenderStore.fallbackRouteParams.has(paramName)) { + return (0, _dynamicrenderingutils.trackPromiseUsed)((0, _dynamicrenderingutils.makeFallbackParamsHangingPromise)(prerenderStore.renderSignal, workStore.route, apiName, // Track access and cancel the cache together when consumed below. + null), ()=>{ + (0, _dynamicrenderingutils.trackFallbackParamsAccessed)(prerenderStore, apiName); + // Like fallback `params`, an unknown root makes the whole cache + // invocation dynamic, even if it contains its own Suspense. + (0, _dynamicaccessasyncstorageexternal.abortOnDynamicAccess)('fallback-params', new Error(`Accessed fallback root parameter "${paramName}" during prerendering.`)); + }); + } + return Promise.resolve(workUnitStore.rootParams[paramName]); + } + case 'prerender': + case 'prerender-legacy': + { + return createPrerenderRootParamPromise(paramName, workStore, workUnitStore, apiName); + } + case 'validation-client': + case 'prerender-client': + { + throw new _invarianterror.InvariantError(`${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.`); + } + case 'request': + { + if (process.env.__NEXT_CACHE_COMPONENTS && workUnitStore.validationSamples) { + const { assertRootParamInSamples } = require('../app-render/instant-validation/instant-samples'); + // If we error, make sure we return a rejected promise instead of erroring synchronously. + try { + assertRootParamInSamples(workStore, workUnitStore.validationSamples.params, paramName); + } catch (err) { + return Promise.reject(err); + } + } + break; + } + case 'private-cache': + { + workUnitStore.readRootParamNames.add(paramName); + return Promise.resolve(workUnitStore.rootParams[paramName]); + } + case 'prerender-runtime': + { + break; + } + case 'build-time-generator': + { + if (!(paramName in workUnitStore.rootParams)) { + if (workUnitStore.functionName !== 'generateStaticParams') { + throw new Error(`Route ${workStore.route} used ${apiName} inside \`${workUnitStore.functionName}\`, but the \`${paramName}\` parameter is not available in this build-time generator.`); + } + throw new Error(`Route ${workStore.route} used ${apiName} inside \`generateStaticParams\`, but the \`${paramName}\` parameter was not provided by a parent \`generateStaticParams\`. In \`generateStaticParams\`, root params are only available for segments nested below the segment that provides them.`); + } + break; + } + default: + { + workUnitStore; + } + } + (0, _varyparams.accumulateRootVaryParam)(paramName); + return Promise.resolve(workUnitStore.rootParams[paramName]); +} +function createPrerenderRootParamPromise(paramName, workStore, prerenderStore, apiName) { + switch(prerenderStore.type){ + case 'prerender': + case 'prerender-legacy': + default: + } + const underlyingParams = prerenderStore.rootParams; + switch(prerenderStore.type){ + case 'prerender': + { + // We are in a cacheComponents prerender. + // The param is a fallback, so it should be treated as dynamic. + if (prerenderStore.fallbackRouteParams && prerenderStore.fallbackRouteParams.has(paramName)) { + return (0, _dynamicrenderingutils.makeFallbackParamsHangingPromise)(prerenderStore.renderSignal, workStore.route, apiName, prerenderStore); + } + break; + } + case 'prerender-legacy': + { + break; + } + default: + { + prerenderStore; + } + } + // If the param is not a fallback param, we just return the statically available value. + (0, _varyparams.accumulateRootVaryParam)(paramName); + return Promise.resolve(underlyingParams[paramName]); +} + +//# sourceMappingURL=root-params.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/root-params.js.map b/e-commerce/node_modules/next/dist/server/request/root-params.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5de7e54e7aaa339948e02f4fa6b29f9445b14bb2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/root-params.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/root-params.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n makeFallbackParamsHangingPromise,\n trackFallbackParamsAccessed,\n trackPromiseUsed,\n} from '../dynamic-rendering-utils'\nimport { abortOnDynamicAccess } from '../app-render/dynamic-access-async-storage.external'\nimport type { ParamValue } from './params'\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external'\nimport { accumulateRootVaryParam } from '../app-render/vary-params'\n\n/**\n * Used for the compiler-generated `next/root-params` module.\n * @internal\n */\nexport function getRootParam(paramName: string): Promise {\n const apiName = `\\`import('next/root-params').${paramName}()\\``\n\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(`Missing workStore in ${apiName}`)\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} outside of a Server Component. This is not allowed.`\n )\n }\n\n const actionStore = actionAsyncStorage.getStore()\n if (actionStore) {\n if (actionStore.isAppRoute) {\n // TODO(root-params): add support for route handlers\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside a Route Handler. Support for this API in Route Handlers is planned for a future version of Next.js.`\n )\n }\n if (actionStore.isAction && workUnitStore.phase === 'action') {\n // Actions are not fundamentally tied to a route (even if they're always submitted from some page),\n // so root params would be inconsistent if an action is called from multiple roots.\n // Make sure we check if the phase is \"action\" - we should not error in the rerender\n // after an action revalidates or updates cookies (which will still have `actionStore.isAction === true`)\n throw new Error(\n `${apiName} was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route.`\n )\n }\n }\n\n switch (workUnitStore.type) {\n case 'unstable-cache': {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`unstable_cache\\`. This is not supported. Use \\`\"use cache\"\\` instead.`\n )\n }\n case 'cache': {\n if (!workUnitStore.rootParams) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`\"use cache\"\\` nested within \\`unstable_cache\\`. Root params are not available in this context.`\n )\n }\n workUnitStore.readRootParamNames.add(paramName)\n const prerenderStore = workUnitStore.fallbackRootParamsPrerender\n if (\n prerenderStore !== null &&\n prerenderStore.fallbackRouteParams !== null &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return trackPromiseUsed(\n makeFallbackParamsHangingPromise(\n prerenderStore.renderSignal,\n workStore.route,\n apiName,\n // Track access and cancel the cache together when consumed below.\n null\n ),\n () => {\n trackFallbackParamsAccessed(prerenderStore, apiName)\n // Like fallback `params`, an unknown root makes the whole cache\n // invocation dynamic, even if it contains its own Suspense.\n abortOnDynamicAccess(\n 'fallback-params',\n new Error(\n `Accessed fallback root parameter \"${paramName}\" during prerendering.`\n )\n )\n }\n )\n }\n return Promise.resolve(workUnitStore.rootParams[paramName])\n }\n case 'prerender':\n case 'prerender-legacy': {\n return createPrerenderRootParamPromise(\n paramName,\n workStore,\n workUnitStore,\n apiName\n )\n }\n case 'validation-client':\n case 'prerender-client': {\n throw new InvariantError(\n `${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.`\n )\n }\n case 'request': {\n if (\n process.env.__NEXT_CACHE_COMPONENTS &&\n workUnitStore.validationSamples\n ) {\n const { assertRootParamInSamples } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n // If we error, make sure we return a rejected promise instead of erroring synchronously.\n try {\n assertRootParamInSamples(\n workStore,\n workUnitStore.validationSamples.params,\n paramName\n )\n } catch (err) {\n return Promise.reject(err)\n }\n }\n break\n }\n case 'private-cache': {\n workUnitStore.readRootParamNames.add(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n }\n case 'prerender-runtime': {\n break\n }\n case 'build-time-generator': {\n if (!(paramName in workUnitStore.rootParams)) {\n if (workUnitStore.functionName !== 'generateStaticParams') {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`${workUnitStore.functionName}\\`, but the \\`${paramName}\\` parameter is not available in this build-time generator.`\n )\n }\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`generateStaticParams\\`, but the \\`${paramName}\\` parameter was not provided by a parent \\`generateStaticParams\\`. In \\`generateStaticParams\\`, root params are only available for segments nested below the segment that provides them.`\n )\n }\n break\n }\n default: {\n workUnitStore satisfies never\n }\n }\n\n accumulateRootVaryParam(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n}\n\nfunction createPrerenderRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStoreModernServer,\n apiName: string\n): Promise {\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n default:\n }\n\n const underlyingParams = prerenderStore.rootParams\n\n switch (prerenderStore.type) {\n case 'prerender': {\n // We are in a cacheComponents prerender.\n // The param is a fallback, so it should be treated as dynamic.\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeFallbackParamsHangingPromise(\n prerenderStore.renderSignal,\n workStore.route,\n apiName,\n prerenderStore\n )\n }\n break\n }\n case 'prerender-legacy': {\n // legacy prerenders can't have fallback params\n break\n }\n default: {\n prerenderStore satisfies never\n }\n }\n\n // If the param is not a fallback param, we just return the statically available value.\n accumulateRootVaryParam(paramName)\n return Promise.resolve(underlyingParams[paramName])\n}\n"],"names":["getRootParam","paramName","apiName","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","Error","route","actionStore","actionAsyncStorage","isAppRoute","isAction","phase","type","rootParams","readRootParamNames","add","prerenderStore","fallbackRootParamsPrerender","fallbackRouteParams","has","trackPromiseUsed","makeFallbackParamsHangingPromise","renderSignal","trackFallbackParamsAccessed","abortOnDynamicAccess","Promise","resolve","createPrerenderRootParamPromise","process","env","__NEXT_CACHE_COMPONENTS","validationSamples","assertRootParamInSamples","require","params","err","reject","functionName","accumulateRootVaryParam","underlyingParams"],"mappings":";;;;+BAwBgBA;;;eAAAA;;;gCAxBe;0CAIxB;8CAKA;uCAKA;mDAC8B;4CAEF;4BACK;AAMjC,SAASA,aAAaC,SAAiB;I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C,MAAM,EAAEN,UAAUO,KAAK,CAAC,MAAM,EAAER,QAAQ,UAAU,EAAEK,cAAckC,YAAY,CAAC,cAAc,EAAExC,UAAU,2DAA2D,CAAC;oBAE1K;oBACA,MAAM,IAAIQ,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,MAAM,EAAER,QAAQ,4CAA4C,EAAED,UAAU,yLAAyL,CAAC;gBAE/R;gBACA;YACF;QACA;YAAS;gBACPM;YACF;IACF;IAEAmC,IAAAA,mCAAuB,EAACzC;IACxB,OAAO4B,QAAQC,OAAO,CAACvB,cAAcU,UAAU,CAAChB,UAAU;AAC5D;AAEA,SAAS8B,gCACP9B,SAAiB,EACjBE,SAAoB,EACpBiB,cAAiE,EACjElB,OAAe;IAEf,OAAQkB,eAAeJ,IAAI;QACzB,KAAK;QACL,KAAK;QACL;IACF;IAEA,MAAM2B,mBAAmBvB,eAAeH,UAAU;IAElD,OAAQG,eAAeJ,IAAI;QACzB,KAAK;YAAa;gBAChB,yCAAyC;gBACzC,+DAA+D;gBAC/D,IACEI,eAAeE,mBAAmB,IAClCF,eAAeE,mBAAmB,CAACC,GAAG,CAACtB,YACvC;oBACA,OAAOwB,IAAAA,uDAAgC,EACrCL,eAAeM,YAAY,EAC3BvB,UAAUO,KAAK,EACfR,SACAkB;gBAEJ;gBACA;YACF;QACA,KAAK;YAAoB;gBAEvB;YACF;QACA;YAAS;gBACPA;YACF;IACF;IAEA,uFAAuF;IACvFsB,IAAAA,mCAAuB,EAACzC;IACxB,OAAO4B,QAAQC,OAAO,CAACa,gBAAgB,CAAC1C,UAAU;AACpD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/search-params.d.ts b/e-commerce/node_modules/next/dist/server/request/search-params.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c327ed1f7b8d153357c7f3b2fd7cef37b88627eb --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/search-params.d.ts @@ -0,0 +1,14 @@ +import type { VaryParamsAccumulator } from '../app-render/vary-params'; +export type SearchParams = { + [key: string]: string | string[] | undefined; +}; +export declare function createSearchParamsFromClient(underlyingSearchParams: SearchParams): Promise; +export declare function createServerSearchParamsForMetadata(underlyingSearchParams: SearchParams): Promise; +export declare function createServerSearchParamsForServerPage(underlyingSearchParams: SearchParams, varyParamsAccumulator: VaryParamsAccumulator | null): Promise; +export declare function createPrerenderSearchParamsForClientPage(): Promise; +/** + * This is a variation of `makeErroringSearchParams` that always throws an + * error on access, because accessing searchParams inside of `"use cache"` is + * not allowed. + */ +export declare function makeErroringSearchParamsForUseCache(): Promise; diff --git a/e-commerce/node_modules/next/dist/server/request/search-params.js b/e-commerce/node_modules/next/dist/server/request/search-params.js new file mode 100644 index 0000000000000000000000000000000000000000..b5fd8c222ce7afda03a13cc8032fea6d8b7a8a94 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/search-params.js @@ -0,0 +1,505 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + createPrerenderSearchParamsForClientPage: null, + createSearchParamsFromClient: null, + createServerSearchParamsForMetadata: null, + createServerSearchParamsForServerPage: null, + makeErroringSearchParamsForUseCache: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + createPrerenderSearchParamsForClientPage: function() { + return createPrerenderSearchParamsForClientPage; + }, + createSearchParamsFromClient: function() { + return createSearchParamsFromClient; + }, + createServerSearchParamsForMetadata: function() { + return createServerSearchParamsForMetadata; + }, + createServerSearchParamsForServerPage: function() { + return createServerSearchParamsForServerPage; + }, + makeErroringSearchParamsForUseCache: function() { + return makeErroringSearchParamsForUseCache; + } +}); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _varyparams = require("../app-render/vary-params"); +const _reflect = require("../web/spec-extension/adapters/reflect"); +const _dynamicrendering = require("../app-render/dynamic-rendering"); +const _dynamicaccessasyncstorageexternal = require("../app-render/dynamic-access-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _creatededupedbycallsiteservererrorlogger = require("../create-deduped-by-callsite-server-error-logger"); +const _reflectutils = require("../../shared/lib/utils/reflect-utils"); +const _utils = require("./utils"); +function createSearchParamsFromClient(underlyingSearchParams) { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new _invarianterror.InvariantError('Expected workStore to be initialized'); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore) { + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-client': + case 'prerender-legacy': + return createStaticPrerenderSearchParams(workStore, workUnitStore); + case 'prerender-runtime': + throw new _invarianterror.InvariantError('createSearchParamsFromClient should not be called in a runtime prerender.'); + case 'cache': + case 'private-cache': + case 'unstable-cache': + throw new _invarianterror.InvariantError('createSearchParamsFromClient should not be called in cache contexts.'); + case 'build-time-generator': + throw new _invarianterror.InvariantError(`createSearchParamsFromClient should not be called inside ${workUnitStore.functionName}.`); + case 'validation-client': + { + if (workUnitStore.validationSamples) { + return createClientSearchParamsInValidation(underlyingSearchParams, workStore, workUnitStore); + } + return makeUntrackedSearchParams(underlyingSearchParams); + } + case 'request': + return createRenderSearchParams(underlyingSearchParams, workStore, workUnitStore); + default: + workUnitStore; + } + } + (0, _workunitasyncstorageexternal.throwInvariantForMissingStore)(); +} +function createServerSearchParamsForMetadata(underlyingSearchParams) { + const metadataVaryParamsAccumulator = (0, _varyparams.getMetadataVaryParamsAccumulator)(); + return createServerSearchParamsForServerPage(underlyingSearchParams, metadataVaryParamsAccumulator); +} +function createServerSearchParamsForServerPage(underlyingSearchParams, varyParamsAccumulator) { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new _invarianterror.InvariantError('Expected workStore to be initialized'); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore) { + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-client': + case 'prerender-legacy': + return createStaticPrerenderSearchParams(workStore, workUnitStore); + case 'validation-client': + throw new _invarianterror.InvariantError('createServerSearchParamsForServerPage should not be called in a client validation.'); + case 'cache': + case 'private-cache': + case 'unstable-cache': + throw new _invarianterror.InvariantError('createServerSearchParamsForServerPage should not be called in cache contexts.'); + case 'build-time-generator': + throw new _invarianterror.InvariantError(`createServerSearchParamsForServerPage should not be called inside ${workUnitStore.functionName}.`); + case 'prerender-runtime': + return createRuntimePrerenderSearchParams(underlyingSearchParams, workStore, workUnitStore, varyParamsAccumulator); + case 'request': + return createRenderSearchParams(underlyingSearchParams, workStore, workUnitStore); + default: + workUnitStore; + } + } + (0, _workunitasyncstorageexternal.throwInvariantForMissingStore)(); +} +function createPrerenderSearchParamsForClientPage() { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new _invarianterror.InvariantError('Expected workStore to be initialized'); + } + if (workStore.forceStatic) { + // When using forceStatic we override all other logic and always just return an empty + // dictionary object. + return Promise.resolve({}); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore) { + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-client': + // We're prerendering in a mode that aborts (cacheComponents) and should stall + // the promise to ensure the RSC side is considered dynamic + return (0, _dynamicrenderingutils.makeURLDataHangingPromise)(workUnitStore.renderSignal, workStore.route, '`searchParams`', workUnitStore); + case 'validation-client': + throw new _invarianterror.InvariantError('createPrerenderSearchParamsForClientPage should not be called in a client validation.'); + case 'prerender-runtime': + throw new _invarianterror.InvariantError('createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'); + case 'cache': + case 'private-cache': + case 'unstable-cache': + throw new _invarianterror.InvariantError('createPrerenderSearchParamsForClientPage should not be called in cache contexts.'); + case 'build-time-generator': + throw new _invarianterror.InvariantError(`createPrerenderSearchParamsForClientPage should not be called inside ${workUnitStore.functionName}.`); + case 'prerender-legacy': + case 'request': + return Promise.resolve({}); + default: + workUnitStore; + } + } + (0, _workunitasyncstorageexternal.throwInvariantForMissingStore)(); +} +function createStaticPrerenderSearchParams(workStore, prerenderStore) { + if (workStore.forceStatic) { + // When using forceStatic we override all other logic and always just return an empty + // dictionary object. + return Promise.resolve({}); + } + switch(prerenderStore.type){ + case 'prerender': + case 'prerender-client': + { + // We are in a cacheComponents (PPR or otherwise) prerender + return makeHangingSearchParams(workStore, prerenderStore); + } + case 'prerender-legacy': + // We are in a legacy static generation and need to interrupt the + // prerender when search params are accessed. + return makeErroringSearchParams(workStore, prerenderStore); + default: + return prerenderStore; + } +} +function createRuntimePrerenderSearchParams(underlyingSearchParams, workStore, workUnitStore, varyParamsAccumulator) { + const userspaceSearchParams = varyParamsAccumulator !== null ? (0, _varyparams.createVaryingSearchParams)(varyParamsAccumulator, underlyingSearchParams) : underlyingSearchParams; + const searchParamsStage = _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.runtimeUrlData; + const { stagedRendering } = workUnitStore; + if (!stagedRendering) { + // If there's no stage controller, we're in a prospective runtime prerender. + // Make sure we don't unblock content that won't be reached in the final prerender. + if (workUnitStore.finalStage < searchParamsStage) { + return makeHangingSearchParams(workStore, workUnitStore); + } else { + return makeUntrackedSearchParams(userspaceSearchParams); + } + } + // If search params don't resolve in this prerender, caches need to treat them as a hanging input. + if (stagedRendering.finalStage && stagedRendering.finalStage < searchParamsStage) { + return makeHangingSearchParams(workStore, workUnitStore); + } else { + return stagedRendering.delayUntilStage(searchParamsStage, 'searchParams', userspaceSearchParams); + } +} +function createRenderSearchParams(underlyingSearchParams, workStore, requestStore) { + const { asyncApiPromises, validationSamples } = requestStore; + if (asyncApiPromises) { + let userspaceSearchParams = underlyingSearchParams; + if (validationSamples) { + userspaceSearchParams = createSearchParamsProxyForInstantValidation(workStore, validationSamples, underlyingSearchParams); + } + return createStagedRenderSearchParams(workStore, asyncApiPromises, underlyingSearchParams, userspaceSearchParams); + } + // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations + if (workStore.forceStatic) { + // When using forceStatic we override all other logic and always just return an empty + // dictionary object. + return Promise.resolve({}); + } + if (process.env.NODE_ENV === 'development') { + // Semantically we only need the dev tracking when running in `next dev` + // but since you would never use next dev with production NODE_ENV we use this + // as a proxy so we can statically exclude this code from production builds. + return makeUntrackedSearchParamsWithDevWarnings(underlyingSearchParams, workStore, requestStore); + } else { + return makeUntrackedSearchParams(underlyingSearchParams); + } +} +function createStagedRenderSearchParams(workStore, asyncApiPromises, underlyingSearchParams, userspaceSearchParams) { + const trigger = asyncApiPromises.sharedSearchParamsParent; + if (process.env.NODE_ENV === 'development') { + // We wrap each instance of searchParams in a `new Promise()`. + // This is important when all awaits are in third party which would otherwise + // track all the way to the internal params. + const promise = new Promise((resolve, reject)=>{ + trigger.then(()=>resolve(userspaceSearchParams), reject); + }); + // @ts-expect-error + promise.displayName = 'searchParams'; + promise.catch(ignoreReject); + return instrumentSearchParamsPromiseWithDevWarnings(underlyingSearchParams, promise, workStore); + } else { + return (0, _dynamicrenderingutils.makePromiseFromTrigger)(trigger, userspaceSearchParams); + } +} +function createSearchParamsProxyForInstantValidation(workStore, validationSamples, underlyingSearchParams) { + const { createExhaustiveSearchParamsProxy } = require('../app-render/instant-validation/instant-samples'); + const declaredKeys = new Set(Object.keys(validationSamples.searchParams ?? {})); + return createExhaustiveSearchParamsProxy(underlyingSearchParams, declaredKeys, workStore.route); +} +const CachedSearchParams = new WeakMap(); +const CachedSearchParamsForUseCache = new WeakMap(); +function makeHangingSearchParams(workStore, prerenderStore) { + const cachedSearchParams = CachedSearchParams.get(prerenderStore); + if (cachedSearchParams) { + return cachedSearchParams; + } + const promise = (0, _dynamicrenderingutils.makeURLDataHangingPromise)(prerenderStore.renderSignal, workStore.route, '`searchParams`', // Passing `null` for the store disables tracking of params usage. + // We want accesses of chained promises to be tracked as well. + // TODO: The custom tracking seems unnecessary, we should standardize it + null); + const trackSearchParamsAccessed = ()=>{ + // Record against the store that's active at access time: the promise is + // created while the RSC payload is constructed, but typically accessed + // later, during the render, under a different store. + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + (0, _dynamicrenderingutils.trackURLDataAccessed)(workUnitStore ?? prerenderStore, '`searchParams`'); + }; + const proxyHandler = { + get (target, prop, receiver) { + if (Object.hasOwn(target, prop)) { + // The promise has this property directly. we must return it. + // We know it isn't a dynamic access because it can only be something + // that was previously written to the promise and thus not an underlying searchParam value + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + switch(prop){ + case 'then': + case 'catch': + case 'finally': + { + const originalMethod = _reflect.ReflectAdapter.get(target, prop, receiver); + return ({ + [prop]: (...args)=>{ + const expression = '`await searchParams`, `searchParams.then`, or similar'; + trackSearchParamsAccessed(); + (0, _dynamicrendering.annotateDynamicAccess)(expression, prerenderStore); + // Mirror `makeHangingParams`: when this never-resolving promise + // is awaited while a `use cache` key is being encoded + // (dynamicAccessAsyncStorage is set), abort so the surrounding + // cache bails out to a dynamic hole instead of hanging on it. + // Without this, a private cache that reads `searchParams` would + // stall the App Shell cache-warming render. Re-wrapping the + // result propagates the same behavior to promises derived via + // `.then`/`.catch`/`.finally` that are then passed into a cache. + (0, _dynamicaccessasyncstorageexternal.abortOnDynamicAccess)('runtime', new Error('Accessed `searchParams` during prerendering.')); + return new Proxy(originalMethod.apply(target, args), proxyHandler); + } + })[prop]; + } + case 'status': + { + const expression = '`use(searchParams)`, `searchParams.status`, or similar'; + trackSearchParamsAccessed(); + (0, _dynamicrendering.annotateDynamicAccess)(expression, prerenderStore); + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + default: + { + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + } + } + }; + const proxiedPromise = new Proxy(promise, proxyHandler); + CachedSearchParams.set(prerenderStore, proxiedPromise); + return proxiedPromise; +} +function makeErroringSearchParams(workStore, prerenderStore) { + const cachedSearchParams = CachedSearchParams.get(workStore); + if (cachedSearchParams) { + return cachedSearchParams; + } + const underlyingSearchParams = {}; + // For search params we don't construct a ReactPromise because we want to interrupt + // rendering on any property access that was not set from outside and so we only want + // to have properties like value and status if React sets them. + const promise = Promise.resolve(underlyingSearchParams); + const proxiedPromise = new Proxy(promise, { + get (target, prop, receiver) { + if (Object.hasOwn(promise, prop)) { + // The promise has this property directly. we must return it. + // We know it isn't a dynamic access because it can only be something + // that was previously written to the promise and thus not an underlying searchParam value + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + if (typeof prop === 'string' && prop === 'then') { + const expression = '`await searchParams`, `searchParams.then`, or similar'; + if (workStore.dynamicShouldError) { + (0, _utils.throwWithStaticGenerationBailoutErrorWithDynamicError)(workStore.route, expression); + } else { + // Legacy Prerender + (0, _dynamicrendering.throwToInterruptStaticGeneration)(expression, workStore, prerenderStore); + } + } + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + }); + CachedSearchParams.set(workStore, proxiedPromise); + return proxiedPromise; +} +function makeErroringSearchParamsForUseCache() { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new _invarianterror.InvariantError('Expected workStore to be initialized'); + } + const cachedSearchParams = CachedSearchParamsForUseCache.get(workStore); + if (cachedSearchParams) { + return cachedSearchParams; + } + const promise = Promise.resolve({}); + const proxiedPromise = new Proxy(promise, { + get: function get(target, prop, receiver) { + if (Object.hasOwn(promise, prop)) { + // The promise has this property directly. we must return it. We know it + // isn't a dynamic access because it can only be something that was + // previously written to the promise and thus not an underlying + // searchParam value + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + if (typeof prop === 'string' && (prop === 'then' || !_reflectutils.wellKnownProperties.has(prop))) { + (0, _utils.throwForSearchParamsAccessInUseCache)(workStore, get); + } + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + }); + CachedSearchParamsForUseCache.set(workStore, proxiedPromise); + return proxiedPromise; +} +function makeUntrackedSearchParams(underlyingSearchParams) { + const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams); + if (cachedSearchParams) { + return cachedSearchParams; + } + const promise = Promise.resolve(underlyingSearchParams); + CachedSearchParams.set(underlyingSearchParams, promise); + return promise; +} +function makeUntrackedSearchParamsWithDevWarnings(underlyingSearchParams, workStore, requestStore) { + const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams); + if (cachedSearchParams) { + return cachedSearchParams; + } + const promise = makeUntrackedSearchParamsWithDevWarningsImpl(underlyingSearchParams, workStore, requestStore); + CachedSearchParams.set(requestStore, promise); + return promise; +} +function makeUntrackedSearchParamsWithDevWarningsImpl(underlyingSearchParams, workStore, requestStore) { + const promiseInitialized = { + current: false + }; + const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(underlyingSearchParams, workStore, promiseInitialized); + const promise = (0, _dynamicrenderingutils.makeDevtoolsIOAwarePromise)(proxiedUnderlying, requestStore, _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.runtimeUrlData); + promise.then(()=>{ + promiseInitialized.current = true; + }, // If we're in staged rendering, this promise will reject if the render + // is aborted before it can reach the PrefetchRuntime stage. + // In that case, we have to prevent an unhandled rejection from the promise + // created by this `.then()` call. + // This does not affect the `promiseInitialized` logic above, + // because `proxiedUnderlying` will not be used to resolve the promise, + // so there's no risk of any of its properties being accessed and triggering + // an undesireable warning. + ignoreReject); + return instrumentSearchParamsPromiseWithDevWarnings(underlyingSearchParams, promise, workStore); +} +function ignoreReject() {} +function instrumentSearchParamsObjectWithDevWarnings(underlyingSearchParams, workStore, promiseInitialized) { + // We have an unfortunate sequence of events that requires this initialization logic. We want to instrument the underlying + // searchParams object to detect if you are accessing values in dev. This is used for warnings and for things like the static prerender + // indicator. However when we pass this proxy to our Promise.resolve() below the VM checks if the resolved value is a promise by looking + // at the `.then` property. To our dynamic tracking logic this is indistinguishable from a `then` searchParam and so we would normally trigger + // dynamic tracking. However we know that this .then is not real dynamic access, it's just how thenables resolve in sequence. So we introduce + // this initialization concept so we omit the dynamic check until after we've constructed our resolved promise. + return new Proxy(underlyingSearchParams, { + get (target, prop, receiver) { + if (typeof prop === 'string' && promiseInitialized.current) { + if (workStore.dynamicShouldError) { + const expression = (0, _reflectutils.describeStringPropertyAccess)('searchParams', prop); + (0, _utils.throwWithStaticGenerationBailoutErrorWithDynamicError)(workStore.route, expression); + } + } + return _reflect.ReflectAdapter.get(target, prop, receiver); + }, + has (target, prop) { + if (typeof prop === 'string') { + if (workStore.dynamicShouldError) { + const expression = (0, _reflectutils.describeHasCheckingStringProperty)('searchParams', prop); + (0, _utils.throwWithStaticGenerationBailoutErrorWithDynamicError)(workStore.route, expression); + } + } + return Reflect.has(target, prop); + }, + ownKeys (target) { + if (workStore.dynamicShouldError) { + const expression = '`{...searchParams}`, `Object.keys(searchParams)`, or similar'; + (0, _utils.throwWithStaticGenerationBailoutErrorWithDynamicError)(workStore.route, expression); + } + return Reflect.ownKeys(target); + } + }); +} +function instrumentSearchParamsPromiseWithDevWarnings(underlyingSearchParams, promise, workStore) { + // Track which properties we should warn for. + const proxiedProperties = new Set(); + Object.keys(underlyingSearchParams).forEach((prop)=>{ + if (_reflectutils.wellKnownProperties.has(prop)) { + // These properties cannot be shadowed because they need to be the + // true underlying value for Promises to work correctly at runtime + } else { + proxiedProperties.add(prop); + } + }); + return new Proxy(promise, { + get (target, prop, receiver) { + if (prop === 'then' && workStore.dynamicShouldError) { + const expression = '`searchParams.then`'; + (0, _utils.throwWithStaticGenerationBailoutErrorWithDynamicError)(workStore.route, expression); + } + if (typeof prop === 'string') { + if (!_reflectutils.wellKnownProperties.has(prop) && (proxiedProperties.has(prop) || // We are accessing a property that doesn't exist on the promise nor + // the underlying searchParams. + Reflect.has(target, prop) === false)) { + const expression = (0, _reflectutils.describeStringPropertyAccess)('searchParams', prop); + warnForSyncAccess(workStore.route, expression); + } + } + return _reflect.ReflectAdapter.get(target, prop, receiver); + }, + set (target, prop, value, receiver) { + if (typeof prop === 'string') { + proxiedProperties.delete(prop); + } + return Reflect.set(target, prop, value, receiver); + }, + has (target, prop) { + if (typeof prop === 'string') { + if (!_reflectutils.wellKnownProperties.has(prop) && (proxiedProperties.has(prop) || // We are accessing a property that doesn't exist on the promise nor + // the underlying searchParams. + Reflect.has(target, prop) === false)) { + const expression = (0, _reflectutils.describeHasCheckingStringProperty)('searchParams', prop); + warnForSyncAccess(workStore.route, expression); + } + } + return Reflect.has(target, prop); + }, + ownKeys (target) { + const expression = '`Object.keys(searchParams)` or similar'; + warnForSyncAccess(workStore.route, expression); + return Reflect.ownKeys(target); + } + }); +} +const warnForSyncAccess = (0, _creatededupedbycallsiteservererrorlogger.createDedupedByCallsiteServerErrorLoggerDev)(createSearchAccessError); +function createSearchAccessError(route, expression) { + const prefix = route ? `Route "${route}" ` : 'This route '; + return new Error(`${prefix}used ${expression}. ` + `\`searchParams\` is a Promise and must be unwrapped with \`await\` or \`React.use()\` before accessing its properties. ` + `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`); +} +function createClientSearchParamsInValidation(underlyingSearchParams, workStore, workUnitStore) { + var _workUnitStore_validationSamples; + const { createExhaustiveSearchParamsProxy } = require('../app-render/instant-validation/instant-samples'); + const declaredKeys = new Set(Object.keys(((_workUnitStore_validationSamples = workUnitStore.validationSamples) == null ? void 0 : _workUnitStore_validationSamples.searchParams) ?? {})); + underlyingSearchParams = createExhaustiveSearchParamsProxy(underlyingSearchParams, declaredKeys, workStore.route); + return Promise.resolve(underlyingSearchParams); +} + +//# sourceMappingURL=search-params.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/search-params.js.map b/e-commerce/node_modules/next/dist/server/request/search-params.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d42e2925b5612c62222e4e5b5be74643b9f9c5e7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/search-params.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/search-params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingSearchParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n annotateDynamicAccess,\n} from '../app-render/dynamic-rendering'\nimport { abortOnDynamicAccess } from '../app-render/dynamic-access-async-storage.external'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModern,\n type PrerenderStoreModernRuntime,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n makeDevtoolsIOAwarePromise,\n makeURLDataHangingPromise,\n makePromiseFromTrigger,\n trackURLDataAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport {\n describeStringPropertyAccess,\n describeHasCheckingStringProperty,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n throwWithStaticGenerationBailoutErrorWithDynamicError,\n throwForSearchParamsAccessInUseCache,\n} from './utils'\n\nexport type SearchParams = { [key: string]: string | string[] | undefined }\n\nexport function createSearchParamsFromClient(\n underlyingSearchParams: SearchParams\n): Promise {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'prerender-runtime':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in cache contexts.'\n )\n case 'build-time-generator':\n throw new InvariantError(\n `createSearchParamsFromClient should not be called inside ${workUnitStore.functionName}.`\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientSearchParamsInValidation(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n }\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerSearchParamsForMetadata(\n underlyingSearchParams: SearchParams\n): Promise {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerSearchParamsForServerPage(\n underlyingSearchParams,\n metadataVaryParamsAccumulator\n )\n}\n\nexport function createServerSearchParamsForServerPage(\n underlyingSearchParams: SearchParams,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'validation-client':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in a client validation.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in cache contexts.'\n )\n case 'build-time-generator':\n throw new InvariantError(\n `createServerSearchParamsForServerPage should not be called inside ${workUnitStore.functionName}.`\n )\n case 'prerender-runtime':\n return createRuntimePrerenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderSearchParamsForClientPage(): Promise {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We're prerendering in a mode that aborts (cacheComponents) and should stall\n // the promise to ensure the RSC side is considered dynamic\n return makeURLDataHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`searchParams`',\n workUnitStore\n )\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a client validation.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'\n )\n case 'build-time-generator':\n throw new InvariantError(\n `createPrerenderSearchParamsForClientPage should not be called inside ${workUnitStore.functionName}.`\n )\n case 'prerender-legacy':\n case 'request':\n return Promise.resolve({})\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createStaticPrerenderSearchParams(\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore\n): Promise {\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-client': {\n // We are in a cacheComponents (PPR or otherwise) prerender\n return makeHangingSearchParams(workStore, prerenderStore)\n }\n case 'prerender-legacy':\n // We are in a legacy static generation and need to interrupt the\n // prerender when search params are accessed.\n return makeErroringSearchParams(workStore, prerenderStore)\n default:\n return prerenderStore satisfies never\n }\n}\n\nfunction createRuntimePrerenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise {\n const userspaceSearchParams =\n varyParamsAccumulator !== null\n ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)\n : underlyingSearchParams\n\n const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeUrlData\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no stage controller, we're in a prospective runtime prerender.\n // Make sure we don't unblock content that won't be reached in the final prerender.\n if (workUnitStore.finalStage < searchParamsStage) {\n return makeHangingSearchParams(workStore, workUnitStore)\n } else {\n return makeUntrackedSearchParams(userspaceSearchParams)\n }\n }\n\n // If search params don't resolve in this prerender, caches need to treat them as a hanging input.\n if (\n stagedRendering.finalStage &&\n stagedRendering.finalStage < searchParamsStage\n ) {\n return makeHangingSearchParams(workStore, workUnitStore)\n } else {\n return stagedRendering.delayUntilStage(\n searchParamsStage,\n 'searchParams',\n userspaceSearchParams\n )\n }\n}\n\nfunction createRenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise {\n const { asyncApiPromises, validationSamples } = requestStore\n\n if (asyncApiPromises) {\n let userspaceSearchParams = underlyingSearchParams\n if (validationSamples) {\n userspaceSearchParams = createSearchParamsProxyForInstantValidation(\n workStore,\n validationSamples,\n underlyingSearchParams\n )\n }\n\n return createStagedRenderSearchParams(\n workStore,\n asyncApiPromises,\n underlyingSearchParams,\n userspaceSearchParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n } else {\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n}\n\nfunction createStagedRenderSearchParams(\n workStore: WorkStore,\n asyncApiPromises: NonNullable,\n underlyingSearchParams: SearchParams,\n userspaceSearchParams: SearchParams\n): Promise {\n const trigger = asyncApiPromises.sharedSearchParamsParent\n\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of searchParams in a `new Promise()`.\n // This is important when all awaits are in third party which would otherwise\n // track all the way to the internal params.\n const promise = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceSearchParams), reject)\n })\n // @ts-expect-error\n promise.displayName = 'searchParams'\n promise.catch(ignoreReject)\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n } else {\n return makePromiseFromTrigger(trigger, userspaceSearchParams)\n }\n}\n\nfunction createSearchParamsProxyForInstantValidation(\n workStore: WorkStore,\n validationSamples: NonNullable,\n underlyingSearchParams: SearchParams\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(validationSamples.searchParams ?? {})\n )\n return createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n}\n\ninterface CacheLifetime {}\nconst CachedSearchParams = new WeakMap>()\n\nconst CachedSearchParamsForUseCache = new WeakMap<\n CacheLifetime,\n Promise\n>()\n\nfunction makeHangingSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise {\n const cachedSearchParams = CachedSearchParams.get(prerenderStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = makeURLDataHangingPromise(\n prerenderStore.renderSignal,\n workStore.route,\n '`searchParams`',\n // Passing `null` for the store disables tracking of params usage.\n // We want accesses of chained promises to be tracked as well.\n // TODO: The custom tracking seems unnecessary, we should standardize it\n null\n )\n\n const trackSearchParamsAccessed = () => {\n // Record against the store that's active at access time: the promise is\n // created while the RSC payload is constructed, but typically accessed\n // later, during the render, under a different store.\n const workUnitStore = workUnitAsyncStorage.getStore()\n trackURLDataAccessed(workUnitStore ?? prerenderStore, '`searchParams`')\n }\n\n const proxyHandler: ProxyHandler> = {\n get(target, prop, receiver) {\n if (Object.hasOwn(target, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n switch (prop) {\n case 'then':\n case 'catch':\n case 'finally': {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n return {\n [prop]: (...args: unknown[]) => {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n // Mirror `makeHangingParams`: when this never-resolving promise\n // is awaited while a `use cache` key is being encoded\n // (dynamicAccessAsyncStorage is set), abort so the surrounding\n // cache bails out to a dynamic hole instead of hanging on it.\n // Without this, a private cache that reads `searchParams` would\n // stall the App Shell cache-warming render. Re-wrapping the\n // result propagates the same behavior to promises derived via\n // `.then`/`.catch`/`.finally` that are then passed into a cache.\n abortOnDynamicAccess(\n 'runtime',\n new Error('Accessed `searchParams` during prerendering.')\n )\n return new Proxy(originalMethod.apply(target, args), proxyHandler)\n },\n }[prop]\n }\n case 'status': {\n const expression =\n '`use(searchParams)`, `searchParams.status`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n default: {\n return ReflectAdapter.get(target, prop, receiver)\n }\n }\n },\n }\n\n const proxiedPromise = new Proxy(promise, proxyHandler)\n\n CachedSearchParams.set(prerenderStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeErroringSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy\n): Promise {\n const cachedSearchParams = CachedSearchParams.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const underlyingSearchParams = {}\n // For search params we don't construct a ReactPromise because we want to interrupt\n // rendering on any property access that was not set from outside and so we only want\n // to have properties like value and status if React sets them.\n const promise = Promise.resolve(underlyingSearchParams)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (typeof prop === 'string' && prop === 'then') {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n if (workStore.dynamicShouldError) {\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParams.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\n/**\n * This is a variation of `makeErroringSearchParams` that always throws an\n * error on access, because accessing searchParams inside of `\"use cache\"` is\n * not allowed.\n */\nexport function makeErroringSearchParamsForUseCache(): Promise {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const cachedSearchParams = CachedSearchParamsForUseCache.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve({})\n\n const proxiedPromise = new Proxy(promise, {\n get: function get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it. We know it\n // isn't a dynamic access because it can only be something that was\n // previously written to the promise and thus not an underlying\n // searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (\n typeof prop === 'string' &&\n (prop === 'then' || !wellKnownProperties.has(prop))\n ) {\n throwForSearchParamsAccessInUseCache(workStore, get)\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParamsForUseCache.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeUntrackedSearchParams(\n underlyingSearchParams: SearchParams\n): Promise {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve(underlyingSearchParams)\n CachedSearchParams.set(underlyingSearchParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n const promise = makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n CachedSearchParams.set(requestStore, promise)\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise {\n const promiseInitialized = { current: false }\n const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams,\n workStore,\n promiseInitialized\n )\n\n const promise = makeDevtoolsIOAwarePromise(\n proxiedUnderlying,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeUrlData\n )\n\n promise.then(\n () => {\n promiseInitialized.current = true\n },\n // If we're in staged rendering, this promise will reject if the render\n // is aborted before it can reach the PrefetchRuntime stage.\n // In that case, we have to prevent an unhandled rejection from the promise\n // created by this `.then()` call.\n // This does not affect the `promiseInitialized` logic above,\n // because `proxiedUnderlying` will not be used to resolve the promise,\n // so there's no risk of any of its properties being accessed and triggering\n // an undesireable warning.\n ignoreReject\n )\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n}\n\nfunction ignoreReject() {}\n\nfunction instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n promiseInitialized: { current: boolean }\n) {\n // We have an unfortunate sequence of events that requires this initialization logic. We want to instrument the underlying\n // searchParams object to detect if you are accessing values in dev. This is used for warnings and for things like the static prerender\n // indicator. However when we pass this proxy to our Promise.resolve() below the VM checks if the resolved value is a promise by looking\n // at the `.then` property. To our dynamic tracking logic this is indistinguishable from a `then` searchParam and so we would normally trigger\n // dynamic tracking. However we know that this .then is not real dynamic access, it's just how thenables resolve in sequence. So we introduce\n // this initialization concept so we omit the dynamic check until after we've constructed our resolved promise.\n return new Proxy(underlyingSearchParams, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && promiseInitialized.current) {\n if (workStore.dynamicShouldError) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (workStore.dynamicShouldError) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n if (workStore.dynamicShouldError) {\n const expression =\n '`{...searchParams}`, `Object.keys(searchParams)`, or similar'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n return Reflect.ownKeys(target)\n },\n })\n}\n\nfunction instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams: SearchParams,\n promise: Promise,\n workStore: WorkStore\n) {\n // Track which properties we should warn for.\n const proxiedProperties = new Set()\n\n Object.keys(underlyingSearchParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' && workStore.dynamicShouldError) {\n const expression = '`searchParams.then`'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return Reflect.set(target, prop, value, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n const expression = '`Object.keys(searchParams)` or similar'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createSearchAccessError\n)\n\nfunction createSearchAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`searchParams\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction createClientSearchParamsInValidation(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: ValidationStoreClient\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples?.searchParams ?? {})\n )\n underlyingSearchParams = createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n return Promise.resolve(underlyingSearchParams)\n}\n"],"names":["createPrerenderSearchParamsForClientPage","createSearchParamsFromClient","createServerSearchParamsForMetadata","createServerSearchParamsForServerPage","makeErroringSearchParamsForUseCache","underlyingSearchParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","createStaticPrerenderSearchParams","functionName","validationSamples","createClientSearchParamsInValidation","makeUntrackedSearchParams","createRenderSearchParams","throwInvariantForMissingStore","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","varyParamsAccumulator","createRuntimePrerenderSearchParams","forceStatic","Promise","resolve","makeURLDataHangingPromise","renderSignal","route","prerenderStore","makeHangingSearchParams","makeErroringSearchParams","userspaceSearchParams","createVaryingSearchParams","searchParamsStage","RENDER_STAGES_BY_DATA_KIND","runtimeUrlData","stagedRendering","finalStage","delayUntilStage","requestStore","asyncApiPromises","createSearchParamsProxyForInstantValidation","createStagedRenderSearchParams","process","env","NODE_ENV","makeUntrackedSearchParamsWithDevWarnings","trigger","sharedSearchParamsParent","promise","reject","then","displayName","catch","ignoreReject","instrumentSearchParamsPromiseWithDevWarnings","makePromiseFromTrigger","createExhaustiveSearchParamsProxy","require","declaredKeys","Set","Object","keys","searchParams","CachedSearchParams","WeakMap","CachedSearchParamsForUseCache","cachedSearchParams","get","trackSearchParamsAccessed","trackURLDataAccessed","proxyHandler","target","prop","receiver","hasOwn","ReflectAdapter","originalMethod","args","expression","annotateDynamicAccess","abortOnDynamicAccess","Error","Proxy","apply","proxiedPromise","set","dynamicShouldError","throwWithStaticGenerationBailoutErrorWithDynamicError","throwToInterruptStaticGeneration","wellKnownProperties","has","throwForSearchParamsAccessInUseCache","makeUntrackedSearchParamsWithDevWarningsImpl","promiseInitialized","current","proxiedUnderlying","instrumentSearchParamsObjectWithDevWarnings","makeDevtoolsIOAwarePromise","describeStringPropertyAccess","describeHasCheckingStringProperty","Reflect","ownKeys","proxiedProperties","forEach","add","warnForSyncAccess","value","delete","createDedupedByCallsiteServerErrorLoggerDev","createSearchAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IA+JgBA,wCAAwC;eAAxCA;;IA/GAC,4BAA4B;eAA5BA;;IAoDAC,mCAAmC;eAAnCA;;IAUAC,qCAAqC;eAArCA;;IAoZAC,mCAAmC;eAAnCA;;;0CA/fT;4BAKA;yBAEwB;kCAIxB;mDAC8B;8CAW9B;gCACwB;uCAOxB;0DACqD;8BAKrD;uBAIA;AAIA,SAASH,6BACdI,sBAAoC;IAEpC,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,IAAIG,8BAAc,CAAC;IAC3B;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAOC,kCAAkCP,WAAWI;YACtD,KAAK;gBACH,MAAM,IAAID,8BAAc,CACtB;YAEJ,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,IAAIA,8BAAc,CACtB;YAEJ,KAAK;gBACH,MAAM,IAAIA,8BAAc,CACtB,CAAC,yDAAyD,EAAEC,cAAcI,YAAY,CAAC,CAAC,CAAC;YAE7F,KAAK;gBAAqB;oBACxB,IAAIJ,cAAcK,iBAAiB,EAAE;wBACnC,OAAOC,qCACLX,wBACAC,WACAI;oBAEJ;oBACA,OAAOO,0BAA0BZ;gBACnC;YACA,KAAK;gBACH,OAAOa,yBACLb,wBACAC,WACAI;YAEJ;gBACEA;QACJ;IACF;IACAS,IAAAA,2DAA6B;AAC/B;AAGO,SAASjB,oCACdG,sBAAoC;IAEpC,MAAMe,gCAAgCC,IAAAA,4CAAgC;IACtE,OAAOlB,sCACLE,wBACAe;AAEJ;AAEO,SAASjB,sCACdE,sBAAoC,EACpCiB,qBAAmD;IAEnD,MAAMhB,YAAYC,0CAAgB,CAACC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BAA/BL,iCAAiCuD,YAAY,KAAI,CAAC;IAEhE5D,yBAAyBsD,kCACvBtD,wBACAwD,cACAvD,UAAUuB,KAAK;IAEjB,OAAOJ,QAAQC,OAAO,CAACrB;AACzB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/utils.d.ts b/e-commerce/node_modules/next/dist/server/request/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f1a1f0ec2ab161bb62a3223a09200546be2ef0ee --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/utils.d.ts @@ -0,0 +1,5 @@ +import type { WorkStore } from '../app-render/work-async-storage.external'; +import type { WorkUnitStore } from '../app-render/work-unit-async-storage.external'; +export declare function throwWithStaticGenerationBailoutErrorWithDynamicError(route: string, expression: string): never; +export declare function throwForSearchParamsAccessInUseCache(workStore: WorkStore, constructorOpt: Function): never; +export declare function isRequestApiAllowedInCurrentPhase(workUnitStore: WorkUnitStore): boolean; diff --git a/e-commerce/node_modules/next/dist/server/request/utils.js b/e-commerce/node_modules/next/dist/server/request/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..bca9263ce22d2fd015aba5c0771af56d5e46ea3a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/utils.js @@ -0,0 +1,77 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + isRequestApiAllowedInCurrentPhase: null, + throwForSearchParamsAccessInUseCache: null, + throwWithStaticGenerationBailoutErrorWithDynamicError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + isRequestApiAllowedInCurrentPhase: function() { + return isRequestApiAllowedInCurrentPhase; + }, + throwForSearchParamsAccessInUseCache: function() { + return throwForSearchParamsAccessInUseCache; + }, + throwWithStaticGenerationBailoutErrorWithDynamicError: function() { + return throwWithStaticGenerationBailoutErrorWithDynamicError; + } +}); +const _staticgenerationbailout = require("../../client/components/static-generation-bailout"); +const _actionasyncstorageexternal = require("../app-render/action-async-storage.external"); +const _aftertaskasyncstorageexternal = require("../app-render/after-task-async-storage.external"); +const _usecachemessages = require("../use-cache/use-cache-messages"); +function throwWithStaticGenerationBailoutErrorWithDynamicError(route, expression) { + throw new _staticgenerationbailout.StaticGenBailoutError(`Route ${route} with \`dynamic = "error"\` couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`); +} +function throwForSearchParamsAccessInUseCache(workStore, constructorOpt) { + const error = (0, _usecachemessages.createSearchParamsInUseCacheError)(workStore.route); + Error.captureStackTrace(error, constructorOpt); + workStore.invalidDynamicUsageError ??= error; + throw error; +} +function isRequestApiAllowedInCurrentPhase(workUnitStore) { + switch(workUnitStore.phase){ + case 'action': + case 'render': + { + // The request is still in progress. The API may be disallowed for other reasons, + // but not because of phase. + return true; + } + case 'after': + { + // The request has finished. + // If we're in a Route Handler or a Server Action, + // request APIs can be called everywhere, even in after(). + const actionStore = _actionasyncstorageexternal.actionAsyncStorage.getStore(); + if (actionStore && (actionStore.isAppRoute || actionStore.isAction)) { + return true; + } + const afterTaskStore = _aftertaskasyncstorageexternal.afterTaskAsyncStorage.getStore(); + if (afterTaskStore) { + // We're in an `after` callback. Request APIs are callable if + // the `after()` call happened in an action phase: + // - in a Route Handler + // - in a Server Action's body (but not the render after) + // + // TODO(after): Is it even possible to have `phase === 'action'` but no `actionStore`? + // We should revisit this setup and simplify this. + return afterTaskStore.rootTaskSpawnPhase === 'action'; + } + // Otherwise, we must be in a page, in the `after` phase. + // We don't allow calling request APIs here because we'd miss + // them during prerendering and wouldn't know that the page is dynamic. + return false; + } + } +} + +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/request/utils.js.map b/e-commerce/node_modules/next/dist/server/request/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7c6b16d3ea8cfe97656d3e7a54db2f5a9157b85f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/request/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/request/utils.ts"],"sourcesContent":["import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external'\nimport { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external'\nimport type { WorkStore } from '../app-render/work-async-storage.external'\nimport { createSearchParamsInUseCacheError } from '../use-cache/use-cache-messages'\nimport type { WorkUnitStore } from '../app-render/work-unit-async-storage.external'\n\nexport function throwWithStaticGenerationBailoutErrorWithDynamicError(\n route: string,\n expression: string\n): never {\n throw new StaticGenBailoutError(\n `Route ${route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n}\n\nexport function throwForSearchParamsAccessInUseCache(\n workStore: WorkStore,\n constructorOpt: Function\n): never {\n const error = createSearchParamsInUseCacheError(workStore.route)\n\n Error.captureStackTrace(error, constructorOpt)\n workStore.invalidDynamicUsageError ??= error\n\n throw error\n}\n\nexport function isRequestApiAllowedInCurrentPhase(\n workUnitStore: WorkUnitStore\n): boolean {\n switch (workUnitStore.phase) {\n case 'action':\n case 'render': {\n // The request is still in progress. The API may be disallowed for other reasons,\n // but not because of phase.\n return true\n }\n case 'after': {\n // The request has finished.\n\n // If we're in a Route Handler or a Server Action,\n // request APIs can be called everywhere, even in after().\n const actionStore = actionAsyncStorage.getStore()\n if (actionStore && (actionStore.isAppRoute || actionStore.isAction)) {\n return true\n }\n\n const afterTaskStore = afterTaskAsyncStorage.getStore()\n if (afterTaskStore) {\n // We're in an `after` callback. Request APIs are callable if\n // the `after()` call happened in an action phase:\n // - in a Route Handler\n // - in a Server Action's body (but not the render after)\n //\n // TODO(after): Is it even possible to have `phase === 'action'` but no `actionStore`?\n // We should revisit this setup and simplify this.\n return afterTaskStore.rootTaskSpawnPhase === 'action'\n }\n\n // Otherwise, we must be in a page, in the `after` phase.\n // We don't allow calling request APIs here because we'd miss\n // them during prerendering and wouldn't know that the page is dynamic.\n return false\n }\n }\n}\n"],"names":["isRequestApiAllowedInCurrentPhase","throwForSearchParamsAccessInUseCache","throwWithStaticGenerationBailoutErrorWithDynamicError","route","expression","StaticGenBailoutError","workStore","constructorOpt","error","createSearchParamsInUseCacheError","Error","captureStackTrace","invalidDynamicUsageError","workUnitStore","phase","actionStore","actionAsyncStorage","getStore","isAppRoute","isAction","afterTaskStore","afterTaskAsyncStorage","rootTaskSpawnPhase"],"mappings":";;;;;;;;;;;;;;;;IA4BgBA,iCAAiC;eAAjCA;;IAZAC,oCAAoC;eAApCA;;IATAC,qDAAqD;eAArDA;;;yCAPsB;4CACH;+CACG;kCAEY;AAG3C,SAASA,sDACdC,KAAa,EACbC,UAAkB;IAElB,MAAM,IAAIC,8CAAqB,CAC7B,CAAC,MAAM,EAAEF,MAAM,4EAA4E,EAAEC,WAAW,0HAA0H,CAAC;AAEvO;AAEO,SAASH,qCACdK,SAAoB,EACpBC,cAAwB;IAExB,MAAMC,QAAQC,IAAAA,mDAAiC,EAACH,UAAUH,KAAK;IAE/DO,MAAMC,iBAAiB,CAACH,OAAOD;IAC/BD,UAAUM,wBAAwB,KAAKJ;IAEvC,MAAMA;AACR;AAEO,SAASR,kCACda,aAA4B;IAE5B,OAAQA,cAAcC,KAAK;QACzB,KAAK;QACL,KAAK;YAAU;gBACb,iFAAiF;gBACjF,4BAA4B;gBAC5B,OAAO;YACT;QACA,KAAK;YAAS;gBACZ,4BAA4B;gBAE5B,kDAAkD;gBAClD,0DAA0D;gBAC1D,MAAMC,cAAcC,8CAAkB,CAACC,QAAQ;gBAC/C,IAAIF,eAAgBA,CAAAA,YAAYG,UAAU,IAAIH,YAAYI,QAAQ,AAAD,GAAI;oBACnE,OAAO;gBACT;gBAEA,MAAMC,iBAAiBC,oDAAqB,CAACJ,QAAQ;gBACrD,IAAIG,gBAAgB;oBAClB,6DAA6D;oBAC7D,kDAAkD;oBAClD,uBAAuB;oBACvB,yDAAyD;oBACzD,EAAE;oBACF,sFAAsF;oBACtF,kDAAkD;oBAClD,OAAOA,eAAeE,kBAAkB,KAAK;gBAC/C;gBAEA,yDAAyD;gBACzD,6DAA6D;gBAC7D,uEAAuE;gBACvE,OAAO;YACT;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/require-hook.d.ts b/e-commerce/node_modules/next/dist/server/require-hook.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..291d7fbfb28235caff7e2960dbdeece1813db02c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/require-hook.d.ts @@ -0,0 +1,3 @@ +export declare const hookPropertyMap: Map; +export declare const defaultOverrides: Record; +export declare function addHookAliases(aliases?: [string, string][]): void; diff --git a/e-commerce/node_modules/next/dist/server/require-hook.js b/e-commerce/node_modules/next/dist/server/require-hook.js new file mode 100644 index 0000000000000000000000000000000000000000..5e0fee25a3deffd0f1ad8e2e4c0fb547f55bfd67 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/require-hook.js @@ -0,0 +1,82 @@ +// Synchronously inject a require hook for webpack and webpack/. It's required to use the internal ncc webpack version. +// This is needed for userland plugins to attach to the same webpack instance as Next.js'. +// Individually compiled modules are as defined for the compilation in bundles/webpack/packages/*. +// This module will only be loaded once per process. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + addHookAliases: null, + defaultOverrides: null, + hookPropertyMap: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + addHookAliases: function() { + return addHookAliases; + }, + defaultOverrides: function() { + return defaultOverrides; + }, + hookPropertyMap: function() { + return hookPropertyMap; + } +}); +const path = require('path'); +const mod = require('module'); +const originalRequire = mod.prototype.require; +const resolveFilename = // @ts-expect-error +mod._resolveFilename; +let resolve = process.env.NEXT_MINIMAL ? __non_webpack_require__.resolve : require.resolve; +const hookPropertyMap = new Map(); +const defaultOverrides = {}; +try { + Object.assign(defaultOverrides, { + 'styled-jsx': path.dirname(resolve('styled-jsx/package.json')), + 'styled-jsx/style': resolve('styled-jsx/style'), + 'styled-jsx/style.js': resolve('styled-jsx/style') + }); +} catch (_) {} +const toResolveMap = (map)=>{ + const resolveMap = []; + for (const [key, value] of Object.entries(map)){ + try { + resolveMap.push([ + key, + resolve(value) + ]); + } catch {} + } + return resolveMap; +}; +function addHookAliases(aliases = []) { + for (const [key, value] of aliases){ + hookPropertyMap.set(key, value); + } +} +addHookAliases(toResolveMap(defaultOverrides)); +// @ts-expect-error +mod._resolveFilename = (function(originalResolveFilename, requestMap, request, parent, isMain, options) { + const hookResolved = requestMap.get(request); + if (hookResolved) request = hookResolved; + return originalResolveFilename.call(mod, request, parent, isMain, options); +// We use `bind` here to avoid referencing outside variables to create potential memory leaks. +}).bind(null, resolveFilename, hookPropertyMap); +// @ts-expect-error +// This is a hack to make sure that if a user requires a Next.js module that wasn't bundled +// that needs to point to the rendering runtime version, it will point to the correct one. +// This can happen on `pages` when a user requires a dependency that uses next/image for example. +mod.prototype.require = function(request) { + if (request.endsWith('.shared-runtime')) { + return originalRequire.call(this, `next/dist/server/route-modules/pages/vendored/contexts/${path.basename(request, '.shared-runtime')}`); + } + return originalRequire.call(this, request); +}; + +//# sourceMappingURL=require-hook.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/require-hook.js.map b/e-commerce/node_modules/next/dist/server/require-hook.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9dd7dd4e6772a04311de72a0e021c67071d52742 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/require-hook.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/require-hook.ts"],"sourcesContent":["// Synchronously inject a require hook for webpack and webpack/. It's required to use the internal ncc webpack version.\n// This is needed for userland plugins to attach to the same webpack instance as Next.js'.\n// Individually compiled modules are as defined for the compilation in bundles/webpack/packages/*.\n\n// This module will only be loaded once per process.\nconst path = require('path') as typeof import('path')\nconst mod = require('module') as typeof import('module')\nconst originalRequire = mod.prototype.require\nconst resolveFilename =\n // @ts-expect-error\n mod._resolveFilename\n\nlet resolve: typeof require.resolve = process.env.NEXT_MINIMAL\n ? // @ts-ignore\n __non_webpack_require__.resolve\n : require.resolve\n\nexport const hookPropertyMap = new Map()\n\nexport const defaultOverrides: Record = {}\n\ntry {\n Object.assign(defaultOverrides, {\n 'styled-jsx': path.dirname(resolve('styled-jsx/package.json')),\n 'styled-jsx/style': resolve('styled-jsx/style'),\n 'styled-jsx/style.js': resolve('styled-jsx/style'),\n })\n} catch (_) {}\n\nconst toResolveMap = (map: Record): [string, string][] => {\n const resolveMap: [string, string][] = []\n for (const [key, value] of Object.entries(map)) {\n try {\n resolveMap.push([key, resolve(value)])\n } catch {}\n }\n return resolveMap\n}\n\nexport function addHookAliases(aliases: [string, string][] = []) {\n for (const [key, value] of aliases) {\n hookPropertyMap.set(key, value)\n }\n}\n\naddHookAliases(toResolveMap(defaultOverrides))\n\n// @ts-expect-error\nmod._resolveFilename = function (\n originalResolveFilename: (\n request: string,\n parent: string,\n isMain: boolean,\n opts: any\n ) => string,\n requestMap: Map,\n request: string,\n parent: string,\n isMain: boolean,\n options: any\n) {\n const hookResolved = requestMap.get(request)\n if (hookResolved) request = hookResolved\n\n return originalResolveFilename.call(mod, request, parent, isMain, options)\n\n // We use `bind` here to avoid referencing outside variables to create potential memory leaks.\n}.bind(null, resolveFilename, hookPropertyMap)\n\n// @ts-expect-error\n// This is a hack to make sure that if a user requires a Next.js module that wasn't bundled\n// that needs to point to the rendering runtime version, it will point to the correct one.\n// This can happen on `pages` when a user requires a dependency that uses next/image for example.\nmod.prototype.require = function (request: string) {\n if (request.endsWith('.shared-runtime')) {\n return originalRequire.call(\n this,\n `next/dist/server/route-modules/pages/vendored/contexts/${path.basename(\n request,\n '.shared-runtime'\n )}`\n )\n }\n\n return originalRequire.call(this, request)\n}\n"],"names":["addHookAliases","defaultOverrides","hookPropertyMap","path","require","mod","originalRequire","prototype","resolveFilename","_resolveFilename","resolve","process","env","NEXT_MINIMAL","__non_webpack_require__","Map","Object","assign","dirname","_","toResolveMap","map","resolveMap","key","value","entries","push","aliases","set","originalResolveFilename","requestMap","request","parent","isMain","options","hookResolved","get","call","bind","endsWith","basename"],"mappings":"AAAA,uHAAuH;AACvH,0FAA0F;AAC1F,kGAAkG;AAElG,oDAAoD;;;;;;;;;;;;;;;;;IAmCpCA,cAAc;eAAdA;;IApBHC,gBAAgB;eAAhBA;;IAFAC,eAAe;eAAfA;;;AAZb,MAAMC,OAAOC,QAAQ;AACrB,MAAMC,MAAMD,QAAQ;AACpB,MAAME,kBAAkBD,IAAIE,SAAS,CAACH,OAAO;AAC7C,MAAMI,kBACJ,mBAAmB;AACnBH,IAAII,gBAAgB;AAEtB,IAAIC,UAAkCC,QAAQC,GAAG,CAACC,YAAY,GAE1DC,wBAAwBJ,OAAO,GAC/BN,QAAQM,OAAO;AAEZ,MAAMR,kBAAkB,IAAIa;AAE5B,MAAMd,mBAA2C,CAAC;AAEzD,IAAI;IACFe,OAAOC,MAAM,CAAChB,kBAAkB;QAC9B,cAAcE,KAAKe,OAAO,CAACR,QAAQ;QACnC,oBAAoBA,QAAQ;QAC5B,uBAAuBA,QAAQ;IACjC;AACF,EAAE,OAAOS,GAAG,CAAC;AAEb,MAAMC,eAAe,CAACC;IACpB,MAAMC,aAAiC,EAAE;IACzC,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIR,OAAOS,OAAO,CAACJ,KAAM;QAC9C,IAAI;YACFC,WAAWI,IAAI,CAAC;gBAACH;gBAAKb,QAAQc;aAAO;QACvC,EAAE,OAAM,CAAC;IACX;IACA,OAAOF;AACT;AAEO,SAAStB,eAAe2B,UAA8B,EAAE;IAC7D,KAAK,MAAM,CAACJ,KAAKC,MAAM,IAAIG,QAAS;QAClCzB,gBAAgB0B,GAAG,CAACL,KAAKC;IAC3B;AACF;AAEAxB,eAAeoB,aAAanB;AAE5B,mBAAmB;AACnBI,IAAII,gBAAgB,GAAG,CAAA,SACrBoB,uBAKW,EACXC,UAA+B,EAC/BC,OAAe,EACfC,MAAc,EACdC,MAAe,EACfC,OAAY;IAEZ,MAAMC,eAAeL,WAAWM,GAAG,CAACL;IACpC,IAAII,cAAcJ,UAAUI;IAE5B,OAAON,wBAAwBQ,IAAI,CAAChC,KAAK0B,SAASC,QAAQC,QAAQC;AAElE,8FAA8F;AAChG,CAAA,EAAEI,IAAI,CAAC,MAAM9B,iBAAiBN;AAE9B,mBAAmB;AACnB,2FAA2F;AAC3F,0FAA0F;AAC1F,iGAAiG;AACjGG,IAAIE,SAAS,CAACH,OAAO,GAAG,SAAU2B,OAAe;IAC/C,IAAIA,QAAQQ,QAAQ,CAAC,oBAAoB;QACvC,OAAOjC,gBAAgB+B,IAAI,CACzB,IAAI,EACJ,CAAC,uDAAuD,EAAElC,KAAKqC,QAAQ,CACrET,SACA,oBACC;IAEP;IAEA,OAAOzB,gBAAgB+B,IAAI,CAAC,IAAI,EAAEN;AACpC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/require.d.ts b/e-commerce/node_modules/next/dist/server/require.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bf9cf27cd04bd6f5a93d88e0497364f6d338706 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/require.d.ts @@ -0,0 +1,3 @@ +export declare function getMaybePagePath(page: string, distDir: string, locales: readonly string[] | undefined, isAppPath: boolean): string | null; +export declare function getPagePath(page: string, distDir: string, locales: string[] | undefined, isAppPath: boolean): string; +export declare function requirePage(page: string, distDir: string, isAppPath: boolean): Promise; diff --git a/e-commerce/node_modules/next/dist/server/require.js b/e-commerce/node_modules/next/dist/server/require.js new file mode 100644 index 0000000000000000000000000000000000000000..6f4904abc77c9166514259483015c6fd25dd5046 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/require.js @@ -0,0 +1,109 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getMaybePagePath: null, + getPagePath: null, + requirePage: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getMaybePagePath: function() { + return getMaybePagePath; + }, + getPagePath: function() { + return getPagePath; + }, + requirePage: function() { + return requirePage; + } +}); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _constants = require("../shared/lib/constants"); +const _normalizelocalepath = require("../shared/lib/i18n/normalize-locale-path"); +const _normalizepagepath = require("../shared/lib/page-path/normalize-page-path"); +const _denormalizepagepath = require("../shared/lib/page-path/denormalize-page-path"); +const _utils = require("../shared/lib/utils"); +const _lrucache = require("../server/lib/lru-cache"); +const _loadmanifestexternal = require("./load-manifest.external"); +const _fs = require("fs"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +const isDev = process.env.NODE_ENV === 'development'; +const pagePathCache = !isDev ? new _lrucache.LRUCache(1000) : null; +function getMaybePagePath(page, distDir, locales, isAppPath) { + const cacheKey = `${page}:${distDir}:${locales}:${isAppPath}`; + let pagePath = pagePathCache == null ? void 0 : pagePathCache.get(cacheKey); + // If we have a cached path, we can return it directly. + if (pagePath) return pagePath; + const serverBuildPath = _path.default.join(/* turbopackIgnore: true */ distDir, _constants.SERVER_DIRECTORY); + let appPathsManifest; + if (isAppPath) { + appPathsManifest = (0, _loadmanifestexternal.loadManifest)(_path.default.join(/* turbopackIgnore: true */ serverBuildPath, _constants.APP_PATHS_MANIFEST), !isDev); + } + const pagesManifest = (0, _loadmanifestexternal.loadManifest)(_path.default.join(/* turbopackIgnore: true */ serverBuildPath, _constants.PAGES_MANIFEST), !isDev); + try { + page = (0, _denormalizepagepath.denormalizePagePath)((0, _normalizepagepath.normalizePagePath)(page)); + } catch (err) { + console.error(err); + throw new _utils.PageNotFoundError(page); + } + const checkManifest = (manifest)=>{ + let curPath = manifest[page]; + if (!manifest[curPath] && locales) { + const manifestNoLocales = {}; + for (const key of Object.keys(manifest)){ + manifestNoLocales[(0, _normalizelocalepath.normalizeLocalePath)(key, locales).pathname] = pagesManifest[key]; + } + curPath = manifestNoLocales[page]; + } + return curPath; + }; + if (appPathsManifest) { + pagePath = checkManifest(appPathsManifest); + } + if (!pagePath) { + pagePath = checkManifest(pagesManifest); + } + if (!pagePath) { + pagePathCache == null ? void 0 : pagePathCache.set(cacheKey, null); + return null; + } + // Handle absolute paths (e.g., built-in components) + if (_path.default.isAbsolute(pagePath)) { + // Use the absolute path as-is + pagePathCache == null ? void 0 : pagePathCache.set(cacheKey, pagePath); + return pagePath; + } + pagePath = _path.default.join(/* turbopackIgnore: true */ serverBuildPath, pagePath); + pagePathCache == null ? void 0 : pagePathCache.set(cacheKey, pagePath); + return pagePath; +} +function getPagePath(page, distDir, locales, isAppPath) { + const pagePath = getMaybePagePath(page, distDir, locales, isAppPath); + if (!pagePath) { + throw new _utils.PageNotFoundError(page); + } + return pagePath; +} +async function requirePage(page, distDir, isAppPath) { + const pagePath = getPagePath(page, distDir, undefined, isAppPath); + if (pagePath.endsWith('.html')) { + return _fs.promises.readFile(/* turbopackIgnore: true */ pagePath, 'utf8').catch((err)=>{ + throw new _utils.MissingStaticPage(page, err.message); + }); + } + const mod = process.env.NEXT_MINIMAL ? __non_webpack_require__(pagePath) : require(/* turbopackIgnore: true */ pagePath); + return mod; +} + +//# sourceMappingURL=require.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/require.js.map b/e-commerce/node_modules/next/dist/server/require.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3815cd2982de7de2e554287e29631682d1986198 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/require.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/require.ts"],"sourcesContent":["import path from 'path'\nimport {\n PAGES_MANIFEST,\n SERVER_DIRECTORY,\n APP_PATHS_MANIFEST,\n} from '../shared/lib/constants'\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'\nimport type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'\nimport { PageNotFoundError, MissingStaticPage } from '../shared/lib/utils'\nimport { LRUCache } from '../server/lib/lru-cache'\nimport { loadManifest } from './load-manifest.external'\nimport { promises } from 'fs'\n\nconst isDev = process.env.NODE_ENV === 'development'\nconst pagePathCache = !isDev ? new LRUCache(1000) : null\n\nexport function getMaybePagePath(\n page: string,\n distDir: string,\n locales: readonly string[] | undefined,\n isAppPath: boolean\n): string | null {\n const cacheKey = `${page}:${distDir}:${locales}:${isAppPath}`\n\n let pagePath = pagePathCache?.get(cacheKey)\n\n // If we have a cached path, we can return it directly.\n if (pagePath) return pagePath\n\n const serverBuildPath = path.join(\n /* turbopackIgnore: true */ distDir,\n SERVER_DIRECTORY\n )\n let appPathsManifest: undefined | PagesManifest\n\n if (isAppPath) {\n appPathsManifest = loadManifest(\n path.join(\n /* turbopackIgnore: true */ serverBuildPath,\n APP_PATHS_MANIFEST\n ),\n !isDev\n ) as PagesManifest\n }\n const pagesManifest = loadManifest(\n path.join(/* turbopackIgnore: true */ serverBuildPath, PAGES_MANIFEST),\n !isDev\n ) as PagesManifest\n\n try {\n page = denormalizePagePath(normalizePagePath(page))\n } catch (err) {\n console.error(err)\n throw new PageNotFoundError(page)\n }\n\n const checkManifest = (manifest: PagesManifest) => {\n let curPath = manifest[page]\n\n if (!manifest[curPath] && locales) {\n const manifestNoLocales: typeof pagesManifest = {}\n\n for (const key of Object.keys(manifest)) {\n manifestNoLocales[normalizeLocalePath(key, locales).pathname] =\n pagesManifest[key]\n }\n curPath = manifestNoLocales[page]\n }\n return curPath\n }\n\n if (appPathsManifest) {\n pagePath = checkManifest(appPathsManifest)\n }\n\n if (!pagePath) {\n pagePath = checkManifest(pagesManifest)\n }\n\n if (!pagePath) {\n pagePathCache?.set(cacheKey, null)\n return null\n }\n\n // Handle absolute paths (e.g., built-in components)\n if (path.isAbsolute(pagePath)) {\n // Use the absolute path as-is\n pagePathCache?.set(cacheKey, pagePath)\n return pagePath\n }\n\n pagePath = path.join(/* turbopackIgnore: true */ serverBuildPath, pagePath)\n\n pagePathCache?.set(cacheKey, pagePath)\n return pagePath\n}\n\nexport function getPagePath(\n page: string,\n distDir: string,\n locales: string[] | undefined,\n isAppPath: boolean\n): string {\n const pagePath = getMaybePagePath(page, distDir, locales, isAppPath)\n\n if (!pagePath) {\n throw new PageNotFoundError(page)\n }\n\n return pagePath\n}\n\nexport async function requirePage(\n page: string,\n distDir: string,\n isAppPath: boolean\n): Promise {\n const pagePath = getPagePath(page, distDir, undefined, isAppPath)\n if (pagePath.endsWith('.html')) {\n return promises\n .readFile(/* turbopackIgnore: true */ pagePath, 'utf8')\n .catch((err) => {\n throw new MissingStaticPage(page, err.message)\n })\n }\n\n const mod = process.env.NEXT_MINIMAL\n ? // @ts-ignore\n __non_webpack_require__(pagePath)\n : require(/* turbopackIgnore: true */ pagePath)\n return mod\n}\n"],"names":["getMaybePagePath","getPagePath","requirePage","isDev","process","env","NODE_ENV","pagePathCache","LRUCache","page","distDir","locales","isAppPath","cacheKey","pagePath","get","serverBuildPath","path","join","SERVER_DIRECTORY","appPathsManifest","loadManifest","APP_PATHS_MANIFEST","pagesManifest","PAGES_MANIFEST","denormalizePagePath","normalizePagePath","err","console","error","PageNotFoundError","checkManifest","manifest","curPath","manifestNoLocales","key","Object","keys","normalizeLocalePath","pathname","set","isAbsolute","undefined","endsWith","promises","readFile","catch","MissingStaticPage","message","mod","NEXT_MINIMAL","__non_webpack_require__","require"],"mappings":";;;;;;;;;;;;;;;;IAkBgBA,gBAAgB;eAAhBA;;IAiFAC,WAAW;eAAXA;;IAeMC,WAAW;eAAXA;;;6DAlHL;2BAKV;qCAC6B;mCACF;qCACE;uBAEiB;0BAC5B;sCACI;oBACJ;;;;;;AAEzB,MAAMC,QAAQC,QAAQC,GAAG,CAACC,QAA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B;QACpBN,WAAWiB,cAAcX;IAC3B;IAEA,IAAI,CAACN,UAAU;QACbA,WAAWiB,cAAcR;IAC3B;IAEA,IAAI,CAACT,UAAU;QACbP,iCAAAA,cAAeiC,GAAG,CAAC3B,UAAU;QAC7B,OAAO;IACT;IAEA,oDAAoD;IACpD,IAAII,aAAI,CAACwB,UAAU,CAAC3B,WAAW;QAC7B,8BAA8B;QAC9BP,iCAAAA,cAAeiC,GAAG,CAAC3B,UAAUC;QAC7B,OAAOA;IACT;IAEAA,WAAWG,aAAI,CAACC,IAAI,CAAC,yBAAyB,GAAGF,iBAAiBF;IAElEP,iCAAAA,cAAeiC,GAAG,CAAC3B,UAAUC;IAC7B,OAAOA;AACT;AAEO,SAASb,YACdQ,IAAY,EACZC,OAAe,EACfC,OAA6B,EAC7BC,SAAkB;IAElB,MAAME,WAAWd,iBAAiBS,MAAMC,SAASC,SAASC;IAE1D,IAAI,CAACE,UAAU;QACb,MAAM,IAAIgB,wBAAiB,CAACrB;IAC9B;IAEA,OAAOK;AACT;AAEO,eAAeZ,YACpBO,IAAY,EACZC,OAAe,EACfE,SAAkB;IAElB,MAAME,WAAWb,YAAYQ,MAAMC,SAASgC,WAAW9B;IACvD,IAAIE,SAAS6B,QAAQ,CAAC,UAAU;QAC9B,OAAOC,YAAQ,CACZC,QAAQ,CAAC,yBAAyB,GAAG/B,UAAU,QAC/CgC,KAAK,CAAC,CAACnB;YACN,MAAM,IAAIoB,wBAAiB,CAACtC,MAAMkB,IAAIqB,OAAO;QAC/C;IACJ;IAEA,MAAMC,MAAM7C,QAAQC,GAAG,CAAC6C,YAAY,GAEhCC,wBAAwBrC,YACxBsC,QAAQ,yBAAyB,GAAGtC;IACxC,OAAOmC;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/response-cache/index.d.ts b/e-commerce/node_modules/next/dist/server/response-cache/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab65450a4ea3e1f685305aab9d0d96794367a871 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/index.d.ts @@ -0,0 +1,89 @@ +import type { ResponseCacheOwner } from '../lib/route-cache-key'; +import type { ResponseCacheResult, ResponseGenerator, ResponseCacheBase, IncrementalResponseCacheEntry, IncrementalResponseCache } from './types'; +import type { RouteKind } from '../route-kind'; +import type { PrerenderFailure } from '../render-result'; +type IncrementalResponseCacheResult = IncrementalResponseCacheEntry | PrerenderFailure | null; +export * from './types'; +export default class ResponseCache implements ResponseCacheBase { + private readonly getBatcher; + private readonly revalidateBatcher; + /** + * LRU cache for minimal mode using compound keys (pathname + invocationID). + * This allows multiple invocations to cache the same pathname without + * overwriting each other's entries. + */ + private readonly cache; + /** + * Set of invocation IDs that have had cache entries evicted. + * Used to detect when the cache size may be too small. + * Bounded to prevent memory growth. + */ + private readonly evictedInvocationIDs; + /** + * The configured max size, stored for logging. + */ + private readonly maxSize; + /** + * The configured TTL for cache entries in milliseconds. + */ + private readonly ttl; + private minimal_mode?; + private readonly route; + constructor({ minimalMode, route, maxSize, ttl, }: { + minimalMode: boolean; + route: ResponseCacheOwner | 'image'; + maxSize?: number; + ttl?: number; + }); + /** + * Gets the response cache entry for the given key. + * + * @param key - The key to get the response cache entry for. + * @param responseGenerator - The response generator to use to generate the response cache entry. + * @param context - The context for the get request. + * @returns The response cache entry. + */ + get(key: string | null, responseGenerator: ResponseGenerator, context: { + routeKind: RouteKind; + isOnDemandRevalidate?: boolean; + isPrefetch?: boolean; + incrementalCache: IncrementalResponseCache; + isRoutePPREnabled?: boolean; + isFallback?: boolean; + waitUntil?: (prom: Promise) => void; + /** + * The invocation ID from the infrastructure. Used to scope the in-memory + * cache to a single revalidation request in minimal mode. Concurrent + * invocations can still share a pending render through the batchers. + */ + invocationID?: string; + }): Promise; + /** + * Handles the get request for the response cache. + * + * @param key - The key to get the response cache entry for. + * @param responseGenerator - The response generator to use to generate the response cache entry. + * @param context - The context for the get request. + * @param resolve - The resolve function to use to resolve the response cache entry. + * @returns The response cache entry. + */ + private handleGet; + /** + * Revalidates the cache entry for the given key. + * + * @param key - The key to revalidate the cache entry for. + * @param incrementalCache - The incremental cache to use to revalidate the cache entry. + * @param isRoutePPREnabled - Whether the route is PPR enabled. + * @param isFallback - Whether the route is a fallback. + * @param responseGenerator - The response generator to use to generate the response cache entry. + * @param previousIncrementalCacheEntry - The previous cache entry to use to revalidate the cache entry. + * @param hasResolved - Whether the response has been resolved. + * @param waitUntil - Optional function to register background work. + * @param invocationID - The invocation ID for cache key scoping. + * @returns The revalidated cache entry. + */ + revalidate(key: string, incrementalCache: IncrementalResponseCache, isRoutePPREnabled: boolean, isFallback: boolean, responseGenerator: ResponseGenerator, previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null, hasResolved: boolean, waitUntil?: (prom: Promise) => void): Promise; + private handleRevalidate; + private retainPreviousCacheEntry; + private getCacheContext; +} diff --git a/e-commerce/node_modules/next/dist/server/response-cache/index.js b/e-commerce/node_modules/next/dist/server/response-cache/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c8008b7fbb187cb0c1d56a9637362944497ea9f6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/index.js @@ -0,0 +1,361 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return ResponseCache; + } +}); +0 && __export(require("./types")); +const _types = _export_star(require("./types"), exports); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _batcher = require("../../lib/batcher"); +const _lrucache = require("../lib/lru-cache"); +const _log = require("../../build/output/log"); +const _scheduler = require("../../lib/scheduler"); +const _utils = require("./utils"); +function _export_star(from, to) { + Object.keys(from).forEach(function(k) { + if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { + Object.defineProperty(to, k, { + enumerable: true, + get: function() { + return from[k]; + } + }); + } + }); + return from; +} +/** + * Parses an environment variable as a positive integer, returning the fallback + * if the value is missing, not a number, or not positive. + */ function parsePositiveInt(envValue, fallback) { + if (!envValue) return fallback; + const parsed = parseInt(envValue, 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; +} +/** + * Default TTL (in milliseconds) for minimal mode response cache entries. + * Used for cache hit validation as a fallback for providers that don't + * send the x-invocation-id header yet. + * + * 10 seconds chosen because: + * - Long enough to dedupe rapid successive requests (e.g., page + data) + * - Short enough to not serve stale data across unrelated requests + * + * Can be configured via `NEXT_PRIVATE_RESPONSE_CACHE_TTL` environment variable. + */ const DEFAULT_TTL_MS = parsePositiveInt(process.env.NEXT_PRIVATE_RESPONSE_CACHE_TTL, 10000); +/** + * Default maximum number of entries in the response cache. + * Can be configured via `NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE` environment variable. + */ const DEFAULT_MAX_SIZE = parsePositiveInt(process.env.NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE, 150); +/** + * Separator used in compound cache keys to join pathname and invocationID. + * Using null byte (\0) since it cannot appear in valid URL paths or UUIDs. + */ const KEY_SEPARATOR = '\0'; +/** + * Sentinel value used for TTL-based cache entries (when invocationID is undefined). + * Chosen to be a clearly reserved marker for internal cache keys. + */ const TTL_SENTINEL = '__ttl_sentinel__'; +/** + * Creates a compound cache key from pathname and invocationID. + */ function createCacheKey(pathname, invocationID) { + return `${pathname}${KEY_SEPARATOR}${invocationID ?? TTL_SENTINEL}`; +} +/** + * Extracts the invocationID from a compound cache key. + * Returns undefined if the key used TTL_SENTINEL. + */ function extractInvocationID(compoundKey) { + const separatorIndex = compoundKey.lastIndexOf(KEY_SEPARATOR); + if (separatorIndex === -1) return undefined; + const invocationID = compoundKey.slice(separatorIndex + 1); + return invocationID === TTL_SENTINEL ? undefined : invocationID; +} +class ResponseCache { + constructor({ minimalMode, route, maxSize = DEFAULT_MAX_SIZE, ttl = DEFAULT_TTL_MS }){ + // The get and revalidate batchers share pending renders across invocation + // IDs, including failures. Invocation IDs scope reuse of completed results in + // the LRU below. + this.getBatcher = _batcher.Batcher.create({ + // Ensure on-demand revalidate doesn't block normal requests, it should be + // safe to run an on-demand revalidate for the same key as a normal request. + cacheKeyFn: ({ key, isOnDemandRevalidate })=>`${key}-${isOnDemandRevalidate ? '1' : '0'}`, + // We wait to do any async work until after we've added our promise to + // `pendingResponses` to ensure that any any other calls will reuse the + // same promise until we've fully finished our work. + schedulerFn: _scheduler.scheduleOnNextTick + }); + this.revalidateBatcher = _batcher.Batcher.create({ + // We wait to do any async work until after we've added our promise to + // `pendingResponses` to ensure that any any other calls will reuse the + // same promise until we've fully finished our work. + schedulerFn: _scheduler.scheduleOnNextTick + }); + /** + * Set of invocation IDs that have had cache entries evicted. + * Used to detect when the cache size may be too small. + * Bounded to prevent memory growth. + */ this.evictedInvocationIDs = new Set(); + if (!route) { + throw new _invarianterror.InvariantError('Response cache requires a source route'); + } + this.route = route; + this.minimal_mode = minimalMode; + this.maxSize = maxSize; + this.ttl = ttl; + // Create the LRU cache with eviction tracking + this.cache = new _lrucache.LRUCache(maxSize, undefined, (compoundKey)=>{ + const invocationID = extractInvocationID(compoundKey); + if (invocationID) { + // Bound to 100 entries to prevent unbounded memory growth. + // FIFO eviction is acceptable here because: + // 1. Invocations are short-lived (single request lifecycle), so older + // invocations are unlikely to still be active after 100 newer ones + // 2. This warning mechanism is best-effort for developer guidance— + // missing occasional eviction warnings doesn't affect correctness + // 3. If a long-running invocation is somehow evicted and then has + // another cache entry evicted, it will simply be re-added + if (this.evictedInvocationIDs.size >= 100) { + const first = this.evictedInvocationIDs.values().next().value; + if (first) this.evictedInvocationIDs.delete(first); + } + this.evictedInvocationIDs.add(invocationID); + } + }); + } + /** + * Gets the response cache entry for the given key. + * + * @param key - The key to get the response cache entry for. + * @param responseGenerator - The response generator to use to generate the response cache entry. + * @param context - The context for the get request. + * @returns The response cache entry. + */ async get(key, responseGenerator, context) { + // If there is no key for the cache, we can't possibly look this up in the + // cache so just return the result of the response generator. + if (!key) { + return responseGenerator({ + hasResolved: false, + previousCacheEntry: null + }); + } + // Check minimal mode cache before doing any other work. + if (this.minimal_mode) { + const cacheKey = createCacheKey(key, context.invocationID); + const cachedItem = this.cache.get(cacheKey); + if (cachedItem) { + // With invocationID: exact match found - always a hit + // With TTL mode: must check expiration + if (context.invocationID !== undefined) { + return cachedItem.entry !== null && 'error' in cachedItem.entry ? cachedItem.entry : (0, _utils.toResponseCacheEntry)(cachedItem.entry); + } + // TTL entries can be reused by unrelated requests. Exclude failures so + // those requests can retry instead of receiving a cached error. + const now = Date.now(); + if ((cachedItem.entry === null || !('error' in cachedItem.entry)) && cachedItem.expiresAt > now) { + return (0, _utils.toResponseCacheEntry)(cachedItem.entry); + } + // TTL expired - clean up + this.cache.remove(cacheKey); + } + // Warn if this invocation had entries evicted - indicates cache may be too small. + if (context.invocationID && this.evictedInvocationIDs.has(context.invocationID)) { + (0, _log.warnOnce)(`Response cache entry was evicted for invocation ${context.invocationID}. ` + `Consider increasing NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE (current: ${this.maxSize}).`); + } + } + const { incrementalCache, isOnDemandRevalidate = false, isFallback = false, isRoutePPREnabled = false, isPrefetch = false, waitUntil, invocationID } = context; + const response = await this.getBatcher.batch({ + key, + isOnDemandRevalidate + }, ({ resolve })=>{ + const promise = this.handleGet(key, responseGenerator, { + incrementalCache, + isOnDemandRevalidate, + isFallback, + isRoutePPREnabled, + isPrefetch, + invocationID + }, resolve); + // We need to ensure background revalidates are passed to waitUntil. + if (waitUntil) waitUntil(promise); + return promise; + }); + // In minimal mode, each caller with an invocation ID stores the shared + // failure under its own ID for reuse by related requests. Callers without + // an invocation ID receive the failure but do not store it in the LRU. + if (this.minimal_mode && response && ('error' in response ? invocationID !== undefined : response.cacheControl)) { + const cacheKey = createCacheKey(key, invocationID); + this.cache.set(cacheKey, { + entry: response, + expiresAt: Date.now() + this.ttl + }); + } + return response !== null && 'error' in response ? response : (0, _utils.toResponseCacheEntry)(response); + } + /** + * Handles the get request for the response cache. + * + * @param key - The key to get the response cache entry for. + * @param responseGenerator - The response generator to use to generate the response cache entry. + * @param context - The context for the get request. + * @param resolve - The resolve function to use to resolve the response cache entry. + * @returns The response cache entry. + */ async handleGet(key, responseGenerator, context, resolve) { + let previousIncrementalCacheEntry = null; + let resolved = false; + try { + // Get the previous cache entry if not in minimal mode + previousIncrementalCacheEntry = !this.minimal_mode ? await context.incrementalCache.get(key, this.getCacheContext(context.isRoutePPREnabled, context.isFallback)) : null; + // `isStale === -1` signals that the entry is past its `expire` (either + // via an expired tag or, with `cacheLife({ expire })`, past the route's + // expire time in the prerender manifest). In that case we must NOT + // early-resolve with the stale value — instead we fall through to a + // blocking revalidation so the response returned to the user is fresh. + if (previousIncrementalCacheEntry && !context.isOnDemandRevalidate && previousIncrementalCacheEntry.isStale !== -1) { + resolve(previousIncrementalCacheEntry); + resolved = true; + if (!previousIncrementalCacheEntry.isStale || context.isPrefetch) { + // The cached value is still valid, so we don't need to update it yet. + return previousIncrementalCacheEntry; + } + } + // Revalidate the cache entry. + // + // A prefetch request that missed must run its own response generator + // rather than joining an in-flight revalidation through the batcher. A + // background revalidation may be regenerating the concrete (non-fallback) + // entry for this route — e.g. an ISR fallback-shell upgrade scheduled by + // an earlier prefetch sub-request. Joining it would serve that concrete + // result to the prefetch instead of the fallback shell, and which segment + // wins would depend purely on request timing. Running the generator + // directly lets every prefetch segment take the same fallback-shell path, + // independent of any concurrent background upgrade. + const incrementalResponseCacheEntry = context.isPrefetch && previousIncrementalCacheEntry === null ? await this.handleRevalidate(key, context.incrementalCache, context.isRoutePPREnabled, context.isFallback, responseGenerator, previousIncrementalCacheEntry, resolved) : await this.revalidate(key, context.incrementalCache, context.isRoutePPREnabled, context.isFallback, responseGenerator, previousIncrementalCacheEntry, resolved); + if (incrementalResponseCacheEntry !== null && 'error' in incrementalResponseCacheEntry && resolved) { + // The caller already received the stale entry. Report the background + // failure here, as the catch below does for a thrown error. + console.error(incrementalResponseCacheEntry.error); + return null; + } + // Handle null response + if (!incrementalResponseCacheEntry) { + // Remove the cache item if it was set so we don't use it again. + if (this.minimal_mode) { + const cacheKey = createCacheKey(key, context.invocationID); + this.cache.remove(cacheKey); + } + return null; + } + // Resolve for on-demand revalidation or if not already resolved + if (context.isOnDemandRevalidate && !resolved) { + return incrementalResponseCacheEntry; + } + return incrementalResponseCacheEntry; + } catch (err) { + // If we've already resolved the cache entry, we can't reject as we + // already resolved the cache entry so log the error here. + if (resolved) { + console.error(err); + return null; + } + throw err; + } + } + /** + * Revalidates the cache entry for the given key. + * + * @param key - The key to revalidate the cache entry for. + * @param incrementalCache - The incremental cache to use to revalidate the cache entry. + * @param isRoutePPREnabled - Whether the route is PPR enabled. + * @param isFallback - Whether the route is a fallback. + * @param responseGenerator - The response generator to use to generate the response cache entry. + * @param previousIncrementalCacheEntry - The previous cache entry to use to revalidate the cache entry. + * @param hasResolved - Whether the response has been resolved. + * @param waitUntil - Optional function to register background work. + * @param invocationID - The invocation ID for cache key scoping. + * @returns The revalidated cache entry. + */ async revalidate(key, incrementalCache, isRoutePPREnabled, isFallback, responseGenerator, previousIncrementalCacheEntry, hasResolved, waitUntil) { + return this.revalidateBatcher.batch(key, ()=>{ + const promise = this.handleRevalidate(key, incrementalCache, isRoutePPREnabled, isFallback, responseGenerator, previousIncrementalCacheEntry, hasResolved); + // We need to ensure background revalidates are passed to waitUntil. + if (waitUntil) waitUntil(promise); + return promise; + }); + } + async handleRevalidate(key, incrementalCache, isRoutePPREnabled, isFallback, responseGenerator, previousIncrementalCacheEntry, hasResolved) { + let failure; + try { + // Generate the response cache entry using the response generator. + const responseCacheEntry = await responseGenerator({ + hasResolved, + previousCacheEntry: previousIncrementalCacheEntry, + isRevalidating: true + }); + if (!responseCacheEntry) { + return null; + } + if ('error' in responseCacheEntry) { + failure = responseCacheEntry; + } else { + // Convert the response cache entry to an incremental response cache entry. + const incrementalResponseCacheEntry = await (0, _utils.fromResponseCacheEntry)({ + ...responseCacheEntry, + isMiss: !previousIncrementalCacheEntry + }); + // We want to persist the result only if it has a cache control value + // defined. The minimal mode LRU write is handled in get() so that every + // caller, including batched invocations, populates the cache. + if (incrementalResponseCacheEntry.cacheControl && !this.minimal_mode) { + await incrementalCache.set(key, incrementalResponseCacheEntry.value, { + ...this.getCacheContext(isRoutePPREnabled, isFallback), + cacheControl: incrementalResponseCacheEntry.cacheControl + }); + } + return incrementalResponseCacheEntry; + } + } catch (err) { + await this.retainPreviousCacheEntry(key, incrementalCache, isRoutePPREnabled, isFallback, previousIncrementalCacheEntry); + throw err; + } + await this.retainPreviousCacheEntry(key, incrementalCache, isRoutePPREnabled, isFallback, previousIncrementalCacheEntry); + return failure; + } + // Retain the previous successful value and delay retries after revalidation + // fails. + async retainPreviousCacheEntry(key, incrementalCache, isRoutePPREnabled, isFallback, previousIncrementalCacheEntry) { + if (previousIncrementalCacheEntry == null ? void 0 : previousIncrementalCacheEntry.cacheControl) { + const revalidate = Math.min(Math.max(previousIncrementalCacheEntry.cacheControl.revalidate || 3, 3), 30); + const expire = previousIncrementalCacheEntry.cacheControl.expire === undefined ? undefined : Math.max(revalidate + 3, previousIncrementalCacheEntry.cacheControl.expire); + await incrementalCache.set(key, previousIncrementalCacheEntry.value, { + ...this.getCacheContext(isRoutePPREnabled, isFallback), + cacheControl: { + revalidate: revalidate, + expire: expire + } + }); + } + } + getCacheContext(isRoutePPREnabled, isFallback) { + if (this.route === 'image') { + return { + kind: _types.IncrementalCacheKind.IMAGE, + isFallback: false + }; + } + const kind = (0, _utils.routeKindToIncrementalCacheKind)(this.route.kind); + if (kind === _types.IncrementalCacheKind.IMAGE) { + throw new _invarianterror.InvariantError('Images must use the image response cache'); + } + return { + route: this.route, + kind, + isRoutePPREnabled, + isFallback + }; + } +} + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/response-cache/index.js.map b/e-commerce/node_modules/next/dist/server/response-cache/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c01f41260a144946d321a794891f7a4ef5b6e81e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/response-cache/index.ts"],"sourcesContent":["import type { ResponseCacheOwner } from '../lib/route-cache-key'\nimport type {\n ResponseCacheResult,\n ResponseGenerator,\n ResponseCacheBase,\n IncrementalResponseCacheEntry,\n IncrementalResponseCache,\n GetIncrementalResponseCacheContext,\n GetIncrementalImageCacheContext,\n} from './types'\nimport { IncrementalCacheKind } from './types'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nimport { Batcher } from '../../lib/batcher'\nimport { LRUCache } from '../lib/lru-cache'\nimport { warnOnce } from '../../build/output/log'\nimport { scheduleOnNextTick } from '../../lib/scheduler'\nimport {\n fromResponseCacheEntry,\n routeKindToIncrementalCacheKind,\n toResponseCacheEntry,\n} from './utils'\nimport type { RouteKind } from '../route-kind'\nimport type { PrerenderFailure } from '../render-result'\n\ntype IncrementalResponseCacheResult =\n | IncrementalResponseCacheEntry\n | PrerenderFailure\n | null\n\n/**\n * Parses an environment variable as a positive integer, returning the fallback\n * if the value is missing, not a number, or not positive.\n */\nfunction parsePositiveInt(\n envValue: string | undefined,\n fallback: number\n): number {\n if (!envValue) return fallback\n const parsed = parseInt(envValue, 10)\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback\n}\n\n/**\n * Default TTL (in milliseconds) for minimal mode response cache entries.\n * Used for cache hit validation as a fallback for providers that don't\n * send the x-invocation-id header yet.\n *\n * 10 seconds chosen because:\n * - Long enough to dedupe rapid successive requests (e.g., page + data)\n * - Short enough to not serve stale data across unrelated requests\n *\n * Can be configured via `NEXT_PRIVATE_RESPONSE_CACHE_TTL` environment variable.\n */\nconst DEFAULT_TTL_MS = parsePositiveInt(\n process.env.NEXT_PRIVATE_RESPONSE_CACHE_TTL,\n 10_000\n)\n\n/**\n * Default maximum number of entries in the response cache.\n * Can be configured via `NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE` environment variable.\n */\nconst DEFAULT_MAX_SIZE = parsePositiveInt(\n process.env.NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE,\n 150\n)\n\n/**\n * Separator used in compound cache keys to join pathname and invocationID.\n * Using null byte (\\0) since it cannot appear in valid URL paths or UUIDs.\n */\nconst KEY_SEPARATOR = '\\0'\n\n/**\n * Sentinel value used for TTL-based cache entries (when invocationID is undefined).\n * Chosen to be a clearly reserved marker for internal cache keys.\n */\nconst TTL_SENTINEL = '__ttl_sentinel__'\n\n/**\n * Entry stored in the LRU cache.\n */\ntype CacheEntry = {\n entry: IncrementalResponseCacheResult\n /**\n * TTL expiration timestamp in milliseconds. Used as a fallback for\n * cache hit validation when providers don't send x-invocation-id.\n * Memory pressure is managed by LRU eviction rather than timers.\n */\n expiresAt: number\n}\n\n/**\n * Creates a compound cache key from pathname and invocationID.\n */\nfunction createCacheKey(\n pathname: string,\n invocationID: string | undefined\n): string {\n return `${pathname}${KEY_SEPARATOR}${invocationID ?? TTL_SENTINEL}`\n}\n\n/**\n * Extracts the invocationID from a compound cache key.\n * Returns undefined if the key used TTL_SENTINEL.\n */\nfunction extractInvocationID(compoundKey: string): string | undefined {\n const separatorIndex = compoundKey.lastIndexOf(KEY_SEPARATOR)\n if (separatorIndex === -1) return undefined\n\n const invocationID = compoundKey.slice(separatorIndex + 1)\n return invocationID === TTL_SENTINEL ? undefined : invocationID\n}\n\nexport * from './types'\n\nexport default class ResponseCache implements ResponseCacheBase {\n // The get and revalidate batchers share pending renders across invocation\n // IDs, including failures. Invocation IDs scope reuse of completed results in\n // the LRU below.\n private readonly getBatcher = Batcher.create<\n { key: string; isOnDemandRevalidate: boolean },\n IncrementalResponseCacheResult,\n string\n >({\n // Ensure on-demand revalidate doesn't block normal requests, it should be\n // safe to run an on-demand revalidate for the same key as a normal request.\n cacheKeyFn: ({ key, isOnDemandRevalidate }) =>\n `${key}-${isOnDemandRevalidate ? '1' : '0'}`,\n // We wait to do any async work until after we've added our promise to\n // `pendingResponses` to ensure that any any other calls will reuse the\n // same promise until we've fully finished our work.\n schedulerFn: scheduleOnNextTick,\n })\n\n private readonly revalidateBatcher = Batcher.create<\n string,\n IncrementalResponseCacheResult\n >({\n // We wait to do any async work until after we've added our promise to\n // `pendingResponses` to ensure that any any other calls will reuse the\n // same promise until we've fully finished our work.\n schedulerFn: scheduleOnNextTick,\n })\n\n /**\n * LRU cache for minimal mode using compound keys (pathname + invocationID).\n * This allows multiple invocations to cache the same pathname without\n * overwriting each other's entries.\n */\n private readonly cache: LRUCache\n\n /**\n * Set of invocation IDs that have had cache entries evicted.\n * Used to detect when the cache size may be too small.\n * Bounded to prevent memory growth.\n */\n private readonly evictedInvocationIDs: Set = new Set()\n\n /**\n * The configured max size, stored for logging.\n */\n private readonly maxSize: number\n\n /**\n * The configured TTL for cache entries in milliseconds.\n */\n private readonly ttl: number\n\n // we don't use minimal_mode name here as this.minimal_mode is\n // statically replace for server runtimes but we need it to\n // be dynamic here\n private minimal_mode?: boolean\n\n private readonly route: ResponseCacheOwner | 'image'\n\n constructor({\n minimalMode,\n route,\n maxSize = DEFAULT_MAX_SIZE,\n ttl = DEFAULT_TTL_MS,\n }: {\n minimalMode: boolean\n route: ResponseCacheOwner | 'image'\n maxSize?: number\n ttl?: number\n }) {\n if (!route) {\n throw new InvariantError('Response cache requires a source route')\n }\n this.route = route\n this.minimal_mode = minimalMode\n this.maxSize = maxSize\n this.ttl = ttl\n\n // Create the LRU cache with eviction tracking\n this.cache = new LRUCache(maxSize, undefined, (compoundKey) => {\n const invocationID = extractInvocationID(compoundKey)\n if (invocationID) {\n // Bound to 100 entries to prevent unbounded memory growth.\n // FIFO eviction is acceptable here because:\n // 1. Invocations are short-lived (single request lifecycle), so older\n // invocations are unlikely to still be active after 100 newer ones\n // 2. This warning mechanism is best-effort for developer guidance—\n // missing occasional eviction warnings doesn't affect correctness\n // 3. If a long-running invocation is somehow evicted and then has\n // another cache entry evicted, it will simply be re-added\n if (this.evictedInvocationIDs.size >= 100) {\n const first = this.evictedInvocationIDs.values().next().value\n if (first) this.evictedInvocationIDs.delete(first)\n }\n this.evictedInvocationIDs.add(invocationID)\n }\n })\n }\n\n /**\n * Gets the response cache entry for the given key.\n *\n * @param key - The key to get the response cache entry for.\n * @param responseGenerator - The response generator to use to generate the response cache entry.\n * @param context - The context for the get request.\n * @returns The response cache entry.\n */\n public async get(\n key: string | null,\n responseGenerator: ResponseGenerator,\n context: {\n routeKind: RouteKind\n isOnDemandRevalidate?: boolean\n isPrefetch?: boolean\n incrementalCache: IncrementalResponseCache\n isRoutePPREnabled?: boolean\n isFallback?: boolean\n waitUntil?: (prom: Promise) => void\n\n /**\n * The invocation ID from the infrastructure. Used to scope the in-memory\n * cache to a single revalidation request in minimal mode. Concurrent\n * invocations can still share a pending render through the batchers.\n */\n invocationID?: string\n }\n ): Promise {\n // If there is no key for the cache, we can't possibly look this up in the\n // cache so just return the result of the response generator.\n if (!key) {\n return responseGenerator({\n hasResolved: false,\n previousCacheEntry: null,\n })\n }\n\n // Check minimal mode cache before doing any other work.\n if (this.minimal_mode) {\n const cacheKey = createCacheKey(key, context.invocationID)\n const cachedItem = this.cache.get(cacheKey)\n\n if (cachedItem) {\n // With invocationID: exact match found - always a hit\n // With TTL mode: must check expiration\n if (context.invocationID !== undefined) {\n return cachedItem.entry !== null && 'error' in cachedItem.entry\n ? cachedItem.entry\n : toResponseCacheEntry(cachedItem.entry)\n }\n\n // TTL entries can be reused by unrelated requests. Exclude failures so\n // those requests can retry instead of receiving a cached error.\n const now = Date.now()\n if (\n (cachedItem.entry === null || !('error' in cachedItem.entry)) &&\n cachedItem.expiresAt > now\n ) {\n return toResponseCacheEntry(cachedItem.entry)\n }\n\n // TTL expired - clean up\n this.cache.remove(cacheKey)\n }\n\n // Warn if this invocation had entries evicted - indicates cache may be too small.\n if (\n context.invocationID &&\n this.evictedInvocationIDs.has(context.invocationID)\n ) {\n warnOnce(\n `Response cache entry was evicted for invocation ${context.invocationID}. ` +\n `Consider increasing NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE (current: ${this.maxSize}).`\n )\n }\n }\n\n const {\n incrementalCache,\n isOnDemandRevalidate = false,\n isFallback = false,\n isRoutePPREnabled = false,\n isPrefetch = false,\n waitUntil,\n invocationID,\n } = context\n\n const response = await this.getBatcher.batch(\n { key, isOnDemandRevalidate },\n ({ resolve }) => {\n const promise = this.handleGet(\n key,\n responseGenerator,\n {\n incrementalCache,\n isOnDemandRevalidate,\n isFallback,\n isRoutePPREnabled,\n isPrefetch,\n invocationID,\n },\n resolve\n )\n\n // We need to ensure background revalidates are passed to waitUntil.\n if (waitUntil) waitUntil(promise)\n\n return promise\n }\n )\n\n // In minimal mode, each caller with an invocation ID stores the shared\n // failure under its own ID for reuse by related requests. Callers without\n // an invocation ID receive the failure but do not store it in the LRU.\n if (\n this.minimal_mode &&\n response &&\n ('error' in response ? invocationID !== undefined : response.cacheControl)\n ) {\n const cacheKey = createCacheKey(key, invocationID)\n this.cache.set(cacheKey, {\n entry: response,\n expiresAt: Date.now() + this.ttl,\n })\n }\n\n return response !== null && 'error' in response\n ? response\n : toResponseCacheEntry(response)\n }\n\n /**\n * Handles the get request for the response cache.\n *\n * @param key - The key to get the response cache entry for.\n * @param responseGenerator - The response generator to use to generate the response cache entry.\n * @param context - The context for the get request.\n * @param resolve - The resolve function to use to resolve the response cache entry.\n * @returns The response cache entry.\n */\n private async handleGet(\n key: string,\n responseGenerator: ResponseGenerator,\n context: {\n incrementalCache: IncrementalResponseCache\n isOnDemandRevalidate: boolean\n isFallback: boolean\n isRoutePPREnabled: boolean\n isPrefetch: boolean\n invocationID: string | undefined\n },\n resolve: (value: IncrementalResponseCacheResult) => void\n ): Promise {\n let previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null =\n null\n let resolved = false\n\n try {\n // Get the previous cache entry if not in minimal mode\n previousIncrementalCacheEntry = !this.minimal_mode\n ? await context.incrementalCache.get(\n key,\n this.getCacheContext(context.isRoutePPREnabled, context.isFallback)\n )\n : null\n\n // `isStale === -1` signals that the entry is past its `expire` (either\n // via an expired tag or, with `cacheLife({ expire })`, past the route's\n // expire time in the prerender manifest). In that case we must NOT\n // early-resolve with the stale value — instead we fall through to a\n // blocking revalidation so the response returned to the user is fresh.\n if (\n previousIncrementalCacheEntry &&\n !context.isOnDemandRevalidate &&\n previousIncrementalCacheEntry.isStale !== -1\n ) {\n resolve(previousIncrementalCacheEntry)\n resolved = true\n\n if (!previousIncrementalCacheEntry.isStale || context.isPrefetch) {\n // The cached value is still valid, so we don't need to update it yet.\n return previousIncrementalCacheEntry\n }\n }\n\n // Revalidate the cache entry.\n //\n // A prefetch request that missed must run its own response generator\n // rather than joining an in-flight revalidation through the batcher. A\n // background revalidation may be regenerating the concrete (non-fallback)\n // entry for this route — e.g. an ISR fallback-shell upgrade scheduled by\n // an earlier prefetch sub-request. Joining it would serve that concrete\n // result to the prefetch instead of the fallback shell, and which segment\n // wins would depend purely on request timing. Running the generator\n // directly lets every prefetch segment take the same fallback-shell path,\n // independent of any concurrent background upgrade.\n const incrementalResponseCacheEntry =\n context.isPrefetch && previousIncrementalCacheEntry === null\n ? await this.handleRevalidate(\n key,\n context.incrementalCache,\n context.isRoutePPREnabled,\n context.isFallback,\n responseGenerator,\n previousIncrementalCacheEntry,\n resolved\n )\n : await this.revalidate(\n key,\n context.incrementalCache,\n context.isRoutePPREnabled,\n context.isFallback,\n responseGenerator,\n previousIncrementalCacheEntry,\n resolved\n )\n\n if (\n incrementalResponseCacheEntry !== null &&\n 'error' in incrementalResponseCacheEntry &&\n resolved\n ) {\n // The caller already received the stale entry. Report the background\n // failure here, as the catch below does for a thrown error.\n console.error(incrementalResponseCacheEntry.error)\n return null\n }\n\n // Handle null response\n if (!incrementalResponseCacheEntry) {\n // Remove the cache item if it was set so we don't use it again.\n if (this.minimal_mode) {\n const cacheKey = createCacheKey(key, context.invocationID)\n this.cache.remove(cacheKey)\n }\n return null\n }\n\n // Resolve for on-demand revalidation or if not already resolved\n if (context.isOnDemandRevalidate && !resolved) {\n return incrementalResponseCacheEntry\n }\n\n return incrementalResponseCacheEntry\n } catch (err) {\n // If we've already resolved the cache entry, we can't reject as we\n // already resolved the cache entry so log the error here.\n if (resolved) {\n console.error(err)\n return null\n }\n\n throw err\n }\n }\n\n /**\n * Revalidates the cache entry for the given key.\n *\n * @param key - The key to revalidate the cache entry for.\n * @param incrementalCache - The incremental cache to use to revalidate the cache entry.\n * @param isRoutePPREnabled - Whether the route is PPR enabled.\n * @param isFallback - Whether the route is a fallback.\n * @param responseGenerator - The response generator to use to generate the response cache entry.\n * @param previousIncrementalCacheEntry - The previous cache entry to use to revalidate the cache entry.\n * @param hasResolved - Whether the response has been resolved.\n * @param waitUntil - Optional function to register background work.\n * @param invocationID - The invocation ID for cache key scoping.\n * @returns The revalidated cache entry.\n */\n public async revalidate(\n key: string,\n incrementalCache: IncrementalResponseCache,\n isRoutePPREnabled: boolean,\n isFallback: boolean,\n responseGenerator: ResponseGenerator,\n previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null,\n hasResolved: boolean,\n waitUntil?: (prom: Promise) => void\n ) {\n return this.revalidateBatcher.batch(key, () => {\n const promise = this.handleRevalidate(\n key,\n incrementalCache,\n isRoutePPREnabled,\n isFallback,\n responseGenerator,\n previousIncrementalCacheEntry,\n hasResolved\n )\n\n // We need to ensure background revalidates are passed to waitUntil.\n if (waitUntil) waitUntil(promise)\n\n return promise\n })\n }\n\n private async handleRevalidate(\n key: string,\n incrementalCache: IncrementalResponseCache,\n isRoutePPREnabled: boolean,\n isFallback: boolean,\n responseGenerator: ResponseGenerator,\n previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null,\n hasResolved: boolean\n ): Promise {\n let failure: PrerenderFailure\n try {\n // Generate the response cache entry using the response generator.\n const responseCacheEntry = await responseGenerator({\n hasResolved,\n previousCacheEntry: previousIncrementalCacheEntry,\n isRevalidating: true,\n })\n if (!responseCacheEntry) {\n return null\n }\n\n if ('error' in responseCacheEntry) {\n failure = responseCacheEntry\n } else {\n // Convert the response cache entry to an incremental response cache entry.\n const incrementalResponseCacheEntry = await fromResponseCacheEntry({\n ...responseCacheEntry,\n isMiss: !previousIncrementalCacheEntry,\n })\n\n // We want to persist the result only if it has a cache control value\n // defined. The minimal mode LRU write is handled in get() so that every\n // caller, including batched invocations, populates the cache.\n if (incrementalResponseCacheEntry.cacheControl && !this.minimal_mode) {\n await incrementalCache.set(key, incrementalResponseCacheEntry.value, {\n ...this.getCacheContext(isRoutePPREnabled, isFallback),\n cacheControl: incrementalResponseCacheEntry.cacheControl,\n })\n }\n\n return incrementalResponseCacheEntry\n }\n } catch (err) {\n await this.retainPreviousCacheEntry(\n key,\n incrementalCache,\n isRoutePPREnabled,\n isFallback,\n previousIncrementalCacheEntry\n )\n throw err\n }\n\n await this.retainPreviousCacheEntry(\n key,\n incrementalCache,\n isRoutePPREnabled,\n isFallback,\n previousIncrementalCacheEntry\n )\n return failure\n }\n\n // Retain the previous successful value and delay retries after revalidation\n // fails.\n private async retainPreviousCacheEntry(\n key: string,\n incrementalCache: IncrementalResponseCache,\n isRoutePPREnabled: boolean,\n isFallback: boolean,\n previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null\n ): Promise {\n if (previousIncrementalCacheEntry?.cacheControl) {\n const revalidate = Math.min(\n Math.max(previousIncrementalCacheEntry.cacheControl.revalidate || 3, 3),\n 30\n )\n const expire =\n previousIncrementalCacheEntry.cacheControl.expire === undefined\n ? undefined\n : Math.max(\n revalidate + 3,\n previousIncrementalCacheEntry.cacheControl.expire\n )\n\n await incrementalCache.set(key, previousIncrementalCacheEntry.value, {\n ...this.getCacheContext(isRoutePPREnabled, isFallback),\n cacheControl: { revalidate: revalidate, expire: expire },\n })\n }\n }\n\n private getCacheContext(\n isRoutePPREnabled: boolean,\n isFallback: boolean\n ): GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext {\n if (this.route === 'image') {\n return { kind: IncrementalCacheKind.IMAGE, isFallback: false }\n }\n const kind = routeKindToIncrementalCacheKind(this.route.kind)\n if (kind === IncrementalCacheKind.IMAGE) {\n throw new InvariantError('Images must use the image response cache')\n }\n return { route: this.route, kind, isRoutePPREnabled, isFallback }\n }\n}\n"],"names":["ResponseCache","parsePositiveInt","envValue","fallback","parsed","parseInt","Number","isFinite","DEFAULT_TTL_MS","process","env","NEXT_PRIVATE_RESPONSE_CACHE_TTL","DEFAULT_MAX_SIZE","NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE","KEY_SEPARATOR","TTL_SENTINEL","createCacheKey","pathname","invocationID","extractInvocationID","compoundKey","separatorIndex","lastIndexOf","undefined","slice","constructor","minimalMode","route","maxSize","ttl","getBatcher","Batcher","create","cacheKeyFn","key","isOnDemandRevalidate","schedulerFn","scheduleOnNextTick","revalidateBatcher","evictedInvocationIDs","Set","InvariantError","minimal_mode","cache","LRUCache","size","first","values","next","value","delete","add","get","responseGenerator","context","hasResolved","previousCacheEntry","cacheKey","cachedItem","entry","toResponseCacheEntry","now","Date","expiresAt","remove","has","warnOnce","incrementalCache","isFallback","isRoutePPREnabled","isPrefetch","waitUntil","response","batch","resolve","promise","handleGet","cacheControl","set","previousIncrementalCacheEntry","resolved","getCacheContext","isStale","incrementalResponseCacheEntry","handleRevalidate","revalidate","console","error","err","failure","responseCacheEntry","isRevalidating","fromResponseCacheEntry","isMiss","retainPreviousCacheEntry","Math","min","max","expire","kind","IncrementalCacheKind","IMAGE","routeKindToIncrementalCacheKind"],"mappings":";;;;+BAqHA;;;eAAqBA;;;;oCA3GgB;gCACN;yBAEP;0BACC;qBACA;2BACU;uBAK5B;;;;;;;;;;;;;;AASP;;;CAGC,GACD,SAASC,iBACPC,QAA4B,EAC5BC,QAAgB;IAEhB,IAAI,CAACD,UAAU,OAAOC;IACtB,MAAMC,SAASC,SAASH,UAAU;IAClC,OAAOI,OAAOC,QAAQ,CAACH,WAAWA,SAAS,IAAIA,SAASD;AAC1D;AAEA;;;;;;;;;;CAUC,GACD,MAAMK,iBAAiBP,iBACrBQ,QAAQC,GAAG,CAACC,+BAA+B,EAC3C;AAGF;;;CAG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EQ,YAAYA;oBAAYa,QAAQA;gBAAO;YACzD;QACF;IACF;IAEQjB,gBACNZ,iBAA0B,EAC1BD,UAAmB,EACmD;QACtE,IAAI,IAAI,CAACzC,KAAK,KAAK,SAAS;YAC1B,OAAO;gBAAEwE,MAAMC,2BAAoB,CAACC,KAAK;gBAAEjC,YAAY;YAAM;QAC/D;QACA,MAAM+B,OAAOG,IAAAA,sCAA+B,EAAC,IAAI,CAAC3E,KAAK,CAACwE,IAAI;QAC5D,IAAIA,SAASC,2BAAoB,CAACC,KAAK,EAAE;YACvC,MAAM,IAAI5D,8BAAc,CAAC;QAC3B;QACA,OAAO;YAAEd,OAAO,IAAI,CAACA,KAAK;YAAEwE;YAAM9B;YAAmBD;QAAW;IAClE;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/response-cache/types.d.ts b/e-commerce/node_modules/next/dist/server/response-cache/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..23780c7d8ee6dd1fb82fd8e5ae13b627077f58f0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/types.d.ts @@ -0,0 +1,231 @@ +import type { ResponseCacheOwner } from '../lib/route-cache-key'; +import type { OutgoingHttpHeaders } from 'http'; +import type RenderResult from '../render-result'; +import type { CacheControl, Revalidate } from '../lib/cache-control'; +import type { RouteKind } from '../route-kind'; +import type { PrerenderFailure } from '../render-result'; +export interface ResponseCacheBase { + get(key: string | null, responseGenerator: ResponseGenerator, context: { + isOnDemandRevalidate?: boolean; + isPrefetch?: boolean; + incrementalCache: IncrementalCache; + /** + * This is a hint to the cache to help it determine what kind of route + * this is so it knows where to look up the cache entry from. If not + * provided it will test the filesystem to check. + */ + routeKind: RouteKind; + /** + * True if this is a fallback request. + */ + isFallback?: boolean; + /** + * True if the route is enabled for PPR. + */ + isRoutePPREnabled?: boolean; + }): Promise; +} +export interface ServerComponentsHmrCache { + get(key: string): CachedFetchData | undefined; + set(key: string, data: CachedFetchData): void; +} +export type CachedFetchData = { + headers: Record; + body: string; + url: string; + status?: number; +}; +export declare const enum CachedRouteKind { + APP_PAGE = "APP_PAGE", + APP_ROUTE = "APP_ROUTE", + PAGES = "PAGES", + FETCH = "FETCH", + REDIRECT = "REDIRECT", + IMAGE = "IMAGE" +} +export interface CachedFetchValue { + kind: CachedRouteKind.FETCH; + data: CachedFetchData; + tags?: string[]; + revalidate: number; +} +export interface CachedRedirectValue { + kind: CachedRouteKind.REDIRECT; + props: Object; +} +export interface CachedAppPageValue { + kind: CachedRouteKind.APP_PAGE; + html: RenderResult; + rscData: Buffer | undefined; + status: number | undefined; + postponed: string | undefined; + headers: OutgoingHttpHeaders | undefined; + segmentData: Map | undefined; +} +export interface CachedPageValue { + kind: CachedRouteKind.PAGES; + html: RenderResult; + pageData: Object; + status: number | undefined; + headers: OutgoingHttpHeaders | undefined; +} +export interface CachedRouteValue { + kind: CachedRouteKind.APP_ROUTE; + body: Buffer; + status: number; + headers: OutgoingHttpHeaders; +} +export interface CachedImageValue { + kind: CachedRouteKind.IMAGE; + etag: string; + upstreamEtag: string; + buffer: Buffer; + extension: string; + revalidate?: number; + isMiss?: boolean; + isStale?: boolean; +} +export interface IncrementalCachedAppPageValue { + kind: CachedRouteKind.APP_PAGE; + html: string; + rscData: Buffer | undefined; + headers: OutgoingHttpHeaders | undefined; + postponed: string | undefined; + status: number | undefined; + segmentData: Map | undefined; +} +export interface IncrementalCachedPageValue { + kind: CachedRouteKind.PAGES; + html: string; + pageData: Object; + headers: OutgoingHttpHeaders | undefined; + status: number | undefined; +} +export interface IncrementalResponseCacheEntry { + cacheControl?: CacheControl; + /** + * timestamp in milliseconds to revalidate after + */ + revalidateAfter?: Revalidate; + /** + * `-1` here dictates a blocking revalidate should be used + */ + isStale?: boolean | -1; + isMiss?: boolean; + isFallback?: boolean; + value: Exclude | null; +} +export interface IncrementalFetchCacheEntry { + /** + * `-1` here dictates a blocking revalidate should be used + */ + isStale?: boolean | -1; + value: CachedFetchValue; +} +export type IncrementalCacheEntry = IncrementalResponseCacheEntry | IncrementalFetchCacheEntry; +export type IncrementalCacheValue = CachedRedirectValue | IncrementalCachedPageValue | IncrementalCachedAppPageValue | CachedImageValue | CachedFetchValue | CachedRouteValue; +export type ResponseCacheValue = CachedRedirectValue | CachedPageValue | CachedAppPageValue | CachedImageValue | CachedRouteValue; +export type ResponseCacheEntry = { + cacheControl?: CacheControl; + value: ResponseCacheValue | null; + isStale?: boolean | -1; + isMiss?: boolean; + isFallback?: boolean; +}; +export type ResponseCacheResult = ResponseCacheEntry | PrerenderFailure | null; +/** + * @param hasResolved whether the responseGenerator has resolved it's promise + * @param previousCacheEntry the previous cache entry if it exists or the current + */ +export type ResponseGenerator = (state: { + hasResolved: boolean; + previousCacheEntry?: IncrementalResponseCacheEntry | null; + isRevalidating?: boolean; + span?: any; + /** + * When true, this indicates that the response generator is being called in a + * context where the response must be generated statically. + * + * CRITICAL: This should only currently be used when revalidating due to a + * dynamic RSC request. + */ + forceStaticRender?: boolean; +}) => Promise; +export declare const enum IncrementalCacheKind { + APP_PAGE = "APP_PAGE", + APP_ROUTE = "APP_ROUTE", + PAGES = "PAGES", + FETCH = "FETCH", + IMAGE = "IMAGE" +} +export interface GetIncrementalFetchCacheContext { + kind: IncrementalCacheKind.FETCH; + revalidate?: Revalidate; + fetchUrl?: string; + fetchIdx?: number; + tags?: string[]; + softTags?: string[]; +} +export interface GetIncrementalResponseCacheHandlerContext { + kind: Exclude; + /** + * True if the route is enabled for PPR. + */ + isRoutePPREnabled?: boolean; + /** + * True if this is a fallback request. + */ + isFallback: boolean; +} +export interface GetIncrementalResponseCacheContext extends GetIncrementalResponseCacheHandlerContext { + /** Internal ownership used before invoking the storage handler. */ + route: ResponseCacheOwner; +} +export interface SetIncrementalFetchCacheContext { + fetchCache: true; + fetchUrl?: string; + fetchIdx?: number; + tags?: string[]; + isImplicitBuildTimeCache?: boolean; +} +export interface SetIncrementalResponseCacheHandlerContext { + fetchCache?: false; + cacheControl?: CacheControl; + /** + * True if the route is enabled for PPR. + */ + isRoutePPREnabled?: boolean; + /** + * True if this is a fallback request. + */ + isFallback?: boolean; +} +export interface SetIncrementalResponseCacheContext extends SetIncrementalResponseCacheHandlerContext { + /** Internal ownership used before invoking the storage handler. */ + route: ResponseCacheOwner; +} +export interface GetIncrementalImageCacheContext { + kind: IncrementalCacheKind.IMAGE; + route?: never; + isFallback: false; + isRoutePPREnabled?: false; +} +export interface SetIncrementalImageCacheContext { + kind: IncrementalCacheKind.IMAGE; + route?: never; + fetchCache?: false; + cacheControl?: CacheControl; +} +export interface IncrementalResponseCache { + get(cacheKey: string, ctx: GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext): Promise; + set(key: string, data: Exclude | null, ctx: SetIncrementalResponseCacheContext | SetIncrementalImageCacheContext): Promise; +} +export interface IncrementalCache extends IncrementalResponseCache { + get(cacheKey: string, ctx: GetIncrementalFetchCacheContext): Promise; + get(cacheKey: string, ctx: GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext): Promise; + set(key: string, data: CachedFetchValue | null, ctx: SetIncrementalFetchCacheContext): Promise; + set(key: string, data: Exclude | null, ctx: SetIncrementalResponseCacheContext | SetIncrementalImageCacheContext): Promise; + revalidateTag(tags: string | string[], durations?: { + expire?: number; + }): Promise; +} diff --git a/e-commerce/node_modules/next/dist/server/response-cache/types.js b/e-commerce/node_modules/next/dist/server/response-cache/types.js new file mode 100644 index 0000000000000000000000000000000000000000..774f550323dce7c78ce95c64e4e0cf9103b1b41a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/types.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + CachedRouteKind: null, + IncrementalCacheKind: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + CachedRouteKind: function() { + return CachedRouteKind; + }, + IncrementalCacheKind: function() { + return IncrementalCacheKind; + } +}); +var CachedRouteKind = /*#__PURE__*/ function(CachedRouteKind) { + CachedRouteKind["APP_PAGE"] = "APP_PAGE"; + CachedRouteKind["APP_ROUTE"] = "APP_ROUTE"; + CachedRouteKind["PAGES"] = "PAGES"; + CachedRouteKind["FETCH"] = "FETCH"; + CachedRouteKind["REDIRECT"] = "REDIRECT"; + CachedRouteKind["IMAGE"] = "IMAGE"; + return CachedRouteKind; +}({}); +var IncrementalCacheKind = /*#__PURE__*/ function(IncrementalCacheKind) { + IncrementalCacheKind["APP_PAGE"] = "APP_PAGE"; + IncrementalCacheKind["APP_ROUTE"] = "APP_ROUTE"; + IncrementalCacheKind["PAGES"] = "PAGES"; + IncrementalCacheKind["FETCH"] = "FETCH"; + IncrementalCacheKind["IMAGE"] = "IMAGE"; + return IncrementalCacheKind; +}({}); + +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/response-cache/types.js.map b/e-commerce/node_modules/next/dist/server/response-cache/types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d85c4012997fc650bec9afa61db4a17d5512a62a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/types.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/response-cache/types.ts"],"sourcesContent":["import type { ResponseCacheOwner } from '../lib/route-cache-key'\nimport type { OutgoingHttpHeaders } from 'http'\nimport type RenderResult from '../render-result'\nimport type { CacheControl, Revalidate } from '../lib/cache-control'\nimport type { RouteKind } from '../route-kind'\nimport type { PrerenderFailure } from '../render-result'\n\nexport interface ResponseCacheBase {\n get(\n key: string | null,\n responseGenerator: ResponseGenerator,\n context: {\n isOnDemandRevalidate?: boolean\n isPrefetch?: boolean\n incrementalCache: IncrementalCache\n /**\n * This is a hint to the cache to help it determine what kind of route\n * this is so it knows where to look up the cache entry from. If not\n * provided it will test the filesystem to check.\n */\n routeKind: RouteKind\n\n /**\n * True if this is a fallback request.\n */\n isFallback?: boolean\n\n /**\n * True if the route is enabled for PPR.\n */\n isRoutePPREnabled?: boolean\n }\n ): Promise\n}\n\n// The server components HMR cache might store other data as well in the future,\n// at which point this should be refactored to a discriminated union type.\nexport interface ServerComponentsHmrCache {\n get(key: string): CachedFetchData | undefined\n set(key: string, data: CachedFetchData): void\n}\n\nexport type CachedFetchData = {\n headers: Record\n body: string\n url: string\n status?: number\n}\n\nexport const enum CachedRouteKind {\n APP_PAGE = 'APP_PAGE',\n APP_ROUTE = 'APP_ROUTE',\n PAGES = 'PAGES',\n FETCH = 'FETCH',\n REDIRECT = 'REDIRECT',\n IMAGE = 'IMAGE',\n}\n\nexport interface CachedFetchValue {\n kind: CachedRouteKind.FETCH\n data: CachedFetchData\n // tags are only present with file-system-cache\n // fetch cache stores tags outside of cache entry\n tags?: string[]\n revalidate: number\n}\n\nexport interface CachedRedirectValue {\n kind: CachedRouteKind.REDIRECT\n props: Object\n}\n\nexport interface CachedAppPageValue {\n kind: CachedRouteKind.APP_PAGE\n // this needs to be a RenderResult so since renderResponse\n // expects that type instead of a string\n html: RenderResult\n rscData: Buffer | undefined\n status: number | undefined\n postponed: string | undefined\n headers: OutgoingHttpHeaders | undefined\n segmentData: Map | undefined\n}\n\nexport interface CachedPageValue {\n kind: CachedRouteKind.PAGES\n // this needs to be a RenderResult so since renderResponse\n // expects that type instead of a string\n html: RenderResult\n pageData: Object\n status: number | undefined\n headers: OutgoingHttpHeaders | undefined\n}\n\nexport interface CachedRouteValue {\n kind: CachedRouteKind.APP_ROUTE\n // this needs to be a RenderResult so since renderResponse\n // expects that type instead of a string\n body: Buffer\n status: number\n headers: OutgoingHttpHeaders\n}\n\nexport interface CachedImageValue {\n kind: CachedRouteKind.IMAGE\n etag: string\n upstreamEtag: string\n buffer: Buffer\n extension: string\n revalidate?: number\n isMiss?: boolean\n isStale?: boolean\n}\n\nexport interface IncrementalCachedAppPageValue {\n kind: CachedRouteKind.APP_PAGE\n // this needs to be a string since the cache expects to store\n // the string value\n html: string\n rscData: Buffer | undefined\n headers: OutgoingHttpHeaders | undefined\n postponed: string | undefined\n status: number | undefined\n segmentData: Map | undefined\n}\n\nexport interface IncrementalCachedPageValue {\n kind: CachedRouteKind.PAGES\n // this needs to be a string since the cache expects to store\n // the string value\n html: string\n pageData: Object\n headers: OutgoingHttpHeaders | undefined\n status: number | undefined\n}\n\nexport interface IncrementalResponseCacheEntry {\n cacheControl?: CacheControl\n /**\n * timestamp in milliseconds to revalidate after\n */\n revalidateAfter?: Revalidate\n /**\n * `-1` here dictates a blocking revalidate should be used\n */\n isStale?: boolean | -1\n isMiss?: boolean\n isFallback?: boolean\n value: Exclude | null\n}\n\nexport interface IncrementalFetchCacheEntry {\n /**\n * `-1` here dictates a blocking revalidate should be used\n */\n isStale?: boolean | -1\n value: CachedFetchValue\n}\n\nexport type IncrementalCacheEntry =\n | IncrementalResponseCacheEntry\n | IncrementalFetchCacheEntry\n\nexport type IncrementalCacheValue =\n | CachedRedirectValue\n | IncrementalCachedPageValue\n | IncrementalCachedAppPageValue\n | CachedImageValue\n | CachedFetchValue\n | CachedRouteValue\n\nexport type ResponseCacheValue =\n | CachedRedirectValue\n | CachedPageValue\n | CachedAppPageValue\n | CachedImageValue\n | CachedRouteValue\n\nexport type ResponseCacheEntry = {\n cacheControl?: CacheControl\n value: ResponseCacheValue | null\n isStale?: boolean | -1\n isMiss?: boolean\n isFallback?: boolean\n}\n\nexport type ResponseCacheResult = ResponseCacheEntry | PrerenderFailure | null\n\n/**\n * @param hasResolved whether the responseGenerator has resolved it's promise\n * @param previousCacheEntry the previous cache entry if it exists or the current\n */\nexport type ResponseGenerator = (state: {\n hasResolved: boolean\n previousCacheEntry?: IncrementalResponseCacheEntry | null\n isRevalidating?: boolean\n span?: any\n\n /**\n * When true, this indicates that the response generator is being called in a\n * context where the response must be generated statically.\n *\n * CRITICAL: This should only currently be used when revalidating due to a\n * dynamic RSC request.\n */\n forceStaticRender?: boolean\n}) => Promise\n\nexport const enum IncrementalCacheKind {\n APP_PAGE = 'APP_PAGE',\n APP_ROUTE = 'APP_ROUTE',\n PAGES = 'PAGES',\n FETCH = 'FETCH',\n IMAGE = 'IMAGE',\n}\n\nexport interface GetIncrementalFetchCacheContext {\n kind: IncrementalCacheKind.FETCH\n revalidate?: Revalidate\n fetchUrl?: string\n fetchIdx?: number\n tags?: string[]\n softTags?: string[]\n}\n\nexport interface GetIncrementalResponseCacheHandlerContext {\n kind: Exclude<\n IncrementalCacheKind,\n IncrementalCacheKind.FETCH | IncrementalCacheKind.IMAGE\n >\n\n /**\n * True if the route is enabled for PPR.\n */\n isRoutePPREnabled?: boolean\n\n /**\n * True if this is a fallback request.\n */\n isFallback: boolean\n}\n\nexport interface GetIncrementalResponseCacheContext\n extends GetIncrementalResponseCacheHandlerContext {\n /** Internal ownership used before invoking the storage handler. */\n route: ResponseCacheOwner\n}\n\nexport interface SetIncrementalFetchCacheContext {\n fetchCache: true\n fetchUrl?: string\n fetchIdx?: number\n tags?: string[]\n isImplicitBuildTimeCache?: boolean\n}\n\nexport interface SetIncrementalResponseCacheHandlerContext {\n fetchCache?: false\n cacheControl?: CacheControl\n\n /**\n * True if the route is enabled for PPR.\n */\n isRoutePPREnabled?: boolean\n\n /**\n * True if this is a fallback request.\n */\n isFallback?: boolean\n}\n\nexport interface SetIncrementalResponseCacheContext\n extends SetIncrementalResponseCacheHandlerContext {\n /** Internal ownership used before invoking the storage handler. */\n route: ResponseCacheOwner\n}\n\nexport interface GetIncrementalImageCacheContext {\n kind: IncrementalCacheKind.IMAGE\n route?: never\n isFallback: false\n isRoutePPREnabled?: false\n}\n\nexport interface SetIncrementalImageCacheContext {\n kind: IncrementalCacheKind.IMAGE\n route?: never\n fetchCache?: false\n cacheControl?: CacheControl\n}\n\nexport interface IncrementalResponseCache {\n get(\n cacheKey: string,\n ctx: GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext\n ): Promise\n set(\n key: string,\n data: Exclude | null,\n ctx: SetIncrementalResponseCacheContext | SetIncrementalImageCacheContext\n ): Promise\n}\n\nexport interface IncrementalCache extends IncrementalResponseCache {\n get(\n cacheKey: string,\n ctx: GetIncrementalFetchCacheContext\n ): Promise\n get(\n cacheKey: string,\n ctx: GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext\n ): Promise\n set(\n key: string,\n data: CachedFetchValue | null,\n ctx: SetIncrementalFetchCacheContext\n ): Promise\n set(\n key: string,\n data: Exclude | null,\n ctx: SetIncrementalResponseCacheContext | SetIncrementalImageCacheContext\n ): Promise\n revalidateTag(\n tags: string | string[],\n durations?: { expire?: number }\n ): Promise\n}\n"],"names":["CachedRouteKind","IncrementalCacheKind"],"mappings":";;;;;;;;;;;;;;;IAiDkBA,eAAe;eAAfA;;IA+JAC,oBAAoB;eAApBA;;;AA/JX,IAAA,AAAWD,yCAAAA;;;;;;;WAAAA;;AA+JX,IAAA,AAAWC,8CAAAA;;;;;;WAAAA","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/response-cache/utils.d.ts b/e-commerce/node_modules/next/dist/server/response-cache/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc57e21507317aba5861bc63c4f169d3adf34db3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/utils.d.ts @@ -0,0 +1,5 @@ +import { IncrementalCacheKind, type IncrementalResponseCacheEntry, type ResponseCacheEntry } from './types'; +import { RouteKind } from '../route-kind'; +export declare function fromResponseCacheEntry(cacheEntry: ResponseCacheEntry): Promise; +export declare function toResponseCacheEntry(response: IncrementalResponseCacheEntry | null): Promise; +export declare function routeKindToIncrementalCacheKind(routeKind: RouteKind): Exclude; diff --git a/e-commerce/node_modules/next/dist/server/response-cache/utils.js b/e-commerce/node_modules/next/dist/server/response-cache/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..ac85f43a8b3fec128d89fba70b5808ac6677647a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/utils.js @@ -0,0 +1,100 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + fromResponseCacheEntry: null, + routeKindToIncrementalCacheKind: null, + toResponseCacheEntry: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + fromResponseCacheEntry: function() { + return fromResponseCacheEntry; + }, + routeKindToIncrementalCacheKind: function() { + return routeKindToIncrementalCacheKind; + }, + toResponseCacheEntry: function() { + return toResponseCacheEntry; + } +}); +const _types = require("./types"); +const _renderresult = /*#__PURE__*/ _interop_require_default(require("../render-result")); +const _routekind = require("../route-kind"); +const _constants = require("../../lib/constants"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +async function fromResponseCacheEntry(cacheEntry) { + var _cacheEntry_value, _cacheEntry_value1; + return { + ...cacheEntry, + value: ((_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) === _types.CachedRouteKind.PAGES ? { + kind: _types.CachedRouteKind.PAGES, + html: await cacheEntry.value.html.toUnchunkedString(true), + pageData: cacheEntry.value.pageData, + headers: cacheEntry.value.headers, + status: cacheEntry.value.status + } : ((_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind) === _types.CachedRouteKind.APP_PAGE ? { + kind: _types.CachedRouteKind.APP_PAGE, + html: await cacheEntry.value.html.toUnchunkedString(true), + postponed: cacheEntry.value.postponed, + rscData: cacheEntry.value.rscData, + headers: cacheEntry.value.headers, + status: cacheEntry.value.status, + segmentData: cacheEntry.value.segmentData + } : cacheEntry.value + }; +} +async function toResponseCacheEntry(response) { + var _response_value, _response_value1; + if (!response) return null; + return { + isMiss: response.isMiss, + isStale: response.isStale, + cacheControl: response.cacheControl, + isFallback: response.isFallback, + value: ((_response_value = response.value) == null ? void 0 : _response_value.kind) === _types.CachedRouteKind.PAGES ? { + kind: _types.CachedRouteKind.PAGES, + html: _renderresult.default.fromStatic(response.value.html, _constants.HTML_CONTENT_TYPE_HEADER), + pageData: response.value.pageData, + headers: response.value.headers, + status: response.value.status + } : ((_response_value1 = response.value) == null ? void 0 : _response_value1.kind) === _types.CachedRouteKind.APP_PAGE ? { + kind: _types.CachedRouteKind.APP_PAGE, + html: _renderresult.default.fromStatic(response.value.html, _constants.HTML_CONTENT_TYPE_HEADER), + rscData: response.value.rscData, + headers: response.value.headers, + status: response.value.status, + postponed: response.value.postponed, + segmentData: response.value.segmentData + } : response.value + }; +} +function routeKindToIncrementalCacheKind(routeKind) { + switch(routeKind){ + case _routekind.RouteKind.PAGES: + return _types.IncrementalCacheKind.PAGES; + case _routekind.RouteKind.APP_PAGE: + return _types.IncrementalCacheKind.APP_PAGE; + case _routekind.RouteKind.IMAGE: + return _types.IncrementalCacheKind.IMAGE; + case _routekind.RouteKind.APP_ROUTE: + return _types.IncrementalCacheKind.APP_ROUTE; + case _routekind.RouteKind.PAGES_API: + // Pages Router API routes are not cached in the incremental cache. + throw new Error(`Unexpected route kind ${routeKind}`); + default: + return routeKind; + } +} + +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/response-cache/utils.js.map b/e-commerce/node_modules/next/dist/server/response-cache/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ed34ce1157bc39ae575e0ede92a7fe33e41bcc24 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/response-cache/utils.ts"],"sourcesContent":["import {\n CachedRouteKind,\n IncrementalCacheKind,\n type CachedAppPageValue,\n type CachedPageValue,\n type IncrementalResponseCacheEntry,\n type ResponseCacheEntry,\n} from './types'\n\nimport RenderResult from '../render-result'\nimport { RouteKind } from '../route-kind'\nimport { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'\n\nexport async function fromResponseCacheEntry(\n cacheEntry: ResponseCacheEntry\n): Promise {\n return {\n ...cacheEntry,\n value:\n cacheEntry.value?.kind === CachedRouteKind.PAGES\n ? {\n kind: CachedRouteKind.PAGES,\n html: await cacheEntry.value.html.toUnchunkedString(true),\n pageData: cacheEntry.value.pageData,\n headers: cacheEntry.value.headers,\n status: cacheEntry.value.status,\n }\n : cacheEntry.value?.kind === CachedRouteKind.APP_PAGE\n ? {\n kind: CachedRouteKind.APP_PAGE,\n html: await cacheEntry.value.html.toUnchunkedString(true),\n postponed: cacheEntry.value.postponed,\n rscData: cacheEntry.value.rscData,\n headers: cacheEntry.value.headers,\n status: cacheEntry.value.status,\n segmentData: cacheEntry.value.segmentData,\n }\n : cacheEntry.value,\n }\n}\n\nexport async function toResponseCacheEntry(\n response: IncrementalResponseCacheEntry | null\n): Promise {\n if (!response) return null\n\n return {\n isMiss: response.isMiss,\n isStale: response.isStale,\n cacheControl: response.cacheControl,\n isFallback: response.isFallback,\n value:\n response.value?.kind === CachedRouteKind.PAGES\n ? ({\n kind: CachedRouteKind.PAGES,\n html: RenderResult.fromStatic(\n response.value.html,\n HTML_CONTENT_TYPE_HEADER\n ),\n pageData: response.value.pageData,\n headers: response.value.headers,\n status: response.value.status,\n } satisfies CachedPageValue)\n : response.value?.kind === CachedRouteKind.APP_PAGE\n ? ({\n kind: CachedRouteKind.APP_PAGE,\n html: RenderResult.fromStatic(\n response.value.html,\n HTML_CONTENT_TYPE_HEADER\n ),\n rscData: response.value.rscData,\n headers: response.value.headers,\n status: response.value.status,\n postponed: response.value.postponed,\n segmentData: response.value.segmentData,\n } satisfies CachedAppPageValue)\n : response.value,\n }\n}\n\nexport function routeKindToIncrementalCacheKind(\n routeKind: RouteKind\n): Exclude {\n switch (routeKind) {\n case RouteKind.PAGES:\n return IncrementalCacheKind.PAGES\n case RouteKind.APP_PAGE:\n return IncrementalCacheKind.APP_PAGE\n case RouteKind.IMAGE:\n return IncrementalCacheKind.IMAGE\n case RouteKind.APP_ROUTE:\n return IncrementalCacheKind.APP_ROUTE\n case RouteKind.PAGES_API:\n // Pages Router API routes are not cached in the incremental cache.\n throw new Error(`Unexpected route kind ${routeKind}`)\n default:\n return routeKind satisfies never\n }\n}\n"],"names":["fromResponseCacheEntry","routeKindToIncrementalCacheKind","toResponseCacheEntry","cacheEntry","value","kind","CachedRouteKind","PAGES","html","toUnchunkedString","pageData","headers","status","APP_PAGE","postponed","rscData","segmentData","response","isMiss","isStale","cacheControl","isFallback","RenderResult","fromStatic","HTML_CONTENT_TYPE_HEADER","routeKind","RouteKind","IncrementalCacheKind","IMAGE","APP_ROUTE","PAGES_API","Error"],"mappings":";;;;;;;;;;;;;;;;IAasBA,sBAAsB;eAAtBA;;IAmENC,+BAA+B;eAA/BA;;IAvCMC,oBAAoB;eAApBA;;;uBAlCf;qEAEkB;2BACC;2BACe;;;;;;AAElC,eAAeF,uBACpBG,UAA8B;QAK1BA,mBAQIA;IAXR,OAAO;QACL,GAAGA,UAAU;QACbC,OACED,EAAAA,oBAAAA,WAAWC,KAAK,qBAAhBD,kBAAkBE,IAAI,MAAKC,sBAAe,CAACC,KAAK,GAC5C;YACEF,MAAMC,sBAAe,CAACC,KAAK;YAC3BC,MAAM,MAAML,WAAWC,KAAK,CAACI,IAAI,CAACC,iBAAiB,CAAC;YACpDC,UAAUP,WAAWC,KAAK,CAACM,QAAQ;YACnCC,SAASR,WAAWC,KAAK,CAACO,OAAO;YACjCC,QAAQT,WAAWC,KAAK,CAACQ,MAAM;QACjC,IACAT,EAAAA,qBAAAA,WAAWC,KAAK,qBAAhBD,mBAAkBE,IAAI,MAAKC,sBAAe,CAACO,QAAQ,GACjD;YACER,MAAMC,sBAAe,CAACO,QAAQ;YAC9BL,MAAM,MAAML,WAAWC,KAAK,CAACI,IAAI,CAACC,iBAAiB,CAAC;YACpDK,WAAWX,WAAWC,KAAK,CAACU,SAAS;YACrCC,SAASZ,WAAWC,KAAK,CAACW,OAAO;YACjCJ,SAASR,WAAWC,KAAK,CAACO,OAAO;YACjCC,QAAQT,WAAWC,KAAK,CAACQ,MAAM;YAC/BI,aAAab,WAAWC,KAAK,CAACY,WAAW;QAC3C,IACAb,WAAWC,KAAK;IAC1B;AACF;AAEO,eAAeF,qBACp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AACG,SAAS;YACtB,OAAOF,2BAAoB,CAACE,SAAS;QACvC,KAAKH,oBAAS,CAACI,SAAS;YACtB,mEAAmE;YACnE,MAAM,IAAIC,MAAM,CAAC,sBAAsB,EAAEN,WAAW;QACtD;YACE,OAAOA;IACX;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/response-cache/web.d.ts b/e-commerce/node_modules/next/dist/server/response-cache/web.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..687778f19d9bef7997da26458128198983cf93ba --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/web.d.ts @@ -0,0 +1,20 @@ +import type { ResponseCacheEntry, ResponseGenerator } from './types'; +/** + * In the web server, there is currently no incremental cache provided and we + * always SSR the page. + */ +export default class WebResponseCache { + pendingResponses: Map>; + previousCacheItem?: { + key: string; + entry: ResponseCacheEntry | null; + expiresAt: number; + }; + minimalMode?: boolean; + constructor(minimalMode: boolean); + get(key: string | null, responseGenerator: ResponseGenerator, context: { + isOnDemandRevalidate?: boolean; + isPrefetch?: boolean; + incrementalCache: any; + }): Promise; +} diff --git a/e-commerce/node_modules/next/dist/server/response-cache/web.js b/e-commerce/node_modules/next/dist/server/response-cache/web.js new file mode 100644 index 0000000000000000000000000000000000000000..8534a4bb0970c28323e2178557e7212229656b72 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/web.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, /** + * In the web server, there is currently no incremental cache provided and we + * always SSR the page. + */ "default", { + enumerable: true, + get: function() { + return WebResponseCache; + } +}); +const _promisewithresolvers = require("../../shared/lib/promise-with-resolvers"); +class WebResponseCache { + constructor(minimalMode){ + this.pendingResponses = new Map(); + // this is a hack to avoid Webpack knowing this is equal to this.minimalMode + // because we replace this.minimalMode to true in production bundles. + Object.assign(this, { + minimalMode + }); + } + get(key, responseGenerator, context) { + var _this_previousCacheItem; + // ensure on-demand revalidate doesn't block normal requests + const pendingResponseKey = key ? `${key}-${context.isOnDemandRevalidate ? '1' : '0'}` : null; + const pendingResponse = pendingResponseKey ? this.pendingResponses.get(pendingResponseKey) : null; + if (pendingResponse) { + return pendingResponse; + } + const { promise, resolve: resolver, reject: rejecter } = (0, _promisewithresolvers.createPromiseWithResolvers)(); + if (pendingResponseKey) { + this.pendingResponses.set(pendingResponseKey, promise); + } + let hasResolved = false; + const resolve = (cacheEntry)=>{ + if (pendingResponseKey) { + // Ensure all reads from the cache get the latest value. + this.pendingResponses.set(pendingResponseKey, Promise.resolve(cacheEntry)); + } + if (!hasResolved) { + hasResolved = true; + resolver(cacheEntry); + } + }; + // we keep the previous cache entry around to leverage + // when the incremental cache is disabled in minimal mode + if (pendingResponseKey && this.minimalMode && ((_this_previousCacheItem = this.previousCacheItem) == null ? void 0 : _this_previousCacheItem.key) === pendingResponseKey && this.previousCacheItem.expiresAt > Date.now()) { + resolve(this.previousCacheItem.entry); + this.pendingResponses.delete(pendingResponseKey); + return promise; + } + // We wait to do any async work until after we've added our promise to + // `pendingResponses` to ensure that any any other calls will reuse the + // same promise until we've fully finished our work. + ; + (async ()=>{ + try { + const cacheEntry = await responseGenerator({ + hasResolved + }); + if (cacheEntry !== null && 'error' in cacheEntry) { + throw cacheEntry.error; + } + const resolveValue = cacheEntry === null ? null : { + ...cacheEntry, + isMiss: true + }; + // for on-demand revalidate wait to resolve until cache is set + if (!context.isOnDemandRevalidate) { + resolve(resolveValue); + } + if (key && cacheEntry && cacheEntry.cacheControl) { + this.previousCacheItem = { + key: pendingResponseKey || key, + entry: cacheEntry, + expiresAt: Date.now() + 1000 + }; + } else { + this.previousCacheItem = undefined; + } + if (context.isOnDemandRevalidate) { + resolve(resolveValue); + } + } catch (err) { + // while revalidating in the background we can't reject as + // we already resolved the cache entry so log the error here + if (hasResolved) { + console.error(err); + } else { + rejecter(err); + } + } finally{ + if (pendingResponseKey) { + this.pendingResponses.delete(pendingResponseKey); + } + } + })(); + return promise; + } +} + +//# sourceMappingURL=web.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/response-cache/web.js.map b/e-commerce/node_modules/next/dist/server/response-cache/web.js.map new file mode 100644 index 0000000000000000000000000000000000000000..eb5c937c8099a36e9a4626e6086bce352ec1cb0f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/response-cache/web.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/response-cache/web.ts"],"sourcesContent":["import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\nimport type { ResponseCacheEntry, ResponseGenerator } from './types'\n\n/**\n * In the web server, there is currently no incremental cache provided and we\n * always SSR the page.\n */\nexport default class WebResponseCache {\n pendingResponses: Map>\n previousCacheItem?: {\n key: string\n entry: ResponseCacheEntry | null\n expiresAt: number\n }\n minimalMode?: boolean\n\n constructor(minimalMode: boolean) {\n this.pendingResponses = new Map()\n // this is a hack to avoid Webpack knowing this is equal to this.minimalMode\n // because we replace this.minimalMode to true in production bundles.\n Object.assign(this, { minimalMode })\n }\n\n public get(\n key: string | null,\n responseGenerator: ResponseGenerator,\n context: {\n isOnDemandRevalidate?: boolean\n isPrefetch?: boolean\n incrementalCache: any\n }\n ): Promise {\n // ensure on-demand revalidate doesn't block normal requests\n const pendingResponseKey = key\n ? `${key}-${context.isOnDemandRevalidate ? '1' : '0'}`\n : null\n\n const pendingResponse = pendingResponseKey\n ? this.pendingResponses.get(pendingResponseKey)\n : null\n if (pendingResponse) {\n return pendingResponse\n }\n\n const {\n promise,\n resolve: resolver,\n reject: rejecter,\n } = createPromiseWithResolvers()\n if (pendingResponseKey) {\n this.pendingResponses.set(pendingResponseKey, promise)\n }\n\n let hasResolved = false\n const resolve = (cacheEntry: ResponseCacheEntry | null) => {\n if (pendingResponseKey) {\n // Ensure all reads from the cache get the latest value.\n this.pendingResponses.set(\n pendingResponseKey,\n Promise.resolve(cacheEntry)\n )\n }\n if (!hasResolved) {\n hasResolved = true\n resolver(cacheEntry)\n }\n }\n\n // we keep the previous cache entry around to leverage\n // when the incremental cache is disabled in minimal mode\n if (\n pendingResponseKey &&\n this.minimalMode &&\n this.previousCacheItem?.key === pendingResponseKey &&\n this.previousCacheItem.expiresAt > Date.now()\n ) {\n resolve(this.previousCacheItem.entry)\n this.pendingResponses.delete(pendingResponseKey)\n return promise\n }\n\n // We wait to do any async work until after we've added our promise to\n // `pendingResponses` to ensure that any any other calls will reuse the\n // same promise until we've fully finished our work.\n ;(async () => {\n try {\n const cacheEntry = await responseGenerator({ hasResolved })\n if (cacheEntry !== null && 'error' in cacheEntry) {\n throw cacheEntry.error\n }\n\n const resolveValue =\n cacheEntry === null\n ? null\n : {\n ...cacheEntry,\n isMiss: true,\n }\n\n // for on-demand revalidate wait to resolve until cache is set\n if (!context.isOnDemandRevalidate) {\n resolve(resolveValue)\n }\n\n if (key && cacheEntry && cacheEntry.cacheControl) {\n this.previousCacheItem = {\n key: pendingResponseKey || key,\n entry: cacheEntry,\n expiresAt: Date.now() + 1000,\n }\n } else {\n this.previousCacheItem = undefined\n }\n\n if (context.isOnDemandRevalidate) {\n resolve(resolveValue)\n }\n } catch (err) {\n // while revalidating in the background we can't reject as\n // we already resolved the cache entry so log the error here\n if (hasResolved) {\n console.error(err)\n } else {\n rejecter(err as Error)\n }\n } finally {\n if (pendingResponseKey) {\n this.pendingResponses.delete(pendingResponseKey)\n }\n }\n })()\n return promise\n }\n}\n"],"names":["WebResponseCache","constructor","minimalMode","pendingResponses","Map","Object","assign","get","key","responseGenerator","context","pendingResponseKey","isOnDemandRevalidate","pendingResponse","promise","resolve","resolver","reject","rejecter","createPromiseWithResolvers","set","hasResolved","cacheEntry","Promise","previousCacheItem","expiresAt","Date","now","entry","delete","error","resolveValue","isMiss","cacheControl","undefined","err","console"],"mappings":";;;;+BAGA;;;CAGC,GACD;;;eAAqBA;;;sCAPsB;AAO5B,MAAMA;IASnBC,YAAYC,WAAoB,CAAE;QAChC,IAAI,CAACC,gBAAgB,GAAG,IAA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zD,IAAIC,eAAe,QAAQ,WAAWA,YAAY;oBAChD,MAAMA,WAAWQ,KAAK;gBACxB;gBAEA,MAAMC,eACJT,eAAe,OACX,OACA;oBACE,GAAGA,UAAU;oBACbU,QAAQ;gBACV;gBAEN,8DAA8D;gBAC9D,IAAI,CAACtB,QAAQE,oBAAoB,EAAE;oBACjCG,QAAQgB;gBACV;gBAEA,IAAIvB,OAAOc,cAAcA,WAAWW,YAAY,EAAE;oBAChD,IAAI,CAACT,iBAAiB,GAAG;wBACvBhB,KAAKG,sBAAsBH;wBAC3BoB,OAAON;wBACPG,WAAWC,KAAKC,GAAG,KAAK;oBAC1B;gBACF,OAAO;oBACL,IAAI,CAACH,iBAAiB,GAAGU;gBAC3B;gBAEA,IAAIxB,QAAQE,oBAAoB,EAAE;oBAChCG,QAAQgB;gBACV;YACF,EAAE,OAAOI,KAAK;gBACZ,0DAA0D;gBAC1D,4DAA4D;gBAC5D,IAAId,aAAa;oBACfe,QAAQN,KAAK,CAACK;gBAChB,OAAO;oBACLjB,SAASiB;gBACX;YACF,SAAU;gBACR,IAAIxB,oBAAoB;oBACtB,IAAI,CAACR,gBAAgB,CAAC0B,MAAM,CAAClB;gBAC/B;YACF;QACF,CAAA;QACA,OAAOG;IACT;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/resume-data-cache/cache-store.d.ts b/e-commerce/node_modules/next/dist/server/resume-data-cache/cache-store.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..37e21e5c917689ac6532e96fdec768b74f4f44d9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/resume-data-cache/cache-store.d.ts @@ -0,0 +1,66 @@ +import type { CachedFetchValue } from '../response-cache/types'; +import type { CollectedCacheResult } from '../use-cache/use-cache-wrapper'; +/** + * A generic cache store type that provides a subset of Map functionality + */ +type CacheStore = Pick, 'entries' | 'keys' | 'size' | 'get' | 'set' | 'has' | typeof Symbol.iterator>; +/** + * A cache store specifically for fetch cache values + */ +export type FetchCacheStore = CacheStore; +/** + * A cache store for encrypted bound args of inline server functions. + */ +export type EncryptedBoundArgsCacheStore = CacheStore; +/** + * An in-memory-only cache store for decrypted bound args of inline server + * functions. + */ +export type DecryptedBoundArgsCacheStore = CacheStore; +/** + * An in-memory-only cache store for rendered `ImageResponse` array buffers, + * keyed by a serialization of the `ImageResponse` constructor args. This lets + * the prospective prerender render the image once and hand the array buffer to + * the final prerender within microtasks, so that metadata image routes can be + * statically prerendered under Cache Components. Never serialized into the + * resume store. + */ +export type ImageResponseCacheStore = CacheStore>; +/** + * Serialized format for "use cache" entries + */ +export interface UseCacheCacheStoreSerialized { + entry: { + value: string; + tags: string[]; + stale: number; + timestamp: number; + expire: number; + revalidate: number; + }; + hasExplicitRevalidate: boolean | undefined; + hasExplicitExpire: boolean | undefined; + readRootParamNames: string[] | undefined; +} +export declare const FALLBACK_PARAMS: unique symbol; +export declare const RUNTIME_DATA: unique symbol; +export declare const SESSION_DATA: unique symbol; +type UseCacheCacheStoreValue = Promise | typeof FALLBACK_PARAMS | typeof RUNTIME_DATA | typeof SESSION_DATA; +/** + * A cache store for "use cache" results, or markers explaining why an entry + * could not be included in this prerender. + */ +export type UseCacheCacheStore = CacheStore; +/** + * Parses serialized cache entries into a UseCacheCacheStore + * @param entries - The serialized entries to parse + * @returns A new UseCacheCacheStore containing the parsed entries + */ +export declare function parseUseCacheCacheStore(entries: Iterable<[string, UseCacheCacheStoreSerialized]>): UseCacheCacheStore; +/** + * Serializes UseCacheCacheStore entries into an array of key-value pairs + * @param entries - The store entries to stringify + * @returns A promise that resolves to an array of key-value pairs with serialized values + */ +export declare function serializeUseCacheCacheStore(entries: IterableIterator<[string, UseCacheCacheStoreValue]>, isCacheComponentsEnabled: boolean): Promise>; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/resume-data-cache/cache-store.js b/e-commerce/node_modules/next/dist/server/resume-data-cache/cache-store.js new file mode 100644 index 0000000000000000000000000000000000000000..2dc28be7399f887daa880134d862886f5b6f56e9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/resume-data-cache/cache-store.js @@ -0,0 +1,119 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + FALLBACK_PARAMS: null, + RUNTIME_DATA: null, + SESSION_DATA: null, + parseUseCacheCacheStore: null, + serializeUseCacheCacheStore: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + FALLBACK_PARAMS: function() { + return FALLBACK_PARAMS; + }, + RUNTIME_DATA: function() { + return RUNTIME_DATA; + }, + SESSION_DATA: function() { + return SESSION_DATA; + }, + parseUseCacheCacheStore: function() { + return parseUseCacheCacheStore; + }, + serializeUseCacheCacheStore: function() { + return serializeUseCacheCacheStore; + } +}); +const _encryptionutils = require("../app-render/encryption-utils"); +const _constants = require("../use-cache/constants"); +const FALLBACK_PARAMS = Symbol.for('next.resume-data-cache.fallback-params'); +const RUNTIME_DATA = Symbol.for('next.resume-data-cache.runtime-data'); +const SESSION_DATA = Symbol.for('next.resume-data-cache.session-data'); +function parseUseCacheCacheStore(entries) { + const store = new Map(); + for (const [key, { entry, hasExplicitRevalidate, hasExplicitExpire, readRootParamNames }] of entries){ + store.set(key, Promise.resolve({ + entry: { + // Create a ReadableStream from the Uint8Array + value: new ReadableStream({ + start (controller) { + // Enqueue the Uint8Array to the stream + controller.enqueue((0, _encryptionutils.stringToUint8Array)(atob(entry.value))); + // Close the stream + controller.close(); + } + }), + tags: entry.tags, + stale: entry.stale, + timestamp: entry.timestamp, + expire: entry.expire, + revalidate: entry.revalidate + }, + hasExplicitRevalidate, + hasExplicitExpire, + readRootParamNames: readRootParamNames ? new Set(readRootParamNames) : undefined, + // Serialized RDC entries are non-dynamic by construction (the + // serializer drops dynamic entries), so this is never produced from the + // wire — the throw path that consumes it is only reachable for dynamic + // entries, which only exist in the in-memory RDC. + dynamicNestedCacheError: undefined + })); + } + return store; +} +async function serializeUseCacheCacheStore(entries, isCacheComponentsEnabled) { + return Promise.all(Array.from(entries).map(([key, value])=>{ + if (value === FALLBACK_PARAMS || value === RUNTIME_DATA || value === SESSION_DATA) { + return null; + } + return value.then(async ({ entry, hasExplicitRevalidate, hasExplicitExpire, readRootParamNames })=>{ + if (isCacheComponentsEnabled && (entry.revalidate === 0 || entry.expire < _constants.MIN_PRERENDERABLE_EXPIRE)) { + // The entry was omitted from the prerender result, and subsequently + // does not need to be included in the serialized RDC. + return null; + } + const [left, right] = entry.value.tee(); + entry.value = right; + let binaryString = ''; + // We want to encode the value as a string, but we aren't sure if the + // value is a a stream of UTF-8 bytes or not, so let's just encode it + // as a string using base64. + for await (const chunk of left){ + binaryString += (0, _encryptionutils.arrayBufferToString)(chunk); + } + return [ + key, + { + entry: { + // Encode the value as a base64 string. + value: btoa(binaryString), + tags: entry.tags, + stale: entry.stale, + timestamp: entry.timestamp, + expire: entry.expire, + revalidate: entry.revalidate + }, + hasExplicitRevalidate, + hasExplicitExpire, + readRootParamNames: readRootParamNames ? [ + ...readRootParamNames + ] : undefined + } + ]; + }).catch(()=>{ + // Any failed cache writes should be ignored as to not discard the + // entire cache. + return null; + }); + })); +} + +//# sourceMappingURL=cache-store.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/resume-data-cache/cache-store.js.map b/e-commerce/node_modules/next/dist/server/resume-data-cache/cache-store.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c0cfc31c959e1e61aab04ac43a4894514ff7e9cc --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/resume-data-cache/cache-store.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/resume-data-cache/cache-store.ts"],"sourcesContent":["import {\n arrayBufferToString,\n stringToUint8Array,\n} from '../app-render/encryption-utils'\nimport type { CachedFetchValue } from '../response-cache/types'\nimport { MIN_PRERENDERABLE_EXPIRE } from '../use-cache/constants'\nimport type { CollectedCacheResult } from '../use-cache/use-cache-wrapper'\n\n/**\n * A generic cache store type that provides a subset of Map functionality\n */\ntype CacheStore = Pick<\n Map,\n 'entries' | 'keys' | 'size' | 'get' | 'set' | 'has' | typeof Symbol.iterator\n>\n\n/**\n * A cache store specifically for fetch cache values\n */\nexport type FetchCacheStore = CacheStore\n\n/**\n * A cache store for encrypted bound args of inline server functions.\n */\nexport type EncryptedBoundArgsCacheStore = CacheStore\n\n/**\n * An in-memory-only cache store for decrypted bound args of inline server\n * functions.\n */\nexport type DecryptedBoundArgsCacheStore = CacheStore\n\n/**\n * An in-memory-only cache store for rendered `ImageResponse` array buffers,\n * keyed by a serialization of the `ImageResponse` constructor args. This lets\n * the prospective prerender render the image once and hand the array buffer to\n * the final prerender within microtasks, so that metadata image routes can be\n * statically prerendered under Cache Components. Never serialized into the\n * resume store.\n */\nexport type ImageResponseCacheStore = CacheStore>\n\n/**\n * Serialized format for \"use cache\" entries\n */\nexport interface UseCacheCacheStoreSerialized {\n entry: {\n value: string\n tags: string[]\n stale: number\n timestamp: number\n expire: number\n revalidate: number\n }\n hasExplicitRevalidate: boolean | undefined\n hasExplicitExpire: boolean | undefined\n readRootParamNames: string[] | undefined\n}\n\n// These markers carry holes from the prospective prerender to the final pass.\n// They are never serialized: a request resuming the shell must be able to fill\n// them. Symbol.for keeps their identity across separately bundled runtime code.\nexport const FALLBACK_PARAMS = Symbol.for(\n 'next.resume-data-cache.fallback-params'\n)\nexport const RUNTIME_DATA = Symbol.for('next.resume-data-cache.runtime-data')\n// Unlike params/searchParams, short-lived data also prevents a static shell.\nexport const SESSION_DATA = Symbol.for('next.resume-data-cache.session-data')\n\ntype UseCacheCacheStoreValue =\n | Promise\n | typeof FALLBACK_PARAMS\n | typeof RUNTIME_DATA\n | typeof SESSION_DATA\n\n/**\n * A cache store for \"use cache\" results, or markers explaining why an entry\n * could not be included in this prerender.\n */\nexport type UseCacheCacheStore = CacheStore\n\n/**\n * Parses serialized cache entries into a UseCacheCacheStore\n * @param entries - The serialized entries to parse\n * @returns A new UseCacheCacheStore containing the parsed entries\n */\nexport function parseUseCacheCacheStore(\n entries: Iterable<[string, UseCacheCacheStoreSerialized]>\n): UseCacheCacheStore {\n const store = new Map>()\n\n for (const [\n key,\n { entry, hasExplicitRevalidate, hasExplicitExpire, readRootParamNames },\n ] of entries) {\n store.set(\n key,\n Promise.resolve({\n entry: {\n // Create a ReadableStream from the Uint8Array\n value: new ReadableStream({\n start(controller) {\n // Enqueue the Uint8Array to the stream\n controller.enqueue(stringToUint8Array(atob(entry.value)))\n\n // Close the stream\n controller.close()\n },\n }),\n tags: entry.tags,\n stale: entry.stale,\n timestamp: entry.timestamp,\n expire: entry.expire,\n revalidate: entry.revalidate,\n },\n hasExplicitRevalidate,\n hasExplicitExpire,\n readRootParamNames: readRootParamNames\n ? new Set(readRootParamNames)\n : undefined,\n // Serialized RDC entries are non-dynamic by construction (the\n // serializer drops dynamic entries), so this is never produced from the\n // wire — the throw path that consumes it is only reachable for dynamic\n // entries, which only exist in the in-memory RDC.\n dynamicNestedCacheError: undefined,\n })\n )\n }\n\n return store\n}\n\n/**\n * Serializes UseCacheCacheStore entries into an array of key-value pairs\n * @param entries - The store entries to stringify\n * @returns A promise that resolves to an array of key-value pairs with serialized values\n */\nexport async function serializeUseCacheCacheStore(\n entries: IterableIterator<[string, UseCacheCacheStoreValue]>,\n isCacheComponentsEnabled: boolean\n): Promise> {\n return Promise.all(\n Array.from(entries).map(([key, value]) => {\n if (\n value === FALLBACK_PARAMS ||\n value === RUNTIME_DATA ||\n value === SESSION_DATA\n ) {\n return null\n }\n\n return value\n .then(\n async ({\n entry,\n hasExplicitRevalidate,\n hasExplicitExpire,\n readRootParamNames,\n }) => {\n if (\n isCacheComponentsEnabled &&\n (entry.revalidate === 0 ||\n entry.expire < MIN_PRERENDERABLE_EXPIRE)\n ) {\n // The entry was omitted from the prerender result, and subsequently\n // does not need to be included in the serialized RDC.\n return null\n }\n\n const [left, right] = entry.value.tee()\n entry.value = right\n\n let binaryString: string = ''\n\n // We want to encode the value as a string, but we aren't sure if the\n // value is a a stream of UTF-8 bytes or not, so let's just encode it\n // as a string using base64.\n for await (const chunk of left) {\n binaryString += arrayBufferToString(chunk)\n }\n\n return [\n key,\n {\n entry: {\n // Encode the value as a base64 string.\n value: btoa(binaryString),\n tags: entry.tags,\n stale: entry.stale,\n timestamp: entry.timestamp,\n expire: entry.expire,\n revalidate: entry.revalidate,\n },\n hasExplicitRevalidate,\n hasExplicitExpire,\n readRootParamNames: readRootParamNames\n ? [...readRootParamNames]\n : undefined,\n },\n ] satisfies [string, UseCacheCacheStoreSerialized]\n }\n )\n .catch(() => {\n // Any failed cache writes should be ignored as to not discard the\n // entire cache.\n return null\n })\n })\n )\n}\n"],"names":["FALLBACK_PARAMS","RUNTIME_DATA","SESSION_DATA","parseUseCacheCacheStore","serializeUseCacheCacheStore","Symbol","for","entries","store","Map","key","entry","hasExplicitRevalidate","hasExplicitExpire","readRootParamNames","set","Promise","resolve","value","ReadableStream","start","controller","enqueue","stringToUint8Array","atob","close","tags","stale","timestamp","expire","revalidate","Set","undefined","dynamicNestedCacheError","isCacheComponentsEnabled","all","Array","from","map","then","MIN_PRERENDERABLE_EXPIRE","left","right","tee","binaryString","chunk","arrayBufferToString","btoa","catch"],"mappings":";;;;;;;;;;;;;;;;;;IA8DaA,eAAe;eAAfA;;IAGAC,YAAY;eAAZA;;IAEAC,YAAY;eAAZA;;IAmBGC,uBAAuB;eAAvBA;;IAmDMC,2BAA2B;eAA3BA;;;iCAtIf;2BAEkC;AAyDlC,MAAMJ,kBAAkBK,OAAOC,GAAG,CACvC;AAEK,MAAML,eAAeI,OAAOC,GAAG,CAAC;AAEhC,MAAMJ,eAAeG,OAAOC,GAAG,CAAC;AAmBhC,SAASH,wBACdI,OAAyD;IAEzD,MAAMC,QAAQ,IAAIC;IAElB,KAAK,MAAM,CACTC,KACA,EAAEC,KAAK,EAAEC,qBAAqB,EAAEC,iBAAiB,EAAEC,kBAAkB,EAAE,CACxE,IAAIP,QAAS;QACZC,MAAMO,GAAG,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AAMC,SAASJ,KAAM;gBAC9BG,gBAAgBE,IAAAA,oCAAmB,EAACD;YACtC;YAEA,OAAO;gBACLnC;gBACA;oBACEC,OAAO;wBACL,uCAAuC;wBACvCO,OAAO6B,KAAKH;wBACZlB,MAAMf,MAAMe,IAAI;wBAChBC,OAAOhB,MAAMgB,KAAK;wBAClBC,WAAWjB,MAAMiB,SAAS;wBAC1BC,QAAQlB,MAAMkB,MAAM;wBACpBC,YAAYnB,MAAMmB,UAAU;oBAC9B;oBACAlB;oBACAC;oBACAC,oBAAoBA,qBAChB;2BAAIA;qBAAmB,GACvBkB;gBACN;aACD;QACH,GAEDgB,KAAK,CAAC;YACL,kEAAkE;YAClE,gBAAgB;YAChB,OAAO;QACT;IACJ;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/resume-data-cache/resume-data-cache.d.ts b/e-commerce/node_modules/next/dist/server/resume-data-cache/resume-data-cache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a6c6eeda2a1da664f55572e0c92cf774ec1da8ea --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/resume-data-cache/resume-data-cache.d.ts @@ -0,0 +1,126 @@ +import { type UseCacheCacheStore, type FetchCacheStore, type EncryptedBoundArgsCacheStore, type DecryptedBoundArgsCacheStore, type ImageResponseCacheStore } from './cache-store'; +/** + * An immutable version of the resume data cache used during rendering. + * This cache is read-only and cannot be modified once created. + */ +export interface RenderResumeDataCache { + /** + * Discriminator. `false` means this cache is read-only and cannot be filled + * with new entries. Used by `ResumeDataCache` consumers to narrow the union + * via standard discriminated-union narrowing (e.g. `if + * (resumeDataCache.mutable)`). + */ + readonly mutable: false; + /** + * A read-only Map store for values cached by the 'use cache' React hook. + * The 'set' operation is omitted to enforce immutability. + */ + readonly cache: Omit; + /** + * A read-only Map store for cached fetch responses. + * The 'set' operation is omitted to enforce immutability. + */ + readonly fetch: Omit; + /** + * A read-only Map store for encrypted bound args of inline server functions. + * The 'set' operation is omitted to enforce immutability. + */ + readonly encryptedBoundArgs: Omit; + /** + * A read-only Map store for decrypted bound args of inline server functions. + * This is only intended for in-memory usage during pre-rendering, and must + * not be persisted in the resume store. The 'set' operation is omitted to + * enforce immutability. + */ + readonly decryptedBoundArgs: Omit; + /** + * A read-only in-memory Map store for rendered `ImageResponse` array buffers. + * This is only intended for in-memory usage during pre-rendering, and must + * not be persisted in the resume store. The 'set' operation is omitted to + * enforce immutability. + */ + readonly imageResponses: Omit; +} +/** + * A mutable version of the resume data cache used during pre-rendering. + * This cache allows both reading and writing of cached values. + */ +export interface PrerenderResumeDataCache { + /** + * Discriminator. `true` means this cache is mutable and can be filled with + * new entries during this prerender. Used by `ResumeDataCache` consumers to + * narrow the union via standard discriminated-union narrowing (e.g. + * `if (resumeDataCache.mutable)`). + */ + readonly mutable: true; + /** + * A mutable Map store for values cached by the 'use cache' React hook. + * Supports both 'get' and 'set' operations to build the cache during + * pre-rendering. + */ + readonly cache: UseCacheCacheStore; + /** + * A mutable Map store for cached fetch responses. + * Supports both 'get' and 'set' operations to build the cache during + * pre-rendering. + */ + readonly fetch: FetchCacheStore; + /** + * A mutable Map store for encrypted bound args of inline server functions. + * Supports both 'get' and 'set' operations to build the cache during + * pre-rendering. + */ + readonly encryptedBoundArgs: EncryptedBoundArgsCacheStore; + /** + * A mutable Map store for decrypted bound args of inline server functions. + * This is only intended for in-memory usage during pre-rendering, and must + * not be persisted in the resume store. Supports both 'get' and 'set' + * operations to build the cache during pre-rendering. + */ + readonly decryptedBoundArgs: DecryptedBoundArgsCacheStore; + /** + * A mutable in-memory Map store for rendered `ImageResponse` array buffers. + * Filled during the prospective prerender and read during the final + * prerender. Never persisted in the resume store. + */ + readonly imageResponses: ImageResponseCacheStore; +} +/** + * Discriminated union of the two resume data cache flavors. Consumers should + * narrow via `resumeDataCache.mutable` to access the mutable Map API (only + * available on `PrerenderResumeDataCache`). + */ +export type ResumeDataCache = RenderResumeDataCache | PrerenderResumeDataCache; +/** + * Serializes a resume data cache into a JSON string for storage or + * transmission. Handles 'use cache' values, fetch responses, and encrypted + * bound args for inline server functions. + * + * @param resumeDataCache - The immutable cache to serialize + * @returns A Promise that resolves to the serialized cache as a JSON string, or + * 'null' if empty + */ +export declare function stringifyResumeDataCache(resumeDataCache: ResumeDataCache, isCacheComponentsEnabled: boolean): Promise; +export declare function deflateResumeDataCache(serializedResumeDataCache: string): string; +/** + * Creates a new empty mutable resume data cache for pre-rendering. + * Initializes fresh Map instances for both the 'use cache' and fetch caches. + * Used at the start of pre-rendering to begin collecting cached values. + * + * @returns A new empty PrerenderResumeDataCache instance + */ +export declare function createPrerenderResumeDataCache(source?: ResumeDataCache): PrerenderResumeDataCache; +/** + * Creates an immutable render resume data cache from either: + * 1. An existing prerender cache instance + * 2. A serialized cache string + * + * @param renderResumeDataCache - A RenderResumeDataCache instance to be used directly + * @param prerenderResumeDataCache - A PrerenderResumeDataCache instance to convert to immutable + * @param persistedCache - A serialized cache string to parse + * @param maxPostponedStateSizeBytes - The max compressed size limit in bytes (used to calculate 5x decompression limit) + * @param disableResumeDataCacheCompression - Whether the persisted cache is raw JSON instead of compressed + * @returns An immutable RenderResumeDataCache instance + */ +export declare function createRenderResumeDataCache(resumeDataCache: ResumeDataCache): RenderResumeDataCache; +export declare function createRenderResumeDataCache(persistedCache: string, maxPostponedStateSizeBytes: number | undefined, disableResumeDataCacheCompression?: boolean): RenderResumeDataCache; diff --git a/e-commerce/node_modules/next/dist/server/resume-data-cache/resume-data-cache.js b/e-commerce/node_modules/next/dist/server/resume-data-cache/resume-data-cache.js new file mode 100644 index 0000000000000000000000000000000000000000..a5a2f6f7effc63aa04379418c9969939da3221e9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/resume-data-cache/resume-data-cache.js @@ -0,0 +1,144 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + createPrerenderResumeDataCache: null, + createRenderResumeDataCache: null, + deflateResumeDataCache: null, + stringifyResumeDataCache: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + createPrerenderResumeDataCache: function() { + return createPrerenderResumeDataCache; + }, + createRenderResumeDataCache: function() { + return createRenderResumeDataCache; + }, + deflateResumeDataCache: function() { + return deflateResumeDataCache; + }, + stringifyResumeDataCache: function() { + return stringifyResumeDataCache; + } +}); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _cachestore = require("./cache-store"); +async function stringifyResumeDataCache(resumeDataCache, isCacheComponentsEnabled) { + if (process.env.NEXT_RUNTIME === 'edge') { + throw new _invarianterror.InvariantError('`stringifyResumeDataCache` should not be called in edge runtime.'); + } + if (resumeDataCache.fetch.size === 0 && resumeDataCache.cache.size === 0) { + return 'null'; + } + const json = { + store: { + fetch: Object.fromEntries(resumeDataCache.fetch), + cache: Object.fromEntries((await (0, _cachestore.serializeUseCacheCacheStore)(resumeDataCache.cache.entries(), isCacheComponentsEnabled)).filter((entry)=>entry !== null)), + encryptedBoundArgs: Object.fromEntries(resumeDataCache.encryptedBoundArgs) + } + }; + return JSON.stringify(json); +} +function deflateResumeDataCache(serializedResumeDataCache) { + if (process.env.NEXT_RUNTIME === 'edge') { + throw new _invarianterror.InvariantError('`deflateResumeDataCache` should not be called in edge runtime.'); + } else { + if (serializedResumeDataCache === 'null') { + return serializedResumeDataCache; + } + // Compress the JSON string using zlib. As the data is already in memory, + // we use the synchronous deflateSync function. + const { deflateSync } = require('node:zlib'); + return deflateSync(serializedResumeDataCache).toString('base64'); + } +} +function createPrerenderResumeDataCache(source) { + if (source) { + return { + mutable: true, + cache: new Map(source.cache), + fetch: new Map(source.fetch), + encryptedBoundArgs: new Map(source.encryptedBoundArgs), + decryptedBoundArgs: new Map(source.decryptedBoundArgs), + imageResponses: new Map(source.imageResponses) + }; + } else { + return { + mutable: true, + cache: new Map(), + fetch: new Map(), + encryptedBoundArgs: new Map(), + decryptedBoundArgs: new Map(), + imageResponses: new Map() + }; + } +} +function createRenderResumeDataCache(resumeDataCacheOrPersistedCache, maxPostponedStateSizeBytes, disableResumeDataCacheCompression = false) { + if (process.env.NEXT_RUNTIME === 'edge') { + throw new _invarianterror.InvariantError('`createRenderResumeDataCache` should not be called in edge runtime.'); + } else { + if (typeof resumeDataCacheOrPersistedCache !== 'string') { + // If the cache is already read-only, return it directly. Otherwise we + // perform a type change by overriding the discriminator — the underlying + // Map references are still shared, but callers should treat the result + // as immutable. + if (!resumeDataCacheOrPersistedCache.mutable) { + return resumeDataCacheOrPersistedCache; + } + return { + ...resumeDataCacheOrPersistedCache, + mutable: false + }; + } + if (resumeDataCacheOrPersistedCache === 'null') { + return { + mutable: false, + cache: new Map(), + fetch: new Map(), + encryptedBoundArgs: new Map(), + decryptedBoundArgs: new Map(), + imageResponses: new Map() + }; + } + let serializedResumeDataCache = resumeDataCacheOrPersistedCache; + if (!disableResumeDataCacheCompression) { + // This should be a compressed string. Let's decompress it using zlib. + // As the data we already want to decompress is in memory, we use the + // synchronous inflateSync function. + const { inflateSync } = require('node:zlib'); + // Limit decompressed size to prevent zipbomb attacks. This is 5x the + // configured maxPostponedStateSize, allowing reasonable compression + // ratios while preventing extreme decompression bombs. + // Default is 500MB (5x the default 100MB compressed limit). + const maxDecompressedSize = maxPostponedStateSizeBytes ? maxPostponedStateSizeBytes * 5 : 500 * 1024 * 1024; + try { + serializedResumeDataCache = inflateSync(Buffer.from(serializedResumeDataCache, 'base64'), { + maxOutputLength: maxDecompressedSize + }).toString('utf-8'); + } catch (err) { + if (err instanceof RangeError && err.code === 'ERR_BUFFER_TOO_LARGE') { + throw new Error(`Decompressed resume data cache exceeded ${maxDecompressedSize} byte limit`); + } + throw err; + } + } + const json = JSON.parse(serializedResumeDataCache); + return { + mutable: false, + cache: (0, _cachestore.parseUseCacheCacheStore)(Object.entries(json.store.cache)), + fetch: new Map(Object.entries(json.store.fetch)), + encryptedBoundArgs: new Map(Object.entries(json.store.encryptedBoundArgs)), + decryptedBoundArgs: new Map(), + imageResponses: new Map() + }; + } +} + +//# sourceMappingURL=resume-data-cache.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/resume-data-cache/resume-data-cache.js.map b/e-commerce/node_modules/next/dist/server/resume-data-cache/resume-data-cache.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d0d464594d439cdd6b3db145abbe20c6b802435f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/resume-data-cache/resume-data-cache.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/resume-data-cache/resume-data-cache.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n type UseCacheCacheStore,\n type FetchCacheStore,\n type EncryptedBoundArgsCacheStore,\n serializeUseCacheCacheStore,\n parseUseCacheCacheStore,\n type DecryptedBoundArgsCacheStore,\n type ImageResponseCacheStore,\n type UseCacheCacheStoreSerialized,\n} from './cache-store'\n\n/**\n * An immutable version of the resume data cache used during rendering.\n * This cache is read-only and cannot be modified once created.\n */\nexport interface RenderResumeDataCache {\n /**\n * Discriminator. `false` means this cache is read-only and cannot be filled\n * with new entries. Used by `ResumeDataCache` consumers to narrow the union\n * via standard discriminated-union narrowing (e.g. `if\n * (resumeDataCache.mutable)`).\n */\n readonly mutable: false\n\n /**\n * A read-only Map store for values cached by the 'use cache' React hook.\n * The 'set' operation is omitted to enforce immutability.\n */\n readonly cache: Omit\n\n /**\n * A read-only Map store for cached fetch responses.\n * The 'set' operation is omitted to enforce immutability.\n */\n readonly fetch: Omit\n\n /**\n * A read-only Map store for encrypted bound args of inline server functions.\n * The 'set' operation is omitted to enforce immutability.\n */\n readonly encryptedBoundArgs: Omit\n\n /**\n * A read-only Map store for decrypted bound args of inline server functions.\n * This is only intended for in-memory usage during pre-rendering, and must\n * not be persisted in the resume store. The 'set' operation is omitted to\n * enforce immutability.\n */\n readonly decryptedBoundArgs: Omit\n\n /**\n * A read-only in-memory Map store for rendered `ImageResponse` array buffers.\n * This is only intended for in-memory usage during pre-rendering, and must\n * not be persisted in the resume store. The 'set' operation is omitted to\n * enforce immutability.\n */\n readonly imageResponses: Omit\n}\n\n/**\n * A mutable version of the resume data cache used during pre-rendering.\n * This cache allows both reading and writing of cached values.\n */\nexport interface PrerenderResumeDataCache {\n /**\n * Discriminator. `true` means this cache is mutable and can be filled with\n * new entries during this prerender. Used by `ResumeDataCache` consumers to\n * narrow the union via standard discriminated-union narrowing (e.g.\n * `if (resumeDataCache.mutable)`).\n */\n readonly mutable: true\n\n /**\n * A mutable Map store for values cached by the 'use cache' React hook.\n * Supports both 'get' and 'set' operations to build the cache during\n * pre-rendering.\n */\n readonly cache: UseCacheCacheStore\n\n /**\n * A mutable Map store for cached fetch responses.\n * Supports both 'get' and 'set' operations to build the cache during\n * pre-rendering.\n */\n readonly fetch: FetchCacheStore\n\n /**\n * A mutable Map store for encrypted bound args of inline server functions.\n * Supports both 'get' and 'set' operations to build the cache during\n * pre-rendering.\n */\n readonly encryptedBoundArgs: EncryptedBoundArgsCacheStore\n\n /**\n * A mutable Map store for decrypted bound args of inline server functions.\n * This is only intended for in-memory usage during pre-rendering, and must\n * not be persisted in the resume store. Supports both 'get' and 'set'\n * operations to build the cache during pre-rendering.\n */\n readonly decryptedBoundArgs: DecryptedBoundArgsCacheStore\n\n /**\n * A mutable in-memory Map store for rendered `ImageResponse` array buffers.\n * Filled during the prospective prerender and read during the final\n * prerender. Never persisted in the resume store.\n */\n readonly imageResponses: ImageResponseCacheStore\n}\n\n/**\n * Discriminated union of the two resume data cache flavors. Consumers should\n * narrow via `resumeDataCache.mutable` to access the mutable Map API (only\n * available on `PrerenderResumeDataCache`).\n */\nexport type ResumeDataCache = RenderResumeDataCache | PrerenderResumeDataCache\n\ntype ResumeStoreSerialized = {\n store: {\n cache: {\n [key: string]: any\n }\n fetch: {\n [key: string]: any\n }\n encryptedBoundArgs: {\n [key: string]: string\n }\n }\n}\n\n/**\n * Serializes a resume data cache into a JSON string for storage or\n * transmission. Handles 'use cache' values, fetch responses, and encrypted\n * bound args for inline server functions.\n *\n * @param resumeDataCache - The immutable cache to serialize\n * @returns A Promise that resolves to the serialized cache as a JSON string, or\n * 'null' if empty\n */\nexport async function stringifyResumeDataCache(\n resumeDataCache: ResumeDataCache,\n isCacheComponentsEnabled: boolean\n): Promise {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n '`stringifyResumeDataCache` should not be called in edge runtime.'\n )\n }\n\n if (resumeDataCache.fetch.size === 0 && resumeDataCache.cache.size === 0) {\n return 'null'\n }\n\n const json: ResumeStoreSerialized = {\n store: {\n fetch: Object.fromEntries(resumeDataCache.fetch),\n cache: Object.fromEntries(\n (\n await serializeUseCacheCacheStore(\n resumeDataCache.cache.entries(),\n isCacheComponentsEnabled\n )\n ).filter(\n (entry): entry is [string, UseCacheCacheStoreSerialized] =>\n entry !== null\n )\n ),\n encryptedBoundArgs: Object.fromEntries(\n resumeDataCache.encryptedBoundArgs\n ),\n },\n }\n\n return JSON.stringify(json)\n}\n\nexport function deflateResumeDataCache(\n serializedResumeDataCache: string\n): string {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n '`deflateResumeDataCache` should not be called in edge runtime.'\n )\n } else {\n if (serializedResumeDataCache === 'null') {\n return serializedResumeDataCache\n }\n\n // Compress the JSON string using zlib. As the data is already in memory,\n // we use the synchronous deflateSync function.\n const { deflateSync } = require('node:zlib') as typeof import('node:zlib')\n return deflateSync(serializedResumeDataCache).toString('base64')\n }\n}\n\n/**\n * Creates a new empty mutable resume data cache for pre-rendering.\n * Initializes fresh Map instances for both the 'use cache' and fetch caches.\n * Used at the start of pre-rendering to begin collecting cached values.\n *\n * @returns A new empty PrerenderResumeDataCache instance\n */\nexport function createPrerenderResumeDataCache(\n source?: ResumeDataCache\n): PrerenderResumeDataCache {\n if (source) {\n return {\n mutable: true,\n cache: new Map(source.cache),\n fetch: new Map(source.fetch),\n encryptedBoundArgs: new Map(source.encryptedBoundArgs),\n decryptedBoundArgs: new Map(source.decryptedBoundArgs),\n imageResponses: new Map(source.imageResponses),\n }\n } else {\n return {\n mutable: true,\n cache: new Map(),\n fetch: new Map(),\n encryptedBoundArgs: new Map(),\n decryptedBoundArgs: new Map(),\n imageResponses: new Map(),\n }\n }\n}\n\n/**\n * Creates an immutable render resume data cache from either:\n * 1. An existing prerender cache instance\n * 2. A serialized cache string\n *\n * @param renderResumeDataCache - A RenderResumeDataCache instance to be used directly\n * @param prerenderResumeDataCache - A PrerenderResumeDataCache instance to convert to immutable\n * @param persistedCache - A serialized cache string to parse\n * @param maxPostponedStateSizeBytes - The max compressed size limit in bytes (used to calculate 5x decompression limit)\n * @param disableResumeDataCacheCompression - Whether the persisted cache is raw JSON instead of compressed\n * @returns An immutable RenderResumeDataCache instance\n */\nexport function createRenderResumeDataCache(\n resumeDataCache: ResumeDataCache\n): RenderResumeDataCache\nexport function createRenderResumeDataCache(\n persistedCache: string,\n maxPostponedStateSizeBytes: number | undefined,\n disableResumeDataCacheCompression?: boolean\n): RenderResumeDataCache\nexport function createRenderResumeDataCache(\n resumeDataCacheOrPersistedCache: ResumeDataCache | string,\n maxPostponedStateSizeBytes?: number | undefined,\n disableResumeDataCacheCompression = false\n): RenderResumeDataCache {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new InvariantError(\n '`createRenderResumeDataCache` should not be called in edge runtime.'\n )\n } else {\n if (typeof resumeDataCacheOrPersistedCache !== 'string') {\n // If the cache is already read-only, return it directly. Otherwise we\n // perform a type change by overriding the discriminator — the underlying\n // Map references are still shared, but callers should treat the result\n // as immutable.\n if (!resumeDataCacheOrPersistedCache.mutable) {\n return resumeDataCacheOrPersistedCache\n }\n return { ...resumeDataCacheOrPersistedCache, mutable: false }\n }\n\n if (resumeDataCacheOrPersistedCache === 'null') {\n return {\n mutable: false,\n cache: new Map(),\n fetch: new Map(),\n encryptedBoundArgs: new Map(),\n decryptedBoundArgs: new Map(),\n imageResponses: new Map(),\n }\n }\n\n let serializedResumeDataCache = resumeDataCacheOrPersistedCache\n if (!disableResumeDataCacheCompression) {\n // This should be a compressed string. Let's decompress it using zlib.\n // As the data we already want to decompress is in memory, we use the\n // synchronous inflateSync function.\n const { inflateSync } = require('node:zlib') as typeof import('node:zlib')\n\n // Limit decompressed size to prevent zipbomb attacks. This is 5x the\n // configured maxPostponedStateSize, allowing reasonable compression\n // ratios while preventing extreme decompression bombs.\n // Default is 500MB (5x the default 100MB compressed limit).\n const maxDecompressedSize = maxPostponedStateSizeBytes\n ? maxPostponedStateSizeBytes * 5\n : 500 * 1024 * 1024\n\n try {\n serializedResumeDataCache = inflateSync(\n Buffer.from(serializedResumeDataCache, 'base64'),\n {\n maxOutputLength: maxDecompressedSize,\n }\n ).toString('utf-8')\n } catch (err: unknown) {\n if (\n err instanceof RangeError &&\n (err as NodeJS.ErrnoException).code === 'ERR_BUFFER_TOO_LARGE'\n ) {\n throw new Error(\n `Decompressed resume data cache exceeded ${maxDecompressedSize} byte limit`\n )\n }\n throw err\n }\n }\n\n const json = JSON.parse(serializedResumeDataCache) as ResumeStoreSerialized\n\n return {\n mutable: false,\n cache: parseUseCacheCacheStore(Object.entries(json.store.cache)),\n fetch: new Map(Object.entries(json.store.fetch)),\n encryptedBoundArgs: new Map(\n Object.entries(json.store.encryptedBoundArgs)\n ),\n decryptedBoundArgs: new Map(),\n imageResponses: new Map(),\n }\n }\n}\n"],"names":["createPrerenderResumeDataCache","createRenderResumeDataCache","deflateResumeDataCache","stringifyResumeDataCache","resumeDataCache","isCacheComponentsEnabled","process","env","NEXT_RUNTIME","InvariantError","fetch","size","cache","json","store","Object","fromEntries","serializeUseCacheCacheStore","entries","filter","entry","encryptedBoundArgs","JSON","stringify","serializedResumeDataCache","deflateSync","require","toString","source","mutable","Map","decryptedBoundArgs","imageResponses","resumeDataCacheOrPersistedCache","maxPostponedStateSizeBytes","disableResumeDataCacheCompression","inflateSync","maxDecompressedSize","Buffer","from","maxOutputLength","err","RangeError","code","Error","parse","parseUseCacheCacheStore"],"mappings":";;;;;;;;;;;;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ACrB,IACEA,eAAeC,cACf,AAACD,IAA8BE,IAAI,KAAK,wBACxC;oBACA,MAAM,IAAIC,MACR,CAAC,wCAAwC,EAAEP,oBAAoB,WAAW,CAAC;gBAE/E;gBACA,MAAMI;YACR;QACF;QAEA,MAAM5B,OAAOS,KAAKuB,KAAK,CAACrB;QAExB,OAAO;YACLK,SAAS;YACTjB,OAAOkC,IAAAA,mCAAuB,EAAC/B,OAAOG,OAAO,CAACL,KAAKC,KAAK,CAACF,KAAK;YAC9DF,OAAO,IAAIoB,IAAIf,OAAOG,OAAO,CAACL,KAAKC,KAAK,CAACJ,KAAK;YAC9CW,oBAAoB,IAAIS,IACtBf,OAAOG,OAAO,CAACL,KAAKC,KAAK,CAACO,kBAAkB;YAE9CU,oBAAoB,IAAID;YACxBE,gBAAgB,IAAIF;QACtB;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/revalidation-utils.d.ts b/e-commerce/node_modules/next/dist/server/revalidation-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b15fe4a3100ce05f97a5c2689f334e028d9897b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/revalidation-utils.d.ts @@ -0,0 +1,6 @@ +import type { WorkStore } from './app-render/work-async-storage.external'; +/** Run a callback, and execute any *new* revalidations added during its runtime. */ +export declare function withExecuteRevalidates(store: WorkStore | undefined, callback: () => Promise): Promise; +type RevalidationState = Required>; +export declare function executeRevalidates(workStore: WorkStore, state?: RevalidationState): false | Promise; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/revalidation-utils.js b/e-commerce/node_modules/next/dist/server/revalidation-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..e76882e353639029e33ab998f84c452c8feb8930 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/revalidation-utils.js @@ -0,0 +1,158 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + executeRevalidates: null, + withExecuteRevalidates: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + executeRevalidates: function() { + return executeRevalidates; + }, + withExecuteRevalidates: function() { + return withExecuteRevalidates; + } +}); +const _handlers = require("./use-cache/handlers"); +async function withExecuteRevalidates(store, callback) { + if (!store) { + return callback(); + } + // If we executed any revalidates during the request, then we don't want to execute them again. + // save the state so we can check if anything changed after we're done running callbacks. + const savedRevalidationState = cloneRevalidationState(store); + try { + return await callback(); + } finally{ + // Check if we have any new revalidates, and if so, wait until they are all resolved. + const newRevalidates = diffRevalidationState(savedRevalidationState, cloneRevalidationState(store)); + await executeRevalidates(store, newRevalidates); + } +} +function cloneRevalidationState(store) { + return { + // revalidateTag updates revalidatedAt in place when the tag/profile already + // exists, so snapshot the items as well as the array. + pendingRevalidatedTags: store.pendingRevalidatedTags ? store.pendingRevalidatedTags.map((item)=>({ + ...item + })) : [], + pendingRevalidates: { + ...store.pendingRevalidates + }, + pendingRevalidateWrites: store.pendingRevalidateWrites ? [ + ...store.pendingRevalidateWrites + ] : [] + }; +} +function diffRevalidationState(prev, curr) { + const prevTagsWithProfile = new Map(prev.pendingRevalidatedTags.map((item)=>{ + const profileKey = typeof item.profile === 'object' ? JSON.stringify(item.profile) : item.profile || ''; + return [ + `${item.tag}:${profileKey}`, + item.revalidatedAt + ]; + })); + const prevRevalidateWrites = new Set(prev.pendingRevalidateWrites); + return { + pendingRevalidatedTags: curr.pendingRevalidatedTags.filter((item)=>{ + const profileKey = typeof item.profile === 'object' ? JSON.stringify(item.profile) : item.profile || ''; + const previousRevalidatedAt = prevTagsWithProfile.get(`${item.tag}:${profileKey}`); + return previousRevalidatedAt === undefined || item.revalidatedAt > previousRevalidatedAt; + }), + pendingRevalidates: Object.fromEntries(Object.entries(curr.pendingRevalidates).filter(([key])=>!(key in prev.pendingRevalidates))), + pendingRevalidateWrites: curr.pendingRevalidateWrites.filter((promise)=>!prevRevalidateWrites.has(promise)) + }; +} +async function revalidateTags(tagsWithProfile, incrementalCache, workStore) { + if (tagsWithProfile.length === 0) { + return; + } + const handlers = (0, _handlers.getCacheHandlers)() ?? []; + const promises = []; + // Group tags by profile for batch processing + const tagsByProfile = new Map(); + for (const item of tagsWithProfile){ + const profile = item.profile; + // Find existing profile by comparing values + let existingKey = undefined; + for (const [key] of tagsByProfile){ + if (typeof key === 'string' && typeof profile === 'string' && key === profile) { + existingKey = key; + break; + } + if (typeof key === 'object' && typeof profile === 'object' && JSON.stringify(key) === JSON.stringify(profile)) { + existingKey = key; + break; + } + if (key === profile) { + existingKey = key; + break; + } + } + const profileKey = existingKey || profile; + if (!tagsByProfile.has(profileKey)) { + tagsByProfile.set(profileKey, []); + } + tagsByProfile.get(profileKey).push(item.tag); + } + // Process each profile group + for (const [profile, tagsForProfile] of tagsByProfile){ + // Look up the cache profile from workStore if available + let durations; + if (profile) { + let cacheLife; + if (typeof profile === 'object') { + // Profile is already a cacheLife configuration object + cacheLife = profile; + } else if (typeof profile === 'string') { + // Profile is a string key, look it up in workStore + cacheLife = workStore == null ? void 0 : workStore.cacheLifeProfiles[profile]; + if (!cacheLife) { + throw new Error(`Invalid profile provided "${profile}" must be configured under cacheLife in next.config or be "max"`); + } + } + if (cacheLife) { + durations = { + expire: cacheLife.expire + }; + } + } + // If profile is not found and not 'max', durations will be undefined + // which will trigger immediate expiration in the cache handler + for (const handler of handlers){ + if (profile) { + promises.push(handler.updateTags == null ? void 0 : handler.updateTags.call(handler, tagsForProfile, durations)); + } else { + promises.push(handler.updateTags == null ? void 0 : handler.updateTags.call(handler, tagsForProfile)); + } + } + if (incrementalCache) { + promises.push(incrementalCache.revalidateTag(tagsForProfile, durations)); + } + } + await Promise.all(promises); +} +function executeRevalidates(workStore, state) { + const promises = []; + const pendingRevalidatedTags = (state == null ? void 0 : state.pendingRevalidatedTags) ?? workStore.pendingRevalidatedTags ?? []; + if (pendingRevalidatedTags.length > 0) { + promises.push(revalidateTags(pendingRevalidatedTags, workStore.incrementalCache, workStore)); + } + const pendingRevalidates = Object.values((state == null ? void 0 : state.pendingRevalidates) ?? workStore.pendingRevalidates ?? {}); + promises.push(...pendingRevalidates); + const pendingRevalidateWrites = (state == null ? void 0 : state.pendingRevalidateWrites) ?? workStore.pendingRevalidateWrites ?? []; + promises.push(...pendingRevalidateWrites); + if (promises.length === 0) { + return false; + } + return Promise.all(promises).then(()=>undefined); +} + +//# sourceMappingURL=revalidation-utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/revalidation-utils.js.map b/e-commerce/node_modules/next/dist/server/revalidation-utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d0d7f718f3e446b69cbaaf7e0114a1e35307c07c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/revalidation-utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/revalidation-utils.ts"],"sourcesContent":["import type { WorkStore } from './app-render/work-async-storage.external'\nimport type { IncrementalCache } from './lib/incremental-cache'\nimport { getCacheHandlers } from './use-cache/handlers'\n\n/** Run a callback, and execute any *new* revalidations added during its runtime. */\nexport async function withExecuteRevalidates(\n store: WorkStore | undefined,\n callback: () => Promise\n): Promise {\n if (!store) {\n return callback()\n }\n // If we executed any revalidates during the request, then we don't want to execute them again.\n // save the state so we can check if anything changed after we're done running callbacks.\n const savedRevalidationState = cloneRevalidationState(store)\n try {\n return await callback()\n } finally {\n // Check if we have any new revalidates, and if so, wait until they are all resolved.\n const newRevalidates = diffRevalidationState(\n savedRevalidationState,\n cloneRevalidationState(store)\n )\n await executeRevalidates(store, newRevalidates)\n }\n}\n\ntype RevalidationState = Required<\n Pick<\n WorkStore,\n 'pendingRevalidatedTags' | 'pendingRevalidates' | 'pendingRevalidateWrites'\n >\n>\n\nfunction cloneRevalidationState(store: WorkStore): RevalidationState {\n return {\n // revalidateTag updates revalidatedAt in place when the tag/profile already\n // exists, so snapshot the items as well as the array.\n pendingRevalidatedTags: store.pendingRevalidatedTags\n ? store.pendingRevalidatedTags.map((item) => ({ ...item }))\n : [],\n pendingRevalidates: { ...store.pendingRevalidates },\n pendingRevalidateWrites: store.pendingRevalidateWrites\n ? [...store.pendingRevalidateWrites]\n : [],\n }\n}\n\nfunction diffRevalidationState(\n prev: RevalidationState,\n curr: RevalidationState\n): RevalidationState {\n const prevTagsWithProfile = new Map(\n prev.pendingRevalidatedTags.map((item) => {\n const profileKey =\n typeof item.profile === 'object'\n ? JSON.stringify(item.profile)\n : item.profile || ''\n return [`${item.tag}:${profileKey}`, item.revalidatedAt] as const\n })\n )\n const prevRevalidateWrites = new Set(prev.pendingRevalidateWrites)\n return {\n pendingRevalidatedTags: curr.pendingRevalidatedTags.filter((item) => {\n const profileKey =\n typeof item.profile === 'object'\n ? JSON.stringify(item.profile)\n : item.profile || ''\n const previousRevalidatedAt = prevTagsWithProfile.get(\n `${item.tag}:${profileKey}`\n )\n return (\n previousRevalidatedAt === undefined ||\n item.revalidatedAt > previousRevalidatedAt\n )\n }),\n pendingRevalidates: Object.fromEntries(\n Object.entries(curr.pendingRevalidates).filter(\n ([key]) => !(key in prev.pendingRevalidates)\n )\n ),\n pendingRevalidateWrites: curr.pendingRevalidateWrites.filter(\n (promise) => !prevRevalidateWrites.has(promise)\n ),\n }\n}\n\nasync function revalidateTags(\n tagsWithProfile: Array<{\n tag: string\n profile?: string | { expire?: number }\n }>,\n incrementalCache: IncrementalCache | undefined,\n workStore?: WorkStore\n): Promise {\n if (tagsWithProfile.length === 0) {\n return\n }\n\n const handlers = getCacheHandlers() ?? []\n const promises: Promise[] = []\n\n // Group tags by profile for batch processing\n const tagsByProfile = new Map<\n | string\n | { stale?: number; revalidate?: number; expire?: number }\n | undefined,\n string[]\n >()\n\n for (const item of tagsWithProfile) {\n const profile = item.profile\n // Find existing profile by comparing values\n let existingKey = undefined\n for (const [key] of tagsByProfile) {\n if (\n typeof key === 'string' &&\n typeof profile === 'string' &&\n key === profile\n ) {\n existingKey = key\n break\n }\n if (\n typeof key === 'object' &&\n typeof profile === 'object' &&\n JSON.stringify(key) === JSON.stringify(profile)\n ) {\n existingKey = key\n break\n }\n if (key === profile) {\n existingKey = key\n break\n }\n }\n\n const profileKey = existingKey || profile\n if (!tagsByProfile.has(profileKey)) {\n tagsByProfile.set(profileKey, [])\n }\n tagsByProfile.get(profileKey)!.push(item.tag)\n }\n\n // Process each profile group\n for (const [profile, tagsForProfile] of tagsByProfile) {\n // Look up the cache profile from workStore if available\n let durations: { expire?: number } | undefined\n\n if (profile) {\n let cacheLife:\n | { stale?: number; revalidate?: number; expire?: number }\n | undefined\n\n if (typeof profile === 'object') {\n // Profile is already a cacheLife configuration object\n cacheLife = profile\n } else if (typeof profile === 'string') {\n // Profile is a string key, look it up in workStore\n cacheLife = workStore?.cacheLifeProfiles[profile]\n\n if (!cacheLife) {\n throw new Error(\n `Invalid profile provided \"${profile}\" must be configured under cacheLife in next.config or be \"max\"`\n )\n }\n }\n\n if (cacheLife) {\n durations = {\n expire: cacheLife.expire,\n }\n }\n }\n // If profile is not found and not 'max', durations will be undefined\n // which will trigger immediate expiration in the cache handler\n\n for (const handler of handlers) {\n if (profile) {\n promises.push(handler.updateTags?.(tagsForProfile, durations))\n } else {\n promises.push(handler.updateTags?.(tagsForProfile))\n }\n }\n\n if (incrementalCache) {\n promises.push(incrementalCache.revalidateTag(tagsForProfile, durations))\n }\n }\n\n await Promise.all(promises)\n}\n\nexport function executeRevalidates(\n workStore: WorkStore,\n state?: RevalidationState\n): false | Promise {\n const promises: Promise[] = []\n\n const pendingRevalidatedTags =\n state?.pendingRevalidatedTags ?? workStore.pendingRevalidatedTags ?? []\n\n if (pendingRevalidatedTags.length > 0) {\n promises.push(\n revalidateTags(\n pendingRevalidatedTags,\n workStore.incrementalCache,\n workStore\n )\n )\n }\n\n const pendingRevalidates = Object.values(\n state?.pendingRevalidates ?? workStore.pendingRevalidates ?? {}\n )\n\n promises.push(...pendingRevalidates)\n\n const pendingRevalidateWrites =\n state?.pendingRevalidateWrites ?? workStore.pendingRevalidateWrites ?? []\n\n promises.push(...pendingRevalidateWrites)\n\n if (promises.length === 0) {\n return false\n }\n\n return Promise.all(promises).then(() => undefined)\n}\n"],"names":["executeRevalidates","withExecuteRevalidates","store","callback","savedRevalidationState","cloneRevalidationState","newRevalidates","diffRevalidationState","pendingRevalidatedTags","map","item","pendingRevalidates","pendingRevalidateWrites","prev","curr","prevTagsWithProfile","Map","profileKey","profile","JSON","stringify","tag","revalidatedAt","prevRevalidateWrites","Set","filter","previousRevalidatedAt","get","undefined","Object","fromEntries","entries","key","promise","has","revalidateTags","tagsWithProfile","incrementalCache","workStore","length","handlers","getCacheHandlers","promises","tagsByProfile","existingKey","set","push","tagsForProfile","durations","cacheLife","cacheLifeProfiles","Error","expire","handler","updateTags","revalidateTag","Promise","all","state","values","then"],"mappings":";;;;;;;;;;;;;;;IAiMgBA,kBAAkB;eAAlBA;;IA5LMC,sBAAsB;eAAtBA;;;0BAHW;AAG1B,eAAeA,uBACpBC,KAA4B,EAC5BC,QAA0B;IAE1B,IAAI,CAACD,OAAO;QACV,OAAOC;IACT;IACA,+FAA+F;IAC/F,yFAAyF;IACzF,MAAMC,yBAAyBC,uBAAuBH;IACtD,IAAI;QACF,OAAO,MAAMC;IACf,SAAU;QACR,qFAAqF;QACrF,MAAMG,iBAAiBC,sBACrBH,wBACAC,uBAAuBH;QAEzB,MAAMF,mBAAmBE,OAAOI;IAClC;AACF;AASA,SAASD,uBAAuBH,KAAgB;IAC9C,OAAO;QACL,4EAA4E;QAC5E,sDAAsD;QACtDM,wBAAwBN,MAAMM,sBAAsB,GAChDN,MAAMM,sBAAsB,CAACC,GAAG,CAAC,CAACC,OAAU,CAAA;gBAAE,GAAGA,IAAI;YAAC,CAAA,KACtD,EAAE;QACNC,oBAAoB;YAAE,GAAGT,MAAMS,kBAAkB;QAAC;QAClDC,yBAAyBV,MAAMU,uBAAuB,GAClD;eAAIV,MAAMU,uBAAuB;SAAC,GAClC,EAAE;IACR;AACF;AAEA,SAASL,sBACPM,IAAuB,EACvB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lBD,SAAqBN,gBAAgBC;YACrD,OAAO;gBACLN,SAASI,IAAI,CAACO,QAAQC,UAAU,oBAAlBD,QAAQC,UAAU,MAAlBD,SAAqBN;YACrC;QACF;QAEA,IAAIV,kBAAkB;YACpBK,SAASI,IAAI,CAACT,iBAAiBkB,aAAa,CAACR,gBAAgBC;QAC/D;IACF;IAEA,MAAMQ,QAAQC,GAAG,CAACf;AACpB;AAEO,SAAS1C,mBACdsC,SAAoB,EACpBoB,KAAyB;IAEzB,MAAMhB,WAA+B,EAAE;IAEvC,MAAMlC,yBACJkD,CAAAA,yBAAAA,MAAOlD,sBAAsB,KAAI8B,UAAU9B,sBAAsB,IAAI,EAAE;IAEzE,IAAIA,uBAAuB+B,MAAM,GAAG,GAAG;QACrCG,SAASI,IAAI,CACXX,eACE3B,wBACA8B,UAAUD,gBAAgB,EAC1BC;IAGN;IAEA,MAAM3B,qBAAqBkB,OAAO8B,MAAM,CACtCD,CAAAA,yBAAAA,MAAO/C,kBAAkB,KAAI2B,UAAU3B,kBAAkB,IAAI,CAAC;IAGhE+B,SAASI,IAAI,IAAInC;IAEjB,MAAMC,0BACJ8C,CAAAA,yBAAAA,MAAO9C,uBAAuB,KAAI0B,UAAU1B,uBAAuB,IAAI,EAAE;IAE3E8B,SAASI,IAAI,IAAIlC;IAEjB,IAAI8B,SAASH,MAAM,KAAK,GAAG;QACzB,OAAO;IACT;IAEA,OAAOiB,QAAQC,GAAG,CAACf,UAAUkB,IAAI,CAAC,IAAMhC;AAC1C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/app-page-route-definition.d.ts b/e-commerce/node_modules/next/dist/server/route-definitions/app-page-route-definition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d39ee09415bea6dd7c9ad2c3a5b6f20bbfd2a8d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/app-page-route-definition.d.ts @@ -0,0 +1,9 @@ +import type { RouteDefinition } from './route-definition'; +import { RouteKind } from '../route-kind'; +export interface AppPageRouteDefinition extends RouteDefinition { + readonly appPaths: ReadonlyArray; +} +/** + * Returns true if the given definition is an App Page route definition. + */ +export declare function isAppPageRouteDefinition(definition: RouteDefinition): definition is AppPageRouteDefinition; diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/app-page-route-definition.js b/e-commerce/node_modules/next/dist/server/route-definitions/app-page-route-definition.js new file mode 100644 index 0000000000000000000000000000000000000000..90fee8f0d00032694f947926aa0e013ab9918d83 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/app-page-route-definition.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isAppPageRouteDefinition", { + enumerable: true, + get: function() { + return isAppPageRouteDefinition; + } +}); +const _routekind = require("../route-kind"); +function isAppPageRouteDefinition(definition) { + return definition.kind === _routekind.RouteKind.APP_PAGE; +} + +//# sourceMappingURL=app-page-route-definition.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/app-page-route-definition.js.map b/e-commerce/node_modules/next/dist/server/route-definitions/app-page-route-definition.js.map new file mode 100644 index 0000000000000000000000000000000000000000..45810d97c9272e4c432dcbfed0b33180f8398db2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/app-page-route-definition.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/route-definitions/app-page-route-definition.ts"],"sourcesContent":["import type { RouteDefinition } from './route-definition'\nimport { RouteKind } from '../route-kind'\n\nexport interface AppPageRouteDefinition\n extends RouteDefinition {\n readonly appPaths: ReadonlyArray\n}\n\n/**\n * Returns true if the given definition is an App Page route definition.\n */\nexport function isAppPageRouteDefinition(\n definition: RouteDefinition\n): definition is AppPageRouteDefinition {\n return definition.kind === RouteKind.APP_PAGE\n}\n"],"names":["isAppPageRouteDefinition","definition","kind","RouteKind","APP_PAGE"],"mappings":";;;;+BAWgBA;;;eAAAA;;;2BAVU;AAUnB,SAASA,yBACdC,UAA2B;IAE3B,OAAOA,WAAWC,IAAI,KAAKC,oBAAS,CAACC,QAAQ;AAC/C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/app-route-route-definition.d.ts b/e-commerce/node_modules/next/dist/server/route-definitions/app-route-route-definition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..95de92fe7c89f9fac71ea62cadd64248e17eee6c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/app-route-route-definition.d.ts @@ -0,0 +1,4 @@ +import type { RouteKind } from '../route-kind'; +import type { RouteDefinition } from './route-definition'; +export interface AppRouteRouteDefinition extends RouteDefinition { +} diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/app-route-route-definition.js b/e-commerce/node_modules/next/dist/server/route-definitions/app-route-route-definition.js new file mode 100644 index 0000000000000000000000000000000000000000..892841d6372125148c5aa78df4091dad10b702aa --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/app-route-route-definition.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=app-route-route-definition.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/app-route-route-definition.js.map b/e-commerce/node_modules/next/dist/server/route-definitions/app-route-route-definition.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/app-route-route-definition.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/locale-route-definition.d.ts b/e-commerce/node_modules/next/dist/server/route-definitions/locale-route-definition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..673f995a6fb4ae60f2f2b3aa8133705d27de81de --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/locale-route-definition.d.ts @@ -0,0 +1,15 @@ +import type { RouteDefinition } from './route-definition'; +import type { RouteKind } from '../route-kind'; +export interface LocaleRouteDefinition extends RouteDefinition { + /** + * When defined it means that this route is locale aware. When undefined, + * it means no special handling has to occur to process locales. + */ + i18n?: { + /** + * Describes the locale for the route. If this is undefined, then it + * indicates that this route can handle _any_ locale. + */ + locale?: string; + }; +} diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/locale-route-definition.js b/e-commerce/node_modules/next/dist/server/route-definitions/locale-route-definition.js new file mode 100644 index 0000000000000000000000000000000000000000..23737e0ade52f757ae6ccc5285b0eded65ab933e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/locale-route-definition.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=locale-route-definition.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/locale-route-definition.js.map b/e-commerce/node_modules/next/dist/server/route-definitions/locale-route-definition.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/locale-route-definition.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/pages-api-route-definition.d.ts b/e-commerce/node_modules/next/dist/server/route-definitions/pages-api-route-definition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1005dc8a7932171b3c4ee7f3d281c3a00889616 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/pages-api-route-definition.d.ts @@ -0,0 +1,4 @@ +import type { RouteKind } from '../route-kind'; +import type { LocaleRouteDefinition } from './locale-route-definition'; +export interface PagesAPIRouteDefinition extends LocaleRouteDefinition { +} diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/pages-api-route-definition.js b/e-commerce/node_modules/next/dist/server/route-definitions/pages-api-route-definition.js new file mode 100644 index 0000000000000000000000000000000000000000..5686a7a91d71d2bc0dce2e559fb18ce55e8f2739 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/pages-api-route-definition.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=pages-api-route-definition.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/pages-api-route-definition.js.map b/e-commerce/node_modules/next/dist/server/route-definitions/pages-api-route-definition.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/pages-api-route-definition.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/pages-route-definition.d.ts b/e-commerce/node_modules/next/dist/server/route-definitions/pages-route-definition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..494969fcfa51867315e777a8f1ce6948f8b63e74 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/pages-route-definition.d.ts @@ -0,0 +1,4 @@ +import type { LocaleRouteDefinition } from './locale-route-definition'; +import type { RouteKind } from '../route-kind'; +export interface PagesRouteDefinition extends LocaleRouteDefinition { +} diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/pages-route-definition.js b/e-commerce/node_modules/next/dist/server/route-definitions/pages-route-definition.js new file mode 100644 index 0000000000000000000000000000000000000000..cb8294319c604453012aaa896aaa384afd929d85 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/pages-route-definition.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=pages-route-definition.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/pages-route-definition.js.map b/e-commerce/node_modules/next/dist/server/route-definitions/pages-route-definition.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/pages-route-definition.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/route-definition.d.ts b/e-commerce/node_modules/next/dist/server/route-definitions/route-definition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ece0fb37afef42ddbb10c125f46d099a1b6a0bea --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/route-definition.d.ts @@ -0,0 +1,16 @@ +import type { RouteKind } from '../route-kind'; +export interface RouteDefinition { + readonly kind: K; + readonly bundlePath: string; + readonly filename: string; + /** + * Describes the pathname including all internal modifiers such as + * intercepting routes, parallel routes and route/page suffixes that are not + * part of the pathname. + */ + readonly page: string; + /** + * The pathname (including dynamic placeholders) for a route to resolve. + */ + readonly pathname: string; +} diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/route-definition.js b/e-commerce/node_modules/next/dist/server/route-definitions/route-definition.js new file mode 100644 index 0000000000000000000000000000000000000000..873a6cd992d18a34c9be96f8bc340a1b8a0c8e17 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/route-definition.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=route-definition.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-definitions/route-definition.js.map b/e-commerce/node_modules/next/dist/server/route-definitions/route-definition.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-definitions/route-definition.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-kind.d.ts b/e-commerce/node_modules/next/dist/server/route-kind.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a787d2e487cf2e46f7e6cb5bdee010c9707394b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-kind.d.ts @@ -0,0 +1,24 @@ +export declare const enum RouteKind { + /** + * `PAGES` represents all the React pages that are under `pages/`. + */ + PAGES = "PAGES", + /** + * `PAGES_API` represents all the API routes under `pages/api/`. + */ + PAGES_API = "PAGES_API", + /** + * `APP_PAGE` represents all the React pages that are under `app/` with the + * filename of `page.{j,t}s{,x}`. + */ + APP_PAGE = "APP_PAGE", + /** + * `APP_ROUTE` represents all the API routes and metadata routes that are under `app/` with the + * filename of `route.{j,t}s{,x}`. + */ + APP_ROUTE = "APP_ROUTE", + /** + * `IMAGE` represents all the images that are generated by `next/image`. + */ + IMAGE = "IMAGE" +} diff --git a/e-commerce/node_modules/next/dist/server/route-kind.js b/e-commerce/node_modules/next/dist/server/route-kind.js new file mode 100644 index 0000000000000000000000000000000000000000..6a352c27ba380db216d0a286a5bce684b8875a33 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-kind.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "RouteKind", { + enumerable: true, + get: function() { + return RouteKind; + } +}); +var RouteKind = /*#__PURE__*/ function(RouteKind) { + /** + * `PAGES` represents all the React pages that are under `pages/`. + */ RouteKind["PAGES"] = "PAGES"; + /** + * `PAGES_API` represents all the API routes under `pages/api/`. + */ RouteKind["PAGES_API"] = "PAGES_API"; + /** + * `APP_PAGE` represents all the React pages that are under `app/` with the + * filename of `page.{j,t}s{,x}`. + */ RouteKind["APP_PAGE"] = "APP_PAGE"; + /** + * `APP_ROUTE` represents all the API routes and metadata routes that are under `app/` with the + * filename of `route.{j,t}s{,x}`. + */ RouteKind["APP_ROUTE"] = "APP_ROUTE"; + /** + * `IMAGE` represents all the images that are generated by `next/image`. + */ RouteKind["IMAGE"] = "IMAGE"; + return RouteKind; +}({}); + +//# sourceMappingURL=route-kind.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-kind.js.map b/e-commerce/node_modules/next/dist/server/route-kind.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ee38f9e50ab94ed7d9ddc2c32bab44e3e9f2b07f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-kind.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/route-kind.ts"],"sourcesContent":["export const enum RouteKind {\n /**\n * `PAGES` represents all the React pages that are under `pages/`.\n */\n PAGES = 'PAGES',\n /**\n * `PAGES_API` represents all the API routes under `pages/api/`.\n */\n PAGES_API = 'PAGES_API',\n /**\n * `APP_PAGE` represents all the React pages that are under `app/` with the\n * filename of `page.{j,t}s{,x}`.\n */\n APP_PAGE = 'APP_PAGE',\n /**\n * `APP_ROUTE` represents all the API routes and metadata routes that are under `app/` with the\n * filename of `route.{j,t}s{,x}`.\n */\n APP_ROUTE = 'APP_ROUTE',\n\n /**\n * `IMAGE` represents all the images that are generated by `next/image`.\n */\n IMAGE = 'IMAGE',\n}\n"],"names":["RouteKind"],"mappings":";;;;+BAAkBA;;;eAAAA;;;AAAX,IAAA,AAAWA,mCAAAA;IAChB;;GAEC;IAED;;GAEC;IAED;;;GAGC;IAED;;;GAGC;IAGD;;GAEC;WAtBeA","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/app-page-route-match.d.ts b/e-commerce/node_modules/next/dist/server/route-matches/app-page-route-match.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a35a01952b7bd654dc642ca5230c1f74b4ece3ee --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/app-page-route-match.d.ts @@ -0,0 +1,4 @@ +import type { RouteMatch } from './route-match'; +import type { AppPageRouteDefinition } from '../route-definitions/app-page-route-definition'; +export interface AppPageRouteMatch extends RouteMatch { +} diff --git a/e-commerce/node_modules/next/dist/server/route-matches/app-page-route-match.js b/e-commerce/node_modules/next/dist/server/route-matches/app-page-route-match.js new file mode 100644 index 0000000000000000000000000000000000000000..8c1220c87accd14f9202976272feabcf94809868 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/app-page-route-match.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=app-page-route-match.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/app-page-route-match.js.map b/e-commerce/node_modules/next/dist/server/route-matches/app-page-route-match.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/app-page-route-match.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/app-route-route-match.d.ts b/e-commerce/node_modules/next/dist/server/route-matches/app-route-route-match.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..411a8d698a269747a73f9de26834014865641d7b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/app-route-route-match.d.ts @@ -0,0 +1,4 @@ +import type { RouteMatch } from './route-match'; +import type { AppRouteRouteDefinition } from '../route-definitions/app-route-route-definition'; +export interface AppRouteRouteMatch extends RouteMatch { +} diff --git a/e-commerce/node_modules/next/dist/server/route-matches/app-route-route-match.js b/e-commerce/node_modules/next/dist/server/route-matches/app-route-route-match.js new file mode 100644 index 0000000000000000000000000000000000000000..3b7590d93556fb23823210002ccb5791085b7872 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/app-route-route-match.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=app-route-route-match.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/app-route-route-match.js.map b/e-commerce/node_modules/next/dist/server/route-matches/app-route-route-match.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/app-route-route-match.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/locale-route-match.d.ts b/e-commerce/node_modules/next/dist/server/route-matches/locale-route-match.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..132869375def952245855fda3731809b709be410 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/locale-route-match.d.ts @@ -0,0 +1,5 @@ +import type { LocaleRouteDefinition } from '../route-definitions/locale-route-definition'; +import type { RouteMatch } from './route-match'; +export interface LocaleRouteMatch extends RouteMatch { + readonly detectedLocale?: string; +} diff --git a/e-commerce/node_modules/next/dist/server/route-matches/locale-route-match.js b/e-commerce/node_modules/next/dist/server/route-matches/locale-route-match.js new file mode 100644 index 0000000000000000000000000000000000000000..7428821de8d1d0fed5524a50b3467a6cc72ace00 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/locale-route-match.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=locale-route-match.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/locale-route-match.js.map b/e-commerce/node_modules/next/dist/server/route-matches/locale-route-match.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/locale-route-match.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/pages-api-route-match.d.ts b/e-commerce/node_modules/next/dist/server/route-matches/pages-api-route-match.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dfe6181bb5be7797608ba229a6dcdf0478a7ab04 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/pages-api-route-match.d.ts @@ -0,0 +1,10 @@ +import type { RouteMatch } from './route-match'; +import type { PagesAPIRouteDefinition } from '../route-definitions/pages-api-route-definition'; +export interface PagesAPIRouteMatch extends RouteMatch { +} +/** + * Checks if the given match is a Pages API route match. + * @param match the match to check + * @returns true if the match is a Pages API route match, false otherwise + */ +export declare function isPagesAPIRouteMatch(match: RouteMatch): match is PagesAPIRouteMatch; diff --git a/e-commerce/node_modules/next/dist/server/route-matches/pages-api-route-match.js b/e-commerce/node_modules/next/dist/server/route-matches/pages-api-route-match.js new file mode 100644 index 0000000000000000000000000000000000000000..6b10e3781bb3437e18532eedc38af033c3be2e38 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/pages-api-route-match.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isPagesAPIRouteMatch", { + enumerable: true, + get: function() { + return isPagesAPIRouteMatch; + } +}); +const _routekind = require("../route-kind"); +function isPagesAPIRouteMatch(match) { + return match.definition.kind === _routekind.RouteKind.PAGES_API; +} + +//# sourceMappingURL=pages-api-route-match.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/pages-api-route-match.js.map b/e-commerce/node_modules/next/dist/server/route-matches/pages-api-route-match.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a16d01cddc356769bb7d5f3852d9db1d419a0210 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/pages-api-route-match.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/route-matches/pages-api-route-match.ts"],"sourcesContent":["import type { RouteMatch } from './route-match'\nimport type { PagesAPIRouteDefinition } from '../route-definitions/pages-api-route-definition'\n\nimport { RouteKind } from '../route-kind'\n\nexport interface PagesAPIRouteMatch\n extends RouteMatch {}\n\n/**\n * Checks if the given match is a Pages API route match.\n * @param match the match to check\n * @returns true if the match is a Pages API route match, false otherwise\n */\nexport function isPagesAPIRouteMatch(\n match: RouteMatch\n): match is PagesAPIRouteMatch {\n return match.definition.kind === RouteKind.PAGES_API\n}\n"],"names":["isPagesAPIRouteMatch","match","definition","kind","RouteKind","PAGES_API"],"mappings":";;;;+BAagBA;;;eAAAA;;;2BAVU;AAUnB,SAASA,qBACdC,KAAiB;IAEjB,OAAOA,MAAMC,UAAU,CAACC,IAAI,KAAKC,oBAAS,CAACC,SAAS;AACtD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/pages-route-match.d.ts b/e-commerce/node_modules/next/dist/server/route-matches/pages-route-match.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a182eb699a653cf21822d10db5c18d686ef60502 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/pages-route-match.d.ts @@ -0,0 +1,4 @@ +import type { PagesRouteDefinition } from '../route-definitions/pages-route-definition'; +import type { LocaleRouteMatch } from './locale-route-match'; +export interface PagesRouteMatch extends LocaleRouteMatch { +} diff --git a/e-commerce/node_modules/next/dist/server/route-matches/pages-route-match.js b/e-commerce/node_modules/next/dist/server/route-matches/pages-route-match.js new file mode 100644 index 0000000000000000000000000000000000000000..576780c6b3b647411aa456bdc7beecf5365e0a3a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/pages-route-match.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=pages-route-match.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/pages-route-match.js.map b/e-commerce/node_modules/next/dist/server/route-matches/pages-route-match.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/pages-route-match.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/route-match.d.ts b/e-commerce/node_modules/next/dist/server/route-matches/route-match.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..891ae78b4d6684bb002bb061d92e4c315d721231 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/route-match.d.ts @@ -0,0 +1,15 @@ +import type { Params } from '../request/params'; +import type { RouteDefinition } from '../route-definitions/route-definition'; +/** + * RouteMatch is the resolved match for a given request. This will contain all + * the dynamic parameters used for this route. + */ +export interface RouteMatch { + readonly definition: D; + /** + * params when provided are the dynamic route parameters that were parsed from + * the incoming request pathname. If a route match is returned without any + * params, it should be considered a static route. + */ + readonly params: Params | undefined; +} diff --git a/e-commerce/node_modules/next/dist/server/route-matches/route-match.js b/e-commerce/node_modules/next/dist/server/route-matches/route-match.js new file mode 100644 index 0000000000000000000000000000000000000000..36ddf21bf4fe69bceac4c61dee2ce4188153412e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/route-match.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=route-match.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-matches/route-match.js.map b/e-commerce/node_modules/next/dist/server/route-matches/route-match.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-matches/route-match.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/dev-render-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/dev-render-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6ea6c88929bfd118e0e7d5fcefbe47ae15ce1e9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/dev-render-context.d.ts @@ -0,0 +1,5 @@ +import { type NextIncomingMessage } from '../../request-meta'; +import type { ServerComponentsHmrCache } from '../../response-cache'; +import type { DevRenderContext } from './module'; +/** Capture HMR inputs at the App Page handler boundary in dev. */ +export declare function createDevRenderContext(req: NextIncomingMessage, hmrCacheFallback?: ServerComponentsHmrCache): DevRenderContext | undefined; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/dev-render-context.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/dev-render-context.js new file mode 100644 index 0000000000000000000000000000000000000000..e1dd6e9157dce93b7bd47c259d31aa3aae873736 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/dev-render-context.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "createDevRenderContext", { + enumerable: true, + get: function() { + return createDevRenderContext; + } +}); +const _requestmeta = require("../../request-meta"); +function createDevRenderContext(req, hmrCacheFallback) { + if (!process.env.__NEXT_DEV_SERVER) { + return undefined; + } + const { serverComponentsHmrCache, hmrRefreshHash } = (0, _requestmeta.getRequestMeta)(req); + return { + serverComponentsHmrCache: serverComponentsHmrCache ?? hmrCacheFallback, + hmrRefreshHash + }; +} + +//# sourceMappingURL=dev-render-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/dev-render-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/dev-render-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..693381fe916f6370d87aebeb27bc8e83ba26da9a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/dev-render-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/app-page/dev-render-context.ts"],"sourcesContent":["import { getRequestMeta, type NextIncomingMessage } from '../../request-meta'\nimport type { ServerComponentsHmrCache } from '../../response-cache'\nimport type { DevRenderContext } from './module'\n\n/** Capture HMR inputs at the App Page handler boundary in dev. */\nexport function createDevRenderContext(\n req: NextIncomingMessage,\n hmrCacheFallback?: ServerComponentsHmrCache\n): DevRenderContext | undefined {\n if (!process.env.__NEXT_DEV_SERVER) {\n return undefined\n }\n\n const { serverComponentsHmrCache, hmrRefreshHash } = getRequestMeta(req)\n return {\n serverComponentsHmrCache: serverComponentsHmrCache ?? hmrCacheFallback,\n hmrRefreshHash,\n }\n}\n"],"names":["createDevRenderContext","req","hmrCacheFallback","process","env","__NEXT_DEV_SERVER","undefined","serverComponentsHmrCache","hmrRefreshHash","getRequestMeta"],"mappings":";;;;+BAKgBA;;;eAAAA;;;6BALyC;AAKlD,SAASA,uBACdC,GAAwB,EACxBC,gBAA2C;IAE3C,IAAI,CAACC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAOC;IACT;IAEA,MAAM,EAAEC,wBAAwB,EAAEC,cAAc,EAAE,GAAGC,IAAAA,2BAAc,EAACR;IACpE,OAAO;QACLM,0BAA0BA,4BAA4BL;QACtDM;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/helpers/prerender-manifest-matcher.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/helpers/prerender-manifest-matcher.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eeea4a4d5a53c0e291ca29fb13963657c99abc1a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/helpers/prerender-manifest-matcher.d.ts @@ -0,0 +1,23 @@ +import type { DynamicPrerenderManifestRoute, PrerenderManifest } from '../../../../build'; +import type { DeepReadonly } from '../../../../shared/lib/deep-readonly'; +export type PrerenderManifestMatch = { + source: string; + route: DeepReadonly; +}; +/** + * A matcher for the prerender manifest. + * + * This class is used to match the pathname to the dynamic route. + */ +export declare class PrerenderManifestMatcher { + private readonly matchers; + constructor(pathname: string, prerenderManifest: DeepReadonly); + /** + * Match the pathname to the dynamic route. If no match is found, an error is + * thrown. + * + * @param pathname - The pathname to match. + * @returns The dynamic route that matches the pathname. + */ + match(pathname: string): PrerenderManifestMatch | null; +} diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/helpers/prerender-manifest-matcher.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/helpers/prerender-manifest-matcher.js new file mode 100644 index 0000000000000000000000000000000000000000..a280e9bc1740960f432e4e45178678ebd7e2ea92 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/helpers/prerender-manifest-matcher.js @@ -0,0 +1,52 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "PrerenderManifestMatcher", { + enumerable: true, + get: function() { + return PrerenderManifestMatcher; + } +}); +const _routeregex = require("../../../../shared/lib/router/utils/route-regex"); +class PrerenderManifestMatcher { + constructor(pathname, prerenderManifest){ + this.matchers = Object.entries(prerenderManifest.dynamicRoutes).filter(([source, route])=>{ + // If the pathname is a fallback source route, or the source route is + // the same as the pathname, then we should include it in the matchers. + return route.fallbackSourceRoute === pathname || source === pathname; + }).map(([source, route])=>({ + source, + route + })); + } + /** + * Match the pathname to the dynamic route. If no match is found, an error is + * thrown. + * + * @param pathname - The pathname to match. + * @returns The dynamic route that matches the pathname. + */ match(pathname) { + // Iterate over the matchers. They're already in the correct order of + // specificity as they were inserted into the prerender manifest that way + // and iterating over them with Object.entries guarantees that. + for (const matcher of this.matchers){ + // Lazily create the matcher, this is only done once per matcher. + if (!matcher.matcher) { + // The pathname has already been decoded for manifest lookup. We only + // need to check its structure here; extracting captures would decode + // route parameters again and reject literal percent signs. + matcher.matcher = (0, _routeregex.getRouteRegex)(matcher.source).re; + } + if (matcher.matcher.test(pathname)) { + return { + source: matcher.source, + route: matcher.route + }; + } + } + return null; + } +} + +//# sourceMappingURL=prerender-manifest-matcher.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/helpers/prerender-manifest-matcher.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/helpers/prerender-manifest-matcher.js.map new file mode 100644 index 0000000000000000000000000000000000000000..975c9cbc24d086f538e713e4d8ee7750bbce8788 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/helpers/prerender-manifest-matcher.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/route-modules/app-page/helpers/prerender-manifest-matcher.ts"],"sourcesContent":["import type {\n DynamicPrerenderManifestRoute,\n PrerenderManifest,\n} from '../../../../build'\nimport type { DeepReadonly } from '../../../../shared/lib/deep-readonly'\nimport { getRouteRegex } from '../../../../shared/lib/router/utils/route-regex'\n\n/**\n * A matcher for a dynamic route.\n */\ntype Matcher = {\n /**\n * The matcher for the dynamic route. This is lazily created when the matcher\n * is first used.\n */\n matcher?: RegExp\n\n /**\n * The source of the dynamic route.\n */\n source: string\n\n /**\n * The route that matches the source.\n */\n route: DeepReadonly\n}\n\nexport type PrerenderManifestMatch = {\n source: string\n route: DeepReadonly\n}\n\n/**\n * A matcher for the prerender manifest.\n *\n * This class is used to match the pathname to the dynamic route.\n */\nexport class PrerenderManifestMatcher {\n private readonly matchers: Array\n constructor(\n pathname: string,\n prerenderManifest: DeepReadonly\n ) {\n this.matchers = Object.entries(prerenderManifest.dynamicRoutes)\n .filter(([source, route]) => {\n // If the pathname is a fallback source route, or the source route is\n // the same as the pathname, then we should include it in the matchers.\n return route.fallbackSourceRoute === pathname || source === pathname\n })\n .map(([source, route]) => ({ source, route }))\n }\n\n /**\n * Match the pathname to the dynamic route. If no match is found, an error is\n * thrown.\n *\n * @param pathname - The pathname to match.\n * @returns The dynamic route that matches the pathname.\n */\n public match(pathname: string): PrerenderManifestMatch | null {\n // Iterate over the matchers. They're already in the correct order of\n // specificity as they were inserted into the prerender manifest that way\n // and iterating over them with Object.entries guarantees that.\n for (const matcher of this.matchers) {\n // Lazily create the matcher, this is only done once per matcher.\n if (!matcher.matcher) {\n // The pathname has already been decoded for manifest lookup. We only\n // need to check its structure here; extracting captures would decode\n // route parameters again and reject literal percent signs.\n matcher.matcher = getRouteRegex(matcher.source).re\n }\n\n if (matcher.matcher.test(pathname)) {\n return {\n source: matcher.source,\n route: matcher.route,\n }\n }\n }\n\n return null\n }\n}\n"],"names":["PrerenderManifestMatcher","constructor","pathname","prerenderManifest","matchers","Object","entries","dynamicRoutes","filter","source","route","fallbackSourceRoute","map","match","matcher","getRouteRegex","re","test"],"mappings":";;;;+BAsCaA;;;eAAAA;;;4BAjCiB;AAiCvB,MAAMA;IAEXC,YACEC,QAAgB,EAChBC,iBAAkD,CAClD;QACA,IAAI,CAACC,QAAQ,GAAGC,OAAOC,OAAO,CAACH,kBAAkBI,aAAa,EAC3DC,MAAM,CAAC,CAAC,CAACC,QAAQC,MAAM;YACtB,qEAAqE;YACrE,uEAAuE;YACvE,OAAOA,MAAMC,mBAAmB,KAAKT,YAAYO,WAAWP;QAC9D,GACCU,GAAG,CAAC,CAAC,CAACH,QAAQC,MAAM,GAAM,CAAA;gBAAED;gBAAQC;YAAM,CAAA;IAC/C;IAEA;;;;;;GAMC,GACD,AAAOG,MAAMX,QAAgB,EAAiC;QAC5D,qEAAqE;QACrE,yEAAyE;QACzE,+DAA+D;QAC/D,KAAK,MAAMY,WAAW,IAAI,CAACV,QAAQ,CAAE;YACnC,iEAAiE;YACjE,IAAI,CAACU,QAAQA,OAAO,EAAE;gBACpB,qEAAqE;gBACrE,qEAAqE;gBACrE,2DAA2D;gBAC3DA,QAAQA,OAAO,GAAGC,IAAAA,yBAAa,EAACD,QAAQL,MAAM,EAAEO,EAAE;YACpD;YAEA,IAAIF,QAAQA,OAAO,CAACG,IAAI,CAACf,WAAW;gBAClC,OAAO;oBACLO,QAAQK,QAAQL,MAAM;oBACtBC,OAAOI,QAAQJ,KAAK;gBACtB;YACF;QACF;QAEA,OAAO;IACT;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.compiled.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.compiled.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5401340695abe4a87f20f88a898449b7a42edfd6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.compiled.d.ts @@ -0,0 +1 @@ +export * from './module' diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.compiled.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.compiled.js new file mode 100644 index 0000000000000000000000000000000000000000..c4a8ce75fbcc380fe6e068d3a2fd44964bd0a125 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.compiled.js @@ -0,0 +1,36 @@ +"use strict"; +if (process.env.NEXT_RUNTIME === 'edge') { + module.exports = require('next/dist/server/route-modules/app-page/module.js'); +} else { + if (process.env.__NEXT_EXPERIMENTAL_REACT) { + if (process.env.NODE_ENV === 'development') { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/app-page-turbo-experimental.runtime.dev.js'); + } else { + module.exports = require('next/dist/compiled/next-server/app-page-experimental.runtime.dev.js'); + } + } else { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js'); + } else { + module.exports = require('next/dist/compiled/next-server/app-page-experimental.runtime.prod.js'); + } + } + } else { + if (process.env.NODE_ENV === 'development') { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/app-page-turbo.runtime.dev.js'); + } else { + module.exports = require('next/dist/compiled/next-server/app-page.runtime.dev.js'); + } + } else { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/app-page-turbo.runtime.prod.js'); + } else { + module.exports = require('next/dist/compiled/next-server/app-page.runtime.prod.js'); + } + } + } +} + +//# sourceMappingURL=module.compiled.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.compiled.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.compiled.js.map new file mode 100644 index 0000000000000000000000000000000000000000..baa72140e50372451e280163f67fd515f274b00e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.compiled.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/app-page/module.compiled.js"],"sourcesContent":["if (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/app-page/module.js')\n} else {\n if (process.env.__NEXT_EXPERIMENTAL_REACT) {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-page-turbo-experimental.runtime.dev.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/app-page-experimental.runtime.dev.js')\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/app-page-experimental.runtime.prod.js')\n }\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-page-turbo.runtime.dev.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/app-page.runtime.dev.js')\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-page-turbo.runtime.prod.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/app-page.runtime.prod.js')\n }\n }\n }\n}\n"],"names":["process","env","NEXT_RUNTIME","module","exports","require","__NEXT_EXPERIMENTAL_REACT","NODE_ENV","TURBOPACK"],"mappings":";AAAA,IAAIA,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCC,OAAOC,OAAO,GAAGC,QAAQ;AAC3B,OAAO;IACL,IAAIL,QAAQC,GAAG,CAACK,yBAAyB,EAAE;QACzC,IAAIN,QAAQC,GAAG,CAACM,QAAQ,KAAK,eAAe;YAC1C,IAAIP,QAAQC,GAAG,CAACO,SAAS,EAAE;gBACzBL,OAAOC,OAAO,GAAGC,QAAQ;YAC3B,OAAO;gBACLF,OAAOC,OAAO,GAAGC,QAAQ;YAC3B;QACF,OAAO;YACL,IAAIL,QAAQC,GAAG,CAACO,SAAS,EAAE;gBACzBL,OAAOC,OAAO,GAAGC,QAAQ;YAC3B,OAAO;gBACLF,OAAOC,OAAO,GAAGC,QAAQ;YAC3B;QACF;IACF,OAAO;QACL,IAAIL,QAAQC,GAAG,CAACM,QAAQ,KAAK,eAAe;YAC1C,IAAIP,QAAQC,GAAG,CAACO,SAAS,EAAE;gBACzBL,OAAOC,OAAO,GAAGC,QAAQ;YAC3B,OAAO;gBACLF,OAAOC,OAAO,GAAGC,QAAQ;YAC3B;QACF,OAAO;YACL,IAAIL,QAAQC,GAAG,CAACO,SAAS,EAAE;gBACzBL,OAAOC,OAAO,GAAGC,QAAQ;YAC3B,OAAO;gBACLF,OAAOC,OAAO,GAAGC,QAAQ;YAC3B;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..143a62e8b69115f750db3862a23b6d4f1587e5ce --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.d.ts @@ -0,0 +1,76 @@ +import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition'; +import type RenderResult from '../../render-result'; +import type { PrerenderResult } from '../../render-result'; +import type { RenderOpts } from '../../app-render/types'; +import { type NextParsedUrlQuery } from '../../request-meta'; +import type { LoaderTree } from '../../lib/app-dir-module'; +import type { PrerenderManifest } from '../../../build'; +import { prerenderToHTMLOrFlight, 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'; +import * as vendoredContexts from './vendored/contexts/entrypoints'; +import type { BaseNextRequest, BaseNextResponse } from '../../base-http'; +import type { ServerComponentsHmrCache } from '../../response-cache'; +import type { OpaqueFallbackRouteParams } from '../../request/fallback-params'; +import type { DeepReadonly } from '../../../shared/lib/deep-readonly'; +import type { ParsedRequestHeaders } from './parse-request-headers'; +import type { UrlWithParsedQuery } from 'url'; +import type { IncomingMessage } from 'http'; +/** + * The AppPageModule is the type of the module exported by the bundled app page + * module. + */ +export type AppPageModule = typeof import('../../../build/templates/app-page'); +type AppPageUserlandModule = { + /** + * The tree created in next-app-loader that holds component segments and modules + */ + loaderTree: LoaderTree; +}; +export type RouteMatch = { + readonly resolvedPathname: string; +}; +/** Live dev-server state captured for a render; absent in production and build prerenders. */ +export type DevRenderContext = { + readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined; + readonly hmrRefreshHash: string | undefined; +}; +export interface AppPageRouteHandlerContext extends RouteModuleHandleContext { + page: string; + routeMatch: RouteMatch; + query: NextParsedUrlQuery; + fallbackRouteParams: OpaqueFallbackRouteParams | null; + renderOpts: RenderOpts; + dev: DevRenderContext | undefined; + parsedRequestHeaders: ParsedRequestHeaders; + sharedContext: AppSharedContext; +} +export type AppPageRouteModuleOptions = RouteModuleOptions; +export declare class AppPageRouteModule extends RouteModule { + private matchers; + match(pathname: string, prerenderManifest: DeepReadonly): import("./helpers/prerender-manifest-matcher").PrerenderManifestMatch | null; + private normalizers; + normalizeUrl(req: IncomingMessage | BaseNextRequest, parsedUrl: UrlWithParsedQuery): false | undefined; + render(req: BaseNextRequest, res: BaseNextResponse, context: AppPageRouteHandlerContext): Promise; + prerender(req: BaseNextRequest, res: BaseNextResponse, context: AppPageRouteHandlerContext): Promise; + /** + * 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 | undefined>; + private pathCouldBeIntercepted; + getVaryHeader(resolvedPathname: string, interceptionRoutePatterns: RegExp[]): string; +} +declare const vendored: { + 'react-rsc': typeof import("./vendored/rsc/entrypoints") | undefined; + 'react-ssr': typeof import("./vendored/ssr/entrypoints") | undefined; + contexts: typeof vendoredContexts; +}; +export { prerenderToHTMLOrFlight, renderToHTMLOrFlight, vendored }; +export default AppPageRouteModule; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.js new file mode 100644 index 0000000000000000000000000000000000000000..c349d2ad740fbe90e3ce0cccfa8863ccf0d60cc8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.js @@ -0,0 +1,188 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + AppPageRouteModule: null, + default: null, + prerenderToHTMLOrFlight: null, + renderToHTMLOrFlight: null, + vendored: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + AppPageRouteModule: function() { + return AppPageRouteModule; + }, + default: function() { + return _default; + }, + prerenderToHTMLOrFlight: function() { + return _apprender.prerenderToHTMLOrFlight; + }, + renderToHTMLOrFlight: function() { + return _apprender.renderToHTMLOrFlight; + }, + vendored: function() { + return vendored; + } +}); +const _requestmeta = require("../../request-meta"); +const _apprender = require("../../app-render/app-render"); +const _routemodule = require("../route-module"); +const _entrypoints = /*#__PURE__*/ _interop_require_wildcard(require("./vendored/contexts/entrypoints")); +const _prerendermanifestmatcher = require("./helpers/prerender-manifest-matcher"); +const _approuterheaders = require("../../../client/components/app-router-headers"); +const _interceptionroutes = require("../../../shared/lib/router/utils/interception-routes"); +const _rsc = require("../../normalizers/request/rsc"); +const _segmentprefixrsc = require("../../normalizers/request/segment-prefix-rsc"); +const _normalizerequesturl = require("./normalize-request-url"); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +let vendoredReactRSC; +let vendoredReactSSR; +// the vendored Reacts are loaded from their original source in the edge runtime +if (process.env.NEXT_RUNTIME !== 'edge') { + vendoredReactRSC = require('./vendored/rsc/entrypoints'); + vendoredReactSSR = require('./vendored/ssr/entrypoints'); + // In Node environments we need to access the correct React instance from external modules such + // as global patches. We register the loaded React instances here. + const { registerServerReact, registerClientReact } = require('../../runtime-reacts.external'); + registerServerReact(vendoredReactRSC.React); + registerClientReact(vendoredReactSSR.React); +} +class AppPageRouteModule extends _routemodule.RouteModule { + match(pathname, prerenderManifest) { + // Lazily create the matcher based on the provided prerender manifest. + let matcher = this.matchers.get(prerenderManifest); + if (!matcher) { + matcher = new _prerendermanifestmatcher.PrerenderManifestMatcher(this.definition.pathname, prerenderManifest); + this.matchers.set(prerenderManifest, matcher); + } + // Match the pathname to the dynamic route. + return matcher.match(pathname); + } + normalizeUrl(req, parsedUrl) { + if (this.normalizers.segmentPrefetchRSC.match(parsedUrl.pathname || '/')) { + const result = this.normalizers.segmentPrefetchRSC.extract(parsedUrl.pathname || '/'); + if (!result) return false; + const { originalPathname, segmentPath } = result; + parsedUrl.pathname = originalPathname; + // Mark the request as a router prefetch request. + req.headers[_approuterheaders.RSC_HEADER] = '1'; + req.headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER] = '1'; + req.headers[_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath; + (0, _requestmeta.addRequestMeta)(req, 'isRSCRequest', true); + (0, _requestmeta.addRequestMeta)(req, 'isPrefetchRSCRequest', true); + (0, _requestmeta.addRequestMeta)(req, 'segmentPrefetchRSCRequest', segmentPath); + } else if (this.normalizers.rsc.match(parsedUrl.pathname || '/')) { + parsedUrl.pathname = this.normalizers.rsc.normalize(parsedUrl.pathname || '/', true); + // Mark the request as a RSC request. + req.headers[_approuterheaders.RSC_HEADER] = '1'; + } else { + super.normalizeUrl(req, parsedUrl); + } + // Minimal adapters can bypass base-server request normalization and invoke + // route modules directly, so derive RSC/prefetch metadata from headers. + (0, _normalizerequesturl.applyAppPageRscRequestMetaFromHeaders)(req); + (0, _normalizerequesturl.normalizeAppPageRequestUrl)(req, parsedUrl.pathname || '/'); + } + render(req, res, context) { + return (0, _apprender.renderToHTMLOrFlight)(req, res, context.page, context.query, context.fallbackRouteParams, // HEAD responses do not consume the render stream, so they cannot + // establish a new status for the dev indicator. + process.env.__NEXT_DEV_SERVER && req.method === 'HEAD' ? { + ...context.renderOpts, + setIsrStatus: undefined + } : context.renderOpts, context.dev, context.sharedContext, context.routeMatch, context.parsedRequestHeaders); + } + prerender(req, res, context) { + return (0, _apprender.prerenderToHTMLOrFlight)(req, res, context.page, context.query, context.fallbackRouteParams, context.renderOpts, undefined, context.sharedContext, context.routeMatch, context.parsedRequestHeaders); + } + /** + * 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) { + return (0, _interceptionroutes.isInterceptionRouteAppPath)(resolvedPathname) || interceptionRoutePatterns.some((regexp)=>{ + return regexp.test(resolvedPathname); + }); + } + getVaryHeader(resolvedPathname, interceptionRoutePatterns) { + const baseVaryHeader = `${_approuterheaders.RSC_HEADER}, ${_approuterheaders.NEXT_ROUTER_STATE_TREE_HEADER}, ${_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER}, ${_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`; + if (this.pathCouldBeIntercepted(resolvedPathname, interceptionRoutePatterns)) { + // Interception route responses can vary based on the `Next-URL` header. + // We use the Vary header to signal this behavior to the client to properly cache the response. + return `${baseVaryHeader}, ${_approuterheaders.NEXT_URL}`; + } else { + // We don't need to include `Next-URL` in the Vary header for non-interception routes since it won't affect the response. + // We also set this header for pages to avoid caching issues when navigating between pages and app. + return baseVaryHeader; + } + } + constructor(...args){ + super(...args), this.matchers = new WeakMap(), this.normalizers = { + rsc: new _rsc.RSCPathnameNormalizer(), + segmentPrefetchRSC: new _segmentprefixrsc.SegmentPrefixRSCPathnameNormalizer() + }; + } +} +const vendored = { + 'react-rsc': vendoredReactRSC, + 'react-ssr': vendoredReactSSR, + contexts: _entrypoints +}; +const _default = AppPageRouteModule; + +//# sourceMappingURL=module.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1b849f6e0aae4e73a6ebc3230c902f498dd33f14 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.js.map @@ -0,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 { PrerenderResult } 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 prerenderToHTMLOrFlight,\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 type { ParsedRequestHeaders } from './parse-request-headers'\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 type RouteMatch = {\n // The pathname produced by route preparation, including its delimiter-safe\n // encoding for path parameters.\n readonly resolvedPathname: string\n}\n\n/** Live dev-server state captured for a render; absent in production and build prerenders. */\nexport type DevRenderContext = {\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly hmrRefreshHash: string | undefined\n}\n\nexport interface AppPageRouteHandlerContext extends RouteModuleHandleContext {\n page: string\n routeMatch: RouteMatch\n query: NextParsedUrlQuery\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n renderOpts: RenderOpts\n dev: DevRenderContext | undefined\n parsedRequestHeaders: ParsedRequestHeaders\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,\n PrerenderManifestMatcher\n >()\n public match(\n pathname: string,\n prerenderManifest: DeepReadonly\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 {\n return renderToHTMLOrFlight(\n req,\n res,\n context.page,\n context.query,\n context.fallbackRouteParams,\n // HEAD responses do not consume the render stream, so they cannot\n // establish a new status for the dev indicator.\n process.env.__NEXT_DEV_SERVER && req.method === 'HEAD'\n ? { ...context.renderOpts, setIsrStatus: undefined }\n : context.renderOpts,\n context.dev,\n context.sharedContext,\n context.routeMatch,\n context.parsedRequestHeaders\n )\n }\n\n public prerender(\n req: BaseNextRequest,\n res: BaseNextResponse,\n context: AppPageRouteHandlerContext\n ): Promise {\n return prerenderToHTMLOrFlight(\n req,\n res,\n context.page,\n context.query,\n context.fallbackRouteParams,\n context.renderOpts,\n undefined,\n context.sharedContext,\n context.routeMatch,\n context.parsedRequestHeaders\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 | 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 { prerenderToHTMLOrFlight, renderToHTMLOrFlight, vendored }\n\nexport default AppPageRouteModule\n"],"names":["AppPageRouteModule","prerenderToHTMLOrFlight","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","__NEXT_DEV_SERVER","method","renderOpts","setIsrStatus","undefined","dev","sharedContext","routeMatch","parsedRequestHeaders","prerender","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":";;;;;;;;;;;;;;;;;;IAuGaA,kBAAkB;eAAlBA;;IA0Kb,OAAiC;eAAjC;;IAFSC,uBAAuB;eAAvBA,kCAAuB;;IAAEC,oBAAoB;eAApBA,+BAAoB;;IAAEC,QAAQ;eAARA;;;6BA3QA;2BASjD;6BAMA;qEAC2B;0CAIO;kCASlC;oCACoC;qBACL;kCACa;qCAM5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEP,IAAIC;AACJ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mC,EACnCC,WAAwB,EACa;QACrC,OAAOC,IAAAA,yCAA8B,EAACF,SAASD,cAAcE;IAC/D;IAEQE,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,GAAGrC,4BAAU,CAAC,EAAE,EAAEsC,+CAA6B,CAAC,EAAE,EAAErC,6CAA2B,CAAC,EAAE,EAAEC,qDAAmC,EAAE;QAEhJ,IACE,IAAI,CAAC2B,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;;QA/JK,qBAIGpD,WAAW,IAAIuD,gBAsBf/C,cAAc;YACpBW,KAAK,IAAIqC,0BAAqB;YAC9B/C,oBAAoB,IAAIgD,oDAAkC;QAC5D;;AAmIF;AAEA,MAAMxE,WAAW;IACf,aAAaC;IACb,aAAaC;IACbuE,UAAUC;AACZ;MAIA,WAAe7E","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.render.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.render.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..67fb0aebcab809e83f390744d5e8d47b958c1bac --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.render.d.ts @@ -0,0 +1,3 @@ +import type { AppPagePrerender, AppPageRender } from '../../app-render/app-render'; +export declare const lazyRenderAppPage: AppPageRender; +export declare const lazyPrerenderAppPage: AppPagePrerender; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.render.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.render.js new file mode 100644 index 0000000000000000000000000000000000000000..eb34ffa2913e49e4def0588e4d55e8f5964d3935 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.render.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + lazyPrerenderAppPage: null, + lazyRenderAppPage: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + lazyPrerenderAppPage: function() { + return lazyPrerenderAppPage; + }, + lazyRenderAppPage: function() { + return lazyRenderAppPage; + } +}); +function getAppPageModule() { + if (process.env.NEXT_MINIMAL) { + throw new Error("Can't use lazyRenderAppPage in minimal mode"); + } else { + return require('./module.compiled'); + } +} +const lazyRenderAppPage = (...args)=>{ + const render = getAppPageModule().renderToHTMLOrFlight; + return render(...args); +}; +const lazyPrerenderAppPage = (...args)=>{ + const prerender = getAppPageModule().prerenderToHTMLOrFlight; + return prerender(...args); +}; + +//# sourceMappingURL=module.render.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.render.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.render.js.map new file mode 100644 index 0000000000000000000000000000000000000000..566b0e49f3e7d9c5ab16abb6c43b58b4a1b9221c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/module.render.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/app-page/module.render.ts"],"sourcesContent":["import type {\n AppPagePrerender,\n AppPageRender,\n} from '../../app-render/app-render'\n\nfunction getAppPageModule(): typeof import('./module.compiled') {\n if (process.env.NEXT_MINIMAL) {\n throw new Error(\"Can't use lazyRenderAppPage in minimal mode\")\n } else {\n return require('./module.compiled') as typeof import('./module.compiled')\n }\n}\n\nexport const lazyRenderAppPage: AppPageRender = (...args) => {\n const render: AppPageRender = getAppPageModule().renderToHTMLOrFlight\n return render(...args)\n}\n\nexport const lazyPrerenderAppPage: AppPagePrerender = (...args) => {\n const prerender: AppPagePrerender = getAppPageModule().prerenderToHTMLOrFlight\n return prerender(...args)\n}\n"],"names":["lazyPrerenderAppPage","lazyRenderAppPage","getAppPageModule","process","env","NEXT_MINIMAL","Error","require","args","render","renderToHTMLOrFlight","prerender","prerenderToHTMLOrFlight"],"mappings":";;;;;;;;;;;;;;;IAkBaA,oBAAoB;eAApBA;;IALAC,iBAAiB;eAAjBA;;;AARb,SAASC;IACP,IAAIC,QAAQC,GAAG,CAACC,YAAY,EAAE;QAC5B,MAAM,IAAIC,MAAM;IAClB,OAAO;QACL,OAAOC,QAAQ;IACjB;AACF;AAEO,MAAMN,oBAAmC,CAAC,GAAGO;IAClD,MAAMC,SAAwBP,mBAAmBQ,oBAAoB;IACrE,OAAOD,UAAUD;AACnB;AAEO,MAAMR,uBAAyC,CAAC,GAAGQ;IACxD,MAAMG,YAA8BT,mBAAmBU,uBAAuB;IAC9E,OAAOD,aAAaH;AACtB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/normalize-request-url.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/normalize-request-url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..90d7452609b694a913f058a40e1193ac5c72ddbe --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/normalize-request-url.d.ts @@ -0,0 +1,4 @@ +import type { IncomingMessage } from 'http'; +import type { BaseNextRequest } from '../../base-http'; +export declare function applyAppPageRscRequestMetaFromHeaders(req: Pick): void; +export declare function normalizeAppPageRequestUrl(req: Pick, pathname: string): void; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/normalize-request-url.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/normalize-request-url.js new file mode 100644 index 0000000000000000000000000000000000000000..172be22b81d973fbd3118bf83806271bd581f810 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/normalize-request-url.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + applyAppPageRscRequestMetaFromHeaders: null, + normalizeAppPageRequestUrl: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + applyAppPageRscRequestMetaFromHeaders: function() { + return applyAppPageRscRequestMetaFromHeaders; + }, + normalizeAppPageRequestUrl: function() { + return normalizeAppPageRequestUrl; + } +}); +const _approuterheaders = require("../../../client/components/app-router-headers"); +const _isrscrequest = require("../../lib/is-rsc-request"); +const _url = require("../../../lib/url"); +const _formaturl = require("../../../shared/lib/router/utils/format-url"); +const _requestmeta = require("../../request-meta"); +function getHeaderValue(value) { + if (Array.isArray(value)) { + return value[0]; + } + return value; +} +function applyAppPageRscRequestMetaFromHeaders(req) { + const isRscRequest = (0, _isrscrequest.isRSCRequestHeader)(req.headers[_approuterheaders.RSC_HEADER]); + if (!isRscRequest) { + return; + } + (0, _requestmeta.addRequestMeta)(req, 'isRSCRequest', true); + const isPrefetchRequest = getHeaderValue(req.headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER]) === '1'; + if (!isPrefetchRequest) { + return; + } + (0, _requestmeta.addRequestMeta)(req, 'isPrefetchRSCRequest', true); + const segmentPrefetchPath = getHeaderValue(req.headers[_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]); + if (segmentPrefetchPath) { + (0, _requestmeta.addRequestMeta)(req, 'segmentPrefetchRSCRequest', segmentPrefetchPath); + } +} +function normalizeAppPageRequestUrl(req, pathname) { + if (!req.url) { + return; + } + const normalizedUrl = (0, _url.parseReqUrl)(req.url); + if (!normalizedUrl) { + return; + } + normalizedUrl.pathname = pathname; + req.url = (0, _formaturl.formatUrl)(normalizedUrl); +} + +//# sourceMappingURL=normalize-request-url.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/normalize-request-url.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/normalize-request-url.js.map new file mode 100644 index 0000000000000000000000000000000000000000..be29995c83c729b74ab4b3c608e2ae2c52d3fc5c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/normalize-request-url.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/app-page/normalize-request-url.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\n\nimport {\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n RSC_HEADER,\n} from '../../../client/components/app-router-headers'\nimport type { BaseNextRequest } from '../../base-http'\nimport { isRSCRequestHeader } from '../../lib/is-rsc-request'\nimport { parseReqUrl } from '../../../lib/url'\nimport { formatUrl } from '../../../shared/lib/router/utils/format-url'\nimport { addRequestMeta } from '../../request-meta'\n\nfunction getHeaderValue(\n value: string | string[] | undefined\n): string | undefined {\n if (Array.isArray(value)) {\n return value[0]\n }\n return value\n}\n\nexport function applyAppPageRscRequestMetaFromHeaders(\n req: Pick\n): void {\n const isRscRequest = isRSCRequestHeader(req.headers[RSC_HEADER])\n if (!isRscRequest) {\n return\n }\n\n addRequestMeta(req as IncomingMessage, 'isRSCRequest', true)\n\n const isPrefetchRequest =\n getHeaderValue(req.headers[NEXT_ROUTER_PREFETCH_HEADER]) === '1'\n if (!isPrefetchRequest) {\n return\n }\n\n addRequestMeta(req as IncomingMessage, 'isPrefetchRSCRequest', true)\n\n const segmentPrefetchPath = getHeaderValue(\n req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]\n )\n if (segmentPrefetchPath) {\n addRequestMeta(\n req as IncomingMessage,\n 'segmentPrefetchRSCRequest',\n segmentPrefetchPath\n )\n }\n}\n\nexport function normalizeAppPageRequestUrl(\n req: Pick,\n pathname: string\n) {\n if (!req.url) {\n return\n }\n\n const normalizedUrl = parseReqUrl(req.url)\n if (!normalizedUrl) {\n return\n }\n\n normalizedUrl.pathname = pathname\n req.url = formatUrl(normalizedUrl)\n}\n"],"names":["applyAppPageRscRequestMetaFromHeaders","normalizeAppPageRequestUrl","getHeaderValue","value","Array","isArray","req","isRscRequest","isRSCRequestHeader","headers","RSC_HEADER","addRequestMeta","isPrefetchRequest","NEXT_ROUTER_PREFETCH_HEADER","segmentPrefetchPath","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","pathname","url","normalizedUrl","parseReqUrl","formatUrl"],"mappings":";;;;;;;;;;;;;;;IAsBgBA,qCAAqC;eAArCA;;IA8BAC,0BAA0B;eAA1BA;;;kCA9CT;8BAE4B;qBACP;2BACF;6BACK;AAE/B,SAASC,eACPC,KAAoC;IAEpC,IAAIC,MAAMC,OAAO,CAACF,QAAQ;QACxB,OAAOA,KAAK,CAAC,EAAE;IACjB;IACA,OAAOA;AACT;AAEO,SAASH,sCACdM,GAAuD;IAEvD,MAAMC,eAAeC,IAAAA,gCAAkB,EAACF,IAAIG,OAAO,CAACC,4BAAU,CAAC;IAC/D,IAAI,CAACH,cAAc;QACjB;IACF;IAEAI,IAAAA,2BAAc,EAACL,KAAwB,gBAAgB;IAEvD,MAAMM,oBACJV,eAAeI,IAAIG,OAAO,CAACI,6CAA2B,CAAC,MAAM;IAC/D,IAAI,CAACD,mBAAmB;QACtB;IACF;IAEAD,IAAAA,2BAAc,EAACL,KAAwB,wBAAwB;IAE/D,MAAMQ,sBAAsBZ,eAC1BI,IAAIG,OAAO,CAACM,qDAAmC,CAAC;IAElD,IAAID,qBAAqB;QACvBH,IAAAA,2BAAc,EACZL,KACA,6BACAQ;IAEJ;AACF;AAEO,SAASb,2BACdK,GAAmD,EACnDU,QAAgB;IAEhB,IAAI,CAACV,IAAIW,GAAG,EAAE;QACZ;IACF;IAEA,MAAMC,gBAAgBC,IAAAA,gBAAW,EAACb,IAAIW,GAAG;IACzC,IAAI,CAACC,eAAe;QAClB;IACF;IAEAA,cAAcF,QAAQ,GAAGA;IACzBV,IAAIW,GAAG,GAAGG,IAAAA,oBAAS,EAACF;AACtB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/parse-request-headers.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/parse-request-headers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d00c0e0035fc003aa6fea79a4ad483dd1cd6def2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/parse-request-headers.d.ts @@ -0,0 +1,32 @@ +import type { IncomingHttpHeaders } from 'http'; +import type { FlightRouterState } from '../../../shared/lib/app-router-types'; +interface ParseRequestHeadersOptions { + readonly isRoutePPREnabled: boolean; + readonly previewModeId: string | undefined; +} +export interface ParsedRequestHeaders { + /** + * Router state provided from the client-side router. Used to handle rendering + * from the common layout down. This value will be undefined if the request is + * not a client-side navigation request, or if the request is a prefetch + * request. + */ + readonly flightRouterState: FlightRouterState | undefined; + readonly isPrefetchRequest: boolean; + readonly isRuntimePrefetchRequest: boolean; + /** + * App Shell prefetch: a runtime prefetch that the server renders with + * params omitted (any `await params` hangs forever). Produces the + * param-independent shell of the route. Implies isRuntimePrefetchRequest. + */ + readonly isAppShellPrefetchRequest: boolean; + readonly isRouteTreePrefetchRequest: boolean; + readonly isHmrRefresh: boolean; + readonly isRSCRequest: boolean; + readonly nonce: string | undefined; + readonly previouslyRevalidatedTags: string[]; + readonly requestId: string | undefined; + readonly htmlRequestId: string | undefined; +} +export declare function parseRequestHeaders(headers: IncomingHttpHeaders, options: ParseRequestHeadersOptions): ParsedRequestHeaders; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/parse-request-headers.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/parse-request-headers.js new file mode 100644 index 0000000000000000000000000000000000000000..c035284f69e8d2693453a3cdcbf646786c7ff53d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/parse-request-headers.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "parseRequestHeaders", { + enumerable: true, + get: function() { + return parseRequestHeaders; + } +}); +const _approuterheaders = require("../../../client/components/app-router-headers"); +const _isrscrequest = require("../../lib/is-rsc-request"); +const _getscriptnoncefromheader = require("../../app-render/get-script-nonce-from-header"); +const _parseandvalidateflightrouterstate = require("../../app-render/parse-and-validate-flight-router-state"); +const _serverutils = require("../../server-utils"); +function parseRequestHeaders(headers, options) { + const isRSCRequest = (0, _isrscrequest.isRSCRequestHeader)(headers[_approuterheaders.RSC_HEADER]); + // runtime prefetch requests are *not* treated as prefetch requests + // (TODO: this is confusing, we should refactor this to express this better) + const isPrefetchRequest = isRSCRequest && headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER] === '1'; + const isAppShellPrefetchRequest = isRSCRequest && headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER] === '3'; + // App Shell prefetches are a subtype of runtime prefetch — same code path, + // but with less resolved content (omitting link data) + const isRuntimePrefetchRequest = isRSCRequest && (headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER] === '2' || isAppShellPrefetchRequest); + const isHmrRefresh = headers[_approuterheaders.NEXT_HMR_REFRESH_HEADER] !== undefined; + const shouldProvideFlightRouterState = isRSCRequest && (!isPrefetchRequest || !options.isRoutePPREnabled); + const flightRouterState = shouldProvideFlightRouterState ? (0, _parseandvalidateflightrouterstate.parseAndValidateFlightRouterState)(headers[_approuterheaders.NEXT_ROUTER_STATE_TREE_HEADER]) : undefined; + // Checks if this is a prefetch of the Route Tree by the Segment Cache + const isRouteTreePrefetchRequest = isRSCRequest && headers[_approuterheaders.NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] === '/_tree'; + const csp = headers['content-security-policy'] || headers['content-security-policy-report-only']; + const nonce = typeof csp === 'string' ? (0, _getscriptnoncefromheader.getScriptNonceFromHeader)(csp) : undefined; + const previouslyRevalidatedTags = (0, _serverutils.getPreviouslyRevalidatedTags)(headers, options.previewModeId); + let requestId; + let htmlRequestId; + if (process.env.__NEXT_DEV_SERVER) { + // The request IDs are only used for the dev server to send debug + // information to the matching client (identified by the HTML request ID + // that was sent to the client with the HTML document) for the current + // request (identified by the request ID, as defined by the client). + requestId = typeof headers[_approuterheaders.NEXT_REQUEST_ID_HEADER] === 'string' ? headers[_approuterheaders.NEXT_REQUEST_ID_HEADER] : undefined; + htmlRequestId = typeof headers[_approuterheaders.NEXT_HTML_REQUEST_ID_HEADER] === 'string' ? headers[_approuterheaders.NEXT_HTML_REQUEST_ID_HEADER] : undefined; + } + return { + flightRouterState, + isPrefetchRequest, + isRuntimePrefetchRequest, + isAppShellPrefetchRequest, + isRouteTreePrefetchRequest, + isHmrRefresh, + isRSCRequest, + nonce, + previouslyRevalidatedTags, + requestId, + htmlRequestId + }; +} + +//# sourceMappingURL=parse-request-headers.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/parse-request-headers.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/parse-request-headers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3f6f38770bfaab2497ac6bf76d8c7214e6674715 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/parse-request-headers.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/app-page/parse-request-headers.ts"],"sourcesContent":["import type { IncomingHttpHeaders } from 'http'\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport {\n NEXT_HMR_REFRESH_HEADER,\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n RSC_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_REQUEST_ID_HEADER,\n NEXT_HTML_REQUEST_ID_HEADER,\n} from '../../../client/components/app-router-headers'\nimport { isRSCRequestHeader } from '../../lib/is-rsc-request'\nimport { getScriptNonceFromHeader } from '../../app-render/get-script-nonce-from-header'\nimport { parseAndValidateFlightRouterState } from '../../app-render/parse-and-validate-flight-router-state'\nimport { getPreviouslyRevalidatedTags } from '../../server-utils'\n\ninterface ParseRequestHeadersOptions {\n readonly isRoutePPREnabled: boolean\n readonly previewModeId: string | undefined\n}\n\nexport interface ParsedRequestHeaders {\n /**\n * Router state provided from the client-side router. Used to handle rendering\n * from the common layout down. This value will be undefined if the request is\n * not a client-side navigation request, or if the request is a prefetch\n * request.\n */\n readonly flightRouterState: FlightRouterState | undefined\n readonly isPrefetchRequest: boolean\n readonly isRuntimePrefetchRequest: boolean\n /**\n * App Shell prefetch: a runtime prefetch that the server renders with\n * params omitted (any `await params` hangs forever). Produces the\n * param-independent shell of the route. Implies isRuntimePrefetchRequest.\n */\n readonly isAppShellPrefetchRequest: boolean\n readonly isRouteTreePrefetchRequest: boolean\n readonly isHmrRefresh: boolean\n readonly isRSCRequest: boolean\n readonly nonce: string | undefined\n readonly previouslyRevalidatedTags: string[]\n readonly requestId: string | undefined\n readonly htmlRequestId: string | undefined\n}\n\nexport function parseRequestHeaders(\n headers: IncomingHttpHeaders,\n options: ParseRequestHeadersOptions\n): ParsedRequestHeaders {\n const isRSCRequest = isRSCRequestHeader(headers[RSC_HEADER])\n\n // runtime prefetch requests are *not* treated as prefetch requests\n // (TODO: this is confusing, we should refactor this to express this better)\n const isPrefetchRequest =\n isRSCRequest && headers[NEXT_ROUTER_PREFETCH_HEADER] === '1'\n\n const isAppShellPrefetchRequest =\n isRSCRequest && headers[NEXT_ROUTER_PREFETCH_HEADER] === '3'\n\n // App Shell prefetches are a subtype of runtime prefetch — same code path,\n // but with less resolved content (omitting link data)\n const isRuntimePrefetchRequest =\n isRSCRequest &&\n (headers[NEXT_ROUTER_PREFETCH_HEADER] === '2' || isAppShellPrefetchRequest)\n\n const isHmrRefresh = headers[NEXT_HMR_REFRESH_HEADER] !== undefined\n\n const shouldProvideFlightRouterState =\n isRSCRequest && (!isPrefetchRequest || !options.isRoutePPREnabled)\n\n const flightRouterState = shouldProvideFlightRouterState\n ? parseAndValidateFlightRouterState(headers[NEXT_ROUTER_STATE_TREE_HEADER])\n : undefined\n\n // Checks if this is a prefetch of the Route Tree by the Segment Cache\n const isRouteTreePrefetchRequest =\n isRSCRequest && headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] === '/_tree'\n\n const csp =\n headers['content-security-policy'] ||\n headers['content-security-policy-report-only']\n\n const nonce =\n typeof csp === 'string' ? getScriptNonceFromHeader(csp) : undefined\n\n const previouslyRevalidatedTags = getPreviouslyRevalidatedTags(\n headers,\n options.previewModeId\n )\n\n let requestId: string | undefined\n let htmlRequestId: string | undefined\n\n if (process.env.__NEXT_DEV_SERVER) {\n // The request IDs are only used for the dev server to send debug\n // information to the matching client (identified by the HTML request ID\n // that was sent to the client with the HTML document) for the current\n // request (identified by the request ID, as defined by the client).\n\n requestId =\n typeof headers[NEXT_REQUEST_ID_HEADER] === 'string'\n ? headers[NEXT_REQUEST_ID_HEADER]\n : undefined\n\n htmlRequestId =\n typeof headers[NEXT_HTML_REQUEST_ID_HEADER] === 'string'\n ? headers[NEXT_HTML_REQUEST_ID_HEADER]\n : undefined\n }\n\n return {\n flightRouterState,\n isPrefetchRequest,\n isRuntimePrefetchRequest,\n isAppShellPrefetchRequest,\n isRouteTreePrefetchRequest,\n isHmrRefresh,\n isRSCRequest,\n nonce,\n previouslyRevalidatedTags,\n requestId,\n htmlRequestId,\n }\n}\n"],"names":["parseRequestHeaders","headers","options","isRSCRequest","isRSCRequestHeader","RSC_HEADER","isPrefetchRequest","NEXT_ROUTER_PREFETCH_HEADER","isAppShellPrefetchRequest","isRuntimePrefetchRequest","isHmrRefresh","NEXT_HMR_REFRESH_HEADER","undefined","shouldProvideFlightRouterState","isRoutePPREnabled","flightRouterState","parseAndValidateFlightRouterState","NEXT_ROUTER_STATE_TREE_HEADER","isRouteTreePrefetchRequest","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","csp","nonce","getScriptNonceFromHeader","previouslyRevalidatedTags","getPreviouslyRevalidatedTags","previewModeId","requestId","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,KAAK,WACvC9B,OAAO,CAAC8B,wCAAsB,CAAC,GAC/BnB;QAENe,gBACE,OAAO1B,OAAO,CAAC+B,6CAA2B,CAAC,KAAK,WAC5C/B,OAAO,CAAC+B,6CAA2B,CAAC,GACpCpB;IACR;IAEA,OAAO;QACLG;QACAT;QACAG;QACAD;QACAU;QACAR;QACAP;QACAkB;QACAE;QACAG;QACAC;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js new file mode 100644 index 0000000000000000000000000000000000000000..74fa6622e2a5367e88e0b801cd98447f8188c090 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].AppRouterContext; + +//# sourceMappingURL=app-router-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7ac1dfff7df8bdbda1ad2cb735d03939bc594ef8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/contexts/app-router-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].AppRouterContext\n"],"names":["module","exports","require","vendored","AppRouterContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,gBAAgB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/entrypoints.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/entrypoints.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fc5160bc090fa2d7b9ab747ff9497f65162caa7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/entrypoints.d.ts @@ -0,0 +1,6 @@ +export * as HeadManagerContext from '../../../../../shared/lib/head-manager-context.shared-runtime'; +export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-html.shared-runtime'; +export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime'; +export * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime'; +export * as RouterContext from '../../../../../shared/lib/router-context.shared-runtime'; +export * as ImageConfigContext from '../../../../../shared/lib/image-config-context.shared-runtime'; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/entrypoints.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/entrypoints.js new file mode 100644 index 0000000000000000000000000000000000000000..7e21cb42f803ccadf70d6f8becf64e22c5010282 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/entrypoints.js @@ -0,0 +1,87 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + AppRouterContext: null, + HeadManagerContext: null, + HooksClientContext: null, + ImageConfigContext: null, + RouterContext: null, + ServerInsertedHtml: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + AppRouterContext: function() { + return _approutercontextsharedruntime; + }, + HeadManagerContext: function() { + return _headmanagercontextsharedruntime; + }, + HooksClientContext: function() { + return _hooksclientcontextsharedruntime; + }, + ImageConfigContext: function() { + return _imageconfigcontextsharedruntime; + }, + RouterContext: function() { + return _routercontextsharedruntime; + }, + ServerInsertedHtml: function() { + return _serverinsertedhtmlsharedruntime; + } +}); +const _headmanagercontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/head-manager-context.shared-runtime")); +const _serverinsertedhtmlsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/server-inserted-html.shared-runtime")); +const _approutercontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/app-router-context.shared-runtime")); +const _hooksclientcontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/hooks-client-context.shared-runtime")); +const _routercontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/router-context.shared-runtime")); +const _imageconfigcontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/image-config-context.shared-runtime")); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +//# sourceMappingURL=entrypoints.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/entrypoints.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/entrypoints.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2cbbdbb0937cc3c533f23687447140abba6182c9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/entrypoints.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/contexts/entrypoints.ts"],"sourcesContent":["export * as HeadManagerContext from '../../../../../shared/lib/head-manager-context.shared-runtime'\nexport * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-html.shared-runtime'\nexport * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime'\nexport * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime'\nexport * as RouterContext from '../../../../../shared/lib/router-context.shared-runtime'\nexport * as ImageConfigContext from '../../../../../shared/lib/image-config-context.shared-runtime'\n"],"names":["AppRouterContext","HeadManagerContext","HooksClientContext","ImageConfigContext","RouterContext","ServerInsertedHtml"],"mappings":";;;;;;;;;;;;;;;;;;;IAEYA,gBAAgB;;;IAFhBC,kBAAkB;;;IAGlBC,kBAAkB;;;IAElBC,kBAAkB;;;IADlBC,aAAa;;;IAHbC,kBAAkB;;;;yFADM;yFACA;uFACF;yFACE;oFACL;yFACK","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/head-manager-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/head-manager-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/head-manager-context.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/head-manager-context.js new file mode 100644 index 0000000000000000000000000000000000000000..161d1246033466b8eb50881ac6c1631ed89cee36 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/head-manager-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].HeadManagerContext; + +//# sourceMappingURL=head-manager-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/head-manager-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/head-manager-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d418de167979d4a07feddf8de99ff337767c01b3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/head-manager-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/contexts/head-manager-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].HeadManagerContext\n"],"names":["module","exports","require","vendored","HeadManagerContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,kBAAkB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/hooks-client-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/hooks-client-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/hooks-client-context.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/hooks-client-context.js new file mode 100644 index 0000000000000000000000000000000000000000..8a86415fa56106cf614206e4c8ba2256d7125f81 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/hooks-client-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].HooksClientContext; + +//# sourceMappingURL=hooks-client-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/hooks-client-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/hooks-client-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6b9cc6285722ab11cfe5ab9070acebe80f54f2c7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/hooks-client-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/contexts/hooks-client-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].HooksClientContext\n"],"names":["module","exports","require","vendored","HooksClientContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,kBAAkB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/image-config-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/image-config-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/image-config-context.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/image-config-context.js new file mode 100644 index 0000000000000000000000000000000000000000..53255f9b8b07068f9b2363a3bc97d8111a98a492 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/image-config-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].ImageConfigContext; + +//# sourceMappingURL=image-config-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/image-config-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/image-config-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e0f9567a159d75aac61516d175f3e2a49c50d76d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/image-config-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/contexts/image-config-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].ImageConfigContext\n"],"names":["module","exports","require","vendored","ImageConfigContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,kBAAkB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/router-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/router-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/router-context.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/router-context.js new file mode 100644 index 0000000000000000000000000000000000000000..424b2ce70b12d651376d8edc2afd98fd0311c017 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/router-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].RouterContext; + +//# sourceMappingURL=router-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/router-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/router-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..72cfaba6690cfe03fa957c852be20686ccd9fd0b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/router-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/contexts/router-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].RouterContext\n"],"names":["module","exports","require","vendored","RouterContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,aAAa","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/server-inserted-html.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/server-inserted-html.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/server-inserted-html.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/server-inserted-html.js new file mode 100644 index 0000000000000000000000000000000000000000..ebbbd2d6344ed38978abf8cdfc9e2dc6f33c3481 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/server-inserted-html.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].ServerInsertedHtml; + +//# sourceMappingURL=server-inserted-html.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/server-inserted-html.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/server-inserted-html.js.map new file mode 100644 index 0000000000000000000000000000000000000000..66dd9a96f648166d7f2c4fb4347eade12083fcb9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/server-inserted-html.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/contexts/server-inserted-html.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].ServerInsertedHtml\n"],"names":["module","exports","require","vendored","ServerInsertedHtml"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,kBAAkB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/entrypoints.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/entrypoints.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3eb1f5d8527092077feb783a87e47dd17268e482 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/entrypoints.d.ts @@ -0,0 +1,8 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import * as ReactJsxDevRuntime from 'react/jsx-dev-runtime'; +import * as ReactJsxRuntime from 'react/jsx-runtime'; +import * as ReactCompilerRuntime from 'react/compiler-runtime'; +declare let ReactServerDOMTurbopackServer: any, ReactServerDOMWebpackServer: any; +declare let ReactServerDOMTurbopackStatic: any, ReactServerDOMWebpackStatic: any; +export { React, ReactJsxDevRuntime, ReactJsxRuntime, ReactCompilerRuntime, ReactDOM, ReactServerDOMTurbopackServer, ReactServerDOMTurbopackStatic, ReactServerDOMWebpackServer, ReactServerDOMWebpackStatic, }; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/entrypoints.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/entrypoints.js new file mode 100644 index 0000000000000000000000000000000000000000..aa52a607770366c50a7ccb09a04ad4811c936001 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/entrypoints.js @@ -0,0 +1,136 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + React: null, + ReactCompilerRuntime: null, + ReactDOM: null, + ReactJsxDevRuntime: null, + ReactJsxRuntime: null, + ReactServerDOMTurbopackServer: null, + ReactServerDOMTurbopackStatic: null, + ReactServerDOMWebpackServer: null, + ReactServerDOMWebpackStatic: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + React: function() { + return _react; + }, + ReactCompilerRuntime: function() { + return _compilerruntime; + }, + ReactDOM: function() { + return _reactdom; + }, + ReactJsxDevRuntime: function() { + return _jsxdevruntime; + }, + ReactJsxRuntime: function() { + return _jsxruntime; + }, + ReactServerDOMTurbopackServer: function() { + return ReactServerDOMTurbopackServer; + }, + ReactServerDOMTurbopackStatic: function() { + return ReactServerDOMTurbopackStatic; + }, + ReactServerDOMWebpackServer: function() { + return ReactServerDOMWebpackServer; + }, + ReactServerDOMWebpackStatic: function() { + return ReactServerDOMWebpackStatic; + } +}); +const _react = /*#__PURE__*/ _interop_require_wildcard(require("react")); +const _reactdom = /*#__PURE__*/ _interop_require_wildcard(require("react-dom")); +const _jsxdevruntime = /*#__PURE__*/ _interop_require_wildcard(require("react/jsx-dev-runtime")); +const _jsxruntime = /*#__PURE__*/ _interop_require_wildcard(require("react/jsx-runtime")); +const _compilerruntime = /*#__PURE__*/ _interop_require_wildcard(require("react/compiler-runtime")); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +function getAltProxyForBindingsDEV(type, pkg) { + if (process.env.NODE_ENV === 'development') { + const altType = type === 'Turbopack' ? 'Webpack' : 'Turbopack'; + const altPkg = pkg.replace(new RegExp(type, 'gi'), altType.toLowerCase()); + return new Proxy({}, { + get (_, prop) { + throw new Error(`Expected to use ${type} bindings (${pkg}) for React but the current process is referencing '${prop}' from the ${altType} bindings (${altPkg}). This is likely a bug in our integration of the Next.js server runtime.`); + } + }); + } +} +let ReactServerDOMTurbopackServer, ReactServerDOMWebpackServer; +let ReactServerDOMTurbopackStatic, ReactServerDOMWebpackStatic; +if (process.env.TURBOPACK) { + ReactServerDOMTurbopackServer = // @ts-expect-error -- TODO: Add types + // eslint-disable-next-line import/no-extraneous-dependencies + require('react-server-dom-turbopack/server'); + if (process.env.NODE_ENV === 'development') { + ReactServerDOMWebpackServer = getAltProxyForBindingsDEV('Turbopack', 'react-server-dom-turbopack/server'); + } + ReactServerDOMTurbopackStatic = // @ts-expect-error -- TODO: Add types + // eslint-disable-next-line import/no-extraneous-dependencies + require('react-server-dom-turbopack/static'); + if (process.env.NODE_ENV === 'development') { + ReactServerDOMWebpackStatic = getAltProxyForBindingsDEV('Turbopack', 'react-server-dom-turbopack/static'); + } +} else { + ReactServerDOMWebpackServer = // eslint-disable-next-line import/no-extraneous-dependencies + require('react-server-dom-webpack/server'); + if (process.env.NODE_ENV === 'development') { + ReactServerDOMTurbopackServer = getAltProxyForBindingsDEV('Webpack', 'react-server-dom-webpack/server'); + } + ReactServerDOMWebpackStatic = // eslint-disable-next-line import/no-extraneous-dependencies + require('react-server-dom-webpack/static'); + if (process.env.NODE_ENV === 'development') { + ReactServerDOMTurbopackStatic = getAltProxyForBindingsDEV('Webpack', 'react-server-dom-webpack/static'); + } +} + +//# sourceMappingURL=entrypoints.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/entrypoints.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/entrypoints.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4671328b3cff38ee38ae27f7e8b001926ebca0df --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/entrypoints.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/rsc/entrypoints.ts"],"sourcesContent":["import * as React from 'react'\nimport * as ReactDOM from 'react-dom'\nimport * as ReactJsxDevRuntime from 'react/jsx-dev-runtime'\nimport * as ReactJsxRuntime from 'react/jsx-runtime'\nimport * as ReactCompilerRuntime from 'react/compiler-runtime'\n\nfunction getAltProxyForBindingsDEV(\n type: 'Turbopack' | 'Webpack',\n pkg:\n | 'react-server-dom-turbopack/server'\n | 'react-server-dom-turbopack/static'\n | 'react-server-dom-webpack/server'\n | 'react-server-dom-webpack/static'\n) {\n if (process.env.NODE_ENV === 'development') {\n const altType = type === 'Turbopack' ? 'Webpack' : 'Turbopack'\n const altPkg = pkg.replace(new RegExp(type, 'gi'), altType.toLowerCase())\n\n return new Proxy(\n {},\n {\n get(_, prop: string) {\n throw new Error(\n `Expected to use ${type} bindings (${pkg}) for React but the current process is referencing '${prop}' from the ${altType} bindings (${altPkg}). This is likely a bug in our integration of the Next.js server runtime.`\n )\n },\n }\n )\n }\n}\n\nlet ReactServerDOMTurbopackServer, ReactServerDOMWebpackServer\nlet ReactServerDOMTurbopackStatic, ReactServerDOMWebpackStatic\n\nif (process.env.TURBOPACK) {\n ReactServerDOMTurbopackServer =\n // @ts-expect-error -- TODO: Add types\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-turbopack/server') as typeof import('react-server-dom-turbopack/server')\n if (process.env.NODE_ENV === 'development') {\n ReactServerDOMWebpackServer = getAltProxyForBindingsDEV(\n 'Turbopack',\n 'react-server-dom-turbopack/server'\n )\n }\n ReactServerDOMTurbopackStatic =\n // @ts-expect-error -- TODO: Add types\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-turbopack/static') as typeof import('react-server-dom-turbopack/static')\n if (process.env.NODE_ENV === 'development') {\n ReactServerDOMWebpackStatic = getAltProxyForBindingsDEV(\n 'Turbopack',\n 'react-server-dom-turbopack/static'\n )\n }\n} else {\n ReactServerDOMWebpackServer =\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-webpack/server') as typeof import('react-server-dom-webpack/server')\n if (process.env.NODE_ENV === 'development') {\n ReactServerDOMTurbopackServer = getAltProxyForBindingsDEV(\n 'Webpack',\n 'react-server-dom-webpack/server'\n )\n }\n ReactServerDOMWebpackStatic =\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-webpack/static') as typeof import('react-server-dom-webpack/static')\n if (process.env.NODE_ENV === 'development') {\n ReactServerDOMTurbopackStatic = getAltProxyForBindingsDEV(\n 'Webpack',\n 'react-server-dom-webpack/static'\n )\n }\n}\n\nexport {\n React,\n ReactJsxDevRuntime,\n ReactJsxRuntime,\n ReactCompilerRuntime,\n ReactDOM,\n ReactServerDOMTurbopackServer,\n ReactServerDOMTurbopackStatic,\n ReactServerDOMWebpackServer,\n ReactServerDOMWebpackStatic,\n}\n"],"names":["React","ReactCompilerRuntime","ReactDOM","ReactJsxDevRuntime","ReactJsxRuntime","ReactServerDOMTurbopackServer","ReactServerDOMTurbopackStatic","ReactServerDOMWebpackServer","ReactServerDOMWebpackStatic","getAltProxyForBindingsDEV","type","pkg","process","env","NODE_ENV","altType","altPkg","replace","RegExp","toLowerCase","Proxy","get","_","prop","Error","TURBOPACK","require"],"mappings":";;;;;;;;;;;;;;;;;;;;;;IA6EEA,KAAK;eAALA;;IAGAC,oBAAoB;eAApBA;;IACAC,QAAQ;eAARA;;IAHAC,kBAAkB;eAAlBA;;IACAC,eAAe;eAA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QAC1CR,gCAAgCG,0BAC9B,WACA;IAEJ;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-compiler-runtime.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-compiler-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-compiler-runtime.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-compiler-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..375311777f14c44ce18dd41637235fb72595d24e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-compiler-runtime.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-rsc'].ReactCompilerRuntime; + +//# sourceMappingURL=react-compiler-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-compiler-runtime.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-compiler-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..306a7572bbeca8d7e11514811fdeeff2516571da --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-compiler-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/rsc/react-compiler-runtime.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-rsc']!.ReactCompilerRuntime\n"],"names":["module","exports","require","vendored","ReactCompilerRuntime"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,oBAAoB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-dom.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-dom.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-dom.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-dom.js new file mode 100644 index 0000000000000000000000000000000000000000..3ca430c8fcc216a6c13263dcde124fa9b6a4cd3b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-dom.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-rsc'].ReactDOM; + +//# sourceMappingURL=react-dom.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-dom.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-dom.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8aa002260255fc7d4c37eb1aecd2f370f2701c8e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-dom.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/rsc/react-dom.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-rsc']!.ReactDOM\n"],"names":["module","exports","require","vendored","ReactDOM"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,QAAQ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-dev-runtime.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-dev-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-dev-runtime.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-dev-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..4a4ed1e949d7751d7a6d9e00d6aa1e034d4de2e7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-dev-runtime.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-rsc'].ReactJsxDevRuntime; + +//# sourceMappingURL=react-jsx-dev-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-dev-runtime.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-dev-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3fc229170bf843eade8de7d6ae2ced13b657643c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-dev-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/rsc/react-jsx-dev-runtime.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-rsc']!.ReactJsxDevRuntime\n"],"names":["module","exports","require","vendored","ReactJsxDevRuntime"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,kBAAkB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-runtime.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-runtime.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..dd618647d3fca2e2f2b8595a1ff7b5b0eb9b1c72 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-runtime.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-rsc'].ReactJsxRuntime; + +//# sourceMappingURL=react-jsx-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-runtime.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0994ed9a3277881e34cfec55c7d438aa136459a1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-jsx-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/rsc/react-jsx-runtime.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-rsc']!.ReactJsxRuntime\n"],"names":["module","exports","require","vendored","ReactJsxRuntime"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,eAAe","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-server.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-server.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-server.js new file mode 100644 index 0000000000000000000000000000000000000000..024d96d1cdbc759171413e66cf771465ac1dcdd2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-server.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-rsc'].ReactServerDOMTurbopackServer; + +//# sourceMappingURL=react-server-dom-turbopack-server.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-server.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-server.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8543b60c271070648d5db8fbbace29ca41eaf39a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-server.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-server.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-rsc']!.ReactServerDOMTurbopackServer\n"],"names":["module","exports","require","vendored","ReactServerDOMTurbopackServer"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,6BAA6B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-static.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-static.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-static.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-static.js new file mode 100644 index 0000000000000000000000000000000000000000..927ff14917dfaee863858e6bdb5cca872d8b1d2a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-static.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-rsc'].ReactServerDOMTurbopackStatic; + +//# sourceMappingURL=react-server-dom-turbopack-static.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-static.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-static.js.map new file mode 100644 index 0000000000000000000000000000000000000000..32827a8153dc4c8e83e5518ab0e602218999b53a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-static.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/rsc/react-server-dom-turbopack-static.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-rsc']!.ReactServerDOMTurbopackStatic\n"],"names":["module","exports","require","vendored","ReactServerDOMTurbopackStatic"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,6BAA6B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-server.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-server.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-server.js new file mode 100644 index 0000000000000000000000000000000000000000..31734529b321f4cdb82b24bace9cc5f3d1edebba --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-server.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-rsc'].ReactServerDOMWebpackServer; + +//# sourceMappingURL=react-server-dom-webpack-server.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-server.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-server.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e2af8d6bb006142c6434823c2ca14d4adf6da5f3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-server.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-server.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-rsc']!.ReactServerDOMWebpackServer\n"],"names":["module","exports","require","vendored","ReactServerDOMWebpackServer"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,2BAA2B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-static.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-static.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-static.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-static.js new file mode 100644 index 0000000000000000000000000000000000000000..5e8a20648a908c23e83b62b9b86018777a50d02e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-static.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-rsc'].ReactServerDOMWebpackStatic; + +//# sourceMappingURL=react-server-dom-webpack-static.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-static.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-static.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5f3797be7d149ad91199de1fa968ec9934b18ee7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-static.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/rsc/react-server-dom-webpack-static.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-rsc']!.ReactServerDOMWebpackStatic\n"],"names":["module","exports","require","vendored","ReactServerDOMWebpackStatic"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,2BAA2B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react.js new file mode 100644 index 0000000000000000000000000000000000000000..6e789a3c49857e453a77a2ae06cab9aa116de477 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-rsc'].React; + +//# sourceMappingURL=react.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5f70e79f6b1e580b9abb3f3fbd570dc000fe8373 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/rsc/react.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/rsc/react.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-rsc']!.React\n"],"names":["module","exports","require","vendored","React"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,KAAK","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/entrypoints.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/entrypoints.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e57ad9106dbbcef2ac34e192838a561c1bfd12bd --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/entrypoints.d.ts @@ -0,0 +1,8 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import * as ReactJsxDevRuntime from 'react/jsx-dev-runtime'; +import * as ReactJsxRuntime from 'react/jsx-runtime'; +import * as ReactCompilerRuntime from 'react/compiler-runtime'; +import * as ReactDOMServer from 'react-dom/server'; +declare let ReactServerDOMTurbopackClient: any, ReactServerDOMWebpackClient: any; +export { React, ReactJsxDevRuntime, ReactJsxRuntime, ReactCompilerRuntime, ReactDOM, ReactDOMServer, ReactServerDOMTurbopackClient, ReactServerDOMWebpackClient, }; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/entrypoints.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/entrypoints.js new file mode 100644 index 0000000000000000000000000000000000000000..f62237b0c12c2f7c23c22f22b463ce09c6764987 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/entrypoints.js @@ -0,0 +1,121 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + React: null, + ReactCompilerRuntime: null, + ReactDOM: null, + ReactDOMServer: null, + ReactJsxDevRuntime: null, + ReactJsxRuntime: null, + ReactServerDOMTurbopackClient: null, + ReactServerDOMWebpackClient: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + React: function() { + return _react; + }, + ReactCompilerRuntime: function() { + return _compilerruntime; + }, + ReactDOM: function() { + return _reactdom; + }, + ReactDOMServer: function() { + return _server; + }, + ReactJsxDevRuntime: function() { + return _jsxdevruntime; + }, + ReactJsxRuntime: function() { + return _jsxruntime; + }, + ReactServerDOMTurbopackClient: function() { + return ReactServerDOMTurbopackClient; + }, + ReactServerDOMWebpackClient: function() { + return ReactServerDOMWebpackClient; + } +}); +const _react = /*#__PURE__*/ _interop_require_wildcard(require("react")); +const _reactdom = /*#__PURE__*/ _interop_require_wildcard(require("react-dom")); +const _jsxdevruntime = /*#__PURE__*/ _interop_require_wildcard(require("react/jsx-dev-runtime")); +const _jsxruntime = /*#__PURE__*/ _interop_require_wildcard(require("react/jsx-runtime")); +const _compilerruntime = /*#__PURE__*/ _interop_require_wildcard(require("react/compiler-runtime")); +const _server = /*#__PURE__*/ _interop_require_wildcard(require("react-dom/server")); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +function getAltProxyForBindingsDEV(type, pkg) { + if (process.env.NODE_ENV === 'development') { + const altType = type === 'Turbopack' ? 'Webpack' : 'Turbopack'; + const altPkg = pkg.replace(new RegExp(type, 'gi'), altType.toLowerCase()); + return new Proxy({}, { + get (_, prop) { + throw new Error(`Expected to use ${type} bindings (${pkg}) for React but the current process is referencing '${prop}' from the ${altType} bindings (${altPkg}). This is likely a bug in our integration of the Next.js server runtime.`); + } + }); + } +} +let ReactServerDOMTurbopackClient, ReactServerDOMWebpackClient; +if (process.env.TURBOPACK) { + ReactServerDOMTurbopackClient = // @ts-expect-error -- TODO: Add types + // eslint-disable-next-line import/no-extraneous-dependencies + require('react-server-dom-turbopack/client'); + if (process.env.NODE_ENV === 'development') { + ReactServerDOMWebpackClient = getAltProxyForBindingsDEV('Turbopack', 'react-server-dom-turbopack/client'); + } +} else { + ReactServerDOMWebpackClient = // eslint-disable-next-line import/no-extraneous-dependencies + require('react-server-dom-webpack/client'); + if (process.env.NODE_ENV === 'development') { + ReactServerDOMTurbopackClient = getAltProxyForBindingsDEV('Webpack', 'react-server-dom-webpack/client'); + } +} + +//# sourceMappingURL=entrypoints.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/entrypoints.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/entrypoints.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e974a5e269154ec2985efe5f452ad205c6060741 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/entrypoints.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/ssr/entrypoints.ts"],"sourcesContent":["import * as React from 'react'\nimport * as ReactDOM from 'react-dom'\nimport * as ReactJsxDevRuntime from 'react/jsx-dev-runtime'\nimport * as ReactJsxRuntime from 'react/jsx-runtime'\nimport * as ReactCompilerRuntime from 'react/compiler-runtime'\n\nimport * as ReactDOMServer from 'react-dom/server'\n\nfunction getAltProxyForBindingsDEV(\n type: 'Turbopack' | 'Webpack',\n pkg: 'react-server-dom-turbopack/client' | 'react-server-dom-webpack/client'\n) {\n if (process.env.NODE_ENV === 'development') {\n const altType = type === 'Turbopack' ? 'Webpack' : 'Turbopack'\n const altPkg = pkg.replace(new RegExp(type, 'gi'), altType.toLowerCase())\n\n return new Proxy(\n {},\n {\n get(_, prop: string) {\n throw new Error(\n `Expected to use ${type} bindings (${pkg}) for React but the current process is referencing '${prop}' from the ${altType} bindings (${altPkg}). This is likely a bug in our integration of the Next.js server runtime.`\n )\n },\n }\n )\n }\n}\n\nlet ReactServerDOMTurbopackClient, ReactServerDOMWebpackClient\nif (process.env.TURBOPACK) {\n ReactServerDOMTurbopackClient =\n // @ts-expect-error -- TODO: Add types\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-turbopack/client') as typeof import('react-server-dom-turbopack/client')\n if (process.env.NODE_ENV === 'development') {\n ReactServerDOMWebpackClient = getAltProxyForBindingsDEV(\n 'Turbopack',\n 'react-server-dom-turbopack/client'\n )\n }\n} else {\n ReactServerDOMWebpackClient =\n // eslint-disable-next-line import/no-extraneous-dependencies\n require('react-server-dom-webpack/client') as typeof import('react-server-dom-webpack/client')\n if (process.env.NODE_ENV === 'development') {\n ReactServerDOMTurbopackClient = getAltProxyForBindingsDEV(\n 'Webpack',\n 'react-server-dom-webpack/client'\n )\n }\n}\n\nexport {\n React,\n ReactJsxDevRuntime,\n ReactJsxRuntime,\n ReactCompilerRuntime,\n ReactDOM,\n ReactDOMServer,\n ReactServerDOMTurbopackClient,\n ReactServerDOMWebpackClient,\n}\n"],"names":["React","ReactCompilerRuntime","ReactDOM","ReactDOMServer","ReactJsxDevRuntime","ReactJsxRuntime","ReactServerDOMTurbopackClient","ReactServerDOMWebpackClient","getAltProxyForBindingsDEV","type","pkg","process","env","NODE_ENV","altType","altPkg","replace","RegExp","toLowerCase","Proxy","get","_","prop","Error","TURBOPACK","require"],"mappings":";;;;;;;;;;;;;;;;;;;;;IAsDEA,KAAK;eAALA;;IAGAC,oBAAoB;eAApBA;;IACAC,QAAQ;eAARA;;IACAC,cAAc;eAAdA;;IAJAC,kBAAkB;eAAlBA;;IACAC,eAAe;eAAfA;;IAIAC,6BAA6B;eAA7BA;;IACAC,2BAA2B;eAA3BA;;;+DA7DqB;kEACG;uEACU;oEACH;yEACK;gEAEN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEhC,SAASC,0BACPC,IAA6B,EAC7BC,GAA4E;IAE5E,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QAC1C,MAAMC,UAAUL,SAAS,cAAc,YAAY;QACnD,MAAMM,SAASL,IAAIM,OAAO,CAAC,IAAIC,OAAOR,MAAM,OAAOK,QAAQI,WAAW;QAEtE,OAAO,IAAIC,MACT,CAAC,GACD;YACEC,KAAIC,CAAC,EAAEC,IAAY;gBACjB,MAAM,IAAIC,MACR,CAAC,gBAAgB,EAAEd,KAAK,WAAW,EAAEC,IAAI,oDAAoD,EAAEY,KAAK,WAAW,EAAER,QAAQ,WAAW,EAAEC,OAAO,yEAAyE,CAAC;YAE3N;QACF;IAEJ;AACF;AAEA,IAAIT,+BAA+BC;AACnC,IAAII,QAAQC,GAAG,CAACY,SAAS,EAAE;IACzBlB,gCACE,sCAAsC;IACtC,6DAA6D;IAC7DmB,QAAQ;IACV,IAAId,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QAC1CN,8BAA8BC,0BAC5B,aACA;IAEJ;AACF,OAAO;IACLD,8BACE,6DAA6D;IAC7DkB,QAAQ;IACV,IAAId,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QAC1CP,gCAAgCE,0BAC9B,WACA;IAEJ;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-compiler-runtime.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-compiler-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-compiler-runtime.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-compiler-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..9ea121bcc99d9365c4fc9746f8f6762753bf4fd8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-compiler-runtime.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-ssr'].ReactCompilerRuntime; + +//# sourceMappingURL=react-compiler-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-compiler-runtime.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-compiler-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..57cace2297988e2fd7781625586510d841911f4a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-compiler-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/ssr/react-compiler-runtime.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.ReactCompilerRuntime\n"],"names":["module","exports","require","vendored","ReactCompilerRuntime"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,oBAAoB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom-server.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom-server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom-server.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom-server.js new file mode 100644 index 0000000000000000000000000000000000000000..e684bce8ab5758d8c799a968a89e2d75456acf2f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom-server.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-ssr'].ReactDOMServer; + +//# sourceMappingURL=react-dom-server.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom-server.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom-server.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7234b44e53618ed72e9d001495c701d6f17d3533 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom-server.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/ssr/react-dom-server.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.ReactDOMServer\n"],"names":["module","exports","require","vendored","ReactDOMServer"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,cAAc","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom.js new file mode 100644 index 0000000000000000000000000000000000000000..9e49bcc739dc12163d3f0edb3ad324cd770538f6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-ssr'].ReactDOM; + +//# sourceMappingURL=react-dom.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e5866a34c92163e3438b7ad658be6d094dc34a9f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-dom.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/ssr/react-dom.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.ReactDOM\n"],"names":["module","exports","require","vendored","ReactDOM"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,QAAQ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-dev-runtime.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-dev-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-dev-runtime.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-dev-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..494bdd740495fae515b7406857120eaa8b115a80 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-dev-runtime.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-ssr'].ReactJsxDevRuntime; + +//# sourceMappingURL=react-jsx-dev-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-dev-runtime.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-dev-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..311925641558af61db7b277e3c126ccd067d517f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-dev-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/ssr/react-jsx-dev-runtime.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.ReactJsxDevRuntime\n"],"names":["module","exports","require","vendored","ReactJsxDevRuntime"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,kBAAkB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-runtime.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-runtime.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..c9633d01b43ca1c66c78f581e94bc9f607fcbc64 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-runtime.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-ssr'].ReactJsxRuntime; + +//# sourceMappingURL=react-jsx-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-runtime.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c97d1c1d4f101351fa96e0527bfcf38acb90f67f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-jsx-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/ssr/react-jsx-runtime.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.ReactJsxRuntime\n"],"names":["module","exports","require","vendored","ReactJsxRuntime"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,eAAe","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-turbopack-client.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-turbopack-client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-turbopack-client.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-turbopack-client.js new file mode 100644 index 0000000000000000000000000000000000000000..b3422ef1e7568186db3969079b53abd0bffedbc2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-turbopack-client.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-ssr'].ReactServerDOMTurbopackClient; + +//# sourceMappingURL=react-server-dom-turbopack-client.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-turbopack-client.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-turbopack-client.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b4fb7d5d27cb332e2d2b5784527ff2574af3a9e1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-turbopack-client.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/ssr/react-server-dom-turbopack-client.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.ReactServerDOMTurbopackClient\n"],"names":["module","exports","require","vendored","ReactServerDOMTurbopackClient"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,6BAA6B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-webpack-client.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-webpack-client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-webpack-client.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-webpack-client.js new file mode 100644 index 0000000000000000000000000000000000000000..3d4783992e1e22d2225fd3e198241a6fdaeaa6c8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-webpack-client.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-ssr'].ReactServerDOMWebpackClient; + +//# sourceMappingURL=react-server-dom-webpack-client.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-webpack-client.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-webpack-client.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8d0ed90a3476fc00715baa6553c92613a9924398 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react-server-dom-webpack-client.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/ssr/react-server-dom-webpack-client.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.ReactServerDOMWebpackClient\n"],"names":["module","exports","require","vendored","ReactServerDOMWebpackClient"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,2BAA2B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react.js b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react.js new file mode 100644 index 0000000000000000000000000000000000000000..c22246f094e08f92a28c0743f6d629f058f8b1c9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['react-ssr'].React; + +//# sourceMappingURL=react.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react.js.map new file mode 100644 index 0000000000000000000000000000000000000000..87623c74abd521aed7918483d1264bc255783618 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-page/vendored/ssr/react.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/app-page/vendored/ssr/react.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.React\n"],"names":["module","exports","require","vendored","React"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,YAAY,CAAEC,KAAK","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/auto-implement-methods.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/auto-implement-methods.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d03b9be156b060c3c62dc84cc2f22cdd5235f71 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/auto-implement-methods.d.ts @@ -0,0 +1,3 @@ +import type { AppRouteHandlerFn, AppRouteHandlers } from '../module'; +import { type HTTP_METHOD } from '../../../web/http'; +export declare function autoImplementMethods(handlers: AppRouteHandlers): Record; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/auto-implement-methods.js b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/auto-implement-methods.js new file mode 100644 index 0000000000000000000000000000000000000000..b46096e30ef10f41dc00c8162a09218c3545658c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/auto-implement-methods.js @@ -0,0 +1,81 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "autoImplementMethods", { + enumerable: true, + get: function() { + return autoImplementMethods; + } +}); +const _http = require("../../../web/http"); +const AUTOMATIC_ROUTE_METHODS = [ + 'HEAD', + 'OPTIONS' +]; +function handleMethodNotAllowedResponse() { + return new Response(null, { + status: 405 + }); +} +function autoImplementMethods(handlers) { + // Loop through all the HTTP methods to create the initial methods object. + // Each of the methods will be set to the 405 response handler. + const methods = _http.HTTP_METHODS.reduce((acc, method)=>({ + ...acc, + // If the userland module implements the method, then use it. Otherwise, + // use the 405 response handler. + [method]: handlers[method] ?? handleMethodNotAllowedResponse + }), {}); + // Get all the methods that could be automatically implemented that were not + // implemented by the userland module. + const implemented = new Set(_http.HTTP_METHODS.filter((method)=>handlers[method])); + const missing = AUTOMATIC_ROUTE_METHODS.filter((method)=>!implemented.has(method)); + // Loop over the missing methods to automatically implement them if we can. + for (const method of missing){ + // If the userland module doesn't implement the HEAD method, then + // we'll automatically implement it by calling the GET method (if it + // exists). + if (method === 'HEAD') { + if (handlers.GET) { + // Implement the HEAD method by calling the GET method. + methods.HEAD = handlers.GET; + // Mark it as implemented. + implemented.add('HEAD'); + } + continue; + } + // If OPTIONS is not provided then implement it. + if (method === 'OPTIONS') { + // TODO: check if HEAD is implemented, if so, use it to add more headers + // Get all the methods that were implemented by the userland module. + const allow = [ + 'OPTIONS', + ...implemented + ]; + // If the list of methods doesn't include HEAD, but it includes GET, then + // add HEAD as it's automatically implemented. + if (!implemented.has('HEAD') && implemented.has('GET')) { + allow.push('HEAD'); + } + // Sort and join the list with commas to create the `Allow` header. See: + // https://httpwg.org/specs/rfc9110.html#field.allow + const headers = { + Allow: allow.sort().join(', ') + }; + // Implement the OPTIONS method by returning a 204 response with the + // `Allow` header. + methods.OPTIONS = ()=>new Response(null, { + status: 204, + headers + }); + // Mark this method as implemented. + implemented.add('OPTIONS'); + continue; + } + throw new Error(`Invariant: should handle all automatic implementable methods, got method: ${method}`); + } + return methods; +} + +//# sourceMappingURL=auto-implement-methods.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/auto-implement-methods.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/auto-implement-methods.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e78d50a49238b655dd4a5a61519bfa3399a68fdb --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/auto-implement-methods.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/route-modules/app-route/helpers/auto-implement-methods.ts"],"sourcesContent":["import type { AppRouteHandlerFn, AppRouteHandlers } from '../module'\n\nimport { HTTP_METHODS, type HTTP_METHOD } from '../../../web/http'\n\nconst AUTOMATIC_ROUTE_METHODS = ['HEAD', 'OPTIONS'] as const\n\nfunction handleMethodNotAllowedResponse(): Response {\n return new Response(null, { status: 405 })\n}\n\nexport function autoImplementMethods(\n handlers: AppRouteHandlers\n): Record {\n // Loop through all the HTTP methods to create the initial methods object.\n // Each of the methods will be set to the 405 response handler.\n const methods: Record = HTTP_METHODS.reduce(\n (acc, method) => ({\n ...acc,\n // If the userland module implements the method, then use it. Otherwise,\n // use the 405 response handler.\n [method]: handlers[method] ?? handleMethodNotAllowedResponse,\n }),\n {} as Record\n )\n\n // Get all the methods that could be automatically implemented that were not\n // implemented by the userland module.\n const implemented = new Set(HTTP_METHODS.filter((method) => handlers[method]))\n const missing = AUTOMATIC_ROUTE_METHODS.filter(\n (method) => !implemented.has(method)\n )\n\n // Loop over the missing methods to automatically implement them if we can.\n for (const method of missing) {\n // If the userland module doesn't implement the HEAD method, then\n // we'll automatically implement it by calling the GET method (if it\n // exists).\n if (method === 'HEAD') {\n if (handlers.GET) {\n // Implement the HEAD method by calling the GET method.\n methods.HEAD = handlers.GET\n\n // Mark it as implemented.\n implemented.add('HEAD')\n }\n continue\n }\n\n // If OPTIONS is not provided then implement it.\n if (method === 'OPTIONS') {\n // TODO: check if HEAD is implemented, if so, use it to add more headers\n\n // Get all the methods that were implemented by the userland module.\n const allow: HTTP_METHOD[] = ['OPTIONS', ...implemented]\n\n // If the list of methods doesn't include HEAD, but it includes GET, then\n // add HEAD as it's automatically implemented.\n if (!implemented.has('HEAD') && implemented.has('GET')) {\n allow.push('HEAD')\n }\n\n // Sort and join the list with commas to create the `Allow` header. See:\n // https://httpwg.org/specs/rfc9110.html#field.allow\n const headers = { Allow: allow.sort().join(', ') }\n\n // Implement the OPTIONS method by returning a 204 response with the\n // `Allow` header.\n methods.OPTIONS = () => new Response(null, { status: 204, headers })\n\n // Mark this method as implemented.\n implemented.add('OPTIONS')\n\n continue\n }\n\n throw new Error(\n `Invariant: should handle all automatic implementable methods, got method: ${method}`\n )\n }\n\n return methods\n}\n"],"names":["autoImplementMethods","AUTOMATIC_ROUTE_METHODS","handleMethodNotAllowedResponse","Response","status","handlers","methods","HTTP_METHODS","reduce","acc","method","implemented","Set","filter","missing","has","GET","HEAD","add","allow","push","headers","Allow","sort","join","OPTIONS","Error"],"mappings":";;;;+BAUgBA;;;eAAAA;;;sBAR+B;AAE/C,MAAMC,0BAA0B;IAAC;IAAQ;CAAU;AAEnD,SAASC;IACP,OAAO,IAAIC,SAAS,MAAM;QAAEC,QAAQ;IAAI;AAC1C;AAEO,SAASJ,qBACdK,QAA0B;IAE1B,0EAA0E;IAC1E,+DAA+D;IAC/D,MAAMC,UAAkDC,kBAAY,CAACC,MAAM,CACzE,CAACC,KAAKC,SAAY,CAAA;YAChB,GAAGD,GAAG;YACN,wEAAwE;YACxE,gCAAgC;YAChC,CAACC,OAAO,EAAEL,QAAQ,CAACK,OAAO,IAAIR;QAChC,CAAA,GACA,CAAC;IAGH,4EAA4E;IAC5E,sCAAsC;IACtC,MAAMS,cAAc,IAAIC,IAAIL,kBAAY,CAACM,MAAM,CAAC,CAACH,SAAWL,QAAQ,CAACK,OAAO;IAC5E,MAAMI,UAAUb,wBAAwBY,MAAM,CAC5C,CAACH,SAAW,CAACC,YAAYI,GAAG,CAACL;IAG/B,2EAA2E;IAC3E,KAAK,MAAMA,UAAUI,QAAS;QAC5B,iEAAiE;QACjE,oEAAoE;QACpE,WAAW;QACX,IAAIJ,WAAW,QAAQ;YACrB,IAAIL,SAASW,GAAG,EAAE;gBAChB,uDAAuD;gBACvDV,QAAQW,IAAI,GAAGZ,SAASW,GAAG;gBAE3B,0BAA0B;gBAC1BL,YAAYO,GAAG,CAAC;YAClB;YACA;QACF;QAEA,gDAAgD;QAChD,IAAIR,WAAW,WAAW;YACxB,wEAAwE;YAExE,oEAAoE;YACpE,MAAMS,QAAuB;gBAAC;mBAAcR;aAAY;YAExD,yEAAyE;YACzE,8CAA8C;YAC9C,IAAI,CAACA,YAAYI,GAAG,CAAC,WAAWJ,YAAYI,GAAG,CAAC,QAAQ;gBACtDI,MAAMC,IAAI,CAAC;YACb;YAEA,wEAAwE;YACxE,oDAAoD;YACpD,MAAMC,UAAU;gBAAEC,OAAOH,MAAMI,IAAI,GAAGC,IAAI,CAAC;YAAM;YAEjD,oEAAoE;YACpE,kBAAkB;YAClBlB,QAAQmB,OAAO,GAAG,IAAM,IAAItB,SAAS,MAAM;oBAAEC,QAAQ;oBAAKiB;gBAAQ;YAElE,mCAAmC;YACnCV,YAAYO,GAAG,CAAC;YAEhB;QACF;QAEA,MAAM,IAAIQ,MACR,CAAC,0EAA0E,EAAEhB,QAAQ;IAEzF;IAEA,OAAOJ;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/clean-url.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/clean-url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9cc4a1802cb58bb590fc72f4494950d1f6ba546 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/clean-url.d.ts @@ -0,0 +1,7 @@ +/** + * Cleans a URL by stripping the protocol, host, and search params. + * + * @param urlString the url to clean + * @returns the cleaned url + */ +export declare function cleanURL(url: string | URL): URL; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/clean-url.js b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/clean-url.js new file mode 100644 index 0000000000000000000000000000000000000000..2294ff89ed97ad66abf85adab3e356a08549ab68 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/clean-url.js @@ -0,0 +1,24 @@ +/** + * Cleans a URL by stripping the protocol, host, and search params. + * + * @param urlString the url to clean + * @returns the cleaned url + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "cleanURL", { + enumerable: true, + get: function() { + return cleanURL; + } +}); +function cleanURL(url) { + const u = new URL(url); + u.host = 'localhost:3000'; + u.search = ''; + u.protocol = 'http'; + return u; +} + +//# sourceMappingURL=clean-url.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/clean-url.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/clean-url.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a0c529fd5d471ca0622b355babdf55d8cd0199d0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/clean-url.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/route-modules/app-route/helpers/clean-url.ts"],"sourcesContent":["/**\n * Cleans a URL by stripping the protocol, host, and search params.\n *\n * @param urlString the url to clean\n * @returns the cleaned url\n */\n\nexport function cleanURL(url: string | URL): URL {\n const u = new URL(url)\n u.host = 'localhost:3000'\n u.search = ''\n u.protocol = 'http'\n return u\n}\n"],"names":["cleanURL","url","u","URL","host","search","protocol"],"mappings":"AAAA;;;;;CAKC;;;;+BAEeA;;;eAAAA;;;AAAT,SAASA,SAASC,GAAiB;IACxC,MAAMC,IAAI,IAAIC,IAAIF;IAClBC,EAAEE,IAAI,GAAG;IACTF,EAAEG,MAAM,GAAG;IACXH,EAAEI,QAAQ,GAAG;IACb,OAAOJ;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/get-pathname-from-absolute-path.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/get-pathname-from-absolute-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..66d21dbe7115db1fa93a890c61a1c299491ba6b1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/get-pathname-from-absolute-path.d.ts @@ -0,0 +1,7 @@ +/** + * Get pathname from absolute path. + * + * @param absolutePath the absolute path + * @returns the pathname + */ +export declare function getPathnameFromAbsolutePath(absolutePath: string): string; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/get-pathname-from-absolute-path.js b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/get-pathname-from-absolute-path.js new file mode 100644 index 0000000000000000000000000000000000000000..99cdf0e0289b0d5cb1bdf5f79a650eca7c6e1b7c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/get-pathname-from-absolute-path.js @@ -0,0 +1,29 @@ +/** + * Get pathname from absolute path. + * + * @param absolutePath the absolute path + * @returns the pathname + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getPathnameFromAbsolutePath", { + enumerable: true, + get: function() { + return getPathnameFromAbsolutePath; + } +}); +function getPathnameFromAbsolutePath(absolutePath) { + // Remove prefix including app dir + let appDir = '/app/'; + if (!absolutePath.includes(appDir)) { + appDir = '\\app\\'; + } + const [, ...parts] = absolutePath.split(appDir); + const relativePath = appDir[0] + parts.join(appDir); + // remove extension + const pathname = relativePath.split('.').slice(0, -1).join('.'); + return pathname; +} + +//# sourceMappingURL=get-pathname-from-absolute-path.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/get-pathname-from-absolute-path.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/get-pathname-from-absolute-path.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b8ceeb35eb9f80720d3c43a4fef1ae5fd19de4f0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/get-pathname-from-absolute-path.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/route-modules/app-route/helpers/get-pathname-from-absolute-path.ts"],"sourcesContent":["/**\n * Get pathname from absolute path.\n *\n * @param absolutePath the absolute path\n * @returns the pathname\n */\nexport function getPathnameFromAbsolutePath(absolutePath: string) {\n // Remove prefix including app dir\n let appDir = '/app/'\n if (!absolutePath.includes(appDir)) {\n appDir = '\\\\app\\\\'\n }\n const [, ...parts] = absolutePath.split(appDir)\n const relativePath = appDir[0] + parts.join(appDir)\n\n // remove extension\n const pathname = relativePath.split('.').slice(0, -1).join('.')\n return pathname\n}\n"],"names":["getPathnameFromAbsolutePath","absolutePath","appDir","includes","parts","split","relativePath","join","pathname","slice"],"mappings":"AAAA;;;;;CAKC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,4BAA4BC,YAAoB;IAC9D,kCAAkC;IAClC,IAAIC,SAAS;IACb,IAAI,CAACD,aAAaE,QAAQ,CAACD,SAAS;QAClCA,SAAS;IACX;IACA,MAAM,GAAG,GAAGE,MAAM,GAAGH,aAAaI,KAAK,CAACH;IACxC,MAAMI,eAAeJ,MAAM,CAAC,EAAE,GAAGE,MAAMG,IAAI,CAACL;IAE5C,mBAAmB;IACnB,MAAMM,WAAWF,aAAaD,KAAK,CAAC,KAAKI,KAAK,CAAC,GAAG,CAAC,GAAGF,IAAI,CAAC;IAC3D,OAAOC;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/is-static-gen-enabled.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/is-static-gen-enabled.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a324abad039244e6b4e483b1df7f3a388a041dc --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/is-static-gen-enabled.d.ts @@ -0,0 +1,2 @@ +import type { AppRouteModule } from '../module.compiled'; +export declare function isStaticGenEnabled(mod: AppRouteModule['routeModule']['userland']): boolean; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/is-static-gen-enabled.js b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/is-static-gen-enabled.js new file mode 100644 index 0000000000000000000000000000000000000000..3916106cd2bd7b4d8fd8403a474d4135bdc64b53 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/is-static-gen-enabled.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isStaticGenEnabled", { + enumerable: true, + get: function() { + return isStaticGenEnabled; + } +}); +function isStaticGenEnabled(mod) { + return mod.dynamic === 'force-static' || mod.dynamic === 'error' || mod.revalidate === false || mod.revalidate !== undefined && mod.revalidate > 0 || typeof mod.generateStaticParams == 'function'; +} + +//# sourceMappingURL=is-static-gen-enabled.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/is-static-gen-enabled.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/is-static-gen-enabled.js.map new file mode 100644 index 0000000000000000000000000000000000000000..48c4e2e6a46dc8a47e81bb166500240f77664afd --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/is-static-gen-enabled.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/route-modules/app-route/helpers/is-static-gen-enabled.ts"],"sourcesContent":["import type { AppRouteModule } from '../module.compiled'\n\n// route handlers are only statically optimized if they define\n// one of these top-level configs manually\n// - dynamic = 'force-static'\n// - dynamic = 'error'\n// - revalidate > 0\n// - revalidate = false\n// - generateStaticParams\nexport function isStaticGenEnabled(\n mod: AppRouteModule['routeModule']['userland']\n) {\n return (\n mod.dynamic === 'force-static' ||\n mod.dynamic === 'error' ||\n mod.revalidate === false ||\n (mod.revalidate !== undefined && mod.revalidate > 0) ||\n typeof mod.generateStaticParams == 'function'\n )\n}\n"],"names":["isStaticGenEnabled","mod","dynamic","revalidate","undefined","generateStaticParams"],"mappings":";;;;+BASgBA;;;eAAAA;;;AAAT,SAASA,mBACdC,GAA8C;IAE9C,OACEA,IAAIC,OAAO,KAAK,kBAChBD,IAAIC,OAAO,KAAK,WAChBD,IAAIE,UAAU,KAAK,SAClBF,IAAIE,UAAU,KAAKC,aAAaH,IAAIE,UAAU,GAAG,KAClD,OAAOF,IAAII,oBAAoB,IAAI;AAEvC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/parsed-url-query-to-params.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/parsed-url-query-to-params.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2dd9ffef391084e05c28fabf1313cfded08a1fa5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/parsed-url-query-to-params.d.ts @@ -0,0 +1,8 @@ +import type { ParsedUrlQuery } from 'querystring'; +/** + * Converts the query into params. + * + * @param query the query to convert to params + * @returns the params + */ +export declare function parsedUrlQueryToParams(query: ParsedUrlQuery): Record; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/parsed-url-query-to-params.js b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/parsed-url-query-to-params.js new file mode 100644 index 0000000000000000000000000000000000000000..4d619e09c051f59a43407b6e4598b6a5c1f63164 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/parsed-url-query-to-params.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "parsedUrlQueryToParams", { + enumerable: true, + get: function() { + return parsedUrlQueryToParams; + } +}); +function parsedUrlQueryToParams(query) { + const params = {}; + for (const [key, value] of Object.entries(query)){ + if (typeof value === 'undefined') continue; + params[key] = value; + } + return params; +} + +//# sourceMappingURL=parsed-url-query-to-params.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/parsed-url-query-to-params.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/parsed-url-query-to-params.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1a71c4d49e80bb18b33f9d63288d50268200cb74 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/helpers/parsed-url-query-to-params.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/route-modules/app-route/helpers/parsed-url-query-to-params.ts"],"sourcesContent":["import type { ParsedUrlQuery } from 'querystring'\n\n/**\n * Converts the query into params.\n *\n * @param query the query to convert to params\n * @returns the params\n */\nexport function parsedUrlQueryToParams(\n query: ParsedUrlQuery\n): Record {\n const params: Record = {}\n\n for (const [key, value] of Object.entries(query)) {\n if (typeof value === 'undefined') continue\n params[key] = value\n }\n\n return params\n}\n"],"names":["parsedUrlQueryToParams","query","params","key","value","Object","entries"],"mappings":";;;;+BAQgBA;;;eAAAA;;;AAAT,SAASA,uBACdC,KAAqB;IAErB,MAAMC,SAA4C,CAAC;IAEnD,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACL,OAAQ;QAChD,IAAI,OAAOG,UAAU,aAAa;QAClCF,MAAM,CAACC,IAAI,GAAGC;IAChB;IAEA,OAAOF;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.compiled.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.compiled.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5401340695abe4a87f20f88a898449b7a42edfd6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.compiled.d.ts @@ -0,0 +1 @@ +export * from './module' diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.compiled.js b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.compiled.js new file mode 100644 index 0000000000000000000000000000000000000000..a14b6c0ffc7c73a97a70763767eb915e07c41eb4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.compiled.js @@ -0,0 +1,36 @@ +"use strict"; +if (process.env.NEXT_RUNTIME === 'edge') { + module.exports = require('next/dist/server/route-modules/app-route/module.js'); +} else { + if (process.env.__NEXT_EXPERIMENTAL_REACT) { + if (process.env.NODE_ENV === 'development') { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.dev.js'); + } else { + module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.dev.js'); + } + } else { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js'); + } else { + module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.prod.js'); + } + } + } else { + if (process.env.NODE_ENV === 'development') { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js'); + } else { + module.exports = require('next/dist/compiled/next-server/app-route.runtime.dev.js'); + } + } else { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.prod.js'); + } else { + module.exports = require('next/dist/compiled/next-server/app-route.runtime.prod.js'); + } + } + } +} + +//# sourceMappingURL=module.compiled.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.compiled.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.compiled.js.map new file mode 100644 index 0000000000000000000000000000000000000000..dcb1e3dd7e9c41b038cdae7ecb049ab0ef92cda2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.compiled.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/app-route/module.compiled.js"],"sourcesContent":["if (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/app-route/module.js')\n} else {\n if (process.env.__NEXT_EXPERIMENTAL_REACT) {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.dev.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.dev.js')\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.prod.js')\n }\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.dev.js')\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.prod.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.prod.js')\n }\n }\n }\n}\n"],"names":["process","env","NEXT_RUNTIME","module","exports","require","__NEXT_EXPERIMENTAL_REACT","NODE_ENV","TURBOPACK"],"mappings":";AAAA,IAAIA,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCC,OAAOC,OAAO,GAAGC,QAAQ;AAC3B,OAAO;IACL,IAAIL,QAAQC,GAAG,CAACK,yBAAyB,EAAE;QACzC,IAAIN,QAAQC,GAAG,CAACM,QAAQ,KAAK,eAAe;YAC1C,IAAIP,QAAQC,GAAG,CAACO,SAAS,EAAE;gBACzBL,OAAOC,OAAO,GAAGC,QAAQ;YAC3B,OAAO;gBACLF,OAAOC,OAAO,GAAGC,QAAQ;YAC3B;QACF,OAAO;YACL,IAAIL,QAAQC,GAAG,CAACO,SAAS,EAAE;gBACzBL,OAAOC,OAAO,GAAGC,QAAQ;YAC3B,OAAO;gBACLF,OAAOC,OAAO,GAAGC,QAAQ;YAC3B;QACF;IACF,OAAO;QACL,IAAIL,QAAQC,GAAG,CAACM,QAAQ,KAAK,eAAe;YAC1C,IAAIP,QAAQC,GAAG,CAACO,SAAS,EAAE;gBACzBL,OAAOC,OAAO,GAAGC,QAAQ;YAC3B,OAAO;gBACLF,OAAOC,OAAO,GAAGC,QAAQ;YAC3B;QACF,OAAO;YACL,IAAIL,QAAQC,GAAG,CAACO,SAAS,EAAE;gBACzBL,OAAOC,OAAO,GAAGC,QAAQ;YAC3B,OAAO;gBACLF,OAAOC,OAAO,GAAGC,QAAQ;YAC3B;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82ba790863b14e72f6e68a611921b5d25f6c488f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.d.ts @@ -0,0 +1,166 @@ +import type { NextConfig } from '../../config-shared'; +import type { AppRouteRouteDefinition } from '../../route-definitions/app-route-route-definition'; +import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config'; +import type { NextRequest } from '../../web/spec-extension/request'; +import type { DeepReadonly } from '../../../shared/lib/deep-readonly'; +import type { __ApiPreviewProps } from '../../api-utils'; +import { RouteModule, type RouteModuleHandleContext, type RouteModuleOptions } from '../route-module'; +import { type WorkStoreContext } from '../../async-storage/work-store'; +import { type HTTP_METHOD } from '../../web/http'; +import * as serverHooks from '../../../client/components/hooks-server-context'; +import * as sharedModules from './shared-modules'; +import type { AppSegment } from '../../../build/segment-config/app/app-segments'; +import { type RedirectError } from '../../../client/components/redirect-error'; +export declare class WrappedNextRouterError { + readonly error: RedirectError; + readonly headers?: Headers | undefined; + constructor(error: RedirectError, headers?: Headers | undefined); +} +/** + * The AppRouteModule is the type of the module exported by the bundled App + * Route module. + */ +export type AppRouteModule = typeof import('../../../build/templates/app-route'); +export type AppRouteSharedContext = { + buildId: string; + deploymentId: string; +}; +/** + * AppRouteRouteHandlerContext is the context that is passed to the route + * handler for app routes. + */ +export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext { + renderOpts: WorkStoreContext['renderOpts'] & CollectedCacheInfo; + previewProps: DeepReadonly<__ApiPreviewProps>; + sharedContext: AppRouteSharedContext; +} +type CollectedCacheInfo = { + collectedTags?: string; + collectedRevalidate?: number; + collectedExpire?: number; + collectedStale?: number; +}; +/** + * AppRouteHandlerFnContext is the context that is passed to the handler as the + * second argument. + */ +type AppRouteHandlerFnContext = { + params?: Promise>; +}; +/** + * Handler function for app routes. If a non-Response value is returned, an error + * will be thrown. + */ +export type AppRouteHandlerFn = ( +/** + * Incoming request object. + */ +req: NextRequest, +/** + * Context properties on the request (including the parameters if this was a + * dynamic route). + */ +ctx: AppRouteHandlerFnContext) => unknown; +/** + * AppRouteHandlers describes the handlers for app routes that is provided by + * the userland module. + */ +export type AppRouteHandlers = { + [method in HTTP_METHOD]?: AppRouteHandlerFn; +}; +/** + * AppRouteUserlandModule is the userland module that is provided for app + * routes. This contains all the user generated code. + */ +export type AppRouteUserlandModule = AppRouteHandlers & Pick & Pick; +/** + * AppRouteRouteModuleOptions is the options that are passed to the app route + * module from the bundled code. + */ +export interface AppRouteRouteModuleOptions extends Omit, 'userland'> { + readonly userland: () => AppRouteUserlandModule | Promise; + readonly resolvedPagePath: string; + readonly nextConfigOutput: NextConfig['output']; + /** + * Optional synchronous getter that returns the live userland module. When + * provided (Turbopack dev mode), it is called on every request so that + * server HMR updates are picked up without re-executing the entry chunk. + * Using require() instead of import() keeps this synchronous so the time + * spent here is not incorrectly attributed to application-code in timing. + */ + readonly getUserland?: () => AppRouteUserlandModule; +} +/** + * AppRouteRouteHandler is the handler for app routes. + */ +export declare class AppRouteRouteModule extends RouteModule { + /** + * A reference to the request async storage. + */ + readonly workUnitAsyncStorage: import("../../app-render/work-unit-async-storage.external").WorkUnitAsyncStorage; + /** + * A reference to the static generation async storage. + */ + readonly workAsyncStorage: import("../../app-render/work-async-storage.external").WorkAsyncStorage; + /** + * An interface to call server hooks which interact with the underlying + * storage. + */ + readonly serverHooks: typeof serverHooks; + static readonly sharedModules: typeof sharedModules; + /** + * A reference to the mutation related async storage, such as mutations of + * cookies. + */ + readonly actionAsyncStorage: import("../../app-render/action-async-storage.external").ActionAsyncStorage; + readonly resolvedPagePath: string; + readonly nextConfigOutput: NextConfig['output'] | undefined; + private readonly _lazyUserland; + private readonly _getUserland?; + private _methods; + private _hasNonStaticMethods; + private _dynamic; + get userland(): AppRouteUserlandModule; + /** + * Ensures the userland module is fully loaded before it's accessed via + * `userland`. Required for route files that use top-level await, where + * require() returns a promise instead of the module directly. Must be called + * before accessing `userland` in contexts where the module may not yet be + * resolved (e.g. the export/static-generation worker). + */ + ensureUserland(): Promise; + constructor({ userland, getUserland, definition, distDir, relativeProjectDir, resolvedPagePath, nextConfigOutput, }: AppRouteRouteModuleOptions); + private _onUserlandLoaded; + /** + * Returns the handler function for the given HTTP method. + * Must be called after ensureUserland() has resolved so that _methods is + * populated. + */ + private resolveHandler; + /** + * Returns the handler for the given method using a live userland snapshot. + * Used in Turbopack dev mode to pick up server HMR updates. The userland + * is fetched synchronously via require() so no async overhead is added. + */ + private resolveHandlerFromUserland; + private resolvePendingRevalidations; + private handleHandlerError; + private finalizeResponse; + private prerenderToResponse; + private renderToResponse; + private prepareExecution; + private validateExecutionResponse; + private executeRequest; + private executePrerender; + handle(req: NextRequest, context: AppRouteRouteHandlerContext): Promise; + prerender(req: NextRequest, context: AppRouteRouteHandlerContext): Promise; +} +export default AppRouteRouteModule; +/** + * Gets all the method names for handlers that are not considered static. + * + * @param handlers the handlers from the userland module + * @returns the method names that are not considered static or false if all + * methods are static + */ +export declare function hasNonStaticMethods(handlers: AppRouteHandlers): boolean; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.js b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.js new file mode 100644 index 0000000000000000000000000000000000000000..155a0de3aa9ef40bf84d4e568f5a3900f8949714 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.js @@ -0,0 +1,915 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + AppRouteRouteModule: null, + WrappedNextRouterError: null, + default: null, + hasNonStaticMethods: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + AppRouteRouteModule: function() { + return AppRouteRouteModule; + }, + WrappedNextRouterError: function() { + return WrappedNextRouterError; + }, + default: function() { + return _default; + }, + hasNonStaticMethods: function() { + return hasNonStaticMethods; + } +}); +const _routemodule = require("../route-module"); +const _requeststore = require("../../async-storage/request-store"); +const _workstore = require("../../async-storage/work-store"); +const _http = require("../../web/http"); +const _implicittags = require("../../lib/implicit-tags"); +const _patchfetch = require("../../lib/patch-fetch"); +const _tracer = require("../../lib/trace/tracer"); +const _constants = require("../../lib/trace/constants"); +const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../../build/output/log")); +const _autoimplementmethods = require("./helpers/auto-implement-methods"); +const _requestcookies = require("../../web/spec-extension/adapters/request-cookies"); +const _headers = require("../../web/spec-extension/adapters/headers"); +const _parsedurlquerytoparams = require("./helpers/parsed-url-query-to-params"); +const _prospectiverenderutils = require("../../app-render/prospective-render-utils"); +const _hooksservercontext = /*#__PURE__*/ _interop_require_wildcard(require("../../../client/components/hooks-server-context")); +const _workasyncstorageexternal = require("../../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external"); +const _actionasyncstorageexternal = require("../../app-render/action-async-storage.external"); +const _sharedmodules = /*#__PURE__*/ _interop_require_wildcard(require("./shared-modules")); +const _serveractionrequestmeta = require("../../lib/server-action-request-meta"); +const _cookies = require("next/dist/compiled/@edge-runtime/cookies"); +const _cleanurl = require("./helpers/clean-url"); +const _staticgenerationbailout = require("../../../client/components/static-generation-bailout"); +const _isstaticgenenabled = require("./helpers/is-static-gen-enabled"); +const _dynamicrendering = require("../../app-render/dynamic-rendering"); +const _reflect = require("../../web/spec-extension/adapters/reflect"); +const _cachesignal = require("../../app-render/cache-signal"); +const _scheduler = require("../../../lib/scheduler"); +const _params = require("../../request/params"); +const _redirect = require("../../../client/components/redirect"); +const _redirecterror = require("../../../client/components/redirect-error"); +const _httpaccessfallback = require("../../../client/components/http-access-fallback/http-access-fallback"); +const _redirectstatuscode = require("../../../client/components/redirect-status-code"); +const _constants1 = require("../../../lib/constants"); +const _revalidationutils = require("../../revalidation-utils"); +const _trackmoduleloadingexternal = require("../../app-render/module-loading/track-module-loading.external"); +const _invarianterror = require("../../../shared/lib/invariant-error"); +const _lazymodule = require("../../lib/lazy-module"); +const _resumedatacache = require("../../resume-data-cache/resume-data-cache"); +const _usecachemessages = require("../../use-cache/use-cache-messages"); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +class WrappedNextRouterError { + constructor(error, headers){ + this.error = error; + this.headers = headers; + } +} +class AppRouteRouteModule extends _routemodule.RouteModule { + static #_ = this.sharedModules = _sharedmodules; + get userland() { + return this._lazyUserland.assertLoaded(); + } + /** + * Ensures the userland module is fully loaded before it's accessed via + * `userland`. Required for route files that use top-level await, where + * require() returns a promise instead of the module directly. Must be called + * before accessing `userland` in contexts where the module may not yet be + * resolved (e.g. the export/static-generation worker). + */ async ensureUserland() { + await this._lazyUserland.waitUntilLoaded(); + } + constructor({ userland, getUserland, definition, distDir, relativeProjectDir, resolvedPagePath, nextConfigOutput }){ + super({ + userland: undefined, + definition, + distDir, + relativeProjectDir + }), /** + * A reference to the request async storage. + */ this.workUnitAsyncStorage = _workunitasyncstorageexternal.workUnitAsyncStorage, /** + * A reference to the static generation async storage. + */ this.workAsyncStorage = _workasyncstorageexternal.workAsyncStorage, /** + * An interface to call server hooks which interact with the underlying + * storage. + */ this.serverHooks = _hooksservercontext, /** + * A reference to the mutation related async storage, such as mutations of + * cookies. + */ this.actionAsyncStorage = _actionasyncstorageexternal.actionAsyncStorage; + this.resolvedPagePath = resolvedPagePath; + this.nextConfigOutput = nextConfigOutput; + this._getUserland = getUserland; + this._lazyUserland = new _lazymodule.LazyModule(()=>(0, _tracer.getTracer)().trace(_constants.AppRouteRouteModuleSpan.loadUserland, { + spanName: 'load app route module', + attributes: { + 'next.route': this.definition.pathname + } + }, userland), (module1)=>this._onUserlandLoaded(module1)); + // output:export routes load eagerly, so that errors surface at module + // load time (as a Redbox in dev) rather than at request time. + if (nextConfigOutput === 'export') { + this._lazyUserland.loadIfNeeded(); + } + } + _onUserlandLoaded(userland) { + // Automatically implement some methods if they aren't implemented by the + // userland module. + this._methods = (0, _autoimplementmethods.autoImplementMethods)(userland); + // Get the non-static methods for this route. + this._hasNonStaticMethods = hasNonStaticMethods(userland); + // Get the dynamic property from the userland module. + this._dynamic = userland.dynamic; + if (this.nextConfigOutput === 'export') { + if (this._dynamic === 'force-dynamic') { + throw new Error(`export const dynamic = "force-dynamic" on page "${this.definition.pathname}" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`); + } else if (!(0, _isstaticgenenabled.isStaticGenEnabled)(userland) && userland['GET']) { + throw new Error(`export const dynamic = "force-static"/export const revalidate not configured on route "${this.definition.pathname}" with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`); + } else { + this._dynamic = 'error'; + } + } + // We only warn in development after here, so return if we're not in + // development. + if (process.env.NODE_ENV === 'development') { + // Print error in development if the exported handlers are in lowercase, only + // uppercase handlers are supported. + const lowercased = _http.HTTP_METHODS.map((method)=>method.toLowerCase()); + for (const method of lowercased){ + if (method in userland) { + _log.error(`Detected lowercase method '${method}' in '${this.resolvedPagePath}'. Export the uppercase '${method.toUpperCase()}' method name to fix this error.`); + } + } + // Print error if the module exports a default handler, they must use named + // exports for each HTTP method. + if ('default' in userland) { + _log.error(`Detected default export in '${this.resolvedPagePath}'. Export a named export for each HTTP method instead.`); + } + // If there is no methods exported by this module, then return a not found + // response. + if (!_http.HTTP_METHODS.some((method)=>method in userland)) { + _log.error(`No HTTP methods exported in '${this.resolvedPagePath}'. Export a named export for each HTTP method.`); + } + } + } + /** + * Returns the handler function for the given HTTP method. + * Must be called after ensureUserland() has resolved so that _methods is + * populated. + */ resolveHandler(method) { + // Prevent RCE: only allow recognized HTTP methods. + if (!(0, _http.isHTTPMethod)(method)) return ()=>new Response(null, { + status: 400 + }); + return this._methods[method]; + } + /** + * Returns the handler for the given method using a live userland snapshot. + * Used in Turbopack dev mode to pick up server HMR updates. The userland + * is fetched synchronously via require() so no async overhead is added. + */ resolveHandlerFromUserland(method, userland) { + if (!(0, _http.isHTTPMethod)(method)) return ()=>new Response(null, { + status: 400 + }); + return (0, _autoimplementmethods.autoImplementMethods)(userland)[method]; + } + resolvePendingRevalidations(workStore, requestStore, context) { + const maybeRevalidatesPromise = (0, _revalidationutils.executeRevalidates)(workStore); + if (maybeRevalidatesPromise !== false) { + context.renderOpts.pendingWaitUntil = maybeRevalidatesPromise.finally(()=>{ + if (process.env.NEXT_PRIVATE_DEBUG_CACHE) { + console.log('pending revalidates promise finished for:', requestStore.url.pathname + requestStore.url.search); + } + }); + } + } + handleHandlerError(err, actionStore, workStore, requestStore, context) { + if ((0, _redirecterror.isRedirectError)(err)) { + const url = (0, _redirect.getURLFromRedirectError)(err); + if (!url) { + throw new Error('Invariant: Unexpected redirect url format'); + } + // We need to capture any headers that should be sent on the response. + const headers = new Headers({ + Location: url + }); + // Let's append any cookies that were added by the cookie API. + // TODO leaving the gate here b/c it indicates that we might not actually + // want to do this on every handler invocation. During prerender there + // should be no mutableCookies because then they'd be dynamic. + (0, _requestcookies.appendMutableCookies)(headers, requestStore.mutableCookies); + this.resolvePendingRevalidations(workStore, requestStore, context); + return new Response(null, { + // If we're in an action, we want to use a 303 redirect as we don't + // want the POST request to follow the redirect, as it could result in + // erroneous re-submissions. + status: actionStore.isAction ? _redirectstatuscode.RedirectStatusCode.SeeOther : (0, _redirect.getRedirectStatusCodeFromError)(err), + headers + }); + } + if ((0, _httpaccessfallback.isHTTPAccessFallbackError)(err)) { + const httpStatus = (0, _httpaccessfallback.getAccessFallbackHTTPStatus)(err); + return new Response(null, { + status: httpStatus + }); + } + throw err; + } + finalizeResponse(res, request, workStore, requestStore, prerenderStore, context) { + if (!(res instanceof Response)) { + var _res_constructor; + const invalidType = res === null ? 'null' : res === undefined ? 'undefined' : typeof res === 'object' ? ((_res_constructor = res.constructor) == null ? void 0 : _res_constructor.name) || 'object' : typeof res; + throw new Error(`No response is returned from route handler '${this.resolvedPagePath}'. ` + `Expected a Response object but received '${invalidType}' (method: ${request.method}, url: ${requestStore.url.pathname}). ` + `Ensure you return a \`Response\` or a \`NextResponse\` in all branches of your handler.`); + } + context.renderOpts.fetchMetrics = workStore.fetchMetrics; + this.resolvePendingRevalidations(workStore, requestStore, context); + if (prerenderStore) { + var _prerenderStore_tags; + context.renderOpts.collectedTags = (_prerenderStore_tags = prerenderStore.tags) == null ? void 0 : _prerenderStore_tags.join(','); + context.renderOpts.collectedRevalidate = prerenderStore.revalidate; + context.renderOpts.collectedExpire = prerenderStore.expire; + context.renderOpts.collectedStale = prerenderStore.stale; + } + // It's possible cookies were set in the handler, so we need to merge the + // modified cookies and the returned response here. + const headers = new Headers(res.headers); + if ((0, _requestcookies.appendMutableCookies)(headers, requestStore.mutableCookies)) { + return new Response(res.body, { + status: res.status, + statusText: res.statusText, + headers + }); + } + return res; + } + async prerenderToResponse(handler, actionStore, workStore, requestStore, implicitTags, request, context) { + const cacheComponentsEnabled = !!context.renderOpts.cacheComponents; + // Patch the global fetch. + (0, _patchfetch.patchFetch)({ + workAsyncStorage: this.workAsyncStorage, + workUnitAsyncStorage: this.workUnitAsyncStorage + }); + const handlerContext = { + params: context.params ? (0, _params.createServerParamsForRoute)((0, _parsedurlquerytoparams.parsedUrlQueryToParams)(context.params)) : undefined + }; + let prerenderStore; + let res; + try { + const userlandRevalidate = this.userland.revalidate; + const defaultRevalidate = // If the static generation store does not have a revalidate value + // set, then we should set it the revalidate value from the userland + // module or default to false. + userlandRevalidate === false || userlandRevalidate === undefined ? _constants1.INFINITE_CACHE : userlandRevalidate; + if (cacheComponentsEnabled) { + /** + * When we are attempting to statically prerender the GET handler of a route.ts module + * and cacheComponents is on we follow a similar pattern to rendering. + * + * We first run the handler letting caches fill. If something synchronously dynamic occurs + * during this prospective render then we can infer it will happen on every render and we + * just bail out of prerendering. + * + * Next we run the handler again and we check if we get a result back in a microtask. + * Next.js expects the return value to be a Response or a Thenable that resolves to a Response. + * Unfortunately Response's do not allow for accessing the response body synchronously or in + * a microtask so we need to allow one more task to unwrap the response body. This is a slightly + * different semantic than what we have when we render and it means that certain tasks can still + * execute before a prerender completes such as a carefully timed setImmediate. + * + * Functionally though IO should still take longer than the time it takes to unwrap the response body + * so our heuristic of excluding any IO should be preserved. + */ const prospectiveController = new AbortController(); + let prospectiveRenderIsDynamic = false; + const cacheSignal = new _cachesignal.CacheSignal(null); + let dynamicTracking = (0, _dynamicrendering.createDynamicTrackingState)(undefined); + // TODO: Route handlers are never resumed, so it's counter-intuitive + // to use an RDC here. However, we need the data cache to store cached + // results in memory during the prospective prerender, so that they + // can be retrieved during the final prerender within microtasks. This + // is crucial when doing revalidations of a deployed route handler, + // where the default cache handler does not do any in-memory caching. + const prerenderResumeDataCache = (0, _resumedatacache.createPrerenderResumeDataCache)(); + const prospectiveRoutePrerenderStore = prerenderStore = { + type: 'prerender', + phase: 'action', + // This replicates prior behavior where rootParams is empty in routes + // TODO we need to make this have the proper rootParams for this route + rootParams: {}, + fallbackRouteParams: null, + implicitTags, + renderSignal: prospectiveController.signal, + controller: prospectiveController, + stagedRendering: null, + cacheSignal, + // During prospective render we don't use a controller + // because we need to let all caches fill. + dynamicTracking, + revalidate: defaultRevalidate, + expire: _constants1.INFINITE_CACHE, + stale: _constants1.INFINITE_CACHE, + tags: [ + ...implicitTags.tags + ], + resumeDataCache: prerenderResumeDataCache, + hmrRefreshHash: undefined, + varyParamsAccumulator: null, + ensureStaticLevel: null, + prerenderDataTracking: null, + isFallbackUpgradeable: false + }; + let prospectiveResult; + try { + prospectiveResult = this.workUnitAsyncStorage.run(prospectiveRoutePrerenderStore, handler, request, handlerContext); + } catch (err) { + if (prospectiveController.signal.aborted) { + // the route handler called an API which is always dynamic + // there is no need to try again + prospectiveRenderIsDynamic = true; + } else if (process.env.NEXT_DEBUG_BUILD || process.env.__NEXT_VERBOSE_LOGGING) { + (0, _prospectiverenderutils.printDebugThrownValueForProspectiveRender)(err, workStore.route, _prospectiverenderutils.Phase.ProspectiveRender); + } + } + if (typeof prospectiveResult === 'object' && prospectiveResult !== null && typeof prospectiveResult.then === 'function') { + // The handler returned a Thenable. We'll listen for rejections to determine + // if the route is erroring for dynamic reasons. + ; + prospectiveResult.then(()=>{}, (err)=>{ + if (prospectiveController.signal.aborted) { + // the route handler called an API which is always dynamic + // there is no need to try again + prospectiveRenderIsDynamic = true; + } else if (process.env.NEXT_DEBUG_BUILD) { + (0, _prospectiverenderutils.printDebugThrownValueForProspectiveRender)(err, workStore.route, _prospectiverenderutils.Phase.ProspectiveRender); + } + }); + } + (0, _trackmoduleloadingexternal.trackPendingModules)(cacheSignal); + await cacheSignal.cacheReady(); + if (prospectiveRenderIsDynamic) { + // the route handler called an API which is always dynamic + // there is no need to try again + const dynamicReason = (0, _dynamicrendering.getFirstDynamicReason)(dynamicTracking); + if (dynamicReason) { + throw new _hooksservercontext.DynamicServerError(`Route ${workStore.route} couldn't be rendered statically because it used \`${dynamicReason}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`); + } else { + console.error('Expected Next.js to keep track of reason for opting out of static rendering but one was not found. This is a bug in Next.js'); + throw new _hooksservercontext.DynamicServerError(`Route ${workStore.route} couldn't be rendered statically because it used a dynamic API. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`); + } + } + // TODO start passing this controller to the route handler. We should expose + // it so the handler to abort inflight requests and other operations if we abort + // the prerender. + const finalController = new AbortController(); + dynamicTracking = (0, _dynamicrendering.createDynamicTrackingState)(undefined); + const finalRoutePrerenderStore = prerenderStore = { + type: 'prerender', + phase: 'action', + rootParams: {}, + fallbackRouteParams: null, + implicitTags, + renderSignal: finalController.signal, + controller: finalController, + stagedRendering: null, + cacheSignal: null, + dynamicTracking, + revalidate: defaultRevalidate, + expire: _constants1.INFINITE_CACHE, + stale: _constants1.INFINITE_CACHE, + tags: [ + ...implicitTags.tags + ], + resumeDataCache: prerenderResumeDataCache, + hmrRefreshHash: undefined, + varyParamsAccumulator: null, + ensureStaticLevel: null, + prerenderDataTracking: null, + isFallbackUpgradeable: false + }; + let responseHandled = false; + res = await new Promise((resolve, reject)=>{ + (0, _scheduler.scheduleImmediate)(async ()=>{ + try { + const result = await this.workUnitAsyncStorage.run(finalRoutePrerenderStore, handler, request, handlerContext); + if (responseHandled) { + // we already rejected in the followup task + return; + } else if (!(result instanceof Response)) { + // This is going to error but we let that happen below + resolve(result); + return; + } + responseHandled = true; + let bodyHandled = false; + result.arrayBuffer().then((body)=>{ + if (!bodyHandled) { + bodyHandled = true; + resolve(new Response(body, { + headers: result.headers, + status: result.status, + statusText: result.statusText + })); + } + }, reject); + (0, _scheduler.scheduleImmediate)(()=>{ + if (!bodyHandled) { + bodyHandled = true; + finalController.abort(); + reject(createCacheComponentsError(workStore.route)); + } + }); + } catch (err) { + reject(err); + } + }); + (0, _scheduler.scheduleImmediate)(()=>{ + if (!responseHandled) { + responseHandled = true; + finalController.abort(); + reject(createCacheComponentsError(workStore.route)); + } + }); + }); + if (finalController.signal.aborted) { + // We aborted from within the execution + throw createCacheComponentsError(workStore.route); + } else { + // We didn't abort during the execution. We can abort now as a matter of semantics + // though at the moment nothing actually consumes this signal so it won't halt any + // inflight work. + finalController.abort(); + } + } else { + prerenderStore = { + type: 'prerender-legacy', + phase: 'action', + rootParams: {}, + implicitTags, + revalidate: defaultRevalidate, + expire: _constants1.INFINITE_CACHE, + stale: _constants1.INFINITE_CACHE, + tags: [ + ...implicitTags.tags + ] + }; + res = await _workunitasyncstorageexternal.workUnitAsyncStorage.run(prerenderStore, handler, request, handlerContext); + } + } catch (err) { + return this.handleHandlerError(err, actionStore, workStore, requestStore, context); + } + return this.finalizeResponse(res, request, workStore, requestStore, prerenderStore, context); + } + async renderToResponse(handler, actionStore, workStore, requestStore, request, context) { + // Patch the global fetch. + (0, _patchfetch.patchFetch)({ + workAsyncStorage: this.workAsyncStorage, + workUnitAsyncStorage: this.workUnitAsyncStorage + }); + const handlerContext = { + params: context.params ? (0, _params.createServerParamsForRoute)((0, _parsedurlquerytoparams.parsedUrlQueryToParams)(context.params)) : undefined + }; + let res; + try { + res = await _workunitasyncstorageexternal.workUnitAsyncStorage.run(requestStore, handler, request, handlerContext); + } catch (err) { + return this.handleHandlerError(err, actionStore, workStore, requestStore, context); + } + return this.finalizeResponse(res, request, workStore, requestStore, null, context); + } + async prepareExecution(req, context) { + // Ensure userland is fully loaded (handles async modules with top-level + // await, where require() returns a Promise instead of the module). + await this.ensureUserland(); + // In Turbopack dev mode, fetch the live userland module on every request + // via the synchronous require() getter so server HMR updates are reflected + // immediately. This is cheap — it is just a devModuleCache lookup. + // For routes with top-level await, require() may still return a Promise + // (async module); in that case fall back to the already-resolved + // userland module resolved by ensureUserland() above. + const rawLiveUserland = this._getUserland == null ? void 0 : this._getUserland.call(this); + const liveUserland = rawLiveUserland instanceof Promise ? undefined : rawLiveUserland; + const handler = liveUserland ? this.resolveHandlerFromUserland(req.method, liveUserland) : this.resolveHandler(req.method); + // Use the live userland (if available) for per-request values so HMR + // changes to fetchCache, dynamic, etc. are also picked up. + const userland = liveUserland ?? this.userland; + // Add the fetchCache option to the renderOpts. + context.renderOpts.fetchCache = userland.fetchCache; + const actionStore = { + isAppRoute: true, + isAction: (0, _serveractionrequestmeta.getIsPossibleServerAction)(req) + }; + const implicitTags = await (0, _implicittags.getImplicitTags)(this.definition.page, req.nextUrl.pathname, // App Routes don't support unknown route params. + null); + const requestStore = (0, _requeststore.createRequestStoreForAPI)(req, req.nextUrl, implicitTags, undefined, context.previewProps, context.renderOpts.hmrRefreshHash); + return { + handler, + dynamic: (liveUserland == null ? void 0 : liveUserland.dynamic) ?? this._dynamic, + hasNonStaticMethods: liveUserland ? hasNonStaticMethods(liveUserland) : this._hasNonStaticMethods, + actionStore, + implicitTags, + requestStore + }; + } + validateExecutionResponse(response) { + // If the handler didn't return a valid response, then return the internal + // error response. + if (!(response instanceof Response)) { + // TODO: validate the correct handling behavior, maybe log something? + return new Response(null, { + status: 500 + }); + } + if (response.headers.has('x-middleware-rewrite')) { + throw new Error('NextResponse.rewrite() was used in a app route handler, this is not currently supported. Please remove the invocation to continue.'); + } + if (response.headers.get('x-middleware-next') === '1') { + // TODO: move this error into the `NextResponse.next()` function. + throw new Error('NextResponse.next() was used in a app route handler, this is not supported. See here for more info: https://nextjs.org/docs/messages/next-response-next-in-app-route-handler'); + } + return response; + } + async executeRequest(req, context, prepared, workStore) { + const { actionStore, handler, requestStore } = prepared; + const response = await this.actionAsyncStorage.run(actionStore, ()=>this.workUnitAsyncStorage.run(requestStore, ()=>this.workAsyncStorage.run(workStore, ()=>{ + let request = req; + switch(prepared.dynamic){ + case 'force-dynamic': + workStore.forceDynamic = true; + break; + case 'force-static': + workStore.forceStatic = true; + request = new Proxy(req, forceStaticRequestHandlers); + break; + case 'error': + workStore.dynamicShouldError = true; + break; + case undefined: + case 'auto': + request = proxyNextRequest(req, workStore); + break; + default: + prepared.dynamic; + } + const tracer = (0, _tracer.getTracer)(); + const { pathname } = this.definition; + tracer.setRootSpanAttribute('next.route', pathname); + return tracer.trace(_constants.AppRouteRouteHandlersSpan.runHandler, { + spanName: `executing api route (app) ${pathname}`, + attributes: { + 'next.route': pathname + } + }, ()=>this.renderToResponse(handler, actionStore, workStore, requestStore, request, context)); + }))); + return this.validateExecutionResponse(response); + } + async executePrerender(req, context, prepared, workStore) { + const { actionStore, handler, implicitTags, requestStore } = prepared; + // Run the handler with the request AsyncLocalStorage to inject the helper + // support. We set this to `unknown` because the type is not known until + // runtime when we do a instanceof check below. + const response = await this.actionAsyncStorage.run(actionStore, ()=>this.workUnitAsyncStorage.run(requestStore, ()=>this.workAsyncStorage.run(workStore, ()=>{ + if (prepared.hasNonStaticMethods) { + const err = new _hooksservercontext.DynamicServerError('Route is configured with methods that cannot be statically generated.'); + workStore.dynamicUsageDescription = err.message; + workStore.dynamicUsageStack = err.stack; + throw err; + } + let request = req; + switch(prepared.dynamic){ + case 'force-dynamic': + { + workStore.forceDynamic = true; + const err = new _hooksservercontext.DynamicServerError('Route is configured with dynamic = error which cannot be statically generated.'); + workStore.dynamicUsageDescription = err.message; + workStore.dynamicUsageStack = err.stack; + throw err; + } + case 'force-static': + workStore.forceStatic = true; + request = new Proxy(req, forceStaticRequestHandlers); + break; + case 'error': + workStore.dynamicShouldError = true; + request = new Proxy(req, ensureStaticRequestHandlers); + break; + case undefined: + case 'auto': + request = proxyNextRequest(req, workStore); + break; + default: + prepared.dynamic; + } + const tracer = (0, _tracer.getTracer)(); + const { pathname } = this.definition; + tracer.setRootSpanAttribute('next.route', pathname); + return tracer.trace(_constants.AppRouteRouteHandlersSpan.runHandler, { + spanName: `executing api route (app) ${pathname}`, + attributes: { + 'next.route': pathname + } + }, ()=>this.prerenderToResponse(handler, actionStore, workStore, requestStore, implicitTags, request, context)); + }))); + return this.validateExecutionResponse(response); + } + async handle(req, context) { + const prepared = await this.prepareExecution(req, context); + const workStore = (0, _workstore.createWorkStore)({ + page: this.definition.page, + renderOpts: context.renderOpts, + buildId: context.sharedContext.buildId, + deploymentId: context.sharedContext.deploymentId, + previouslyRevalidatedTags: [] + }); + return this.executeRequest(req, context, prepared, workStore); + } + async prerender(req, context) { + const prepared = await this.prepareExecution(req, context); + const workStore = (0, _workstore.createPrerenderWorkStore)({ + page: this.definition.page, + renderOpts: context.renderOpts, + buildId: context.sharedContext.buildId, + deploymentId: context.sharedContext.deploymentId, + previouslyRevalidatedTags: [] + }); + return this.executePrerender(req, context, prepared, workStore); + } +} +const _default = AppRouteRouteModule; +function hasNonStaticMethods(handlers) { + if (// Order these by how common they are to be used + handlers.POST || handlers.PUT || handlers.DELETE || handlers.PATCH || handlers.OPTIONS) { + return true; + } + return false; +} +// These symbols will be used to stash cached values on Proxied requests without requiring +// additional closures or storage such as WeakMaps. +const nextURLSymbol = Symbol('nextUrl'); +const requestCloneSymbol = Symbol('clone'); +const urlCloneSymbol = Symbol('clone'); +const searchParamsSymbol = Symbol('searchParams'); +const hrefSymbol = Symbol('href'); +const toStringSymbol = Symbol('toString'); +const headersSymbol = Symbol('headers'); +const cookiesSymbol = Symbol('cookies'); +/** + * The general technique with these proxy handlers is to prioritize keeping them static + * by stashing computed values on the Proxy itself. This is safe because the Proxy is + * inaccessible to the consumer since all operations are forwarded + */ const forceStaticRequestHandlers = { + get (target, prop, receiver) { + switch(prop){ + case 'headers': + return target[headersSymbol] || (target[headersSymbol] = _headers.HeadersAdapter.seal(new Headers({}))); + case 'cookies': + return target[cookiesSymbol] || (target[cookiesSymbol] = _requestcookies.RequestCookiesAdapter.seal(new _cookies.RequestCookies(new Headers({})))); + case 'nextUrl': + return target[nextURLSymbol] || (target[nextURLSymbol] = new Proxy(target.nextUrl, forceStaticNextUrlHandlers)); + case 'url': + // we don't need to separately cache this we can just read the nextUrl + // and return the href since we know it will have been stripped of any + // dynamic parts. We access via the receiver to trigger the get trap + return receiver.nextUrl.href; + case 'geo': + case 'ip': + return undefined; + case 'clone': + return target[requestCloneSymbol] || (target[requestCloneSymbol] = ()=>new Proxy(// This is vaguely unsafe but it's required since NextRequest does not implement + // clone. The reason we might expect this to work in this context is the Proxy will + // respond with static-amenable values anyway somewhat restoring the interface. + // @TODO we need to rethink NextRequest and NextURL because they are not sufficientlly + // sophisticated to adequately represent themselves in all contexts. A better approach is + // to probably embed the static generation logic into the class itself removing the need + // for any kind of proxying + target.clone(), forceStaticRequestHandlers)); + default: + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + } +}; +const forceStaticNextUrlHandlers = { + get (target, prop, receiver) { + switch(prop){ + // URL properties + case 'search': + return ''; + case 'searchParams': + return target[searchParamsSymbol] || (target[searchParamsSymbol] = new URLSearchParams()); + case 'href': + return target[hrefSymbol] || (target[hrefSymbol] = (0, _cleanurl.cleanURL)(target.href).href); + case 'toJSON': + case 'toString': + return target[toStringSymbol] || (target[toStringSymbol] = ()=>receiver.href); + // NextUrl properties + case 'url': + // Currently nextURL does not expose url but our Docs indicate that it is an available property + // I am forcing this to undefined here to avoid accidentally exposing a dynamic value later if + // the underlying nextURL ends up adding this property + return undefined; + case 'clone': + return target[urlCloneSymbol] || (target[urlCloneSymbol] = ()=>new Proxy(target.clone(), forceStaticNextUrlHandlers)); + default: + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + } +}; +function proxyNextRequest(request, workStore) { + const nextUrlHandlers = { + get (target, prop, receiver) { + switch(prop){ + case 'search': + case 'searchParams': + case 'url': + case 'href': + case 'toJSON': + case 'toString': + case 'origin': + { + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + trackDynamic(workStore, workUnitStore, `nextUrl.${prop}`); + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + case 'clone': + return target[urlCloneSymbol] || (target[urlCloneSymbol] = ()=>new Proxy(target.clone(), nextUrlHandlers)); + default: + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + } + }; + const nextRequestHandlers = { + get (target, prop) { + switch(prop){ + case 'nextUrl': + return target[nextURLSymbol] || (target[nextURLSymbol] = new Proxy(target.nextUrl, nextUrlHandlers)); + case 'headers': + case 'cookies': + case 'url': + case 'body': + case 'blob': + case 'json': + case 'text': + case 'arrayBuffer': + case 'formData': + { + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + trackDynamic(workStore, workUnitStore, `request.${prop}`); + // The receiver arg is intentionally the same as the target to fix an issue with + // edge runtime, where attempting to access internal slots with the wrong `this` context + // results in an error. + return _reflect.ReflectAdapter.get(target, prop, target); + } + case 'clone': + return target[requestCloneSymbol] || (target[requestCloneSymbol] = ()=>new Proxy(// This is vaguely unsafe but it's required since NextRequest does not implement + // clone. The reason we might expect this to work in this context is the Proxy will + // respond with static-amenable values anyway somewhat restoring the interface. + // @TODO we need to rethink NextRequest and NextURL because they are not sufficientlly + // sophisticated to adequately represent themselves in all contexts. A better approach is + // to probably embed the static generation logic into the class itself removing the need + // for any kind of proxying + target.clone(), nextRequestHandlers)); + default: + // The receiver arg is intentionally the same as the target to fix an issue with + // edge runtime, where attempting to access internal slots with the wrong `this` context + // results in an error. + return _reflect.ReflectAdapter.get(target, prop, target); + } + } + }; + return new Proxy(request, nextRequestHandlers); +} +const ensureStaticRequestHandlers = { + get (target, prop, receiver) { + switch(prop){ + case 'nextUrl': + return target[nextURLSymbol] || (target[nextURLSymbol] = new Proxy(target.nextUrl, ensureStaticNextUrlHandlers)); + case 'headers': + case 'cookies': + case 'url': + case 'body': + case 'blob': + case 'json': + case 'text': + case 'arrayBuffer': + case 'formData': + throw new _staticgenerationbailout.StaticGenBailoutError(`Route ${target.nextUrl.pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`request.${prop}\`.`); + case 'clone': + return target[requestCloneSymbol] || (target[requestCloneSymbol] = ()=>new Proxy(// This is vaguely unsafe but it's required since NextRequest does not implement + // clone. The reason we might expect this to work in this context is the Proxy will + // respond with static-amenable values anyway somewhat restoring the interface. + // @TODO we need to rethink NextRequest and NextURL because they are not sufficientlly + // sophisticated to adequately represent themselves in all contexts. A better approach is + // to probably embed the static generation logic into the class itself removing the need + // for any kind of proxying + target.clone(), ensureStaticRequestHandlers)); + default: + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + } +}; +const ensureStaticNextUrlHandlers = { + get (target, prop, receiver) { + switch(prop){ + case 'search': + case 'searchParams': + case 'url': + case 'href': + case 'toJSON': + case 'toString': + case 'origin': + throw new _staticgenerationbailout.StaticGenBailoutError(`Route ${target.pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`nextUrl.${prop}\`.`); + case 'clone': + return target[urlCloneSymbol] || (target[urlCloneSymbol] = ()=>new Proxy(target.clone(), ensureStaticNextUrlHandlers)); + default: + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + } +}; +function createCacheComponentsError(route) { + return new _hooksservercontext.DynamicServerError(`Route ${route} couldn't be rendered statically because it used IO that was not cached. See more info here: https://nextjs.org/docs/messages/cache-components`); +} +function trackDynamic(store, workUnitStore, expression) { + if (store.dynamicShouldError) { + throw new _staticgenerationbailout.StaticGenBailoutError(`Route ${store.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`); + } + if (workUnitStore) { + switch(workUnitStore.type){ + case 'cache': + case 'private-cache': + // TODO: Should we allow reading cookies and search params from the + // request for private caches in route handlers? + throw (0, _usecachemessages.createRouteHandlerRequestInUseCacheError)(store.route, expression); + case 'unstable-cache': + throw (0, _usecachemessages.createRouteHandlerRequestInUnstableCacheError)(store.route, expression); + case 'prerender': + const error = new Error(`Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-request`); + return (0, _dynamicrendering.abortAndThrowOnSynchronousRequestDataAccess)(store.route, expression, error, workUnitStore); + case 'prerender-client': + case 'validation-client': + throw new _invarianterror.InvariantError('A client prerender store should not be used for a route handler.'); + case 'prerender-runtime': + throw new _invarianterror.InvariantError('A runtime prerender store should not be used for a route handler.'); + case 'prerender-legacy': + workUnitStore.revalidate = 0; + const err = new _hooksservercontext.DynamicServerError(`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`); + store.dynamicUsageDescription = expression; + store.dynamicUsageStack = err.stack; + throw err; + case 'request': + break; + case 'build-time-generator': + break; + default: + workUnitStore; + } + } +} + +//# sourceMappingURL=module.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4686465b091bfc543dc880406829aab0b651dce4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/module.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/app-route/module.ts"],"sourcesContent":["import type { NextConfig } from '../../config-shared'\nimport type { AppRouteRouteDefinition } from '../../route-definitions/app-route-route-definition'\nimport type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config'\nimport type { NextRequest } from '../../web/spec-extension/request'\nimport type { NextURL } from '../../web/next-url'\nimport type { DeepReadonly } from '../../../shared/lib/deep-readonly'\nimport type { WorkUnitStore } from '../../app-render/work-unit-async-storage.external'\nimport type { __ApiPreviewProps } from '../../api-utils'\n\nimport {\n RouteModule,\n type RouteModuleHandleContext,\n type RouteModuleOptions,\n} from '../route-module'\nimport { createRequestStoreForAPI } from '../../async-storage/request-store'\nimport {\n createPrerenderWorkStore,\n createWorkStore,\n type WorkStoreContext,\n} from '../../async-storage/work-store'\nimport { type HTTP_METHOD, HTTP_METHODS, isHTTPMethod } from '../../web/http'\nimport { getImplicitTags, type ImplicitTags } from '../../lib/implicit-tags'\nimport { patchFetch } from '../../lib/patch-fetch'\nimport { getTracer } from '../../lib/trace/tracer'\nimport {\n AppRouteRouteHandlersSpan,\n AppRouteRouteModuleSpan,\n} from '../../lib/trace/constants'\nimport * as Log from '../../../build/output/log'\nimport { autoImplementMethods } from './helpers/auto-implement-methods'\nimport {\n appendMutableCookies,\n type ReadonlyRequestCookies,\n} from '../../web/spec-extension/adapters/request-cookies'\nimport { HeadersAdapter } from '../../web/spec-extension/adapters/headers'\nimport { RequestCookiesAdapter } from '../../web/spec-extension/adapters/request-cookies'\nimport { parsedUrlQueryToParams } from './helpers/parsed-url-query-to-params'\nimport {\n Phase,\n printDebugThrownValueForProspectiveRender,\n} from '../../app-render/prospective-render-utils'\n\nimport * as serverHooks from '../../../client/components/hooks-server-context'\nimport { DynamicServerError } from '../../../client/components/hooks-server-context'\n\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../../app-render/work-async-storage.external'\nimport {\n workUnitAsyncStorage,\n type RequestStore,\n type PrerenderStore,\n} from '../../app-render/work-unit-async-storage.external'\nimport {\n actionAsyncStorage,\n type ActionStore,\n} from '../../app-render/action-async-storage.external'\nimport * as sharedModules from './shared-modules'\nimport { getIsPossibleServerAction } from '../../lib/server-action-request-meta'\nimport { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies'\nimport { cleanURL } from './helpers/clean-url'\nimport { StaticGenBailoutError } from '../../../client/components/static-generation-bailout'\nimport { isStaticGenEnabled } from './helpers/is-static-gen-enabled'\nimport {\n abortAndThrowOnSynchronousRequestDataAccess,\n createDynamicTrackingState,\n getFirstDynamicReason,\n} from '../../app-render/dynamic-rendering'\nimport { ReflectAdapter } from '../../web/spec-extension/adapters/reflect'\nimport { CacheSignal } from '../../app-render/cache-signal'\nimport { scheduleImmediate } from '../../../lib/scheduler'\nimport { createServerParamsForRoute } from '../../request/params'\nimport type { AppSegment } from '../../../build/segment-config/app/app-segments'\nimport {\n getRedirectStatusCodeFromError,\n getURLFromRedirectError,\n} from '../../../client/components/redirect'\nimport {\n isRedirectError,\n type RedirectError,\n} from '../../../client/components/redirect-error'\nimport {\n getAccessFallbackHTTPStatus,\n isHTTPAccessFallbackError,\n} from '../../../client/components/http-access-fallback/http-access-fallback'\nimport { RedirectStatusCode } from '../../../client/components/redirect-status-code'\nimport { INFINITE_CACHE } from '../../../lib/constants'\nimport { executeRevalidates } from '../../revalidation-utils'\nimport { trackPendingModules } from '../../app-render/module-loading/track-module-loading.external'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { LazyModule } from '../../lib/lazy-module'\nimport { createPrerenderResumeDataCache } from '../../resume-data-cache/resume-data-cache'\nimport {\n createRouteHandlerRequestInUseCacheError,\n createRouteHandlerRequestInUnstableCacheError,\n} from '../../use-cache/use-cache-messages'\n\nexport class WrappedNextRouterError {\n constructor(\n public readonly error: RedirectError,\n public readonly headers?: Headers\n ) {}\n}\n\n/**\n * The AppRouteModule is the type of the module exported by the bundled App\n * Route module.\n */\nexport type AppRouteModule = typeof import('../../../build/templates/app-route')\n\nexport type AppRouteSharedContext = {\n buildId: string\n deploymentId: string\n}\n\n/**\n * AppRouteRouteHandlerContext is the context that is passed to the route\n * handler for app routes.\n */\nexport interface AppRouteRouteHandlerContext extends RouteModuleHandleContext {\n renderOpts: WorkStoreContext['renderOpts'] & CollectedCacheInfo\n previewProps: DeepReadonly<__ApiPreviewProps>\n sharedContext: AppRouteSharedContext\n}\n\ntype CollectedCacheInfo = {\n collectedTags?: string\n collectedRevalidate?: number\n collectedExpire?: number\n collectedStale?: number\n}\n\n/**\n * AppRouteHandlerFnContext is the context that is passed to the handler as the\n * second argument.\n */\ntype AppRouteHandlerFnContext = {\n params?: Promise>\n}\n\ntype PreparedAppRouteExecution = {\n handler: AppRouteHandlerFn\n dynamic: AppSegmentConfig['dynamic']\n hasNonStaticMethods: boolean\n actionStore: ActionStore\n implicitTags: ImplicitTags\n requestStore: RequestStore\n}\n\n/**\n * Handler function for app routes. If a non-Response value is returned, an error\n * will be thrown.\n */\nexport type AppRouteHandlerFn = (\n /**\n * Incoming request object.\n */\n req: NextRequest,\n /**\n * Context properties on the request (including the parameters if this was a\n * dynamic route).\n */\n ctx: AppRouteHandlerFnContext\n) => unknown\n\n/**\n * AppRouteHandlers describes the handlers for app routes that is provided by\n * the userland module.\n */\nexport type AppRouteHandlers = {\n [method in HTTP_METHOD]?: AppRouteHandlerFn\n}\n\n/**\n * AppRouteUserlandModule is the userland module that is provided for app\n * routes. This contains all the user generated code.\n */\nexport type AppRouteUserlandModule = AppRouteHandlers &\n Pick<\n AppSegmentConfig,\n 'dynamic' | 'revalidate' | 'dynamicParams' | 'fetchCache'\n > &\n Pick\n\n/**\n * AppRouteRouteModuleOptions is the options that are passed to the app route\n * module from the bundled code.\n */\nexport interface AppRouteRouteModuleOptions\n extends Omit<\n RouteModuleOptions,\n 'userland'\n > {\n readonly userland: () =>\n | AppRouteUserlandModule\n | Promise\n readonly resolvedPagePath: string\n readonly nextConfigOutput: NextConfig['output']\n /**\n * Optional synchronous getter that returns the live userland module. When\n * provided (Turbopack dev mode), it is called on every request so that\n * server HMR updates are picked up without re-executing the entry chunk.\n * Using require() instead of import() keeps this synchronous so the time\n * spent here is not incorrectly attributed to application-code in timing.\n */\n readonly getUserland?: () => AppRouteUserlandModule\n}\n\n/**\n * AppRouteRouteHandler is the handler for app routes.\n */\nexport class AppRouteRouteModule extends RouteModule<\n AppRouteRouteDefinition,\n AppRouteUserlandModule\n> {\n /**\n * A reference to the request async storage.\n */\n public readonly workUnitAsyncStorage = workUnitAsyncStorage\n\n /**\n * A reference to the static generation async storage.\n */\n public readonly workAsyncStorage = workAsyncStorage\n\n /**\n * An interface to call server hooks which interact with the underlying\n * storage.\n */\n public readonly serverHooks = serverHooks\n\n public static readonly sharedModules = sharedModules\n\n /**\n * A reference to the mutation related async storage, such as mutations of\n * cookies.\n */\n public readonly actionAsyncStorage = actionAsyncStorage\n\n public readonly resolvedPagePath: string\n public readonly nextConfigOutput: NextConfig['output'] | undefined\n\n // Loaded lazily since the route file may be an async module (top-level\n // await).\n private readonly _lazyUserland: LazyModule\n // Synchronous per-request userland getter for Turbopack dev mode.\n // Called on every request to pick up server HMR updates.\n private readonly _getUserland?: () => AppRouteUserlandModule\n private _methods!: Record\n private _hasNonStaticMethods!: boolean\n private _dynamic!: AppRouteUserlandModule['dynamic']\n\n override get userland(): AppRouteUserlandModule {\n return this._lazyUserland.assertLoaded()\n }\n\n /**\n * Ensures the userland module is fully loaded before it's accessed via\n * `userland`. Required for route files that use top-level await, where\n * require() returns a promise instead of the module directly. Must be called\n * before accessing `userland` in contexts where the module may not yet be\n * resolved (e.g. the export/static-generation worker).\n */\n async ensureUserland(): Promise {\n await this._lazyUserland.waitUntilLoaded()\n }\n\n constructor({\n userland,\n getUserland,\n definition,\n distDir,\n relativeProjectDir,\n resolvedPagePath,\n nextConfigOutput,\n }: AppRouteRouteModuleOptions) {\n super({\n userland: undefined! as AppRouteUserlandModule,\n definition,\n distDir,\n relativeProjectDir,\n })\n\n this.resolvedPagePath = resolvedPagePath\n this.nextConfigOutput = nextConfigOutput\n this._getUserland = getUserland\n this._lazyUserland = new LazyModule(\n () =>\n getTracer().trace(\n AppRouteRouteModuleSpan.loadUserland,\n {\n spanName: 'load app route module',\n attributes: {\n 'next.route': this.definition.pathname,\n },\n },\n userland\n ),\n (module) => this._onUserlandLoaded(module)\n )\n\n // output:export routes load eagerly, so that errors surface at module\n // load time (as a Redbox in dev) rather than at request time.\n if (nextConfigOutput === 'export') {\n this._lazyUserland.loadIfNeeded()\n }\n }\n\n private _onUserlandLoaded(userland: AppRouteUserlandModule): void {\n // Automatically implement some methods if they aren't implemented by the\n // userland module.\n this._methods = autoImplementMethods(userland)\n\n // Get the non-static methods for this route.\n this._hasNonStaticMethods = hasNonStaticMethods(userland)\n\n // Get the dynamic property from the userland module.\n this._dynamic = userland.dynamic\n if (this.nextConfigOutput === 'export') {\n if (this._dynamic === 'force-dynamic') {\n throw new Error(\n `export const dynamic = \"force-dynamic\" on page \"${this.definition.pathname}\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`\n )\n } else if (!isStaticGenEnabled(userland) && userland['GET']) {\n throw new Error(\n `export const dynamic = \"force-static\"/export const revalidate not configured on route \"${this.definition.pathname}\" with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`\n )\n } else {\n this._dynamic = 'error'\n }\n }\n\n // We only warn in development after here, so return if we're not in\n // development.\n if (process.env.NODE_ENV === 'development') {\n // Print error in development if the exported handlers are in lowercase, only\n // uppercase handlers are supported.\n const lowercased = HTTP_METHODS.map((method) => method.toLowerCase())\n for (const method of lowercased) {\n if (method in userland) {\n Log.error(\n `Detected lowercase method '${method}' in '${\n this.resolvedPagePath\n }'. Export the uppercase '${method.toUpperCase()}' method name to fix this error.`\n )\n }\n }\n\n // Print error if the module exports a default handler, they must use named\n // exports for each HTTP method.\n if ('default' in userland) {\n Log.error(\n `Detected default export in '${this.resolvedPagePath}'. Export a named export for each HTTP method instead.`\n )\n }\n\n // If there is no methods exported by this module, then return a not found\n // response.\n if (!HTTP_METHODS.some((method) => method in userland)) {\n Log.error(\n `No HTTP methods exported in '${this.resolvedPagePath}'. Export a named export for each HTTP method.`\n )\n }\n }\n }\n\n /**\n * Returns the handler function for the given HTTP method.\n * Must be called after ensureUserland() has resolved so that _methods is\n * populated.\n */\n private resolveHandler(method: string): AppRouteHandlerFn {\n // Prevent RCE: only allow recognized HTTP methods.\n if (!isHTTPMethod(method)) return () => new Response(null, { status: 400 })\n\n return this._methods[method]\n }\n\n /**\n * Returns the handler for the given method using a live userland snapshot.\n * Used in Turbopack dev mode to pick up server HMR updates. The userland\n * is fetched synchronously via require() so no async overhead is added.\n */\n private resolveHandlerFromUserland(\n method: string,\n userland: AppRouteUserlandModule\n ): AppRouteHandlerFn {\n if (!isHTTPMethod(method)) return () => new Response(null, { status: 400 })\n return autoImplementMethods(userland)[method]\n }\n\n private resolvePendingRevalidations(\n workStore: WorkStore,\n requestStore: RequestStore,\n context: AppRouteRouteHandlerContext\n ): void {\n const maybeRevalidatesPromise = executeRevalidates(workStore)\n\n if (maybeRevalidatesPromise !== false) {\n context.renderOpts.pendingWaitUntil = maybeRevalidatesPromise.finally(\n () => {\n if (process.env.NEXT_PRIVATE_DEBUG_CACHE) {\n console.log(\n 'pending revalidates promise finished for:',\n requestStore.url.pathname + requestStore.url.search\n )\n }\n }\n )\n }\n }\n\n private handleHandlerError(\n err: unknown,\n actionStore: ActionStore,\n workStore: WorkStore,\n requestStore: RequestStore,\n context: AppRouteRouteHandlerContext\n ): Response {\n if (isRedirectError(err)) {\n const url = getURLFromRedirectError(err)\n if (!url) {\n throw new Error('Invariant: Unexpected redirect url format')\n }\n\n // We need to capture any headers that should be sent on the response.\n const headers = new Headers({ Location: url })\n\n // Let's append any cookies that were added by the cookie API.\n // TODO leaving the gate here b/c it indicates that we might not actually\n // want to do this on every handler invocation. During prerender there\n // should be no mutableCookies because then they'd be dynamic.\n appendMutableCookies(headers, requestStore.mutableCookies)\n\n this.resolvePendingRevalidations(workStore, requestStore, context)\n\n return new Response(null, {\n // If we're in an action, we want to use a 303 redirect as we don't\n // want the POST request to follow the redirect, as it could result in\n // erroneous re-submissions.\n status: actionStore.isAction\n ? RedirectStatusCode.SeeOther\n : getRedirectStatusCodeFromError(err),\n headers,\n })\n }\n\n if (isHTTPAccessFallbackError(err)) {\n const httpStatus = getAccessFallbackHTTPStatus(err)\n return new Response(null, { status: httpStatus })\n }\n\n throw err\n }\n\n private finalizeResponse(\n res: unknown,\n request: NextRequest,\n workStore: WorkStore,\n requestStore: RequestStore,\n prerenderStore: PrerenderStore | null,\n context: AppRouteRouteHandlerContext\n ): Response {\n if (!(res instanceof Response)) {\n const invalidType =\n res === null\n ? 'null'\n : res === undefined\n ? 'undefined'\n : typeof res === 'object'\n ? res.constructor?.name || 'object'\n : typeof res\n\n throw new Error(\n `No response is returned from route handler '${this.resolvedPagePath}'. ` +\n `Expected a Response object but received '${invalidType}' (method: ${request.method}, url: ${requestStore.url.pathname}). ` +\n `Ensure you return a \\`Response\\` or a \\`NextResponse\\` in all branches of your handler.`\n )\n }\n\n context.renderOpts.fetchMetrics = workStore.fetchMetrics\n this.resolvePendingRevalidations(workStore, requestStore, context)\n\n if (prerenderStore) {\n context.renderOpts.collectedTags = prerenderStore.tags?.join(',')\n context.renderOpts.collectedRevalidate = prerenderStore.revalidate\n context.renderOpts.collectedExpire = prerenderStore.expire\n context.renderOpts.collectedStale = prerenderStore.stale\n }\n\n // It's possible cookies were set in the handler, so we need to merge the\n // modified cookies and the returned response here.\n const headers = new Headers(res.headers)\n if (appendMutableCookies(headers, requestStore.mutableCookies)) {\n return new Response(res.body, {\n status: res.status,\n statusText: res.statusText,\n headers,\n })\n }\n\n return res\n }\n\n private async prerenderToResponse(\n handler: AppRouteHandlerFn,\n actionStore: ActionStore,\n workStore: WorkStore,\n requestStore: RequestStore,\n implicitTags: ImplicitTags,\n request: NextRequest,\n context: AppRouteRouteHandlerContext\n ) {\n const cacheComponentsEnabled = !!context.renderOpts.cacheComponents\n\n // Patch the global fetch.\n patchFetch({\n workAsyncStorage: this.workAsyncStorage,\n workUnitAsyncStorage: this.workUnitAsyncStorage,\n })\n\n const handlerContext: AppRouteHandlerFnContext = {\n params: context.params\n ? createServerParamsForRoute(parsedUrlQueryToParams(context.params))\n : undefined,\n }\n\n let prerenderStore: PrerenderStore\n\n let res: unknown\n try {\n const userlandRevalidate = this.userland.revalidate\n const defaultRevalidate: number =\n // If the static generation store does not have a revalidate value\n // set, then we should set it the revalidate value from the userland\n // module or default to false.\n userlandRevalidate === false || userlandRevalidate === undefined\n ? INFINITE_CACHE\n : userlandRevalidate\n\n if (cacheComponentsEnabled) {\n /**\n * When we are attempting to statically prerender the GET handler of a route.ts module\n * and cacheComponents is on we follow a similar pattern to rendering.\n *\n * We first run the handler letting caches fill. If something synchronously dynamic occurs\n * during this prospective render then we can infer it will happen on every render and we\n * just bail out of prerendering.\n *\n * Next we run the handler again and we check if we get a result back in a microtask.\n * Next.js expects the return value to be a Response or a Thenable that resolves to a Response.\n * Unfortunately Response's do not allow for accessing the response body synchronously or in\n * a microtask so we need to allow one more task to unwrap the response body. This is a slightly\n * different semantic than what we have when we render and it means that certain tasks can still\n * execute before a prerender completes such as a carefully timed setImmediate.\n *\n * Functionally though IO should still take longer than the time it takes to unwrap the response body\n * so our heuristic of excluding any IO should be preserved.\n */\n const prospectiveController = new AbortController()\n let prospectiveRenderIsDynamic = false\n const cacheSignal = new CacheSignal(null)\n let dynamicTracking = createDynamicTrackingState(undefined)\n\n // TODO: Route handlers are never resumed, so it's counter-intuitive\n // to use an RDC here. However, we need the data cache to store cached\n // results in memory during the prospective prerender, so that they\n // can be retrieved during the final prerender within microtasks. This\n // is crucial when doing revalidations of a deployed route handler,\n // where the default cache handler does not do any in-memory caching.\n const prerenderResumeDataCache = createPrerenderResumeDataCache()\n\n const prospectiveRoutePrerenderStore: PrerenderStore = (prerenderStore =\n {\n type: 'prerender',\n phase: 'action',\n // This replicates prior behavior where rootParams is empty in routes\n // TODO we need to make this have the proper rootParams for this route\n rootParams: {},\n fallbackRouteParams: null,\n implicitTags,\n renderSignal: prospectiveController.signal,\n controller: prospectiveController,\n stagedRendering: null,\n cacheSignal,\n // During prospective render we don't use a controller\n // because we need to let all caches fill.\n dynamicTracking,\n revalidate: defaultRevalidate,\n expire: INFINITE_CACHE,\n stale: INFINITE_CACHE,\n tags: [...implicitTags.tags],\n resumeDataCache: prerenderResumeDataCache,\n hmrRefreshHash: undefined,\n varyParamsAccumulator: null,\n ensureStaticLevel: null,\n prerenderDataTracking: null,\n isFallbackUpgradeable: false,\n })\n\n let prospectiveResult\n try {\n prospectiveResult = this.workUnitAsyncStorage.run(\n prospectiveRoutePrerenderStore,\n handler,\n request,\n handlerContext\n )\n } catch (err) {\n if (prospectiveController.signal.aborted) {\n // the route handler called an API which is always dynamic\n // there is no need to try again\n prospectiveRenderIsDynamic = true\n } else if (\n process.env.NEXT_DEBUG_BUILD ||\n process.env.__NEXT_VERBOSE_LOGGING\n ) {\n printDebugThrownValueForProspectiveRender(\n err,\n workStore.route,\n Phase.ProspectiveRender\n )\n }\n }\n if (\n typeof prospectiveResult === 'object' &&\n prospectiveResult !== null &&\n typeof (prospectiveResult as any).then === 'function'\n ) {\n // The handler returned a Thenable. We'll listen for rejections to determine\n // if the route is erroring for dynamic reasons.\n ;(prospectiveResult as any as Promise).then(\n () => {},\n (err) => {\n if (prospectiveController.signal.aborted) {\n // the route handler called an API which is always dynamic\n // there is no need to try again\n prospectiveRenderIsDynamic = true\n } else if (process.env.NEXT_DEBUG_BUILD) {\n printDebugThrownValueForProspectiveRender(\n err,\n workStore.route,\n Phase.ProspectiveRender\n )\n }\n }\n )\n }\n\n trackPendingModules(cacheSignal)\n await cacheSignal.cacheReady()\n\n if (prospectiveRenderIsDynamic) {\n // the route handler called an API which is always dynamic\n // there is no need to try again\n const dynamicReason = getFirstDynamicReason(dynamicTracking)\n if (dynamicReason) {\n throw new DynamicServerError(\n `Route ${workStore.route} couldn't be rendered statically because it used \\`${dynamicReason}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n } else {\n console.error(\n 'Expected Next.js to keep track of reason for opting out of static rendering but one was not found. This is a bug in Next.js'\n )\n throw new DynamicServerError(\n `Route ${workStore.route} couldn't be rendered statically because it used a dynamic API. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n }\n }\n\n // TODO start passing this controller to the route handler. We should expose\n // it so the handler to abort inflight requests and other operations if we abort\n // the prerender.\n const finalController = new AbortController()\n dynamicTracking = createDynamicTrackingState(undefined)\n\n const finalRoutePrerenderStore: PrerenderStore = (prerenderStore = {\n type: 'prerender',\n phase: 'action',\n rootParams: {},\n fallbackRouteParams: null,\n implicitTags,\n renderSignal: finalController.signal,\n controller: finalController,\n stagedRendering: null,\n cacheSignal: null,\n dynamicTracking,\n revalidate: defaultRevalidate,\n expire: INFINITE_CACHE,\n stale: INFINITE_CACHE,\n tags: [...implicitTags.tags],\n resumeDataCache: prerenderResumeDataCache,\n hmrRefreshHash: undefined,\n varyParamsAccumulator: null,\n ensureStaticLevel: null,\n prerenderDataTracking: null,\n isFallbackUpgradeable: false,\n })\n\n let responseHandled = false\n res = await new Promise((resolve, reject) => {\n scheduleImmediate(async () => {\n try {\n const result = await (this.workUnitAsyncStorage.run(\n finalRoutePrerenderStore,\n handler,\n request,\n handlerContext\n ) as Promise)\n if (responseHandled) {\n // we already rejected in the followup task\n return\n } else if (!(result instanceof Response)) {\n // This is going to error but we let that happen below\n resolve(result)\n return\n }\n\n responseHandled = true\n\n let bodyHandled = false\n result.arrayBuffer().then((body) => {\n if (!bodyHandled) {\n bodyHandled = true\n\n resolve(\n new Response(body, {\n headers: result.headers,\n status: result.status,\n statusText: result.statusText,\n })\n )\n }\n }, reject)\n scheduleImmediate(() => {\n if (!bodyHandled) {\n bodyHandled = true\n finalController.abort()\n reject(createCacheComponentsError(workStore.route))\n }\n })\n } catch (err) {\n reject(err)\n }\n })\n scheduleImmediate(() => {\n if (!responseHandled) {\n responseHandled = true\n finalController.abort()\n reject(createCacheComponentsError(workStore.route))\n }\n })\n })\n if (finalController.signal.aborted) {\n // We aborted from within the execution\n throw createCacheComponentsError(workStore.route)\n } else {\n // We didn't abort during the execution. We can abort now as a matter of semantics\n // though at the moment nothing actually consumes this signal so it won't halt any\n // inflight work.\n finalController.abort()\n }\n } else {\n prerenderStore = {\n type: 'prerender-legacy',\n phase: 'action',\n rootParams: {},\n implicitTags,\n revalidate: defaultRevalidate,\n expire: INFINITE_CACHE,\n stale: INFINITE_CACHE,\n tags: [...implicitTags.tags],\n }\n\n res = await workUnitAsyncStorage.run(\n prerenderStore,\n handler,\n request,\n handlerContext\n )\n }\n } catch (err) {\n return this.handleHandlerError(\n err,\n actionStore,\n workStore,\n requestStore,\n context\n )\n }\n\n return this.finalizeResponse(\n res,\n request,\n workStore,\n requestStore,\n prerenderStore,\n context\n )\n }\n\n private async renderToResponse(\n handler: AppRouteHandlerFn,\n actionStore: ActionStore,\n workStore: WorkStore,\n requestStore: RequestStore,\n request: NextRequest,\n context: AppRouteRouteHandlerContext\n ): Promise {\n // Patch the global fetch.\n patchFetch({\n workAsyncStorage: this.workAsyncStorage,\n workUnitAsyncStorage: this.workUnitAsyncStorage,\n })\n\n const handlerContext: AppRouteHandlerFnContext = {\n params: context.params\n ? createServerParamsForRoute(parsedUrlQueryToParams(context.params))\n : undefined,\n }\n\n let res: unknown\n try {\n res = await workUnitAsyncStorage.run(\n requestStore,\n handler,\n request,\n handlerContext\n )\n } catch (err) {\n return this.handleHandlerError(\n err,\n actionStore,\n workStore,\n requestStore,\n context\n )\n }\n\n return this.finalizeResponse(\n res,\n request,\n workStore,\n requestStore,\n null,\n context\n )\n }\n\n private async prepareExecution(\n req: NextRequest,\n context: AppRouteRouteHandlerContext\n ): Promise {\n // Ensure userland is fully loaded (handles async modules with top-level\n // await, where require() returns a Promise instead of the module).\n await this.ensureUserland()\n\n // In Turbopack dev mode, fetch the live userland module on every request\n // via the synchronous require() getter so server HMR updates are reflected\n // immediately. This is cheap — it is just a devModuleCache lookup.\n // For routes with top-level await, require() may still return a Promise\n // (async module); in that case fall back to the already-resolved\n // userland module resolved by ensureUserland() above.\n const rawLiveUserland = this._getUserland?.()\n const liveUserland =\n rawLiveUserland instanceof Promise\n ? undefined\n : (rawLiveUserland as AppRouteUserlandModule | undefined)\n\n const handler = liveUserland\n ? this.resolveHandlerFromUserland(req.method, liveUserland)\n : this.resolveHandler(req.method)\n\n // Use the live userland (if available) for per-request values so HMR\n // changes to fetchCache, dynamic, etc. are also picked up.\n const userland = liveUserland ?? this.userland\n\n // Add the fetchCache option to the renderOpts.\n context.renderOpts.fetchCache = userland.fetchCache\n\n const actionStore: ActionStore = {\n isAppRoute: true,\n isAction: getIsPossibleServerAction(req),\n }\n\n const implicitTags = await getImplicitTags(\n this.definition.page,\n req.nextUrl.pathname,\n // App Routes don't support unknown route params.\n null\n )\n\n const requestStore = createRequestStoreForAPI(\n req,\n req.nextUrl,\n implicitTags,\n undefined,\n context.previewProps,\n context.renderOpts.hmrRefreshHash\n )\n\n return {\n handler,\n dynamic: liveUserland?.dynamic ?? this._dynamic,\n hasNonStaticMethods: liveUserland\n ? hasNonStaticMethods(liveUserland)\n : this._hasNonStaticMethods,\n actionStore,\n implicitTags,\n requestStore,\n }\n }\n\n private validateExecutionResponse(response: unknown): Response {\n // If the handler didn't return a valid response, then return the internal\n // error response.\n if (!(response instanceof Response)) {\n // TODO: validate the correct handling behavior, maybe log something?\n return new Response(null, { status: 500 })\n }\n\n if (response.headers.has('x-middleware-rewrite')) {\n throw new Error(\n 'NextResponse.rewrite() was used in a app route handler, this is not currently supported. Please remove the invocation to continue.'\n )\n }\n\n if (response.headers.get('x-middleware-next') === '1') {\n // TODO: move this error into the `NextResponse.next()` function.\n throw new Error(\n 'NextResponse.next() was used in a app route handler, this is not supported. See here for more info: https://nextjs.org/docs/messages/next-response-next-in-app-route-handler'\n )\n }\n\n return response\n }\n\n private async executeRequest(\n req: NextRequest,\n context: AppRouteRouteHandlerContext,\n prepared: PreparedAppRouteExecution,\n workStore: WorkStore\n ): Promise {\n const { actionStore, handler, requestStore } = prepared\n\n const response: unknown = await this.actionAsyncStorage.run(\n actionStore,\n () =>\n this.workUnitAsyncStorage.run(requestStore, () =>\n this.workAsyncStorage.run(workStore, () => {\n let request = req\n\n switch (prepared.dynamic) {\n case 'force-dynamic':\n workStore.forceDynamic = true\n break\n case 'force-static':\n workStore.forceStatic = true\n request = new Proxy(req, forceStaticRequestHandlers)\n break\n case 'error':\n workStore.dynamicShouldError = true\n break\n case undefined:\n case 'auto':\n request = proxyNextRequest(req, workStore)\n break\n default:\n prepared.dynamic satisfies never\n }\n\n const tracer = getTracer()\n const { pathname } = this.definition\n tracer.setRootSpanAttribute('next.route', pathname)\n\n return tracer.trace(\n AppRouteRouteHandlersSpan.runHandler,\n {\n spanName: `executing api route (app) ${pathname}`,\n attributes: {\n 'next.route': pathname,\n },\n },\n () =>\n this.renderToResponse(\n handler,\n actionStore,\n workStore,\n requestStore,\n request,\n context\n )\n )\n })\n )\n )\n\n return this.validateExecutionResponse(response)\n }\n\n private async executePrerender(\n req: NextRequest,\n context: AppRouteRouteHandlerContext,\n prepared: PreparedAppRouteExecution,\n workStore: WorkStore\n ): Promise {\n const { actionStore, handler, implicitTags, requestStore } = prepared\n\n // Run the handler with the request AsyncLocalStorage to inject the helper\n // support. We set this to `unknown` because the type is not known until\n // runtime when we do a instanceof check below.\n const response: unknown = await this.actionAsyncStorage.run(\n actionStore,\n () =>\n this.workUnitAsyncStorage.run(requestStore, () =>\n this.workAsyncStorage.run(workStore, () => {\n if (prepared.hasNonStaticMethods) {\n const err = new DynamicServerError(\n 'Route is configured with methods that cannot be statically generated.'\n )\n workStore.dynamicUsageDescription = err.message\n workStore.dynamicUsageStack = err.stack\n throw err\n }\n\n let request = req\n\n switch (prepared.dynamic) {\n case 'force-dynamic': {\n workStore.forceDynamic = true\n const err = new DynamicServerError(\n 'Route is configured with dynamic = error which cannot be statically generated.'\n )\n workStore.dynamicUsageDescription = err.message\n workStore.dynamicUsageStack = err.stack\n throw err\n }\n case 'force-static':\n workStore.forceStatic = true\n request = new Proxy(req, forceStaticRequestHandlers)\n break\n case 'error':\n workStore.dynamicShouldError = true\n request = new Proxy(req, ensureStaticRequestHandlers)\n break\n case undefined:\n case 'auto':\n request = proxyNextRequest(req, workStore)\n break\n default:\n prepared.dynamic satisfies never\n }\n\n const tracer = getTracer()\n const { pathname } = this.definition\n tracer.setRootSpanAttribute('next.route', pathname)\n\n return tracer.trace(\n AppRouteRouteHandlersSpan.runHandler,\n {\n spanName: `executing api route (app) ${pathname}`,\n attributes: {\n 'next.route': pathname,\n },\n },\n () =>\n this.prerenderToResponse(\n handler,\n actionStore,\n workStore,\n requestStore,\n implicitTags,\n request,\n context\n )\n )\n })\n )\n )\n\n return this.validateExecutionResponse(response)\n }\n\n public async handle(\n req: NextRequest,\n context: AppRouteRouteHandlerContext\n ): Promise {\n const prepared = await this.prepareExecution(req, context)\n const workStore = createWorkStore({\n page: this.definition.page,\n renderOpts: context.renderOpts,\n buildId: context.sharedContext.buildId,\n deploymentId: context.sharedContext.deploymentId,\n previouslyRevalidatedTags: [],\n })\n\n return this.executeRequest(req, context, prepared, workStore)\n }\n\n public async prerender(\n req: NextRequest,\n context: AppRouteRouteHandlerContext\n ): Promise {\n const prepared = await this.prepareExecution(req, context)\n const workStore = createPrerenderWorkStore({\n page: this.definition.page,\n renderOpts: context.renderOpts,\n buildId: context.sharedContext.buildId,\n deploymentId: context.sharedContext.deploymentId,\n previouslyRevalidatedTags: [],\n })\n\n return this.executePrerender(req, context, prepared, workStore)\n }\n}\n\nexport default AppRouteRouteModule\n\n/**\n * Gets all the method names for handlers that are not considered static.\n *\n * @param handlers the handlers from the userland module\n * @returns the method names that are not considered static or false if all\n * methods are static\n */\nexport function hasNonStaticMethods(handlers: AppRouteHandlers): boolean {\n if (\n // Order these by how common they are to be used\n handlers.POST ||\n handlers.PUT ||\n handlers.DELETE ||\n handlers.PATCH ||\n handlers.OPTIONS\n ) {\n return true\n }\n return false\n}\n\n// These symbols will be used to stash cached values on Proxied requests without requiring\n// additional closures or storage such as WeakMaps.\nconst nextURLSymbol = Symbol('nextUrl')\nconst requestCloneSymbol = Symbol('clone')\nconst urlCloneSymbol = Symbol('clone')\nconst searchParamsSymbol = Symbol('searchParams')\nconst hrefSymbol = Symbol('href')\nconst toStringSymbol = Symbol('toString')\nconst headersSymbol = Symbol('headers')\nconst cookiesSymbol = Symbol('cookies')\n\ntype RequestSymbolTarget = {\n [headersSymbol]?: Headers\n [cookiesSymbol]?: RequestCookies | ReadonlyRequestCookies\n [nextURLSymbol]?: NextURL\n [requestCloneSymbol]?: () => NextRequest\n}\n\ntype UrlSymbolTarget = {\n [searchParamsSymbol]?: URLSearchParams\n [hrefSymbol]?: string\n [toStringSymbol]?: () => string\n [urlCloneSymbol]?: () => NextURL\n}\n\n/**\n * The general technique with these proxy handlers is to prioritize keeping them static\n * by stashing computed values on the Proxy itself. This is safe because the Proxy is\n * inaccessible to the consumer since all operations are forwarded\n */\nconst forceStaticRequestHandlers = {\n get(\n target: NextRequest & RequestSymbolTarget,\n prop: string | symbol,\n receiver: any\n ): unknown {\n switch (prop) {\n case 'headers':\n return (\n target[headersSymbol] ||\n (target[headersSymbol] = HeadersAdapter.seal(new Headers({})))\n )\n case 'cookies':\n return (\n target[cookiesSymbol] ||\n (target[cookiesSymbol] = RequestCookiesAdapter.seal(\n new RequestCookies(new Headers({}))\n ))\n )\n case 'nextUrl':\n return (\n target[nextURLSymbol] ||\n (target[nextURLSymbol] = new Proxy(\n target.nextUrl,\n forceStaticNextUrlHandlers\n ))\n )\n case 'url':\n // we don't need to separately cache this we can just read the nextUrl\n // and return the href since we know it will have been stripped of any\n // dynamic parts. We access via the receiver to trigger the get trap\n return receiver.nextUrl.href\n case 'geo':\n case 'ip':\n return undefined\n case 'clone':\n return (\n target[requestCloneSymbol] ||\n (target[requestCloneSymbol] = () =>\n new Proxy(\n // This is vaguely unsafe but it's required since NextRequest does not implement\n // clone. The reason we might expect this to work in this context is the Proxy will\n // respond with static-amenable values anyway somewhat restoring the interface.\n // @TODO we need to rethink NextRequest and NextURL because they are not sufficientlly\n // sophisticated to adequately represent themselves in all contexts. A better approach is\n // to probably embed the static generation logic into the class itself removing the need\n // for any kind of proxying\n target.clone() as NextRequest,\n forceStaticRequestHandlers\n ))\n )\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n // We don't need to proxy set because all the properties we proxy are ready only\n // and will be ignored\n}\n\nconst forceStaticNextUrlHandlers = {\n get(\n target: NextURL & UrlSymbolTarget,\n prop: string | symbol,\n receiver: any\n ): unknown {\n switch (prop) {\n // URL properties\n case 'search':\n return ''\n case 'searchParams':\n return (\n target[searchParamsSymbol] ||\n (target[searchParamsSymbol] = new URLSearchParams())\n )\n case 'href':\n return (\n target[hrefSymbol] ||\n (target[hrefSymbol] = cleanURL(target.href).href)\n )\n case 'toJSON':\n case 'toString':\n return (\n target[toStringSymbol] ||\n (target[toStringSymbol] = () => receiver.href)\n )\n\n // NextUrl properties\n case 'url':\n // Currently nextURL does not expose url but our Docs indicate that it is an available property\n // I am forcing this to undefined here to avoid accidentally exposing a dynamic value later if\n // the underlying nextURL ends up adding this property\n return undefined\n case 'clone':\n return (\n target[urlCloneSymbol] ||\n (target[urlCloneSymbol] = () =>\n new Proxy(target.clone(), forceStaticNextUrlHandlers))\n )\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n}\n\nfunction proxyNextRequest(request: NextRequest, workStore: WorkStore) {\n const nextUrlHandlers = {\n get(\n target: NextURL & UrlSymbolTarget,\n prop: string | symbol,\n receiver: any\n ): unknown {\n switch (prop) {\n case 'search':\n case 'searchParams':\n case 'url':\n case 'href':\n case 'toJSON':\n case 'toString':\n case 'origin': {\n const workUnitStore = workUnitAsyncStorage.getStore()\n trackDynamic(workStore, workUnitStore, `nextUrl.${prop}`)\n return ReflectAdapter.get(target, prop, receiver)\n }\n case 'clone':\n return (\n target[urlCloneSymbol] ||\n (target[urlCloneSymbol] = () =>\n new Proxy(target.clone(), nextUrlHandlers))\n )\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n }\n\n const nextRequestHandlers = {\n get(\n target: NextRequest & RequestSymbolTarget,\n prop: string | symbol\n ): unknown {\n switch (prop) {\n case 'nextUrl':\n return (\n target[nextURLSymbol] ||\n (target[nextURLSymbol] = new Proxy(target.nextUrl, nextUrlHandlers))\n )\n case 'headers':\n case 'cookies':\n case 'url':\n case 'body':\n case 'blob':\n case 'json':\n case 'text':\n case 'arrayBuffer':\n case 'formData': {\n const workUnitStore = workUnitAsyncStorage.getStore()\n trackDynamic(workStore, workUnitStore, `request.${prop}`)\n // The receiver arg is intentionally the same as the target to fix an issue with\n // edge runtime, where attempting to access internal slots with the wrong `this` context\n // results in an error.\n return ReflectAdapter.get(target, prop, target)\n }\n case 'clone':\n return (\n target[requestCloneSymbol] ||\n (target[requestCloneSymbol] = () =>\n new Proxy(\n // This is vaguely unsafe but it's required since NextRequest does not implement\n // clone. The reason we might expect this to work in this context is the Proxy will\n // respond with static-amenable values anyway somewhat restoring the interface.\n // @TODO we need to rethink NextRequest and NextURL because they are not sufficientlly\n // sophisticated to adequately represent themselves in all contexts. A better approach is\n // to probably embed the static generation logic into the class itself removing the need\n // for any kind of proxying\n target.clone() as NextRequest,\n nextRequestHandlers\n ))\n )\n default:\n // The receiver arg is intentionally the same as the target to fix an issue with\n // edge runtime, where attempting to access internal slots with the wrong `this` context\n // results in an error.\n return ReflectAdapter.get(target, prop, target)\n }\n },\n // We don't need to proxy set because all the properties we proxy are ready only\n // and will be ignored\n }\n\n return new Proxy(request, nextRequestHandlers)\n}\n\nconst ensureStaticRequestHandlers = {\n get(\n target: NextRequest & RequestSymbolTarget,\n prop: string | symbol,\n receiver: any\n ): unknown {\n switch (prop) {\n case 'nextUrl':\n return (\n target[nextURLSymbol] ||\n (target[nextURLSymbol] = new Proxy(\n target.nextUrl,\n ensureStaticNextUrlHandlers\n ))\n )\n case 'headers':\n case 'cookies':\n case 'url':\n case 'body':\n case 'blob':\n case 'json':\n case 'text':\n case 'arrayBuffer':\n case 'formData':\n throw new StaticGenBailoutError(\n `Route ${target.nextUrl.pathname} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`request.${prop}\\`.`\n )\n case 'clone':\n return (\n target[requestCloneSymbol] ||\n (target[requestCloneSymbol] = () =>\n new Proxy(\n // This is vaguely unsafe but it's required since NextRequest does not implement\n // clone. The reason we might expect this to work in this context is the Proxy will\n // respond with static-amenable values anyway somewhat restoring the interface.\n // @TODO we need to rethink NextRequest and NextURL because they are not sufficientlly\n // sophisticated to adequately represent themselves in all contexts. A better approach is\n // to probably embed the static generation logic into the class itself removing the need\n // for any kind of proxying\n target.clone() as NextRequest,\n ensureStaticRequestHandlers\n ))\n )\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n // We don't need to proxy set because all the properties we proxy are ready only\n // and will be ignored\n}\n\nconst ensureStaticNextUrlHandlers = {\n get(\n target: NextURL & UrlSymbolTarget,\n prop: string | symbol,\n receiver: any\n ): unknown {\n switch (prop) {\n case 'search':\n case 'searchParams':\n case 'url':\n case 'href':\n case 'toJSON':\n case 'toString':\n case 'origin':\n throw new StaticGenBailoutError(\n `Route ${target.pathname} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`nextUrl.${prop}\\`.`\n )\n case 'clone':\n return (\n target[urlCloneSymbol] ||\n (target[urlCloneSymbol] = () =>\n new Proxy(target.clone(), ensureStaticNextUrlHandlers))\n )\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n}\n\nfunction createCacheComponentsError(route: string) {\n return new DynamicServerError(\n `Route ${route} couldn't be rendered statically because it used IO that was not cached. See more info here: https://nextjs.org/docs/messages/cache-components`\n )\n}\n\nfunction trackDynamic(\n store: WorkStore,\n workUnitStore: undefined | WorkUnitStore,\n expression: string\n): void {\n if (store.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${store.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n // TODO: Should we allow reading cookies and search params from the\n // request for private caches in route handlers?\n throw createRouteHandlerRequestInUseCacheError(store.route, expression)\n case 'unstable-cache':\n throw createRouteHandlerRequestInUnstableCacheError(\n store.route,\n expression\n )\n case 'prerender':\n const error = new Error(\n `Route ${store.route} used ${expression} without first calling \\`await connection()\\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-request`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n store.route,\n expression,\n error,\n workUnitStore\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'A client prerender store should not be used for a route handler.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'A runtime prerender store should not be used for a route handler.'\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n break\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n }\n}\n"],"names":["AppRouteRouteModule","WrappedNextRouterError","hasNonStaticMethods","constructor","error","headers","RouteModule","sharedModules","userland","_lazyUserland","assertLoaded","ensureUserland","waitUntilLoaded","getUserland","definition","distDir","relativeProjectDir","resolvedPagePath","nextConfigOutput","undefined","workUnitAsyncStorage","workAsyncStorage","serverHooks","actionAsyncStorage","_getUserland","LazyModule","getTracer","trace","AppRouteRouteModuleSpan","loadUserland","spanName","attributes","pathname","module","_onUserlandLoaded","loadIfNeeded","_methods","autoImplementMethods","_hasNonStaticMethods","_dynamic","dynamic","Error","isStaticGenEnabled","process","env","NODE_ENV","lowercased","HTTP_METHODS","map","method","toLowerCase","Log","toUpperCase","some","resolveHandler","isHTTPMethod","Response","status","resolveHandlerFromUserland","resolvePendingRevalidations","workStore","requestStore","context","maybeRevalidatesPromise","executeRevalidates","renderOpts","pendingWaitUntil","finally","NEXT_PRIVATE_DEBUG_CACHE","console","log","url","search","handleHandlerError","err","actionStore","isRedirectError","getURLFromRedirectError","Headers","Location","appendMutableCookies","mutableCookies","isAction","RedirectStatusCode","SeeOther","getRedirectStatusCodeFromError","isHTTPAccessFallbackError","httpStatus","getAccessFallbackHTTPStatus","finalizeResponse","res","request","prerenderStore","invalidType","name","fetchMetrics","collectedTags","tags","join","collectedRevalidate","revalidate","collectedExpire","expire","collectedStale","stale","body","statusText","prerenderToResponse","handler","implicitTags","cacheComponentsEnabled","cacheComponents","patchFetch","handlerContext","params","createServerParamsForRoute","parsedUrlQueryToParams","userlandRevalidate","defaultRevalidate","INFINITE_CACHE","prospectiveController","AbortController","prospectiveRenderIsDynamic","cacheSignal","CacheSignal","dynamicTracking","createDynamicTrackingState","prerenderResumeDataCache","createPrerenderResumeDataCache","prospectiveRoutePrerenderStore","type","phase","rootParams","fallbackRouteParams","renderSignal","signal","controller","stagedRendering","resumeDataCache","hmrRefreshHash","varyParamsAccumulator","ensureStaticLevel","prerenderDataTracking","isFallbackUpgradeable","prospectiveResult","run","aborted","NEXT_DEBUG_BUILD","__NEXT_VERBOSE_LOGGING","printDebugThrownValueForProspectiveRender","route","Phase","ProspectiveRender","then","trackPendingModules","cacheReady","dynamicReason","getFirstDynamicReason","DynamicServerError","finalController","finalRoutePrerenderStore","responseHandled","Promise","resolve","reject","scheduleImmediate","result","bodyHandled","arrayBuffer","abort","createCacheComponentsError","renderToResponse","prepareExecution","req","rawLiveUserland","liveUserland","fetchCache","isAppRoute","getIsPossibleServerAction","getImplicitTags","page","nextUrl","createRequestStoreForAPI","previewProps","validateExecutionResponse","response","has","get","executeRequest","prepared","forceDynamic","forceStatic","Proxy","forceStaticRequestHandlers","dynamicShouldError","proxyNextRequest","tracer","setRootSpanAttribute","AppRouteRouteHandlersSpan","runHandler","executePrerender","dynamicUsageDescription","message","dynamicUsageStack","stack","ensureStaticRequestHandlers","handle","createWorkStore","buildId","sharedContext","deploymentId","previouslyRevalidatedTags","prerender","createPrerenderWorkStore","handlers","POST","PUT","DELETE","PATCH","OPTIONS","nextURLSymbol","Symbol","requestCloneSymbol","urlCloneSymbol","searchParamsSymbol","hrefSymbol","toStringSymbol","headersSymbol","cookiesSymbol","target","prop","receiver","HeadersAdapter","seal","RequestCookiesAdapter","RequestCookies","forceStaticNextUrlHandlers","href","clone","ReflectAdapter","URLSearchParams","cleanURL","nextUrlHandlers","workUnitStore","getStore","trackDynamic","nextRequestHandlers","ensureStaticNextUrlHandlers","StaticGenBailoutError","store","expression","createRouteHandlerRequestInUseCacheError","createRouteHandlerRequestInUnstableCacheError","abortAndThrowOnSynchronousRequestDataAccess","InvariantError"],"mappings":";;;;;;;;;;;;;;;;;IAoNaA,mBAAmB;eAAnBA;;IAlHAC,sBAAsB;eAAtBA;;IA2/Bb,OAAkC;eAAlC;;IASgBC,mBAAmB;eAAnBA;;;6BAzlCT;8BACkC;2BAKlC;sBACsD;8BACV;4BACxB;wBACD;2BAInB;6DACc;sCACgB;gCAI9B;yBACwB;wCAEQ;wCAIhC;4EAEsB;0CAMtB;8CAKA;4CAIA;uEACwB;yCACW;yBACX;0BACN;yCACa;oCACH;kCAK5B;yBACwB;6BACH;2BACM;wBACS;0BAKpC;+BAIA;oCAIA;oCAC4B;4BACJ;mCACI;4CACC;gCACL;4BACJ;iCACoB;kCAIxC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,MAAMD;IACXE,YACE,AAAgBC,KAAoB,EACpC,AAAgBC,OAAiB,CACjC;aAFgBD,QAAAA;aACAC,UAAAA;IACf;AACL;AA6GO,MAAML,4BAA4BM,wBAAW;qBAoB3BC,gBAAgBA;IAqBvC,IAAaC,WAAmC;QAC9C,OAAO,IAAI,CAACC,aAAa,CAACC,YAAY;IACxC;IAEA;;;;;;GAMC,GACD,MAAMC,iBAAgC;QACpC,MAAM,IAAI,CAACF,aAAa,CAACG,eAAe;IAC1C;IAEAT,YAAY,EACVK,QAAQ,EACRK,WAAW,EACXC,UAAU,EACVC,OAAO,EACPC,kBAAkB,EAClBC,gBAAgB,EAChBC,gBAAgB,EACW,CAAE;QAC7B,KAAK,CAAC;YACJV,UAAUW;YACVL;YACAC;YACAC;QACF,IAlEF;;GAEC,QACeI,uBAAuBA,kDAAoB,EAE3D;;GAEC,QACeC,mBAAmBA,0CAAgB,EAEnD;;;GAGC,QACeC,cAAcA,qBAI9B;;;GAGC,QACeC,qBAAqBA,8CAAkB;QA8CrD,IAAI,CAACN,gBAAgB,GAAGA;QACxB,IAAI,CAACC,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;YACxB,KAAK;YACL,KAAK;gBACH,mEAAmE;gBACnE,gDAAgD;gBAChD,MAAMyH,IAAAA,0DAAwC,EAACF,MAAMnG,KAAK,EAAEoG;YAC9D,KAAK;gBACH,MAAME,IAAAA,+DAA6C,EACjDH,MAAMnG,KAAK,EACXoG;YAEJ,KAAK;gBACH,MAAMtP,QAAQ,IAAIqC,MAChB,CAAC,MAAM,EAAEgN,MAAMnG,KAAK,CAAC,MAAM,EAAEoG,WAAW,+HAA+H,CAAC;gBAE1K,OAAOG,IAAAA,6DAA2C,EAChDJ,MAAMnG,KAAK,EACXoG,YACAtP,OACA+O;YAEJ,KAAK;YACL,KAAK;gBACH,MAAM,IAAIW,8BAAc,CACtB;YAEJ,KAAK;gBACH,MAAM,IAAIA,8BAAc,CACtB;YAEJ,KAAK;gBACHX,cAAc/I,UAAU,GAAG;gBAE3B,MAAM1B,MAAM,IAAIoF,sCAAkB,CAChC,CAAC,MAAM,EAAE2F,MAAMnG,KAAK,CAAC,mDAAmD,EAAEoG,WAAW,6EAA6E,CAAC;gBAErKD,MAAMhD,uBAAuB,GAAGiD;gBAChCD,MAAM9C,iBAAiB,GAAGjI,IAAIkI,KAAK;gBAEnC,MAAMlI;YACR,KAAK;gBACH;YACF,KAAK;gBACH;YACF;gBACEyK;QACJ;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/shared-modules.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/app-route/shared-modules.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..15265a392b0e3041ff53cce228603d19b582623c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/shared-modules.d.ts @@ -0,0 +1 @@ +export * as appRouterContext from '../../../shared/lib/app-router-context.shared-runtime'; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/shared-modules.js b/e-commerce/node_modules/next/dist/server/route-modules/app-route/shared-modules.js new file mode 100644 index 0000000000000000000000000000000000000000..6071963d824c9b6c073fdb0e8ba6187147f23b1e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/shared-modules.js @@ -0,0 +1,56 @@ +// the name of the export has to be the camelCase version of the file name (without the extension) +// TODO: remove this. We need it because using notFound from next/navigation imports this file :( +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "appRouterContext", { + enumerable: true, + get: function() { + return _approutercontextsharedruntime; + } +}); +const _approutercontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../shared/lib/app-router-context.shared-runtime")); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +//# sourceMappingURL=shared-modules.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/app-route/shared-modules.js.map b/e-commerce/node_modules/next/dist/server/route-modules/app-route/shared-modules.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3090c96d1ed9f9ff0f6c38798031173dde08609f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/app-route/shared-modules.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/app-route/shared-modules.ts"],"sourcesContent":["// the name of the export has to be the camelCase version of the file name (without the extension)\n// TODO: remove this. We need it because using notFound from next/navigation imports this file :(\nexport * as appRouterContext from '../../../shared/lib/app-router-context.shared-runtime'\n"],"names":["appRouterContext"],"mappings":"AAAA,kGAAkG;AAClG,iGAAiG;;;;;+BACrFA;;;;;;uFAAsB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/checks.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/checks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e57ae113ab4fb2410c69911079d892db331829ee --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/checks.d.ts @@ -0,0 +1,9 @@ +import type { AppRouteRouteModule } from './app-route/module'; +import type { AppPageRouteModule } from './app-page/module'; +import type { PagesRouteModule } from './pages/module'; +import type { PagesAPIRouteModule } from './pages-api/module'; +import type { RouteModule } from './route-module'; +export declare function isAppRouteRouteModule(routeModule: RouteModule): routeModule is AppRouteRouteModule; +export declare function isAppPageRouteModule(routeModule: RouteModule): routeModule is AppPageRouteModule; +export declare function isPagesRouteModule(routeModule: RouteModule): routeModule is PagesRouteModule; +export declare function isPagesAPIRouteModule(routeModule: RouteModule): routeModule is PagesAPIRouteModule; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/checks.js b/e-commerce/node_modules/next/dist/server/route-modules/checks.js new file mode 100644 index 0000000000000000000000000000000000000000..cf72acec9b610bce9c524a0a01903a707fdba1f7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/checks.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + isAppPageRouteModule: null, + isAppRouteRouteModule: null, + isPagesAPIRouteModule: null, + isPagesRouteModule: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + isAppPageRouteModule: function() { + return isAppPageRouteModule; + }, + isAppRouteRouteModule: function() { + return isAppRouteRouteModule; + }, + isPagesAPIRouteModule: function() { + return isPagesAPIRouteModule; + }, + isPagesRouteModule: function() { + return isPagesRouteModule; + } +}); +const _routekind = require("../route-kind"); +function isAppRouteRouteModule(routeModule) { + return routeModule.definition.kind === _routekind.RouteKind.APP_ROUTE; +} +function isAppPageRouteModule(routeModule) { + return routeModule.definition.kind === _routekind.RouteKind.APP_PAGE; +} +function isPagesRouteModule(routeModule) { + return routeModule.definition.kind === _routekind.RouteKind.PAGES; +} +function isPagesAPIRouteModule(routeModule) { + return routeModule.definition.kind === _routekind.RouteKind.PAGES_API; +} + +//# sourceMappingURL=checks.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/checks.js.map b/e-commerce/node_modules/next/dist/server/route-modules/checks.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1c244dda4803c0a54d13c35a75e39e7b9fd0f883 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/checks.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/route-modules/checks.ts"],"sourcesContent":["import type { AppRouteRouteModule } from './app-route/module'\nimport type { AppPageRouteModule } from './app-page/module'\nimport type { PagesRouteModule } from './pages/module'\nimport type { PagesAPIRouteModule } from './pages-api/module'\n\nimport type { RouteModule } from './route-module'\n\nimport { RouteKind } from '../route-kind'\n\nexport function isAppRouteRouteModule(\n routeModule: RouteModule\n): routeModule is AppRouteRouteModule {\n return routeModule.definition.kind === RouteKind.APP_ROUTE\n}\n\nexport function isAppPageRouteModule(\n routeModule: RouteModule\n): routeModule is AppPageRouteModule {\n return routeModule.definition.kind === RouteKind.APP_PAGE\n}\n\nexport function isPagesRouteModule(\n routeModule: RouteModule\n): routeModule is PagesRouteModule {\n return routeModule.definition.kind === RouteKind.PAGES\n}\n\nexport function isPagesAPIRouteModule(\n routeModule: RouteModule\n): routeModule is PagesAPIRouteModule {\n return routeModule.definition.kind === RouteKind.PAGES_API\n}\n"],"names":["isAppPageRouteModule","isAppRouteRouteModule","isPagesAPIRouteModule","isPagesRouteModule","routeModule","definition","kind","RouteKind","APP_ROUTE","APP_PAGE","PAGES","PAGES_API"],"mappings":";;;;;;;;;;;;;;;;;IAegBA,oBAAoB;eAApBA;;IANAC,qBAAqB;eAArBA;;IAkBAC,qBAAqB;eAArBA;;IANAC,kBAAkB;eAAlBA;;;2BAdU;AAEnB,SAASF,sBACdG,WAAwB;IAExB,OAAOA,YAAYC,UAAU,CAACC,IAAI,KAAKC,oBAAS,CAACC,SAAS;AAC5D;AAEO,SAASR,qBACdI,WAAwB;IAExB,OAAOA,YAAYC,UAAU,CAACC,IAAI,KAAKC,oBAAS,CAACE,QAAQ;AAC3D;AAEO,SAASN,mBACdC,WAAwB;IAExB,OAAOA,YAAYC,UAAU,CAACC,IAAI,KAAKC,oBAAS,CAACG,KAAK;AACxD;AAEO,SAASR,sBACdE,WAAwB;IAExB,OAAOA,YAAYC,UAAU,CAACC,IAAI,KAAKC,oBAAS,CAACI,SAAS;AAC5D","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.compiled.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.compiled.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5401340695abe4a87f20f88a898449b7a42edfd6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.compiled.d.ts @@ -0,0 +1 @@ +export * from './module' diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.compiled.js b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.compiled.js new file mode 100644 index 0000000000000000000000000000000000000000..6c06fb789074d69a25578adf59141abc60d7c3e4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.compiled.js @@ -0,0 +1,20 @@ +"use strict"; +if (process.env.NEXT_RUNTIME === 'edge') { + module.exports = require('next/dist/server/route-modules/pages-api/module.js'); +} else { + if (process.env.NODE_ENV === 'development') { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/pages-api-turbo.runtime.dev.js'); + } else { + module.exports = require('next/dist/compiled/next-server/pages-api.runtime.dev.js'); + } + } else { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/pages-api-turbo.runtime.prod.js'); + } else { + module.exports = require('next/dist/compiled/next-server/pages-api.runtime.prod.js'); + } + } +} + +//# sourceMappingURL=module.compiled.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.compiled.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.compiled.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3869a950fc96cf3316ae7b17c65ca6147446f15d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.compiled.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/pages-api/module.compiled.js"],"sourcesContent":["if (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/pages-api/module.js')\n} else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/pages-api-turbo.runtime.dev.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/pages-api.runtime.dev.js')\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/pages-api-turbo.runtime.prod.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/pages-api.runtime.prod.js')\n }\n }\n}\n"],"names":["process","env","NEXT_RUNTIME","module","exports","require","NODE_ENV","TURBOPACK"],"mappings":";AAAA,IAAIA,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCC,OAAOC,OAAO,GAAGC,QAAQ;AAC3B,OAAO;IACL,IAAIL,QAAQC,GAAG,CAACK,QAAQ,KAAK,eAAe;QAC1C,IAAIN,QAAQC,GAAG,CAACM,SAAS,EAAE;YACzBJ,OAAOC,OAAO,GAAGC,QAAQ;QAC3B,OAAO;YACLF,OAAOC,OAAO,GAAGC,QAAQ;QAC3B;IACF,OAAO;QACL,IAAIL,QAAQC,GAAG,CAACM,SAAS,EAAE;YACzBJ,OAAOC,OAAO,GAAGC,QAAQ;QAC3B,OAAO;YACLF,OAAOC,OAAO,GAAGC,QAAQ;QAC3B;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..420caa661acc681b0105c23dacbddc4dfc10cf4e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.d.ts @@ -0,0 +1,94 @@ +import type { IncomingMessage, ServerResponse } from 'http'; +import type { PagesAPIRouteDefinition } from '../../route-definitions/pages-api-route-definition'; +import type { PageConfig } from '../../../types'; +import type { ParsedUrlQuery } from 'querystring'; +import { type __ApiPreviewProps } from '../../api-utils'; +import type { RouteModuleOptions } from '../route-module'; +import { RouteModule, type RouteModuleHandleContext } from '../route-module'; +import { apiResolver } from '../../api-utils/node/api-resolver'; +import type { RevalidateFn } from '../../lib/router-utils/router-server-context'; +type PagesAPIHandleFn = (req: IncomingMessage, res: ServerResponse) => Promise; +/** + * The PagesAPIModule is the type of the module exported by the bundled Pages + * API module. + */ +export type PagesAPIModule = typeof import('../../../build/templates/pages-api'); +type PagesAPIUserlandModule = { + /** + * The exported handler method. + */ + readonly default: PagesAPIHandleFn; + /** + * The exported page config. + */ + readonly config?: PageConfig; +}; +type PagesAPIRouteHandlerContext = RouteModuleHandleContext & { + /** + * The incoming server request in non-edge runtime. + */ + req?: IncomingMessage; + /** + * The outgoing server response in non-edge runtime. + */ + res?: ServerResponse; + /** + * The hostname for the request. + */ + hostname?: string; + /** + * Keys allowed in the revalidate call. + */ + allowedRevalidateHeaderKeys?: string[]; + /** + * Whether to trust the host header. + */ + trustHostHeader?: boolean; + /** + * The query for the request. + */ + query: ParsedUrlQuery; + /** + * The preview props used by the `preview` API. + */ + previewProps: __ApiPreviewProps; + /** + * True if the server is in development mode. + */ + dev: boolean; + /** + * Whether errors should be left uncaught to handle + * higher up + */ + propagateError: boolean; + /** + * The page that's being rendered. + */ + page: string; + /** + * The error handler for the request. + */ + onError?: Parameters[8]; + /** + * whether multi-zone flag is enabled for draft mode + */ + multiZoneDraftMode?: boolean; + /** + * Internal revalidate function to avoid revalidating + * over the network + */ + internalRevalidate?: RevalidateFn; +}; +export type PagesAPIRouteModuleOptions = RouteModuleOptions; +export declare class PagesAPIRouteModule extends RouteModule { + private apiResolverWrapped; + constructor(options: PagesAPIRouteModuleOptions); + /** + * + * @param req the incoming server request + * @param res the outgoing server response + * @param context the context for the render + */ + render(req: IncomingMessage, res: ServerResponse, context: PagesAPIRouteHandlerContext): Promise; +} +export default PagesAPIRouteModule; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.js b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.js new file mode 100644 index 0000000000000000000000000000000000000000..6bd451aaa185260520f56f51e55da5484cee7c8b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + PagesAPIRouteModule: null, + default: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + PagesAPIRouteModule: function() { + return PagesAPIRouteModule; + }, + default: function() { + return _default; + } +}); +const _apiutils = require("../../api-utils"); +const _routemodule = require("../route-module"); +const _apiresolver = require("../../api-utils/node/api-resolver"); +class PagesAPIRouteModule extends _routemodule.RouteModule { + constructor(options){ + super(options); + if (typeof options.userland.default !== 'function') { + throw new Error(`Page ${options.definition.page} does not export a default function.`); + } + this.apiResolverWrapped = (0, _apiutils.wrapApiHandler)(options.definition.page, _apiresolver.apiResolver); + } + /** + * + * @param req the incoming server request + * @param res the outgoing server response + * @param context the context for the render + */ async render(req, res, context) { + const { apiResolverWrapped } = this; + await apiResolverWrapped(req, res, context.query, this.userland, { + ...context.previewProps, + trustHostHeader: context.trustHostHeader, + allowedRevalidateHeaderKeys: context.allowedRevalidateHeaderKeys, + hostname: context.hostname, + multiZoneDraftMode: context.multiZoneDraftMode, + dev: context.dev, + internalRevalidate: context.internalRevalidate + }, context.propagateError, context.dev, context.page, context.onError); + } +} +const _default = PagesAPIRouteModule; + +//# sourceMappingURL=module.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0dc065a1b71189f477778190cc7d53c894cbde36 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages-api/module.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/pages-api/module.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport type { PagesAPIRouteDefinition } from '../../route-definitions/pages-api-route-definition'\nimport type { PageConfig } from '../../../types'\nimport type { ParsedUrlQuery } from 'querystring'\nimport { wrapApiHandler, type __ApiPreviewProps } from '../../api-utils'\nimport type { RouteModuleOptions } from '../route-module'\n\nimport { RouteModule, type RouteModuleHandleContext } from '../route-module'\nimport { apiResolver } from '../../api-utils/node/api-resolver'\nimport type { RevalidateFn } from '../../lib/router-utils/router-server-context'\n\ntype PagesAPIHandleFn = (\n req: IncomingMessage,\n res: ServerResponse\n) => Promise\n\n/**\n * The PagesAPIModule is the type of the module exported by the bundled Pages\n * API module.\n */\nexport type PagesAPIModule = typeof import('../../../build/templates/pages-api')\n\ntype PagesAPIUserlandModule = {\n /**\n * The exported handler method.\n */\n readonly default: PagesAPIHandleFn\n\n /**\n * The exported page config.\n */\n readonly config?: PageConfig\n}\n\ntype PagesAPIRouteHandlerContext = RouteModuleHandleContext & {\n /**\n * The incoming server request in non-edge runtime.\n */\n req?: IncomingMessage\n\n /**\n * The outgoing server response in non-edge runtime.\n */\n res?: ServerResponse\n\n /**\n * The hostname for the request.\n */\n hostname?: string\n\n /**\n * Keys allowed in the revalidate call.\n */\n allowedRevalidateHeaderKeys?: string[]\n\n /**\n * Whether to trust the host header.\n */\n trustHostHeader?: boolean\n\n /**\n * The query for the request.\n */\n query: ParsedUrlQuery\n\n /**\n * The preview props used by the `preview` API.\n */\n previewProps: __ApiPreviewProps\n\n /**\n * True if the server is in development mode.\n */\n dev: boolean\n\n /**\n * Whether errors should be left uncaught to handle\n * higher up\n */\n propagateError: boolean\n\n /**\n * The page that's being rendered.\n */\n page: string\n\n /**\n * The error handler for the request.\n */\n onError?: Parameters[8]\n\n /**\n * whether multi-zone flag is enabled for draft mode\n */\n multiZoneDraftMode?: boolean\n\n /**\n * Internal revalidate function to avoid revalidating\n * over the network\n */\n internalRevalidate?: RevalidateFn\n}\n\nexport type PagesAPIRouteModuleOptions = RouteModuleOptions<\n PagesAPIRouteDefinition,\n PagesAPIUserlandModule\n>\n\nexport class PagesAPIRouteModule extends RouteModule<\n PagesAPIRouteDefinition,\n PagesAPIUserlandModule\n> {\n private apiResolverWrapped: typeof apiResolver\n\n constructor(options: PagesAPIRouteModuleOptions) {\n super(options)\n\n if (typeof options.userland.default !== 'function') {\n throw new Error(\n `Page ${options.definition.page} does not export a default function.`\n )\n }\n\n this.apiResolverWrapped = wrapApiHandler(\n options.definition.page,\n apiResolver\n )\n }\n\n /**\n *\n * @param req the incoming server request\n * @param res the outgoing server response\n * @param context the context for the render\n */\n public async render(\n req: IncomingMessage,\n res: ServerResponse,\n context: PagesAPIRouteHandlerContext\n ): Promise {\n const { apiResolverWrapped } = this\n await apiResolverWrapped(\n req,\n res,\n context.query,\n this.userland,\n {\n ...context.previewProps,\n trustHostHeader: context.trustHostHeader,\n allowedRevalidateHeaderKeys: context.allowedRevalidateHeaderKeys,\n hostname: context.hostname,\n multiZoneDraftMode: context.multiZoneDraftMode,\n dev: context.dev,\n internalRevalidate: context.internalRevalidate,\n },\n context.propagateError,\n context.dev,\n context.page,\n context.onError\n )\n }\n}\n\nexport default PagesAPIRouteModule\n"],"names":["PagesAPIRouteModule","RouteModule","constructor","options","userland","default","Error","definition","page","apiResolverWrapped","wrapApiHandler","apiResolver","render","req","res","context","query","previewProps","trustHostHeader","allowedRevalidateHeaderKeys","hostname","multiZoneDraftMode","dev","internalRevalidate","propagateError","onError"],"mappings":";;;;;;;;;;;;;;;IA4GaA,mBAAmB;eAAnBA;;IAuDb,OAAkC;eAAlC;;;0BA/JuD;6BAGI;6BAC/B;AAoGrB,MAAMA,4BAA4BC,wBAAW;IAMlDC,YAAYC,OAAmC,CAAE;QAC/C,KAAK,CAACA;QAEN,IAAI,OAAOA,QAAQC,QAAQ,CAACC,OAAO,KAAK,YAAY;YAClD,MAAM,IAAIC,MACR,CAAC,KAAK,EAAEH,QAAQI,UAAU,CAACC,IAAI,CAAC,oCAAoC,CAAC;QAEzE;QAEA,IAAI,CAACC,kBAAkB,GAAGC,IAAAA,wBAAc,EACtCP,QAAQI,UAAU,CAACC,IAAI,EACvBG,wBAAW;IAEf;IAEA;;;;;GAKC,GACD,MAAaC,OACXC,GAAoB,EACpBC,GAAmB,EACnBC,OAAoC,EACrB;QACf,MAAM,EAAEN,kBAAkB,EAAE,GAAG,IAAI;QACnC,MAAMA,mBACJI,KACAC,KACAC,QAAQC,KAAK,EACb,IAAI,CAACZ,QAAQ,EACb;YACE,GAAGW,QAAQE,YAAY;YACvBC,iBAAiBH,QAAQG,eAAe;YACxCC,6BAA6BJ,QAAQI,2BAA2B;YAChEC,UAAUL,QAAQK,QAAQ;YAC1BC,oBAAoBN,QAAQM,kBAAkB;YAC9CC,KAAKP,QAAQO,GAAG;YAChBC,oBAAoBR,QAAQQ,kBAAkB;QAChD,GACAR,QAAQS,cAAc,EACtBT,QAAQO,GAAG,EACXP,QAAQP,IAAI,EACZO,QAAQU,OAAO;IAEnB;AACF;MAEA,WAAezB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/builtin/_error.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/builtin/_error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9172fe3328412971b178b9a10a588b1ac97a7ce --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/builtin/_error.d.ts @@ -0,0 +1,6 @@ +import PagesRouteModule from '../module'; +export declare const routeModule: PagesRouteModule; +export declare const handler: (req: import("http").IncomingMessage, res: import("http").ServerResponse, ctx: { + waitUntil?: (prom: Promise) => void; + requestMeta?: import("../../../request-meta").RequestMeta; +}) => Promise; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/builtin/_error.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/builtin/_error.js new file mode 100644 index 0000000000000000000000000000000000000000..b2d0dcb22fe4e32c45574f35a00b1fad67089764 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/builtin/_error.js @@ -0,0 +1,100 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + handler: null, + routeModule: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + handler: function() { + return handler; + }, + routeModule: function() { + return routeModule; + } +}); +const _app = /*#__PURE__*/ _interop_require_default(require("../../../../pages/_app")); +const _document = /*#__PURE__*/ _interop_require_default(require("../../../../pages/_document")); +const _routekind = require("../../../route-kind"); +const _error = /*#__PURE__*/ _interop_require_wildcard(require("../../../../pages/_error")); +const _module = /*#__PURE__*/ _interop_require_default(require("../module")); +const _pageshandler = require("../pages-handler"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +const routeModule = new _module.default({ + // TODO: add descriptor for internal error page + definition: { + kind: _routekind.RouteKind.PAGES, + page: '/_error', + pathname: '/_error', + filename: '', + bundlePath: '' + }, + distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '', + relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '', + components: { + App: _app.default, + Document: _document.default + }, + userland: _error +}); +const handler = (0, _pageshandler.getHandler)({ + srcPage: '/_error', + routeModule, + userland: _error, + config: {}, + isFallbackError: true +}); + +//# sourceMappingURL=_error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/builtin/_error.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/builtin/_error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..47fa64a122ac6c52455e4273db80180a30886a93 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/builtin/_error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/route-modules/pages/builtin/_error.tsx"],"sourcesContent":["import App from '../../../../pages/_app'\nimport Document from '../../../../pages/_document'\nimport { RouteKind } from '../../../route-kind'\n\nimport * as moduleError from '../../../../pages/_error'\n\nimport PagesRouteModule from '../module'\nimport { getHandler } from '../pages-handler'\n\nexport const routeModule = new PagesRouteModule({\n // TODO: add descriptor for internal error page\n definition: {\n kind: RouteKind.PAGES,\n page: '/_error',\n pathname: '/_error',\n filename: '',\n bundlePath: '',\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n components: {\n App,\n Document,\n },\n userland: moduleError,\n})\n\nexport const handler = getHandler({\n srcPage: '/_error',\n routeModule,\n userland: moduleError,\n config: {},\n isFallbackError: true,\n})\n"],"names":["handler","routeModule","PagesRouteModule","definition","kind","RouteKind","PAGES","page","pathname","filename","bundlePath","distDir","process","env","__NEXT_RELATIVE_DIST_DIR","relativeProjectDir","__NEXT_RELATIVE_PROJECT_DIR","components","App","Document","userland","moduleError","getHandler","srcPage","config","isFallbackError"],"mappings":";;;;;;;;;;;;;;;IA2BaA,OAAO;eAAPA;;IAlBAC,WAAW;eAAXA;;;4DATG;iEACK;2BACK;+DAEG;+DAEA;8BACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpB,MAAMA,cAAc,IAAIC,eAAgB,CAAC;IAC9C,+CAA+C;IAC/CC,YAAY;QACVC,MAAMC,oBAAS,CAACC,KAAK;QACrBC,MAAM;QACNC,UAAU;QACVC,UAAU;QACVC,YAAY;IACd;IACAC,SAASC,QAAQC,GAAG,CAACC,wBAAwB,IAAI;IACjDC,oBAAoBH,QAAQC,GAAG,CAACG,2BAA2B,IAAI;IAC/DC,YAAY;QACVC,KAAAA,YAAG;QACHC,UAAAA,iBAAQ;IACV;IACAC,UAAUC;AACZ;AAEO,MAAMrB,UAAUsB,IAAAA,wBAAU,EAAC;IAChCC,SAAS;IACTtB;IACAmB,UAAUC;IACVG,QAAQ,CAAC;IACTC,iBAAiB;AACnB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/module.compiled.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.compiled.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5401340695abe4a87f20f88a898449b7a42edfd6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.compiled.d.ts @@ -0,0 +1 @@ +export * from './module' diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/module.compiled.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.compiled.js new file mode 100644 index 0000000000000000000000000000000000000000..351c248ad8fef094d42d0527732994e8209c9525 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.compiled.js @@ -0,0 +1,20 @@ +"use strict"; +if (process.env.NEXT_RUNTIME === 'edge') { + module.exports = require('next/dist/server/route-modules/pages/module.js'); +} else { + if (process.env.NODE_ENV === 'development') { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/pages-turbo.runtime.dev.js'); + } else { + module.exports = require('next/dist/compiled/next-server/pages.runtime.dev.js'); + } + } else { + if (process.env.TURBOPACK) { + module.exports = require('next/dist/compiled/next-server/pages-turbo.runtime.prod.js'); + } else { + module.exports = require('next/dist/compiled/next-server/pages.runtime.prod.js'); + } + } +} + +//# sourceMappingURL=module.compiled.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/module.compiled.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.compiled.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7e5d1d7f532cacf3332fcceda5ec6469f3b957da --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.compiled.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/pages/module.compiled.js"],"sourcesContent":["if (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/pages/module.js')\n} else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/pages-turbo.runtime.dev.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/pages.runtime.dev.js')\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/pages-turbo.runtime.prod.js')\n } else {\n module.exports = require('next/dist/compiled/next-server/pages.runtime.prod.js')\n }\n }\n}\n"],"names":["process","env","NEXT_RUNTIME","module","exports","require","NODE_ENV","TURBOPACK"],"mappings":";AAAA,IAAIA,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCC,OAAOC,OAAO,GAAGC,QAAQ;AAC3B,OAAO;IACL,IAAIL,QAAQC,GAAG,CAACK,QAAQ,KAAK,eAAe;QAC1C,IAAIN,QAAQC,GAAG,CAACM,SAAS,EAAE;YACzBJ,OAAOC,OAAO,GAAGC,QAAQ;QAC3B,OAAO;YACLF,OAAOC,OAAO,GAAGC,QAAQ;QAC3B;IACF,OAAO;QACL,IAAIL,QAAQC,GAAG,CAACM,SAAS,EAAE;YACzBJ,OAAOC,OAAO,GAAGC,QAAQ;QAC3B,OAAO;YACLF,OAAOC,OAAO,GAAGC,QAAQ;QAC3B;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/module.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a675fa0bf2d8efc0a89eb515aed826452e50bd73 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.d.ts @@ -0,0 +1,101 @@ +import type { IncomingMessage, ServerResponse } from 'http'; +import type { GetServerSideProps, GetStaticPaths, GetStaticProps, NextComponentType, PageConfig } from '../../../types'; +import type { PagesRouteDefinition } from '../../route-definitions/pages-route-definition'; +import type { NextParsedUrlQuery } from '../../request-meta'; +import type { PagesRenderContext, PagesSharedContext, RenderOpts } from '../../render'; +import type RenderResult from '../../render-result'; +import type { AppType, DocumentType } from '../../../shared/lib/utils'; +import { RouteModule, type RouteModuleHandleContext, type RouteModuleOptions } from '../route-module'; +import { renderToHTML } from '../../render'; +import * as vendoredContexts from './vendored/contexts/entrypoints'; +/** + * The PagesModule is the type of the module exported by the bundled pages + * module. + */ +export type PagesModule = typeof import('../../../build/templates/pages'); +/** + * The userland module for a page. This is the module that is exported from the + * page file that contains the page component, page config, and any page data + * fetching functions. + */ +export type PagesUserlandModule = { + /** + * The exported page component. + */ + readonly default: NextComponentType; + /** + * The exported page config. + */ + readonly config?: PageConfig; + /** + * The exported `getStaticProps` function. + */ + readonly getStaticProps?: GetStaticProps; + /** + * The exported `getStaticPaths` function. + */ + readonly getStaticPaths?: GetStaticPaths; + /** + * The exported `getServerSideProps` function. + */ + readonly getServerSideProps?: GetServerSideProps; +}; +/** + * The components that are used to render a page. These aren't tied to the + * specific page being rendered, but rather are the components that are used to + * render all pages. + */ +type PagesComponents = { + /** + * The `App` component. This could be exported by a user's custom `_app` page + * file, or it could be the default `App` component. + */ + readonly App: AppType; + /** + * The `Document` component. This could be exported by a user's custom + * `_document` page file, or it could be the default `Document` component. + */ + readonly Document: DocumentType; +}; +export interface PagesRouteModuleOptions extends RouteModuleOptions { + readonly components: PagesComponents; +} +/** + * AppRouteRouteHandlerContext is the context that is passed to the route + * handler for app routes. + */ +export interface PagesRouteHandlerContext extends RouteModuleHandleContext { + /** + * The page for the given route. + */ + page: string; + /** + * The parsed URL query for the given request. + */ + query: NextParsedUrlQuery; + /** + * The shared context used for all page renders. + */ + sharedContext: PagesSharedContext; + /** + * The context for the given request. + */ + renderContext: PagesRenderContext; + /** + * The arguments for the given request. + /** + * The RenderOpts for the given request which include the specific modules to + * use for rendering. + */ + renderOpts: Omit; +} +export declare class PagesRouteModule extends RouteModule { + private readonly components; + constructor(options: PagesRouteModuleOptions); + render(req: IncomingMessage, res: ServerResponse, context: PagesRouteHandlerContext): Promise; +} +declare const vendored: { + contexts: typeof vendoredContexts; +}; +export { renderToHTML, vendored }; +export default PagesRouteModule; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/module.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.js new file mode 100644 index 0000000000000000000000000000000000000000..08da35305e0d2f641a3bb713ed0e08e8b51b0b26 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.js @@ -0,0 +1,92 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + PagesRouteModule: null, + default: null, + renderToHTML: null, + vendored: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + PagesRouteModule: function() { + return PagesRouteModule; + }, + default: function() { + return _default; + }, + renderToHTML: function() { + return _render.renderToHTML; + }, + vendored: function() { + return vendored; + } +}); +const _routemodule = require("../route-module"); +const _render = require("../../render"); +const _entrypoints = /*#__PURE__*/ _interop_require_wildcard(require("./vendored/contexts/entrypoints")); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +class PagesRouteModule extends _routemodule.RouteModule { + constructor(options){ + super(options); + this.components = options.components; + } + render(req, res, context) { + return (0, _render.renderToHTMLImpl)(req, res, context.page, context.query, context.renderOpts, { + App: this.components.App, + Document: this.components.Document + }, context.sharedContext, context.renderContext); + } +} +const vendored = { + contexts: _entrypoints +}; +const _default = PagesRouteModule; + +//# sourceMappingURL=module.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/module.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4eb1520fc33995abccd1d389affd9dbea09de4b2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/pages/module.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport type {\n GetServerSideProps,\n GetStaticPaths,\n GetStaticProps,\n NextComponentType,\n PageConfig,\n} from '../../../types'\nimport type { PagesRouteDefinition } from '../../route-definitions/pages-route-definition'\nimport type { NextParsedUrlQuery } from '../../request-meta'\nimport type {\n PagesRenderContext,\n PagesSharedContext,\n RenderOpts,\n} from '../../render'\nimport type RenderResult from '../../render-result'\nimport type { AppType, DocumentType } from '../../../shared/lib/utils'\n\nimport {\n RouteModule,\n type RouteModuleHandleContext,\n type RouteModuleOptions,\n} from '../route-module'\nimport { renderToHTMLImpl, renderToHTML } from '../../render'\nimport * as vendoredContexts from './vendored/contexts/entrypoints'\n\n/**\n * The PagesModule is the type of the module exported by the bundled pages\n * module.\n */\nexport type PagesModule = typeof import('../../../build/templates/pages')\n\n/**\n * The userland module for a page. This is the module that is exported from the\n * page file that contains the page component, page config, and any page data\n * fetching functions.\n */\nexport type PagesUserlandModule = {\n /**\n * The exported page component.\n */\n readonly default: NextComponentType\n\n /**\n * The exported page config.\n */\n readonly config?: PageConfig\n\n /**\n * The exported `getStaticProps` function.\n */\n readonly getStaticProps?: GetStaticProps\n\n /**\n * The exported `getStaticPaths` function.\n */\n readonly getStaticPaths?: GetStaticPaths\n\n /**\n * The exported `getServerSideProps` function.\n */\n readonly getServerSideProps?: GetServerSideProps\n}\n\n/**\n * The components that are used to render a page. These aren't tied to the\n * specific page being rendered, but rather are the components that are used to\n * render all pages.\n */\ntype PagesComponents = {\n /**\n * The `App` component. This could be exported by a user's custom `_app` page\n * file, or it could be the default `App` component.\n */\n readonly App: AppType\n\n /**\n * The `Document` component. This could be exported by a user's custom\n * `_document` page file, or it could be the default `Document` component.\n */\n readonly Document: DocumentType\n}\n\nexport interface PagesRouteModuleOptions\n extends RouteModuleOptions {\n readonly components: PagesComponents\n}\n\n/**\n * AppRouteRouteHandlerContext is the context that is passed to the route\n * handler for app routes.\n */\nexport interface PagesRouteHandlerContext extends RouteModuleHandleContext {\n /**\n * The page for the given route.\n */\n page: string\n\n /**\n * The parsed URL query for the given request.\n */\n query: NextParsedUrlQuery\n\n /**\n * The shared context used for all page renders.\n */\n sharedContext: PagesSharedContext\n\n /**\n * The context for the given request.\n */\n renderContext: PagesRenderContext\n\n /**\n * The arguments for the given request.\n /**\n * The RenderOpts for the given request which include the specific modules to\n * use for rendering.\n */\n // TODO: (wyattjoh) break this out into smaller parts, it currently includes the userland components\n renderOpts: Omit\n}\n\nexport class PagesRouteModule extends RouteModule<\n PagesRouteDefinition,\n PagesUserlandModule\n> {\n private readonly components: PagesComponents\n\n constructor(options: PagesRouteModuleOptions) {\n super(options)\n\n this.components = options.components\n }\n\n public render(\n req: IncomingMessage,\n res: ServerResponse,\n context: PagesRouteHandlerContext\n ): Promise {\n return renderToHTMLImpl(\n req,\n res,\n context.page,\n context.query,\n context.renderOpts,\n {\n App: this.components.App,\n Document: this.components.Document,\n },\n context.sharedContext,\n context.renderContext\n )\n }\n}\n\nconst vendored = {\n contexts: vendoredContexts,\n}\n\n// needed for the static build\nexport { renderToHTML, vendored }\n\nexport default PagesRouteModule\n"],"names":["PagesRouteModule","renderToHTML","vendored","RouteModule","constructor","options","components","render","req","res","context","renderToHTMLImpl","page","query","renderOpts","App","Document","sharedContext","renderContext","contexts","vendoredContexts"],"mappings":";;;;;;;;;;;;;;;;;IA2HaA,gBAAgB;eAAhBA;;IAwCb,OAA+B;eAA/B;;IAFSC,YAAY;eAAZA,oBAAY;;IAAEC,QAAQ;eAARA;;;6BA3IhB;wBACwC;qEACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmG3B,MAAMF,yBAAyBG,wBAAW;IAM/CC,YAAYC,OAAgC,CAAE;QAC5C,KAAK,CAACA;QAEN,IAAI,CAACC,UAAU,GAAGD,QAAQC,UAAU;IACtC;IAEOC,OACLC,GAAoB,EACpBC,GAAmB,EACnBC,OAAiC,EACV;QACvB,OAAOC,IAAAA,wBAAgB,EACrBH,KACAC,KACAC,QAAQE,IAAI,EACZF,QAAQG,KAAK,EACbH,QAAQI,UAAU,EAClB;YACEC,KAAK,IAAI,CAACT,UAAU,CAACS,GAAG;YACxBC,UAAU,IAAI,CAACV,UAAU,CAACU,QAAQ;QACpC,GACAN,QAAQO,aAAa,EACrBP,QAAQQ,aAAa;IAEzB;AACF;AAEA,MAAMhB,WAAW;IACfiB,UAAUC;AACZ;MAKA,WAAepB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/module.render.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.render.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9f1d0c1222958141ed62cea7a177c88cae970dcc --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.render.d.ts @@ -0,0 +1,2 @@ +import type { PagesRender } from '../../render'; +export declare const lazyRenderPagesPage: PagesRender; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/module.render.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.render.js new file mode 100644 index 0000000000000000000000000000000000000000..37c0186d2540111f0ebdd2c1c2f181d27aac6ab7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.render.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "lazyRenderPagesPage", { + enumerable: true, + get: function() { + return lazyRenderPagesPage; + } +}); +const lazyRenderPagesPage = (...args)=>{ + if (process.env.NEXT_MINIMAL) { + throw new Error("Can't use lazyRenderPagesPage in minimal mode"); + } else { + const render = require('./module.compiled').renderToHTML; + return render(...args); + } +}; + +//# sourceMappingURL=module.render.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/module.render.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.render.js.map new file mode 100644 index 0000000000000000000000000000000000000000..749b713c2f3b148960b7df905951473bf907a96a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/module.render.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/pages/module.render.ts"],"sourcesContent":["import type { PagesRender } from '../../render'\n\nexport const lazyRenderPagesPage: PagesRender = (...args) => {\n if (process.env.NEXT_MINIMAL) {\n throw new Error(\"Can't use lazyRenderPagesPage in minimal mode\")\n } else {\n const render: PagesRender = (\n require('./module.compiled') as typeof import('./module.compiled')\n ).renderToHTML\n\n return render(...args)\n }\n}\n"],"names":["lazyRenderPagesPage","args","process","env","NEXT_MINIMAL","Error","render","require","renderToHTML"],"mappings":";;;;+BAEaA;;;eAAAA;;;AAAN,MAAMA,sBAAmC,CAAC,GAAGC;IAClD,IAAIC,QAAQC,GAAG,CAACC,YAAY,EAAE;QAC5B,MAAM,IAAIC,MAAM;IAClB,OAAO;QACL,MAAMC,SAAsB,AAC1BC,QAAQ,qBACRC,YAAY;QAEd,OAAOF,UAAUL;IACnB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/pages-handler.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/pages-handler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..79c3671641cc0ee786484c144019fad2aa6c6796 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/pages-handler.d.ts @@ -0,0 +1,17 @@ +import type { IncomingMessage, ServerResponse } from 'node:http'; +import { type RequestMeta } from '../../request-meta'; +import type { PagesRouteModule } from './module.compiled'; +import type { GetServerSideProps, GetStaticPaths, GetStaticProps } from '../../../types'; +export declare const getHandler: ({ srcPage: originalSrcPage, config, userland, routeModule, isFallbackError, getStaticPaths, getStaticProps, getServerSideProps, }: { + srcPage: string; + config: Record | undefined; + userland: any; + isFallbackError?: boolean; + routeModule: PagesRouteModule; + getStaticProps?: GetStaticProps; + getStaticPaths?: GetStaticPaths; + getServerSideProps?: GetServerSideProps; +}) => (req: IncomingMessage, res: ServerResponse, ctx: { + waitUntil?: (prom: Promise) => void; + requestMeta?: RequestMeta; +}) => Promise; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/pages-handler.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/pages-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..c4e0c59319510ad8327451eddb34519ec5baa8b4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/pages-handler.js @@ -0,0 +1,576 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getHandler", { + enumerable: true, + get: function() { + return getHandler; + } +}); +const _routekind = require("../../route-kind"); +const _constants = require("../../lib/trace/constants"); +const _tracer = require("../../lib/trace/tracer"); +const _formaturl = require("../../../shared/lib/router/utils/format-url"); +const _requestmeta = require("../../request-meta"); +const _interopdefault = require("../../app-render/interop-default"); +const _utils = require("../../instrumentation/utils"); +const _normalizedatapath = require("../../../shared/lib/page-path/normalize-data-path"); +const _responsecache = require("../../response-cache"); +const _cachecontrol = require("../../lib/cache-control"); +const _utils1 = require("../../../shared/lib/utils"); +const _redirectstatus = require("../../../lib/redirect-status"); +const _constants1 = require("../../../lib/constants"); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _sendpayload = require("../../send-payload"); +const _renderresult = /*#__PURE__*/ _interop_require_default(require("../../render-result")); +const _utils2 = require("../../response-cache/utils"); +const _nofallbackerrorexternal = require("../../../shared/lib/no-fallback-error.external"); +const _redirectstatuscode = require("../../../client/components/redirect-status-code"); +const _isbot = require("../../../shared/lib/router/utils/is-bot"); +const _addpathprefix = require("../../../shared/lib/router/utils/add-path-prefix"); +const _removetrailingslash = require("../../../shared/lib/router/utils/remove-trailing-slash"); +const _routecachekey = require("../../lib/route-cache-key"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +const getHandler = ({ srcPage: originalSrcPage, config, userland, routeModule, isFallbackError, getStaticPaths, getStaticProps, getServerSideProps })=>{ + return async function handler(req, res, ctx) { + var _serverFilesManifest_config_experimental, _serverFilesManifest_config, _parsedUrl_pathname; + if (ctx.requestMeta) { + (0, _requestmeta.setRequestMeta)(req, ctx.requestMeta); + } + if (routeModule.isDev) { + (0, _requestmeta.addRequestMeta)(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint()); + } + let srcPage = originalSrcPage; + // turbopack doesn't normalize `/index` in the page name + // so we need to to process dynamic routes properly + // TODO: fix turbopack providing differing value from webpack + if (process.env.TURBOPACK) { + srcPage = srcPage.replace(/\/index$/, '') || '/'; + } else if (srcPage === '/index') { + // we always normalize /index specifically + srcPage = '/'; + } + const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE; + const prepareResult = await routeModule.prepare(req, res, { + srcPage, + multiZoneDraftMode + }); + if (!prepareResult) { + res.statusCode = 400; + res.end('Bad Request'); + ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve()); + return; + } + const isMinimalMode = Boolean((0, _requestmeta.getRequestMeta)(req, 'minimalMode')); + const render404 = async ()=>{ + // TODO: should route-module itself handle rendering the 404 + if (routerServerContext == null ? void 0 : routerServerContext.render404) { + // When the Pages and App Routers coexist, a Pages Router 404 renders + // the App Router not-found page. A direct route-module invocation + // cannot provide the postponed state needed to resume that App Router + // output, so an empty postponed state signals that the renderer must + // perform a complete dynamic render instead. + // + // TODO: Re-enter routing with the App Router not-found output so its + // prerender and postponed state can be selected and resumed. + if (nextConfig.cacheComponents && !routerServerContext.isWrappedByNextServer && typeof (0, _requestmeta.getRequestMeta)(req, 'postponed') !== 'string') { + (0, _requestmeta.addRequestMeta)(req, 'postponed', ''); + } + await routerServerContext.render404(req, res, parsedUrl, false); + } else { + res.end('This page could not be found'); + } + }; + const { buildId, query, params, parsedUrl, originalQuery, originalPathname, buildManifest, fallbackBuildManifest, nextFontManifest, serverFilesManifest, reactLoadableManifest, prerenderManifest, previewProps, isDraftMode, isOnDemandRevalidate, revalidateOnlyGenerated, locale, locales, defaultLocale, routerServerContext, nextConfig, resolvedPathname, encodedResolvedPathname, deploymentId, clientAssetToken } = prepareResult; + const isExperimentalCompile = serverFilesManifest == null ? void 0 : (_serverFilesManifest_config = serverFilesManifest.config) == null ? void 0 : (_serverFilesManifest_config_experimental = _serverFilesManifest_config.experimental) == null ? void 0 : _serverFilesManifest_config_experimental.isExperimentalCompile; + const hasServerProps = Boolean(getServerSideProps); + const hasStaticProps = Boolean(getStaticProps); + const hasStaticPaths = Boolean(getStaticPaths); + const hasGetInitialProps = Boolean((userland.default || userland).getInitialProps); + let cacheKey = null; + let isIsrFallback = false; + let isNextDataRequest = prepareResult.isNextDataRequest && (hasStaticProps || hasServerProps); + const is404Page = srcPage === '/404'; + const is500Page = srcPage === '/500'; + const isErrorPage = srcPage === '/_error'; + if (!routeModule.isDev && !isDraftMode && hasStaticProps) { + cacheKey = `${locale ? `/${locale}` : ''}${(srcPage === '/' || resolvedPathname === '/') && locale ? '' : resolvedPathname}`; + if (is404Page || is500Page || isErrorPage) { + cacheKey = `${locale ? `/${locale}` : ''}${srcPage}`; + } + // ensure /index and / is normalized to one key + cacheKey = cacheKey === '/index' ? '/' : cacheKey; + } + if (hasStaticPaths && !isDraftMode) { + var _nextConfig_i18n; + const decodedPathname = (0, _removetrailingslash.removeTrailingSlash)(locale ? (0, _addpathprefix.addPathPrefix)(resolvedPathname, `/${locale}`) : resolvedPathname); + const isPrerendered = (Boolean(prerenderManifest.routes[decodedPathname]) || prerenderManifest.notFoundRoutes.includes(decodedPathname)) && // A sibling's positive or negative prerender cannot admit parameters + // that this route excluded. Development computes static paths on demand + // instead of reading build-time prerender metadata. + (routeModule.isDev || (0, _routecachekey.isRouteCacheOwner)(decodedPathname, routeModule.cacheOwner, prerenderManifest.routes[decodedPathname], (_nextConfig_i18n = nextConfig.i18n) == null ? void 0 : _nextConfig_i18n.locales)); + const prerenderInfo = prerenderManifest.dynamicRoutes[srcPage]; + if (prerenderInfo) { + if (prerenderInfo.fallback === false && !isPrerendered) { + if (nextConfig.adapterPath) { + return await render404(); + } + throw new _nofallbackerrorexternal.NoFallbackError(); + } + if (typeof prerenderInfo.fallback === 'string' && !isPrerendered && !isNextDataRequest) { + isIsrFallback = true; + } + } + } + // When serving a bot request, we want to serve a blocking render and not + // the prerendered page. This ensures that the correct content is served + // to the bot in the head. + if (isIsrFallback && (0, _isbot.isBot)(req.headers['user-agent'] || '') || isMinimalMode) { + isIsrFallback = false; + } + const tracer = (0, _tracer.getTracer)(); + const activeSpan = tracer.getActiveScopeSpan(); + const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer); + const method = req.method || 'GET'; + const resolvedUrl = (0, _formaturl.formatUrl)({ + pathname: nextConfig.trailingSlash ? `${encodedResolvedPathname}${!encodedResolvedPathname.endsWith('/') && ((_parsedUrl_pathname = parsedUrl.pathname) == null ? void 0 : _parsedUrl_pathname.endsWith('/')) ? '/' : ''}` : (0, _removetrailingslash.removeTrailingSlash)(encodedResolvedPathname || '/'), + // make sure to only add query values from original URL + query: hasStaticProps ? {} : originalQuery + }); + let parentSpan; + const handleResponse = async (span)=>{ + const responseGenerator = async ({ previousCacheEntry })=>{ + var _previousCacheEntry_value; + const doRender = async ()=>{ + try { + var _nextConfig_i18n; + return await routeModule.render(req, res, { + query: hasStaticProps && !isExperimentalCompile ? { + ...params + } : { + ...query, + ...params + }, + params, + page: srcPage, + renderContext: { + isDraftMode, + isFallback: isIsrFallback, + developmentNotFoundSourcePage: (0, _requestmeta.getRequestMeta)(req, 'developmentNotFoundSourcePage') + }, + sharedContext: { + buildId, + customServer: Boolean(routerServerContext == null ? void 0 : routerServerContext.isCustomServer) || undefined, + deploymentId, + clientAssetToken + }, + renderOpts: { + params, + routeModule, + page: srcPage, + pageConfig: config || {}, + Component: (0, _interopdefault.interopDefault)(userland), + ComponentMod: userland, + getStaticProps, + getStaticPaths, + getServerSideProps, + supportsDynamicResponse: !hasStaticProps, + buildManifest: isFallbackError ? fallbackBuildManifest : buildManifest, + nextFontManifest, + reactLoadableManifest, + assetPrefix: routeModule.getAssetPrefixForRender(routerServerContext, nextConfig.assetPrefix), + previewProps, + images: nextConfig.images, + nextConfigOutput: nextConfig.output, + optimizeCss: Boolean(nextConfig.experimental.optimizeCss), + nextScriptWorkers: Boolean(nextConfig.experimental.nextScriptWorkers), + domainLocales: (_nextConfig_i18n = nextConfig.i18n) == null ? void 0 : _nextConfig_i18n.domains, + crossOrigin: nextConfig.crossOrigin, + multiZoneDraftMode, + basePath: nextConfig.basePath, + disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading, + largePageDataBytes: nextConfig.experimental.largePageDataBytes, + isExperimentalCompile, + experimental: { + clientTraceMetadata: nextConfig.experimental.clientTraceMetadata || [] + }, + locale, + locales, + defaultLocale, + setIsrStatus: routerServerContext == null ? void 0 : routerServerContext.setIsrStatus, + isNextDataRequest: isNextDataRequest && (hasServerProps || hasStaticProps), + resolvedUrl, + // For getServerSideProps and getInitialProps we need to ensure we use the original URL + // and not the resolved URL to prevent a hydration mismatch on + // asPath + resolvedAsPath: hasServerProps || hasGetInitialProps ? (0, _formaturl.formatUrl)({ + // we use the original URL pathname less the _next/data prefix if + // present + pathname: isNextDataRequest ? (0, _normalizedatapath.normalizeDataPath)(originalPathname) : originalPathname, + query: originalQuery + }) : resolvedUrl, + isOnDemandRevalidate, + ErrorDebug: (0, _requestmeta.getRequestMeta)(req, 'PagesErrorDebug'), + err: (0, _requestmeta.getRequestMeta)(req, 'invokeError'), + // needed for experimental.optimizeCss feature + distDir: _path.default.join(/* turbopackIgnore: true */ process.cwd(), routeModule.relativeProjectDir, routeModule.distDir) + } + }).then((renderResult)=>{ + const { metadata } = renderResult; + let cacheControl = metadata.cacheControl; + // Apply the `expireTime` fallback as soon as we have the + // render's `cacheControl`, so every downstream consumer (the + // cache stored via `incrementalCache.set`, the response + // Cache-Control header, the outgoing entry returned from this + // responseGenerator) sees a finalized `cacheControl` with a + // populated `expire`. This mirrors the build-time fallback in + // `build/index.ts` so we don't apply an expire to routes that + // opt out of revalidation entirely (`revalidate: false`) or + // that are dynamic (`revalidate: 0`). + if (cacheControl && cacheControl.revalidate !== false && cacheControl.revalidate > 0 && cacheControl.expire === undefined) { + cacheControl.expire = nextConfig.expireTime; + } + if ('isNotFound' in metadata && metadata.isNotFound) { + return { + value: null, + cacheControl + }; + } + // Handle `isRedirect`. + if (metadata.isRedirect) { + return { + value: { + kind: _responsecache.CachedRouteKind.REDIRECT, + props: metadata.pageData ?? metadata.flightData + }, + cacheControl + }; + } + return { + value: { + kind: _responsecache.CachedRouteKind.PAGES, + html: renderResult, + pageData: renderResult.metadata.pageData, + headers: renderResult.metadata.headers, + status: renderResult.metadata.statusCode + }, + cacheControl + }; + }); + } catch (err) { + // if this is a background revalidate we need to report + // the request error here as it won't be bubbled + if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) { + const silenceLog = false; + await routeModule.onRequestError(req, err, { + routerKind: 'Pages Router', + routePath: srcPage, + routeType: 'render', + revalidateReason: (0, _utils.getRevalidateReason)({ + isStaticGeneration: hasStaticProps, + isOnDemandRevalidate + }) + }, silenceLog, routerServerContext); + } + throw err; + } + }; + // if we've already generated this page we no longer + // serve the fallback + if (previousCacheEntry) { + isIsrFallback = false; + } + if (isIsrFallback) { + const fallbackResponse = await routeModule.getResponseCache(req).get(routeModule.isDev ? null : locale ? `/${locale}${srcPage}` : srcPage, async ({ previousCacheEntry: previousFallbackCacheEntry = null })=>{ + if (!routeModule.isDev) { + return (0, _utils2.toResponseCacheEntry)(previousFallbackCacheEntry); + } + return doRender(); + }, { + routeKind: _routekind.RouteKind.PAGES, + isFallback: true, + isRoutePPREnabled: false, + isOnDemandRevalidate: false, + incrementalCache: await routeModule.getIncrementalCache(req, nextConfig, previewProps, prerenderManifest, isMinimalMode), + waitUntil: ctx.waitUntil + }); + if (fallbackResponse !== null && 'error' in fallbackResponse) { + throw fallbackResponse.error; + } + if (fallbackResponse) { + // Remove the cache control from the response to prevent it from being + // used in the surrounding cache. + delete fallbackResponse.cacheControl; + fallbackResponse.isMiss = true; + return fallbackResponse; + } + } + if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) { + res.statusCode = 404; + // on-demand revalidate always sets this header + res.setHeader('x-nextjs-cache', 'REVALIDATED'); + res.end('This page could not be found'); + return null; + } + if (isIsrFallback && (previousCacheEntry == null ? void 0 : (_previousCacheEntry_value = previousCacheEntry.value) == null ? void 0 : _previousCacheEntry_value.kind) === _responsecache.CachedRouteKind.PAGES) { + return { + value: { + kind: _responsecache.CachedRouteKind.PAGES, + html: new _renderresult.default(previousCacheEntry.value.html, { + contentType: _constants1.HTML_CONTENT_TYPE_HEADER, + metadata: { + statusCode: previousCacheEntry.value.status, + headers: previousCacheEntry.value.headers + } + }), + pageData: {}, + status: previousCacheEntry.value.status, + headers: previousCacheEntry.value.headers + }, + cacheControl: { + revalidate: 0, + expire: undefined + } + }; + } + return doRender(); + }; + try { + const result = await routeModule.handleResponse({ + cacheKey, + req, + nextConfig, + routeKind: _routekind.RouteKind.PAGES, + isOnDemandRevalidate, + revalidateOnlyGenerated, + waitUntil: ctx.waitUntil, + responseGenerator: responseGenerator, + previewProps, + prerenderManifest, + isMinimalMode + }); + if (result !== null && 'error' in result) { + throw result.error; + } + // if we got a cache hit this wasn't an ISR fallback + // but it wasn't generated during build so isn't in the + // prerender-manifest + if (isIsrFallback && !(result == null ? void 0 : result.isMiss)) { + isIsrFallback = false; + } + // response is finished is no cache entry + if (!result) { + return; + } + if (hasStaticProps && !isMinimalMode) { + res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : result.isMiss ? 'MISS' : result.isStale ? 'STALE' : 'HIT'); + } + let cacheControl; + if (!hasStaticProps || isIsrFallback) { + if (!res.getHeader('Cache-Control')) { + cacheControl = { + revalidate: 0, + expire: undefined + }; + } + } else if (is404Page) { + const notFoundRevalidate = (0, _requestmeta.getRequestMeta)(req, 'notFoundRevalidate'); + cacheControl = { + revalidate: typeof notFoundRevalidate === 'undefined' ? 0 : notFoundRevalidate, + expire: undefined + }; + } else if (is500Page) { + cacheControl = { + revalidate: 0, + expire: undefined + }; + } else if (result.cacheControl) { + // If the cache entry has a cache control with a revalidate value that's + // a number, use it. + if (typeof result.cacheControl.revalidate === 'number') { + if (result.cacheControl.revalidate < 1) { + throw new Error(`Invalid revalidate configuration provided: ${result.cacheControl.revalidate} < 1`); + } + cacheControl = { + revalidate: result.cacheControl.revalidate, + expire: result.cacheControl.expire + }; + } else { + // revalidate: false + cacheControl = { + revalidate: _constants1.CACHE_ONE_YEAR_SECONDS, + expire: undefined + }; + } + } + // If cache control is already set on the response we don't + // override it to allow users to customize it via next.config + if (cacheControl && !res.getHeader('Cache-Control')) { + res.setHeader('Cache-Control', (0, _cachecontrol.getCacheControlHeader)(cacheControl)); + } + // notFound: true case + if (!result.value) { + var _result_cacheControl; + // add revalidate metadata before rendering 404 page + // so that we can use this as source of truth for the + // cache-control header instead of what the 404 page returns + // for the revalidate value + (0, _requestmeta.addRequestMeta)(req, 'notFoundRevalidate', (_result_cacheControl = result.cacheControl) == null ? void 0 : _result_cacheControl.revalidate); + res.statusCode = 404; + if (isNextDataRequest) { + if (deploymentId) { + res.setHeader(_constants1.NEXT_NAV_DEPLOYMENT_ID_HEADER, deploymentId); + } + res.end('{"notFound":true}'); + return; + } + return await render404(); + } + if (result.value.kind === _responsecache.CachedRouteKind.REDIRECT) { + if (isNextDataRequest) { + if (deploymentId) { + res.setHeader(_constants1.NEXT_NAV_DEPLOYMENT_ID_HEADER, deploymentId); + } + res.setHeader('content-type', _constants1.JSON_CONTENT_TYPE_HEADER); + res.end(JSON.stringify(result.value.props)); + return; + } else { + const handleRedirect = (pageData)=>{ + const redirect = { + destination: pageData.pageProps.__N_REDIRECT, + statusCode: pageData.pageProps.__N_REDIRECT_STATUS, + basePath: pageData.pageProps.__N_REDIRECT_BASE_PATH + }; + const statusCode = (0, _redirectstatus.getRedirectStatus)(redirect); + const { basePath } = nextConfig; + if (basePath && redirect.basePath !== false && redirect.destination.startsWith('/')) { + redirect.destination = `${basePath}${redirect.destination}`; + } + if (redirect.destination.startsWith('/')) { + redirect.destination = (0, _utils1.normalizeRepeatedSlashes)(redirect.destination); + } + res.statusCode = statusCode; + res.setHeader('Location', redirect.destination); + if (statusCode === _redirectstatuscode.RedirectStatusCode.PermanentRedirect) { + res.setHeader('Refresh', `0;url=${redirect.destination}`); + } + res.end(redirect.destination); + }; + await handleRedirect(result.value.props); + return null; + } + } + if (result.value.kind !== _responsecache.CachedRouteKind.PAGES) { + throw new Error(`Invariant: received non-pages cache entry in pages handler`); + } + // Documents and data responses must not be stored in development. + // Browsers reuse a stored response for a history navigation without + // revalidating it, so a back navigation would restore a page from + // before the latest edit. Static assets never reach this code. They + // keep a revalidatable `Cache-Control`, so the browser caches them + // between page loads. + if (routeModule.isDev) { + res.setHeader('Cache-Control', 'no-store'); + } + // Draft mode should never be cached + if (isDraftMode) { + res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate'); + } + // when invoking _error before pages/500 we don't actually + // send the _error response + if ((0, _requestmeta.getRequestMeta)(req, 'customErrorRender') || isErrorPage && isMinimalMode && res.statusCode === 500) { + return null; + } + // Add deployment ID header for data requests + if (isNextDataRequest && !isErrorPage && !is500Page) { + if (deploymentId) { + res.setHeader(_constants1.NEXT_NAV_DEPLOYMENT_ID_HEADER, deploymentId); + } + } + await (0, _sendpayload.sendRenderResult)({ + req, + res, + // If we are rendering the error page it's not a data request + // anymore + result: isNextDataRequest && !isErrorPage && !is500Page ? new _renderresult.default(JSON.stringify(result.value.pageData), { + contentType: _constants1.JSON_CONTENT_TYPE_HEADER, + metadata: result.value.html.metadata + }) : result.value.html, + generateEtags: nextConfig.generateEtags, + poweredByHeader: nextConfig.poweredByHeader, + cacheControl: routeModule.isDev ? undefined : cacheControl + }); + } catch (err) { + if (!(err instanceof _nofallbackerrorexternal.NoFallbackError)) { + const silenceLog = false; + await routeModule.onRequestError(req, err, { + routerKind: 'Pages Router', + routePath: srcPage, + routeType: 'render', + revalidateReason: (0, _utils.getRevalidateReason)({ + isStaticGeneration: hasStaticProps, + isOnDemandRevalidate + }) + }, silenceLog, routerServerContext); + } + // rethrow so that we can handle serving error page + throw err; + } finally{ + // An IIFE to make early returns easier. + ; + (()=>{ + if (!span) return; + span.setAttributes({ + 'http.status_code': res.statusCode, + 'next.rsc': false + }); + const rootSpanAttributes = tracer.getRootSpanAttributes(); + // We were unable to get attributes, probably OTEL is not enabled + if (!rootSpanAttributes) { + return; + } + if (rootSpanAttributes.get('next.span_type') !== _constants.BaseServerSpan.handleRequest) { + console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`); + return; + } + const route = rootSpanAttributes.get('next.route') || srcPage; + const name = `${method} ${route}`; + span.setAttributes({ + 'next.route': route, + 'http.route': route, + 'next.span_name': name + }); + span.updateName(name); + // Propagate http.route to the parent span if one exists + // (e.g. a platform-created HTTP span in adapter + // deployments). + if (parentSpan && parentSpan !== span) { + parentSpan.setAttribute('http.route', route); + parentSpan.updateName(name); + } + })(); + } + }; + // TODO: activeSpan code path is for when wrapped by + // next-server can be removed when this is no longer used + if (isWrappedByNextServer && activeSpan) { + await handleResponse(activeSpan); + } else { + parentSpan = tracer.getActiveScopeSpan(); + await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(_constants.BaseServerSpan.handleRequest, { + spanName: `${method} ${srcPage}`, + kind: _tracer.SpanKind.SERVER, + attributes: { + 'http.method': method, + 'http.target': req.url + } + }, handleResponse), undefined, !isWrappedByNextServer); + } + }; +}; + +//# sourceMappingURL=pages-handler.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/pages-handler.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/pages-handler.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8a2515bc75fce5c6e58049f18f5259d57b7ceb8f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/pages-handler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/route-modules/pages/pages-handler.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { ParsedUrlQuery } from 'node:querystring'\nimport { RouteKind } from '../../route-kind'\nimport { BaseServerSpan } from '../../lib/trace/constants'\nimport { getTracer, SpanKind, type Span } from '../../lib/trace/tracer'\nimport { formatUrl } from '../../../shared/lib/router/utils/format-url'\nimport {\n addRequestMeta,\n getRequestMeta,\n setRequestMeta,\n type RequestMeta,\n} from '../../request-meta'\nimport { interopDefault } from '../../app-render/interop-default'\nimport { getRevalidateReason } from '../../instrumentation/utils'\nimport { normalizeDataPath } from '../../../shared/lib/page-path/normalize-data-path'\nimport {\n CachedRouteKind,\n type CachedPageValue,\n type CachedRedirectValue,\n type ResponseCacheEntry,\n type ResponseGenerator,\n} from '../../response-cache'\n\nimport {\n getCacheControlHeader,\n type CacheControl,\n} from '../../lib/cache-control'\nimport { normalizeRepeatedSlashes } from '../../../shared/lib/utils'\nimport { getRedirectStatus } from '../../../lib/redirect-status'\nimport {\n CACHE_ONE_YEAR_SECONDS,\n HTML_CONTENT_TYPE_HEADER,\n JSON_CONTENT_TYPE_HEADER,\n NEXT_NAV_DEPLOYMENT_ID_HEADER,\n} from '../../../lib/constants'\nimport path from 'path'\nimport { sendRenderResult } from '../../send-payload'\nimport RenderResult from '../../render-result'\nimport { toResponseCacheEntry } from '../../response-cache/utils'\nimport { NoFallbackError } from '../../../shared/lib/no-fallback-error.external'\nimport { RedirectStatusCode } from '../../../client/components/redirect-status-code'\nimport { isBot } from '../../../shared/lib/router/utils/is-bot'\nimport { addPathPrefix } from '../../../shared/lib/router/utils/add-path-prefix'\nimport { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'\nimport { isRouteCacheOwner } from '../../lib/route-cache-key'\nimport type { PagesRouteModule } from './module.compiled'\nimport type {\n GetServerSideProps,\n GetStaticPaths,\n GetStaticProps,\n} from '../../../types'\n\nexport const getHandler = ({\n srcPage: originalSrcPage,\n config,\n userland,\n routeModule,\n isFallbackError,\n getStaticPaths,\n getStaticProps,\n getServerSideProps,\n}: {\n srcPage: string\n config: Record | undefined\n userland: any\n isFallbackError?: boolean\n routeModule: PagesRouteModule\n getStaticProps?: GetStaticProps\n getStaticPaths?: GetStaticPaths\n getServerSideProps?: GetServerSideProps\n}) => {\n return async function handler(\n req: IncomingMessage,\n res: ServerResponse,\n ctx: {\n waitUntil?: (prom: Promise) => void\n requestMeta?: RequestMeta\n }\n ) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta)\n }\n if (routeModule.isDev) {\n addRequestMeta(\n req,\n 'devRequestTimingInternalsEnd',\n process.hrtime.bigint()\n )\n }\n let srcPage = originalSrcPage\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/'\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/'\n }\n const multiZoneDraftMode = process.env\n .__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean\n\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode,\n })\n\n if (!prepareResult) {\n res.statusCode = 400\n res.end('Bad Request')\n ctx.waitUntil?.(Promise.resolve())\n return\n }\n\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'))\n\n const render404 = async () => {\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext?.render404) {\n // When the Pages and App Routers coexist, a Pages Router 404 renders\n // the App Router not-found page. A direct route-module invocation\n // cannot provide the postponed state needed to resume that App Router\n // output, so an empty postponed state signals that the renderer must\n // perform a complete dynamic render instead.\n //\n // TODO: Re-enter routing with the App Router not-found output so its\n // prerender and postponed state can be selected and resumed.\n if (\n nextConfig.cacheComponents &&\n !routerServerContext.isWrappedByNextServer &&\n typeof getRequestMeta(req, 'postponed') !== 'string'\n ) {\n addRequestMeta(req, 'postponed', '')\n }\n await routerServerContext.render404(req, res, parsedUrl, false)\n } else {\n res.end('This page could not be found')\n }\n }\n\n const {\n buildId,\n query,\n params,\n parsedUrl,\n originalQuery,\n originalPathname,\n buildManifest,\n fallbackBuildManifest,\n nextFontManifest,\n serverFilesManifest,\n reactLoadableManifest,\n prerenderManifest,\n previewProps,\n isDraftMode,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n locale,\n locales,\n defaultLocale,\n routerServerContext,\n nextConfig,\n resolvedPathname,\n encodedResolvedPathname,\n deploymentId,\n clientAssetToken,\n } = prepareResult\n\n const isExperimentalCompile =\n serverFilesManifest?.config?.experimental?.isExperimentalCompile\n\n const hasServerProps = Boolean(getServerSideProps)\n const hasStaticProps = Boolean(getStaticProps)\n const hasStaticPaths = Boolean(getStaticPaths)\n const hasGetInitialProps = Boolean(\n (userland.default || userland).getInitialProps\n )\n let cacheKey: null | string = null\n let isIsrFallback = false\n let isNextDataRequest =\n prepareResult.isNextDataRequest && (hasStaticProps || hasServerProps)\n\n const is404Page = srcPage === '/404'\n const is500Page = srcPage === '/500'\n const isErrorPage = srcPage === '/_error'\n\n if (!routeModule.isDev && !isDraftMode && hasStaticProps) {\n cacheKey = `${locale ? `/${locale}` : ''}${\n (srcPage === '/' || resolvedPathname === '/') && locale\n ? ''\n : resolvedPathname\n }`\n\n if (is404Page || is500Page || isErrorPage) {\n cacheKey = `${locale ? `/${locale}` : ''}${srcPage}`\n }\n\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey\n }\n\n if (hasStaticPaths && !isDraftMode) {\n const decodedPathname = removeTrailingSlash(\n locale\n ? addPathPrefix(resolvedPathname, `/${locale}`)\n : resolvedPathname\n )\n const isPrerendered =\n (Boolean(prerenderManifest.routes[decodedPathname]) ||\n prerenderManifest.notFoundRoutes.includes(decodedPathname)) &&\n // A sibling's positive or negative prerender cannot admit parameters\n // that this route excluded. Development computes static paths on demand\n // instead of reading build-time prerender metadata.\n (routeModule.isDev ||\n isRouteCacheOwner(\n decodedPathname,\n routeModule.cacheOwner,\n prerenderManifest.routes[decodedPathname],\n nextConfig.i18n?.locales\n ))\n\n const prerenderInfo = prerenderManifest.dynamicRoutes[srcPage]\n\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404()\n }\n throw new NoFallbackError()\n }\n\n if (\n typeof prerenderInfo.fallback === 'string' &&\n !isPrerendered &&\n !isNextDataRequest\n ) {\n isIsrFallback = true\n }\n }\n }\n\n // When serving a bot request, we want to serve a blocking render and not\n // the prerendered page. This ensures that the correct content is served\n // to the bot in the head.\n if (\n (isIsrFallback && isBot(req.headers['user-agent'] || '')) ||\n isMinimalMode\n ) {\n isIsrFallback = false\n }\n\n const tracer = getTracer()\n const activeSpan = tracer.getActiveScopeSpan()\n const isWrappedByNextServer = Boolean(\n routerServerContext?.isWrappedByNextServer\n )\n\n const method = req.method || 'GET'\n\n const resolvedUrl = formatUrl({\n pathname: nextConfig.trailingSlash\n ? `${encodedResolvedPathname}${!encodedResolvedPathname.endsWith('/') && parsedUrl.pathname?.endsWith('/') ? '/' : ''}`\n : removeTrailingSlash(encodedResolvedPathname || '/'),\n // make sure to only add query values from original URL\n query: hasStaticProps ? {} : originalQuery,\n })\n\n let parentSpan: Span | undefined\n const handleResponse = async (span?: Span) => {\n const responseGenerator: ResponseGenerator = async ({\n previousCacheEntry,\n }) => {\n const doRender = async () => {\n try {\n return await routeModule\n .render(req, res, {\n query:\n hasStaticProps && !isExperimentalCompile\n ? ({\n ...params,\n } as ParsedUrlQuery)\n : {\n ...query,\n ...params,\n },\n params,\n page: srcPage,\n renderContext: {\n isDraftMode,\n isFallback: isIsrFallback,\n developmentNotFoundSourcePage: getRequestMeta(\n req,\n 'developmentNotFoundSourcePage'\n ),\n },\n sharedContext: {\n buildId,\n customServer:\n Boolean(routerServerContext?.isCustomServer) || undefined,\n deploymentId,\n clientAssetToken,\n },\n renderOpts: {\n params,\n routeModule,\n page: srcPage,\n pageConfig: config || {},\n Component: interopDefault(userland),\n ComponentMod: userland,\n getStaticProps,\n getStaticPaths,\n getServerSideProps,\n supportsDynamicResponse: !hasStaticProps,\n buildManifest: isFallbackError\n ? fallbackBuildManifest\n : buildManifest,\n nextFontManifest,\n reactLoadableManifest,\n\n assetPrefix: routeModule.getAssetPrefixForRender(\n routerServerContext,\n nextConfig.assetPrefix\n ),\n previewProps,\n images: nextConfig.images as any,\n nextConfigOutput: nextConfig.output,\n optimizeCss: Boolean(nextConfig.experimental.optimizeCss),\n nextScriptWorkers: Boolean(\n nextConfig.experimental.nextScriptWorkers\n ),\n domainLocales: nextConfig.i18n?.domains,\n crossOrigin: nextConfig.crossOrigin,\n\n multiZoneDraftMode,\n basePath: nextConfig.basePath,\n disableOptimizedLoading:\n nextConfig.experimental.disableOptimizedLoading,\n largePageDataBytes:\n nextConfig.experimental.largePageDataBytes,\n\n isExperimentalCompile,\n\n experimental: {\n clientTraceMetadata:\n nextConfig.experimental.clientTraceMetadata ||\n ([] as any),\n },\n\n locale,\n locales,\n defaultLocale,\n setIsrStatus: routerServerContext?.setIsrStatus,\n\n isNextDataRequest:\n isNextDataRequest && (hasServerProps || hasStaticProps),\n\n resolvedUrl,\n // For getServerSideProps and getInitialProps we need to ensure we use the original URL\n // and not the resolved URL to prevent a hydration mismatch on\n // asPath\n resolvedAsPath:\n hasServerProps || hasGetInitialProps\n ? formatUrl({\n // we use the original URL pathname less the _next/data prefix if\n // present\n pathname: isNextDataRequest\n ? normalizeDataPath(originalPathname)\n : originalPathname,\n query: originalQuery,\n })\n : resolvedUrl,\n\n isOnDemandRevalidate,\n\n ErrorDebug: getRequestMeta(req, 'PagesErrorDebug'),\n err: getRequestMeta(req, 'invokeError'),\n\n // needed for experimental.optimizeCss feature\n distDir: path.join(\n /* turbopackIgnore: true */\n process.cwd(),\n routeModule.relativeProjectDir,\n routeModule.distDir\n ),\n },\n })\n .then((renderResult): ResponseCacheEntry => {\n const { metadata } = renderResult\n\n let cacheControl: CacheControl | undefined =\n metadata.cacheControl\n\n // Apply the `expireTime` fallback as soon as we have the\n // render's `cacheControl`, so every downstream consumer (the\n // cache stored via `incrementalCache.set`, the response\n // Cache-Control header, the outgoing entry returned from this\n // responseGenerator) sees a finalized `cacheControl` with a\n // populated `expire`. This mirrors the build-time fallback in\n // `build/index.ts` so we don't apply an expire to routes that\n // opt out of revalidation entirely (`revalidate: false`) or\n // that are dynamic (`revalidate: 0`).\n if (\n cacheControl &&\n cacheControl.revalidate !== false &&\n cacheControl.revalidate > 0 &&\n cacheControl.expire === undefined\n ) {\n cacheControl.expire = nextConfig.expireTime\n }\n\n if ('isNotFound' in metadata && metadata.isNotFound) {\n return {\n value: null,\n cacheControl,\n } satisfies ResponseCacheEntry\n }\n\n // Handle `isRedirect`.\n if (metadata.isRedirect) {\n return {\n value: {\n kind: CachedRouteKind.REDIRECT,\n props: metadata.pageData ?? metadata.flightData,\n } satisfies CachedRedirectValue,\n cacheControl,\n } satisfies ResponseCacheEntry\n }\n\n return {\n value: {\n kind: CachedRouteKind.PAGES,\n html: renderResult,\n pageData: renderResult.metadata.pageData,\n headers: renderResult.metadata.headers,\n status: renderResult.metadata.statusCode,\n },\n cacheControl,\n }\n })\n } catch (err: unknown) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry?.isStale) {\n const silenceLog = false\n await routeModule.onRequestError(\n req,\n err,\n {\n routerKind: 'Pages Router',\n routePath: srcPage,\n routeType: 'render',\n revalidateReason: getRevalidateReason({\n isStaticGeneration: hasStaticProps,\n isOnDemandRevalidate,\n }),\n },\n silenceLog,\n routerServerContext\n )\n }\n throw err\n }\n }\n\n // if we've already generated this page we no longer\n // serve the fallback\n if (previousCacheEntry) {\n isIsrFallback = false\n }\n\n if (isIsrFallback) {\n const fallbackResponse = await routeModule.getResponseCache(req).get(\n routeModule.isDev\n ? null\n : locale\n ? `/${locale}${srcPage}`\n : srcPage,\n async ({\n previousCacheEntry: previousFallbackCacheEntry = null,\n }) => {\n if (!routeModule.isDev) {\n return toResponseCacheEntry(previousFallbackCacheEntry)\n }\n return doRender()\n },\n {\n routeKind: RouteKind.PAGES,\n isFallback: true,\n isRoutePPREnabled: false,\n isOnDemandRevalidate: false,\n incrementalCache: await routeModule.getIncrementalCache(\n req,\n nextConfig,\n previewProps,\n prerenderManifest,\n isMinimalMode\n ),\n waitUntil: ctx.waitUntil,\n }\n )\n if (fallbackResponse !== null && 'error' in fallbackResponse) {\n throw fallbackResponse.error\n }\n\n if (fallbackResponse) {\n // Remove the cache control from the response to prevent it from being\n // used in the surrounding cache.\n delete fallbackResponse.cacheControl\n fallbackResponse.isMiss = true\n return fallbackResponse\n }\n }\n\n if (\n !isMinimalMode &&\n isOnDemandRevalidate &&\n revalidateOnlyGenerated &&\n !previousCacheEntry\n ) {\n res.statusCode = 404\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED')\n res.end('This page could not be found')\n return null\n }\n\n if (\n isIsrFallback &&\n previousCacheEntry?.value?.kind === CachedRouteKind.PAGES\n ) {\n return {\n value: {\n kind: CachedRouteKind.PAGES,\n html: new RenderResult(previousCacheEntry.value.html, {\n contentType: HTML_CONTENT_TYPE_HEADER,\n metadata: {\n statusCode: previousCacheEntry.value.status,\n headers: previousCacheEntry.value.headers,\n },\n }),\n pageData: {},\n status: previousCacheEntry.value.status,\n headers: previousCacheEntry.value.headers,\n } satisfies CachedPageValue,\n cacheControl: { revalidate: 0, expire: undefined },\n } satisfies ResponseCacheEntry\n }\n return doRender()\n }\n\n try {\n const result = await routeModule.handleResponse({\n cacheKey,\n req,\n nextConfig,\n routeKind: RouteKind.PAGES,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n waitUntil: ctx.waitUntil,\n responseGenerator: responseGenerator,\n previewProps,\n prerenderManifest,\n isMinimalMode,\n })\n\n if (result !== null && 'error' in result) {\n throw result.error\n }\n\n // if we got a cache hit this wasn't an ISR fallback\n // but it wasn't generated during build so isn't in the\n // prerender-manifest\n if (isIsrFallback && !result?.isMiss) {\n isIsrFallback = false\n }\n\n // response is finished is no cache entry\n if (!result) {\n return\n }\n\n if (hasStaticProps && !isMinimalMode) {\n res.setHeader(\n 'x-nextjs-cache',\n isOnDemandRevalidate\n ? 'REVALIDATED'\n : result.isMiss\n ? 'MISS'\n : result.isStale\n ? 'STALE'\n : 'HIT'\n )\n }\n\n let cacheControl: CacheControl | undefined\n\n if (!hasStaticProps || isIsrFallback) {\n if (!res.getHeader('Cache-Control')) {\n cacheControl = { revalidate: 0, expire: undefined }\n }\n } else if (is404Page) {\n const notFoundRevalidate = getRequestMeta(req, 'notFoundRevalidate')\n\n cacheControl = {\n revalidate:\n typeof notFoundRevalidate === 'undefined'\n ? 0\n : notFoundRevalidate,\n expire: undefined,\n }\n } else if (is500Page) {\n cacheControl = { revalidate: 0, expire: undefined }\n } else if (result.cacheControl) {\n // If the cache entry has a cache control with a revalidate value that's\n // a number, use it.\n if (typeof result.cacheControl.revalidate === 'number') {\n if (result.cacheControl.revalidate < 1) {\n throw new Error(\n `Invalid revalidate configuration provided: ${result.cacheControl.revalidate} < 1`\n )\n }\n cacheControl = {\n revalidate: result.cacheControl.revalidate,\n expire: result.cacheControl.expire,\n }\n } else {\n // revalidate: false\n cacheControl = {\n revalidate: CACHE_ONE_YEAR_SECONDS,\n expire: undefined,\n }\n }\n }\n\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheControl && !res.getHeader('Cache-Control')) {\n res.setHeader('Cache-Control', getCacheControlHeader(cacheControl))\n }\n\n // notFound: true case\n if (!result.value) {\n // add revalidate metadata before rendering 404 page\n // so that we can use this as source of truth for the\n // cache-control header instead of what the 404 page returns\n // for the revalidate value\n addRequestMeta(\n req,\n 'notFoundRevalidate',\n result.cacheControl?.revalidate\n )\n\n res.statusCode = 404\n\n if (isNextDataRequest) {\n if (deploymentId) {\n res.setHeader(NEXT_NAV_DEPLOYMENT_ID_HEADER, deploymentId)\n }\n res.end('{\"notFound\":true}')\n return\n }\n return await render404()\n }\n\n if (result.value.kind === CachedRouteKind.REDIRECT) {\n if (isNextDataRequest) {\n if (deploymentId) {\n res.setHeader(NEXT_NAV_DEPLOYMENT_ID_HEADER, deploymentId)\n }\n res.setHeader('content-type', JSON_CONTENT_TYPE_HEADER)\n res.end(JSON.stringify(result.value.props))\n return\n } else {\n const handleRedirect = (pageData: any) => {\n const redirect = {\n destination: pageData.pageProps.__N_REDIRECT,\n statusCode: pageData.pageProps.__N_REDIRECT_STATUS,\n basePath: pageData.pageProps.__N_REDIRECT_BASE_PATH,\n }\n const statusCode = getRedirectStatus(redirect)\n const { basePath } = nextConfig\n\n if (\n basePath &&\n redirect.basePath !== false &&\n redirect.destination.startsWith('/')\n ) {\n redirect.destination = `${basePath}${redirect.destination}`\n }\n\n if (redirect.destination.startsWith('/')) {\n redirect.destination = normalizeRepeatedSlashes(\n redirect.destination\n )\n }\n\n res.statusCode = statusCode\n res.setHeader('Location', redirect.destination)\n if (statusCode === RedirectStatusCode.PermanentRedirect) {\n res.setHeader('Refresh', `0;url=${redirect.destination}`)\n }\n res.end(redirect.destination)\n }\n await handleRedirect(result.value.props)\n return null\n }\n }\n\n if (result.value.kind !== CachedRouteKind.PAGES) {\n throw new Error(\n `Invariant: received non-pages cache entry in pages handler`\n )\n }\n\n // Documents and data responses must not be stored in development.\n // Browsers reuse a stored response for a history navigation without\n // revalidating it, so a back navigation would restore a page from\n // before the latest edit. Static assets never reach this code. They\n // keep a revalidatable `Cache-Control`, so the browser caches them\n // between page loads.\n if (routeModule.isDev) {\n res.setHeader('Cache-Control', 'no-store')\n }\n\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n }\n\n // when invoking _error before pages/500 we don't actually\n // send the _error response\n if (\n getRequestMeta(req, 'customErrorRender') ||\n (isErrorPage && isMinimalMode && res.statusCode === 500)\n ) {\n return null\n }\n\n // Add deployment ID header for data requests\n if (isNextDataRequest && !isErrorPage && !is500Page) {\n if (deploymentId) {\n res.setHeader(NEXT_NAV_DEPLOYMENT_ID_HEADER, deploymentId)\n }\n }\n\n await sendRenderResult({\n req,\n res,\n // If we are rendering the error page it's not a data request\n // anymore\n result:\n isNextDataRequest && !isErrorPage && !is500Page\n ? new RenderResult(JSON.stringify(result.value.pageData), {\n contentType: JSON_CONTENT_TYPE_HEADER,\n metadata: result.value.html.metadata,\n })\n : result.value.html,\n generateEtags: nextConfig.generateEtags,\n poweredByHeader: nextConfig.poweredByHeader,\n cacheControl: routeModule.isDev ? undefined : cacheControl,\n })\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false\n await routeModule.onRequestError(\n req,\n err,\n {\n routerKind: 'Pages Router',\n routePath: srcPage,\n routeType: 'render',\n revalidateReason: getRevalidateReason({\n isStaticGeneration: hasStaticProps,\n isOnDemandRevalidate,\n }),\n },\n silenceLog,\n routerServerContext\n )\n }\n\n // rethrow so that we can handle serving error page\n throw err\n } finally {\n // An IIFE to make early returns easier.\n ;(() => {\n if (!span) return\n\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false,\n })\n\n const rootSpanAttributes = tracer.getRootSpanAttributes()\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return\n }\n\n if (\n rootSpanAttributes.get('next.span_type') !==\n BaseServerSpan.handleRequest\n ) {\n console.warn(\n `Unexpected root span type '${rootSpanAttributes.get(\n 'next.span_type'\n )}'. Please report this Next.js issue https://github.com/vercel/next.js`\n )\n return\n }\n\n const route = rootSpanAttributes.get('next.route') || srcPage\n const name = `${method} ${route}`\n\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name,\n })\n span.updateName(name)\n\n // Propagate http.route to the parent span if one exists\n // (e.g. a platform-created HTTP span in adapter\n // deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route)\n parentSpan.updateName(name)\n }\n })()\n }\n }\n\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan)\n } else {\n parentSpan = tracer.getActiveScopeSpan()\n await tracer.withPropagatedContext(\n req.headers,\n () =>\n tracer.trace(\n BaseServerSpan.handleRequest,\n {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url,\n },\n },\n handleResponse\n ),\n undefined,\n !isWrappedByNextServer\n )\n }\n }\n}\n"],"names":["getHandler","srcPage","originalSrcPage","config","userland","routeModule","isFallbackError","getStaticPaths","getStaticProps","getServerSideProps","handler","req","res","ctx","serverFilesManifest","parsedUrl","requestMeta","setRequestMeta","isDev","addRequestMeta","process","hrtime","bigint","env","TURBOPACK","replace","multiZoneDraftMode","__NEXT_MULTI_ZONE_DRAFT_MODE","prepareResult","prepare","statusCode","end","waitUntil","Promise","resolve","isMinimalMode","Boolean","getRequestMeta","render404","routerServerContext","nextConfig","cacheComponents","isWrappedByNextServer","buildId","query","params","originalQuery","originalPathname","buildManifest","fallbackBuildManifest","nextFontManifest","reactLoadableManifest","prerenderManifest","previewProps","isDraftMode","isOnDemandRevalidate","revalidateOnlyGenerated","locale","locales","defaultLocale","resolvedPathname","encodedResolvedPathname","deploymentId","clientAssetToken","isExperimentalCompile","experimental","hasServerProps","hasStaticProps","hasStaticPaths","hasGetInitialProps","default","getInitialProps","cacheKey","isIsrFallback","isNextDataRequest","is404Page","is500Page","isErrorPage","decodedPathname","removeTrailingSlash","addPathPrefix","isPrerendered","routes","notFoundRoutes","includes","isRouteCacheOwner","cacheOwner","i18n","prerenderInfo","dynamicRoutes","fallback","adapterPath","NoFallbackError","isBot","headers","tracer","getTracer","activeSpan","getActiveScopeSpan","method","resolvedUrl","formatUrl","pathname","trailingSlash","endsWith","parentSpan","handleResponse","span","responseGenerator","previousCacheEntry","doRender","render","page","renderContext","isFallback","developmentNotFoundSourcePage","sharedContext","customServer","isCustomServer","undefined","renderOpts","pageConfig","Component","interopDefault","ComponentMod","supportsDynamicResponse","assetPrefix","getAssetPrefixForRender","images","nextConfigOutput","output","optimizeCss","nextScriptWorkers","domainLocales","domains","crossOrigin","basePath","disableOptimizedLoading","largePageDataBytes","clientTraceMetadata","setIsrStatus","resolvedAsPath","normalizeDataPath","ErrorDebug","err","distDir","path","join","cwd","relativeProjectDir","then","renderResult","metadata","cacheControl","revalidate","expire","expireTime","isNotFound","value","isRedirect","kind","CachedRouteKind","REDIRECT","props","pageData","flightData","PAGES","html","status","isStale","silenceLog","onRequestError","routerKind","routePath","routeType","revalidateReason","getRevalidateReason","isStaticGeneration","fallbackResponse","getResponseCache","get","previousFallbackCacheEntry","toResponseCacheEntry","routeKind","RouteKind","isRoutePPREnabled","incrementalCache","getIncrementalCache","error","isMiss","setHeader","RenderResult","contentType","HTML_CONTENT_TYPE_HEADER","result","getHeader","notFoundRevalidate","Error","CACHE_ONE_YEAR_SECONDS","getCacheControlHeader","NEXT_NAV_DEPLOYMENT_ID_HEADER","JSON_CONTENT_TYPE_HEADER","JSON","stringify","handleRedirect","redirect","destination","pageProps","__N_REDIRECT","__N_REDIRECT_STATUS","__N_REDIRECT_BASE_PATH","getRedirectStatus","startsWith","normalizeRepeatedSlashes","RedirectStatusCode","PermanentRedirect","sendRenderResult","generateEtags","poweredByHeader","setAttributes","rootSpanAttributes","getRootSpanAttributes","BaseServerSpan","handleRequest","console","warn","route","name","updateName","setAttribute","withPropagatedContext","trace","spanName","SpanKind","SERVER","attributes","url"],"mappings":";;;;+BAoDaA;;;eAAAA;;;2BAlDa;2BACK;wBACgB;2BACrB;6BAMnB;gCACwB;uBACK;mCACF;+BAO3B;8BAKA;wBACkC;gCACP;4BAM3B;6DACU;6BACgB;qEACR;wBACY;yCACL;oCACG;uBACb;+BACQ;qCACM;+BACF;;;;;;AAQ3B,MAAMA,aAAa,CAAC,EACzBC,SAASC,eAAe,EACxBC,MAAM,EACNC,QAAQ,EACRC,WAAW,EACXC,eAAe,EACfC,cAAc,EACdC,cAAc,EACdC,kBAAkB,EAUnB;IACC,OAAO,eAAeC,QACpBC,GAAoB,EACpBC,GAAmB,EACnBC,GAGC;YA4FCC,0CAAAA,6BA4F2EC;QAtL7E,IAAIF,IAAIG,WAAW,EAAE;YACnBC,IAAAA,2BAAc,EAACN,KAAKE,IAAIG,WAAW;QACrC;QACA,IAAIX,YAAYa,KAAK,EAAE;YACrBC,IAAAA,2BAAc,EACZR,KACA,gCACAS,QAAQC,MAAM,CAACC,MAAM;QAEzB;QACA,IAAIrB,UAAUC;QACd,wDAAwD;QACxD,mDAAmD;QACnD,6DAA6D;QAC7D,IAAIkB,QAAQG,GAAG,CAACC,SAAS,EAAE;YACzBvB,UAAUA,QAAQwB,OAAO,CAAC,YAAY,OAAO;QAC/C,OAAO,IAAIxB,YAAY,UAAU;YAC/B,0CAA0C;YAC1CA,UAAU;QACZ;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mBAAmBxC,GAAG,CAAC,sBACvB0C,yBAAc,CAACC,aAAa,EAC5B;wBACAC,QAAQC,IAAI,CACV,CAAC,2BAA2B,EAAEL,mBAAmBxC,GAAG,CAClD,kBACA,qEAAqE,CAAC;wBAE1E;oBACF;oBAEA,MAAM8C,QAAQN,mBAAmBxC,GAAG,CAAC,iBAAiBnL;oBACtD,MAAMkO,OAAO,GAAGhI,OAAO,CAAC,EAAE+H,OAAO;oBAEjCvH,KAAKgH,aAAa,CAAC;wBACjB,cAAcO;wBACd,cAAcA;wBACd,kBAAkBC;oBACpB;oBACAxH,KAAKyH,UAAU,CAACD;oBAEhB,wDAAwD;oBACxD,gDAAgD;oBAChD,gBAAgB;oBAChB,IAAI1H,cAAcA,eAAeE,MAAM;wBACrCF,WAAW4H,YAAY,CAAC,cAAcH;wBACtCzH,WAAW2H,UAAU,CAACD;oBACxB;gBACF,CAAA;YACF;QACF;QAEA,oDAAoD;QACpD,yDAAyD;QACzD,IAAIzL,yBAAyBuD,YAAY;YACvC,MAAMS,eAAeT;QACvB,OAAO;YACLQ,aAAaV,OAAOG,kBAAkB;YACtC,MAAMH,OAAOuI,qBAAqB,CAChC3N,IAAImF,OAAO,EACX,IACEC,OAAOwI,KAAK,CACVT,yBAAc,CAACC,aAAa,EAC5B;oBACES,UAAU,GAAGrI,OAAO,CAAC,EAAElG,SAAS;oBAChC+J,MAAMyE,gBAAQ,CAACC,MAAM;oBACrBC,YAAY;wBACV,eAAexI;wBACf,eAAexF,IAAIiO,GAAG;oBACxB;gBACF,GACAlI,iBAEJa,WACA,CAAC7E;QAEL;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/app-router-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/app-router-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/app-router-context.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/app-router-context.js new file mode 100644 index 0000000000000000000000000000000000000000..74fa6622e2a5367e88e0b801cd98447f8188c090 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/app-router-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].AppRouterContext; + +//# sourceMappingURL=app-router-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/app-router-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/app-router-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7b51a2db9671cf42da1093b175d9c4cf4cbd7b01 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/app-router-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/pages/vendored/contexts/app-router-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].AppRouterContext\n"],"names":["module","exports","require","vendored","AppRouterContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,gBAAgB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/entrypoints.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/entrypoints.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2806e8ab3f17455d90db35d58d0f31bee4369483 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/entrypoints.d.ts @@ -0,0 +1,9 @@ +export * as RouterContext from '../../../../../shared/lib/router-context.shared-runtime'; +export * as LoadableContext from '../../../../../shared/lib/loadable-context.shared-runtime'; +export * as Loadable from '../../../../../shared/lib/loadable.shared-runtime'; +export * as ImageConfigContext from '../../../../../shared/lib/image-config-context.shared-runtime'; +export * as HtmlContext from '../../../../../shared/lib/html-context.shared-runtime'; +export * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime'; +export * as HeadManagerContext from '../../../../../shared/lib/head-manager-context.shared-runtime'; +export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime'; +export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-html.shared-runtime'; diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/entrypoints.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/entrypoints.js new file mode 100644 index 0000000000000000000000000000000000000000..e179453cf105aa97be6393bb5687fa16c35be93a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/entrypoints.js @@ -0,0 +1,102 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + AppRouterContext: null, + HeadManagerContext: null, + HooksClientContext: null, + HtmlContext: null, + ImageConfigContext: null, + Loadable: null, + LoadableContext: null, + RouterContext: null, + ServerInsertedHtml: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + AppRouterContext: function() { + return _approutercontextsharedruntime; + }, + HeadManagerContext: function() { + return _headmanagercontextsharedruntime; + }, + HooksClientContext: function() { + return _hooksclientcontextsharedruntime; + }, + HtmlContext: function() { + return _htmlcontextsharedruntime; + }, + ImageConfigContext: function() { + return _imageconfigcontextsharedruntime; + }, + Loadable: function() { + return _loadablesharedruntime; + }, + LoadableContext: function() { + return _loadablecontextsharedruntime; + }, + RouterContext: function() { + return _routercontextsharedruntime; + }, + ServerInsertedHtml: function() { + return _serverinsertedhtmlsharedruntime; + } +}); +const _routercontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/router-context.shared-runtime")); +const _loadablecontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/loadable-context.shared-runtime")); +const _loadablesharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/loadable.shared-runtime")); +const _imageconfigcontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/image-config-context.shared-runtime")); +const _htmlcontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/html-context.shared-runtime")); +const _hooksclientcontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/hooks-client-context.shared-runtime")); +const _headmanagercontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/head-manager-context.shared-runtime")); +const _approutercontextsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/app-router-context.shared-runtime")); +const _serverinsertedhtmlsharedruntime = /*#__PURE__*/ _interop_require_wildcard(require("../../../../../shared/lib/server-inserted-html.shared-runtime")); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} + +//# sourceMappingURL=entrypoints.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/entrypoints.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/entrypoints.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1851362aa18f3056510531df881a598eed791dcf --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/entrypoints.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/pages/vendored/contexts/entrypoints.ts"],"sourcesContent":["export * as RouterContext from '../../../../../shared/lib/router-context.shared-runtime'\nexport * as LoadableContext from '../../../../../shared/lib/loadable-context.shared-runtime'\nexport * as Loadable from '../../../../../shared/lib/loadable.shared-runtime'\nexport * as ImageConfigContext from '../../../../../shared/lib/image-config-context.shared-runtime'\nexport * as HtmlContext from '../../../../../shared/lib/html-context.shared-runtime'\nexport * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime'\nexport * as HeadManagerContext from '../../../../../shared/lib/head-manager-context.shared-runtime'\nexport * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime'\nexport * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-html.shared-runtime'\n"],"names":["AppRouterContext","HeadManagerContext","HooksClientContext","HtmlContext","ImageConfigContext","Loadable","LoadableContext","RouterContext","ServerInsertedHtml"],"mappings":";;;;;;;;;;;;;;;;;;;;;;IAOYA,gBAAgB;;;IADhBC,kBAAkB;;;IADlBC,kBAAkB;;;IADlBC,WAAW;;;IADXC,kBAAkB;;;IADlBC,QAAQ;;;IADRC,eAAe;;;IADfC,aAAa;;;IAQbC,kBAAkB;;;;oFARC;sFACE;+EACP;yFACU;kFACP;yFACO;yFACA;uFACF;yFACE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/head-manager-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/head-manager-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/head-manager-context.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/head-manager-context.js new file mode 100644 index 0000000000000000000000000000000000000000..161d1246033466b8eb50881ac6c1631ed89cee36 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/head-manager-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].HeadManagerContext; + +//# sourceMappingURL=head-manager-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/head-manager-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/head-manager-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bc7c4ccac9a781aefbe0fc265c59f9a5a36a9976 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/head-manager-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/pages/vendored/contexts/head-manager-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].HeadManagerContext\n"],"names":["module","exports","require","vendored","HeadManagerContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,kBAAkB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/hooks-client-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/hooks-client-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/hooks-client-context.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/hooks-client-context.js new file mode 100644 index 0000000000000000000000000000000000000000..8a86415fa56106cf614206e4c8ba2256d7125f81 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/hooks-client-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].HooksClientContext; + +//# sourceMappingURL=hooks-client-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/hooks-client-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/hooks-client-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..dbf253bb29244528a23859304538a923a5b9f750 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/hooks-client-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/pages/vendored/contexts/hooks-client-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].HooksClientContext\n"],"names":["module","exports","require","vendored","HooksClientContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,kBAAkB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/html-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/html-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/html-context.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/html-context.js new file mode 100644 index 0000000000000000000000000000000000000000..358fbd059a56f3638c8f39789504287c7c4c649a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/html-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].HtmlContext; + +//# sourceMappingURL=html-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/html-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/html-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a78facd275506c03f1be1d24f01ee5b2121b56d1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/html-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/pages/vendored/contexts/html-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].HtmlContext\n"],"names":["module","exports","require","vendored","HtmlContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,WAAW","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/image-config-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/image-config-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/image-config-context.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/image-config-context.js new file mode 100644 index 0000000000000000000000000000000000000000..53255f9b8b07068f9b2363a3bc97d8111a98a492 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/image-config-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].ImageConfigContext; + +//# sourceMappingURL=image-config-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/image-config-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/image-config-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..11a415022ae4432f3077f45216f9e27987748380 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/image-config-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/pages/vendored/contexts/image-config-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].ImageConfigContext\n"],"names":["module","exports","require","vendored","ImageConfigContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,kBAAkB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable-context.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable-context.js new file mode 100644 index 0000000000000000000000000000000000000000..38bbdca99fd3a55a7f9aa20858eaa5e3f2542035 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].LoadableContext; + +//# sourceMappingURL=loadable-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5a712a79fff37873eb9a38943b591d11dbaad805 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/pages/vendored/contexts/loadable-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].LoadableContext\n"],"names":["module","exports","require","vendored","LoadableContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,eAAe","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable.js new file mode 100644 index 0000000000000000000000000000000000000000..0f02b181b163ca7ced830ffefde6fd21396ab1d7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].Loadable; + +//# sourceMappingURL=loadable.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable.js.map new file mode 100644 index 0000000000000000000000000000000000000000..159bc6caf1845721252c284b7fc292c91d2f950c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/pages/vendored/contexts/loadable.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].Loadable\n"],"names":["module","exports","require","vendored","Loadable"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,QAAQ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/router-context.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/router-context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/router-context.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/router-context.js new file mode 100644 index 0000000000000000000000000000000000000000..424b2ce70b12d651376d8edc2afd98fd0311c017 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/router-context.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].RouterContext; + +//# sourceMappingURL=router-context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/router-context.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/router-context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..fbcf3f174d36fd73480028aa11de0dc9c10d4971 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/router-context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/pages/vendored/contexts/router-context.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].RouterContext\n"],"names":["module","exports","require","vendored","RouterContext"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,aAAa","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/server-inserted-html.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/server-inserted-html.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/server-inserted-html.js b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/server-inserted-html.js new file mode 100644 index 0000000000000000000000000000000000000000..ebbbd2d6344ed38978abf8cdfc9e2dc6f33c3481 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/server-inserted-html.js @@ -0,0 +1,4 @@ +"use strict"; +module.exports = require('../../module.compiled').vendored['contexts'].ServerInsertedHtml; + +//# sourceMappingURL=server-inserted-html.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/server-inserted-html.js.map b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/server-inserted-html.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a7b5a3d404201fb7ec37c14b00c9a750597e0fcd --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/pages/vendored/contexts/server-inserted-html.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../../src/server/route-modules/pages/vendored/contexts/server-inserted-html.ts"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['contexts'].ServerInsertedHtml\n"],"names":["module","exports","require","vendored","ServerInsertedHtml"],"mappings":";AAAAA,OAAOC,OAAO,GAAG,AACfC,QAAQ,yBACRC,QAAQ,CAAC,WAAW,CAACC,kBAAkB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/route-module.d.ts b/e-commerce/node_modules/next/dist/server/route-modules/route-module.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a2ae086244b8b41015b61e14c9298216bac78c4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/route-module.d.ts @@ -0,0 +1,141 @@ +import '../../build/adapter/setup-node-env.external'; +import type { IncomingMessage, ServerResponse } from 'node:http'; +import type { InstrumentationOnRequestError, RequestErrorContext } from '../instrumentation/types'; +import type { ParsedUrlQuery } from 'node:querystring'; +import type { UrlWithParsedQuery } from 'node:url'; +import type { PrerenderManifest, RequiredServerFilesManifest } from '../../build'; +import type { DevRoutesManifest } from '../lib/router-utils/setup-dev-bundler'; +import type { RouteDefinition } from '../route-definitions/route-definition'; +import type { DeepReadonly } from '../../shared/lib/deep-readonly'; +import { type __ApiPreviewProps } from '../api-utils'; +import type { PreviewData } from '../../types'; +import type { BuildManifest } from '../get-page-files'; +import type { ReactLoadableManifest } from '../load-components'; +import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'; +import { type NextIncomingMessage } from '../request-meta'; +import { IncrementalCache } from '../lib/incremental-cache'; +import { RouteKind } from '../route-kind'; +import { type ResponseCacheOwner } from '../lib/route-cache-key'; +import type { BaseNextRequest } from '../base-http'; +import type { NextConfigRuntime } from '../config-shared'; +import ResponseCache, { type ResponseGenerator } from '../response-cache'; +import { type RouterServerContext } from '../lib/router-utils/router-server-context'; +/** + * RouteModuleOptions is the options that are passed to the route module, other + * route modules should extend this class to add specific options for their + * route. + */ +export interface RouteModuleOptions { + readonly definition: Readonly; + readonly userland: Readonly; + readonly distDir: string; + readonly relativeProjectDir: string; +} +/** + * RouteHandlerContext is the base context for a route handler. + */ +export interface RouteModuleHandleContext { + /** + * Any matched parameters for the request. This is only defined for dynamic + * routes. + */ + params: Record | undefined; +} +/** + * RouteModule is the base class for all route modules. This class should be + * extended by all route modules. + */ +export declare abstract class RouteModule { + /** + * The userland module. This is the module that is exported from the user's + * code. Exposed as a getter so subclasses can override with lazy loading. + */ + protected _userland: Readonly; + get userland(): Readonly; + /** + * The definition of the route. + */ + readonly definition: Readonly; + /** The canonical source identity shared by cache reads, writes, and metadata. */ + readonly cacheOwner: ResponseCacheOwner; + /** + * The shared modules that are exposed and required for the route module. + */ + static readonly sharedModules: any; + isDev: boolean; + distDir: string; + relativeProjectDir: string; + incrementCache?: IncrementalCache; + responseCache?: ResponseCache; + constructor({ userland, definition, distDir, relativeProjectDir, }: RouteModuleOptions); + private getRouterServerContext; + getAssetPrefixForRender(routerServerContext: RouterServerContext[string] | undefined, configuredAssetPrefix: string): string; + normalizeUrl(_req: IncomingMessage | BaseNextRequest, _parsedUrl: UrlWithParsedQuery): void; + instrumentationOnRequestError(req: IncomingMessage | BaseNextRequest, ...args: Parameters): Promise; + private loadManifests; + loadCustomCacheHandlers(req: IncomingMessage | BaseNextRequest, nextConfig: NextConfigRuntime): Promise; + getIncrementalCache(req: IncomingMessage | BaseNextRequest, nextConfig: NextConfigRuntime, previewProps: DeepReadonly<__ApiPreviewProps>, prerenderManifest: DeepReadonly, isMinimalMode: boolean): Promise; + onRequestError(req: IncomingMessage | BaseNextRequest, err: unknown, errorContext: RequestErrorContext, silenceLog: boolean, routerServerContext?: RouterServerContext[string]): Promise; + /** A more lightweight version of `prepare()` for only retrieving the config on edge */ + getNextConfigEdge(req: NextIncomingMessage): { + nextConfig: NextConfigRuntime; + deploymentId: string; + }; + prepare(req: IncomingMessage | BaseNextRequest, res: ServerResponse | null, options: { + srcPage: string; + multiZoneDraftMode?: boolean; + }): Promise<{ + buildId: string; + deploymentId: string; + clientAssetToken: string; + locale?: string; + locales?: readonly string[]; + defaultLocale?: string; + query: ParsedUrlQuery; + originalQuery: ParsedUrlQuery; + originalPathname: string; + params?: ParsedUrlQuery; + parsedUrl: UrlWithParsedQuery; + previewData: PreviewData; + pageIsDynamic: boolean; + isDraftMode: boolean; + resolvedPathname: string; + encodedResolvedPathname: string; + isNextDataRequest: boolean; + buildManifest: DeepReadonly; + fallbackBuildManifest: DeepReadonly; + nextFontManifest: DeepReadonly; + serverFilesManifest: DeepReadonly | undefined; + reactLoadableManifest: DeepReadonly; + routesManifest: DeepReadonly; + prerenderManifest: DeepReadonly; + clientReferenceManifest?: any; + serverActionsManifest?: any; + dynamicCssManifest?: any; + prefetchHintsManifest?: Record; + subresourceIntegrityManifest?: DeepReadonly>; + isOnDemandRevalidate: boolean; + revalidateOnlyGenerated: boolean; + nextConfig: NextConfigRuntime; + routerServerContext?: RouterServerContext[string]; + interceptionRoutePatterns?: any; + previewProps: __ApiPreviewProps; + } | undefined>; + private prepareImpl; + getResponseCache(req: IncomingMessage | BaseNextRequest): ResponseCache; + handleResponse({ req, nextConfig, cacheKey, routeKind, isFallback, previewProps, prerenderManifest, isRoutePPREnabled, isOnDemandRevalidate, revalidateOnlyGenerated, responseGenerator, waitUntil, isMinimalMode, }: { + req: IncomingMessage | BaseNextRequest; + nextConfig: NextConfigRuntime; + cacheKey: string | null; + routeKind: RouteKind; + isFallback?: boolean; + previewProps: DeepReadonly<__ApiPreviewProps>; + prerenderManifest: DeepReadonly; + isRoutePPREnabled?: boolean; + isOnDemandRevalidate?: boolean; + revalidateOnlyGenerated?: boolean; + responseGenerator: ResponseGenerator; + waitUntil?: (prom: Promise) => void; + isMinimalMode: boolean; + }): Promise; +} diff --git a/e-commerce/node_modules/next/dist/server/route-modules/route-module.js b/e-commerce/node_modules/next/dist/server/route-modules/route-module.js new file mode 100644 index 0000000000000000000000000000000000000000..b3826454d7c06c6133a433fba2d36bc6d7163182 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/route-module.js @@ -0,0 +1,700 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "RouteModule", { + enumerable: true, + get: function() { + return RouteModule; + } +}); +require("../../build/adapter/setup-node-env.external"); +const _constants = require("../../shared/lib/constants"); +const _url = require("../../lib/url"); +const _normalizelocalepath = require("../../shared/lib/i18n/normalize-locale-path"); +const _utils = require("../../shared/lib/router/utils"); +const _removepathprefix = require("../../shared/lib/router/utils/remove-path-prefix"); +const _serverutils = require("../server-utils"); +const _detectdomainlocale = require("../../shared/lib/i18n/detect-domain-locale"); +const _gethostname = require("../../shared/lib/get-hostname"); +const _apiutils = require("../api-utils"); +const _normalizedatapath = require("../../shared/lib/page-path/normalize-data-path"); +const _pathhasprefix = require("../../shared/lib/router/utils/path-has-prefix"); +const _requestmeta = require("../request-meta"); +const _patchsetheader = require("../lib/patch-set-header"); +const _normalizepagepath = require("../../shared/lib/page-path/normalize-page-path"); +const _ismetadataroute = require("../../lib/metadata/is-metadata-route"); +const _incrementalcache = require("../lib/incremental-cache"); +const _handlers = require("../use-cache/handlers"); +const _interopdefault = require("../app-render/interop-default"); +const _routekind = require("../route-kind"); +const _routecachekey = require("../lib/route-cache-key"); +const _responsecache = /*#__PURE__*/ _interop_require_default(require("../response-cache")); +const _apppaths = require("../../shared/lib/router/utils/app-paths"); +const _routerservercontext = require("../lib/router-utils/router-server-context"); +const _decodepathparams = require("../lib/router-utils/decode-path-params"); +const _removetrailingslash = require("../../shared/lib/router/utils/remove-trailing-slash"); +const _isinterceptionrouterewrite = require("../../lib/is-interception-route-rewrite"); +const _tracer = require("../lib/trace/tracer"); +const _constants1 = require("../lib/trace/constants"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +const dynamicImportEsmDefault = (id)=>import(/* webpackIgnore: true */ /* turbopackIgnore: true */ id).then((mod)=>mod.default || mod); +class RouteModule { + get userland() { + return this._userland; + } + constructor({ userland, definition, distDir, relativeProjectDir }){ + this._userland = userland; + this.definition = definition; + this.cacheOwner = (0, _routecachekey.getResponseCacheOwner)(definition); + this.isDev = !!process.env.__NEXT_DEV_SERVER; + this.distDir = distDir; + this.relativeProjectDir = relativeProjectDir; + } + getRouterServerContext(req) { + var _routerServerGlobal_RouterServerContextSymbol; + const hostname = (0, _requestmeta.getRequestMeta)(req, 'hostname'); + const revalidate = (0, _requestmeta.getRequestMeta)(req, 'revalidate'); + const render404 = (0, _requestmeta.getRequestMeta)(req, 'render404'); + const relativeProjectDir = (0, _requestmeta.getRequestMeta)(req, 'relativeProjectDir') || this.relativeProjectDir; + const routerServerContext = (_routerServerGlobal_RouterServerContextSymbol = _routerservercontext.routerServerGlobal[_routerservercontext.RouterServerContextSymbol]) == null ? void 0 : _routerServerGlobal_RouterServerContextSymbol[relativeProjectDir]; + return { + ...routerServerContext, + ...hostname !== undefined ? { + hostname + } : {}, + ...revalidate !== undefined ? { + revalidate + } : {}, + ...render404 !== undefined ? { + render404 + } : {} + }; + } + getAssetPrefixForRender(routerServerContext, configuredAssetPrefix) { + // A running NextServer owns overrides from app.setAssetPrefix(). + if (routerServerContext && routerServerContext.getAssetPrefix) { + return routerServerContext.getAssetPrefix(); + } + // Direct route invocations use the configured prefix. + return configuredAssetPrefix; + } + normalizeUrl(_req, _parsedUrl) {} + async instrumentationOnRequestError(req, ...args) { + if (process.env.NEXT_RUNTIME === 'edge') { + const { getEdgeInstrumentationModule } = await import('../web/globals'); + const instrumentation = await getEdgeInstrumentationModule(); + if (instrumentation) { + await (instrumentation.onRequestError == null ? void 0 : instrumentation.onRequestError.call(instrumentation, ...args)); + } + } else { + const { join } = require('node:path'); + const absoluteProjectDir = join(/* turbopackIgnore: true */ process.cwd(), (0, _requestmeta.getRequestMeta)(req, 'relativeProjectDir') || this.relativeProjectDir); + const { instrumentationOnRequestError } = await import('../lib/router-utils/instrumentation-globals.external.js'); + return instrumentationOnRequestError(absoluteProjectDir, this.distDir, ...args); + } + } + loadManifests(srcPage, projectDir) { + let result; + if (process.env.NEXT_RUNTIME === 'edge') { + var _self___RSC_MANIFEST; + const { getEdgePreviewProps } = require('../web/get-edge-preview-props'); + const maybeJSONParse = (str)=>str ? JSON.parse(str) : undefined; + result = { + buildId: process.env.__NEXT_BUILD_ID || '', + buildManifest: self.__BUILD_MANIFEST, + fallbackBuildManifest: {}, + reactLoadableManifest: maybeJSONParse(self.__REACT_LOADABLE_MANIFEST), + nextFontManifest: maybeJSONParse(self.__NEXT_FONT_MANIFEST), + prerenderManifest: { + routes: {}, + dynamicRoutes: {}, + notFoundRoutes: [], + version: 4, + preview: getEdgePreviewProps() + }, + previewProps: getEdgePreviewProps(), + routesManifest: { + version: 4, + caseSensitive: Boolean(process.env.__NEXT_CASE_SENSITIVE_ROUTES), + basePath: process.env.__NEXT_BASE_PATH || '', + rewrites: process.env.__NEXT_REWRITES || { + beforeFiles: [], + afterFiles: [], + fallback: [] + }, + redirects: [], + headers: [], + onMatchHeaders: [], + i18n: process.env.__NEXT_I18N_CONFIG || undefined, + skipProxyUrlNormalize: Boolean(process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) + }, + serverFilesManifest: self.__SERVER_FILES_MANIFEST, + clientReferenceManifest: (_self___RSC_MANIFEST = self.__RSC_MANIFEST) == null ? void 0 : _self___RSC_MANIFEST[srcPage], + serverActionsManifest: maybeJSONParse(self.__RSC_SERVER_MANIFEST), + subresourceIntegrityManifest: maybeJSONParse(self.__SUBRESOURCE_INTEGRITY_MANIFEST), + dynamicCssManifest: maybeJSONParse(self.__DYNAMIC_CSS_MANIFEST), + // Edge pages are always dynamic so prefetch inlining hints + // don't apply. The runtime handles missing hints gracefully. + prefetchHintsManifest: undefined, + interceptionRoutePatterns: (maybeJSONParse(self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST) ?? []).map((rewrite)=>new RegExp(rewrite.regex)) + }; + } else { + var _clientReferenceManifest___RSC_MANIFEST; + if (!projectDir) { + throw new Error('Invariant: projectDir is required for node runtime'); + } + const { loadManifestFromRelativePath, evalManifestFromRelativePath } = require('../load-manifest.external'); + const normalizedPagePath = (0, _normalizepagepath.normalizePagePath)(srcPage); + const router = this.definition.kind === _routekind.RouteKind.PAGES || this.definition.kind === _routekind.RouteKind.PAGES_API ? 'pages' : 'app'; + const [routesManifest, prerenderManifest, previewProps, buildManifest, fallbackBuildManifest, reactLoadableManifest, nextFontManifest, clientReferenceManifest, serverActionsManifest, subresourceIntegrityManifest, serverFilesManifest, buildId, dynamicCssManifest, prefetchHintsManifest] = [ + loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + manifest: _constants.ROUTES_MANIFEST, + shouldCache: !this.isDev + }), + loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + manifest: _constants.PRERENDER_MANIFEST, + shouldCache: !this.isDev + }), + loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + manifest: `server/${_constants.PREVIEW_PROPS_MANIFEST}`, + shouldCache: !this.isDev + }), + loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + manifest: _constants.BUILD_MANIFEST, + shouldCache: !this.isDev + }), + srcPage === '/_error' ? loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + manifest: `fallback-${_constants.BUILD_MANIFEST}`, + shouldCache: !this.isDev, + handleMissing: true + }) ?? {} : {}, + loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + manifest: process.env.TURBOPACK ? `server/${router === 'app' ? 'app' : 'pages'}${normalizedPagePath}/${_constants.REACT_LOADABLE_MANIFEST}` : _constants.REACT_LOADABLE_MANIFEST, + handleMissing: true, + shouldCache: !this.isDev + }) ?? {}, + loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + manifest: `server/${_constants.NEXT_FONT_MANIFEST}.json`, + shouldCache: !this.isDev + }), + router === 'app' && !(0, _ismetadataroute.isStaticMetadataRoute)(srcPage) ? evalManifestFromRelativePath({ + distDir: this.distDir, + projectDir, + handleMissing: true, + manifest: `server/app${srcPage.replace(/%5F/g, '_') + '_' + _constants.CLIENT_REFERENCE_MANIFEST}.js`, + shouldCache: !this.isDev + }) : undefined, + router === 'app' ? loadManifestFromRelativePath({ + distDir: this.distDir, + projectDir, + manifest: `server/${_constants.SERVER_REFERENCE_MANIFEST}.json`, + handleMissing: true, + shouldCache: !this.isDev + }) : {}, + loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + manifest: `server/${_constants.SUBRESOURCE_INTEGRITY_MANIFEST}.json`, + handleMissing: true, + shouldCache: !this.isDev + }), + this.isDev ? undefined : loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + shouldCache: true, + manifest: `${_constants.SERVER_FILES_MANIFEST}.json` + }), + this.isDev ? 'development' : loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + manifest: _constants.BUILD_ID_FILE, + skipParse: true, + shouldCache: true + }), + loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + manifest: _constants.DYNAMIC_CSS_MANIFEST, + shouldCache: !this.isDev, + handleMissing: true + }), + router === 'app' ? loadManifestFromRelativePath({ + projectDir, + distDir: this.distDir, + manifest: `server/${_constants.PREFETCH_HINTS}`, + shouldCache: !this.isDev, + handleMissing: true + }) : undefined + ]; + result = { + buildId, + buildManifest, + fallbackBuildManifest, + routesManifest, + nextFontManifest, + prerenderManifest, + previewProps, + serverFilesManifest, + reactLoadableManifest, + clientReferenceManifest: clientReferenceManifest == null ? void 0 : (_clientReferenceManifest___RSC_MANIFEST = clientReferenceManifest.__RSC_MANIFEST) == null ? void 0 : _clientReferenceManifest___RSC_MANIFEST[srcPage.replace(/%5F/g, '_')], + serverActionsManifest, + subresourceIntegrityManifest, + dynamicCssManifest, + prefetchHintsManifest, + interceptionRoutePatterns: routesManifest.rewrites.beforeFiles.filter(_isinterceptionrouterewrite.isInterceptionRouteRewrite).map((rewrite)=>new RegExp(rewrite.regex)) + }; + } + return result; + } + async loadCustomCacheHandlers(req, nextConfig) { + if (process.env.NEXT_RUNTIME !== 'edge') { + const { cacheMaxMemorySize, cacheHandlers } = nextConfig; + if (!cacheHandlers) return; + (0, _handlers.initializeCacheHandlers)(cacheMaxMemorySize); + await (0, _handlers.registerCustomCacheHandlers)(async ()=>{ + for (const [kind, handler] of Object.entries(cacheHandlers)){ + if (!handler) continue; + const { formatDynamicImportPath } = require('../../lib/format-dynamic-import-path'); + const { join } = require('node:path'); + const absoluteProjectDir = join(/* turbopackIgnore: true */ process.cwd(), (0, _requestmeta.getRequestMeta)(req, 'relativeProjectDir') || this.relativeProjectDir); + (0, _handlers.setCacheHandler)(kind, (0, _interopdefault.interopDefault)(await dynamicImportEsmDefault(formatDynamicImportPath(`${absoluteProjectDir}/${this.distDir}`, handler)))); + } + }); + } + } + async getIncrementalCache(req, nextConfig, previewProps, prerenderManifest, isMinimalMode) { + if (process.env.NEXT_RUNTIME === 'edge') { + return globalThis.__incrementalCache; + } else { + var _nextConfig_i18n; + let CacheHandler; + const { cacheHandler } = nextConfig; + if (cacheHandler) { + const { formatDynamicImportPath } = require('../../lib/format-dynamic-import-path'); + CacheHandler = (0, _interopdefault.interopDefault)(await dynamicImportEsmDefault(formatDynamicImportPath(this.distDir, cacheHandler))); + } + const { join } = require('node:path'); + const projectDir = join(/* turbopackIgnore: true */ process.cwd(), (0, _requestmeta.getRequestMeta)(req, 'relativeProjectDir') || this.relativeProjectDir); + await this.loadCustomCacheHandlers(req, nextConfig); + // incremental-cache is request specific + // although can have shared caches in module scope + // per-cache handler + const incrementalCache = new _incrementalcache.IncrementalCache({ + fs: require('../lib/node-fs-methods').nodeFs, + dev: this.isDev, + requestHeaders: req.headers, + allowedRevalidateHeaderKeys: nextConfig.experimental.allowedRevalidateHeaderKeys, + minimalMode: isMinimalMode, + serverDistDir: `${projectDir}/${this.distDir}/server`, + fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix, + maxMemoryCacheSize: nextConfig.cacheMaxMemorySize, + flushToDisk: !isMinimalMode && nextConfig.experimental.isrFlushToDisk, + previewProps, + prerenderManifest, + CurCacheHandler: CacheHandler, + locales: (_nextConfig_i18n = nextConfig.i18n) == null ? void 0 : _nextConfig_i18n.locales + }); + globalThis.__incrementalCache = incrementalCache; + return incrementalCache; + } + } + async onRequestError(req, err, errorContext, silenceLog, routerServerContext) { + if (!silenceLog) { + if (routerServerContext == null ? void 0 : routerServerContext.logErrorWithOriginalStack) { + routerServerContext.logErrorWithOriginalStack(err, 'app-dir'); + } else { + console.error(err); + } + } + await this.instrumentationOnRequestError(req, err, { + path: req.url || '/', + headers: req.headers, + method: req.method || 'GET' + }, errorContext); + } + /** A more lightweight version of `prepare()` for only retrieving the config on edge */ getNextConfigEdge(req) { + var _nextConfig_experimental; + if (process.env.NEXT_RUNTIME !== 'edge') { + throw new Error('Invariant: getNextConfigEdge must only be called in edge runtime'); + } + let serverFilesManifest = self.__SERVER_FILES_MANIFEST; + const routerServerContext = this.getRouterServerContext(req); + const nextConfig = (routerServerContext == null ? void 0 : routerServerContext.nextConfig) || (serverFilesManifest == null ? void 0 : serverFilesManifest.config); + if (!nextConfig) { + throw new Error("Invariant: nextConfig couldn't be loaded"); + } + let deploymentId; + if ((_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.runtimeServerDeploymentId) { + if (!process.env.NEXT_DEPLOYMENT_ID) { + throw new Error('process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled'); + } + deploymentId = process.env.NEXT_DEPLOYMENT_ID; + } else { + deploymentId = nextConfig.deploymentId || ''; + } + return { + nextConfig, + deploymentId + }; + } + prepare(req, res, options) { + return (0, _tracer.getTracer)().trace(_constants1.RouteModuleSpan.prepare, { + spanName: 'prepare route module' + }, ()=>this.prepareImpl(req, res, options)); + } + async prepareImpl(req, res, { srcPage, multiZoneDraftMode }) { + var _req_headers_xforwardedproto, _nextConfig_experimental; + let absoluteProjectDir; + // edge runtime handles loading instrumentation at the edge adapter level + if (process.env.NEXT_RUNTIME !== 'edge') { + if (res) { + (0, _patchsetheader.patchSetHeaderWithCookieSupport)(req, res); + } + const { join, relative } = require('node:path'); + absoluteProjectDir = join(/* turbopackIgnore: true */ process.cwd(), (0, _requestmeta.getRequestMeta)(req, 'relativeProjectDir') || this.relativeProjectDir); + const absoluteDistDir = (0, _requestmeta.getRequestMeta)(req, 'distDir'); + if (absoluteDistDir) { + this.distDir = relative(absoluteProjectDir, absoluteDistDir); + } + const { ensureInstrumentationRegistered } = await import('../lib/router-utils/instrumentation-globals.external.js'); + // ensure instrumentation is registered and pass + // onRequestError below. Awaited so any caller of `RouteModule.prepare` + // that bypasses `BaseServer.handleRequest` (where this is also awaited + // via `prepareImpl`) still observes the instrumentation hook completing + // before the userland route handler runs. + await ensureInstrumentationRegistered(absoluteProjectDir, this.distDir); + } + const manifests = (0, _tracer.getTracer)().trace(_constants1.RouteModuleSpan.loadManifests, { + spanName: 'load route manifests' + }, ()=>this.loadManifests(srcPage, absoluteProjectDir)); + const { routesManifest, previewProps, serverFilesManifest } = manifests; + const { basePath, i18n, rewrites } = routesManifest; + const routerServerContext = this.getRouterServerContext(req); + const nextConfig = (routerServerContext == null ? void 0 : routerServerContext.nextConfig) || (serverFilesManifest == null ? void 0 : serverFilesManifest.config); + // Injected in base-server.ts + const protocol = ((_req_headers_xforwardedproto = req.headers['x-forwarded-proto']) == null ? void 0 : _req_headers_xforwardedproto.includes('https')) ? 'https' : 'http'; + // When there are hostname and port we build an absolute URL + if (!(0, _requestmeta.getRequestMeta)(req, 'initURL')) { + const initUrl = (serverFilesManifest == null ? void 0 : serverFilesManifest.config.experimental.trustHostHeader) ? `${protocol}://${req.headers.host || 'localhost'}${req.url}` : `${protocol}://${(routerServerContext == null ? void 0 : routerServerContext.hostname) || 'localhost'}${req.url}`; + (0, _requestmeta.addRequestMeta)(req, 'initURL', initUrl); + (0, _requestmeta.addRequestMeta)(req, 'initProtocol', protocol); + } + if (basePath) { + req.url = (0, _removepathprefix.removePathPrefix)(req.url || '/', basePath); + } + const parsedUrl = (0, _url.parseReqUrl)(req.url || '/'); + (0, _requestmeta.addRequestMeta)(req, 'initQuery', { + ...parsedUrl == null ? void 0 : parsedUrl.query + }); + // if we couldn't parse the URL we can't continue + if (!parsedUrl) { + return; + } + let isNextDataRequest = false; + if ((0, _pathhasprefix.pathHasPrefix)(parsedUrl.pathname || '/', '/_next/data')) { + isNextDataRequest = true; + parsedUrl.pathname = (0, _normalizedatapath.normalizeDataPath)(parsedUrl.pathname || '/'); + } + this.normalizeUrl(req, parsedUrl); + let originalPathname = parsedUrl.pathname || '/'; + const originalQuery = { + ...parsedUrl.query + }; + const pageIsDynamic = (0, _utils.isDynamicRoute)(srcPage); + let localeResult; + let detectedLocale; + if (i18n) { + localeResult = (0, _normalizelocalepath.normalizeLocalePath)(parsedUrl.pathname || '/', i18n.locales); + if (localeResult.detectedLocale) { + req.url = `${localeResult.pathname}${parsedUrl.search}`; + originalPathname = localeResult.pathname; + if (!detectedLocale) { + detectedLocale = localeResult.detectedLocale; + } + } + } + // Normalize the page path for route matching. The srcPage contains the + // internal page path (e.g., /app/[slug]/page), but route matchers expect + // the pathname format (e.g., /app/[slug]). + const normalizedSrcPage = (0, _apppaths.normalizeAppPath)(srcPage); + const serverUtils = (0, _serverutils.getServerUtils)({ + page: normalizedSrcPage, + i18n, + basePath, + rewrites, + pageIsDynamic, + trailingSlash: process.env.__NEXT_TRAILING_SLASH, + caseSensitive: Boolean(routesManifest.caseSensitive) + }); + const domainLocale = (0, _detectdomainlocale.detectDomainLocale)(i18n == null ? void 0 : i18n.domains, (0, _gethostname.getHostname)(parsedUrl, req.headers), detectedLocale); + if (Boolean(domainLocale)) { + (0, _requestmeta.addRequestMeta)(req, 'isLocaleDomain', Boolean(domainLocale)); + } + const defaultLocale = (0, _requestmeta.getRequestMeta)(req, 'defaultLocale') || (domainLocale == null ? void 0 : domainLocale.defaultLocale) || (i18n == null ? void 0 : i18n.defaultLocale); + // Ensure parsedUrl.pathname includes locale before processing + // rewrites or they won't match correctly. + if (defaultLocale && !detectedLocale) { + parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname === '/' ? '' : parsedUrl.pathname}`; + } + const locale = (0, _requestmeta.getRequestMeta)(req, 'locale') || detectedLocale || defaultLocale; + // we apply rewrites against cloned URL so that we don't + // modify the original with the rewrite destination + const { rewriteParams, rewrittenParsedUrl } = serverUtils.handleRewrites(req, parsedUrl); + const rewriteParamKeys = Object.keys(rewriteParams); + Object.assign(parsedUrl.query, rewrittenParsedUrl.query); + // after processing rewrites we want to remove locale + // from parsedUrl pathname + if (i18n) { + parsedUrl.pathname = (0, _normalizelocalepath.normalizeLocalePath)(parsedUrl.pathname || '/', i18n.locales).pathname; + rewrittenParsedUrl.pathname = (0, _normalizelocalepath.normalizeLocalePath)(rewrittenParsedUrl.pathname || '/', i18n.locales).pathname; + } + let params = (0, _requestmeta.getRequestMeta)(req, 'params'); + // attempt parsing from pathname + if (!params && serverUtils.dynamicRouteMatcher) { + const paramsMatch = serverUtils.dynamicRouteMatcher((0, _normalizedatapath.normalizeDataPath)((rewrittenParsedUrl == null ? void 0 : rewrittenParsedUrl.pathname) || parsedUrl.pathname || '/')); + const paramsResult = serverUtils.normalizeDynamicRouteParams(paramsMatch || {}, true); + if (paramsResult.hasValidParams) { + params = paramsResult.params; + } + } + // Local "next start" expects the routing parsed query values + // to not be present in the URL although when deployed proxies + // will add query values from resolving the routes to pass to function. + // TODO: do we want to change expectations for "next start" + // to include these query values in the URL which affects asPath + // but would match deployed behavior, e.g. a rewrite from middleware + // that adds a query param would be in asPath as query but locally + // it won't be in the asPath but still available in the query object + const query = (0, _requestmeta.getRequestMeta)(req, 'query') || { + ...parsedUrl.query + }; + const routeParamKeys = new Set(); + const combinedParamKeys = []; + // We don't include rewriteParamKeys in the combinedParamKeys + // for app router since the searchParams is populated from the + // URL so we don't want to strip the rewrite params from the URL + // so that searchParams can include them. + if (this.definition.kind === _routekind.RouteKind.PAGES || this.definition.kind === _routekind.RouteKind.PAGES_API) { + for (const key of [ + ...rewriteParamKeys, + ...Object.keys(serverUtils.defaultRouteMatches || {}) + ]){ + // We only want to filter rewrite param keys from the URL + // if they are matches from the URL e.g. the key/value matches + // before and after applying the rewrites /:path for /hello and + // { path: 'hello' } but not for { path: 'another' } and /hello + // TODO: we should prefix rewrite param keys the same as we do + // for dynamic routes so we can identify them properly + const originalValue = Array.isArray(originalQuery[key]) ? originalQuery[key].join('') : originalQuery[key]; + const queryValue = Array.isArray(query[key]) ? query[key].join('') : query[key]; + if (!(key in originalQuery) || originalValue === queryValue) { + combinedParamKeys.push(key); + } + } + } + serverUtils.normalizeCdnUrl(req, combinedParamKeys); + // When Next is not hosted in a single process, upstream proxies will add query values for route params that were used to match the route. + // Outside of that environment, there is no reason to do any normalization to honor those query values. + if (!(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer)) { + serverUtils.normalizeQueryParams(query, routeParamKeys); + } else { + serverUtils.filterInternalQuery(query, []); + } + serverUtils.filterInternalQuery(originalQuery, combinedParamKeys); + if (pageIsDynamic) { + const queryResult = serverUtils.normalizeDynamicRouteParams(query, true); + const paramsResult = serverUtils.normalizeDynamicRouteParams(params || {}, true); + let paramsToInterpolate; + if (// if both query and params are valid but one + // provided more information and the query params + // were nxtP prefixed rely on that one + query && params && paramsResult.hasValidParams && queryResult.hasValidParams && routeParamKeys.size > 0 && Object.keys(paramsResult.params).length <= Object.keys(queryResult.params).length) { + paramsToInterpolate = queryResult.params; + params = Object.assign(queryResult.params); + } else { + paramsToInterpolate = paramsResult.hasValidParams && params ? params : queryResult.hasValidParams ? query : {}; + } + req.url = serverUtils.interpolateDynamicPath(req.url || '/', paramsToInterpolate); + parsedUrl.pathname = serverUtils.interpolateDynamicPath(parsedUrl.pathname || '/', paramsToInterpolate); + originalPathname = serverUtils.interpolateDynamicPath(originalPathname, paramsToInterpolate); + // try pulling from query if valid + if (!params) { + if (queryResult.hasValidParams) { + params = Object.assign({}, queryResult.params); + // If we pulled from query remove it so it's + // only in params + for(const key in serverUtils.defaultRouteMatches){ + delete query[key]; + } + } else { + // use final params from URL matching + const paramsMatch = serverUtils.dynamicRouteMatcher == null ? void 0 : serverUtils.dynamicRouteMatcher.call(serverUtils, (0, _normalizedatapath.normalizeDataPath)((localeResult == null ? void 0 : localeResult.pathname) || parsedUrl.pathname || '/')); + // we don't normalize these as they are allowed to be + // the literal slug matches here e.g. /blog/[slug] + // actually being requested + if (paramsMatch) { + params = Object.assign({}, paramsMatch); + } + } + } + // When partial nxtP* params are provided (e.g. background + // revalidation for intermediate PPR shells), both + // normalizeDynamicRouteParams calls above fail because not all + // route params are present. Merge the normalized query params + // (from nxtP*) into the current params to override placeholders + // with concrete values. + if (params && routeParamKeys.size > 0 && !paramsResult.hasValidParams && !queryResult.hasValidParams) { + for (const key of routeParamKeys){ + if (query[key] !== undefined) { + params[key] = query[key]; + } + } + (0, _requestmeta.addRequestMeta)(req, 'resolvedRouteParamKeys', routeParamKeys); + } + } + // Remove any normalized params from the query if they + // weren't present as non-prefixed query key e.g. + // ?search=1&nxtPsearch=hello we don't delete search + for (const key of routeParamKeys){ + if (!(key in originalQuery)) { + delete query[key]; + // handle the case where there's collision and we + // normalized nxtPid=123 -> id=123 but user also + // sends id=456 as separate key + } else if (originalQuery[key] && query[key] && originalQuery[key] !== query[key]) { + query[key] = originalQuery[key]; + } + } + const { isOnDemandRevalidate, revalidateOnlyGenerated } = (0, _apiutils.checkIsOnDemandRevalidate)(req.headers, previewProps); + let isDraftMode = false; + let previewData; + // preview data relies on non-edge utils + if (process.env.NEXT_RUNTIME !== 'edge' && res) { + const { tryGetPreviewData } = require('../api-utils/node/try-get-preview-data'); + previewData = tryGetPreviewData(req, res, previewProps, Boolean(multiZoneDraftMode)); + isDraftMode = previewData !== false; + } + if (!nextConfig) { + throw new Error("Invariant: nextConfig couldn't be loaded"); + } + if (process.env.NEXT_RUNTIME !== 'edge') { + const { installProcessErrorHandlers } = require('../node-environment-extensions/process-error-handlers'); + installProcessErrorHandlers(Boolean(nextConfig.experimental.removeUncaughtErrorAndRejectionListeners)); + } + let resolvedPathname = normalizedSrcPage; + if ((0, _utils.isDynamicRoute)(resolvedPathname) && params) { + resolvedPathname = serverUtils.interpolateDynamicPath(resolvedPathname, params); + } + if (resolvedPathname === '/index') { + resolvedPathname = '/'; + } + if (res && Boolean(req.headers['x-nextjs-data']) && (!res.statusCode || res.statusCode === 200)) { + res.setHeader('x-nextjs-matched-path', (0, _removetrailingslash.removeTrailingSlash)(`${locale ? `/${locale}` : ''}${normalizedSrcPage}`)); + } + const encodedResolvedPathname = resolvedPathname; + // we decode for cache key/manifest usage encoded is + // for URL building + try { + resolvedPathname = (0, _decodepathparams.decodePathParams)(resolvedPathname); + } catch (_) {} + resolvedPathname = (0, _removetrailingslash.removeTrailingSlash)(resolvedPathname); + let deploymentId; + if ((_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.runtimeServerDeploymentId) { + if (!process.env.NEXT_DEPLOYMENT_ID) { + throw new Error('process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled'); + } + deploymentId = process.env.NEXT_DEPLOYMENT_ID; + } else { + deploymentId = nextConfig.deploymentId || ''; + } + return { + query, + originalQuery, + originalPathname, + params, + parsedUrl, + locale, + isNextDataRequest, + locales: i18n == null ? void 0 : i18n.locales, + defaultLocale, + isDraftMode, + previewData, + pageIsDynamic, + resolvedPathname, + encodedResolvedPathname, + isOnDemandRevalidate, + revalidateOnlyGenerated, + ...manifests, + // loadManifest returns a readonly object, but we don't want to propagate that throughout the + // whole codebase (for now) + nextConfig: nextConfig, + routerServerContext, + deploymentId, + clientAssetToken: nextConfig.supportsImmutableAssets ? '' : deploymentId + }; + } + getResponseCache(req) { + if (!this.responseCache) { + const minimalMode = (0, _requestmeta.getRequestMeta)(req, 'minimalMode') ?? false; + this.responseCache = new _responsecache.default({ + minimalMode, + route: this.cacheOwner + }); + } + return this.responseCache; + } + async handleResponse({ req, nextConfig, cacheKey, routeKind, isFallback, previewProps, prerenderManifest, isRoutePPREnabled, isOnDemandRevalidate, revalidateOnlyGenerated, responseGenerator, waitUntil, isMinimalMode }) { + const responseCache = this.getResponseCache(req); + const cacheEntry = await responseCache.get(cacheKey, responseGenerator, { + routeKind, + isFallback, + isRoutePPREnabled, + isOnDemandRevalidate, + // A Next.js Segment Cache prefetch uses the `Next-Router-Prefetch` + // header (surfaced as the `isPrefetchRSCRequest` request meta), not the + // standard browser `purpose: prefetch` header. Recognize both so the + // response cache treats segment prefetches as prefetches — most + // importantly, so a prefetch that misses serves a fallback shell rather + // than joining an in-flight background (concrete) revalidation. + isPrefetch: req.headers.purpose === 'prefetch' || (0, _requestmeta.getRequestMeta)(req, 'isPrefetchRSCRequest') === true, + // Use x-invocation-id header to scope the in-memory cache to a single + // revalidation request in minimal mode. + invocationID: req.headers['x-invocation-id'], + incrementalCache: await this.getIncrementalCache(req, nextConfig, previewProps, prerenderManifest, isMinimalMode), + waitUntil + }); + if (!cacheEntry) { + if (cacheKey && // revalidate only generated can bail even if cacheKey is provided + !(isOnDemandRevalidate && revalidateOnlyGenerated)) { + // A cache entry might not be generated if a response is written + // in `getInitialProps` or `getServerSideProps`, but those shouldn't + // have a cache key. If we do have a cache key but we don't end up + // with a cache entry, then either Next.js or the application has a + // bug that needs fixing. + throw new Error('invariant: cache entry required but not generated'); + } + } + return cacheEntry; + } +} + +//# sourceMappingURL=route-module.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/route-modules/route-module.js.map b/e-commerce/node_modules/next/dist/server/route-modules/route-module.js.map new file mode 100644 index 0000000000000000000000000000000000000000..eb583951cb5fd40697422bfa9c976a8c801340c3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/route-modules/route-module.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/route-modules/route-module.ts"],"sourcesContent":["import '../../build/adapter/setup-node-env.external'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type {\n InstrumentationOnRequestError,\n RequestErrorContext,\n} from '../instrumentation/types'\nimport type { ParsedUrlQuery } from 'node:querystring'\nimport type { UrlWithParsedQuery } from 'node:url'\nimport type {\n PrerenderManifest,\n PreviewPropsManifest,\n RequiredServerFilesManifest,\n} from '../../build'\nimport type { DevRoutesManifest } from '../lib/router-utils/setup-dev-bundler'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport {\n BUILD_ID_FILE,\n BUILD_MANIFEST,\n CLIENT_REFERENCE_MANIFEST,\n DYNAMIC_CSS_MANIFEST,\n NEXT_FONT_MANIFEST,\n PREFETCH_HINTS,\n PRERENDER_MANIFEST,\n PREVIEW_PROPS_MANIFEST,\n REACT_LOADABLE_MANIFEST,\n ROUTES_MANIFEST,\n SERVER_FILES_MANIFEST,\n SERVER_REFERENCE_MANIFEST,\n SUBRESOURCE_INTEGRITY_MANIFEST,\n} from '../../shared/lib/constants'\nimport { parseReqUrl } from '../../lib/url'\nimport {\n normalizeLocalePath,\n type PathLocale,\n} from '../../shared/lib/i18n/normalize-locale-path'\nimport { isDynamicRoute } from '../../shared/lib/router/utils'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { getServerUtils } from '../server-utils'\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { checkIsOnDemandRevalidate, type __ApiPreviewProps } from '../api-utils'\nimport type { PreviewData } from '../../types'\nimport type { BuildManifest } from '../get-page-files'\nimport type { ReactLoadableManifest } from '../load-components'\nimport type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'\nimport { normalizeDataPath } from '../../shared/lib/page-path/normalize-data-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextIncomingMessage,\n} from '../request-meta'\nimport { patchSetHeaderWithCookieSupport } from '../lib/patch-set-header'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { isStaticMetadataRoute } from '../../lib/metadata/is-metadata-route'\nimport { IncrementalCache } from '../lib/incremental-cache'\nimport {\n initializeCacheHandlers,\n registerCustomCacheHandlers,\n setCacheHandler,\n} from '../use-cache/handlers'\nimport { interopDefault } from '../app-render/interop-default'\nimport { RouteKind } from '../route-kind'\nimport {\n getResponseCacheOwner,\n type ResponseCacheOwner,\n} from '../lib/route-cache-key'\nimport type { BaseNextRequest } from '../base-http'\nimport type { I18NConfig, NextConfigRuntime } from '../config-shared'\nimport ResponseCache, { type ResponseGenerator } from '../response-cache'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n type RouterServerContext,\n} from '../lib/router-utils/router-server-context'\nimport { decodePathParams } from '../lib/router-utils/decode-path-params'\nimport { removeTrailingSlash } from '../../shared/lib/router/utils/remove-trailing-slash'\nimport { isInterceptionRouteRewrite } from '../../lib/is-interception-route-rewrite'\nimport { getTracer } from '../lib/trace/tracer'\nimport { RouteModuleSpan } from '../lib/trace/constants'\n\n/**\n * RouteModuleOptions is the options that are passed to the route module, other\n * route modules should extend this class to add specific options for their\n * route.\n */\nexport interface RouteModuleOptions<\n D extends RouteDefinition = RouteDefinition,\n U = unknown,\n> {\n readonly definition: Readonly\n readonly userland: Readonly\n readonly distDir: string\n readonly relativeProjectDir: string\n}\n\n/**\n * RouteHandlerContext is the base context for a route handler.\n */\nexport interface RouteModuleHandleContext {\n /**\n * Any matched parameters for the request. This is only defined for dynamic\n * routes.\n */\n params: Record | undefined\n}\n\nconst dynamicImportEsmDefault = (id: string) =>\n import(/* webpackIgnore: true */ /* turbopackIgnore: true */ id).then(\n (mod) => mod.default || mod\n )\n\n/**\n * RouteModule is the base class for all route modules. This class should be\n * extended by all route modules.\n */\nexport abstract class RouteModule<\n D extends RouteDefinition = RouteDefinition,\n U = unknown,\n> {\n /**\n * The userland module. This is the module that is exported from the user's\n * code. Exposed as a getter so subclasses can override with lazy loading.\n */\n protected _userland: Readonly\n\n get userland(): Readonly {\n return this._userland\n }\n\n /**\n * The definition of the route.\n */\n public readonly definition: Readonly\n\n /** The canonical source identity shared by cache reads, writes, and metadata. */\n public readonly cacheOwner: ResponseCacheOwner\n\n /**\n * The shared modules that are exposed and required for the route module.\n */\n public static readonly sharedModules: any\n\n public isDev: boolean\n public distDir: string\n public relativeProjectDir: string\n public incrementCache?: IncrementalCache\n public responseCache?: ResponseCache\n\n constructor({\n userland,\n definition,\n distDir,\n relativeProjectDir,\n }: RouteModuleOptions) {\n this._userland = userland\n this.definition = definition\n this.cacheOwner = getResponseCacheOwner(definition)\n this.isDev = !!process.env.__NEXT_DEV_SERVER\n this.distDir = distDir\n this.relativeProjectDir = relativeProjectDir\n }\n\n private getRouterServerContext(\n req: NextIncomingMessage\n ): RouterServerContext[string] | undefined {\n const hostname = getRequestMeta(req, 'hostname')\n const revalidate = getRequestMeta(req, 'revalidate')\n const render404 = getRequestMeta(req, 'render404')\n const relativeProjectDir =\n getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir\n const routerServerContext =\n routerServerGlobal[RouterServerContextSymbol]?.[relativeProjectDir]\n\n return {\n ...routerServerContext,\n ...(hostname !== undefined ? { hostname } : {}),\n ...(revalidate !== undefined ? { revalidate } : {}),\n ...(render404 !== undefined ? { render404 } : {}),\n }\n }\n\n public getAssetPrefixForRender(\n routerServerContext: RouterServerContext[string] | undefined,\n configuredAssetPrefix: string\n ): string {\n // A running NextServer owns overrides from app.setAssetPrefix().\n if (routerServerContext && routerServerContext.getAssetPrefix) {\n return routerServerContext.getAssetPrefix()\n }\n // Direct route invocations use the configured prefix.\n return configuredAssetPrefix\n }\n\n public normalizeUrl(\n _req: IncomingMessage | BaseNextRequest,\n _parsedUrl: UrlWithParsedQuery\n ) {}\n\n public async instrumentationOnRequestError(\n req: IncomingMessage | BaseNextRequest,\n ...args: Parameters\n ) {\n if (process.env.NEXT_RUNTIME === 'edge') {\n const { getEdgeInstrumentationModule } = await import('../web/globals')\n const instrumentation = await getEdgeInstrumentationModule()\n\n if (instrumentation) {\n await instrumentation.onRequestError?.(...args)\n }\n } else {\n const { join } = require('node:path') as typeof import('node:path')\n const absoluteProjectDir = join(\n /* turbopackIgnore: true */\n process.cwd(),\n getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir\n )\n\n const { instrumentationOnRequestError } = await import(\n '../lib/router-utils/instrumentation-globals.external.js'\n )\n\n return instrumentationOnRequestError(\n absoluteProjectDir,\n this.distDir,\n ...args\n )\n }\n }\n\n private loadManifests(\n srcPage: string,\n projectDir?: string\n ): {\n buildId: string\n buildManifest: BuildManifest\n fallbackBuildManifest: BuildManifest\n routesManifest: DeepReadonly\n nextFontManifest: DeepReadonly\n prerenderManifest: DeepReadonly\n serverFilesManifest: DeepReadonly | undefined\n reactLoadableManifest: DeepReadonly\n subresourceIntegrityManifest: any\n clientReferenceManifest: any\n serverActionsManifest: any\n dynamicCssManifest: any\n prefetchHintsManifest: Record | undefined\n interceptionRoutePatterns: RegExp[]\n previewProps: __ApiPreviewProps\n } {\n let result\n if (process.env.NEXT_RUNTIME === 'edge') {\n const { getEdgePreviewProps } =\n require('../web/get-edge-preview-props') as typeof import('../web/get-edge-preview-props')\n\n const maybeJSONParse = (str?: string) =>\n str ? JSON.parse(str) : undefined\n\n result = {\n buildId: process.env.__NEXT_BUILD_ID || '',\n buildManifest: self.__BUILD_MANIFEST as any,\n fallbackBuildManifest: {} as any,\n reactLoadableManifest: maybeJSONParse(self.__REACT_LOADABLE_MANIFEST),\n nextFontManifest: maybeJSONParse(self.__NEXT_FONT_MANIFEST),\n prerenderManifest: {\n routes: {},\n dynamicRoutes: {},\n notFoundRoutes: [],\n version: 4,\n preview: getEdgePreviewProps(),\n } as const,\n previewProps: getEdgePreviewProps(),\n routesManifest: {\n version: 4,\n caseSensitive: Boolean(process.env.__NEXT_CASE_SENSITIVE_ROUTES),\n basePath: process.env.__NEXT_BASE_PATH || '',\n rewrites: (process.env.__NEXT_REWRITES as any) || {\n beforeFiles: [],\n afterFiles: [],\n fallback: [],\n },\n redirects: [],\n headers: [],\n onMatchHeaders: [],\n i18n:\n (process.env.__NEXT_I18N_CONFIG as any as I18NConfig) || undefined,\n skipProxyUrlNormalize: Boolean(\n process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n ),\n },\n serverFilesManifest: self.__SERVER_FILES_MANIFEST,\n clientReferenceManifest: self.__RSC_MANIFEST?.[srcPage],\n serverActionsManifest: maybeJSONParse(self.__RSC_SERVER_MANIFEST),\n subresourceIntegrityManifest: maybeJSONParse(\n self.__SUBRESOURCE_INTEGRITY_MANIFEST\n ),\n dynamicCssManifest: maybeJSONParse(self.__DYNAMIC_CSS_MANIFEST),\n // Edge pages are always dynamic so prefetch inlining hints\n // don't apply. The runtime handles missing hints gracefully.\n prefetchHintsManifest: undefined,\n interceptionRoutePatterns: (\n maybeJSONParse(self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST) ?? []\n ).map((rewrite: any) => new RegExp(rewrite.regex)),\n }\n } else {\n if (!projectDir) {\n throw new Error('Invariant: projectDir is required for node runtime')\n }\n const { loadManifestFromRelativePath, evalManifestFromRelativePath } =\n require('../load-manifest.external') as typeof import('../load-manifest.external')\n const normalizedPagePath = normalizePagePath(srcPage)\n\n const router =\n this.definition.kind === RouteKind.PAGES ||\n this.definition.kind === RouteKind.PAGES_API\n ? 'pages'\n : 'app'\n\n const [\n routesManifest,\n prerenderManifest,\n previewProps,\n buildManifest,\n fallbackBuildManifest,\n reactLoadableManifest,\n nextFontManifest,\n clientReferenceManifest,\n serverActionsManifest,\n subresourceIntegrityManifest,\n serverFilesManifest,\n buildId,\n dynamicCssManifest,\n prefetchHintsManifest,\n ] = [\n loadManifestFromRelativePath({\n projectDir,\n distDir: this.distDir,\n manifest: ROUTES_MANIFEST,\n shouldCache: !this.isDev,\n }),\n loadManifestFromRelativePath({\n projectDir,\n distDir: this.distDir,\n manifest: PRERENDER_MANIFEST,\n shouldCache: !this.isDev,\n }),\n loadManifestFromRelativePath({\n projectDir,\n distDir: this.distDir,\n manifest: `server/${PREVIEW_PROPS_MANIFEST}`,\n shouldCache: !this.isDev,\n }),\n loadManifestFromRelativePath({\n projectDir,\n distDir: this.distDir,\n manifest: BUILD_MANIFEST,\n shouldCache: !this.isDev,\n }),\n srcPage === '/_error'\n ? (loadManifestFromRelativePath({\n projectDir,\n distDir: this.distDir,\n manifest: `fallback-${BUILD_MANIFEST}`,\n shouldCache: !this.isDev,\n handleMissing: true,\n // TODO this cast is unsafe\n }) ?? ({} as BuildManifest))\n : // TODO this cast is unsafe\n ({} as BuildManifest),\n loadManifestFromRelativePath({\n projectDir,\n distDir: this.distDir,\n manifest: process.env.TURBOPACK\n ? `server/${router === 'app' ? 'app' : 'pages'}${normalizedPagePath}/${REACT_LOADABLE_MANIFEST}`\n : REACT_LOADABLE_MANIFEST,\n handleMissing: true,\n shouldCache: !this.isDev,\n }) ?? ({} satisfies ReactLoadableManifest),\n loadManifestFromRelativePath({\n projectDir,\n distDir: this.distDir,\n manifest: `server/${NEXT_FONT_MANIFEST}.json`,\n shouldCache: !this.isDev,\n }),\n router === 'app' && !isStaticMetadataRoute(srcPage)\n ? evalManifestFromRelativePath({\n distDir: this.distDir,\n projectDir,\n handleMissing: true,\n manifest: `server/app${srcPage.replace(/%5F/g, '_') + '_' + CLIENT_REFERENCE_MANIFEST}.js`,\n shouldCache: !this.isDev,\n })\n : undefined,\n router === 'app'\n ? loadManifestFromRelativePath({\n distDir: this.distDir,\n projectDir,\n manifest: `server/${SERVER_REFERENCE_MANIFEST}.json`,\n handleMissing: true,\n shouldCache: !this.isDev,\n })\n : {},\n loadManifestFromRelativePath>({\n projectDir,\n distDir: this.distDir,\n manifest: `server/${SUBRESOURCE_INTEGRITY_MANIFEST}.json`,\n handleMissing: true,\n shouldCache: !this.isDev,\n }),\n this.isDev\n ? undefined\n : loadManifestFromRelativePath({\n projectDir,\n distDir: this.distDir,\n shouldCache: true,\n manifest: `${SERVER_FILES_MANIFEST}.json`,\n }),\n this.isDev\n ? 'development'\n : loadManifestFromRelativePath({\n projectDir,\n distDir: this.distDir,\n manifest: BUILD_ID_FILE,\n skipParse: true,\n shouldCache: true,\n }),\n loadManifestFromRelativePath({\n projectDir,\n distDir: this.distDir,\n manifest: DYNAMIC_CSS_MANIFEST,\n shouldCache: !this.isDev,\n handleMissing: true,\n }),\n router === 'app'\n ? loadManifestFromRelativePath>({\n projectDir,\n distDir: this.distDir,\n manifest: `server/${PREFETCH_HINTS}`,\n shouldCache: !this.isDev,\n handleMissing: true,\n })\n : undefined,\n ]\n\n result = {\n buildId,\n buildManifest,\n fallbackBuildManifest,\n routesManifest,\n nextFontManifest,\n prerenderManifest,\n previewProps,\n serverFilesManifest,\n reactLoadableManifest,\n clientReferenceManifest: (clientReferenceManifest as any)\n ?.__RSC_MANIFEST?.[srcPage.replace(/%5F/g, '_')],\n serverActionsManifest,\n subresourceIntegrityManifest,\n dynamicCssManifest,\n prefetchHintsManifest,\n interceptionRoutePatterns: routesManifest.rewrites.beforeFiles\n .filter(isInterceptionRouteRewrite)\n .map((rewrite) => new RegExp(rewrite.regex)),\n }\n }\n\n return result\n }\n\n public async loadCustomCacheHandlers(\n req: IncomingMessage | BaseNextRequest,\n nextConfig: NextConfigRuntime\n ) {\n if (process.env.NEXT_RUNTIME !== 'edge') {\n const { cacheMaxMemorySize, cacheHandlers } = nextConfig\n if (!cacheHandlers) return\n\n initializeCacheHandlers(cacheMaxMemorySize)\n await registerCustomCacheHandlers(async () => {\n for (const [kind, handler] of Object.entries(cacheHandlers)) {\n if (!handler) continue\n\n const { formatDynamicImportPath } =\n require('../../lib/format-dynamic-import-path') as typeof import('../../lib/format-dynamic-import-path')\n\n const { join } = require('node:path') as typeof import('node:path')\n const absoluteProjectDir = join(\n /* turbopackIgnore: true */\n process.cwd(),\n getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir\n )\n\n setCacheHandler(\n kind,\n interopDefault(\n await dynamicImportEsmDefault(\n formatDynamicImportPath(\n `${absoluteProjectDir}/${this.distDir}`,\n handler\n )\n )\n )\n )\n }\n })\n }\n }\n\n public async getIncrementalCache(\n req: IncomingMessage | BaseNextRequest,\n nextConfig: NextConfigRuntime,\n previewProps: DeepReadonly<__ApiPreviewProps>,\n prerenderManifest: DeepReadonly,\n isMinimalMode: boolean\n ): Promise {\n if (process.env.NEXT_RUNTIME === 'edge') {\n return (globalThis as any).__incrementalCache\n } else {\n let CacheHandler: any\n const { cacheHandler } = nextConfig\n\n if (cacheHandler) {\n const { formatDynamicImportPath } =\n require('../../lib/format-dynamic-import-path') as typeof import('../../lib/format-dynamic-import-path')\n\n CacheHandler = interopDefault(\n await dynamicImportEsmDefault(\n formatDynamicImportPath(this.distDir, cacheHandler)\n )\n )\n }\n const { join } = require('node:path') as typeof import('node:path')\n const projectDir = join(\n /* turbopackIgnore: true */\n process.cwd(),\n getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir\n )\n\n await this.loadCustomCacheHandlers(req, nextConfig)\n\n // incremental-cache is request specific\n // although can have shared caches in module scope\n // per-cache handler\n const incrementalCache = new IncrementalCache({\n fs: (\n require('../lib/node-fs-methods') as typeof import('../lib/node-fs-methods')\n ).nodeFs,\n dev: this.isDev,\n requestHeaders: req.headers,\n allowedRevalidateHeaderKeys:\n nextConfig.experimental.allowedRevalidateHeaderKeys,\n minimalMode: isMinimalMode,\n serverDistDir: `${projectDir}/${this.distDir}/server`,\n fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,\n maxMemoryCacheSize: nextConfig.cacheMaxMemorySize,\n flushToDisk: !isMinimalMode && nextConfig.experimental.isrFlushToDisk,\n previewProps,\n prerenderManifest,\n CurCacheHandler: CacheHandler,\n locales: nextConfig.i18n?.locales,\n })\n\n // we need to expose this on globalThis as the app-render\n // workStore grabs the incrementalCache from there\n ;(globalThis as any).__incrementalCache = incrementalCache\n return incrementalCache\n }\n }\n\n public async onRequestError(\n req: IncomingMessage | BaseNextRequest,\n err: unknown,\n errorContext: RequestErrorContext,\n silenceLog: boolean,\n routerServerContext?: RouterServerContext[string]\n ) {\n if (!silenceLog) {\n if (routerServerContext?.logErrorWithOriginalStack) {\n routerServerContext.logErrorWithOriginalStack(err, 'app-dir')\n } else {\n console.error(err)\n }\n }\n await this.instrumentationOnRequestError(\n req,\n err,\n {\n path: req.url || '/',\n headers: req.headers,\n method: req.method || 'GET',\n },\n errorContext\n )\n }\n\n /** A more lightweight version of `prepare()` for only retrieving the config on edge */\n public getNextConfigEdge(req: NextIncomingMessage): {\n nextConfig: NextConfigRuntime\n deploymentId: string\n } {\n if (process.env.NEXT_RUNTIME !== 'edge') {\n throw new Error(\n 'Invariant: getNextConfigEdge must only be called in edge runtime'\n )\n }\n\n let serverFilesManifest = self.__SERVER_FILES_MANIFEST as any as\n | RequiredServerFilesManifest\n | undefined\n const routerServerContext = this.getRouterServerContext(req)\n const nextConfig =\n routerServerContext?.nextConfig || serverFilesManifest?.config\n\n if (!nextConfig) {\n throw new Error(\"Invariant: nextConfig couldn't be loaded\")\n }\n\n let deploymentId\n if (nextConfig.experimental?.runtimeServerDeploymentId) {\n if (!process.env.NEXT_DEPLOYMENT_ID) {\n throw new Error(\n 'process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled'\n )\n }\n deploymentId = process.env.NEXT_DEPLOYMENT_ID\n } else {\n deploymentId = nextConfig.deploymentId || ''\n }\n\n return { nextConfig, deploymentId }\n }\n\n public prepare(\n req: IncomingMessage | BaseNextRequest,\n res: ServerResponse | null,\n options: {\n srcPage: string\n multiZoneDraftMode?: boolean\n }\n ) {\n return getTracer().trace(\n RouteModuleSpan.prepare,\n { spanName: 'prepare route module' },\n () => this.prepareImpl(req, res, options)\n )\n }\n\n private async prepareImpl(\n req: IncomingMessage | BaseNextRequest,\n res: ServerResponse | null,\n {\n srcPage,\n multiZoneDraftMode,\n }: {\n srcPage: string\n multiZoneDraftMode?: boolean\n }\n ): Promise<\n | {\n buildId: string\n deploymentId: string\n clientAssetToken: string\n locale?: string\n locales?: readonly string[]\n defaultLocale?: string\n query: ParsedUrlQuery\n originalQuery: ParsedUrlQuery\n originalPathname: string\n params?: ParsedUrlQuery\n parsedUrl: UrlWithParsedQuery\n previewData: PreviewData\n pageIsDynamic: boolean\n isDraftMode: boolean\n resolvedPathname: string\n encodedResolvedPathname: string\n isNextDataRequest: boolean\n buildManifest: DeepReadonly\n fallbackBuildManifest: DeepReadonly\n nextFontManifest: DeepReadonly\n serverFilesManifest:\n | DeepReadonly\n | undefined\n reactLoadableManifest: DeepReadonly\n routesManifest: DeepReadonly\n prerenderManifest: DeepReadonly\n // we can't pull in the client reference type or it causes issues with\n // our pre-compiled types\n clientReferenceManifest?: any\n serverActionsManifest?: any\n dynamicCssManifest?: any\n prefetchHintsManifest?: Record\n subresourceIntegrityManifest?: DeepReadonly>\n isOnDemandRevalidate: boolean\n revalidateOnlyGenerated: boolean\n nextConfig: NextConfigRuntime\n routerServerContext?: RouterServerContext[string]\n interceptionRoutePatterns?: any\n previewProps: __ApiPreviewProps\n }\n | undefined\n > {\n let absoluteProjectDir: string | undefined\n\n // edge runtime handles loading instrumentation at the edge adapter level\n if (process.env.NEXT_RUNTIME !== 'edge') {\n if (res) {\n patchSetHeaderWithCookieSupport(req, res)\n }\n\n const { join, relative } =\n require('node:path') as typeof import('node:path')\n\n absoluteProjectDir = join(\n /* turbopackIgnore: true */\n process.cwd(),\n getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir\n )\n\n const absoluteDistDir = getRequestMeta(req, 'distDir')\n\n if (absoluteDistDir) {\n this.distDir = relative(absoluteProjectDir, absoluteDistDir)\n }\n const { ensureInstrumentationRegistered } = await import(\n '../lib/router-utils/instrumentation-globals.external.js'\n )\n // ensure instrumentation is registered and pass\n // onRequestError below. Awaited so any caller of `RouteModule.prepare`\n // that bypasses `BaseServer.handleRequest` (where this is also awaited\n // via `prepareImpl`) still observes the instrumentation hook completing\n // before the userland route handler runs.\n await ensureInstrumentationRegistered(absoluteProjectDir, this.distDir)\n }\n const manifests = getTracer().trace(\n RouteModuleSpan.loadManifests,\n { spanName: 'load route manifests' },\n () => this.loadManifests(srcPage, absoluteProjectDir)\n )\n const { routesManifest, previewProps, serverFilesManifest } = manifests\n\n const { basePath, i18n, rewrites } = routesManifest\n\n const routerServerContext = this.getRouterServerContext(req)\n const nextConfig =\n routerServerContext?.nextConfig || serverFilesManifest?.config\n\n // Injected in base-server.ts\n const protocol = req.headers['x-forwarded-proto']?.includes('https')\n ? 'https'\n : 'http'\n\n // When there are hostname and port we build an absolute URL\n if (!getRequestMeta(req, 'initURL')) {\n const initUrl = serverFilesManifest?.config.experimental.trustHostHeader\n ? `${protocol}://${req.headers.host || 'localhost'}${req.url}`\n : `${protocol}://${routerServerContext?.hostname || 'localhost'}${req.url}`\n\n addRequestMeta(req, 'initURL', initUrl)\n addRequestMeta(req, 'initProtocol', protocol)\n }\n\n if (basePath) {\n req.url = removePathPrefix(req.url || '/', basePath)\n }\n\n const parsedUrl = parseReqUrl(req.url || '/')\n addRequestMeta(req, 'initQuery', { ...parsedUrl?.query })\n // if we couldn't parse the URL we can't continue\n if (!parsedUrl) {\n return\n }\n let isNextDataRequest = false\n\n if (pathHasPrefix(parsedUrl.pathname || '/', '/_next/data')) {\n isNextDataRequest = true\n parsedUrl.pathname = normalizeDataPath(parsedUrl.pathname || '/')\n }\n this.normalizeUrl(req, parsedUrl)\n let originalPathname = parsedUrl.pathname || '/'\n const originalQuery = { ...parsedUrl.query }\n const pageIsDynamic = isDynamicRoute(srcPage)\n\n let localeResult: PathLocale | undefined\n let detectedLocale: string | undefined\n\n if (i18n) {\n localeResult = normalizeLocalePath(\n parsedUrl.pathname || '/',\n i18n.locales\n )\n\n if (localeResult.detectedLocale) {\n req.url = `${localeResult.pathname}${parsedUrl.search}`\n originalPathname = localeResult.pathname\n\n if (!detectedLocale) {\n detectedLocale = localeResult.detectedLocale\n }\n }\n }\n\n // Normalize the page path for route matching. The srcPage contains the\n // internal page path (e.g., /app/[slug]/page), but route matchers expect\n // the pathname format (e.g., /app/[slug]).\n const normalizedSrcPage = normalizeAppPath(srcPage)\n\n const serverUtils = getServerUtils({\n page: normalizedSrcPage,\n i18n,\n basePath,\n rewrites,\n pageIsDynamic,\n trailingSlash: process.env.__NEXT_TRAILING_SLASH as any as boolean,\n caseSensitive: Boolean(routesManifest.caseSensitive),\n })\n\n const domainLocale = detectDomainLocale(\n i18n?.domains,\n getHostname(parsedUrl, req.headers),\n detectedLocale\n )\n\n if (Boolean(domainLocale)) {\n addRequestMeta(req, 'isLocaleDomain', Boolean(domainLocale))\n }\n\n const defaultLocale =\n getRequestMeta(req, 'defaultLocale') ||\n domainLocale?.defaultLocale ||\n i18n?.defaultLocale\n\n // Ensure parsedUrl.pathname includes locale before processing\n // rewrites or they won't match correctly.\n if (defaultLocale && !detectedLocale) {\n parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname === '/' ? '' : parsedUrl.pathname}`\n }\n const locale =\n getRequestMeta(req, 'locale') || detectedLocale || defaultLocale\n\n // we apply rewrites against cloned URL so that we don't\n // modify the original with the rewrite destination\n const { rewriteParams, rewrittenParsedUrl } = serverUtils.handleRewrites(\n req,\n parsedUrl\n )\n const rewriteParamKeys = Object.keys(rewriteParams)\n Object.assign(parsedUrl.query, rewrittenParsedUrl.query)\n\n // after processing rewrites we want to remove locale\n // from parsedUrl pathname\n if (i18n) {\n parsedUrl.pathname = normalizeLocalePath(\n parsedUrl.pathname || '/',\n i18n.locales\n ).pathname\n\n rewrittenParsedUrl.pathname = normalizeLocalePath(\n rewrittenParsedUrl.pathname || '/',\n i18n.locales\n ).pathname\n }\n\n let params: Record | undefined =\n getRequestMeta(req, 'params')\n\n // attempt parsing from pathname\n if (!params && serverUtils.dynamicRouteMatcher) {\n const paramsMatch = serverUtils.dynamicRouteMatcher(\n normalizeDataPath(\n rewrittenParsedUrl?.pathname || parsedUrl.pathname || '/'\n )\n )\n const paramsResult = serverUtils.normalizeDynamicRouteParams(\n paramsMatch || {},\n true\n )\n\n if (paramsResult.hasValidParams) {\n params = paramsResult.params\n }\n }\n\n // Local \"next start\" expects the routing parsed query values\n // to not be present in the URL although when deployed proxies\n // will add query values from resolving the routes to pass to function.\n\n // TODO: do we want to change expectations for \"next start\"\n // to include these query values in the URL which affects asPath\n // but would match deployed behavior, e.g. a rewrite from middleware\n // that adds a query param would be in asPath as query but locally\n // it won't be in the asPath but still available in the query object\n const query = getRequestMeta(req, 'query') || {\n ...parsedUrl.query,\n }\n\n const routeParamKeys = new Set()\n const combinedParamKeys = []\n\n // We don't include rewriteParamKeys in the combinedParamKeys\n // for app router since the searchParams is populated from the\n // URL so we don't want to strip the rewrite params from the URL\n // so that searchParams can include them.\n if (\n this.definition.kind === RouteKind.PAGES ||\n this.definition.kind === RouteKind.PAGES_API\n ) {\n for (const key of [\n ...rewriteParamKeys,\n ...Object.keys(serverUtils.defaultRouteMatches || {}),\n ]) {\n // We only want to filter rewrite param keys from the URL\n // if they are matches from the URL e.g. the key/value matches\n // before and after applying the rewrites /:path for /hello and\n // { path: 'hello' } but not for { path: 'another' } and /hello\n // TODO: we should prefix rewrite param keys the same as we do\n // for dynamic routes so we can identify them properly\n const originalValue = Array.isArray(originalQuery[key])\n ? originalQuery[key].join('')\n : originalQuery[key]\n\n const queryValue = Array.isArray(query[key])\n ? query[key].join('')\n : query[key]\n\n if (!(key in originalQuery) || originalValue === queryValue) {\n combinedParamKeys.push(key)\n }\n }\n }\n\n serverUtils.normalizeCdnUrl(req, combinedParamKeys)\n // When Next is not hosted in a single process, upstream proxies will add query values for route params that were used to match the route.\n // Outside of that environment, there is no reason to do any normalization to honor those query values.\n if (!routerServerContext?.isWrappedByNextServer) {\n serverUtils.normalizeQueryParams(query, routeParamKeys)\n } else {\n serverUtils.filterInternalQuery(query, [])\n }\n serverUtils.filterInternalQuery(originalQuery, combinedParamKeys)\n\n if (pageIsDynamic) {\n const queryResult = serverUtils.normalizeDynamicRouteParams(query, true)\n\n const paramsResult = serverUtils.normalizeDynamicRouteParams(\n params || {},\n true\n )\n\n let paramsToInterpolate: ParsedUrlQuery\n\n if (\n // if both query and params are valid but one\n // provided more information and the query params\n // were nxtP prefixed rely on that one\n query &&\n params &&\n paramsResult.hasValidParams &&\n queryResult.hasValidParams &&\n routeParamKeys.size > 0 &&\n Object.keys(paramsResult.params).length <=\n Object.keys(queryResult.params).length\n ) {\n paramsToInterpolate = queryResult.params\n params = Object.assign(queryResult.params)\n } else {\n paramsToInterpolate =\n paramsResult.hasValidParams && params\n ? params\n : queryResult.hasValidParams\n ? query\n : {}\n }\n\n req.url = serverUtils.interpolateDynamicPath(\n req.url || '/',\n paramsToInterpolate\n )\n parsedUrl.pathname = serverUtils.interpolateDynamicPath(\n parsedUrl.pathname || '/',\n paramsToInterpolate\n )\n originalPathname = serverUtils.interpolateDynamicPath(\n originalPathname,\n paramsToInterpolate\n )\n\n // try pulling from query if valid\n if (!params) {\n if (queryResult.hasValidParams) {\n params = Object.assign({}, queryResult.params)\n\n // If we pulled from query remove it so it's\n // only in params\n for (const key in serverUtils.defaultRouteMatches) {\n delete query[key]\n }\n } else {\n // use final params from URL matching\n const paramsMatch = serverUtils.dynamicRouteMatcher?.(\n normalizeDataPath(\n localeResult?.pathname || parsedUrl.pathname || '/'\n )\n )\n // we don't normalize these as they are allowed to be\n // the literal slug matches here e.g. /blog/[slug]\n // actually being requested\n if (paramsMatch) {\n params = Object.assign({}, paramsMatch)\n }\n }\n }\n\n // When partial nxtP* params are provided (e.g. background\n // revalidation for intermediate PPR shells), both\n // normalizeDynamicRouteParams calls above fail because not all\n // route params are present. Merge the normalized query params\n // (from nxtP*) into the current params to override placeholders\n // with concrete values.\n if (\n params &&\n routeParamKeys.size > 0 &&\n !paramsResult.hasValidParams &&\n !queryResult.hasValidParams\n ) {\n for (const key of routeParamKeys) {\n if (query[key] !== undefined) {\n params[key] = query[key]\n }\n }\n addRequestMeta(req, 'resolvedRouteParamKeys', routeParamKeys)\n }\n }\n\n // Remove any normalized params from the query if they\n // weren't present as non-prefixed query key e.g.\n // ?search=1&nxtPsearch=hello we don't delete search\n for (const key of routeParamKeys) {\n if (!(key in originalQuery)) {\n delete query[key]\n // handle the case where there's collision and we\n // normalized nxtPid=123 -> id=123 but user also\n // sends id=456 as separate key\n } else if (\n originalQuery[key] &&\n query[key] &&\n originalQuery[key] !== query[key]\n ) {\n query[key] = originalQuery[key]\n }\n }\n\n const { isOnDemandRevalidate, revalidateOnlyGenerated } =\n checkIsOnDemandRevalidate(req.headers, previewProps)\n\n let isDraftMode = false\n let previewData: PreviewData\n\n // preview data relies on non-edge utils\n if (process.env.NEXT_RUNTIME !== 'edge' && res) {\n const { tryGetPreviewData } =\n require('../api-utils/node/try-get-preview-data') as typeof import('../api-utils/node/try-get-preview-data')\n\n previewData = tryGetPreviewData(\n req,\n res,\n previewProps,\n Boolean(multiZoneDraftMode)\n )\n isDraftMode = previewData !== false\n }\n\n if (!nextConfig) {\n throw new Error(\"Invariant: nextConfig couldn't be loaded\")\n }\n\n if (process.env.NEXT_RUNTIME !== 'edge') {\n const { installProcessErrorHandlers } =\n require('../node-environment-extensions/process-error-handlers') as typeof import('../node-environment-extensions/process-error-handlers')\n\n installProcessErrorHandlers(\n Boolean(\n nextConfig.experimental.removeUncaughtErrorAndRejectionListeners\n )\n )\n }\n\n let resolvedPathname = normalizedSrcPage\n if (isDynamicRoute(resolvedPathname) && params) {\n resolvedPathname = serverUtils.interpolateDynamicPath(\n resolvedPathname,\n params\n )\n }\n\n if (resolvedPathname === '/index') {\n resolvedPathname = '/'\n }\n\n if (\n res &&\n Boolean(req.headers['x-nextjs-data']) &&\n (!res.statusCode || res.statusCode === 200)\n ) {\n res.setHeader(\n 'x-nextjs-matched-path',\n removeTrailingSlash(`${locale ? `/${locale}` : ''}${normalizedSrcPage}`)\n )\n }\n const encodedResolvedPathname = resolvedPathname\n\n // we decode for cache key/manifest usage encoded is\n // for URL building\n try {\n resolvedPathname = decodePathParams(resolvedPathname)\n } catch (_) {}\n\n resolvedPathname = removeTrailingSlash(resolvedPathname)\n\n let deploymentId\n if (nextConfig.experimental?.runtimeServerDeploymentId) {\n if (!process.env.NEXT_DEPLOYMENT_ID) {\n throw new Error(\n 'process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled'\n )\n }\n deploymentId = process.env.NEXT_DEPLOYMENT_ID\n } else {\n deploymentId = nextConfig.deploymentId || ''\n }\n\n return {\n query,\n originalQuery,\n originalPathname,\n params,\n parsedUrl,\n locale,\n isNextDataRequest,\n locales: i18n?.locales,\n defaultLocale,\n isDraftMode,\n previewData,\n pageIsDynamic,\n resolvedPathname,\n encodedResolvedPathname,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n ...manifests,\n // loadManifest returns a readonly object, but we don't want to propagate that throughout the\n // whole codebase (for now)\n nextConfig:\n nextConfig satisfies DeepReadonly as NextConfigRuntime,\n routerServerContext,\n deploymentId,\n clientAssetToken: nextConfig.supportsImmutableAssets ? '' : deploymentId,\n }\n }\n\n public getResponseCache(req: IncomingMessage | BaseNextRequest) {\n if (!this.responseCache) {\n const minimalMode = getRequestMeta(req, 'minimalMode') ?? false\n this.responseCache = new ResponseCache({\n minimalMode,\n route: this.cacheOwner,\n })\n }\n return this.responseCache\n }\n\n public async handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind,\n isFallback,\n previewProps,\n prerenderManifest,\n isRoutePPREnabled,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil,\n isMinimalMode,\n }: {\n req: IncomingMessage | BaseNextRequest\n nextConfig: NextConfigRuntime\n cacheKey: string | null\n routeKind: RouteKind\n isFallback?: boolean\n previewProps: DeepReadonly<__ApiPreviewProps>\n prerenderManifest: DeepReadonly\n isRoutePPREnabled?: boolean\n isOnDemandRevalidate?: boolean\n revalidateOnlyGenerated?: boolean\n responseGenerator: ResponseGenerator\n waitUntil?: (prom: Promise) => void\n isMinimalMode: boolean\n }) {\n const responseCache = this.getResponseCache(req)\n const cacheEntry = await responseCache.get(cacheKey, responseGenerator, {\n routeKind,\n isFallback,\n isRoutePPREnabled,\n isOnDemandRevalidate,\n // A Next.js Segment Cache prefetch uses the `Next-Router-Prefetch`\n // header (surfaced as the `isPrefetchRSCRequest` request meta), not the\n // standard browser `purpose: prefetch` header. Recognize both so the\n // response cache treats segment prefetches as prefetches — most\n // importantly, so a prefetch that misses serves a fallback shell rather\n // than joining an in-flight background (concrete) revalidation.\n isPrefetch:\n req.headers.purpose === 'prefetch' ||\n getRequestMeta(req, 'isPrefetchRSCRequest') === true,\n // Use x-invocation-id header to scope the in-memory cache to a single\n // revalidation request in minimal mode.\n invocationID: req.headers['x-invocation-id'] as string | undefined,\n incrementalCache: await this.getIncrementalCache(\n req,\n nextConfig,\n previewProps,\n prerenderManifest,\n isMinimalMode\n ),\n waitUntil,\n })\n\n if (!cacheEntry) {\n if (\n cacheKey &&\n // revalidate only generated can bail even if cacheKey is provided\n !(isOnDemandRevalidate && revalidateOnlyGenerated)\n ) {\n // A cache entry might not be generated if a response is written\n // in `getInitialProps` or `getServerSideProps`, but those shouldn't\n // have a cache key. If we do have a cache key but we don't end up\n // with a cache entry, then either Next.js or the application has a\n // bug that needs fixing.\n throw new Error('invariant: cache entry required but not generated')\n }\n }\n return cacheEntry\n }\n}\n"],"names":["RouteModule","dynamicImportEsmDefault","id","then","mod","default","userland","_userland","constructor","definition","distDir","relativeProjectDir","cacheOwner","getResponseCacheOwner","isDev","process","env","__NEXT_DEV_SERVER","getRouterServerContext","req","routerServerGlobal","hostname","getRequestMeta","revalidate","render404","routerServerContext","RouterServerContextSymbol","undefined","getAssetPrefixForRender","configuredAssetPrefix","getAssetPrefix","normalizeUrl","_req","_parsedUrl","instrumentationOnRequestError","args","NEXT_RUNTIME","getEdgeInstrumentationModule","instrumentation","onRequestError","join","require","absoluteProjectDir","cwd","loadManifests","srcPage","projectDir","result","self","getEdgePreviewProps","maybeJSONParse","str","JSON","parse","buildId","__NEXT_BUILD_ID","buildManifest","__BUILD_MANIFEST","fallbackBuildManifest","reactLoadableManifest","__REACT_LOADABLE_MANIFEST","nextFontManifest","__NEXT_FONT_MANIFEST","prerenderManifest","routes","dynamicRoutes","notFoundRoutes","version","preview","previewProps","routesManifest","caseSensitive","Boolean","__NEXT_CASE_SENSITIVE_ROUTES","basePath","__NEXT_BASE_PATH","rewrites","__NEXT_REWRITES","beforeFiles","afterFiles","fallback","redirects","headers","onMatchHeaders","i18n","__NEXT_I18N_CONFIG","skipProxyUrlNormalize","__NEXT_NO_MIDDLEWARE_URL_NORMALIZE","serverFilesManifest","__SERVER_FILES_MANIFEST","clientReferenceManifest","__RSC_MANIFEST","serverActionsManifest","__RSC_SERVER_MANIFEST","subresourceIntegrityManifest","__SUBRESOURCE_INTEGRITY_MANIFEST","dynamicCssManifest","__DYNAMIC_CSS_MANIFEST","prefetchHintsManifest","interceptionRoutePatterns","__INTERCEPTION_ROUTE_REWRITE_MANIFEST","map","rewrite","RegExp","regex","Error","loadManifestFromRelativePath","evalManifestFromRelativePath","normalizedPagePath","normalizePagePath","router","kind","RouteKind","PAGES","PAGES_API","manifest","ROUTES_MANIFEST","shouldCache","PRERENDER_MANIFEST","PREVIEW_PROPS_MANIFEST","BUILD_MANIFEST","handleMissing","TURBOPACK","REACT_LOADABLE_MANIFEST","NEXT_FONT_MANIFEST","isStaticMetadataRoute","replace","CLIENT_REFERENCE_MANIFEST","SERVER_REFERENCE_MANIFEST","SUBRESOURCE_INTEGRITY_MANIFEST","SERVER_FILES_MANIFEST","BUILD_ID_FILE","skipParse","DYNAMIC_CSS_MANIFEST","PREFETCH_HINTS","filter","isInterceptionRouteRewrite","loadCustomCacheHandlers","nextConfig","cacheMaxMemorySize","cacheHandlers","initializeCacheHandlers","registerCustomCacheHandlers","handler","Object","entries","formatDynamicImportPath","setCacheHandler","interopDefault","getIncrementalCache","isMinimalMode","globalThis","__incrementalCache","CacheHandler","cacheHandler","incrementalCache","IncrementalCache","fs","nodeFs","dev","requestHeaders","allowedRevalidateHeaderKeys","experimental","minimalMode","serverDistDir","fetchCacheKeyPrefix","maxMemoryCacheSize","flushToDisk","isrFlushToDisk","CurCacheHandler","locales","err","errorContext","silenceLog","logErrorWithOriginalStack","console","error","path","url","method","getNextConfigEdge","config","deploymentId","runtimeServerDeploymentId","NEXT_DEPLOYMENT_ID","prepare","res","options","getTracer","trace","RouteModuleSpan","spanName","prepareImpl","multiZoneDraftMode","patchSetHeaderWithCookieSupport","relative","absoluteDistDir","ensureInstrumentationRegistered","manifests","protocol","includes","initUrl","trustHostHeader","host","addRequestMeta","removePathPrefix","parsedUrl","parseReqUrl","query","isNextDataRequest","pathHasPrefix","pathname","normalizeDataPath","originalPathname","originalQuery","pageIsDynamic","isDynamicRoute","localeResult","detectedLocale","normalizeLocalePath","search","normalizedSrcPage","normalizeAppPath","serverUtils","getServerUtils","page","trailingSlash","__NEXT_TRAILING_SLASH","domainLocale","detectDomainLocale","domains","getHostname","defaultLocale","locale","rewriteParams","rewrittenParsedUrl","handleRewrites","rewriteParamKeys","keys","assign","params","dynamicRouteMatcher","paramsMatch","paramsResult","normalizeDynamicRouteParams","hasValidParams","routeParamKeys","Set","combinedParamKeys","key","defaultRouteMatches","originalValue","Array","isArray","queryValue","push","normalizeCdnUrl","isWrappedByNextServer","normalizeQueryParams","filterInternalQuery","queryResult","paramsToInterpolate","size","length","interpolateDynamicPath","isOnDemandRevalidate","revalidateOnlyGenerated","checkIsOnDemandRevalidate","isDraftMode","previewData","tryGetPreviewData","installProcessErrorHandlers","removeUncaughtErrorAndRejectionListeners","resolvedPathname","statusCode","setHeader","removeTrailingSlash","encodedResolvedPathname","decodePathParams","_","clientAssetToken","supportsImmutableAssets","getResponseCache","responseCache","ResponseCache","route","handleResponse","cacheKey","routeKind","isFallback","isRoutePPREnabled","responseGenerator","waitUntil","cacheEntry","get","isPrefetch","purpose","invocationID"],"mappings":";;;;+BAsHsBA;;;eAAAA;;;QAtHf;2BA8BA;qBACqB;qCAIrB;uBACwB;kCACE;6BACF;oCACI;6BACP;0BACsC;mCAKhC;+BACJ;6BAKvB;gCACyC;mCACd;iCACI;kCACL;0BAK1B;gCACwB;2BACL;+BAInB;sEAG+C;0BACrB;qCAK1B;kCAC0B;qCACG;4CACO;wBACjB;4BACM;;;;;;AA4BhC,MAAMC,0BAA0B,CAACC,KAC/B,MAAM,CAAC,uBAAuB,GAAG,yBAAyB,GAAGA,IAAIC,IAAI,CACnE,CAACC,MAAQA,IAAIC,OAAO,IAAID;AAOrB,MAAeJ;IAUpB,IAAIM,WAAwB;QAC1B,OAAO,IAAI,CAACC,SAAS;IACvB;IAqBAC,YAAY,EACVF,QAAQ,EACRG,UAAU,EACVC,OAAO,EACPC,kBAAkB,EACO,CAAE;QAC3B,IAAI,CAACJ,SAAS,GAAGD;QACjB,IAAI,CA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AClB;QACF;QACA,OAAO4L;IACT;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/runtime-reacts.external.d.ts b/e-commerce/node_modules/next/dist/server/runtime-reacts.external.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a1319ec2280236776e96aaf03f0bae1a2753892 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/runtime-reacts.external.d.ts @@ -0,0 +1,4 @@ +export declare function registerClientReact(react: typeof import('react')): void; +export declare function getClientReact(): typeof import("react") | null; +export declare function registerServerReact(react: typeof import('react')): void; +export declare function getServerReact(): typeof import("react") | null; diff --git a/e-commerce/node_modules/next/dist/server/runtime-reacts.external.js b/e-commerce/node_modules/next/dist/server/runtime-reacts.external.js new file mode 100644 index 0000000000000000000000000000000000000000..6e99319a266ba684034ec8eb781ade772880a5c2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/runtime-reacts.external.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getClientReact: null, + getServerReact: null, + registerClientReact: null, + registerServerReact: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getClientReact: function() { + return getClientReact; + }, + getServerReact: function() { + return getServerReact; + }, + registerClientReact: function() { + return registerClientReact; + }, + registerServerReact: function() { + return registerServerReact; + } +}); +let ClientReact = null; +function registerClientReact(react) { + ClientReact = react; +} +function getClientReact() { + return ClientReact; +} +let ServerReact = null; +function registerServerReact(react) { + ServerReact = react; +} +function getServerReact() { + return ServerReact; +} + +//# sourceMappingURL=runtime-reacts.external.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/runtime-reacts.external.js.map b/e-commerce/node_modules/next/dist/server/runtime-reacts.external.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5fb38e06e6a6b8cd1458126911a4593e4e35dadf --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/runtime-reacts.external.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/runtime-reacts.external.ts"],"sourcesContent":["let ClientReact: typeof import('react') | null = null\nexport function registerClientReact(react: typeof import('react')) {\n ClientReact = react\n}\nexport function getClientReact() {\n return ClientReact\n}\n\nlet ServerReact: typeof import('react') | null = null\nexport function registerServerReact(react: typeof import('react')) {\n ServerReact = react\n}\nexport function getServerReact() {\n return ServerReact\n}\n"],"names":["getClientReact","getServerReact","registerClientReact","registerServerReact","ClientReact","react","ServerReact"],"mappings":";;;;;;;;;;;;;;;;;IAIgBA,cAAc;eAAdA;;IAQAC,cAAc;eAAdA;;IAXAC,mBAAmB;eAAnBA;;IAQAC,mBAAmB;eAAnBA;;;AAThB,IAAIC,cAA6C;AAC1C,SAASF,oBAAoBG,KAA6B;IAC/DD,cAAcC;AAChB;AACO,SAASL;IACd,OAAOI;AACT;AAEA,IAAIE,cAA6C;AAC1C,SAASH,oBAAoBE,KAA6B;IAC/DC,cAAcD;AAChB;AACO,SAASJ;IACd,OAAOK;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/send-payload.d.ts b/e-commerce/node_modules/next/dist/server/send-payload.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4b7a8df8b64beab3d59ff2dc4ee47151f7662f4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/send-payload.d.ts @@ -0,0 +1,12 @@ +import type { IncomingMessage, ServerResponse } from 'http'; +import type RenderResult from './render-result'; +import type { CacheControl } from './lib/cache-control'; +export declare function sendEtagResponse(req: IncomingMessage, res: ServerResponse, etag: string | undefined): boolean; +export declare function sendRenderResult({ req, res, result, generateEtags, poweredByHeader, cacheControl, }: { + req: IncomingMessage; + res: ServerResponse; + result: RenderResult; + generateEtags: boolean; + poweredByHeader: boolean; + cacheControl: CacheControl | undefined; +}): Promise; diff --git a/e-commerce/node_modules/next/dist/server/send-payload.js b/e-commerce/node_modules/next/dist/server/send-payload.js new file mode 100644 index 0000000000000000000000000000000000000000..dc844c8444ec0d5c78f8721db815fb176bb9eb8d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/send-payload.js @@ -0,0 +1,88 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + sendEtagResponse: null, + sendRenderResult: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + sendEtagResponse: function() { + return sendEtagResponse; + }, + sendRenderResult: function() { + return sendRenderResult; + } +}); +const _utils = require("../shared/lib/utils"); +const _etag = require("./lib/etag"); +const _fresh = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/fresh")); +const _cachecontrol = require("./lib/cache-control"); +const _constants = require("../lib/constants"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function sendEtagResponse(req, res, etag) { + if (etag) { + /** + * The server generating a 304 response MUST generate any of the + * following header fields that would have been sent in a 200 (OK) + * response to the same request: Cache-Control, Content-Location, Date, + * ETag, Expires, and Vary. https://tools.ietf.org/html/rfc7232#section-4.1 + */ res.setHeader('ETag', etag); + } + if ((0, _fresh.default)(req.headers, { + etag + })) { + res.statusCode = 304; + res.end(); + return true; + } + return false; +} +async function sendRenderResult({ req, res, result, generateEtags, poweredByHeader, cacheControl }) { + if ((0, _utils.isResSent)(res)) { + return; + } + if (poweredByHeader && result.contentType === _constants.HTML_CONTENT_TYPE_HEADER) { + res.setHeader('X-Powered-By', 'Next.js'); + } + // If cache control is already set on the response we don't + // override it to allow users to customize it via next.config + if (cacheControl && !res.getHeader('Cache-Control')) { + res.setHeader('Cache-Control', (0, _cachecontrol.getCacheControlHeader)(cacheControl)); + } + const payload = result.isDynamic ? null : result.toUnchunkedString(); + if (generateEtags && payload !== null) { + const etag = (0, _etag.generateETag)(payload); + if (sendEtagResponse(req, res, etag)) { + return; + } + } + if (!res.getHeader('Content-Type') && result.contentType) { + res.setHeader('Content-Type', result.contentType); + } + if (payload) { + res.setHeader('Content-Length', Buffer.byteLength(payload)); + } + if (req.method === 'HEAD') { + res.end(null); + return; + } + if (payload !== null) { + res.end(payload); + return; + } + // Pipe the render result to the response after we get a writer for it. + await result.pipeToNodeResponse(res); +} + +//# sourceMappingURL=send-payload.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/send-payload.js.map b/e-commerce/node_modules/next/dist/server/send-payload.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f17bf71ed1e2aa369fe7c97489c6b352d76cdff4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/send-payload.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/send-payload.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport type RenderResult from './render-result'\nimport type { CacheControl } from './lib/cache-control'\n\nimport { isResSent } from '../shared/lib/utils'\nimport { generateETag } from './lib/etag'\nimport fresh from 'next/dist/compiled/fresh'\nimport { getCacheControlHeader } from './lib/cache-control'\nimport { HTML_CONTENT_TYPE_HEADER } from '../lib/constants'\n\nexport function sendEtagResponse(\n req: IncomingMessage,\n res: ServerResponse,\n etag: string | undefined\n): boolean {\n if (etag) {\n /**\n * The server generating a 304 response MUST generate any of the\n * following header fields that would have been sent in a 200 (OK)\n * response to the same request: Cache-Control, Content-Location, Date,\n * ETag, Expires, and Vary. https://tools.ietf.org/html/rfc7232#section-4.1\n */\n res.setHeader('ETag', etag)\n }\n\n if (fresh(req.headers, { etag })) {\n res.statusCode = 304\n res.end()\n return true\n }\n\n return false\n}\n\nexport async function sendRenderResult({\n req,\n res,\n result,\n generateEtags,\n poweredByHeader,\n cacheControl,\n}: {\n req: IncomingMessage\n res: ServerResponse\n result: RenderResult\n generateEtags: boolean\n poweredByHeader: boolean\n cacheControl: CacheControl | undefined\n}): Promise {\n if (isResSent(res)) {\n return\n }\n\n if (poweredByHeader && result.contentType === HTML_CONTENT_TYPE_HEADER) {\n res.setHeader('X-Powered-By', 'Next.js')\n }\n\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheControl && !res.getHeader('Cache-Control')) {\n res.setHeader('Cache-Control', getCacheControlHeader(cacheControl))\n }\n\n const payload = result.isDynamic ? null : result.toUnchunkedString()\n\n if (generateEtags && payload !== null) {\n const etag = generateETag(payload)\n if (sendEtagResponse(req, res, etag)) {\n return\n }\n }\n\n if (!res.getHeader('Content-Type') && result.contentType) {\n res.setHeader('Content-Type', result.contentType)\n }\n\n if (payload) {\n res.setHeader('Content-Length', Buffer.byteLength(payload))\n }\n\n if (req.method === 'HEAD') {\n res.end(null)\n return\n }\n\n if (payload !== null) {\n res.end(payload)\n return\n }\n\n // Pipe the render result to the response after we get a writer for it.\n await result.pipeToNodeResponse(res)\n}\n"],"names":["sendEtagResponse","sendRenderResult","req","res","etag","setHeader","fresh","headers","statusCode","end","result","generateEtags","poweredByHeader","cacheControl","isResSent","contentType","HTML_CONTENT_TYPE_HEADER","getHeader","getCacheControlHeader","payload","isDynamic","toUnchunkedString","generateETag","Buffer","byteLength","method","pipeToNodeResponse"],"mappings":";;;;;;;;;;;;;;;IAUgBA,gBAAgB;eAAhBA;;IAwBMC,gBAAgB;eAAhBA;;;uBA9BI;sBACG;8DACX;8BACoB;2BACG;;;;;;AAElC,SAASD,iBACdE,GAAoB,EACpBC,GAAmB,EACnBC,IAAwB;IAExB,IAAIA,MAAM;QACR;;;;;KAKC,GACDD,IAAIE,SAAS,CAAC,QAAQD;IACxB;IAEA,IAAIE,IAAAA,cAAK,EAACJ,IAAIK,OAAO,EAAE;QAAEH;IAAK,IAAI;QAChCD,IAAIK,UAAU,GAAG;QACjBL,IAAIM,GAAG;QACP,OAAO;IACT;IAEA,OAAO;AACT;AAEO,eAAeR,iBAAiB,EACrCC,GAAG,EACHC,GAAG,EACHO,MAAM,EACNC,aAAa,EACbC,eAAe,EACfC,YAAY,EAQb;IACC,IAAIC,IAAAA,gBAAS,EAACX,MAAM;QAClB;IACF;IAEA,IAAIS,mBAAmBF,OAAOK,WAAW,KAAKC,mCAAwB,EAAE;QACtEb,IAAIE,SAAS,CAAC,gBAAgB;IAChC;IAEA,2DAA2D;IAC3D,6DAA6D;IAC7D,IAAIQ,gBAAgB,CAACV,IAAIc,SAAS,CAAC,kBAAkB;QACnDd,IAAIE,SAAS,CAAC,iBAAiBa,IAAAA,mCAAqB,EAACL;IACvD;IAEA,MAAMM,UAAUT,OAAOU,SAAS,GAAG,OAAOV,OAAOW,iBAAiB;IAElE,IAAIV,iBAAiBQ,YAAY,MAAM;QACrC,MAAMf,OAAOkB,IAAAA,kBAAY,EAACH;QAC1B,IAAInB,iBAAiBE,KAAKC,KAAKC,OAAO;YACpC;QACF;IACF;IAEA,IAAI,CAACD,IAAIc,SAAS,CAAC,mBAAmBP,OAAOK,WAAW,EAAE;QACxDZ,IAAIE,SAAS,CAAC,gBAAgBK,OAAOK,WAAW;IAClD;IAEA,IAAII,SAAS;QACXhB,IAAIE,SAAS,CAAC,kBAAkBkB,OAAOC,UAAU,CAACL;IACpD;IAEA,IAAIjB,IAAIuB,MAAM,KAAK,QAAQ;QACzBtB,IAAIM,GAAG,CAAC;QACR;IACF;IAEA,IAAIU,YAAY,MAAM;QACpBhB,IAAIM,GAAG,CAACU;QACR;IACF;IAEA,uEAAuE;IACvE,MAAMT,OAAOgB,kBAAkB,CAACvB;AAClC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/send-response.d.ts b/e-commerce/node_modules/next/dist/server/send-response.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e48d5094557cc40c85dff74f1a64cb8b63d372e1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/send-response.d.ts @@ -0,0 +1,9 @@ +import type { BaseNextRequest, BaseNextResponse } from './base-http'; +/** + * Sends the response on the underlying next response object. + * + * @param req the underlying request object + * @param res the underlying response object + * @param response the response to send + */ +export declare function sendResponse(req: BaseNextRequest, res: BaseNextResponse, response: Response, waitUntil?: Promise): Promise; diff --git a/e-commerce/node_modules/next/dist/server/send-response.js b/e-commerce/node_modules/next/dist/server/send-response.js new file mode 100644 index 0000000000000000000000000000000000000000..ad737fa8220040b606263a126371741117224c41 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/send-response.js @@ -0,0 +1,70 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "sendResponse", { + enumerable: true, + get: function() { + return sendResponse; + } +}); +const _helpers = require("./base-http/helpers"); +const _pipereadable = require("./pipe-readable"); +const _utils = require("./web/utils"); +async function sendResponse(req, res, response, waitUntil) { + if (// The type check here ensures that `req` is correctly typed, and the + // environment variable check provides dead code elimination. + process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextResponse)(res)) { + var // Copy over the response headers. + _response_headers; + // Copy over the response status. + res.statusCode = response.status; + res.statusMessage = response.statusText; + // TODO: this is not spec-compliant behavior and we should not restrict + // headers that are allowed to appear many times. + // + // See: + // https://github.com/vercel/next.js/pull/70127 + const headersWithMultipleValuesAllowed = [ + // can add more headers to this list if needed + 'set-cookie', + 'www-authenticate', + 'proxy-authenticate', + 'vary' + ]; + (_response_headers = response.headers) == null ? void 0 : _response_headers.forEach((value, name)=>{ + // `x-middleware-set-cookie` is an internal header not needed for the response + if (name.toLowerCase() === 'x-middleware-set-cookie') { + return; + } + // The append handling is special cased for `set-cookie`. + if (name.toLowerCase() === 'set-cookie') { + // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici + for (const cookie of (0, _utils.splitCookiesString)(value)){ + res.appendHeader(name, cookie); + } + } else { + // only append the header if it is either not present in the outbound response + // or if the header supports multiple values + const isHeaderPresent = typeof res.getHeader(name) !== 'undefined'; + if (headersWithMultipleValuesAllowed.includes(name.toLowerCase()) || !isHeaderPresent) { + res.appendHeader(name, value); + } + } + }); + /** + * The response can't be directly piped to the underlying response. The + * following is duplicated from the edge runtime handler. + * + * See packages/next/server/next-server.ts + */ const { originalResponse } = res; + // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD + if (response.body && req.method !== 'HEAD') { + await (0, _pipereadable.pipeToNodeResponse)(response.body, originalResponse, waitUntil); + } else { + originalResponse.end(); + } + } +} + +//# sourceMappingURL=send-response.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/send-response.js.map b/e-commerce/node_modules/next/dist/server/send-response.js.map new file mode 100644 index 0000000000000000000000000000000000000000..230a8decd30c84bee6837ea4f072575282edd3c0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/send-response.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/send-response.ts"],"sourcesContent":["import type { BaseNextRequest, BaseNextResponse } from './base-http'\nimport { isNodeNextResponse } from './base-http/helpers'\n\nimport { pipeToNodeResponse } from './pipe-readable'\nimport { splitCookiesString } from './web/utils'\n\n/**\n * Sends the response on the underlying next response object.\n *\n * @param req the underlying request object\n * @param res the underlying response object\n * @param response the response to send\n */\nexport async function sendResponse(\n req: BaseNextRequest,\n res: BaseNextResponse,\n response: Response,\n waitUntil?: Promise\n): Promise {\n if (\n // The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' &&\n isNodeNextResponse(res)\n ) {\n // Copy over the response status.\n res.statusCode = response.status\n res.statusMessage = response.statusText\n\n // TODO: this is not spec-compliant behavior and we should not restrict\n // headers that are allowed to appear many times.\n //\n // See:\n // https://github.com/vercel/next.js/pull/70127\n const headersWithMultipleValuesAllowed = [\n // can add more headers to this list if needed\n 'set-cookie',\n 'www-authenticate',\n 'proxy-authenticate',\n 'vary',\n ]\n\n // Copy over the response headers.\n response.headers?.forEach((value, name) => {\n // `x-middleware-set-cookie` is an internal header not needed for the response\n if (name.toLowerCase() === 'x-middleware-set-cookie') {\n return\n }\n\n // The append handling is special cased for `set-cookie`.\n if (name.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of splitCookiesString(value)) {\n res.appendHeader(name, cookie)\n }\n } else {\n // only append the header if it is either not present in the outbound response\n // or if the header supports multiple values\n const isHeaderPresent = typeof res.getHeader(name) !== 'undefined'\n if (\n headersWithMultipleValuesAllowed.includes(name.toLowerCase()) ||\n !isHeaderPresent\n ) {\n res.appendHeader(name, value)\n }\n }\n })\n\n /**\n * The response can't be directly piped to the underlying response. The\n * following is duplicated from the edge runtime handler.\n *\n * See packages/next/server/next-server.ts\n */\n\n const { originalResponse } = res\n\n // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD\n if (response.body && req.method !== 'HEAD') {\n await pipeToNodeResponse(response.body, originalResponse, waitUntil)\n } else {\n originalResponse.end()\n }\n }\n}\n"],"names":["sendResponse","req","res","response","waitUntil","process","env","NEXT_RUNTIME","isNodeNextResponse","statusCode","status","statusMessage","statusText","headersWithMultipleValuesAllowed","headers","forEach","value","name","toLowerCase","cookie","splitCookiesString","appendHeader","isHeaderPresent","getHeader","includes","originalResponse","body","method","pipeToNodeResponse","end"],"mappings":";;;;+BAasBA;;;eAAAA;;;yBAZa;8BAEA;uBACA;AAS5B,eAAeA,aACpBC,GAAoB,EACpBC,GAAqB,EACrBC,QAAkB,EAClBC,SAA4B;IAE5B,IACE,qEAAqE;IACrE,6DAA6D;IAC7DC,QAAQC,GAAG,CAACC,YAAY,KAAK,UAC7BC,IAAAA,2BAAkB,EAACN,MACnB;YAkBA,kCAAkC;QAClCC;QAlBA,iCAAiC;QACjCD,IAAIO,UAAU,GAAGN,SAASO,MAAM;QAChCR,IAAIS,aAAa,GAAGR,SAASS,UAAU;QAEvC,uEAAuE;QACvE,iDAAiD;QACjD,EAAE;QACF,OAAO;QACP,+CAA+C;QAC/C,MAAMC,mCAAmC;YACvC,8CAA8C;YAC9C;YACA;YACA;YACA;SACD;SAGDV,oBAAAA,SAASW,OAAO,qBAAhBX,kBAAkBY,OAAO,CAAC,CAACC,OAAOC;YAChC,8EAA8E;YAC9E,IAAIA,KAAKC,WAAW,OAAO,2BAA2B;gBACpD;YACF;YAEA,yDAAyD;YACzD,IAAID,KAAKC,WAAW,OAAO,cAAc;gBACvC,qFAAqF;gBACrF,KAAK,MAAMC,UAAUC,IAAAA,yBAAkB,EAACJ,OAAQ;oBAC9Cd,IAAImB,YAAY,CAACJ,MAAME;gBACzB;YACF,OAAO;gBACL,8EAA8E;gBAC9E,4CAA4C;gBAC5C,MAAMG,kBAAkB,OAAOpB,IAAIqB,SAAS,CAACN,UAAU;gBACvD,IACEJ,iCAAiCW,QAAQ,CAACP,KAAKC,WAAW,OAC1D,CAACI,iBACD;oBACApB,IAAImB,YAAY,CAACJ,MAAMD;gBACzB;YACF;QACF;QAEA;;;;;KAKC,GAED,MAAM,EAAES,gBAAgB,EAAE,GAAGvB;QAE7B,qGAAqG;QACrG,IAAIC,SAASuB,IAAI,IAAIzB,IAAI0B,MAAM,KAAK,QAAQ;YAC1C,MAAMC,IAAAA,gCAAkB,EAACzB,SAASuB,IAAI,EAAED,kBAAkBrB;QAC5D,OAAO;YACLqB,iBAAiBI,GAAG;QACtB;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/serve-static.d.ts b/e-commerce/node_modules/next/dist/server/serve-static.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b224990aa37d66e6c7f92ddd07953a9dde85e38 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/serve-static.d.ts @@ -0,0 +1,5 @@ +import type { IncomingMessage, ServerResponse } from 'http'; +import send from 'next/dist/compiled/send'; +export declare function serveStatic(req: IncomingMessage, res: ServerResponse, path: string, opts?: Parameters[2]): Promise; +export declare const getContentType: (extWithoutDot: string) => string | null; +export declare const getExtension: (contentType: string) => string | null; diff --git a/e-commerce/node_modules/next/dist/server/serve-static.js b/e-commerce/node_modules/next/dist/server/serve-static.js new file mode 100644 index 0000000000000000000000000000000000000000..6ddb9fd8a8e94e0289c7d3cef6f8956b9d989779 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/serve-static.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getContentType: null, + getExtension: null, + serveStatic: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getContentType: function() { + return getContentType; + }, + getExtension: function() { + return getExtension; + }, + serveStatic: function() { + return serveStatic; + } +}); +const _send = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/send")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +// TODO: Remove this once "send" has updated the "mime", or next.js use custom version of "mime" +// Although "mime" has already add avif in version 2.4.7, "send" is still using mime@1.6.0 +_send.default.mime.define({ + 'image/avif': [ + 'avif' + ], + 'image/x-icns': [ + 'icns' + ], + 'image/jxl': [ + 'jxl' + ], + 'image/heic': [ + 'heic' + ] +}); +function serveStatic(req, res, path, opts) { + return new Promise((resolve, reject)=>{ + (0, _send.default)(req, path, opts).on('directory', ()=>{ + // We don't allow directories to be read. + const err = new Error('No directory access'); + err.code = 'ENOENT'; + reject(err); + }).on('error', reject).pipe(res).on('finish', resolve); + }); +} +const getContentType = 'getType' in _send.default.mime ? (extWithoutDot)=>_send.default.mime.getType(extWithoutDot) : (extWithoutDot)=>_send.default.mime.lookup(extWithoutDot); +const getExtension = 'getExtension' in _send.default.mime ? (contentType)=>_send.default.mime.getExtension(contentType) : (contentType)=>_send.default.mime.extension(contentType); + +//# sourceMappingURL=serve-static.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/serve-static.js.map b/e-commerce/node_modules/next/dist/server/serve-static.js.map new file mode 100644 index 0000000000000000000000000000000000000000..82387ab3dd835ac064e9ade0b179c2d475a9f4be --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/serve-static.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/serve-static.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport send from 'next/dist/compiled/send'\n\n// TODO: Remove this once \"send\" has updated the \"mime\", or next.js use custom version of \"mime\"\n// Although \"mime\" has already add avif in version 2.4.7, \"send\" is still using mime@1.6.0\nsend.mime.define({\n 'image/avif': ['avif'],\n 'image/x-icns': ['icns'],\n 'image/jxl': ['jxl'],\n 'image/heic': ['heic'],\n})\n\nexport function serveStatic(\n req: IncomingMessage,\n res: ServerResponse,\n path: string,\n opts?: Parameters[2]\n): Promise {\n return new Promise((resolve, reject) => {\n send(req, path, opts)\n .on('directory', () => {\n // We don't allow directories to be read.\n const err: any = new Error('No directory access')\n err.code = 'ENOENT'\n reject(err)\n })\n .on('error', reject)\n .pipe(res)\n .on('finish', resolve)\n })\n}\n\nexport const getContentType: (extWithoutDot: string) => string | null =\n 'getType' in send.mime\n ? (extWithoutDot: string) => send.mime.getType(extWithoutDot)\n : (extWithoutDot: string) => (send.mime as any).lookup(extWithoutDot)\n\nexport const getExtension: (contentType: string) => string | null =\n 'getExtension' in send.mime\n ? (contentType: string) => send.mime.getExtension(contentType)\n : (contentType: string) => (send.mime as any).extension(contentType)\n"],"names":["getContentType","getExtension","serveStatic","send","mime","define","req","res","path","opts","Promise","resolve","reject","on","err","Error","code","pipe","extWithoutDot","getType","lookup","contentType","extension"],"mappings":";;;;;;;;;;;;;;;;IAgCaA,cAAc;eAAdA;;IAKAC,YAAY;eAAZA;;IAzBGC,WAAW;eAAXA;;;6DAXC;;;;;;AAEjB,gGAAgG;AAChG,0FAA0F;AAC1FC,aAAI,CAACC,IAAI,CAACC,MAAM,CAAC;IACf,cAAc;QAAC;KAAO;IACtB,gBAAgB;QAAC;KAAO;IACxB,aAAa;QAAC;KAAM;IACpB,cAAc;QAAC;KAAO;AACxB;AAEO,SAASH,YACdI,GAAoB,EACpBC,GAAmB,EACnBC,IAAY,EACZC,IAAiC;IAEjC,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3BT,IAAAA,aAAI,EAACG,KAAKE,MAAMC,MACbI,EAAE,CAAC,aAAa;YACf,yCAAyC;YACzC,MAAMC,MAAW,IAAIC,MAAM;YAC3BD,IAAIE,IAAI,GAAG;YACXJ,OAAOE;QACT,GACCD,EAAE,CAAC,SAASD,QACZK,IAAI,CAACV,KACLM,EAAE,CAAC,UAAUF;IAClB;AACF;AAEO,MAAMX,iBACX,aAAaG,aAAI,CAACC,IAAI,GAClB,CAACc,gBAA0Bf,aAAI,CAACC,IAAI,CAACe,OAAO,CAACD,iBAC7C,CAACA,gBAA0B,AAACf,aAAI,CAACC,IAAI,CAASgB,MAAM,CAACF;AAEpD,MAAMjB,eACX,kBAAkBE,aAAI,CAACC,IAAI,GACvB,CAACiB,cAAwBlB,aAAI,CAACC,IAAI,CAACH,YAAY,CAACoB,eAChD,CAACA,cAAwB,AAAClB,aAAI,CAACC,IAAI,CAASkB,SAAS,CAACD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/server-route-utils.d.ts b/e-commerce/node_modules/next/dist/server/server-route-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..635b2b4a45b14f02fa696518e2b11bc541019dfd --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/server-route-utils.d.ts @@ -0,0 +1,3 @@ +import type { BaseNextRequest } from './base-http'; +import type { ParsedUrlQuery } from 'querystring'; +export declare const stringifyQuery: (req: BaseNextRequest, query: ParsedUrlQuery) => string; diff --git a/e-commerce/node_modules/next/dist/server/server-route-utils.js b/e-commerce/node_modules/next/dist/server/server-route-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..b1a2a2bd55e3d2092bdc86265b2ee2d2d4572e27 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/server-route-utils.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "stringifyQuery", { + enumerable: true, + get: function() { + return stringifyQuery; + } +}); +const _requestmeta = require("./request-meta"); +const _querystring = require("querystring"); +const stringifyQuery = (req, query)=>{ + const initialQuery = (0, _requestmeta.getRequestMeta)(req, 'initQuery') || {}; + const initialQueryValues = Object.values(initialQuery); + return (0, _querystring.stringify)(query, undefined, undefined, { + encodeURIComponent (value) { + if (value in initialQuery || initialQueryValues.some((initialQueryVal)=>{ + // `value` always refers to a query value, even if it's nested in an array + return Array.isArray(initialQueryVal) ? initialQueryVal.includes(value) : initialQueryVal === value; + })) { + // Encode keys and values from initial query + return encodeURIComponent(value); + } + return value; + } + }); +}; + +//# sourceMappingURL=server-route-utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/server-route-utils.js.map b/e-commerce/node_modules/next/dist/server/server-route-utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..256246c4d7c27159e4ec855aab9d4192d45ff1a5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/server-route-utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/server-route-utils.ts"],"sourcesContent":["import type { BaseNextRequest } from './base-http'\nimport type { ParsedUrlQuery } from 'querystring'\n\nimport { getRequestMeta } from './request-meta'\nimport { stringify as stringifyQs } from 'querystring'\n\n// since initial query values are decoded by querystring.parse\n// we need to re-encode them here but still allow passing through\n// values from rewrites/redirects\nexport const stringifyQuery = (req: BaseNextRequest, query: ParsedUrlQuery) => {\n const initialQuery = getRequestMeta(req, 'initQuery') || {}\n const initialQueryValues = Object.values(initialQuery)\n\n return stringifyQs(query, undefined, undefined, {\n encodeURIComponent(value) {\n if (\n value in initialQuery ||\n initialQueryValues.some((initialQueryVal) => {\n // `value` always refers to a query value, even if it's nested in an array\n return Array.isArray(initialQueryVal)\n ? initialQueryVal.includes(value)\n : initialQueryVal === value\n })\n ) {\n // Encode keys and values from initial query\n return encodeURIComponent(value)\n }\n\n return value\n },\n })\n}\n"],"names":["stringifyQuery","req","query","initialQuery","getRequestMeta","initialQueryValues","Object","values","stringifyQs","undefined","encodeURIComponent","value","some","initialQueryVal","Array","isArray","includes"],"mappings":";;;;+BASaA;;;eAAAA;;;6BANkB;6BACU;AAKlC,MAAMA,iBAAiB,CAACC,KAAsBC;IACnD,MAAMC,eAAeC,IAAAA,2BAAc,EAACH,KAAK,gBAAgB,CAAC;IAC1D,MAAMI,qBAAqBC,OAAOC,MAAM,CAACJ;IAEzC,OAAOK,IAAAA,sBAAW,EAACN,OAAOO,WAAWA,WAAW;QAC9CC,oBAAmBC,KAAK;YACtB,IACEA,SAASR,gBACTE,mBAAmBO,IAAI,CAAC,CAACC;gBACvB,0EAA0E;gBAC1E,OAAOC,MAAMC,OAAO,CAACF,mBACjBA,gBAAgBG,QAAQ,CAACL,SACzBE,oBAAoBF;YAC1B,IACA;gBACA,4CAA4C;gBAC5C,OAAOD,mBAAmBC;YAC5B;YAEA,OAAOA;QACT;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/server-utils.d.ts b/e-commerce/node_modules/next/dist/server/server-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..164a5df7383b3981990b8af28e11b0976ad4864c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/server-utils.d.ts @@ -0,0 +1,64 @@ +import type { Rewrite } from '../lib/load-custom-routes'; +import type { RouteMatchFn } from '../shared/lib/router/utils/route-matcher'; +import type { NextConfig } from './config'; +import type { BaseNextRequest } from './base-http'; +import type { NextUrlWithParsedQuery } from './request-meta'; +import type { ParsedUrlQuery } from 'querystring'; +import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'; +import type { IncomingHttpHeaders, IncomingMessage } from 'http'; +import type { DeepReadonly } from '../shared/lib/deep-readonly'; +export declare function normalizeCdnUrl(req: BaseNextRequest | IncomingMessage, paramKeys: string[]): string | undefined; +export declare function interpolateDynamicPath(pathname: string, params: ParsedUrlQuery, defaultRouteRegex?: ReturnType | undefined): string; +export declare function normalizeDynamicRouteParams(query: ParsedUrlQuery, defaultRouteRegex: ReturnType, defaultRouteMatches: ParsedUrlQuery, ignoreMissingOptional: boolean): { + params: ParsedUrlQuery; + hasValidParams: boolean; +}; +export declare function getServerUtils({ page, i18n, basePath, rewrites, pageIsDynamic, trailingSlash, caseSensitive, }: { + page: string; + i18n?: NextConfig['i18n']; + basePath: string; + rewrites: DeepReadonly<{ + fallback?: ReadonlyArray; + afterFiles?: ReadonlyArray; + beforeFiles?: ReadonlyArray; + }>; + pageIsDynamic: boolean; + trailingSlash?: boolean; + caseSensitive: boolean; +}): { + handleRewrites: (req: BaseNextRequest | IncomingMessage, parsedUrl: DeepReadonly) => { + rewriteParams: Record; + rewrittenParsedUrl: NextUrlWithParsedQuery; + }; + defaultRouteRegex: { + namedRegex: string; + routeKeys: { + [named: string]: string; + }; + pathToRegexpPattern: string; + reference: import("../shared/lib/router/utils/route-regex").RegexReference; + groups: { + [groupName: string]: import("../shared/lib/router/utils/route-regex").Group; + }; + re: RegExp; + } | undefined; + dynamicRouteMatcher: RouteMatchFn | undefined; + defaultRouteMatches: ParsedUrlQuery | undefined; + normalizeQueryParams: (query: Record, routeParamKeys: Set) => void; + getParamsFromRouteMatches: (routeMatchesHeader: string) => import("./request/params").Params | null; + /** + * Normalize dynamic route params. + * + * @param query - The query params to normalize. + * @param ignoreMissingOptional - Whether to ignore missing optional params. + * @returns The normalized params and whether they are valid. + */ + normalizeDynamicRouteParams: (query: ParsedUrlQuery, ignoreMissingOptional: boolean) => { + params: ParsedUrlQuery; + hasValidParams: boolean; + }; + normalizeCdnUrl: (req: BaseNextRequest | IncomingMessage, paramKeys: string[]) => string | undefined; + interpolateDynamicPath: (pathname: string, params: Record) => string; + filterInternalQuery: (query: ParsedUrlQuery, paramKeys: string[]) => void; +}; +export declare function getPreviouslyRevalidatedTags(headers: IncomingHttpHeaders, previewModeId: string | undefined): string[]; diff --git a/e-commerce/node_modules/next/dist/server/server-utils.js b/e-commerce/node_modules/next/dist/server/server-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..f70a8a84b08dd70320e274df7f3bee32d7529b9b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/server-utils.js @@ -0,0 +1,340 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getPreviouslyRevalidatedTags: null, + getServerUtils: null, + interpolateDynamicPath: null, + normalizeCdnUrl: null, + normalizeDynamicRouteParams: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getPreviouslyRevalidatedTags: function() { + return getPreviouslyRevalidatedTags; + }, + getServerUtils: function() { + return getServerUtils; + }, + interpolateDynamicPath: function() { + return interpolateDynamicPath; + }, + normalizeCdnUrl: function() { + return normalizeCdnUrl; + }, + normalizeDynamicRouteParams: function() { + return normalizeDynamicRouteParams; + } +}); +const _normalizelocalepath = require("../shared/lib/i18n/normalize-locale-path"); +const _pathmatch = require("../shared/lib/router/utils/path-match"); +const _routeregex = require("../shared/lib/router/utils/route-regex"); +const _routematcher = require("../shared/lib/router/utils/route-matcher"); +const _preparedestination = require("../shared/lib/router/utils/prepare-destination"); +const _removetrailingslash = require("../shared/lib/router/utils/remove-trailing-slash"); +const _apppaths = require("../shared/lib/router/utils/app-paths"); +const _constants = require("../lib/constants"); +const _utils = require("./web/utils"); +const _decodequerypathparameter = require("./lib/decode-query-path-parameter"); +const _url = require("../lib/url"); +const _formaturl = require("../shared/lib/router/utils/format-url"); +function filterInternalQuery(query, paramKeys) { + // this is used to pass query information in rewrites + // but should not be exposed in final query + delete query['nextInternalLocale']; + for(const key in query){ + const isNextQueryPrefix = key !== _constants.NEXT_QUERY_PARAM_PREFIX && key.startsWith(_constants.NEXT_QUERY_PARAM_PREFIX); + const isNextInterceptionMarkerPrefix = key !== _constants.NEXT_INTERCEPTION_MARKER_PREFIX && key.startsWith(_constants.NEXT_INTERCEPTION_MARKER_PREFIX); + if (isNextQueryPrefix || isNextInterceptionMarkerPrefix || paramKeys.includes(key)) { + delete query[key]; + } + } +} +function normalizeCdnUrl(req, paramKeys) { + // make sure to normalize req.url from CDNs to strip dynamic and rewrite + // params from the query which are added during routing + const _parsedUrl = (0, _url.parseReqUrl)(req.url); + // we can't normalize if we can't parse + if (!_parsedUrl) { + return req.url; + } + delete _parsedUrl.search; + filterInternalQuery(_parsedUrl.query, paramKeys); + req.url = (0, _formaturl.formatUrl)(_parsedUrl); +} +function interpolateDynamicPath(pathname, params, defaultRouteRegex) { + if (!defaultRouteRegex) return pathname; + for (const param of Object.keys(defaultRouteRegex.groups)){ + const { optional, repeat } = defaultRouteRegex.groups[param]; + let builtParam = `[${repeat ? '...' : ''}${param}]`; + if (optional) { + builtParam = `[${builtParam}]`; + } + let paramValue; + const value = params[param]; + if (Array.isArray(value)) { + paramValue = value.map((v)=>v && encodeURIComponent(v)).join('/'); + } else if (value) { + paramValue = encodeURIComponent(value); + } else { + paramValue = ''; + } + if (paramValue || optional) { + pathname = pathname.replaceAll(builtParam, paramValue); + } + } + return pathname; +} +function normalizeDynamicRouteParams(query, defaultRouteRegex, defaultRouteMatches, ignoreMissingOptional) { + const isDefaultValueMatch = (candidateValue, defaultValue)=>{ + if (!candidateValue) { + return false; + } + let normalizedCandidateValue = (0, _apppaths.normalizeRscURL)(candidateValue); + for(let i = 0; i < 3; i++){ + if (normalizedCandidateValue === defaultValue) { + return true; + } + const decodedCandidateValue = (0, _decodequerypathparameter.decodeQueryPathParameter)(normalizedCandidateValue); + if (decodedCandidateValue === normalizedCandidateValue) { + break; + } + normalizedCandidateValue = decodedCandidateValue; + } + return false; + }; + let hasValidParams = true; + let params = {}; + for (const key of Object.keys(defaultRouteRegex.groups)){ + let value = query[key]; + if (typeof value === 'string') { + value = (0, _apppaths.normalizeRscURL)(value); + } else if (Array.isArray(value)) { + value = value.map(_apppaths.normalizeRscURL); + } + // if the value matches the default value we can't rely + // on the parsed params, this is used to signal if we need + // to parse x-now-route-matches or not + const defaultValue = defaultRouteMatches[key]; + const isOptional = defaultRouteRegex.groups[key].optional; + const isDefaultValue = Array.isArray(defaultValue) ? defaultValue.some((defaultVal)=>{ + return Array.isArray(value) ? value.some((val)=>isDefaultValueMatch(val, defaultVal)) : isDefaultValueMatch(value, defaultVal); + }) : Array.isArray(value) ? value.some((val)=>isDefaultValueMatch(val, defaultValue)) : isDefaultValueMatch(value, defaultValue); + if (isDefaultValue || typeof value === 'undefined' && !(isOptional && ignoreMissingOptional)) { + return { + params: {}, + hasValidParams: false + }; + } + // non-provided optional values should be undefined so normalize + // them to undefined + if (isOptional && (!value || Array.isArray(value) && value.length === 1 && // fallback optional catch-all SSG pages have + // [[...paramName]] for the root path on Vercel + (value[0] === 'index' || value[0] === `[[...${key}]]`) || value === 'index' || value === `[[...${key}]]`)) { + value = undefined; + delete query[key]; + } + // query values from the proxy aren't already split into arrays + // so make sure to normalize catch-all values + if (value && typeof value === 'string' && defaultRouteRegex.groups[key].repeat) { + value = value.split('/'); + } + if (value) { + params[key] = value; + } + } + return { + params, + hasValidParams + }; +} +function getServerUtils({ page, i18n, basePath, rewrites, pageIsDynamic, trailingSlash, caseSensitive }) { + let defaultRouteRegex; + let dynamicRouteMatcher; + let defaultRouteMatches; + if (pageIsDynamic) { + defaultRouteRegex = (0, _routeregex.getNamedRouteRegex)(page, { + prefixRouteKeys: false + }); + dynamicRouteMatcher = (0, _routematcher.getRouteMatcher)(defaultRouteRegex); + defaultRouteMatches = dynamicRouteMatcher(page); + } + function handleRewrites(req, parsedUrl) { + // Here we deep clone the parsedUrl to avoid mutating the original. We also + // cast this to a mutable type so we can mutate it within this scope. + const rewrittenParsedUrl = structuredClone(parsedUrl); + const rewriteParams = {}; + let fsPathname = rewrittenParsedUrl.pathname; + const matchesPage = ()=>{ + const fsPathnameNoSlash = (0, _removetrailingslash.removeTrailingSlash)(fsPathname || ''); + return fsPathnameNoSlash === (0, _removetrailingslash.removeTrailingSlash)(page) || (dynamicRouteMatcher == null ? void 0 : dynamicRouteMatcher(fsPathnameNoSlash)); + }; + const checkRewrite = (rewrite)=>{ + const matcher = (0, _pathmatch.getPathMatch)(rewrite.source + (trailingSlash ? '(/)?' : ''), { + removeUnnamedParams: true, + strict: true, + sensitive: !!caseSensitive + }); + if (!rewrittenParsedUrl.pathname) return false; + let params = matcher(rewrittenParsedUrl.pathname); + if ((rewrite.has || rewrite.missing) && params) { + const hasParams = (0, _preparedestination.matchHas)(req, rewrittenParsedUrl.query, rewrite.has, rewrite.missing); + if (hasParams) { + Object.assign(params, hasParams); + } else { + params = false; + } + } + if (params) { + const { parsedDestination, destQuery } = (0, _preparedestination.prepareDestination)({ + appendParamsToQuery: true, + destination: rewrite.destination, + params: params, + query: rewrittenParsedUrl.query + }); + // if the rewrite destination is external break rewrite chain + if (parsedDestination.protocol) { + return true; + } + Object.assign(rewriteParams, destQuery, params); + Object.assign(rewrittenParsedUrl.query, parsedDestination.query); + delete parsedDestination.query; + Object.assign(rewrittenParsedUrl, parsedDestination); + fsPathname = rewrittenParsedUrl.pathname; + if (!fsPathname) return false; + if (basePath) { + fsPathname = fsPathname.replace(new RegExp(`^${basePath}`), '') || '/'; + } + if (i18n) { + const result = (0, _normalizelocalepath.normalizeLocalePath)(fsPathname, i18n.locales); + fsPathname = result.pathname; + rewrittenParsedUrl.query.nextInternalLocale = result.detectedLocale || params.nextInternalLocale; + } + if (fsPathname === page) { + return true; + } + if (pageIsDynamic && dynamicRouteMatcher) { + const dynamicParams = dynamicRouteMatcher(fsPathname); + if (dynamicParams) { + rewrittenParsedUrl.query = { + ...rewrittenParsedUrl.query, + ...dynamicParams + }; + return true; + } + } + } + return false; + }; + for (const rewrite of rewrites.beforeFiles || []){ + checkRewrite(rewrite); + } + if (fsPathname !== page) { + let finished = false; + for (const rewrite of rewrites.afterFiles || []){ + finished = checkRewrite(rewrite); + if (finished) break; + } + if (!finished && !matchesPage()) { + for (const rewrite of rewrites.fallback || []){ + finished = checkRewrite(rewrite); + if (finished) break; + } + } + } + return { + rewriteParams, + rewrittenParsedUrl + }; + } + function getParamsFromRouteMatches(routeMatchesHeader) { + // If we don't have a default route regex, we can't get params from route + // matches + if (!defaultRouteRegex) return null; + const { groups, routeKeys } = defaultRouteRegex; + const matcher = (0, _routematcher.getRouteMatcher)({ + re: { + // Simulate a RegExp match from the \`req.url\` input + exec: (str)=>{ + // Normalize all the prefixed query params. + const obj = Object.fromEntries(new URLSearchParams(str)); + for (const [key, value] of Object.entries(obj)){ + const normalizedKey = (0, _utils.normalizeNextQueryParam)(key); + if (!normalizedKey) continue; + obj[normalizedKey] = value; + delete obj[key]; + } + // Use all the named route keys. + const result = {}; + for (const keyName of Object.keys(routeKeys)){ + const paramName = routeKeys[keyName]; + // If this param name is not a valid parameter name, then skip it. + if (!paramName) continue; + const group = groups[paramName]; + const value = obj[keyName]; + // When we're missing a required param, we can't match the route. + if (!group.optional && !value) return null; + result[group.pos] = value; + } + return result; + } + }, + groups + }); + const routeMatches = matcher(routeMatchesHeader); + if (!routeMatches) return null; + return routeMatches; + } + function normalizeQueryParams(query, routeParamKeys) { + // this is used to pass query information in rewrites + // but should not be exposed in final query + delete query['nextInternalLocale']; + for (const [key, value] of Object.entries(query)){ + const normalizedKey = (0, _utils.normalizeNextQueryParam)(key); + if (!normalizedKey) continue; + // Remove the prefixed key from the query params because we want + // to consume it for the dynamic route matcher. + delete query[key]; + routeParamKeys.add(normalizedKey); + if (typeof value === 'undefined') continue; + query[normalizedKey] = Array.isArray(value) ? value.map((v)=>(0, _decodequerypathparameter.decodeQueryPathParameter)(v)) : (0, _decodequerypathparameter.decodeQueryPathParameter)(value); + } + } + return { + handleRewrites, + defaultRouteRegex, + dynamicRouteMatcher, + defaultRouteMatches, + normalizeQueryParams, + getParamsFromRouteMatches, + /** + * Normalize dynamic route params. + * + * @param query - The query params to normalize. + * @param ignoreMissingOptional - Whether to ignore missing optional params. + * @returns The normalized params and whether they are valid. + */ normalizeDynamicRouteParams: (query, ignoreMissingOptional)=>{ + if (!defaultRouteRegex || !defaultRouteMatches) { + return { + params: {}, + hasValidParams: false + }; + } + return normalizeDynamicRouteParams(query, defaultRouteRegex, defaultRouteMatches, ignoreMissingOptional); + }, + normalizeCdnUrl: (req, paramKeys)=>normalizeCdnUrl(req, paramKeys), + interpolateDynamicPath: (pathname, params)=>interpolateDynamicPath(pathname, params, defaultRouteRegex), + filterInternalQuery: (query, paramKeys)=>filterInternalQuery(query, paramKeys) + }; +} +function getPreviouslyRevalidatedTags(headers, previewModeId) { + return typeof headers[_constants.NEXT_CACHE_REVALIDATED_TAGS_HEADER] === 'string' && headers[_constants.NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER] === previewModeId ? headers[_constants.NEXT_CACHE_REVALIDATED_TAGS_HEADER].split(',') : []; +} + +//# sourceMappingURL=server-utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/server-utils.js.map b/e-commerce/node_modules/next/dist/server/server-utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..755af525c6a82b5272f889975a217358d35b57ea --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/server-utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/server-utils.ts"],"sourcesContent":["import type { Rewrite } from '../lib/load-custom-routes'\nimport type { RouteMatchFn } from '../shared/lib/router/utils/route-matcher'\nimport type { NextConfig } from './config'\nimport type { BaseNextRequest } from './base-http'\nimport type { NextUrlWithParsedQuery } from './request-meta'\nimport type { ParsedUrlQuery } from 'querystring'\n\nimport { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'\nimport { getPathMatch } from '../shared/lib/router/utils/path-match'\nimport { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'\nimport { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'\nimport {\n matchHas,\n prepareDestination,\n} from '../shared/lib/router/utils/prepare-destination'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\nimport { normalizeRscURL } from '../shared/lib/router/utils/app-paths'\nimport {\n NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,\n NEXT_CACHE_REVALIDATED_TAGS_HEADER,\n NEXT_INTERCEPTION_MARKER_PREFIX,\n NEXT_QUERY_PARAM_PREFIX,\n} from '../lib/constants'\nimport { normalizeNextQueryParam } from './web/utils'\nimport type { IncomingHttpHeaders, IncomingMessage } from 'http'\nimport { decodeQueryPathParameter } from './lib/decode-query-path-parameter'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { parseReqUrl } from '../lib/url'\nimport { formatUrl } from '../shared/lib/router/utils/format-url'\n\nfunction filterInternalQuery(\n query: Record,\n paramKeys: string[]\n) {\n // this is used to pass query information in rewrites\n // but should not be exposed in final query\n delete query['nextInternalLocale']\n\n for (const key in query) {\n const isNextQueryPrefix =\n key !== NEXT_QUERY_PARAM_PREFIX && key.startsWith(NEXT_QUERY_PARAM_PREFIX)\n\n const isNextInterceptionMarkerPrefix =\n key !== NEXT_INTERCEPTION_MARKER_PREFIX &&\n key.startsWith(NEXT_INTERCEPTION_MARKER_PREFIX)\n\n if (\n isNextQueryPrefix ||\n isNextInterceptionMarkerPrefix ||\n paramKeys.includes(key)\n ) {\n delete query[key]\n }\n }\n}\n\nexport function normalizeCdnUrl(\n req: BaseNextRequest | IncomingMessage,\n paramKeys: string[]\n) {\n // make sure to normalize req.url from CDNs to strip dynamic and rewrite\n // params from the query which are added during routing\n const _parsedUrl = parseReqUrl(req.url!)\n\n // we can't normalize if we can't parse\n if (!_parsedUrl) {\n return req.url\n }\n delete (_parsedUrl as any).search\n filterInternalQuery(_parsedUrl.query, paramKeys)\n\n req.url = formatUrl(_parsedUrl)\n}\n\nexport function interpolateDynamicPath(\n pathname: string,\n params: ParsedUrlQuery,\n defaultRouteRegex?: ReturnType | undefined\n) {\n if (!defaultRouteRegex) return pathname\n\n for (const param of Object.keys(defaultRouteRegex.groups)) {\n const { optional, repeat } = defaultRouteRegex.groups[param]\n let builtParam = `[${repeat ? '...' : ''}${param}]`\n\n if (optional) {\n builtParam = `[${builtParam}]`\n }\n\n let paramValue: string\n const value = params[param]\n\n if (Array.isArray(value)) {\n paramValue = value.map((v) => v && encodeURIComponent(v)).join('/')\n } else if (value) {\n paramValue = encodeURIComponent(value)\n } else {\n paramValue = ''\n }\n\n if (paramValue || optional) {\n pathname = pathname.replaceAll(builtParam, paramValue)\n }\n }\n\n return pathname\n}\n\nexport function normalizeDynamicRouteParams(\n query: ParsedUrlQuery,\n defaultRouteRegex: ReturnType,\n defaultRouteMatches: ParsedUrlQuery,\n ignoreMissingOptional: boolean\n) {\n const isDefaultValueMatch = (\n candidateValue: string | undefined,\n defaultValue: string\n ) => {\n if (!candidateValue) {\n return false\n }\n\n let normalizedCandidateValue = normalizeRscURL(candidateValue)\n for (let i = 0; i < 3; i++) {\n if (normalizedCandidateValue === defaultValue) {\n return true\n }\n\n const decodedCandidateValue = decodeQueryPathParameter(\n normalizedCandidateValue\n )\n\n if (decodedCandidateValue === normalizedCandidateValue) {\n break\n }\n\n normalizedCandidateValue = decodedCandidateValue\n }\n\n return false\n }\n\n let hasValidParams = true\n let params: ParsedUrlQuery = {}\n\n for (const key of Object.keys(defaultRouteRegex.groups)) {\n let value: string | string[] | undefined = query[key]\n\n if (typeof value === 'string') {\n value = normalizeRscURL(value)\n } else if (Array.isArray(value)) {\n value = value.map(normalizeRscURL)\n }\n\n // if the value matches the default value we can't rely\n // on the parsed params, this is used to signal if we need\n // to parse x-now-route-matches or not\n const defaultValue = defaultRouteMatches![key]\n const isOptional = defaultRouteRegex!.groups[key].optional\n\n const isDefaultValue = Array.isArray(defaultValue)\n ? defaultValue.some((defaultVal) => {\n return Array.isArray(value)\n ? value.some((val) => isDefaultValueMatch(val, defaultVal))\n : isDefaultValueMatch(value, defaultVal)\n })\n : Array.isArray(value)\n ? value.some((val) => isDefaultValueMatch(val, defaultValue as string))\n : isDefaultValueMatch(value, defaultValue as string)\n\n if (\n isDefaultValue ||\n (typeof value === 'undefined' && !(isOptional && ignoreMissingOptional))\n ) {\n return { params: {}, hasValidParams: false }\n }\n\n // non-provided optional values should be undefined so normalize\n // them to undefined\n if (\n isOptional &&\n (!value ||\n (Array.isArray(value) &&\n value.length === 1 &&\n // fallback optional catch-all SSG pages have\n // [[...paramName]] for the root path on Vercel\n (value[0] === 'index' || value[0] === `[[...${key}]]`)) ||\n value === 'index' ||\n value === `[[...${key}]]`)\n ) {\n value = undefined\n delete query[key]\n }\n\n // query values from the proxy aren't already split into arrays\n // so make sure to normalize catch-all values\n if (\n value &&\n typeof value === 'string' &&\n defaultRouteRegex!.groups[key].repeat\n ) {\n value = value.split('/')\n }\n\n if (value) {\n params[key] = value\n }\n }\n\n return {\n params,\n hasValidParams,\n }\n}\n\nexport function getServerUtils({\n page,\n i18n,\n basePath,\n rewrites,\n pageIsDynamic,\n trailingSlash,\n caseSensitive,\n}: {\n page: string\n i18n?: NextConfig['i18n']\n basePath: string\n rewrites: DeepReadonly<{\n fallback?: ReadonlyArray\n afterFiles?: ReadonlyArray\n beforeFiles?: ReadonlyArray\n }>\n pageIsDynamic: boolean\n trailingSlash?: boolean\n caseSensitive: boolean\n}) {\n let defaultRouteRegex: ReturnType | undefined\n let dynamicRouteMatcher: RouteMatchFn | undefined\n let defaultRouteMatches: ParsedUrlQuery | undefined\n\n if (pageIsDynamic) {\n defaultRouteRegex = getNamedRouteRegex(page, {\n prefixRouteKeys: false,\n })\n dynamicRouteMatcher = getRouteMatcher(defaultRouteRegex)\n defaultRouteMatches = dynamicRouteMatcher(page) as ParsedUrlQuery\n }\n\n function handleRewrites(\n req: BaseNextRequest | IncomingMessage,\n parsedUrl: DeepReadonly\n ) {\n // Here we deep clone the parsedUrl to avoid mutating the original. We also\n // cast this to a mutable type so we can mutate it within this scope.\n const rewrittenParsedUrl = structuredClone(\n parsedUrl\n ) as NextUrlWithParsedQuery\n const rewriteParams: Record = {}\n let fsPathname = rewrittenParsedUrl.pathname\n\n const matchesPage = () => {\n const fsPathnameNoSlash = removeTrailingSlash(fsPathname || '')\n return (\n fsPathnameNoSlash === removeTrailingSlash(page) ||\n dynamicRouteMatcher?.(fsPathnameNoSlash)\n )\n }\n\n const checkRewrite = (rewrite: DeepReadonly): boolean => {\n const matcher = getPathMatch(\n rewrite.source + (trailingSlash ? '(/)?' : ''),\n {\n removeUnnamedParams: true,\n strict: true,\n sensitive: !!caseSensitive,\n }\n )\n\n if (!rewrittenParsedUrl.pathname) return false\n\n let params = matcher(rewrittenParsedUrl.pathname)\n\n if ((rewrite.has || rewrite.missing) && params) {\n const hasParams = matchHas(\n req,\n rewrittenParsedUrl.query,\n rewrite.has as Rewrite['has'],\n rewrite.missing as Rewrite['missing']\n )\n\n if (hasParams) {\n Object.assign(params, hasParams)\n } else {\n params = false\n }\n }\n\n if (params) {\n const { parsedDestination, destQuery } = prepareDestination({\n appendParamsToQuery: true,\n destination: rewrite.destination,\n params: params,\n query: rewrittenParsedUrl.query,\n })\n\n // if the rewrite destination is external break rewrite chain\n if (parsedDestination.protocol) {\n return true\n }\n\n Object.assign(rewriteParams, destQuery, params)\n Object.assign(rewrittenParsedUrl.query, parsedDestination.query)\n delete (parsedDestination as any).query\n\n Object.assign(rewrittenParsedUrl, parsedDestination)\n\n fsPathname = rewrittenParsedUrl.pathname\n if (!fsPathname) return false\n\n if (basePath) {\n fsPathname = fsPathname.replace(new RegExp(`^${basePath}`), '') || '/'\n }\n\n if (i18n) {\n const result = normalizeLocalePath(fsPathname, i18n.locales)\n fsPathname = result.pathname\n rewrittenParsedUrl.query.nextInternalLocale =\n result.detectedLocale || params.nextInternalLocale\n }\n\n if (fsPathname === page) {\n return true\n }\n\n if (pageIsDynamic && dynamicRouteMatcher) {\n const dynamicParams = dynamicRouteMatcher(fsPathname)\n if (dynamicParams) {\n rewrittenParsedUrl.query = {\n ...rewrittenParsedUrl.query,\n ...dynamicParams,\n }\n return true\n }\n }\n }\n\n return false\n }\n\n for (const rewrite of rewrites.beforeFiles || []) {\n checkRewrite(rewrite)\n }\n\n if (fsPathname !== page) {\n let finished = false\n\n for (const rewrite of rewrites.afterFiles || []) {\n finished = checkRewrite(rewrite)\n if (finished) break\n }\n\n if (!finished && !matchesPage()) {\n for (const rewrite of rewrites.fallback || []) {\n finished = checkRewrite(rewrite)\n if (finished) break\n }\n }\n }\n\n return { rewriteParams, rewrittenParsedUrl }\n }\n\n function getParamsFromRouteMatches(routeMatchesHeader: string) {\n // If we don't have a default route regex, we can't get params from route\n // matches\n if (!defaultRouteRegex) return null\n\n const { groups, routeKeys } = defaultRouteRegex\n\n const matcher = getRouteMatcher({\n re: {\n // Simulate a RegExp match from the \\`req.url\\` input\n exec: (str: string) => {\n // Normalize all the prefixed query params.\n const obj: Record = Object.fromEntries(\n new URLSearchParams(str)\n )\n for (const [key, value] of Object.entries(obj)) {\n const normalizedKey = normalizeNextQueryParam(key)\n if (!normalizedKey) continue\n\n obj[normalizedKey] = value\n delete obj[key]\n }\n\n // Use all the named route keys.\n const result = {} as RegExpExecArray\n for (const keyName of Object.keys(routeKeys)) {\n const paramName = routeKeys[keyName]\n\n // If this param name is not a valid parameter name, then skip it.\n if (!paramName) continue\n\n const group = groups[paramName]\n const value = obj[keyName]\n\n // When we're missing a required param, we can't match the route.\n if (!group.optional && !value) return null\n\n result[group.pos] = value\n }\n\n return result\n },\n },\n groups,\n })\n\n const routeMatches = matcher(routeMatchesHeader)\n if (!routeMatches) return null\n\n return routeMatches\n }\n\n function normalizeQueryParams(\n query: Record,\n routeParamKeys: Set\n ) {\n // this is used to pass query information in rewrites\n // but should not be exposed in final query\n delete query['nextInternalLocale']\n\n for (const [key, value] of Object.entries(query)) {\n const normalizedKey = normalizeNextQueryParam(key)\n if (!normalizedKey) continue\n\n // Remove the prefixed key from the query params because we want\n // to consume it for the dynamic route matcher.\n delete query[key]\n routeParamKeys.add(normalizedKey)\n\n if (typeof value === 'undefined') continue\n\n query[normalizedKey] = Array.isArray(value)\n ? value.map((v) => decodeQueryPathParameter(v))\n : decodeQueryPathParameter(value)\n }\n }\n\n return {\n handleRewrites,\n defaultRouteRegex,\n dynamicRouteMatcher,\n defaultRouteMatches,\n normalizeQueryParams,\n getParamsFromRouteMatches,\n /**\n * Normalize dynamic route params.\n *\n * @param query - The query params to normalize.\n * @param ignoreMissingOptional - Whether to ignore missing optional params.\n * @returns The normalized params and whether they are valid.\n */\n normalizeDynamicRouteParams: (\n query: ParsedUrlQuery,\n ignoreMissingOptional: boolean\n ) => {\n if (!defaultRouteRegex || !defaultRouteMatches) {\n return { params: {}, hasValidParams: false }\n }\n\n return normalizeDynamicRouteParams(\n query,\n defaultRouteRegex,\n defaultRouteMatches,\n ignoreMissingOptional\n )\n },\n\n normalizeCdnUrl: (\n req: BaseNextRequest | IncomingMessage,\n paramKeys: string[]\n ) => normalizeCdnUrl(req, paramKeys),\n\n interpolateDynamicPath: (\n pathname: string,\n params: Record\n ) => interpolateDynamicPath(pathname, params, defaultRouteRegex),\n\n filterInternalQuery: (query: ParsedUrlQuery, paramKeys: string[]) =>\n filterInternalQuery(query, paramKeys),\n }\n}\n\nexport function getPreviouslyRevalidatedTags(\n headers: IncomingHttpHeaders,\n previewModeId: string | undefined\n): string[] {\n return typeof headers[NEXT_CACHE_REVALIDATED_TAGS_HEADER] === 'string' &&\n headers[NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER] === previewModeId\n ? headers[NEXT_CACHE_REVALIDATED_TAGS_HEADER].split(',')\n : []\n}\n"],"names":["getPreviouslyRevalidatedTags","getServerUtils","interpolateDynamicPath","normalizeCdnUrl","normalizeDynamicRouteParams","filterInternalQuery","query","paramKeys","key","isNextQueryPrefix","NEXT_QUERY_PARAM_PREFIX","startsWith","isNextInterceptionMarkerPrefix","NEXT_INTERCEPTION_MARKER_PREFIX","includes","req","_parsedUrl","parseReqUrl","url","search","formatUrl","pathname","params","defaultRouteRegex","param","Object","keys","groups","optional","repeat","builtParam","paramValue","value","Array","isArray","map","v","encodeURIComponent","join","replaceAll","defaultRouteMatches","ignoreMissingOptional","isDefaultValueMatch","candidateValue","defaultValue","normalizedCandidateValue","normalizeRscURL","i","decodedCandidateValue","decodeQueryPathParameter","hasValidParams","isOptional","isDefaultValue","some","defaultVal","val","length","undefined","split","page","i18n","basePath","rewrites","pageIsDynamic","trailingSlash","caseSensitive","dynamicRouteMatcher","getNamedRouteRegex","prefixRouteKeys","getRouteMatcher","handleRewrites","parsedUrl","rewrittenParsedUrl","structuredClone","rewriteParams","fsPathname","matchesPage","fsPathnameNoSlash","removeTrailingSlash","checkRewrite","rewrite","matcher","getPathMatch","source","removeUnnamedParams","strict","sensitive","has","missing","hasParams","matchHas","assign","parsedDestination","destQuery","prepareDestination","appendParamsToQuery","destination","protocol","replace","RegExp","result","normalizeLocalePath","locales","nextInternalLocale","detectedLocale","dynamicParams","beforeFiles","finished","afterFiles","fallback","getParamsFromRouteMatches","routeMatchesHeader","routeKeys","re","exec","str","obj","fromEntries","URLSearchParams","entries","normalizedKey","normalizeNextQueryParam","keyName","paramName","group","pos","routeMatches","normalizeQueryParams","routeParamKeys","add","headers","previewModeId","NEXT_CACHE_REVALIDATED_TAGS_HEADER","NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER"],"mappings":";;;;;;;;;;;;;;;;;;IA8egBA,4BAA4B;eAA5BA;;IAvRAC,cAAc;eAAdA;;IA7IAC,sBAAsB;eAAtBA;;IAlBAC,eAAe;eAAfA;;IAoDAC,2BAA2B;eAA3BA;;;qCArGoB;2BACP;4BACM;8BACH;oCAIzB;qCAC6B;0BACJ;2BAMzB;uBACiC;0CAEC;qBAEb;2BACF;AAE1B,SAASC,oBACPC,KAAoD,EACpDC,SAAmB;IAEnB,qDAAqD;IACrD,2CAA2C;IAC3C,OAAOD,KAAK,CAAC,qBAAqB;IAElC,IAAK,MAAME,OAAOF,MAAO;QACvB,MAAMG,oBACJD,QAAQE,kCAAuB,IAAIF,IAAIG,UAAU,CAACD,kCAAuB;QAE3E,MAAME,iCACJJ,QAAQK,0CAA+B,IACvCL,IAAIG,UAAU,CAACE,0CAA+B;QAEhD,IACEJ,qBACAG,kCACAL,UAAUO,QAAQ,CAACN,MACnB;YACA,OAAOF,KAAK,CAACE,IAAI;QACnB;IACF;AACF;AAEO,SAASL,gBACdY,GAAs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,OAAO,CAACF,SACjCA,MAAMG,GAAG,CAAC,CAACC,IAAMa,IAAAA,kDAAwB,EAACb,MAC1Ca,IAAAA,kDAAwB,EAACjB;QAC/B;IACF;IAEA,OAAO;QACLsC;QACA/C;QACA2C;QACA1B;QACAuF;QACAjB;QACA;;;;;;KAMC,GACD1G,6BAA6B,CAC3BE,OACAmC;YAEA,IAAI,CAAClB,qBAAqB,CAACiB,qBAAqB;gBAC9C,OAAO;oBAAElB,QAAQ,CAAC;oBAAG4B,gBAAgB;gBAAM;YAC7C;YAEA,OAAO9C,4BACLE,OACAiB,mBACAiB,qBACAC;QAEJ;QAEAtC,iBAAiB,CACfY,KACAR,YACGJ,gBAAgBY,KAAKR;QAE1BL,wBAAwB,CACtBmB,UACAC,SACGpB,uBAAuBmB,UAAUC,QAAQC;QAE9ClB,qBAAqB,CAACC,OAAuBC,YAC3CF,oBAAoBC,OAAOC;IAC/B;AACF;AAEO,SAASP,6BACdkI,OAA4B,EAC5BC,aAAiC;IAEjC,OAAO,OAAOD,OAAO,CAACE,6CAAkC,CAAC,KAAK,YAC5DF,OAAO,CAACG,iDAAsC,CAAC,KAAKF,gBAClDD,OAAO,CAACE,6CAAkC,CAAC,CAAC1E,KAAK,CAAC,OAClD,EAAE;AACR","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/setup-http-agent-env.d.ts b/e-commerce/node_modules/next/dist/server/setup-http-agent-env.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..890f5b7e23a37cf9f1109c6da2c5c1ea6e6424e6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/setup-http-agent-env.d.ts @@ -0,0 +1,4 @@ +import type { NextConfig } from '../types'; +export declare function setHttpClientAndAgentOptions(config: { + httpAgentOptions?: NextConfig['httpAgentOptions']; +}): void; diff --git a/e-commerce/node_modules/next/dist/server/setup-http-agent-env.js b/e-commerce/node_modules/next/dist/server/setup-http-agent-env.js new file mode 100644 index 0000000000000000000000000000000000000000..65d1ee12b817aa2d4fd3305c08f07bebe9a84b63 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/setup-http-agent-env.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "setHttpClientAndAgentOptions", { + enumerable: true, + get: function() { + return setHttpClientAndAgentOptions; + } +}); +const _http = require("http"); +const _https = require("https"); +function setHttpClientAndAgentOptions(config) { + if (globalThis.__NEXT_HTTP_AGENT) { + // We only need to assign once because we want + // to reuse the same agent for all requests. + return; + } + if (!config) { + throw new Error('Expected config.httpAgentOptions to be an object'); + } + globalThis.__NEXT_HTTP_AGENT_OPTIONS = config.httpAgentOptions; + globalThis.__NEXT_HTTP_AGENT = new _http.Agent(config.httpAgentOptions); + globalThis.__NEXT_HTTPS_AGENT = new _https.Agent(config.httpAgentOptions); +} + +//# sourceMappingURL=setup-http-agent-env.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/setup-http-agent-env.js.map b/e-commerce/node_modules/next/dist/server/setup-http-agent-env.js.map new file mode 100644 index 0000000000000000000000000000000000000000..30bffe65e69543f6b2eb186cd781f3d68616d14d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/setup-http-agent-env.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/setup-http-agent-env.ts"],"sourcesContent":["import type { NextConfig } from '../types'\nimport { Agent as HttpAgent } from 'http'\nimport { Agent as HttpsAgent } from 'https'\n\nexport function setHttpClientAndAgentOptions(config: {\n httpAgentOptions?: NextConfig['httpAgentOptions']\n}) {\n if (globalThis.__NEXT_HTTP_AGENT) {\n // We only need to assign once because we want\n // to reuse the same agent for all requests.\n return\n }\n\n if (!config) {\n throw new Error('Expected config.httpAgentOptions to be an object')\n }\n\n globalThis.__NEXT_HTTP_AGENT_OPTIONS = config.httpAgentOptions\n globalThis.__NEXT_HTTP_AGENT = new HttpAgent(config.httpAgentOptions)\n globalThis.__NEXT_HTTPS_AGENT = new HttpsAgent(config.httpAgentOptions)\n}\n"],"names":["setHttpClientAndAgentOptions","config","globalThis","__NEXT_HTTP_AGENT","Error","__NEXT_HTTP_AGENT_OPTIONS","httpAgentOptions","HttpAgent","__NEXT_HTTPS_AGENT","HttpsAgent"],"mappings":";;;;+BAIgBA;;;eAAAA;;;sBAHmB;uBACC;AAE7B,SAASA,6BAA6BC,MAE5C;IACC,IAAIC,WAAWC,iBAAiB,EAAE;QAChC,8CAA8C;QAC9C,4CAA4C;QAC5C;IACF;IAEA,IAAI,CAACF,QAAQ;QACX,MAAM,IAAIG,MAAM;IAClB;IAEAF,WAAWG,yBAAyB,GAAGJ,OAAOK,gBAAgB;IAC9DJ,WAAWC,iBAAiB,GAAG,IAAII,WAAS,CAACN,OAAOK,gBAAgB;IACpEJ,WAAWM,kBAAkB,GAAG,IAAIC,YAAU,CAACR,OAAOK,gBAAgB;AACxE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/stream-utils/encoded-tags.d.ts b/e-commerce/node_modules/next/dist/server/stream-utils/encoded-tags.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..550625e66cd067edad6d79e4e64b25d0c4a35844 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/stream-utils/encoded-tags.d.ts @@ -0,0 +1,16 @@ +export declare const ENCODED_TAGS: { + readonly OPENING: { + readonly HTML: Uint8Array; + readonly HEAD: Uint8Array; + readonly BODY: Uint8Array; + }; + readonly CLOSED: { + readonly HEAD: Uint8Array; + readonly BODY: Uint8Array; + readonly HTML: Uint8Array; + readonly BODY_AND_HTML: Uint8Array; + }; + readonly META: { + readonly ICON_MARK: Uint8Array; + }; +}; diff --git a/e-commerce/node_modules/next/dist/server/stream-utils/encoded-tags.js b/e-commerce/node_modules/next/dist/server/stream-utils/encoded-tags.js new file mode 100644 index 0000000000000000000000000000000000000000..9e5fdaf9f4a454e3ba846d749e973e7700219be9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/stream-utils/encoded-tags.js @@ -0,0 +1,122 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ENCODED_TAGS", { + enumerable: true, + get: function() { + return ENCODED_TAGS; + } +}); +const ENCODED_TAGS = { + // opening tags do not have the closing `>` since they can contain other attributes such as `` + OPENING: { + // + HEAD: new Uint8Array([ + 60, + 47, + 104, + 101, + 97, + 100, + 62 + ]), + // + BODY: new Uint8Array([ + 60, + 47, + 98, + 111, + 100, + 121, + 62 + ]), + // + HTML: new Uint8Array([ + 60, + 47, + 104, + 116, + 109, + 108, + 62 + ]), + // + BODY_AND_HTML: new Uint8Array([ + 60, + 47, + 98, + 111, + 100, + 121, + 62, + 60, + 47, + 104, + 116, + 109, + 108, + 62 + ]) + }, + META: { + // Only the match the prefix cause the suffix can be different whether it's xml compatible or not ">" or "/>" + // ` since they can contain other attributes such as ``\n OPENING: {\n // \n HEAD: new Uint8Array([60, 47, 104, 101, 97, 100, 62]),\n // \n BODY: new Uint8Array([60, 47, 98, 111, 100, 121, 62]),\n // \n HTML: new Uint8Array([60, 47, 104, 116, 109, 108, 62]),\n // \n BODY_AND_HTML: new Uint8Array([\n 60, 47, 98, 111, 100, 121, 62, 60, 47, 104, 116, 109, 108, 62,\n ]),\n },\n META: {\n // Only the match the prefix cause the suffix can be different whether it's xml compatible or not \">\" or \"/>\"\n // = maxBufferByteLength) { + flushBuffered(this); + } else if (!flushScheduled) { + flushScheduled = true; + queueMicrotask(()=>{ + flushScheduled = false; + flushBuffered(this); + }); + } + callback(); + }, + flush (callback) { + flushBuffered(this); + callback(); + } + }); +} + +//# sourceMappingURL=node-buffered-transform-stream.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/stream-utils/node-buffered-transform-stream.js.map b/e-commerce/node_modules/next/dist/server/stream-utils/node-buffered-transform-stream.js.map new file mode 100644 index 0000000000000000000000000000000000000000..000fb8b7a53040af40531882e99fb3ff1a2bbb19 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/stream-utils/node-buffered-transform-stream.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/stream-utils/node-buffered-transform-stream.ts"],"sourcesContent":["import { Transform } from 'node:stream'\n\n/**\n * Node.js `Transform` that coalesces chunks written in the same microtask into\n * a single `Uint8Array` before pushing downstream, flushing synchronously once\n * the buffer reaches `maxBufferByteLength` (default: never, i.e.\n * microtask-only).\n *\n * This lives in its own module, separate from `stream-ops.node`, so that\n * consumers outside the render layer (e.g. the dev server's React debug\n * channel) can batch Node streams without pulling in `stream-ops.node`'s\n * `react-dom/server` and `react-dom/static` imports. Those resolve to the\n * vendored React only inside aliased app bundles; loaded from the unaliased\n * dev-server runtime they resolve to the app's installed React, which on React\n * 18 has no `react-dom/static` export.\n */\nexport function createNodeBufferedTransformStream(\n maxBufferByteLength: number = Infinity\n): Transform {\n let bufferedChunks: Array = []\n let bufferByteLength = 0\n let flushScheduled = false\n\n function flushBuffered(stream: Transform): void {\n if (bufferedChunks.length === 0) return\n\n const merged = new Uint8Array(bufferByteLength)\n let copiedBytes = 0\n for (let i = 0; i < bufferedChunks.length; i++) {\n const bufferedChunk = bufferedChunks[i]\n merged.set(bufferedChunk, copiedBytes)\n copiedBytes += bufferedChunk.byteLength\n }\n bufferedChunks.length = 0\n bufferByteLength = 0\n stream.push(merged)\n }\n\n return new Transform({\n transform(chunk, _encoding, callback) {\n bufferedChunks.push(chunk)\n bufferByteLength += chunk.byteLength\n\n if (bufferByteLength >= maxBufferByteLength) {\n flushBuffered(this)\n } else if (!flushScheduled) {\n flushScheduled = true\n queueMicrotask(() => {\n flushScheduled = false\n flushBuffered(this)\n })\n }\n callback()\n },\n flush(callback) {\n flushBuffered(this)\n callback()\n },\n })\n}\n"],"names":["createNodeBufferedTransformStream","maxBufferByteLength","Infinity","bufferedChunks","bufferByteLength","flushScheduled","flushBuffered","stream","length","merged","Uint8Array","copiedBytes","i","bufferedChunk","set","byteLength","push","Transform","transform","chunk","_encoding","callback","queueMicrotask","flush"],"mappings":";;;;+BAgBgBA;;;eAAAA;;;4BAhBU;AAgBnB,SAASA,kCACdC,sBAA8BC,QAAQ;IAEtC,IAAIC,iBAAoC,EAAE;IAC1C,IAAIC,mBAAmB;IACvB,IAAIC,iBAAiB;IAErB,SAASC,cAAcC,MAAiB;QACtC,IAAIJ,eAAeK,MAAM,KAAK,GAAG;QAEjC,MAAMC,SAAS,IAAIC,WAAWN;QAC9B,IAAIO,cAAc;QAClB,IAAK,IAAIC,IAAI,GAAGA,IAAIT,eAAeK,MAAM,EAAEI,IAAK;YAC9C,MAAMC,gBAAgBV,cAAc,CAACS,EAAE;YACvCH,OAAOK,GAAG,CAACD,eAAeF;YAC1BA,eAAeE,cAAcE,UAAU;QACzC;QACAZ,eAAeK,MAAM,GAAG;QACxBJ,mBAAmB;QACnBG,OAAOS,IAAI,CAACP;IACd;IAEA,OAAO,IAAIQ,qBAAS,CAAC;QACnBC,WAAUC,KAAK,EAAEC,SAAS,EAAEC,QAAQ;YAClClB,eAAea,IAAI,CAACG;YACpBf,oBAAoBe,MAAMJ,UAAU;YAEpC,IAAIX,oBAAoBH,qBAAqB;gBAC3CK,cAAc,IAAI;YACpB,OAAO,IAAI,CAACD,gBAAgB;gBAC1BA,iBAAiB;gBACjBiB,eAAe;oBACbjB,iBAAiB;oBACjBC,cAAc,IAAI;gBACpB;YACF;YACAe;QACF;QACAE,OAAMF,QAAQ;YACZf,cAAc,IAAI;YAClBe;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/stream-utils/node-web-streams-helper.d.ts b/e-commerce/node_modules/next/dist/server/stream-utils/node-web-streams-helper.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39954f0708ecbb63a3ac84e33cae8f61e0c2cad0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/stream-utils/node-web-streams-helper.d.ts @@ -0,0 +1,94 @@ +import type { ReactDOMServerReadableStream } from 'react-dom/server'; +import type { AnyStream } from '../app-render/stream-ops'; +export declare function chainStreams(...streams: ReadableStream[]): ReadableStream; +export declare function streamFromString(str: string): ReadableStream; +/** + * Creates a stream that delivers `chunk` and then closes. + * + * The stream is a default stream, and it has to stay one. A byte stream (`type: + * 'bytes'`) transfers the buffer of each chunk that it receives, which detaches + * `chunk`. A caller that keeps `chunk` to serve more than one read, such as an + * in-memory cache handler, loses the data on the first read. + * + * Every reader receives the same `chunk` instance. A reader that modifies it + * changes what later readers see. + */ +export declare function streamFromBuffer(chunk: Buffer): ReadableStream; +export declare function webstreamToUint8Array(stream: ReadableStream): Promise; +export declare function nodestreamToUint8Array(stream: AnyStream): Promise; +export declare function streamToUint8Array(stream: AnyStream): Promise>; +export declare function streamToBuffer(stream: ReadableStream): Promise; +export declare function streamToString(stream: ReadableStream, signal?: AbortSignal): Promise; +export type BufferedTransformOptions = { + /** + * Flush synchronously once the buffer reaches this many bytes. + */ + readonly maxBufferByteLength?: number; +}; +export declare function createBufferedTransformStream(options?: BufferedTransformOptions): TransformStream; +export declare function renderToInitialFizzStream({ ReactDOMServer, element, streamOptions, }: { + ReactDOMServer: { + renderToReadableStream: typeof import('react-dom/server').renderToReadableStream; + }; + element: React.ReactElement; + streamOptions?: Parameters[1]; +}): Promise; +export declare function createMetadataTransformStream(insert: () => Promise | string): TransformStream; +export declare function createHeadInsertionTransformStream(insert: () => Promise): TransformStream; +export declare function createDeferredSuffixStream(suffix: string): TransformStream; +export declare function createFlightDataInjectionTransformStream(stream: ReadableStream, delayDataUntilFirstHtmlChunk: boolean): TransformStream; +export declare const CLOSE_TAG = ""; +/** + * This transform stream moves the suffix to the end of the stream, so results + * like `` will be transformed to + * ``. + */ +export declare function createMoveSuffixStream(): TransformStream; +export declare function createHtmlDataDplIdTransformStream(dplId: string): TransformStream; +export declare function createRootLayoutValidatorStream(): TransformStream; +export declare function chainTransformers(readable: ReadableStream, transformers: ReadonlyArray | null>): ReadableStream; +export type ContinueStreamOptions = { + inlinedDataStream: ReadableStream | undefined; + waitForAllReady: boolean; + deploymentId: string | undefined; + getServerInsertedHTML: () => Promise; + getServerInsertedMetadata: () => Promise; + validateRootLayout?: boolean; + /** + * Suffix to inject after the buffered data, but before the close tags. + */ + suffix?: string | undefined; +}; +export declare function continueFizzStream(renderStream: ReactDOMServerReadableStream, { suffix, inlinedDataStream, waitForAllReady, deploymentId, getServerInsertedHTML, getServerInsertedMetadata, validateRootLayout, }: ContinueStreamOptions): Promise>; +type ContinueDynamicPrerenderOptions = { + getServerInsertedHTML: () => Promise; + getServerInsertedMetadata: () => Promise; + deploymentId: string | undefined; +}; +export declare function continueDynamicPrerender(prerenderStream: ReadableStream, { getServerInsertedHTML, getServerInsertedMetadata, deploymentId, }: ContinueDynamicPrerenderOptions): Promise>>; +type ContinueStaticPrerenderOptions = { + inlinedDataStream: ReadableStream; + getServerInsertedHTML: () => Promise; + getServerInsertedMetadata: () => Promise; + deploymentId: string | undefined; +}; +export declare function continueStaticPrerender(prerenderStream: ReadableStream, { inlinedDataStream, getServerInsertedHTML, getServerInsertedMetadata, deploymentId, }: ContinueStaticPrerenderOptions): Promise>>; +export declare function continueStaticFallbackPrerender(prerenderStream: ReadableStream, { inlinedDataStream, getServerInsertedHTML, getServerInsertedMetadata, deploymentId, }: ContinueStaticPrerenderOptions): Promise>>; +type ContinueResumeOptions = { + inlinedDataStream: ReadableStream; + getServerInsertedHTML: () => Promise; + getServerInsertedMetadata: () => Promise; + delayDataUntilFirstHtmlChunk: boolean; + deploymentId: string | undefined; +}; +export declare function continueDynamicHTMLResume(renderStream: ReadableStream, { delayDataUntilFirstHtmlChunk, inlinedDataStream, getServerInsertedHTML, getServerInsertedMetadata, deploymentId, }: ContinueResumeOptions): Promise>>; +export declare function createDocumentClosingStream(): ReadableStream; +/** + * Web TransformStream that replaces the runtime prefetch sentinel in an RSC + * payload stream: `[]` -> `[,]`. + * + * This is the web equivalent of createRuntimePrefetchNodeTransform + * in node-stream-helpers.ts. + */ +export declare function createRuntimePrefetchTransformStream(sentinel: number, isPartial: boolean, staleTime: number): TransformStream; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/stream-utils/node-web-streams-helper.js b/e-commerce/node_modules/next/dist/server/stream-utils/node-web-streams-helper.js new file mode 100644 index 0000000000000000000000000000000000000000..88ca32abf1404a46a487a8b7c79f73011c29f051 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/stream-utils/node-web-streams-helper.js @@ -0,0 +1,935 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + CLOSE_TAG: null, + chainStreams: null, + chainTransformers: null, + continueDynamicHTMLResume: null, + continueDynamicPrerender: null, + continueFizzStream: null, + continueStaticFallbackPrerender: null, + continueStaticPrerender: null, + createBufferedTransformStream: null, + createDeferredSuffixStream: null, + createDocumentClosingStream: null, + createFlightDataInjectionTransformStream: null, + createHeadInsertionTransformStream: null, + createHtmlDataDplIdTransformStream: null, + createMetadataTransformStream: null, + createMoveSuffixStream: null, + createRootLayoutValidatorStream: null, + createRuntimePrefetchTransformStream: null, + nodestreamToUint8Array: null, + renderToInitialFizzStream: null, + streamFromBuffer: null, + streamFromString: null, + streamToBuffer: null, + streamToString: null, + streamToUint8Array: null, + webstreamToUint8Array: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + CLOSE_TAG: function() { + return CLOSE_TAG; + }, + chainStreams: function() { + return chainStreams; + }, + chainTransformers: function() { + return chainTransformers; + }, + continueDynamicHTMLResume: function() { + return continueDynamicHTMLResume; + }, + continueDynamicPrerender: function() { + return continueDynamicPrerender; + }, + continueFizzStream: function() { + return continueFizzStream; + }, + continueStaticFallbackPrerender: function() { + return continueStaticFallbackPrerender; + }, + continueStaticPrerender: function() { + return continueStaticPrerender; + }, + createBufferedTransformStream: function() { + return createBufferedTransformStream; + }, + createDeferredSuffixStream: function() { + return createDeferredSuffixStream; + }, + createDocumentClosingStream: function() { + return createDocumentClosingStream; + }, + createFlightDataInjectionTransformStream: function() { + return createFlightDataInjectionTransformStream; + }, + createHeadInsertionTransformStream: function() { + return createHeadInsertionTransformStream; + }, + createHtmlDataDplIdTransformStream: function() { + return createHtmlDataDplIdTransformStream; + }, + createMetadataTransformStream: function() { + return createMetadataTransformStream; + }, + createMoveSuffixStream: function() { + return createMoveSuffixStream; + }, + createRootLayoutValidatorStream: function() { + return createRootLayoutValidatorStream; + }, + createRuntimePrefetchTransformStream: function() { + return createRuntimePrefetchTransformStream; + }, + nodestreamToUint8Array: function() { + return nodestreamToUint8Array; + }, + renderToInitialFizzStream: function() { + return renderToInitialFizzStream; + }, + streamFromBuffer: function() { + return streamFromBuffer; + }, + streamFromString: function() { + return streamFromString; + }, + streamToBuffer: function() { + return streamToBuffer; + }, + streamToString: function() { + return streamToString; + }, + streamToUint8Array: function() { + return streamToUint8Array; + }, + webstreamToUint8Array: function() { + return webstreamToUint8Array; + } +}); +const _tracer = require("../lib/trace/tracer"); +const _constants = require("../lib/trace/constants"); +const _promisewithresolvers = require("../../shared/lib/promise-with-resolvers"); +const _scheduler = require("../../lib/scheduler"); +const _encodedtags = require("./encoded-tags"); +const _uint8arrayhelpers = require("./uint8array-helpers"); +const _constants1 = require("../../shared/lib/errors/constants"); +const _approuterheaders = require("../../client/components/app-router-headers"); +const _cachebustingsearchparam = require("../../shared/lib/router/utils/cache-busting-search-param"); +function voidCatch() { +// this catcher is designed to be used with pipeTo where we expect the underlying +// pipe implementation to forward errors but we don't want the pipeTo promise to reject +// and be unhandled +} +// We can share the same encoder instance everywhere +// Notably we cannot do the same for TextDecoder because it is stateful +// when handling streaming data +const encoder = new TextEncoder(); +function chainStreams(...streams) { + // If we have no streams, return an empty stream. This behavior is + // intentional as we're now providing the `RenderResult.EMPTY` value. + if (streams.length === 0) { + return new ReadableStream({ + start (controller) { + controller.close(); + } + }); + } + // If we only have 1 stream we fast path it by returning just this stream + if (streams.length === 1) { + return streams[0]; + } + const { readable, writable } = new TransformStream(); + // We always initiate pipeTo immediately. We know we have at least 2 streams + // so we need to avoid closing the writable when this one finishes. + let promise = streams[0].pipeTo(writable, { + preventClose: true + }); + let i = 1; + for(; i < streams.length - 1; i++){ + const nextStream = streams[i]; + promise = promise.then(()=>nextStream.pipeTo(writable, { + preventClose: true + })); + } + // We can omit the length check because we halted before the last stream and there + // is at least two streams so the lastStream here will always be defined + const lastStream = streams[i]; + promise = promise.then(()=>lastStream.pipeTo(writable)); + // Catch any errors from the streams and ignore them, they will be handled + // by whatever is consuming the readable stream. + promise.catch(voidCatch); + return readable; +} +function streamFromString(str) { + return new ReadableStream({ + start (controller) { + controller.enqueue(encoder.encode(str)); + controller.close(); + } + }); +} +function streamFromBuffer(chunk) { + return new ReadableStream({ + start (controller) { + controller.enqueue(chunk); + controller.close(); + } + }); +} +async function streamToChunks(stream) { + const reader = stream.getReader(); + const chunks = []; + while(true){ + const { done, value } = await reader.read(); + if (done) { + break; + } + chunks.push(value); + } + return chunks; +} +function concatUint8Arrays(chunks) { + const totalLength = chunks.reduce((sum, chunk)=>sum + chunk.length, 0); + const result = new Uint8Array(totalLength); + let offset = 0; + for (const chunk of chunks){ + result.set(chunk, offset); + offset += chunk.length; + } + return result; +} +async function webstreamToUint8Array(stream) { + return concatUint8Arrays(await streamToChunks(stream)); +} +function webToReadable(stream) { + if (process.env.NEXT_RUNTIME === 'edge') { + throw new Error('webToReadable cannot be used in the edge runtime'); + } else { + let Readable; + if (process.env.TURBOPACK) { + Readable = require('node:stream').Readable; + } else if (process.env.__NEXT_BUNDLER === 'Webpack' || process.env.__NEXT_BUNDLER === 'Rspack') { + Readable = __non_webpack_require__('node:stream').Readable; + } else { + Readable = require('node:stream').Readable; + } + if (stream instanceof Readable) { + return stream; + } + return Readable.fromWeb(stream); + } +} +async function nodestreamToUint8Array(stream) { + const chunks = []; + for await (const chunk of webToReadable(stream)){ + chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk); + } + return Buffer.concat(chunks); +} +async function streamToUint8Array(stream) { + if (process.env.NEXT_RUNTIME === 'edge') { + // Edge runtime always uses web streams + return webstreamToUint8Array(stream); + } else { + let Readable; + if (process.env.TURBOPACK) { + Readable = require('node:stream').Readable; + } else if (process.env.__NEXT_BUNDLER === 'Webpack' || process.env.__NEXT_BUNDLER === 'Rspack') { + Readable = __non_webpack_require__('node:stream').Readable; + } else { + Readable = require('node:stream').Readable; + } + if (stream instanceof Readable) { + return nodestreamToUint8Array(stream); + } + return webstreamToUint8Array(stream); + } +} +async function streamToBuffer(stream) { + return Buffer.concat(await streamToChunks(stream)); +} +async function streamToString(stream, signal) { + const decoder = new TextDecoder('utf-8', { + fatal: true + }); + let string = ''; + for await (const chunk of stream){ + if (signal == null ? void 0 : signal.aborted) { + return string; + } + string += decoder.decode(chunk, { + stream: true + }); + } + string += decoder.decode(); + return string; +} +function createBufferedTransformStream(options = {}) { + const { maxBufferByteLength = Infinity } = options; + let bufferedChunks = []; + let bufferByteLength = 0; + let pending; + const flush = (controller)=>{ + try { + if (bufferedChunks.length === 0) { + return; + } + const chunk = new Uint8Array(bufferByteLength); + let copiedBytes = 0; + for(let i = 0; i < bufferedChunks.length; i++){ + const bufferedChunk = bufferedChunks[i]; + chunk.set(bufferedChunk, copiedBytes); + copiedBytes += bufferedChunk.byteLength; + } + // We just wrote all the buffered chunks so we need to reset the bufferedChunks array + // and our bufferByteLength to prepare for the next round of buffered chunks + bufferedChunks.length = 0; + bufferByteLength = 0; + controller.enqueue(chunk); + } catch { + // If an error occurs while enqueuing, it can't be due to this + // transformer. It's most likely caused by the controller having been + // errored (for example, if the stream was cancelled). + } + }; + const scheduleFlush = (controller)=>{ + if (pending) { + return; + } + const detached = (0, _promisewithresolvers.createPromiseWithResolvers)(); + pending = detached; + (0, _scheduler.scheduleImmediate)(()=>{ + try { + flush(controller); + } finally{ + pending = undefined; + detached.resolve(); + } + }); + }; + return new TransformStream({ + transform (chunk, controller) { + // Combine the previous buffer with the new chunk. + bufferedChunks.push(chunk); + bufferByteLength += chunk.byteLength; + if (bufferByteLength >= maxBufferByteLength) { + flush(controller); + } else { + scheduleFlush(controller); + } + }, + flush () { + return pending == null ? void 0 : pending.promise; + } + }); +} +function renderToInitialFizzStream({ ReactDOMServer, element, streamOptions }) { + return (0, _tracer.getTracer)().trace(_constants.AppRenderSpan.renderToReadableStream, async ()=>ReactDOMServer.renderToReadableStream(element, streamOptions)); +} +function createMetadataTransformStream(insert) { + let chunkIndex = -1; + let isMarkRemoved = false; + return new TransformStream({ + async transform (chunk, controller) { + let iconMarkIndex = -1; + let closedHeadIndex = -1; + chunkIndex++; + if (isMarkRemoved) { + controller.enqueue(chunk); + return; + } + let iconMarkLength = 0; + // Only search for the closed head tag once + if (iconMarkIndex === -1) { + iconMarkIndex = (0, _uint8arrayhelpers.indexOfUint8Array)(chunk, _encodedtags.ENCODED_TAGS.META.ICON_MARK); + if (iconMarkIndex === -1) { + controller.enqueue(chunk); + return; + } else { + // When we found the `` or `>`, checking the next char to ensure we cover both cases. + iconMarkLength = _encodedtags.ENCODED_TAGS.META.ICON_MARK.length; + // Check if next char is /, this is for xml mode. + if (chunk[iconMarkIndex + iconMarkLength] === 47) { + iconMarkLength += 2; + } else { + // The last char is `>` + iconMarkLength++; + } + } + } + // Check if icon mark is inside tag in the first chunk. + if (chunkIndex === 0) { + closedHeadIndex = (0, _uint8arrayhelpers.indexOfUint8Array)(chunk, _encodedtags.ENCODED_TAGS.CLOSED.HEAD); + if (iconMarkIndex !== -1) { + // The mark icon is located in the 1st chunk before the head tag. + // We do not need to insert the script tag in this case because it's in the head. + // Just remove the icon mark from the chunk. + if (iconMarkIndex < closedHeadIndex) { + const replaced = new Uint8Array(chunk.length - iconMarkLength); + // Remove the icon mark from the chunk. + replaced.set(chunk.subarray(0, iconMarkIndex)); + replaced.set(chunk.subarray(iconMarkIndex + iconMarkLength), iconMarkIndex); + chunk = replaced; + } else { + // The icon mark is after the head tag, replace and insert the script tag at that position. + const insertion = await insert(); + const encodedInsertion = encoder.encode(insertion); + const insertionLength = encodedInsertion.length; + const replaced = new Uint8Array(chunk.length - iconMarkLength + insertionLength); + replaced.set(chunk.subarray(0, iconMarkIndex)); + replaced.set(encodedInsertion, iconMarkIndex); + replaced.set(chunk.subarray(iconMarkIndex + iconMarkLength), iconMarkIndex + insertionLength); + chunk = replaced; + } + isMarkRemoved = true; + } + // If there's no icon mark located, it will be handled later when if present in the following chunks. + } else { + // When it's appeared in the following chunks, we'll need to + // remove the mark and then insert the script tag at that position. + const insertion = await insert(); + const encodedInsertion = encoder.encode(insertion); + const insertionLength = encodedInsertion.length; + // Replace the icon mark with the hoist script or empty string. + const replaced = new Uint8Array(chunk.length - iconMarkLength + insertionLength); + // Set the first part of the chunk, before the icon mark. + replaced.set(chunk.subarray(0, iconMarkIndex)); + // Set the insertion after the icon mark. + replaced.set(encodedInsertion, iconMarkIndex); + // Set the rest of the chunk after the icon mark. + replaced.set(chunk.subarray(iconMarkIndex + iconMarkLength), iconMarkIndex + insertionLength); + chunk = replaced; + isMarkRemoved = true; + } + controller.enqueue(chunk); + } + }); +} +function createHeadInsertionTransformStream(insert) { + let inserted = false; + // We need to track if this transform saw any bytes because if it didn't + // we won't want to insert any server HTML at all + let hasBytes = false; + return new TransformStream({ + async transform (chunk, controller) { + hasBytes = true; + const insertion = await insert(); + if (inserted) { + if (insertion) { + const encodedInsertion = encoder.encode(insertion); + controller.enqueue(encodedInsertion); + } + controller.enqueue(chunk); + } else { + // TODO (@Ethan-Arrowood): Replace the generic `indexOfUint8Array` method with something finely tuned for the subset of things actually being checked for. + const index = (0, _uint8arrayhelpers.indexOfUint8Array)(chunk, _encodedtags.ENCODED_TAGS.CLOSED.HEAD); + // In fully static rendering or non PPR rendering cases: + // `/head>` will always be found in the chunk in first chunk rendering. + if (index !== -1) { + if (insertion) { + const encodedInsertion = encoder.encode(insertion); + // Get the total count of the bytes in the chunk and the insertion + // e.g. + // chunk = + // insertion = + // output = [ ] + const insertedHeadContent = new Uint8Array(chunk.length + encodedInsertion.length); + // Append the first part of the chunk, before the head tag + insertedHeadContent.set(chunk.slice(0, index)); + // Append the server inserted content + insertedHeadContent.set(encodedInsertion, index); + // Append the rest of the chunk + insertedHeadContent.set(chunk.slice(index), index + encodedInsertion.length); + controller.enqueue(insertedHeadContent); + } else { + controller.enqueue(chunk); + } + inserted = true; + } else { + // This will happens in PPR rendering during next start, when the page is partially rendered. + // When the page resumes, the head tag will be found in the middle of the chunk. + // Where we just need to append the insertion and chunk to the current stream. + // e.g. + // PPR-static: ... [ resume content ] + // PPR-resume: [ insertion ] [ rest content ] + if (insertion) { + controller.enqueue(encoder.encode(insertion)); + } + controller.enqueue(chunk); + inserted = true; + } + } + }, + async flush (controller) { + // Check before closing if there's anything remaining to insert. + if (hasBytes) { + const insertion = await insert(); + if (insertion) { + controller.enqueue(encoder.encode(insertion)); + } + } + } + }); +} +async function createClientResumeScriptInsertionTransformStream() { + const segmentPath = '/_full'; + const cacheBustingHeader = await (0, _cachebustingsearchparam.computeCacheBustingSearchParam)('1', '/_full', undefined, undefined // headers[NEXT_URL] + ); + const searchStr = `${_approuterheaders.NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}`; + const NEXT_CLIENT_RESUME_SCRIPT = ``; + let didAlreadyInsert = false; + return new TransformStream({ + transform (chunk, controller) { + if (didAlreadyInsert) { + // Already inserted the script into the head. Pass through. + controller.enqueue(chunk); + return; + } + // TODO (@Ethan-Arrowood): Replace the generic `indexOfUint8Array` method with something finely tuned for the subset of things actually being checked for. + const headClosingTagIndex = (0, _uint8arrayhelpers.indexOfUint8Array)(chunk, _encodedtags.ENCODED_TAGS.CLOSED.HEAD); + if (headClosingTagIndex === -1) { + // In fully static rendering or non PPR rendering cases: + // `/head>` will always be found in the chunk in first chunk rendering. + controller.enqueue(chunk); + return; + } + const encodedInsertion = encoder.encode(NEXT_CLIENT_RESUME_SCRIPT); + // Get the total count of the bytes in the chunk and the insertion + // e.g. + // chunk = + // insertion = + // output = [ ] + const insertedHeadContent = new Uint8Array(chunk.length + encodedInsertion.length); + // Append the first part of the chunk, before the head tag + insertedHeadContent.set(chunk.slice(0, headClosingTagIndex)); + // Append the server inserted content + insertedHeadContent.set(encodedInsertion, headClosingTagIndex); + // Append the rest of the chunk + insertedHeadContent.set(chunk.slice(headClosingTagIndex), headClosingTagIndex + encodedInsertion.length); + controller.enqueue(insertedHeadContent); + didAlreadyInsert = true; + } + }); +} +function createDeferredSuffixStream(suffix) { + let flushed = false; + let pending; + const flush = (controller)=>{ + const detached = (0, _promisewithresolvers.createPromiseWithResolvers)(); + pending = detached; + (0, _scheduler.scheduleImmediate)(()=>{ + try { + controller.enqueue(encoder.encode(suffix)); + } catch { + // If an error occurs while enqueuing it can't be due to this + // transformers fault. It's likely due to the controller being + // errored due to the stream being cancelled. + } finally{ + pending = undefined; + detached.resolve(); + } + }); + }; + return new TransformStream({ + transform (chunk, controller) { + controller.enqueue(chunk); + // If we've already flushed, we're done. + if (flushed) return; + // Schedule the flush to happen. + flushed = true; + flush(controller); + }, + flush (controller) { + if (pending) return pending.promise; + if (flushed) return; + // Flush now. + controller.enqueue(encoder.encode(suffix)); + } + }); +} +function createFlightDataInjectionTransformStream(stream, delayDataUntilFirstHtmlChunk) { + let htmlStreamFinished = false; + let pull = null; + let donePulling = false; + function startOrContinuePulling(controller) { + if (!pull) { + pull = startPulling(controller); + } + return pull; + } + async function startPulling(controller) { + const reader = stream.getReader(); + if (delayDataUntilFirstHtmlChunk) { + // NOTE: streaming flush + // We are buffering here for the inlined data stream because the + // "shell" stream might be chunkenized again by the underlying stream + // implementation, e.g. with a specific high-water mark. To ensure it's + // the safe timing to pipe the data stream, this extra tick is + // necessary. + // We don't start reading until we've left the current Task to ensure + // that it's inserted after flushing the shell. Note that this implementation + // might get stale if impl details of Fizz change in the future. + await (0, _scheduler.atLeastOneTask)(); + } + try { + while(true){ + const { done, value } = await reader.read(); + if (done) { + donePulling = true; + return; + } + // We want to prioritize HTML over RSC data. + // The SSR render is based on the same RSC stream, so when we get a new RSC chunk, + // we're likely to produce an HTML chunk as well, so give it a chance to flush first. + if (!delayDataUntilFirstHtmlChunk && !htmlStreamFinished) { + await (0, _scheduler.atLeastOneTask)(); + } + controller.enqueue(value); + } + } catch (err) { + controller.error(err); + } + } + return new TransformStream({ + start (controller) { + if (!delayDataUntilFirstHtmlChunk) { + startOrContinuePulling(controller); + } + }, + transform (chunk, controller) { + controller.enqueue(chunk); + // Start the streaming if it hasn't already been started yet. + if (delayDataUntilFirstHtmlChunk) { + startOrContinuePulling(controller); + } + }, + flush (controller) { + htmlStreamFinished = true; + if (donePulling) { + return; + } + return startOrContinuePulling(controller); + } + }); +} +const CLOSE_TAG = ''; +function createMoveSuffixStream() { + let foundSuffix = false; + return new TransformStream({ + transform (chunk, controller) { + if (foundSuffix) { + return controller.enqueue(chunk); + } + const index = (0, _uint8arrayhelpers.indexOfUint8Array)(chunk, _encodedtags.ENCODED_TAGS.CLOSED.BODY_AND_HTML); + if (index > -1) { + foundSuffix = true; + // If the whole chunk is the suffix, then don't write anything, it will + // be written in the flush. + if (chunk.length === _encodedtags.ENCODED_TAGS.CLOSED.BODY_AND_HTML.length) { + return; + } + // Write out the part before the suffix. + const before = chunk.slice(0, index); + controller.enqueue(before); + // In the case where the suffix is in the middle of the chunk, we need + // to split the chunk into two parts. + if (chunk.length > _encodedtags.ENCODED_TAGS.CLOSED.BODY_AND_HTML.length + index) { + // Write out the part after the suffix. + const after = chunk.slice(index + _encodedtags.ENCODED_TAGS.CLOSED.BODY_AND_HTML.length); + controller.enqueue(after); + } + } else { + controller.enqueue(chunk); + } + }, + flush (controller) { + // Even if we didn't find the suffix, the HTML is not valid if we don't + // add it, so insert it at the end. + controller.enqueue(_encodedtags.ENCODED_TAGS.CLOSED.BODY_AND_HTML); + } + }); +} +function createStripDocumentClosingTagsTransform() { + return new TransformStream({ + transform (chunk, controller) { + // We rely on the assumption that chunks will never break across a code unit. + // This is reasonable because we currently concat all of React's output from a single + // flush into one chunk before streaming it forward which means the chunk will represent + // a single coherent utf-8 string. This is not safe to use if we change our streaming to no + // longer do this large buffered chunk + if ((0, _uint8arrayhelpers.isEquivalentUint8Arrays)(chunk, _encodedtags.ENCODED_TAGS.CLOSED.BODY_AND_HTML) || (0, _uint8arrayhelpers.isEquivalentUint8Arrays)(chunk, _encodedtags.ENCODED_TAGS.CLOSED.BODY) || (0, _uint8arrayhelpers.isEquivalentUint8Arrays)(chunk, _encodedtags.ENCODED_TAGS.CLOSED.HTML)) { + // the entire chunk is the closing tags; return without enqueueing anything. + return; + } + // We assume these tags will go at together at the end of the document and that + // they won't appear anywhere else in the document. This is not really a safe assumption + // but until we revamp our streaming infra this is a performant way to string the tags + chunk = (0, _uint8arrayhelpers.removeFromUint8Array)(chunk, _encodedtags.ENCODED_TAGS.CLOSED.BODY); + chunk = (0, _uint8arrayhelpers.removeFromUint8Array)(chunk, _encodedtags.ENCODED_TAGS.CLOSED.HTML); + controller.enqueue(chunk); + } + }); +} +function createHtmlDataDplIdTransformStream(dplId) { + let didTransform = false; + return new TransformStream({ + transform (chunk, controller) { + if (didTransform) { + controller.enqueue(chunk); + return; + } + const htmlTagIndex = (0, _uint8arrayhelpers.indexOfUint8Array)(chunk, _encodedtags.ENCODED_TAGS.OPENING.HTML); + if (htmlTagIndex === -1) { + controller.enqueue(chunk); + return; + } + // Insert the data-dpl-id attribute right after " -1) { + foundHtml = true; + } + if (!foundBody && (0, _uint8arrayhelpers.indexOfUint8Array)(chunk, _encodedtags.ENCODED_TAGS.OPENING.BODY) > -1) { + foundBody = true; + } + controller.enqueue(chunk); + }, + flush (controller) { + const missingTags = []; + if (!foundHtml) missingTags.push('html'); + if (!foundBody) missingTags.push('body'); + if (!missingTags.length) return; + controller.enqueue(encoder.encode(` + + `)); + } + }); +} +function chainTransformers(readable, transformers) { + let stream = readable; + for (const transformer of transformers){ + if (!transformer) continue; + stream = stream.pipeThrough(transformer); + } + return stream; +} +async function continueFizzStream(renderStream, { suffix, inlinedDataStream, waitForAllReady, deploymentId, getServerInsertedHTML, getServerInsertedMetadata, validateRootLayout }) { + // Suffix itself might contain close tags at the end, so we need to split it. + const suffixUnclosed = suffix ? suffix.split(CLOSE_TAG, 1)[0] : null; + if (waitForAllReady) { + // Wait for all Suspense boundaries to resolve before continuing. + await renderStream.allReady; + } else { + // Otherwise, we want to make sure Fizz is done with all microtasky work + // before we start pulling the stream and cause a flush. + await (0, _scheduler.waitAtLeastOneReactRenderTask)(); + } + return chainTransformers(renderStream, [ + // Buffer everything to avoid flushing too frequently + createBufferedTransformStream(), + // Insert data-dpl-id attribute on the html tag + deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null, + // Transform metadata + createMetadataTransformStream(getServerInsertedMetadata), + // Insert suffix content + suffixUnclosed != null && suffixUnclosed.length > 0 ? createDeferredSuffixStream(suffixUnclosed) : null, + // Insert the inlined data (Flight data, form state, etc.) stream into the HTML + inlinedDataStream ? createFlightDataInjectionTransformStream(inlinedDataStream, true) : null, + // Validate the root layout for missing html or body tags + validateRootLayout ? createRootLayoutValidatorStream() : null, + // Close tags should always be deferred to the end + createMoveSuffixStream(), + // Special head insertions + // TODO-APP: Insert server side html to end of head in app layout rendering, to avoid + // hydration errors. Remove this once it's ready to be handled by react itself. + createHeadInsertionTransformStream(getServerInsertedHTML) + ]); +} +async function continueDynamicPrerender(prerenderStream, { getServerInsertedHTML, getServerInsertedMetadata, deploymentId }) { + return chainTransformers(prerenderStream, [ + // Buffer everything to avoid flushing too frequently + createBufferedTransformStream(), + createStripDocumentClosingTagsTransform(), + // Insert data-dpl-id attribute on the html tag + deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null, + // Insert generated tags to head + createHeadInsertionTransformStream(getServerInsertedHTML), + // Transform metadata + createMetadataTransformStream(getServerInsertedMetadata) + ]); +} +async function continueStaticPrerender(prerenderStream, { inlinedDataStream, getServerInsertedHTML, getServerInsertedMetadata, deploymentId }) { + return chainTransformers(prerenderStream, [ + // Buffer everything to avoid flushing too frequently + createBufferedTransformStream(), + // Add build id comment to start of the HTML document (in export mode) + // Insert data-dpl-id attribute on the html tag + deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null, + // Insert generated tags to head + createHeadInsertionTransformStream(getServerInsertedHTML), + // Transform metadata + createMetadataTransformStream(getServerInsertedMetadata), + // Insert the inlined data (Flight data, form state, etc.) stream into the HTML + createFlightDataInjectionTransformStream(inlinedDataStream, true), + // Close tags should always be deferred to the end + createMoveSuffixStream() + ]); +} +async function continueStaticFallbackPrerender(prerenderStream, { inlinedDataStream, getServerInsertedHTML, getServerInsertedMetadata, deploymentId }) { + // Same as `continueStaticPrerender`, but also inserts an additional script + // to instruct the client to start fetching the hydration data as early + // as possible. + return chainTransformers(prerenderStream, [ + // Buffer everything to avoid flushing too frequently + createBufferedTransformStream(), + // Insert data-dpl-id attribute on the html tag + deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null, + // Insert generated tags to head + createHeadInsertionTransformStream(getServerInsertedHTML), + // Insert the client resume script into the head + await createClientResumeScriptInsertionTransformStream(), + // Transform metadata + createMetadataTransformStream(getServerInsertedMetadata), + // Insert the inlined data (Flight data, form state, etc.) stream into the HTML + createFlightDataInjectionTransformStream(inlinedDataStream, true), + // Close tags should always be deferred to the end + createMoveSuffixStream() + ]); +} +async function continueDynamicHTMLResume(renderStream, { delayDataUntilFirstHtmlChunk, inlinedDataStream, getServerInsertedHTML, getServerInsertedMetadata, deploymentId }) { + return chainTransformers(renderStream, [ + // Buffer everything to avoid flushing too frequently + createBufferedTransformStream(), + // Insert data-dpl-id attribute on the html tag + deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null, + // Insert generated tags to head + createHeadInsertionTransformStream(getServerInsertedHTML), + // Transform metadata + createMetadataTransformStream(getServerInsertedMetadata), + // Insert the inlined data (Flight data, form state, etc.) stream into the HTML + createFlightDataInjectionTransformStream(inlinedDataStream, delayDataUntilFirstHtmlChunk), + // Close tags should always be deferred to the end + createMoveSuffixStream() + ]); +} +function createDocumentClosingStream() { + return streamFromString(CLOSE_TAG); +} +function createRuntimePrefetchTransformStream(sentinel, isPartial, staleTime) { + const enc = new TextEncoder(); + // Search for: [] + // Replace with: [,] + const search = enc.encode(`[${sentinel}]`); + const first = search[0]; + const replace = enc.encode(`[${isPartial},${staleTime}]`); + const searchLen = search.length; + let currentChunk = null; + let found = false; + function processChunk(controller, nextChunk) { + if (found) { + if (nextChunk) { + controller.enqueue(nextChunk); + } + return; + } + if (currentChunk) { + // We can't search past the index that can contain a full match + let exclusiveUpperBound = currentChunk.length - (searchLen - 1); + if (nextChunk) { + // If we have any overflow bytes we can search up to the chunk's final byte + exclusiveUpperBound += Math.min(nextChunk.length, searchLen - 1); + } + if (exclusiveUpperBound < 1) { + // we can't match the current chunk. + controller.enqueue(currentChunk); + currentChunk = nextChunk // advance so we don't process this chunk again + ; + return; + } + let currentIndex = currentChunk.indexOf(first); + // check the current candidate match if it is within the bounds of our search space for the currentChunk + candidateLoop: while(-1 < currentIndex && currentIndex < exclusiveUpperBound){ + // We already know index 0 matches because we used indexOf to find the candidateIndex so we start at index 1 + let matchIndex = 1; + while(matchIndex < searchLen){ + const candidateIndex = currentIndex + matchIndex; + const candidateValue = candidateIndex < currentChunk.length ? currentChunk[candidateIndex] : nextChunk[candidateIndex - currentChunk.length]; + if (candidateValue !== search[matchIndex]) { + // No match, reset and continue the search from the next position + currentIndex = currentChunk.indexOf(first, currentIndex + 1); + continue candidateLoop; + } + matchIndex++; + } + // We found a complete match. currentIndex is our starting point to replace the value. + found = true; + // enqueue everything up to the match + controller.enqueue(currentChunk.subarray(0, currentIndex)); + // enqueue the replacement value + controller.enqueue(replace); + // If there are bytes in the currentChunk after the match enqueue them + if (currentIndex + searchLen < currentChunk.length) { + controller.enqueue(currentChunk.slice(currentIndex + searchLen)); + } + // If we have a next chunk we enqueue it now + if (nextChunk) { + // if replacement spills over to the next chunk we first exclude the replaced bytes + const overflowBytes = currentIndex + searchLen - currentChunk.length; + const truncatedChunk = overflowBytes > 0 ? nextChunk.subarray(overflowBytes) : nextChunk; + controller.enqueue(truncatedChunk); + } + // We are now in found mode and don't need to track currentChunk anymore + currentChunk = null; + return; + } + // No match found in this chunk, emit it and wait for the next one + controller.enqueue(currentChunk); + } + // Advance to the next chunk + currentChunk = nextChunk; + } + return new TransformStream({ + transform (chunk, controller) { + processChunk(controller, chunk); + }, + flush (controller) { + processChunk(controller, null); + } + }); +} + +//# sourceMappingURL=node-web-streams-helper.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/stream-utils/node-web-streams-helper.js.map b/e-commerce/node_modules/next/dist/server/stream-utils/node-web-streams-helper.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c16f0ea951b9d0cd59eb02477904321c17ae812f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/stream-utils/node-web-streams-helper.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/stream-utils/node-web-streams-helper.ts"],"sourcesContent":["import type { ReactDOMServerReadableStream } from 'react-dom/server'\nimport { getTracer } from '../lib/trace/tracer'\nimport { AppRenderSpan } from '../lib/trace/constants'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\nimport {\n scheduleImmediate,\n atLeastOneTask,\n waitAtLeastOneReactRenderTask,\n} from '../../lib/scheduler'\nimport { ENCODED_TAGS } from './encoded-tags'\nimport {\n indexOfUint8Array,\n isEquivalentUint8Arrays,\n removeFromUint8Array,\n} from './uint8array-helpers'\nimport { MISSING_ROOT_TAGS_ERROR } from '../../shared/lib/errors/constants'\nimport {\n RSC_HEADER,\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_RSC_UNION_QUERY,\n} from '../../client/components/app-router-headers'\nimport { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'\nimport type { AnyStream } from '../app-render/stream-ops'\n\nfunction voidCatch() {\n // this catcher is designed to be used with pipeTo where we expect the underlying\n // pipe implementation to forward errors but we don't want the pipeTo promise to reject\n // and be unhandled\n}\n\n// We can share the same encoder instance everywhere\n// Notably we cannot do the same for TextDecoder because it is stateful\n// when handling streaming data\nconst encoder = new TextEncoder()\n\nexport function chainStreams(\n ...streams: ReadableStream[]\n): ReadableStream {\n // If we have no streams, return an empty stream. This behavior is\n // intentional as we're now providing the `RenderResult.EMPTY` value.\n if (streams.length === 0) {\n return new ReadableStream({\n start(controller) {\n controller.close()\n },\n })\n }\n\n // If we only have 1 stream we fast path it by returning just this stream\n if (streams.length === 1) {\n return streams[0]\n }\n\n const { readable, writable } = new TransformStream()\n\n // We always initiate pipeTo immediately. We know we have at least 2 streams\n // so we need to avoid closing the writable when this one finishes.\n let promise = streams[0].pipeTo(writable, { preventClose: true })\n\n let i = 1\n for (; i < streams.length - 1; i++) {\n const nextStream = streams[i]\n promise = promise.then(() =>\n nextStream.pipeTo(writable, { preventClose: true })\n )\n }\n\n // We can omit the length check because we halted before the last stream and there\n // is at least two streams so the lastStream here will always be defined\n const lastStream = streams[i]\n promise = promise.then(() => lastStream.pipeTo(writable))\n\n // Catch any errors from the streams and ignore them, they will be handled\n // by whatever is consuming the readable stream.\n promise.catch(voidCatch)\n\n return readable\n}\n\nexport function streamFromString(str: string): ReadableStream {\n return new ReadableStream({\n start(controller) {\n controller.enqueue(encoder.encode(str))\n controller.close()\n },\n })\n}\n\n/**\n * Creates a stream that delivers `chunk` and then closes.\n *\n * The stream is a default stream, and it has to stay one. A byte stream (`type:\n * 'bytes'`) transfers the buffer of each chunk that it receives, which detaches\n * `chunk`. A caller that keeps `chunk` to serve more than one read, such as an\n * in-memory cache handler, loses the data on the first read.\n *\n * Every reader receives the same `chunk` instance. A reader that modifies it\n * changes what later readers see.\n */\nexport function streamFromBuffer(chunk: Buffer): ReadableStream {\n return new ReadableStream({\n start(controller) {\n controller.enqueue(chunk)\n controller.close()\n },\n })\n}\n\nasync function streamToChunks(\n stream: ReadableStream\n): Promise> {\n const reader = stream.getReader()\n const chunks: Array = []\n\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n break\n }\n\n chunks.push(value)\n }\n\n return chunks\n}\n\nfunction concatUint8Arrays(chunks: Array): Uint8Array {\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0)\n const result = new Uint8Array(totalLength)\n let offset = 0\n for (const chunk of chunks) {\n result.set(chunk, offset)\n offset += chunk.length\n }\n return result\n}\n\nexport async function webstreamToUint8Array(\n stream: ReadableStream\n): Promise {\n return concatUint8Arrays(await streamToChunks(stream))\n}\n\nfunction webToReadable(\n stream: ReadableStream | import('node:stream').Readable\n): import('node:stream').Readable {\n if (process.env.NEXT_RUNTIME === 'edge') {\n throw new Error('webToReadable cannot be used in the edge runtime')\n } else {\n let Readable: typeof import('node:stream').Readable\n if (process.env.TURBOPACK) {\n Readable = (require('node:stream') as typeof import('node:stream'))\n .Readable\n } else if (\n process.env.__NEXT_BUNDLER === 'Webpack' ||\n process.env.__NEXT_BUNDLER === 'Rspack'\n ) {\n Readable = (\n __non_webpack_require__('node:stream') as typeof import('node:stream')\n ).Readable\n } else {\n Readable = (require('node:stream') as typeof import('node:stream'))\n .Readable\n }\n if (stream instanceof Readable) {\n return stream\n }\n return Readable.fromWeb(stream as import('stream/web').ReadableStream)\n }\n}\n\nexport async function nodestreamToUint8Array(\n stream: AnyStream\n): Promise {\n const chunks: Buffer[] = []\n for await (const chunk of webToReadable(stream)) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)\n }\n return Buffer.concat(chunks)\n}\n\nexport async function streamToUint8Array(stream: AnyStream) {\n if (process.env.NEXT_RUNTIME === 'edge') {\n // Edge runtime always uses web streams\n return webstreamToUint8Array(stream as ReadableStream)\n } else {\n let Readable: typeof import('node:stream').Readable\n if (process.env.TURBOPACK) {\n Readable = (require('node:stream') as typeof import('node:stream'))\n .Readable\n } else if (\n process.env.__NEXT_BUNDLER === 'Webpack' ||\n process.env.__NEXT_BUNDLER === 'Rspack'\n ) {\n Readable = (\n __non_webpack_require__('node:stream') as typeof import('node:stream')\n ).Readable\n } else {\n Readable = (require('node:stream') as typeof import('node:stream'))\n .Readable\n }\n\n if (stream instanceof Readable) {\n return nodestreamToUint8Array(stream)\n }\n\n return webstreamToUint8Array(stream)\n }\n}\n\nexport async function streamToBuffer(\n stream: ReadableStream\n): Promise {\n return Buffer.concat(await streamToChunks(stream))\n}\n\nexport async function streamToString(\n stream: ReadableStream,\n signal?: AbortSignal\n): Promise {\n const decoder = new TextDecoder('utf-8', { fatal: true })\n let string = ''\n\n for await (const chunk of stream) {\n if (signal?.aborted) {\n return string\n }\n\n string += decoder.decode(chunk, { stream: true })\n }\n\n string += decoder.decode()\n\n return string\n}\n\nexport type BufferedTransformOptions = {\n /**\n * Flush synchronously once the buffer reaches this many bytes.\n */\n readonly maxBufferByteLength?: number\n}\n\nexport function createBufferedTransformStream(\n options: BufferedTransformOptions = {}\n): TransformStream {\n const { maxBufferByteLength = Infinity } = options\n\n let bufferedChunks: Array = []\n let bufferByteLength: number = 0\n let pending: PromiseWithResolvers | undefined\n\n const flush = (controller: TransformStreamDefaultController) => {\n try {\n if (bufferedChunks.length === 0) {\n return\n }\n\n const chunk = new Uint8Array(bufferByteLength)\n let copiedBytes = 0\n\n for (let i = 0; i < bufferedChunks.length; i++) {\n const bufferedChunk = bufferedChunks[i]\n chunk.set(bufferedChunk, copiedBytes)\n copiedBytes += bufferedChunk.byteLength\n }\n // We just wrote all the buffered chunks so we need to reset the bufferedChunks array\n // and our bufferByteLength to prepare for the next round of buffered chunks\n bufferedChunks.length = 0\n bufferByteLength = 0\n controller.enqueue(chunk)\n } catch {\n // If an error occurs while enqueuing, it can't be due to this\n // transformer. It's most likely caused by the controller having been\n // errored (for example, if the stream was cancelled).\n }\n }\n\n const scheduleFlush = (controller: TransformStreamDefaultController) => {\n if (pending) {\n return\n }\n\n const detached = createPromiseWithResolvers()\n pending = detached\n\n scheduleImmediate(() => {\n try {\n flush(controller)\n } finally {\n pending = undefined\n detached.resolve()\n }\n })\n }\n\n return new TransformStream({\n transform(chunk, controller) {\n // Combine the previous buffer with the new chunk.\n bufferedChunks.push(chunk)\n bufferByteLength += chunk.byteLength\n\n if (bufferByteLength >= maxBufferByteLength) {\n flush(controller)\n } else {\n scheduleFlush(controller)\n }\n },\n flush() {\n return pending?.promise\n },\n })\n}\n\n// TODO this is currently unused but once we add proper output:export support, it needs to be\n// revisited. See https://github.com/vercel/next.js/pull/89478 for more details\n//\n// function createPrefetchCommentStream(\n// isBuildTimePrerendering: boolean,\n// buildId: string\n// ): TransformStream {\n// // Insert an extra comment at the beginning of the HTML document. This must\n// // come after the DOCTYPE, which is inserted by React.\n// //\n// // The first chunk sent by React will contain the doctype. After that, we can\n// // pass through the rest of the chunks as-is.\n// let didTransformFirstChunk = false\n// return new TransformStream({\n// transform(chunk, controller) {\n// if (isBuildTimePrerendering && !didTransformFirstChunk) {\n// didTransformFirstChunk = true\n// const decoder = new TextDecoder('utf-8', { fatal: true })\n// const chunkStr = decoder.decode(chunk, {\n// stream: true,\n// })\n// const updatedChunkStr = insertBuildIdComment(chunkStr, buildId)\n// controller.enqueue(encoder.encode(updatedChunkStr))\n// return\n// }\n// controller.enqueue(chunk)\n// },\n// })\n// }\n\nexport function renderToInitialFizzStream({\n ReactDOMServer,\n element,\n streamOptions,\n}: {\n ReactDOMServer: {\n renderToReadableStream: typeof import('react-dom/server').renderToReadableStream\n }\n element: React.ReactElement\n streamOptions?: Parameters[1]\n}): Promise {\n return getTracer().trace(AppRenderSpan.renderToReadableStream, async () =>\n ReactDOMServer.renderToReadableStream(element, streamOptions)\n )\n}\n\nexport function createMetadataTransformStream(\n insert: () => Promise | string\n): TransformStream {\n let chunkIndex = -1\n let isMarkRemoved = false\n\n return new TransformStream({\n async transform(chunk, controller) {\n let iconMarkIndex = -1\n let closedHeadIndex = -1\n chunkIndex++\n\n if (isMarkRemoved) {\n controller.enqueue(chunk)\n return\n }\n let iconMarkLength = 0\n // Only search for the closed head tag once\n if (iconMarkIndex === -1) {\n iconMarkIndex = indexOfUint8Array(chunk, ENCODED_TAGS.META.ICON_MARK)\n if (iconMarkIndex === -1) {\n controller.enqueue(chunk)\n return\n } else {\n // When we found the `` or `>`, checking the next char to ensure we cover both cases.\n iconMarkLength = ENCODED_TAGS.META.ICON_MARK.length\n // Check if next char is /, this is for xml mode.\n if (chunk[iconMarkIndex + iconMarkLength] === 47) {\n iconMarkLength += 2\n } else {\n // The last char is `>`\n iconMarkLength++\n }\n }\n }\n\n // Check if icon mark is inside tag in the first chunk.\n if (chunkIndex === 0) {\n closedHeadIndex = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)\n if (iconMarkIndex !== -1) {\n // The mark icon is located in the 1st chunk before the head tag.\n // We do not need to insert the script tag in this case because it's in the head.\n // Just remove the icon mark from the chunk.\n if (iconMarkIndex < closedHeadIndex) {\n const replaced = new Uint8Array(chunk.length - iconMarkLength)\n\n // Remove the icon mark from the chunk.\n replaced.set(chunk.subarray(0, iconMarkIndex))\n replaced.set(\n chunk.subarray(iconMarkIndex + iconMarkLength),\n iconMarkIndex\n )\n chunk = replaced\n } else {\n // The icon mark is after the head tag, replace and insert the script tag at that position.\n const insertion = await insert()\n const encodedInsertion = encoder.encode(insertion)\n const insertionLength = encodedInsertion.length\n const replaced = new Uint8Array(\n chunk.length - iconMarkLength + insertionLength\n )\n replaced.set(chunk.subarray(0, iconMarkIndex))\n replaced.set(encodedInsertion, iconMarkIndex)\n replaced.set(\n chunk.subarray(iconMarkIndex + iconMarkLength),\n iconMarkIndex + insertionLength\n )\n chunk = replaced\n }\n isMarkRemoved = true\n }\n // If there's no icon mark located, it will be handled later when if present in the following chunks.\n } else {\n // When it's appeared in the following chunks, we'll need to\n // remove the mark and then insert the script tag at that position.\n const insertion = await insert()\n const encodedInsertion = encoder.encode(insertion)\n const insertionLength = encodedInsertion.length\n // Replace the icon mark with the hoist script or empty string.\n const replaced = new Uint8Array(\n chunk.length - iconMarkLength + insertionLength\n )\n // Set the first part of the chunk, before the icon mark.\n replaced.set(chunk.subarray(0, iconMarkIndex))\n // Set the insertion after the icon mark.\n replaced.set(encodedInsertion, iconMarkIndex)\n\n // Set the rest of the chunk after the icon mark.\n replaced.set(\n chunk.subarray(iconMarkIndex + iconMarkLength),\n iconMarkIndex + insertionLength\n )\n chunk = replaced\n isMarkRemoved = true\n }\n controller.enqueue(chunk)\n },\n })\n}\n\nexport function createHeadInsertionTransformStream(\n insert: () => Promise\n): TransformStream {\n let inserted = false\n\n // We need to track if this transform saw any bytes because if it didn't\n // we won't want to insert any server HTML at all\n let hasBytes = false\n\n return new TransformStream({\n async transform(chunk, controller) {\n hasBytes = true\n\n const insertion = await insert()\n if (inserted) {\n if (insertion) {\n const encodedInsertion = encoder.encode(insertion)\n controller.enqueue(encodedInsertion)\n }\n controller.enqueue(chunk)\n } else {\n // TODO (@Ethan-Arrowood): Replace the generic `indexOfUint8Array` method with something finely tuned for the subset of things actually being checked for.\n const index = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)\n // In fully static rendering or non PPR rendering cases:\n // `/head>` will always be found in the chunk in first chunk rendering.\n if (index !== -1) {\n if (insertion) {\n const encodedInsertion = encoder.encode(insertion)\n // Get the total count of the bytes in the chunk and the insertion\n // e.g.\n // chunk = \n // insertion = \n // output = [ ] \n const insertedHeadContent = new Uint8Array(\n chunk.length + encodedInsertion.length\n )\n // Append the first part of the chunk, before the head tag\n insertedHeadContent.set(chunk.slice(0, index))\n // Append the server inserted content\n insertedHeadContent.set(encodedInsertion, index)\n // Append the rest of the chunk\n insertedHeadContent.set(\n chunk.slice(index),\n index + encodedInsertion.length\n )\n controller.enqueue(insertedHeadContent)\n } else {\n controller.enqueue(chunk)\n }\n inserted = true\n } else {\n // This will happens in PPR rendering during next start, when the page is partially rendered.\n // When the page resumes, the head tag will be found in the middle of the chunk.\n // Where we just need to append the insertion and chunk to the current stream.\n // e.g.\n // PPR-static: ... [ resume content ] \n // PPR-resume: [ insertion ] [ rest content ]\n if (insertion) {\n controller.enqueue(encoder.encode(insertion))\n }\n controller.enqueue(chunk)\n inserted = true\n }\n }\n },\n async flush(controller) {\n // Check before closing if there's anything remaining to insert.\n if (hasBytes) {\n const insertion = await insert()\n if (insertion) {\n controller.enqueue(encoder.encode(insertion))\n }\n }\n },\n })\n}\n\nasync function createClientResumeScriptInsertionTransformStream(): Promise<\n TransformStream\n> {\n const segmentPath = '/_full'\n const cacheBustingHeader = await computeCacheBustingSearchParam(\n '1', // headers[NEXT_ROUTER_PREFETCH_HEADER]\n '/_full', // headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]\n undefined, // headers[NEXT_ROUTER_STATE_TREE_HEADER]\n undefined // headers[NEXT_URL]\n )\n const searchStr = `${NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}`\n const NEXT_CLIENT_RESUME_SCRIPT = ``\n\n let didAlreadyInsert = false\n return new TransformStream({\n transform(chunk, controller) {\n if (didAlreadyInsert) {\n // Already inserted the script into the head. Pass through.\n controller.enqueue(chunk)\n return\n }\n // TODO (@Ethan-Arrowood): Replace the generic `indexOfUint8Array` method with something finely tuned for the subset of things actually being checked for.\n const headClosingTagIndex = indexOfUint8Array(\n chunk,\n ENCODED_TAGS.CLOSED.HEAD\n )\n\n if (headClosingTagIndex === -1) {\n // In fully static rendering or non PPR rendering cases:\n // `/head>` will always be found in the chunk in first chunk rendering.\n controller.enqueue(chunk)\n return\n }\n\n const encodedInsertion = encoder.encode(NEXT_CLIENT_RESUME_SCRIPT)\n // Get the total count of the bytes in the chunk and the insertion\n // e.g.\n // chunk = \n // insertion = \n // output = [ ] \n const insertedHeadContent = new Uint8Array(\n chunk.length + encodedInsertion.length\n )\n // Append the first part of the chunk, before the head tag\n insertedHeadContent.set(chunk.slice(0, headClosingTagIndex))\n // Append the server inserted content\n insertedHeadContent.set(encodedInsertion, headClosingTagIndex)\n // Append the rest of the chunk\n insertedHeadContent.set(\n chunk.slice(headClosingTagIndex),\n headClosingTagIndex + encodedInsertion.length\n )\n\n controller.enqueue(insertedHeadContent)\n didAlreadyInsert = true\n },\n })\n}\n\n// Suffix after main body content - scripts before ,\n// but wait for the major chunks to be enqueued.\nexport function createDeferredSuffixStream(\n suffix: string\n): TransformStream {\n let flushed = false\n let pending: PromiseWithResolvers | undefined\n\n const flush = (controller: TransformStreamDefaultController) => {\n const detached = createPromiseWithResolvers()\n pending = detached\n\n scheduleImmediate(() => {\n try {\n controller.enqueue(encoder.encode(suffix))\n } catch {\n // If an error occurs while enqueuing it can't be due to this\n // transformers fault. It's likely due to the controller being\n // errored due to the stream being cancelled.\n } finally {\n pending = undefined\n detached.resolve()\n }\n })\n }\n\n return new TransformStream({\n transform(chunk, controller) {\n controller.enqueue(chunk)\n\n // If we've already flushed, we're done.\n if (flushed) return\n\n // Schedule the flush to happen.\n flushed = true\n flush(controller)\n },\n flush(controller) {\n if (pending) return pending.promise\n if (flushed) return\n\n // Flush now.\n controller.enqueue(encoder.encode(suffix))\n },\n })\n}\n\nexport function createFlightDataInjectionTransformStream(\n stream: ReadableStream,\n delayDataUntilFirstHtmlChunk: boolean\n): TransformStream {\n let htmlStreamFinished = false\n\n let pull: Promise | null = null\n let donePulling = false\n\n function startOrContinuePulling(\n controller: TransformStreamDefaultController\n ) {\n if (!pull) {\n pull = startPulling(controller)\n }\n return pull\n }\n\n async function startPulling(controller: TransformStreamDefaultController) {\n const reader = stream.getReader()\n\n if (delayDataUntilFirstHtmlChunk) {\n // NOTE: streaming flush\n // We are buffering here for the inlined data stream because the\n // \"shell\" stream might be chunkenized again by the underlying stream\n // implementation, e.g. with a specific high-water mark. To ensure it's\n // the safe timing to pipe the data stream, this extra tick is\n // necessary.\n\n // We don't start reading until we've left the current Task to ensure\n // that it's inserted after flushing the shell. Note that this implementation\n // might get stale if impl details of Fizz change in the future.\n await atLeastOneTask()\n }\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n donePulling = true\n return\n }\n\n // We want to prioritize HTML over RSC data.\n // The SSR render is based on the same RSC stream, so when we get a new RSC chunk,\n // we're likely to produce an HTML chunk as well, so give it a chance to flush first.\n if (!delayDataUntilFirstHtmlChunk && !htmlStreamFinished) {\n await atLeastOneTask()\n }\n controller.enqueue(value)\n }\n } catch (err) {\n controller.error(err)\n }\n }\n\n return new TransformStream({\n start(controller) {\n if (!delayDataUntilFirstHtmlChunk) {\n startOrContinuePulling(controller)\n }\n },\n transform(chunk, controller) {\n controller.enqueue(chunk)\n\n // Start the streaming if it hasn't already been started yet.\n if (delayDataUntilFirstHtmlChunk) {\n startOrContinuePulling(controller)\n }\n },\n flush(controller) {\n htmlStreamFinished = true\n if (donePulling) {\n return\n }\n return startOrContinuePulling(controller)\n },\n })\n}\n\nexport const CLOSE_TAG = ''\n\n/**\n * This transform stream moves the suffix to the end of the stream, so results\n * like `` will be transformed to\n * ``.\n */\nexport function createMoveSuffixStream(): TransformStream<\n Uint8Array,\n Uint8Array\n> {\n let foundSuffix = false\n\n return new TransformStream({\n transform(chunk, controller) {\n if (foundSuffix) {\n return controller.enqueue(chunk)\n }\n\n const index = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.BODY_AND_HTML)\n if (index > -1) {\n foundSuffix = true\n\n // If the whole chunk is the suffix, then don't write anything, it will\n // be written in the flush.\n if (chunk.length === ENCODED_TAGS.CLOSED.BODY_AND_HTML.length) {\n return\n }\n\n // Write out the part before the suffix.\n const before = chunk.slice(0, index)\n controller.enqueue(before)\n\n // In the case where the suffix is in the middle of the chunk, we need\n // to split the chunk into two parts.\n if (chunk.length > ENCODED_TAGS.CLOSED.BODY_AND_HTML.length + index) {\n // Write out the part after the suffix.\n const after = chunk.slice(\n index + ENCODED_TAGS.CLOSED.BODY_AND_HTML.length\n )\n controller.enqueue(after)\n }\n } else {\n controller.enqueue(chunk)\n }\n },\n flush(controller) {\n // Even if we didn't find the suffix, the HTML is not valid if we don't\n // add it, so insert it at the end.\n controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)\n },\n })\n}\n\nfunction createStripDocumentClosingTagsTransform(): TransformStream<\n Uint8Array,\n Uint8Array\n> {\n return new TransformStream({\n transform(chunk, controller) {\n // We rely on the assumption that chunks will never break across a code unit.\n // This is reasonable because we currently concat all of React's output from a single\n // flush into one chunk before streaming it forward which means the chunk will represent\n // a single coherent utf-8 string. This is not safe to use if we change our streaming to no\n // longer do this large buffered chunk\n if (\n isEquivalentUint8Arrays(chunk, ENCODED_TAGS.CLOSED.BODY_AND_HTML) ||\n isEquivalentUint8Arrays(chunk, ENCODED_TAGS.CLOSED.BODY) ||\n isEquivalentUint8Arrays(chunk, ENCODED_TAGS.CLOSED.HTML)\n ) {\n // the entire chunk is the closing tags; return without enqueueing anything.\n return\n }\n\n // We assume these tags will go at together at the end of the document and that\n // they won't appear anywhere else in the document. This is not really a safe assumption\n // but until we revamp our streaming infra this is a performant way to string the tags\n chunk = removeFromUint8Array(chunk, ENCODED_TAGS.CLOSED.BODY)\n chunk = removeFromUint8Array(chunk, ENCODED_TAGS.CLOSED.HTML)\n\n controller.enqueue(chunk)\n },\n })\n}\n\nexport function createHtmlDataDplIdTransformStream(\n dplId: string\n): TransformStream {\n let didTransform = false\n\n return new TransformStream({\n transform(chunk, controller) {\n if (didTransform) {\n controller.enqueue(chunk)\n return\n }\n\n const htmlTagIndex = indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HTML)\n if (htmlTagIndex === -1) {\n controller.enqueue(chunk)\n return\n }\n\n // Insert the data-dpl-id attribute right after \" {\n let foundHtml = false\n let foundBody = false\n return new TransformStream({\n async transform(chunk, controller) {\n // Peek into the streamed chunk to see if the tags are present.\n if (\n !foundHtml &&\n indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HTML) > -1\n ) {\n foundHtml = true\n }\n\n if (\n !foundBody &&\n indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.BODY) > -1\n ) {\n foundBody = true\n }\n\n controller.enqueue(chunk)\n },\n flush(controller) {\n const missingTags: ('html' | 'body')[] = []\n if (!foundHtml) missingTags.push('html')\n if (!foundBody) missingTags.push('body')\n\n if (!missingTags.length) return\n\n controller.enqueue(\n encoder.encode(\n `\n `<${c}>`)\n .join(\n missingTags.length > 1 ? ' and ' : ''\n )} tags in the root layout.\\nRead more at https://nextjs.org/docs/messages/missing-root-layout-tags\"\n data-next-error-digest=\"${MISSING_ROOT_TAGS_ERROR}\"\n data-next-error-stack=\"\"\n >\n `\n )\n )\n },\n })\n}\n\nexport function chainTransformers(\n readable: ReadableStream,\n transformers: ReadonlyArray | null>\n): ReadableStream {\n let stream = readable\n for (const transformer of transformers) {\n if (!transformer) continue\n\n stream = stream.pipeThrough(transformer)\n }\n return stream\n}\n\nexport type ContinueStreamOptions = {\n inlinedDataStream: ReadableStream | undefined\n waitForAllReady: boolean\n deploymentId: string | undefined\n getServerInsertedHTML: () => Promise\n getServerInsertedMetadata: () => Promise\n validateRootLayout?: boolean\n /**\n * Suffix to inject after the buffered data, but before the close tags.\n */\n suffix?: string | undefined\n}\n\nexport async function continueFizzStream(\n renderStream: ReactDOMServerReadableStream,\n {\n suffix,\n inlinedDataStream,\n waitForAllReady,\n deploymentId,\n getServerInsertedHTML,\n getServerInsertedMetadata,\n validateRootLayout,\n }: ContinueStreamOptions\n): Promise> {\n // Suffix itself might contain close tags at the end, so we need to split it.\n const suffixUnclosed = suffix ? suffix.split(CLOSE_TAG, 1)[0] : null\n\n if (waitForAllReady) {\n // Wait for all Suspense boundaries to resolve before continuing.\n await renderStream.allReady\n } else {\n // Otherwise, we want to make sure Fizz is done with all microtasky work\n // before we start pulling the stream and cause a flush.\n await waitAtLeastOneReactRenderTask()\n }\n\n return chainTransformers(renderStream, [\n // Buffer everything to avoid flushing too frequently\n createBufferedTransformStream(),\n\n // Insert data-dpl-id attribute on the html tag\n deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n\n // Transform metadata\n createMetadataTransformStream(getServerInsertedMetadata),\n\n // Insert suffix content\n suffixUnclosed != null && suffixUnclosed.length > 0\n ? createDeferredSuffixStream(suffixUnclosed)\n : null,\n\n // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n inlinedDataStream\n ? createFlightDataInjectionTransformStream(inlinedDataStream, true)\n : null,\n\n // Validate the root layout for missing html or body tags\n validateRootLayout ? createRootLayoutValidatorStream() : null,\n\n // Close tags should always be deferred to the end\n createMoveSuffixStream(),\n\n // Special head insertions\n // TODO-APP: Insert server side html to end of head in app layout rendering, to avoid\n // hydration errors. Remove this once it's ready to be handled by react itself.\n createHeadInsertionTransformStream(getServerInsertedHTML),\n ])\n}\n\ntype ContinueDynamicPrerenderOptions = {\n getServerInsertedHTML: () => Promise\n getServerInsertedMetadata: () => Promise\n deploymentId: string | undefined\n}\n\nexport async function continueDynamicPrerender(\n prerenderStream: ReadableStream,\n {\n getServerInsertedHTML,\n getServerInsertedMetadata,\n deploymentId,\n }: ContinueDynamicPrerenderOptions\n) {\n return chainTransformers(prerenderStream, [\n // Buffer everything to avoid flushing too frequently\n createBufferedTransformStream(),\n createStripDocumentClosingTagsTransform(),\n // Insert data-dpl-id attribute on the html tag\n deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n // Insert generated tags to head\n createHeadInsertionTransformStream(getServerInsertedHTML),\n // Transform metadata\n createMetadataTransformStream(getServerInsertedMetadata),\n ])\n}\n\ntype ContinueStaticPrerenderOptions = {\n inlinedDataStream: ReadableStream\n getServerInsertedHTML: () => Promise\n getServerInsertedMetadata: () => Promise\n deploymentId: string | undefined\n}\n\nexport async function continueStaticPrerender(\n prerenderStream: ReadableStream,\n {\n inlinedDataStream,\n getServerInsertedHTML,\n getServerInsertedMetadata,\n deploymentId,\n }: ContinueStaticPrerenderOptions\n) {\n return chainTransformers(prerenderStream, [\n // Buffer everything to avoid flushing too frequently\n createBufferedTransformStream(),\n // Add build id comment to start of the HTML document (in export mode)\n // Insert data-dpl-id attribute on the html tag\n deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n // Insert generated tags to head\n createHeadInsertionTransformStream(getServerInsertedHTML),\n // Transform metadata\n createMetadataTransformStream(getServerInsertedMetadata),\n // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n createFlightDataInjectionTransformStream(inlinedDataStream, true),\n // Close tags should always be deferred to the end\n createMoveSuffixStream(),\n ])\n}\n\nexport async function continueStaticFallbackPrerender(\n prerenderStream: ReadableStream,\n {\n inlinedDataStream,\n getServerInsertedHTML,\n getServerInsertedMetadata,\n deploymentId,\n }: ContinueStaticPrerenderOptions\n) {\n // Same as `continueStaticPrerender`, but also inserts an additional script\n // to instruct the client to start fetching the hydration data as early\n // as possible.\n return chainTransformers(prerenderStream, [\n // Buffer everything to avoid flushing too frequently\n createBufferedTransformStream(),\n // Insert data-dpl-id attribute on the html tag\n deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n // Insert generated tags to head\n createHeadInsertionTransformStream(getServerInsertedHTML),\n // Insert the client resume script into the head\n await createClientResumeScriptInsertionTransformStream(),\n // Transform metadata\n createMetadataTransformStream(getServerInsertedMetadata),\n // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n createFlightDataInjectionTransformStream(inlinedDataStream, true),\n // Close tags should always be deferred to the end\n createMoveSuffixStream(),\n ])\n}\n\ntype ContinueResumeOptions = {\n inlinedDataStream: ReadableStream\n getServerInsertedHTML: () => Promise\n getServerInsertedMetadata: () => Promise\n delayDataUntilFirstHtmlChunk: boolean\n deploymentId: string | undefined\n}\n\nexport async function continueDynamicHTMLResume(\n renderStream: ReadableStream,\n {\n delayDataUntilFirstHtmlChunk,\n inlinedDataStream,\n getServerInsertedHTML,\n getServerInsertedMetadata,\n deploymentId,\n }: ContinueResumeOptions\n) {\n return chainTransformers(renderStream, [\n // Buffer everything to avoid flushing too frequently\n createBufferedTransformStream(),\n // Insert data-dpl-id attribute on the html tag\n deploymentId ? createHtmlDataDplIdTransformStream(deploymentId) : null,\n // Insert generated tags to head\n createHeadInsertionTransformStream(getServerInsertedHTML),\n // Transform metadata\n createMetadataTransformStream(getServerInsertedMetadata),\n // Insert the inlined data (Flight data, form state, etc.) stream into the HTML\n createFlightDataInjectionTransformStream(\n inlinedDataStream,\n delayDataUntilFirstHtmlChunk\n ),\n // Close tags should always be deferred to the end\n createMoveSuffixStream(),\n ])\n}\n\nexport function createDocumentClosingStream(): ReadableStream {\n return streamFromString(CLOSE_TAG)\n}\n\n// ---------------------------------------------------------------------------\n// Runtime prefetch transform (Web streams)\n// ---------------------------------------------------------------------------\n\n/**\n * Web TransformStream that replaces the runtime prefetch sentinel in an RSC\n * payload stream: `[]` -> `[,]`.\n *\n * This is the web equivalent of createRuntimePrefetchNodeTransform\n * in node-stream-helpers.ts.\n */\nexport function createRuntimePrefetchTransformStream(\n sentinel: number,\n isPartial: boolean,\n staleTime: number\n): TransformStream {\n const enc = new TextEncoder()\n\n // Search for: []\n // Replace with: [,]\n const search = enc.encode(`[${sentinel}]`)\n const first = search[0]\n const replace = enc.encode(`[${isPartial},${staleTime}]`)\n const searchLen = search.length\n\n let currentChunk: Uint8Array | null = null\n let found = false\n\n function processChunk(\n controller: TransformStreamDefaultController,\n nextChunk: null | Uint8Array\n ) {\n if (found) {\n if (nextChunk) {\n controller.enqueue(nextChunk)\n }\n return\n }\n\n if (currentChunk) {\n // We can't search past the index that can contain a full match\n let exclusiveUpperBound = currentChunk.length - (searchLen - 1)\n if (nextChunk) {\n // If we have any overflow bytes we can search up to the chunk's final byte\n exclusiveUpperBound += Math.min(nextChunk.length, searchLen - 1)\n }\n if (exclusiveUpperBound < 1) {\n // we can't match the current chunk.\n controller.enqueue(currentChunk)\n currentChunk = nextChunk // advance so we don't process this chunk again\n return\n }\n\n let currentIndex = currentChunk.indexOf(first)\n\n // check the current candidate match if it is within the bounds of our search space for the currentChunk\n candidateLoop: while (\n -1 < currentIndex &&\n currentIndex < exclusiveUpperBound\n ) {\n // We already know index 0 matches because we used indexOf to find the candidateIndex so we start at index 1\n let matchIndex = 1\n while (matchIndex < searchLen) {\n const candidateIndex = currentIndex + matchIndex\n const candidateValue =\n candidateIndex < currentChunk.length\n ? currentChunk[candidateIndex]\n : // if we ever hit this condition it is because there is a nextChunk we can read from\n nextChunk![candidateIndex - currentChunk.length]\n if (candidateValue !== search[matchIndex]) {\n // No match, reset and continue the search from the next position\n currentIndex = currentChunk.indexOf(first, currentIndex + 1)\n continue candidateLoop\n }\n matchIndex++\n }\n // We found a complete match. currentIndex is our starting point to replace the value.\n found = true\n // enqueue everything up to the match\n controller.enqueue(currentChunk.subarray(0, currentIndex))\n // enqueue the replacement value\n controller.enqueue(replace)\n // If there are bytes in the currentChunk after the match enqueue them\n if (currentIndex + searchLen < currentChunk.length) {\n controller.enqueue(currentChunk.slice(currentIndex + searchLen))\n }\n // If we have a next chunk we enqueue it now\n if (nextChunk) {\n // if replacement spills over to the next chunk we first exclude the replaced bytes\n const overflowBytes = currentIndex + searchLen - currentChunk.length\n const truncatedChunk =\n overflowBytes > 0 ? nextChunk!.subarray(overflowBytes) : nextChunk\n controller.enqueue(truncatedChunk)\n }\n // We are now in found mode and don't need to track currentChunk anymore\n currentChunk = null\n return\n }\n // No match found in this chunk, emit it and wait for the next one\n controller.enqueue(currentChunk)\n }\n\n // Advance to the next chunk\n currentChunk = nextChunk\n }\n\n return new TransformStream({\n transform(chunk, controller) {\n processChunk(controller, chunk)\n },\n flush(controller) {\n processChunk(controller, null)\n },\n })\n}\n"],"names":["CLOSE_TAG","chainStreams","chainTransformers","continueDynamicHTMLResume","continueDynamicPrerender","continueFizzStream","continueStaticFallbackPrerender","continueStaticPrerender","createBufferedTransformStream","createDeferredSuffixStream","createDocumentClosingStream","createFlightDataInjectionTransformStream","createHeadInsertionTransformStream","createHtmlDataDplIdTransformStream","createMetadataTransformStream","createMoveSuffixStream","createRootLayoutValidatorStream","createRuntimePrefetchTransformStream","nodestreamToUint8Array","renderToInitialFizzStream","streamFromBuffer","streamFromString","streamToBuffer","streamToString","streamToUint8Array","webstreamToUint8Array","voidCatch","encoder","TextEncoder","streams","length","ReadableStream","start","controller","close","readable","writable","TransformStream","promise","pipeTo","preventClose","i","nextStream","then","lastStream","catch","str","enqueue","encode","chunk","streamToChunks","stream","reader","getReader","chunks","done","value","read","push","concatUint8Arrays","totalLength","reduce","sum","result","Uint8Array","offset","set","webToReadable","process","env","NEXT_RUNTIME","Error","Readable","TURBOPACK","require","__NEXT_BUNDLER","__non_webpack_require__","fromWeb","Buffer","from","concat","signal","decoder","TextDecoder","fatal","string","aborted","decode","options","maxBufferByteLength","Infinity","bufferedChunks","bufferByteLength","pending","flush","copiedBytes","bufferedChunk","byteLength","scheduleFlush","detached","createPromiseWithResolvers","scheduleImmediate","undefined","resolve","transform","ReactDOMServer","element","streamOptions","getTracer","trace","AppRenderSpan","renderToReadableStream","insert","chunkIndex","isMarkRemoved","iconMarkIndex","closedHeadIndex","iconMarkLength","indexOfUint8Array","ENCODED_TAGS","META","ICON_MARK","CLOSED","HEAD","replaced","subarray","insertion","encodedInsertion","insertionLength","inserted","hasBytes","index","insertedHeadContent","slice","createClientResumeScriptInsertionTransformStream","segmentPath","cacheBustingHeader","computeCacheBustingSearchParam","searchStr","NEXT_RSC_UNION_QUERY","NEXT_CLIENT_RESUME_SCRIPT","RSC_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","didAlreadyInsert","headClosingTagIndex","suffix","flushed","delayDataUntilFirstHtmlChunk","htmlStreamFinished","pull","donePulling","startOrContinuePulling","startPulling","atLeastOneTask","err","error","foundSuffix","BODY_AND_HTML","before","after","createStripDocumentClosingTagsTransform","isEquivalentUint8Arrays","BODY","HTML","removeFromUint8Array","dplId","didTransform","htmlTagIndex","OPENING","insertionPoint","attribute","encodedAttribute","modifiedChunk","foundHtml","foundBody","missingTags","map","c","join","MISSING_ROOT_TAGS_ERROR","transformers","transformer","pipeThrough","renderStream","inlinedDataStream","waitForAllReady","deploymentId","getServerInsertedHTML","getServerInsertedMetadata","validateRootLayout","suffixUnclosed","split","allReady","waitAtLeastOneReactRenderTask","prerenderStream","sentinel","isPartial","staleTime","enc","search","first","replace","searchLen","currentChunk","found","processChunk","nextChunk","exclusiveUpperBound","Math","min","currentIndex","indexOf","candidateLoop","matchIndex","candidateIndex","candidateValue","overflowBytes","truncatedChunk"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAqtBaA,SAAS;eAATA;;IAjrBGC,YAAY;eAAZA;;IAw2BAC,iBAAiB;eAAjBA;;IAqLMC,yBAAyB;eAAzBA;;IA5FAC,wBAAwB;eAAxBA;;IA/DAC,kBAAkB;eAAlBA;;IAqHAC,+BAA+B;eAA/BA;;IA1BAC,uBAAuB;eAAvBA;;IA7wBNC,6BAA6B;eAA7BA;;IAoWAC,0BAA0B;eAA1BA;;IAsgBAC,2BAA2B;eAA3BA;;IAzdAC,wCAAwC;eAAxCA;;IAvLAC,kCAAkC;eAAlCA;;IA4VAC,kCAAkC;eAAlCA;;IAjcAC,6BAA6B;eAA7BA;;IAmXAC,sBAAsB;eAAtBA;;IA6HAC,+BAA+B;eAA/BA;;IAoRAC,oCAAoC;eAApCA;;IAj8BMC,sBAAsB;eAAtBA;;IA6KNC,yBAAyB;eAAzBA;;IArPAC,gBAAgB;eAAhBA;;IApBAC,gBAAgB;eAAhBA;;IAmIMC,cAAc;eAAdA;;IAMAC,cAAc;eAAdA;;IAnCAC,kBAAkB;eAAlBA;;IA5CAC,qBAAqB;eAArBA;;;wBAzII;2BACI;sCACa;2BAKpC;6BACsB;mCAKtB;4BACiC;kCAMjC;yCACwC;AAG/C,SAASC;AACP,iFAAiF;AACjF,uFAAuF;AACvF,mBAAmB;AACrB;AAEA,oDAAoD;AACpD,uEAAuE;AACvE,+BAA+B;AAC/B,MAAMC,UAAU,IAAIC;AAEb,SAAS3B,aACd,GAAG4B,OAA4B;IAE/B,kEAAkE;IAClE,qEAAqE;IACrE,IAAIA,QAAQC,MAAM,KAAK,GAAG;QACxB,OAAO,IAAIC,eAAkB;YAC3BC,OAAMC,UAAU;gBACdA,WAAWC,KAAK;YAClB;QACF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AaX,UAAW;oBAC7B,MAAMY,iBAAiBJ,eAAeG;oBACtC,MAAME,iBACJD,iBAAiBX,aAAa9K,MAAM,GAChC8K,YAAY,CAACW,eAAe,GAE5BR,SAAU,CAACQ,iBAAiBX,aAAa9K,MAAM,CAAC;oBACtD,IAAI0L,mBAAmBhB,MAAM,CAACc,WAAW,EAAE;wBACzC,iEAAiE;wBACjEH,eAAeP,aAAaQ,OAAO,CAACX,OAAOU,eAAe;wBAC1D,SAASE;oBACX;oBACAC;gBACF;gBACA,sFAAsF;gBACtFT,QAAQ;gBACR,qCAAqC;gBACrC5K,WAAWc,OAAO,CAAC6J,aAAa/E,QAAQ,CAAC,GAAGsF;gBAC5C,gCAAgC;gBAChClL,WAAWc,OAAO,CAAC2J;gBACnB,sEAAsE;gBACtE,IAAIS,eAAeR,YAAYC,aAAa9K,MAAM,EAAE;oBAClDG,WAAWc,OAAO,CAAC6J,aAAavE,KAAK,CAAC8E,eAAeR;gBACvD;gBACA,4CAA4C;gBAC5C,IAAII,WAAW;oBACb,mFAAmF;oBACnF,MAAMU,gBAAgBN,eAAeR,YAAYC,aAAa9K,MAAM;oBACpE,MAAM4L,iBACJD,gBAAgB,IAAIV,UAAWlF,QAAQ,CAAC4F,iBAAiBV;oBAC3D9K,WAAWc,OAAO,CAAC2K;gBACrB;gBACA,wEAAwE;gBACxEd,eAAe;gBACf;YACF;YACA,kEAAkE;YAClE3K,WAAWc,OAAO,CAAC6J;QACrB;QAEA,4BAA4B;QAC5BA,eAAeG;IACjB;IAEA,OAAO,IAAI1K,gBAAwC;QACjDmE,WAAUvD,KAAK,EAAEhB,UAAU;YACzB6K,aAAa7K,YAAYgB;QAC3B;QACA6C,OAAM7D,UAAU;YACd6K,aAAa7K,YAAY;QAC3B;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/stream-utils/uint8array-helpers.d.ts b/e-commerce/node_modules/next/dist/server/stream-utils/uint8array-helpers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..49276d617193819e3e9fd8dca21cd42b51cc4f5d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/stream-utils/uint8array-helpers.d.ts @@ -0,0 +1,16 @@ +/** + * Find the starting index of Uint8Array `b` within Uint8Array `a`. + */ +export declare function indexOfUint8Array(a: Uint8Array, b: Uint8Array): number; +/** + * Check if two Uint8Arrays are strictly equivalent. + */ +export declare function isEquivalentUint8Arrays(a: Uint8Array, b: Uint8Array): boolean; +/** + * Remove Uint8Array `b` from Uint8Array `a`. + * + * If `b` is not in `a`, `a` is returned unchanged. + * + * Otherwise, the function returns a new Uint8Array instance with size `a.length - b.length` + */ +export declare function removeFromUint8Array(a: Uint8Array, b: Uint8Array): Uint8Array; diff --git a/e-commerce/node_modules/next/dist/server/stream-utils/uint8array-helpers.js b/e-commerce/node_modules/next/dist/server/stream-utils/uint8array-helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..c0e0c0ac2ea20538330f81aaa40fe5eada7fcbc9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/stream-utils/uint8array-helpers.js @@ -0,0 +1,74 @@ +/** + * Find the starting index of Uint8Array `b` within Uint8Array `a`. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + indexOfUint8Array: null, + isEquivalentUint8Arrays: null, + removeFromUint8Array: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + indexOfUint8Array: function() { + return indexOfUint8Array; + }, + isEquivalentUint8Arrays: function() { + return isEquivalentUint8Arrays; + }, + removeFromUint8Array: function() { + return removeFromUint8Array; + } +}); +function indexOfUint8Array(a, b) { + if (b.length === 0) return 0; + if (a.length === 0 || b.length > a.length) return -1; + // Use Node's native implementation when available. + if (typeof Buffer !== 'undefined') { + const haystack = Buffer.isBuffer(a) ? a : Buffer.from(a.buffer, a.byteOffset, a.byteLength); + return haystack.indexOf(b); + } + // start iterating through `a` + for(let i = 0; i <= a.length - b.length; i++){ + let completeMatch = true; + // from index `i`, iterate through `b` and check for mismatch + for(let j = 0; j < b.length; j++){ + // if the values do not match, then this isn't a complete match, exit `b` iteration early and iterate to next index of `a`. + if (a[i + j] !== b[j]) { + completeMatch = false; + break; + } + } + if (completeMatch) { + return i; + } + } + return -1; +} +function isEquivalentUint8Arrays(a, b) { + if (a.length !== b.length) return false; + for(let i = 0; i < a.length; i++){ + if (a[i] !== b[i]) return false; + } + return true; +} +function removeFromUint8Array(a, b) { + const tagIndex = indexOfUint8Array(a, b); + if (tagIndex === 0) return a.subarray(b.length); + if (tagIndex > -1) { + const removed = new Uint8Array(a.length - b.length); + removed.set(a.subarray(0, tagIndex)); + removed.set(a.subarray(tagIndex + b.length), tagIndex); + return removed; + } else { + return a; + } +} + +//# sourceMappingURL=uint8array-helpers.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/stream-utils/uint8array-helpers.js.map b/e-commerce/node_modules/next/dist/server/stream-utils/uint8array-helpers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..95fa795a3b832374f0e55b9f0f9257d7ab95e36c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/stream-utils/uint8array-helpers.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/stream-utils/uint8array-helpers.ts"],"sourcesContent":["/**\n * Find the starting index of Uint8Array `b` within Uint8Array `a`.\n */\nexport function indexOfUint8Array(a: Uint8Array, b: Uint8Array) {\n if (b.length === 0) return 0\n if (a.length === 0 || b.length > a.length) return -1\n\n // Use Node's native implementation when available.\n if (typeof Buffer !== 'undefined') {\n const haystack = Buffer.isBuffer(a)\n ? a\n : Buffer.from(a.buffer, a.byteOffset, a.byteLength)\n return haystack.indexOf(b)\n }\n\n // start iterating through `a`\n for (let i = 0; i <= a.length - b.length; i++) {\n let completeMatch = true\n // from index `i`, iterate through `b` and check for mismatch\n for (let j = 0; j < b.length; j++) {\n // if the values do not match, then this isn't a complete match, exit `b` iteration early and iterate to next index of `a`.\n if (a[i + j] !== b[j]) {\n completeMatch = false\n break\n }\n }\n\n if (completeMatch) {\n return i\n }\n }\n\n return -1\n}\n\n/**\n * Check if two Uint8Arrays are strictly equivalent.\n */\nexport function isEquivalentUint8Arrays(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false\n\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false\n }\n\n return true\n}\n\n/**\n * Remove Uint8Array `b` from Uint8Array `a`.\n *\n * If `b` is not in `a`, `a` is returned unchanged.\n *\n * Otherwise, the function returns a new Uint8Array instance with size `a.length - b.length`\n */\nexport function removeFromUint8Array(a: Uint8Array, b: Uint8Array) {\n const tagIndex = indexOfUint8Array(a, b)\n if (tagIndex === 0) return a.subarray(b.length)\n if (tagIndex > -1) {\n const removed = new Uint8Array(a.length - b.length)\n removed.set(a.subarray(0, tagIndex))\n removed.set(a.subarray(tagIndex + b.length), tagIndex)\n return removed\n } else {\n return a\n }\n}\n"],"names":["indexOfUint8Array","isEquivalentUint8Arrays","removeFromUint8Array","a","b","length","Buffer","haystack","isBuffer","from","buffer","byteOffset","byteLength","indexOf","i","completeMatch","j","tagIndex","subarray","removed","Uint8Array","set"],"mappings":"AAAA;;CAEC;;;;;;;;;;;;;;;;IACeA,iBAAiB;eAAjBA;;IAmCAC,uBAAuB;eAAvBA;;IAiBAC,oBAAoB;eAApBA;;;AApDT,SAASF,kBAAkBG,CAAa,EAAEC,CAAa;IAC5D,IAAIA,EAAEC,MAAM,KAAK,GAAG,OAAO;IAC3B,IAAIF,EAAEE,MAAM,KAAK,KAAKD,EAAEC,MAAM,GAAGF,EAAEE,MAAM,EAAE,OAAO,CAAC;IAEnD,mDAAmD;IACnD,IAAI,OAAOC,WAAW,aAAa;QACjC,MAAMC,WAAWD,OAAOE,QAAQ,CAACL,KAC7BA,IACAG,OAAOG,IAAI,CAACN,EAAEO,MAAM,EAAEP,EAAEQ,UAAU,EAAER,EAAES,UAAU;QACpD,OAAOL,SAASM,OAAO,CAACT;IAC1B;IAEA,8BAA8B;IAC9B,IAAK,IAAIU,IAAI,GAAGA,KAAKX,EAAEE,MAAM,GAAGD,EAAEC,MAAM,EAAES,IAAK;QAC7C,IAAIC,gBAAgB;QACpB,6DAA6D;QAC7D,IAAK,IAAIC,IAAI,GAAGA,IAAIZ,EAAEC,MAAM,EAAEW,IAAK;YACjC,2HAA2H;YAC3H,IAAIb,CAAC,CAACW,IAAIE,EAAE,KAAKZ,CAAC,CAACY,EAAE,EAAE;gBACrBD,gBAAgB;gBAChB;YACF;QACF;QAEA,IAAIA,eAAe;YACjB,OAAOD;QACT;IACF;IAEA,OAAO,CAAC;AACV;AAKO,SAASb,wBAAwBE,CAAa,EAAEC,CAAa;IAClE,IAAID,EAAEE,MAAM,KAAKD,EAAEC,MAAM,EAAE,OAAO;IAElC,IAAK,IAAIS,IAAI,GAAGA,IAAIX,EAAEE,MAAM,EAAES,IAAK;QACjC,IAAIX,CAAC,CAACW,EAAE,KAAKV,CAAC,CAACU,EAAE,EAAE,OAAO;IAC5B;IAEA,OAAO;AACT;AASO,SAASZ,qBAAqBC,CAAa,EAAEC,CAAa;IAC/D,MAAMa,WAAWjB,kBAAkBG,GAAGC;IACtC,IAAIa,aAAa,GAAG,OAAOd,EAAEe,QAAQ,CAACd,EAAEC,MAAM;IAC9C,IAAIY,WAAW,CAAC,GAAG;QACjB,MAAME,UAAU,IAAIC,WAAWjB,EAAEE,MAAM,GAAGD,EAAEC,MAAM;QAClDc,QAAQE,GAAG,CAAClB,EAAEe,QAAQ,CAAC,GAAGD;QAC1BE,QAAQE,GAAG,CAAClB,EAAEe,QAAQ,CAACD,WAAWb,EAAEC,MAAM,GAAGY;QAC7C,OAAOE;IACT,OAAO;QACL,OAAOhB;IACT;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/constant.d.ts b/e-commerce/node_modules/next/dist/server/typescript/constant.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d224d5eaede817731bdacd7aac7d214397564edd --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/constant.d.ts @@ -0,0 +1,19 @@ +export declare const NEXT_TS_ERRORS: { + INVALID_SERVER_API: number; + INVALID_ENTRY_EXPORT: number; + INVALID_OPTION_VALUE: number; + MISPLACED_ENTRY_DIRECTIVE: number; + INVALID_PAGE_PROP: number; + INVALID_CONFIG_OPTION: number; + INVALID_CLIENT_ENTRY_PROP: number; + INVALID_METADATA_EXPORT: number; + INVALID_ERROR_COMPONENT: number; + INVALID_ENTRY_DIRECTIVE: number; + INVALID_SERVER_ENTRY_RETURN: number; +}; +export declare const ALLOWED_EXPORTS: string[]; +export declare const LEGACY_CONFIG_EXPORT = "config"; +export declare const DISALLOWED_SERVER_REACT_APIS: string[]; +export declare const DISALLOWED_SERVER_REACT_DOM_APIS: string[]; +export declare const ALLOWED_PAGE_PROPS: string[]; +export declare const ALLOWED_LAYOUT_PROPS: string[]; diff --git a/e-commerce/node_modules/next/dist/server/typescript/constant.js b/e-commerce/node_modules/next/dist/server/typescript/constant.js new file mode 100644 index 0000000000000000000000000000000000000000..55df19b421d0531c05df0e282e4fedb00d3733b5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/constant.js @@ -0,0 +1,100 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + ALLOWED_EXPORTS: null, + ALLOWED_LAYOUT_PROPS: null, + ALLOWED_PAGE_PROPS: null, + DISALLOWED_SERVER_REACT_APIS: null, + DISALLOWED_SERVER_REACT_DOM_APIS: null, + LEGACY_CONFIG_EXPORT: null, + NEXT_TS_ERRORS: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + ALLOWED_EXPORTS: function() { + return ALLOWED_EXPORTS; + }, + ALLOWED_LAYOUT_PROPS: function() { + return ALLOWED_LAYOUT_PROPS; + }, + ALLOWED_PAGE_PROPS: function() { + return ALLOWED_PAGE_PROPS; + }, + DISALLOWED_SERVER_REACT_APIS: function() { + return DISALLOWED_SERVER_REACT_APIS; + }, + DISALLOWED_SERVER_REACT_DOM_APIS: function() { + return DISALLOWED_SERVER_REACT_DOM_APIS; + }, + LEGACY_CONFIG_EXPORT: function() { + return LEGACY_CONFIG_EXPORT; + }, + NEXT_TS_ERRORS: function() { + return NEXT_TS_ERRORS; + } +}); +const NEXT_TS_ERRORS = { + INVALID_SERVER_API: 71001, + INVALID_ENTRY_EXPORT: 71002, + INVALID_OPTION_VALUE: 71003, + MISPLACED_ENTRY_DIRECTIVE: 71004, + INVALID_PAGE_PROP: 71005, + INVALID_CONFIG_OPTION: 71006, + INVALID_CLIENT_ENTRY_PROP: 71007, + INVALID_METADATA_EXPORT: 71008, + INVALID_ERROR_COMPONENT: 71009, + INVALID_ENTRY_DIRECTIVE: 71010, + INVALID_SERVER_ENTRY_RETURN: 71011 +}; +const ALLOWED_EXPORTS = [ + 'config', + 'generateStaticParams', + 'unstable_paramMatching', + 'unstable_generateParamMatching', + 'metadata', + 'generateMetadata', + 'viewport', + 'generateViewport' +]; +const LEGACY_CONFIG_EXPORT = 'config'; +const DISALLOWED_SERVER_REACT_APIS = [ + 'useState', + 'useEffect', + 'useEffectEvent', + 'useLayoutEffect', + 'useDeferredValue', + 'useImperativeHandle', + 'useInsertionEffect', + 'useReducer', + 'useRef', + 'useSyncExternalStore', + 'useTransition', + 'Component', + 'PureComponent', + 'createContext', + 'createFactory', + 'experimental_useOptimistic', + 'useOptimistic', + 'useActionState' +]; +const DISALLOWED_SERVER_REACT_DOM_APIS = [ + 'useFormStatus', + 'useFormState' +]; +const ALLOWED_PAGE_PROPS = [ + 'params', + 'searchParams' +]; +const ALLOWED_LAYOUT_PROPS = [ + 'params', + 'children' +]; + +//# sourceMappingURL=constant.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/constant.js.map b/e-commerce/node_modules/next/dist/server/typescript/constant.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ba2f8e9cb7fed6891b266b04f759cebd852e406b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/constant.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/typescript/constant.ts"],"sourcesContent":["export const NEXT_TS_ERRORS = {\n INVALID_SERVER_API: 71001,\n INVALID_ENTRY_EXPORT: 71002,\n INVALID_OPTION_VALUE: 71003,\n MISPLACED_ENTRY_DIRECTIVE: 71004,\n INVALID_PAGE_PROP: 71005,\n INVALID_CONFIG_OPTION: 71006,\n INVALID_CLIENT_ENTRY_PROP: 71007,\n INVALID_METADATA_EXPORT: 71008,\n INVALID_ERROR_COMPONENT: 71009,\n INVALID_ENTRY_DIRECTIVE: 71010,\n INVALID_SERVER_ENTRY_RETURN: 71011,\n}\n\nexport const ALLOWED_EXPORTS = [\n 'config',\n 'generateStaticParams',\n 'unstable_paramMatching',\n 'unstable_generateParamMatching',\n 'metadata',\n 'generateMetadata',\n 'viewport',\n 'generateViewport',\n]\n\nexport const LEGACY_CONFIG_EXPORT = 'config'\n\nexport const DISALLOWED_SERVER_REACT_APIS: string[] = [\n 'useState',\n 'useEffect',\n 'useEffectEvent',\n 'useLayoutEffect',\n 'useDeferredValue',\n 'useImperativeHandle',\n 'useInsertionEffect',\n 'useReducer',\n 'useRef',\n 'useSyncExternalStore',\n 'useTransition',\n 'Component',\n 'PureComponent',\n 'createContext',\n 'createFactory',\n 'experimental_useOptimistic',\n 'useOptimistic',\n 'useActionState',\n]\n\nexport const DISALLOWED_SERVER_REACT_DOM_APIS: string[] = [\n 'useFormStatus',\n 'useFormState',\n]\n\nexport const ALLOWED_PAGE_PROPS = ['params', 'searchParams']\nexport const ALLOWED_LAYOUT_PROPS = ['params', 'children']\n"],"names":["ALLOWED_EXPORTS","ALLOWED_LAYOUT_PROPS","ALLOWED_PAGE_PROPS","DISALLOWED_SERVER_REACT_APIS","DISALLOWED_SERVER_REACT_DOM_APIS","LEGACY_CONFIG_EXPORT","NEXT_TS_ERRORS","INVALID_SERVER_API","INVALID_ENTRY_EXPORT","INVALID_OPTION_VALUE","MISPLACED_ENTRY_DIRECTIVE","INVALID_PAGE_PROP","INVALID_CONFIG_OPTION","INVALID_CLIENT_ENTRY_PROP","INVALID_METADATA_EXPORT","INVALID_ERROR_COMPONENT","INVALID_ENTRY_DIRECTIVE","INVALID_SERVER_ENTRY_RETURN"],"mappings":";;;;;;;;;;;;;;;;;;;;IAcaA,eAAe;eAAfA;;IAwCAC,oBAAoB;eAApBA;;IADAC,kBAAkB;eAAlBA;;IA1BAC,4BAA4B;eAA5BA;;IAqBAC,gCAAgC;eAAhCA;;IAvBAC,oBAAoB;eAApBA;;IAzBAC,cAAc;eAAdA;;;AAAN,MAAMA,iBAAiB;IAC5BC,oBAAoB;IACpBC,sBAAsB;IACtBC,sBAAsB;IACtBC,2BAA2B;IAC3BC,mBAAmB;IACnBC,uBAAuB;IACvBC,2BAA2B;IAC3BC,yBAAyB;IACzBC,yBAAyB;IACzBC,yBAAyB;IACzBC,6BAA6B;AAC/B;AAEO,MAAMjB,kBAAkB;IAC7B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAEM,MAAMK,uBAAuB;AAE7B,MAAMF,+BAAyC;IACpD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAEM,MAAMC,mCAA6C;IACxD;IACA;CACD;AAEM,MAAMF,qBAAqB;IAAC;IAAU;CAAe;AACrD,MAAMD,uBAAuB;IAAC;IAAU;CAAW","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/index.d.ts b/e-commerce/node_modules/next/dist/server/typescript/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b469b18e03e6aba5dbb435183047c053136bc2df --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/index.d.ts @@ -0,0 +1,11 @@ +/** + * This is a TypeScript language service plugin for Next.js app directory, + * it provides the following features: + * + * - Warns about disallowed React APIs in server components. + * - Warns about disallowed layout and page exports. + * - Autocompletion for entry configurations. + * - Hover hint and docs for entry configurations. + */ +import type tsModule from 'typescript/lib/tsserverlibrary'; +export declare const createTSPlugin: tsModule.server.PluginModuleFactory; diff --git a/e-commerce/node_modules/next/dist/server/typescript/index.js b/e-commerce/node_modules/next/dist/server/typescript/index.js new file mode 100644 index 0000000000000000000000000000000000000000..643e5ecd3571fae37a577429b6dafd1130d09cff --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/index.js @@ -0,0 +1,199 @@ +/** + * This is a TypeScript language service plugin for Next.js app directory, + * it provides the following features: + * + * - Warns about disallowed React APIs in server components. + * - Warns about disallowed layout and page exports. + * - Autocompletion for entry configurations. + * - Hover hint and docs for entry configurations. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "createTSPlugin", { + enumerable: true, + get: function() { + return createTSPlugin; + } +}); +const _utils = require("./utils"); +const _constant = require("./constant"); +const _config = /*#__PURE__*/ _interop_require_default(require("./rules/config")); +const _server = /*#__PURE__*/ _interop_require_default(require("./rules/server")); +const _entry = /*#__PURE__*/ _interop_require_default(require("./rules/entry")); +const _clientboundary = /*#__PURE__*/ _interop_require_default(require("./rules/client-boundary")); +const _serverboundary = /*#__PURE__*/ _interop_require_default(require("./rules/server-boundary")); +const _metadata = /*#__PURE__*/ _interop_require_default(require("./rules/metadata")); +const _error = /*#__PURE__*/ _interop_require_default(require("./rules/error")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +const createTSPlugin = ({ typescript: ts })=>{ + function create(info) { + // Get plugin options + // config is the plugin options from the user's tsconfig.json + // e.g. { "plugins": [{ "name": "next", "enabled": true }] } + // config will be { "name": "next", "enabled": true } + // The default user config is { "name": "next" } + const isPluginEnabled = info.config.enabled ?? true; + if (!isPluginEnabled) { + return info.languageService; + } + (0, _utils.init)({ + ts, + info + }); + // Set up decorator object + const proxy = Object.create(null); + for (let k of Object.keys(info.languageService)){ + const x = info.languageService[k]; + // @ts-expect-error - JS runtime trickery which is tricky to type tersely + proxy[k] = (...args)=>x.apply(info.languageService, args); + } + // Auto completion + proxy.getCompletionsAtPosition = (fileName, position, options)=>{ + let prior = info.languageService.getCompletionsAtPosition(fileName, position, options) || { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries: [] + }; + if (!(0, _utils.isAppEntryFile)(fileName)) return prior; + // If it's a server entry. + const entryInfo = (0, _utils.getEntryInfo)(fileName); + if (!entryInfo.client) { + // Remove specified entries from completion list + prior.entries = _server.default.filterCompletionsAtPosition(prior.entries); + } + // Add auto completions for export configs. + _config.default.addCompletionsAtPosition(fileName, position, prior); + const source = (0, _utils.getSource)(fileName); + if (!source) return prior; + ts.forEachChild(source, (node)=>{ + // Auto completion for default export function's props. + if ((0, _utils.isPositionInsideNode)(position, node) && (0, _utils.isDefaultFunctionExport)(node)) { + prior.entries.push(..._entry.default.getCompletionsAtPosition(fileName, node, position)); + } + }); + return prior; + }; + // Show auto completion details + proxy.getCompletionEntryDetails = (fileName, position, entryName, formatOptions, source, preferences, data)=>{ + const entryCompletionEntryDetails = _config.default.getCompletionEntryDetails(entryName, data, fileName); + if (entryCompletionEntryDetails) return entryCompletionEntryDetails; + return info.languageService.getCompletionEntryDetails(fileName, position, entryName, formatOptions, source, preferences, data); + }; + // Quick info + proxy.getQuickInfoAtPosition = (fileName, position, ...args)=>{ + const prior = info.languageService.getQuickInfoAtPosition(fileName, position, ...args); + if (!(0, _utils.isAppEntryFile)(fileName)) return prior; + // Remove type suggestions for disallowed APIs in server components. + const entryInfo = (0, _utils.getEntryInfo)(fileName); + if (!entryInfo.client) { + const definitions = info.languageService.getDefinitionAtPosition(fileName, position); + if (definitions && _server.default.hasDisallowedReactAPIDefinition(definitions)) { + return; + } + } + const overridden = _config.default.getQuickInfoAtPosition(fileName, position, prior); + if (overridden) return overridden; + return prior; + }; + // Show errors for disallowed imports + proxy.getSemanticDiagnostics = (fileName)=>{ + const prior = info.languageService.getSemanticDiagnostics(fileName); + const source = (0, _utils.getSource)(fileName); + if (!source) return prior; + let isClientEntry = false; + let isServerEntry = false; + const isAppEntry = (0, _utils.isAppEntryFile)(fileName); + try { + const entryInfo = (0, _utils.getEntryInfo)(fileName, true); + isClientEntry = entryInfo.client; + isServerEntry = entryInfo.server; + } catch (e) { + prior.push({ + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.MISPLACED_ENTRY_DIRECTIVE, + ...e + }); + isClientEntry = false; + isServerEntry = false; + } + if ((0, _utils.isInsideApp)(fileName)) { + const errorDiagnostic = _error.default.getSemanticDiagnostics(source, isClientEntry); + prior.push(...errorDiagnostic); + } + ts.forEachChild(source, (node)=>{ + var _node_modifiers, _node_modifiers1; + if (ts.isImportDeclaration(node)) { + // import ... + if (isAppEntry) { + if (!isClientEntry || isServerEntry) { + // Check if it has valid imports in the server layer + const diagnostics = _server.default.getSemanticDiagnosticsForImportDeclaration(source, node); + prior.push(...diagnostics); + } + } + } else if (ts.isVariableStatement(node) && ((_node_modifiers = node.modifiers) == null ? void 0 : _node_modifiers.some((m)=>m.kind === ts.SyntaxKind.ExportKeyword))) { + // export const ... + if (isAppEntry) { + // Check if it has correct option exports + const diagnostics = _config.default.getSemanticDiagnosticsForExportVariableStatement(source, node); + const metadataDiagnostics = isClientEntry ? _metadata.default.client.getSemanticDiagnosticsForExportVariableStatement(fileName, node) : _metadata.default.server.getSemanticDiagnosticsForExportVariableStatement(fileName, node); + prior.push(...diagnostics, ...metadataDiagnostics); + } + if (isClientEntry) { + prior.push(..._clientboundary.default.getSemanticDiagnosticsForExportVariableStatement(source, node)); + } + if (isServerEntry) { + prior.push(..._serverboundary.default.getSemanticDiagnosticsForExportVariableStatement(source, node)); + } + } else if ((0, _utils.isDefaultFunctionExport)(node)) { + // export default function ... + if (isAppEntry) { + const diagnostics = _entry.default.getSemanticDiagnostics(fileName, source, node); + prior.push(...diagnostics); + } + if (isClientEntry) { + prior.push(..._clientboundary.default.getSemanticDiagnosticsForFunctionExport(source, node)); + } + if (isServerEntry) { + prior.push(..._serverboundary.default.getSemanticDiagnosticsForFunctionExport(source, node)); + } + } else if (ts.isFunctionDeclaration(node) && ((_node_modifiers1 = node.modifiers) == null ? void 0 : _node_modifiers1.some((m)=>m.kind === ts.SyntaxKind.ExportKeyword))) { + // export function ... + if (isAppEntry) { + const metadataDiagnostics = isClientEntry ? _metadata.default.client.getSemanticDiagnosticsForExportVariableStatement(fileName, node) : _metadata.default.server.getSemanticDiagnosticsForExportVariableStatement(fileName, node); + prior.push(...metadataDiagnostics); + } + if (isClientEntry) { + prior.push(..._clientboundary.default.getSemanticDiagnosticsForFunctionExport(source, node)); + } + if (isServerEntry) { + prior.push(..._serverboundary.default.getSemanticDiagnosticsForFunctionExport(source, node)); + } + } else if (ts.isExportDeclaration(node)) { + // export { ... } + if (isAppEntry) { + const metadataDiagnostics = isClientEntry ? _metadata.default.client.getSemanticDiagnosticsForExportDeclaration(fileName, node) : _metadata.default.server.getSemanticDiagnosticsForExportDeclaration(fileName, node); + prior.push(...metadataDiagnostics); + } + if (isServerEntry) { + prior.push(..._serverboundary.default.getSemanticDiagnosticsForExportDeclaration(source, node)); + } + } + }); + return prior; + }; + return proxy; + } + return { + create + }; +}; + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/index.js.map b/e-commerce/node_modules/next/dist/server/typescript/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ab011233c4c674012bdec9562472193966a11158 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/typescript/index.ts"],"sourcesContent":["/**\n * This is a TypeScript language service plugin for Next.js app directory,\n * it provides the following features:\n *\n * - Warns about disallowed React APIs in server components.\n * - Warns about disallowed layout and page exports.\n * - Autocompletion for entry configurations.\n * - Hover hint and docs for entry configurations.\n */\n\nimport {\n init,\n getEntryInfo,\n isAppEntryFile,\n isDefaultFunctionExport,\n isPositionInsideNode,\n getSource,\n isInsideApp,\n} from './utils'\nimport { NEXT_TS_ERRORS } from './constant'\n\nimport entryConfig from './rules/config'\nimport serverLayer from './rules/server'\nimport entryDefault from './rules/entry'\nimport clientBoundary from './rules/client-boundary'\nimport serverBoundary from './rules/server-boundary'\nimport metadata from './rules/metadata'\nimport errorEntry from './rules/error'\nimport type tsModule from 'typescript/lib/tsserverlibrary'\n\nexport const createTSPlugin: tsModule.server.PluginModuleFactory = ({\n typescript: ts,\n}) => {\n function create(info: tsModule.server.PluginCreateInfo) {\n // Get plugin options\n // config is the plugin options from the user's tsconfig.json\n // e.g. { \"plugins\": [{ \"name\": \"next\", \"enabled\": true }] }\n // config will be { \"name\": \"next\", \"enabled\": true }\n // The default user config is { \"name\": \"next\" }\n const isPluginEnabled = info.config.enabled ?? true\n\n if (!isPluginEnabled) {\n return info.languageService\n }\n\n init({\n ts,\n info,\n })\n\n // Set up decorator object\n const proxy: tsModule.LanguageService = Object.create(null)\n for (let k of Object.keys(info.languageService)) {\n const x = info.languageService[k as keyof tsModule.LanguageService]\n // @ts-expect-error - JS runtime trickery which is tricky to type tersely\n proxy[k] = (...args: Array<{}>) => x.apply(info.languageService, args)\n }\n\n // Auto completion\n proxy.getCompletionsAtPosition = (\n fileName: string,\n position: number,\n options: any\n ) => {\n let prior = info.languageService.getCompletionsAtPosition(\n fileName,\n position,\n options\n ) || {\n isGlobalCompletion: false,\n isMemberCompletion: false,\n isNewIdentifierLocation: false,\n entries: [],\n }\n if (!isAppEntryFile(fileName)) return prior\n\n // If it's a server entry.\n const entryInfo = getEntryInfo(fileName)\n if (!entryInfo.client) {\n // Remove specified entries from completion list\n prior.entries = serverLayer.filterCompletionsAtPosition(prior.entries)\n }\n\n // Add auto completions for export configs.\n entryConfig.addCompletionsAtPosition(fileName, position, prior)\n\n const source = getSource(fileName)\n if (!source) return prior\n\n ts.forEachChild(source!, (node) => {\n // Auto completion for default export function's props.\n if (\n isPositionInsideNode(position, node) &&\n isDefaultFunctionExport(node)\n ) {\n prior.entries.push(\n ...entryDefault.getCompletionsAtPosition(\n fileName,\n node as tsModule.FunctionDeclaration,\n position\n )\n )\n }\n })\n\n return prior\n }\n\n // Show auto completion details\n proxy.getCompletionEntryDetails = (\n fileName: string,\n position: number,\n entryName: string,\n formatOptions: tsModule.FormatCodeOptions,\n source: string,\n preferences: tsModule.UserPreferences,\n data: tsModule.CompletionEntryData\n ) => {\n const entryCompletionEntryDetails = entryConfig.getCompletionEntryDetails(\n entryName,\n data,\n fileName\n )\n if (entryCompletionEntryDetails) return entryCompletionEntryDetails\n\n return info.languageService.getCompletionEntryDetails(\n fileName,\n position,\n entryName,\n formatOptions,\n source,\n preferences,\n data\n )\n }\n\n // Quick info\n proxy.getQuickInfoAtPosition = (\n fileName: string,\n position: number,\n ...args: any[]\n ) => {\n const prior = (\n info.languageService.getQuickInfoAtPosition as (\n fileName: string,\n position: number,\n ...args: any[]\n ) => tsModule.QuickInfo | undefined\n )(fileName, position, ...args)\n if (!isAppEntryFile(fileName)) return prior\n\n // Remove type suggestions for disallowed APIs in server components.\n const entryInfo = getEntryInfo(fileName)\n if (!entryInfo.client) {\n const definitions = info.languageService.getDefinitionAtPosition(\n fileName,\n position\n )\n if (\n definitions &&\n serverLayer.hasDisallowedReactAPIDefinition(definitions)\n ) {\n return\n }\n }\n\n const overridden = entryConfig.getQuickInfoAtPosition(\n fileName,\n position,\n prior\n )\n if (overridden) return overridden\n\n return prior\n }\n\n // Show errors for disallowed imports\n proxy.getSemanticDiagnostics = (fileName: string) => {\n const prior = info.languageService.getSemanticDiagnostics(fileName)\n const source = getSource(fileName)\n if (!source) return prior\n\n let isClientEntry = false\n let isServerEntry = false\n const isAppEntry = isAppEntryFile(fileName)\n\n try {\n const entryInfo = getEntryInfo(fileName, true)\n isClientEntry = entryInfo.client\n isServerEntry = entryInfo.server\n } catch (e: any) {\n prior.push({\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.MISPLACED_ENTRY_DIRECTIVE,\n ...e,\n })\n isClientEntry = false\n isServerEntry = false\n }\n\n if (isInsideApp(fileName)) {\n const errorDiagnostic = errorEntry.getSemanticDiagnostics(\n source!,\n isClientEntry\n )\n prior.push(...errorDiagnostic)\n }\n\n ts.forEachChild(source!, (node) => {\n if (ts.isImportDeclaration(node)) {\n // import ...\n if (isAppEntry) {\n if (!isClientEntry || isServerEntry) {\n // Check if it has valid imports in the server layer\n const diagnostics =\n serverLayer.getSemanticDiagnosticsForImportDeclaration(\n source,\n node\n )\n prior.push(...diagnostics)\n }\n }\n } else if (\n ts.isVariableStatement(node) &&\n node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)\n ) {\n // export const ...\n if (isAppEntry) {\n // Check if it has correct option exports\n const diagnostics =\n entryConfig.getSemanticDiagnosticsForExportVariableStatement(\n source,\n node\n )\n const metadataDiagnostics = isClientEntry\n ? metadata.client.getSemanticDiagnosticsForExportVariableStatement(\n fileName,\n node\n )\n : metadata.server.getSemanticDiagnosticsForExportVariableStatement(\n fileName,\n node\n )\n prior.push(...diagnostics, ...metadataDiagnostics)\n }\n\n if (isClientEntry) {\n prior.push(\n ...clientBoundary.getSemanticDiagnosticsForExportVariableStatement(\n source,\n node\n )\n )\n }\n\n if (isServerEntry) {\n prior.push(\n ...serverBoundary.getSemanticDiagnosticsForExportVariableStatement(\n source,\n node\n )\n )\n }\n } else if (isDefaultFunctionExport(node)) {\n // export default function ...\n if (isAppEntry) {\n const diagnostics = entryDefault.getSemanticDiagnostics(\n fileName,\n source,\n node\n )\n prior.push(...diagnostics)\n }\n\n if (isClientEntry) {\n prior.push(\n ...clientBoundary.getSemanticDiagnosticsForFunctionExport(\n source,\n node\n )\n )\n }\n\n if (isServerEntry) {\n prior.push(\n ...serverBoundary.getSemanticDiagnosticsForFunctionExport(\n source,\n node\n )\n )\n }\n } else if (\n ts.isFunctionDeclaration(node) &&\n node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)\n ) {\n // export function ...\n if (isAppEntry) {\n const metadataDiagnostics = isClientEntry\n ? metadata.client.getSemanticDiagnosticsForExportVariableStatement(\n fileName,\n node\n )\n : metadata.server.getSemanticDiagnosticsForExportVariableStatement(\n fileName,\n node\n )\n prior.push(...metadataDiagnostics)\n }\n\n if (isClientEntry) {\n prior.push(\n ...clientBoundary.getSemanticDiagnosticsForFunctionExport(\n source,\n node\n )\n )\n }\n\n if (isServerEntry) {\n prior.push(\n ...serverBoundary.getSemanticDiagnosticsForFunctionExport(\n source,\n node\n )\n )\n }\n } else if (ts.isExportDeclaration(node)) {\n // export { ... }\n if (isAppEntry) {\n const metadataDiagnostics = isClientEntry\n ? metadata.client.getSemanticDiagnosticsForExportDeclaration(\n fileName,\n node\n )\n : metadata.server.getSemanticDiagnosticsForExportDeclaration(\n fileName,\n node\n )\n prior.push(...metadataDiagnostics)\n }\n\n if (isServerEntry) {\n prior.push(\n ...serverBoundary.getSemanticDiagnosticsForExportDeclaration(\n source,\n node\n )\n )\n }\n }\n })\n\n return prior\n }\n\n return proxy\n }\n\n return { create }\n}\n"],"names":["createTSPlugin","typescript","ts","create","info","isPluginEnabled","config","enabled","languageService","init","proxy","Object","k","keys","x","args","apply","getCompletionsAtPosition","fileName","position","options","prior","isGlobalCompletion","isMemberCompletion","isNewIdentifierLocation","entries","isAppEntryFile","entryInfo","getEntryInfo","client","serverLayer","filterCompletionsAtPosition","entryConfig","addCompletionsAtPosition","source","getSource","forEachChild","node","isPositionInsideNode","isDefaultFunctionExport","push","entryDefault","getCompletionEntryDetails","entryName","formatOptions","preferences","data","entryCompletionEntryDetails","getQuickInfoAtPosition","definitions","getDefinitionAtPosition","hasDisallowedReactAPIDefinition","overridden","getSemanticDiagnostics","isClientEntry","isServerEntry","isAppEntry","server","e","file","category","DiagnosticCategory","Error","code","NEXT_TS_ERRORS","MISPLACED_ENTRY_DIRECTIVE","isInsideApp","errorDiagnostic","errorEntry","isImportDeclaration","diagnostics","getSemanticDiagnosticsForImportDeclaration","isVariableStatement","modifiers","some","m","kind","SyntaxKind","ExportKeyword","getSemanticDiagnosticsForExportVariableStatement","metadataDiagnostics","metadata","clientBoundary","serverBoundary","getSemanticDiagnosticsForFunctionExport","isFunctionDeclaration","isExportDeclaration","getSemanticDiagnosticsForExportDeclaration"],"mappings":"AAAA;;;;;;;;CAQC;;;;+BAsBYA;;;eAAAA;;;uBAZN;0BACwB;+DAEP;+DACA;8DACC;uEACE;uEACA;iEACN;8DACE;;;;;;AAGhB,MAAMA,iBAAsD,CAAC,EAClEC,YAAYC,EAAE,EACf;IACC,SAASC,OAAOC,IAAsC;QACpD,qBAAqB;QACrB,6DAA6D;QAC7D,4DAA4D;QAC5D,qDAAqD;QACrD,gDAAgD;QAChD,MAAMC,kBAAkBD,KAAKE,MAAM,CAACC,OAAO,IAAI;QAE/C,IAAI,CAACF,iBAAiB;YACpB,OAAOD,KAAKI,eAAe;QAC7B;QAEAC,IAAAA,WAAI,EAAC;YACHP;YACAE;QACF;QAEA,0BAA0B;QAC1B,MAAMM,QAAkCC,OAAOR,MAAM,CAAC;QACtD,KAAK,IAAIS,KAAKD,OAAOE,IAAI,CAACT,KAAKI,eAAe,EAAG;YAC/C,MAAMM,IAAIV,KAAKI,eAAe,CAACI,EAAoC;YACnE,yEAAyE;YACzEF,KAAK,CAACE,EAAE,GAAG,CAAC,GAAGG,OAAoBD,EAAEE,KAAK,CAACZ,KAAKI,eAAe,EAAEO;QACnE;QAEA,kBAAkB;QAClBL,MAAMO,wBAAwB,GAAG,CAC/BC,UACAC,UACAC;YAEA,IAAIC,QAAQjB,KAAKI,eAAe,CAACS,wBAAwB,CACvDC,UACAC,UACAC,YACG;gBACHE,oBAAoB;gBACpBC,oBAAoB;gBACpBC,yBAAyB;gBACzBC,SAAS,EAAE;YACb;YACA,IAAI,CAACC,IAAAA,qBAAc,EAACR,WAAW,OAA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aAAa,IAClE;oBACA,sBAAsB;oBACtB,IAAItB,YAAY;wBACd,MAAMwB,sBAAsB1B,gBACxB2B,iBAAQ,CAACpD,MAAM,CAACkD,gDAAgD,CAC9D7D,UACAmB,QAEF4C,iBAAQ,CAACxB,MAAM,CAACsB,gDAAgD,CAC9D7D,UACAmB;wBAENhB,MAAMmB,IAAI,IAAIwC;oBAChB;oBAEA,IAAI1B,eAAe;wBACjBjC,MAAMmB,IAAI,IACL0C,uBAAc,CAACE,uCAAuC,CACvDlD,QACAG;oBAGN;oBAEA,IAAIkB,eAAe;wBACjBlC,MAAMmB,IAAI,IACL2C,uBAAc,CAACC,uCAAuC,CACvDlD,QACAG;oBAGN;gBACF,OAAO,IAAInC,GAAGoF,mBAAmB,CAACjD,OAAO;oBACvC,iBAAiB;oBACjB,IAAImB,YAAY;wBACd,MAAMwB,sBAAsB1B,gBACxB2B,iBAAQ,CAACpD,MAAM,CAAC0D,0CAA0C,CACxDrE,UACAmB,QAEF4C,iBAAQ,CAACxB,MAAM,CAAC8B,0CAA0C,CACxDrE,UACAmB;wBAENhB,MAAMmB,IAAI,IAAIwC;oBAChB;oBAEA,IAAIzB,eAAe;wBACjBlC,MAAMmB,IAAI,IACL2C,uBAAc,CAACI,0CAA0C,CAC1DrD,QACAG;oBAGN;gBACF;YACF;YAEA,OAAOhB;QACT;QAEA,OAAOX;IACT;IAEA,OAAO;QAAEP;IAAO;AAClB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/client-boundary.d.ts b/e-commerce/node_modules/next/dist/server/typescript/rules/client-boundary.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..59020314ddb1369d070a534d2bd1bd8467c71f0f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/client-boundary.d.ts @@ -0,0 +1,6 @@ +import type tsModule from 'typescript/lib/tsserverlibrary'; +declare const clientBoundary: { + getSemanticDiagnosticsForExportVariableStatement(source: tsModule.SourceFile, node: tsModule.VariableStatement): tsModule.Diagnostic[]; + getSemanticDiagnosticsForFunctionExport(source: tsModule.SourceFile, node: tsModule.FunctionDeclaration | tsModule.ArrowFunction): tsModule.Diagnostic[]; +}; +export default clientBoundary; diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/client-boundary.js b/e-commerce/node_modules/next/dist/server/typescript/rules/client-boundary.js new file mode 100644 index 0000000000000000000000000000000000000000..ac4a100750ba40cf7a31b64d92f0a199dad7e174 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/client-boundary.js @@ -0,0 +1,100 @@ +// This module provides intellisense for all components that has the `"use client"` directive. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _constant = require("../constant"); +const _utils = require("../utils"); +const clientBoundary = { + getSemanticDiagnosticsForExportVariableStatement (source, node) { + const ts = (0, _utils.getTs)(); + const diagnostics = []; + if (ts.isVariableDeclarationList(node.declarationList)) { + for (const declaration of node.declarationList.declarations){ + const initializer = declaration.initializer; + if (initializer && ts.isArrowFunction(initializer)) { + diagnostics.push(...clientBoundary.getSemanticDiagnosticsForFunctionExport(source, initializer)); + } + } + } + return diagnostics; + }, + getSemanticDiagnosticsForFunctionExport (source, node) { + var _node_parameters; + const ts = (0, _utils.getTs)(); + const typeChecker = (0, _utils.getTypeChecker)(); + if (!typeChecker) return []; + const diagnostics = []; + const isErrorFile = /[\\/]error\.tsx?$/.test(source.fileName); + const isGlobalErrorFile = /[\\/]global-error\.tsx?$/.test(source.fileName); + const props = (_node_parameters = node.parameters) == null ? void 0 : _node_parameters[0]; + if (props) { + var _propsType_symbol_getDeclarations, _propsType_symbol; + const propsType = typeChecker.getTypeAtLocation(props); + const typeNode = (_propsType_symbol = propsType.symbol) == null ? void 0 : (_propsType_symbol_getDeclarations = _propsType_symbol.getDeclarations()) == null ? void 0 : _propsType_symbol_getDeclarations[0]; + if (typeNode && ts.isTypeLiteralNode(typeNode)) { + for (const member of typeNode.members){ + if (ts.isPropertySignature(member)) { + const propName = member.name.getText(); + const propType = member.type; + if (propType) { + var _propTypeInfo_symbol_getDeclarations, _propTypeInfo_symbol; + const propTypeInfo = typeChecker.getTypeAtLocation(propType); + const typeDeclarationNode = (_propTypeInfo_symbol = propTypeInfo.symbol) == null ? void 0 : (_propTypeInfo_symbol_getDeclarations = _propTypeInfo_symbol.getDeclarations()) == null ? void 0 : _propTypeInfo_symbol_getDeclarations[0]; + if (typeDeclarationNode) { + if (ts.isFunctionTypeNode(typeDeclarationNode) || // someFunc(): void + ts.isMethodSignature(typeDeclarationNode)) { + // By convention, props named "action" can accept functions since we + // assume these are Server Actions. Structurally, there's no + // difference between a Server Action and a normal function until + // TypeScript exposes directives in the type of a function. This + // will miss accidentally passing normal functions but a false + // negative is better than a false positive given how frequent the + // false-positive would be. + const maybeServerAction = propName === 'action' || /.+Action$/.test(propName); + // There's a special case for error files where the + // framework-injected `reset` and `retry` props are + // allowed to be functions. Next.js provides these props, the + // user doesn't pass them, so they don't need to be + // serializable. + // https://github.com/vercel/next.js/issues/46573 + const isErrorBoundaryFunctionProp = (isErrorFile || isGlobalErrorFile) && (propName === 'reset' || propName === 'retry'); + if (!maybeServerAction && !isErrorBoundaryFunctionProp) { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Warning, + code: _constant.NEXT_TS_ERRORS.INVALID_CLIENT_ENTRY_PROP, + messageText: `Props must be serializable for components in the "use client" entry file. ` + `"${propName}" is a function that's not a Server Action. ` + `Rename "${propName}" either to "action" or have its name end with "Action" e.g. "${propName}Action" to indicate it is a Server Action.`, + start: propType.getStart(), + length: propType.getWidth() + }); + } + } else if (// Show warning for not serializable props. + ts.isConstructorTypeNode(typeDeclarationNode) || ts.isClassDeclaration(typeDeclarationNode)) { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Warning, + code: _constant.NEXT_TS_ERRORS.INVALID_CLIENT_ENTRY_PROP, + messageText: `Props must be serializable for components in the "use client" entry file, "${propName}" is invalid.`, + start: propType.getStart(), + length: propType.getWidth() + }); + } + } + } + } + } + } + } + return diagnostics; + } +}; +const _default = clientBoundary; + +//# sourceMappingURL=client-boundary.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/client-boundary.js.map b/e-commerce/node_modules/next/dist/server/typescript/rules/client-boundary.js.map new file mode 100644 index 0000000000000000000000000000000000000000..95d1117940798e43bc021d1cab0539982885f3e2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/client-boundary.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/typescript/rules/client-boundary.ts"],"sourcesContent":["// This module provides intellisense for all components that has the `\"use client\"` directive.\n\nimport { NEXT_TS_ERRORS } from '../constant'\nimport { getTs, getTypeChecker } from '../utils'\nimport type tsModule from 'typescript/lib/tsserverlibrary'\n\nconst clientBoundary = {\n getSemanticDiagnosticsForExportVariableStatement(\n source: tsModule.SourceFile,\n node: tsModule.VariableStatement\n ) {\n const ts = getTs()\n\n const diagnostics: tsModule.Diagnostic[] = []\n\n if (ts.isVariableDeclarationList(node.declarationList)) {\n for (const declaration of node.declarationList.declarations) {\n const initializer = declaration.initializer\n if (initializer && ts.isArrowFunction(initializer)) {\n diagnostics.push(\n ...clientBoundary.getSemanticDiagnosticsForFunctionExport(\n source,\n initializer\n )\n )\n }\n }\n }\n\n return diagnostics\n },\n\n getSemanticDiagnosticsForFunctionExport(\n source: tsModule.SourceFile,\n node: tsModule.FunctionDeclaration | tsModule.ArrowFunction\n ) {\n const ts = getTs()\n const typeChecker = getTypeChecker()\n if (!typeChecker) return []\n\n const diagnostics: tsModule.Diagnostic[] = []\n\n const isErrorFile = /[\\\\/]error\\.tsx?$/.test(source.fileName)\n const isGlobalErrorFile = /[\\\\/]global-error\\.tsx?$/.test(source.fileName)\n\n const props = node.parameters?.[0]\n if (props) {\n const propsType = typeChecker.getTypeAtLocation(props)\n const typeNode = propsType.symbol?.getDeclarations()?.[0]\n\n if (typeNode && ts.isTypeLiteralNode(typeNode)) {\n for (const member of typeNode.members) {\n if (ts.isPropertySignature(member)) {\n const propName = member.name.getText()\n const propType = member.type\n\n if (propType) {\n const propTypeInfo = typeChecker.getTypeAtLocation(propType)\n const typeDeclarationNode =\n propTypeInfo.symbol?.getDeclarations()?.[0]\n\n if (typeDeclarationNode) {\n if (\n ts.isFunctionTypeNode(typeDeclarationNode) ||\n // someFunc(): void\n ts.isMethodSignature(typeDeclarationNode)\n ) {\n // By convention, props named \"action\" can accept functions since we\n // assume these are Server Actions. Structurally, there's no\n // difference between a Server Action and a normal function until\n // TypeScript exposes directives in the type of a function. This\n // will miss accidentally passing normal functions but a false\n // negative is better than a false positive given how frequent the\n // false-positive would be.\n const maybeServerAction =\n propName === 'action' || /.+Action$/.test(propName)\n\n // There's a special case for error files where the\n // framework-injected `reset` and `retry` props are\n // allowed to be functions. Next.js provides these props, the\n // user doesn't pass them, so they don't need to be\n // serializable.\n // https://github.com/vercel/next.js/issues/46573\n const isErrorBoundaryFunctionProp =\n (isErrorFile || isGlobalErrorFile) &&\n (propName === 'reset' || propName === 'retry')\n\n if (!maybeServerAction && !isErrorBoundaryFunctionProp) {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Warning,\n code: NEXT_TS_ERRORS.INVALID_CLIENT_ENTRY_PROP,\n messageText:\n `Props must be serializable for components in the \"use client\" entry file. ` +\n `\"${propName}\" is a function that's not a Server Action. ` +\n `Rename \"${propName}\" either to \"action\" or have its name end with \"Action\" e.g. \"${propName}Action\" to indicate it is a Server Action.`,\n start: propType.getStart(),\n length: propType.getWidth(),\n })\n }\n } else if (\n // Show warning for not serializable props.\n ts.isConstructorTypeNode(typeDeclarationNode) ||\n ts.isClassDeclaration(typeDeclarationNode)\n ) {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Warning,\n code: NEXT_TS_ERRORS.INVALID_CLIENT_ENTRY_PROP,\n messageText: `Props must be serializable for components in the \"use client\" entry file, \"${propName}\" is invalid.`,\n start: propType.getStart(),\n length: propType.getWidth(),\n })\n }\n }\n }\n }\n }\n }\n }\n\n return diagnostics\n },\n}\n\nexport default clientBoundary\n"],"names":["clientBoundary","getSemanticDiagnosticsForExportVariableStatement","source","node","ts","getTs","diagnostics","isVariableDeclarationList","declarationList","declaration","declarations","initializer","isArrowFunction","push","getSemanticDiagnosticsForFunctionExport","typeChecker","getTypeChecker","isErrorFile","test","fileName","isGlobalErrorFile","props","parameters","propsType","getTypeAtLocation","typeNode","symbol","getDeclarations","isTypeLiteralNode","member","members","isPropertySignature","propName","name","getText","propType","type","propTypeInfo","typeDeclarationNode","isFunctionTypeNode","isMethodSignature","maybeServerAction","isErrorBoundaryFunctionProp","file","category","DiagnosticCategory","Warning","code","NEXT_TS_ERRORS","INVALID_CLIENT_ENTRY_PROP","messageText","start","getStart","length","getWidth","isConstructorTypeNode","isClassDeclaration"],"mappings":"AAAA,8FAA8F;;;;;+BA6H9F;;;eAAA;;;0BA3H+B;uBACO;AAGtC,MAAMA,iBAAiB;IACrBC,kDACEC,MAA2B,EAC3BC,IAAgC;QAEhC,MAAMC,KAAKC,IAAAA,YAAK;QAEhB,MAAMC,cAAqC,EAAE;QAE7C,IAAIF,GAAGG,yBAAyB,CAACJ,KAAKK,eAAe,GAAG;YACtD,KAAK,MAAMC,eAAeN,KAAKK,eAAe,CAACE,YAAY,CAAE;gBAC3D,MAAMC,cAAcF,YAAYE,WAAW;gBAC3C,IAAIA,eAAeP,GAAGQ,eAAe,CAACD,cAAc;oBAClDL,YAAYO,IAAI,IACXb,eAAec,uCAAuC,CACvDZ,QACAS;gBAGN;YACF;QACF;QAEA,OAAOL;IACT;IAEAQ,yCACEZ,MAA2B,EAC3BC,IAA2D;YAW7CA;QATd,MAAMC,KAAKC,IAAAA,YAAK;QAChB,MAAMU,cAAcC,IAAAA,qBAAc;QAClC,IAAI,CAACD,aAAa,OAAO,EAAE;QAE3B,MAAMT,cAAqC,EAAE;QAE7C,MAAM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WAAWA,aAAa,OAAM;oCAE9C,IAAI,CAACS,qBAAqB,CAACC,6BAA6B;wCACtDpC,YAAYO,IAAI,CAAC;4CACf8B,MAAMzC;4CACN0C,UAAUxC,GAAGyC,kBAAkB,CAACC,OAAO;4CACvCC,MAAMC,wBAAc,CAACC,yBAAyB;4CAC9CC,aACE,CAAC,0EAA0E,CAAC,GAC5E,CAAC,CAAC,EAAElB,SAAS,4CAA4C,CAAC,GAC1D,CAAC,QAAQ,EAAEA,SAAS,8DAA8D,EAAEA,SAAS,0CAA0C,CAAC;4CAC1ImB,OAAOhB,SAASiB,QAAQ;4CACxBC,QAAQlB,SAASmB,QAAQ;wCAC3B;oCACF;gCACF,OAAO,IACL,2CAA2C;gCAC3ClD,GAAGmD,qBAAqB,CAACjB,wBACzBlC,GAAGoD,kBAAkB,CAAClB,sBACtB;oCACAhC,YAAYO,IAAI,CAAC;wCACf8B,MAAMzC;wCACN0C,UAAUxC,GAAGyC,kBAAkB,CAACC,OAAO;wCACvCC,MAAMC,wBAAc,CAACC,yBAAyB;wCAC9CC,aAAa,CAAC,2EAA2E,EAAElB,SAAS,aAAa,CAAC;wCAClHmB,OAAOhB,SAASiB,QAAQ;wCACxBC,QAAQlB,SAASmB,QAAQ;oCAC3B;gCACF;4BACF;wBACF;oBACF;gBACF;YACF;QACF;QAEA,OAAOhD;IACT;AACF;MAEA,WAAeN","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/config.d.ts b/e-commerce/node_modules/next/dist/server/typescript/rules/config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..97292355d3c59e71cd472086c2399a8e326783a7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/config.d.ts @@ -0,0 +1,8 @@ +import type tsModule from 'typescript/lib/tsserverlibrary'; +declare const config: { + addCompletionsAtPosition(fileName: string, position: number, prior: tsModule.WithMetadata): void; + getQuickInfoAtPosition(fileName: string, position: number, prior?: tsModule.QuickInfo): tsModule.QuickInfo | undefined; + getCompletionEntryDetails(entryName: string, data: tsModule.CompletionEntryData, fileName: string): tsModule.CompletionEntryDetails | undefined; + getSemanticDiagnosticsForExportVariableStatement(source: tsModule.SourceFile, node: tsModule.VariableStatement): tsModule.Diagnostic[]; +}; +export default config; diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/config.js b/e-commerce/node_modules/next/dist/server/typescript/rules/config.js new file mode 100644 index 0000000000000000000000000000000000000000..a4975cd43d705cad4938d400a4abf1bf48facad4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/config.js @@ -0,0 +1,561 @@ +// This module provides intellisense for page and layout's exported configs. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _utils = require("../utils"); +const _constant = require("../constant"); +const API_DOCS = { + dynamic: { + description: 'The `dynamic` option provides a few ways to opt in or out of dynamic behavior.', + options: { + '"auto"': "Heuristic to cache as much as possible but doesn't prevent any component to opt-in to dynamic behavior.", + '"force-dynamic"': 'This disables all caching of fetches and always revalidates. (This is equivalent to `getServerSideProps`.)', + '"error"': 'This errors if any dynamic Hooks or fetches are used. (This is equivalent to `getStaticProps`.)', + '"force-static"': 'This forces caching of all fetches and returns empty values from `cookies`, `headers` and `useSearchParams`.' + }, + link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamic' + }, + fetchCache: { + description: "The `fetchCache` option controls how Next.js statically caches fetches. By default it statically caches fetches reachable before any dynamic Hooks are used, and it doesn't cache fetches that are discovered after that.", + options: { + '"force-no-store"': "This lets you intentionally opt-out of all caching of data. This option forces all fetches to be refetched every request even if the `cache: 'force-cache'` option is passed to `fetch()`.", + '"only-no-store"': "This lets you enforce that all data opts out of caching. This option makes `fetch()` reject with an error if `cache: 'force-cache'` is provided. It also changes the default to `no-store`.", + '"default-no-store"': "Allows any explicit `cache` option to be passed to `fetch()` but if `'default'`, or no option, is provided then it defaults to `'no-store'`. This means that even fetches before a dynamic Hook are considered dynamic.", + '"auto"': "This is the default option. It caches any fetches with the default `cache` option provided, that happened before a dynamic Hook is used and don't cache any such fetches if they're issued after a dynamic Hook.", + '"default-cache"': "Allows any explicit `cache` option to be passed to `fetch()` but if `'default'`, or no option, is provided then it defaults to `'force-cache'`. This means that even fetches before a dynamic Hook are considered dynamic.", + '"only-cache"': "This lets you enforce that all data opts into caching. This option makes `fetch()` reject with an error if `cache: 'force-cache'` is provided. It also changes the default to `force-cache`. This error can be discovered early during static builds - or dynamically during Edge rendering.", + '"force-cache"': "This lets you intentionally opt-in to all caching of data. This option forces all fetches to be cache even if the `cache: 'no-store'` option is passed to `fetch()`." + }, + link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#fetchcache' + }, + preferredRegion: { + description: '@deprecated\\n\\nThe `preferredRegion` route segment config is deprecated. Remove this export.', + options: { + '"auto"': '@deprecated\\n\\nNext.js will first deploy to the `"home"` region. Then if it doesn\'t detect any waterfall requests after a few requests, it can upgrade that route, to be deployed globally. If it detects any waterfall requests after that, it can eventually downgrade back to `"home`".', + '"global"': '@deprecated\\n\\nPrefer deploying globally.', + '"home"': '@deprecated\\n\\nPrefer deploying to the Home region.' + }, + link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#preferredregion', + isValid: (value)=>{ + try { + const parsed = JSON.parse(value); + return typeof parsed === 'string' || Array.isArray(parsed) && !parsed.some((v)=>typeof v !== 'string'); + } catch (err) { + return false; + } + }, + getHint: (value)=>{ + if (value === 'auto') return `Automatically chosen by Next.js.`; + if (value === 'global') return `Prefer deploying globally.`; + if (value === 'home') return `Prefer deploying to the Home region.`; + if (Array.isArray(value)) return `Deploy to regions: ${value.join(', ')}.`; + if (typeof value === 'string') return `Deploy to region: ${value}.`; + } + }, + revalidate: { + description: "The `revalidate` option sets the default revalidation time for that layout or page. Note that it doesn't override the value specify by each `fetch()`.", + type: 'mixed', + options: { + false: 'This is the default and changes the fetch cache to indefinitely cache anything that uses force-cache or is fetched before a dynamic Hook/fetch.', + 0: 'Specifying `0` implies that this layout or page should never be static.', + 30: 'Set the revalidation time to `30` seconds. The value can be `0` or any positive number.' + }, + link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#revalidate', + isValid: (value)=>{ + return value === 'false' || Number(value.replace(/_/g, '')) >= 0; + }, + getHint: (value)=>{ + return `Set the default revalidation time to \`${value}\` seconds.`; + } + }, + dynamicParams: { + description: '`dynamicParams` replaces the `fallback` option of `getStaticPaths`. It controls whether we allow `dynamicParams` beyond the generated static params from `generateStaticParams`.', + options: { + true: 'Allow rendering dynamic params that are not generated by `generateStaticParams`.', + false: 'Disallow rendering dynamic params that are not generated by `generateStaticParams`.' + }, + link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamicparams', + isValid: (value)=>{ + return value === 'true' || value === 'false'; + } + }, + runtime: { + description: 'The `runtime` option controls the preferred runtime to render this route.', + options: { + '"nodejs"': 'Prefer the Node.js runtime.', + '"edge"': `@deprecated\n\nThe Edge Runtime is deprecated. Use \`"nodejs"\` instead.`, + '"experimental-edge"': `@deprecated\n\nThis option is no longer experimental. Use \`edge\` instead.` + }, + link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#runtime' + }, + metadata: { + description: 'Next.js Metadata configurations', + link: 'https://nextjs.org/docs/app/building-your-application/optimizing/metadata', + insertText: 'metadata: Metadata = {};' + }, + generateMetadata: { + description: 'Next.js generateMetadata configurations', + link: 'https://nextjs.org/docs/app/api-reference/functions/generate-metadata', + insertText: 'generateMetadata = (): Metadata => { return {} };' + }, + maxDuration: { + description: '`maxDuration` allows you to set max default execution time for your function. If it is not specified, the default value is dependent on your deployment platform and plan.', + link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#maxduration' + }, + instant: { + description: `Enables instant navigation validation for this segment.`, + link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant', + type: 'true | object | false', + // TODO: ideally, we'd validate the config object somehow, but this is difficult to do + // with the way this plugin is currently structured. + // For now, since we don't provide an `options` here, we won't do any validation in + // `getSemanticDiagnosticsForExportVariableStatement` below, and only provide hover a tooltip + autocomplete. + insertText: 'instant = true;' + }, + prefetch: { + description: `Controls prefetching behavior for this segment. Some options are experimental and may change.`, + link: '(docs coming soon)', + type: `"auto" | "partial" | "force-disabled"`, + options: { + auto: 'Default. Framework decides based on instant validation and segment configuration. You do not need to set this explicitly.', + partial: 'Enables Partial Prefetching for this segment. When a static prefetch is insufficient, Next.js may prefetch the segment with a runtime server request so it can access session data, such as cookies.', + 'force-disabled': 'Never prefetch this segment.' + }, + insertText: `prefetch = 'partial';` + }, + ensureStatic: { + description: `Controls which rendering phases require static output for this segment. This option is experimental and may change.`, + link: '(docs coming soon)', + type: `"auto" | "shell" | "prefetch" | "navigation" | false`, + options: { + '"auto"': 'Default. The shell, prefetch, or entire page will automatically be prerendered statically if possible.', + '"shell"': 'Force the shell for the route to be prerendered statically.', + '"prefetch"': 'Force both the shell and the prefetch (``) for the route to be prerendered statically.', + '"navigation"': 'Require the route to be fully static.', + false: 'Indicate that this segment must use the default behavior and should not have `ensureStatic = "shell" | "prefetch" | "navigation"` applied to it by another segment. Errors if another segment on the route uses `ensureStatic` with those values.' + }, + insertText: `ensureStatic = 'shell';`, + isValid: (value)=>{ + try { + const parsed = JSON.parse(value); + return VALID_ENSURE_STATIC_VALUES.includes(parsed); + } catch { + return false; + } + } + }, + unstable_dynamicStaleTime: { + description: `Controls how long the client-side router cache retains dynamic page data (in seconds). Pages only — not allowed in layouts. Cannot be combined with \`instant\`.`, + link: '(docs coming soon)', + type: 'number', + isValid: (value)=>{ + return Number(value.replace(/_/g, '')) >= 0; + }, + getHint: (value)=>{ + return `Set the dynamic stale time to \`${value}\` seconds.`; + } + } +}; +const VALID_ENSURE_STATIC_VALUES = [ + 'auto', + 'shell', + 'prefetch', + 'navigation', + false +]; +function visitEntryConfig(fileName, position, callback) { + const source = (0, _utils.getSource)(fileName); + if (source) { + const ts = (0, _utils.getTs)(); + ts.forEachChild(source, function visit(node) { + // Covered by this node + if ((0, _utils.isPositionInsideNode)(position, node)) { + var _node_modifiers; + // Export variable + if (ts.isVariableStatement(node) && ((_node_modifiers = node.modifiers) == null ? void 0 : _node_modifiers.some((m)=>m.kind === ts.SyntaxKind.ExportKeyword))) { + if (ts.isVariableDeclarationList(node.declarationList)) { + for (const declaration of node.declarationList.declarations){ + if ((0, _utils.isPositionInsideNode)(position, declaration)) { + // `export const ... = ...` + const text = declaration.name.getText(); + callback(text, declaration); + } + } + } + } + } + }); + } +} +function createAutoCompletionOptionName(sort, name) { + const ts = (0, _utils.getTs)(); + return { + name, + insertText: API_DOCS[name].insertText, + sortText: '!' + sort, + kind: ts.ScriptElementKind.constElement, + kindModifiers: ts.ScriptElementKindModifier.exportedModifier, + labelDetails: { + description: `Next.js ${name} option` + }, + data: { + exportName: name, + moduleSpecifier: 'next/typescript/entry_option_name' + } + }; +} +function createAutoCompletionOptionValue(sort, name, apiName) { + const ts = (0, _utils.getTs)(); + const isString = name.startsWith('"'); + return { + name, + insertText: (0, _utils.removeStringQuotes)(name), + sortText: '' + sort, + kind: isString ? ts.ScriptElementKind.string : ts.ScriptElementKind.unknown, + kindModifiers: ts.ScriptElementKindModifier.none, + labelDetails: { + description: `Next.js ${apiName} option` + }, + data: { + exportName: apiName, + moduleSpecifier: 'next/typescript/entry_option_value' + } + }; +} +function getAPIDescription(api) { + return API_DOCS[api].description + '\n\n' + Object.entries(API_DOCS[api].options || {}).map(([key, value])=>`- \`${key}\`: ${value}`).join('\n'); +} +const config = { + // Auto completion for entry exported configs. + addCompletionsAtPosition (fileName, position, prior) { + visitEntryConfig(fileName, position, (entryConfig, declaration)=>{ + if (!API_DOCS[entryConfig]) { + if ((0, _utils.isPositionInsideNode)(position, declaration.name)) { + prior.entries.push(...Object.keys(API_DOCS).map((name, index)=>{ + return createAutoCompletionOptionName(index, name); + })); + } + return; + } + prior.entries.push(...Object.keys(API_DOCS[entryConfig].options || {}).map((name, index)=>{ + return createAutoCompletionOptionValue(index, name, entryConfig); + })); + }); + }, + // Show docs when hovering on the exported configs. + getQuickInfoAtPosition (fileName, position, prior) { + const ts = (0, _utils.getTs)(); + let overridden; + visitEntryConfig(fileName, position, (entryConfig, declaration)=>{ + if (!API_DOCS[entryConfig]) return; + const name = declaration.name; + const value = declaration.initializer; + const docsLink = { + kind: 'text', + text: `\n\nRead more about the "${entryConfig}" option: ` + API_DOCS[entryConfig].link + }; + // When the value is a flexible type (like a function), also compute its + // inferred type so we can surface it alongside the docs. This is useful + // even when the value is considered invalid by the config validation, + // as long as it's not a direct literal export. + let displayParts = []; + const typeChecker = (0, _utils.getTypeChecker)(); + const isString = !!value && ts.isStringLiteral(value); + const isFunctionValue = !!value && !isString && (ts.isArrowFunction(value) || ts.isFunctionExpression(value) || ts.isFunctionDeclaration(value)); + if (typeChecker && value && isFunctionValue) { + try { + // If we're hovering the config identifier, ask for the type at the + // identifier; otherwise, ask at the value node. This makes sure + // highlighting `generateMetadata` itself also shows the inferred type. + const typeTarget = (0, _utils.isPositionInsideNode)(position, name) ? name : value; + const type = typeChecker.getTypeAtLocation(typeTarget); + if (type) { + const typeString = typeChecker.typeToString(type, typeTarget); + if (typeString) { + displayParts = [ + { + text: typeString, + kind: 'typeName' + } + ]; + } + } + } catch { + // If type checking fails, continue without type info. + } + } + // For non-function values (like literals), hovering the value should show + // option-specific docs. For function-valued configs (e.g. `generateMetadata`), + // we let TypeScript handle hover anywhere in the initializer except for the + // export identifier itself. + if (value && !isFunctionValue && (0, _utils.isPositionInsideNode)(position, value)) { + var _API_DOCS_entryConfig_isValid, _API_DOCS_entryConfig, _API_DOCS_entryConfig_options; + // Hovering the value of the config + const text = (0, _utils.removeStringQuotes)(value.getText()); + const key = isString ? `"${text}"` : text; + const isValid = API_DOCS[entryConfig].isValid ? (_API_DOCS_entryConfig_isValid = (_API_DOCS_entryConfig = API_DOCS[entryConfig]).isValid) == null ? void 0 : _API_DOCS_entryConfig_isValid.call(_API_DOCS_entryConfig, key) : !!((_API_DOCS_entryConfig_options = API_DOCS[entryConfig].options) == null ? void 0 : _API_DOCS_entryConfig_options[key]); + if (isValid) { + var _API_DOCS_entryConfig_options1, _API_DOCS_entryConfig_getHint, _API_DOCS_entryConfig1; + const documentation = [ + ...(prior == null ? void 0 : prior.documentation) || [], + { + kind: 'text', + text: ((_API_DOCS_entryConfig_options1 = API_DOCS[entryConfig].options) == null ? void 0 : _API_DOCS_entryConfig_options1[key]) || ((_API_DOCS_entryConfig_getHint = (_API_DOCS_entryConfig1 = API_DOCS[entryConfig]).getHint) == null ? void 0 : _API_DOCS_entryConfig_getHint.call(_API_DOCS_entryConfig1, key)) || '' + }, + docsLink + ]; + overridden = prior ? { + ...prior, + documentation + } : { + kind: ts.ScriptElementKind.enumElement, + kindModifiers: ts.ScriptElementKindModifier.none, + textSpan: { + start: value.getStart(), + length: value.getWidth() + }, + displayParts: [], + documentation + }; + } else { + // Wrong value: still show the docs link, and when available, the + // inferred type for non-literal (i.e. non-direct) exports. + overridden = { + kind: ts.ScriptElementKind.enumElement, + kindModifiers: ts.ScriptElementKindModifier.none, + textSpan: { + start: value.getStart(), + length: value.getWidth() + }, + displayParts, + documentation: [ + docsLink + ] + }; + } + } else { + // For function-valued configs, if we're hovering anywhere within the + // initializer (including `async`, parameters, or the body) but not on + // the export identifier itself, don't override TypeScript's default + // hover. We only want to override when hovering the config identifier + // (e.g. `generateMetadata`), not arbitrary tokens within the function. + if (isFunctionValue && (0, _utils.isPositionInsideNode)(position, value) && // hover is somewhere within the function initializer + !(0, _utils.isPositionInsideNode)(position, name) // ...but not on the export identifier itself + ) { + return; + } + // Hovers the name of the config + const documentation = [ + ...(prior == null ? void 0 : prior.documentation) || [], + { + kind: 'text', + text: getAPIDescription(entryConfig) + }, + docsLink + ]; + overridden = prior ? { + ...prior, + documentation + } : { + kind: ts.ScriptElementKind.enumElement, + kindModifiers: ts.ScriptElementKindModifier.none, + textSpan: { + start: name.getStart(), + length: name.getWidth() + }, + displayParts, + documentation + }; + } + }); + return overridden; + }, + // Show details on the side when auto completing. + getCompletionEntryDetails (entryName, data, fileName) { + const ts = (0, _utils.getTs)(); + if (data && data.moduleSpecifier && data.moduleSpecifier.startsWith('next/typescript')) { + let content = ''; + if (data.moduleSpecifier === 'next/typescript/entry_option_name') { + content = getAPIDescription(entryName); + } else { + const options = API_DOCS[data.exportName].options; + if (!options) return; + content = options[entryName]; + } + if (entryName === 'metadata' || entryName === 'generateMetadata') { + const sourceFile = (0, _utils.getSource)(fileName); + let start = 0; + let foundMetadataImport = false; + if (sourceFile) { + const visitor = (node)=>{ + // Check for top directive + if (ts.isExpressionStatement(node) && ts.isStringLiteral(node.expression) && node.expression.getStart() === 0) { + const text = node.expression.text; + if (text.startsWith('use ')) { + start = node.end + 1; + return node // Continue traversal + ; + } + } + // Check for Metadata import + if (ts.isImportDeclaration(node) && (node.moduleSpecifier.getText() === '"next"' || node.moduleSpecifier.getText() === "'next'")) { + var _node_importClause; + const namedImports = (_node_importClause = node.importClause) == null ? void 0 : _node_importClause.namedBindings; + if (namedImports && ts.isNamedImports(namedImports)) { + foundMetadataImport = namedImports.elements.some((element)=>{ + var _element_propertyName; + const name = element.name.getText(); + const propertyName = (_element_propertyName = element.propertyName) == null ? void 0 : _element_propertyName.getText(); + return name === 'Metadata' || propertyName === 'Metadata'; + }); + if (foundMetadataImport) { + return; // Stop traversal + } + } + } + return node; + }; + for (const statement of sourceFile.statements){ + if (foundMetadataImport) break; + ts.visitNode(statement, visitor); + } + } + return { + name: entryName, + kind: ts.ScriptElementKind.enumElement, + kindModifiers: ts.ScriptElementKindModifier.none, + displayParts: [], + codeActions: foundMetadataImport ? undefined : [ + { + description: `Import type 'Metadata' from module 'next'`, + changes: [ + { + fileName, + textChanges: [ + { + span: { + start, + length: 0 + }, + newText: `import type { Metadata } from 'next';\n` + } + ] + } + ] + } + ], + documentation: [ + { + kind: 'text', + text: content + } + ] + }; + } + return { + name: entryName, + kind: ts.ScriptElementKind.enumElement, + kindModifiers: ts.ScriptElementKindModifier.none, + displayParts: [], + documentation: [ + { + kind: 'text', + text: content + } + ] + }; + } + }, + // Show errors for invalid export fields. + getSemanticDiagnosticsForExportVariableStatement (source, node) { + const ts = (0, _utils.getTs)(); + const diagnostics = []; + // Check if it has correct option exports + if (ts.isVariableDeclarationList(node.declarationList)) { + for (const declaration of node.declarationList.declarations){ + const name = declaration.name; + if (ts.isIdentifier(name)) { + if (!_constant.ALLOWED_EXPORTS.includes(name.text) && !API_DOCS[name.text]) { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_ENTRY_EXPORT, + messageText: `"${name.text}" is not a valid Next.js entry export value.`, + start: name.getStart(), + length: name.getWidth() + }); + } else if (API_DOCS[name.text]) { + // Check if the value is valid + const value = declaration.initializer; + const options = API_DOCS[name.text].options; + if (value && options) { + let displayedValue = ''; + let errorMessage = ''; + let isInvalid = false; + if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value)) { + var _API_DOCS_name_text_isValid, _API_DOCS_name_text; + const val = '"' + (0, _utils.removeStringQuotes)(value.getText()) + '"'; + const allowedValues = Object.keys(options).filter((v)=>/^['"]/.test(v)); + if (!allowedValues.includes(val) && !((_API_DOCS_name_text_isValid = (_API_DOCS_name_text = API_DOCS[name.text]).isValid) == null ? void 0 : _API_DOCS_name_text_isValid.call(_API_DOCS_name_text, val))) { + isInvalid = true; + displayedValue = val; + } + } else if (ts.isNumericLiteral(value) || ts.isPrefixUnaryExpression(value) && ts.isMinusToken(value.operator) && (ts.isNumericLiteral(value.operand.kind) || ts.isIdentifier(value.operand.kind) && value.operand.kind.getText() === 'Infinity') || ts.isIdentifier(value) && value.getText() === 'Infinity') { + var _API_DOCS_name_text_isValid1, _API_DOCS_name_text1; + const v = value.getText(); + if (!((_API_DOCS_name_text_isValid1 = (_API_DOCS_name_text1 = API_DOCS[name.text]).isValid) == null ? void 0 : _API_DOCS_name_text_isValid1.call(_API_DOCS_name_text1, v))) { + isInvalid = true; + displayedValue = v; + } + } else if (value.kind === ts.SyntaxKind.TrueKeyword || value.kind === ts.SyntaxKind.FalseKeyword) { + var _API_DOCS_name_text_isValid2, _API_DOCS_name_text2; + const v = value.getText(); + if (!((_API_DOCS_name_text_isValid2 = (_API_DOCS_name_text2 = API_DOCS[name.text]).isValid) == null ? void 0 : _API_DOCS_name_text_isValid2.call(_API_DOCS_name_text2, v))) { + isInvalid = true; + displayedValue = v; + } + } else if (ts.isArrayLiteralExpression(value)) { + var _API_DOCS_name_text_isValid3, _API_DOCS_name_text3; + const v = value.getText(); + if (!((_API_DOCS_name_text_isValid3 = (_API_DOCS_name_text3 = API_DOCS[name.text]).isValid) == null ? void 0 : _API_DOCS_name_text_isValid3.call(_API_DOCS_name_text3, JSON.stringify(value.elements.map((e)=>e.getText()))))) { + isInvalid = true; + displayedValue = v; + } + } else if (// Other literals + ts.isBigIntLiteral(value) || ts.isObjectLiteralExpression(value) || ts.isRegularExpressionLiteral(value) || ts.isPrefixUnaryExpression(value)) { + isInvalid = true; + displayedValue = value.getText(); + } else { + // Not a literal, error because it's not statically analyzable + isInvalid = true; + displayedValue = value.getText(); + errorMessage = `"${displayedValue}" is not a valid value for the "${name.text}" option. The configuration must be statically analyzable.`; + } + if (isInvalid) { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_OPTION_VALUE, + messageText: errorMessage || `"${displayedValue}" is not a valid value for the "${name.text}" option.`, + start: value.getStart(), + length: value.getWidth() + }); + } + } + } + } + } + } + return diagnostics; + } +}; +const _default = config; + +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/config.js.map b/e-commerce/node_modules/next/dist/server/typescript/rules/config.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5cb4a373f54ded48c8709ee154c1c7bfb5f70f6b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/config.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/typescript/rules/config.ts"],"sourcesContent":["// This module provides intellisense for page and layout's exported configs.\n\nimport {\n getSource,\n isPositionInsideNode,\n getTs,\n removeStringQuotes,\n getTypeChecker,\n} from '../utils'\nimport { NEXT_TS_ERRORS, ALLOWED_EXPORTS } from '../constant'\nimport type tsModule from 'typescript/lib/tsserverlibrary'\nimport type {\n AppSegmentConfig,\n EnsureStatic,\n} from '../../../build/segment-config/app/app-segment-config'\n\nconst API_DOCS: Record<\n string,\n {\n description: string\n options?: Record\n link?: string\n type?: string\n isValid?: (value: string) => boolean\n getHint?: (value: any) => string | undefined\n insertText?: string\n }\n> = {\n dynamic: {\n description:\n 'The `dynamic` option provides a few ways to opt in or out of dynamic behavior.',\n options: {\n '\"auto\"':\n \"Heuristic to cache as much as possible but doesn't prevent any component to opt-in to dynamic behavior.\",\n '\"force-dynamic\"':\n 'This disables all caching of fetches and always revalidates. (This is equivalent to `getServerSideProps`.)',\n '\"error\"':\n 'This errors if any dynamic Hooks or fetches are used. (This is equivalent to `getStaticProps`.)',\n '\"force-static\"':\n 'This forces caching of all fetches and returns empty values from `cookies`, `headers` and `useSearchParams`.',\n } satisfies DocsOptionsObject,\n link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamic',\n },\n fetchCache: {\n description:\n \"The `fetchCache` option controls how Next.js statically caches fetches. By default it statically caches fetches reachable before any dynamic Hooks are used, and it doesn't cache fetches that are discovered after that.\",\n options: {\n '\"force-no-store\"':\n \"This lets you intentionally opt-out of all caching of data. This option forces all fetches to be refetched every request even if the `cache: 'force-cache'` option is passed to `fetch()`.\",\n '\"only-no-store\"':\n \"This lets you enforce that all data opts out of caching. This option makes `fetch()` reject with an error if `cache: 'force-cache'` is provided. It also changes the default to `no-store`.\",\n '\"default-no-store\"':\n \"Allows any explicit `cache` option to be passed to `fetch()` but if `'default'`, or no option, is provided then it defaults to `'no-store'`. This means that even fetches before a dynamic Hook are considered dynamic.\",\n '\"auto\"':\n \"This is the default option. It caches any fetches with the default `cache` option provided, that happened before a dynamic Hook is used and don't cache any such fetches if they're issued after a dynamic Hook.\",\n '\"default-cache\"':\n \"Allows any explicit `cache` option to be passed to `fetch()` but if `'default'`, or no option, is provided then it defaults to `'force-cache'`. This means that even fetches before a dynamic Hook are considered dynamic.\",\n '\"only-cache\"':\n \"This lets you enforce that all data opts into caching. This option makes `fetch()` reject with an error if `cache: 'force-cache'` is provided. It also changes the default to `force-cache`. This error can be discovered early during static builds - or dynamically during Edge rendering.\",\n '\"force-cache\"':\n \"This lets you intentionally opt-in to all caching of data. This option forces all fetches to be cache even if the `cache: 'no-store'` option is passed to `fetch()`.\",\n } satisfies DocsOptionsObject,\n link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#fetchcache',\n },\n preferredRegion: {\n description:\n '@deprecated\\\\n\\\\nThe `preferredRegion` route segment config is deprecated. Remove this export.',\n options: {\n '\"auto\"':\n '@deprecated\\\\n\\\\nNext.js will first deploy to the `\"home\"` region. Then if it doesn\\'t detect any waterfall requests after a few requests, it can upgrade that route, to be deployed globally. If it detects any waterfall requests after that, it can eventually downgrade back to `\"home`\".',\n '\"global\"': '@deprecated\\\\n\\\\nPrefer deploying globally.',\n '\"home\"': '@deprecated\\\\n\\\\nPrefer deploying to the Home region.',\n },\n link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#preferredregion',\n isValid: (value: string) => {\n try {\n const parsed = JSON.parse(value)\n return (\n typeof parsed === 'string' ||\n (Array.isArray(parsed) && !parsed.some((v) => typeof v !== 'string'))\n )\n } catch (err) {\n return false\n }\n },\n getHint: (value: any) => {\n if (value === 'auto') return `Automatically chosen by Next.js.`\n if (value === 'global') return `Prefer deploying globally.`\n if (value === 'home') return `Prefer deploying to the Home region.`\n if (Array.isArray(value)) return `Deploy to regions: ${value.join(', ')}.`\n if (typeof value === 'string') return `Deploy to region: ${value}.`\n },\n },\n revalidate: {\n description:\n \"The `revalidate` option sets the default revalidation time for that layout or page. Note that it doesn't override the value specify by each `fetch()`.\",\n type: 'mixed',\n options: {\n false:\n 'This is the default and changes the fetch cache to indefinitely cache anything that uses force-cache or is fetched before a dynamic Hook/fetch.',\n 0: 'Specifying `0` implies that this layout or page should never be static.',\n 30: 'Set the revalidation time to `30` seconds. The value can be `0` or any positive number.',\n },\n link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#revalidate',\n isValid: (value: string) => {\n return value === 'false' || Number(value.replace(/_/g, '')) >= 0\n },\n getHint: (value: any) => {\n return `Set the default revalidation time to \\`${value}\\` seconds.`\n },\n },\n dynamicParams: {\n description:\n '`dynamicParams` replaces the `fallback` option of `getStaticPaths`. It controls whether we allow `dynamicParams` beyond the generated static params from `generateStaticParams`.',\n options: {\n true: 'Allow rendering dynamic params that are not generated by `generateStaticParams`.',\n false:\n 'Disallow rendering dynamic params that are not generated by `generateStaticParams`.',\n } satisfies DocsOptionsObject,\n link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamicparams',\n isValid: (value: string) => {\n return value === 'true' || value === 'false'\n },\n },\n runtime: {\n description:\n 'The `runtime` option controls the preferred runtime to render this route.',\n options: {\n '\"nodejs\"': 'Prefer the Node.js runtime.',\n '\"edge\"': `@deprecated\\n\\nThe Edge Runtime is deprecated. Use \\`\"nodejs\"\\` instead.`,\n '\"experimental-edge\"': `@deprecated\\n\\nThis option is no longer experimental. Use \\`edge\\` instead.`,\n } satisfies DocsOptionsObject<\n FullAppSegmentConfig['runtime'] | 'experimental-edge'\n >,\n link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#runtime',\n },\n metadata: {\n description: 'Next.js Metadata configurations',\n link: 'https://nextjs.org/docs/app/building-your-application/optimizing/metadata',\n insertText: 'metadata: Metadata = {};',\n },\n generateMetadata: {\n description: 'Next.js generateMetadata configurations',\n link: 'https://nextjs.org/docs/app/api-reference/functions/generate-metadata',\n insertText: 'generateMetadata = (): Metadata => { return {} };',\n },\n maxDuration: {\n description:\n '`maxDuration` allows you to set max default execution time for your function. If it is not specified, the default value is dependent on your deployment platform and plan.',\n link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#maxduration',\n },\n instant: {\n description: `Enables instant navigation validation for this segment.`,\n link: 'https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant',\n type: 'true | object | false',\n // TODO: ideally, we'd validate the config object somehow, but this is difficult to do\n // with the way this plugin is currently structured.\n // For now, since we don't provide an `options` here, we won't do any validation in\n // `getSemanticDiagnosticsForExportVariableStatement` below, and only provide hover a tooltip + autocomplete.\n insertText: 'instant = true;',\n },\n prefetch: {\n description: `Controls prefetching behavior for this segment. Some options are experimental and may change.`,\n link: '(docs coming soon)',\n type: `\"auto\" | \"partial\" | \"force-disabled\"`,\n options: {\n auto: 'Default. Framework decides based on instant validation and segment configuration. You do not need to set this explicitly.',\n partial:\n 'Enables Partial Prefetching for this segment. When a static prefetch is insufficient, Next.js may prefetch the segment with a runtime server request so it can access session data, such as cookies.',\n 'force-disabled': 'Never prefetch this segment.',\n },\n insertText: `prefetch = 'partial';`,\n },\n ensureStatic: {\n description: `Controls which rendering phases require static output for this segment. This option is experimental and may change.`,\n link: '(docs coming soon)',\n type: `\"auto\" | \"shell\" | \"prefetch\" | \"navigation\" | false`,\n options: {\n '\"auto\"':\n 'Default. The shell, prefetch, or entire page will automatically be prerendered statically if possible.',\n '\"shell\"': 'Force the shell for the route to be prerendered statically.',\n '\"prefetch\"':\n 'Force both the shell and the prefetch (``) for the route to be prerendered statically.',\n '\"navigation\"': 'Require the route to be fully static.',\n false:\n 'Indicate that this segment must use the default behavior and should not have `ensureStatic = \"shell\" | \"prefetch\" | \"navigation\"` applied to it by another segment. Errors if another segment on the route uses `ensureStatic` with those values.',\n } satisfies DocsOptionsObject,\n insertText: `ensureStatic = 'shell';`,\n isValid: (value) => {\n try {\n const parsed: unknown = JSON.parse(value)\n return (VALID_ENSURE_STATIC_VALUES as unknown[]).includes(parsed)\n } catch {\n return false\n }\n },\n },\n unstable_dynamicStaleTime: {\n description: `Controls how long the client-side router cache retains dynamic page data (in seconds). Pages only — not allowed in layouts. Cannot be combined with \\`instant\\`.`,\n link: '(docs coming soon)',\n type: 'number',\n isValid: (value: string) => {\n return Number(value.replace(/_/g, '')) >= 0\n },\n getHint: (value: any) => {\n return `Set the dynamic stale time to \\`${value}\\` seconds.`\n },\n },\n}\n\nconst VALID_ENSURE_STATIC_VALUES: EnsureStatic[] = [\n 'auto',\n 'shell',\n 'prefetch',\n 'navigation',\n false,\n]\n\ntype FullAppSegmentConfig = Required\n\n/**\n * Maps a type for a config value to a docs object that lists all its values.\n * This ensures that all the valid options are listed.\n * Note that values that aren't primitives are skipped.\n *\n * ```\n * DocsOptionsObject<0 | false | \"yes\"> = { 0: string, false: string, '\"yes\"': string }\n * ```\n */\ntype DocsOptionsObject = {\n [Value in T as AsObjectKey]: string\n}\n\ntype AsObjectKey = Value extends string\n ? `\"${Value}\"`\n : Value extends number | boolean | null | undefined\n ? `${Value}`\n : never\n\nfunction visitEntryConfig(\n fileName: string,\n position: number,\n callback: (entryEonfig: string, value: tsModule.VariableDeclaration) => void\n) {\n const source = getSource(fileName)\n if (source) {\n const ts = getTs()\n ts.forEachChild(source, function visit(node) {\n // Covered by this node\n if (isPositionInsideNode(position, node)) {\n // Export variable\n if (\n ts.isVariableStatement(node) &&\n node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)\n ) {\n if (ts.isVariableDeclarationList(node.declarationList)) {\n for (const declaration of node.declarationList.declarations) {\n if (isPositionInsideNode(position, declaration)) {\n // `export const ... = ...`\n const text = declaration.name.getText()\n callback(text, declaration)\n }\n }\n }\n }\n }\n })\n }\n}\n\nfunction createAutoCompletionOptionName(sort: number, name: string) {\n const ts = getTs()\n\n return {\n name,\n insertText: API_DOCS[name].insertText,\n sortText: '!' + sort,\n kind: ts.ScriptElementKind.constElement,\n kindModifiers: ts.ScriptElementKindModifier.exportedModifier,\n labelDetails: {\n description: `Next.js ${name} option`,\n },\n data: {\n exportName: name,\n moduleSpecifier: 'next/typescript/entry_option_name',\n },\n } as tsModule.CompletionEntry\n}\n\nfunction createAutoCompletionOptionValue(\n sort: number,\n name: string,\n apiName: string\n) {\n const ts = getTs()\n const isString = name.startsWith('\"')\n return {\n name,\n insertText: removeStringQuotes(name),\n sortText: '' + sort,\n kind: isString ? ts.ScriptElementKind.string : ts.ScriptElementKind.unknown,\n kindModifiers: ts.ScriptElementKindModifier.none,\n labelDetails: {\n description: `Next.js ${apiName} option`,\n },\n data: {\n exportName: apiName,\n moduleSpecifier: 'next/typescript/entry_option_value',\n },\n } as tsModule.CompletionEntry\n}\n\nfunction getAPIDescription(api: string): string {\n return (\n API_DOCS[api].description +\n '\\n\\n' +\n Object.entries(API_DOCS[api].options || {})\n .map(([key, value]) => `- \\`${key}\\`: ${value}`)\n .join('\\n')\n )\n}\n\nconst config = {\n // Auto completion for entry exported configs.\n addCompletionsAtPosition(\n fileName: string,\n position: number,\n prior: tsModule.WithMetadata\n ) {\n visitEntryConfig(fileName, position, (entryConfig, declaration) => {\n if (!API_DOCS[entryConfig]) {\n if (isPositionInsideNode(position, declaration.name)) {\n prior.entries.push(\n ...Object.keys(API_DOCS).map((name, index) => {\n return createAutoCompletionOptionName(index, name)\n })\n )\n }\n return\n }\n\n prior.entries.push(\n ...Object.keys(API_DOCS[entryConfig].options || {}).map(\n (name, index) => {\n return createAutoCompletionOptionValue(index, name, entryConfig)\n }\n )\n )\n })\n },\n\n // Show docs when hovering on the exported configs.\n getQuickInfoAtPosition(\n fileName: string,\n position: number,\n prior?: tsModule.QuickInfo\n ) {\n const ts = getTs()\n\n let overridden: tsModule.QuickInfo | undefined\n visitEntryConfig(fileName, position, (entryConfig, declaration) => {\n if (!API_DOCS[entryConfig]) return\n\n const name = declaration.name\n const value = declaration.initializer\n\n const docsLink = {\n kind: 'text',\n text:\n `\\n\\nRead more about the \"${entryConfig}\" option: ` +\n API_DOCS[entryConfig].link,\n }\n\n // When the value is a flexible type (like a function), also compute its\n // inferred type so we can surface it alongside the docs. This is useful\n // even when the value is considered invalid by the config validation,\n // as long as it's not a direct literal export.\n let displayParts: tsModule.SymbolDisplayPart[] = []\n const typeChecker = getTypeChecker()\n const isString = !!value && ts.isStringLiteral(value)\n const isFunctionValue =\n !!value &&\n !isString &&\n (ts.isArrowFunction(value) ||\n ts.isFunctionExpression(value) ||\n ts.isFunctionDeclaration(value))\n\n if (typeChecker && value && isFunctionValue) {\n try {\n // If we're hovering the config identifier, ask for the type at the\n // identifier; otherwise, ask at the value node. This makes sure\n // highlighting `generateMetadata` itself also shows the inferred type.\n const typeTarget = isPositionInsideNode(position, name) ? name : value\n const type = typeChecker.getTypeAtLocation(typeTarget)\n if (type) {\n const typeString = typeChecker.typeToString(type, typeTarget)\n if (typeString) {\n displayParts = [\n {\n text: typeString,\n kind: 'typeName',\n },\n ]\n }\n }\n } catch {\n // If type checking fails, continue without type info.\n }\n }\n\n // For non-function values (like literals), hovering the value should show\n // option-specific docs. For function-valued configs (e.g. `generateMetadata`),\n // we let TypeScript handle hover anywhere in the initializer except for the\n // export identifier itself.\n if (value && !isFunctionValue && isPositionInsideNode(position, value)) {\n // Hovering the value of the config\n const text = removeStringQuotes(value.getText())\n const key = isString ? `\"${text}\"` : text\n\n const isValid = API_DOCS[entryConfig].isValid\n ? API_DOCS[entryConfig].isValid?.(key)\n : !!API_DOCS[entryConfig].options?.[key]\n\n if (isValid) {\n const documentation: tsModule.SymbolDisplayPart[] = [\n ...(prior?.documentation || []),\n {\n kind: 'text',\n text:\n API_DOCS[entryConfig].options?.[key] ||\n API_DOCS[entryConfig].getHint?.(key) ||\n '',\n },\n docsLink,\n ]\n\n overridden = prior\n ? { ...prior, documentation }\n : {\n kind: ts.ScriptElementKind.enumElement,\n kindModifiers: ts.ScriptElementKindModifier.none,\n textSpan: {\n start: value.getStart(),\n length: value.getWidth(),\n },\n displayParts: [],\n documentation,\n }\n } else {\n // Wrong value: still show the docs link, and when available, the\n // inferred type for non-literal (i.e. non-direct) exports.\n overridden = {\n kind: ts.ScriptElementKind.enumElement,\n kindModifiers: ts.ScriptElementKindModifier.none,\n textSpan: {\n start: value.getStart(),\n length: value.getWidth(),\n },\n displayParts,\n documentation: [docsLink],\n }\n }\n } else {\n // For function-valued configs, if we're hovering anywhere within the\n // initializer (including `async`, parameters, or the body) but not on\n // the export identifier itself, don't override TypeScript's default\n // hover. We only want to override when hovering the config identifier\n // (e.g. `generateMetadata`), not arbitrary tokens within the function.\n if (\n isFunctionValue &&\n isPositionInsideNode(position, value) && // hover is somewhere within the function initializer\n !isPositionInsideNode(position, name) // ...but not on the export identifier itself\n ) {\n return\n }\n // Hovers the name of the config\n const documentation: tsModule.SymbolDisplayPart[] = [\n ...(prior?.documentation || []),\n {\n kind: 'text',\n text: getAPIDescription(entryConfig),\n },\n docsLink,\n ]\n\n overridden = prior\n ? { ...prior, documentation }\n : {\n kind: ts.ScriptElementKind.enumElement,\n kindModifiers: ts.ScriptElementKindModifier.none,\n textSpan: {\n start: name.getStart(),\n length: name.getWidth(),\n },\n displayParts,\n documentation,\n }\n }\n })\n return overridden\n },\n\n // Show details on the side when auto completing.\n getCompletionEntryDetails(\n entryName: string,\n data: tsModule.CompletionEntryData,\n fileName: string\n ): tsModule.CompletionEntryDetails | undefined {\n const ts = getTs()\n if (\n data &&\n data.moduleSpecifier &&\n data.moduleSpecifier.startsWith('next/typescript')\n ) {\n let content = ''\n if (data.moduleSpecifier === 'next/typescript/entry_option_name') {\n content = getAPIDescription(entryName)\n } else {\n const options = API_DOCS[data.exportName].options\n if (!options) return\n content = options[entryName]\n }\n\n if (entryName === 'metadata' || entryName === 'generateMetadata') {\n const sourceFile = getSource(fileName)\n let start = 0\n let foundMetadataImport = false\n\n if (sourceFile) {\n const visitor: tsModule.Visitor = (node) => {\n // Check for top directive\n if (\n ts.isExpressionStatement(node) &&\n ts.isStringLiteral(node.expression) &&\n node.expression.getStart() === 0\n ) {\n const text = node.expression.text\n if (text.startsWith('use ')) {\n start = node.end + 1\n return node // Continue traversal\n }\n }\n\n // Check for Metadata import\n if (\n ts.isImportDeclaration(node) &&\n (node.moduleSpecifier.getText() === '\"next\"' ||\n node.moduleSpecifier.getText() === \"'next'\")\n ) {\n const namedImports = node.importClause?.namedBindings\n if (namedImports && ts.isNamedImports(namedImports)) {\n foundMetadataImport = namedImports.elements.some((element) => {\n const name = element.name.getText()\n const propertyName = element.propertyName?.getText()\n return name === 'Metadata' || propertyName === 'Metadata'\n })\n if (foundMetadataImport) {\n return // Stop traversal\n }\n }\n }\n\n return node\n }\n\n for (const statement of sourceFile.statements) {\n if (foundMetadataImport) break\n ts.visitNode(statement, visitor)\n }\n }\n\n return {\n name: entryName,\n kind: ts.ScriptElementKind.enumElement,\n kindModifiers: ts.ScriptElementKindModifier.none,\n displayParts: [],\n codeActions: foundMetadataImport\n ? undefined\n : [\n {\n description: `Import type 'Metadata' from module 'next'`,\n changes: [\n {\n fileName,\n textChanges: [\n {\n span: { start, length: 0 },\n newText: `import type { Metadata } from 'next';\\n`,\n },\n ],\n },\n ],\n },\n ],\n documentation: [\n {\n kind: 'text',\n text: content,\n },\n ],\n }\n }\n\n return {\n name: entryName,\n kind: ts.ScriptElementKind.enumElement,\n kindModifiers: ts.ScriptElementKindModifier.none,\n displayParts: [],\n documentation: [\n {\n kind: 'text',\n text: content,\n },\n ],\n }\n }\n },\n\n // Show errors for invalid export fields.\n getSemanticDiagnosticsForExportVariableStatement(\n source: tsModule.SourceFile,\n node: tsModule.VariableStatement\n ) {\n const ts = getTs()\n\n const diagnostics: tsModule.Diagnostic[] = []\n\n // Check if it has correct option exports\n if (ts.isVariableDeclarationList(node.declarationList)) {\n for (const declaration of node.declarationList.declarations) {\n const name = declaration.name\n if (ts.isIdentifier(name)) {\n if (!ALLOWED_EXPORTS.includes(name.text) && !API_DOCS[name.text]) {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_ENTRY_EXPORT,\n messageText: `\"${name.text}\" is not a valid Next.js entry export value.`,\n start: name.getStart(),\n length: name.getWidth(),\n })\n } else if (API_DOCS[name.text]) {\n // Check if the value is valid\n const value = declaration.initializer\n const options = API_DOCS[name.text].options\n\n if (value && options) {\n let displayedValue = ''\n let errorMessage = ''\n let isInvalid = false\n\n if (\n ts.isStringLiteral(value) ||\n ts.isNoSubstitutionTemplateLiteral(value)\n ) {\n const val = '\"' + removeStringQuotes(value.getText()) + '\"'\n const allowedValues = Object.keys(options).filter((v) =>\n /^['\"]/.test(v)\n )\n\n if (\n !allowedValues.includes(val) &&\n !API_DOCS[name.text].isValid?.(val)\n ) {\n isInvalid = true\n displayedValue = val\n }\n } else if (\n ts.isNumericLiteral(value) ||\n (ts.isPrefixUnaryExpression(value) &&\n ts.isMinusToken((value as any).operator) &&\n (ts.isNumericLiteral((value as any).operand.kind) ||\n (ts.isIdentifier((value as any).operand.kind) &&\n (value as any).operand.kind.getText() === 'Infinity'))) ||\n (ts.isIdentifier(value) && value.getText() === 'Infinity')\n ) {\n const v = value.getText()\n if (!API_DOCS[name.text].isValid?.(v)) {\n isInvalid = true\n displayedValue = v\n }\n } else if (\n value.kind === ts.SyntaxKind.TrueKeyword ||\n value.kind === ts.SyntaxKind.FalseKeyword\n ) {\n const v = value.getText()\n if (!API_DOCS[name.text].isValid?.(v)) {\n isInvalid = true\n displayedValue = v\n }\n } else if (ts.isArrayLiteralExpression(value)) {\n const v = value.getText()\n if (\n !API_DOCS[name.text].isValid?.(\n JSON.stringify(value.elements.map((e) => e.getText()))\n )\n ) {\n isInvalid = true\n displayedValue = v\n }\n } else if (\n // Other literals\n ts.isBigIntLiteral(value) ||\n ts.isObjectLiteralExpression(value) ||\n ts.isRegularExpressionLiteral(value) ||\n ts.isPrefixUnaryExpression(value)\n ) {\n isInvalid = true\n displayedValue = value.getText()\n } else {\n // Not a literal, error because it's not statically analyzable\n isInvalid = true\n displayedValue = value.getText()\n errorMessage = `\"${displayedValue}\" is not a valid value for the \"${name.text}\" option. The configuration must be statically analyzable.`\n }\n\n if (isInvalid) {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_OPTION_VALUE,\n messageText:\n errorMessage ||\n `\"${displayedValue}\" is not a valid value for the \"${name.text}\" option.`,\n start: value.getStart(),\n length: value.getWidth(),\n })\n }\n }\n }\n }\n }\n }\n\n return diagnostics\n },\n}\n\nexport default config\n"],"names":["API_DOCS","dynamic","description","options","link","fetchCache","preferredRegion","isValid","value","parsed","JSON","parse","Array","isArray","some","v","err","getHint","join","revalidate","type","false","Number","replace","dynamicParams","true","runtime","metadata","insertText","generateMetadata","maxDuration","instant","prefetch","auto","partial","ensureStatic","VALID_ENSURE_STATIC_VALUES","includes","unstable_dynamicStaleTime","visitEntryConfig","fileName","position","callback","source","getSource","ts","getTs","forEachChild","visit","node","isPositionInsideNode","isVariableStatement","modifiers","m","kind","SyntaxKind","ExportKeyword","isVariableDeclarationList","declarationList","declaration","declarations","text","name","getText","createAutoCompletionOptionName","sort","sortText","ScriptElementKind","constElement","kindModifiers","ScriptElementKindModifier","exportedModifier","labelDetails","data","exportName","moduleSpecifier","createAutoCompletionOptionValue","apiName","isString","startsWith","removeStringQuotes","string","unknown","none","getAPIDescription","api","Object","entries","map","key","config","addCompletionsAtPosition","prior","entryConfig","push","keys","index","getQuickInfoAtPosition","overridden","initializer","docsLink","displayParts","typeChecker","getTypeChecker","isStringLiteral","isFunctionValue","isArrowFunction","isFunctionExpression","isFunctionDeclaration","typeTarget","getTypeAtLocation","typeString","typeToString","documentation","enumElement","textSpan","start","getStart","length","getWidth","getCompletionEntryDetails","entryName","content","sourceFile","foundMetadataImport","visitor","isExpressionStatement","expression","end","isImportDeclaration","namedImports","importClause","namedBindings","isNamedImports","elements","element","propertyName","statement","statements","visitNode","codeActions","undefined","changes","textChanges","span","newText","getSemanticDiagnosticsForExportVariableStatement","diagnostics","isIdentifier","ALLOWED_EXPORTS","file","category","DiagnosticCategory","Error","code","NEXT_TS_ERRORS","INVALID_ENTRY_EXPORT","messageText","displayedValue","errorMessage","isInvalid","isNoSubstitutionTemplateLiteral","val","allowedValues","filter","test","isNumericLiteral","isPrefixUnaryExpression","isMinusToken","operator","operand","TrueKeyword","FalseKeyword","isArrayLiteralExpression","stringify","e","isBigIntLiteral","isObjectLiteralExpression","isRegularExpressionLiteral","INVALID_OPTION_VALUE"],"mappings":"AAAA,4EAA4E;;;;;+BAkuB5E;;;eAAA;;;uBA1tBO;0BACyC;AAOhD,MAAMA,WAWF;IACFC,SAAS;QACPC,aACE;QACFC,SAAS;YACP,UACE;YACF,mBACE;YACF,WACE;YACF,kBACE;QACJ;QACAC,MAAM;IACR;IACAC,YAAY;QACVH,aACE;QACFC,SAAS;YACP,oBACE;YACF,mBACE;YACF,sBACE;YACF,UACE;YACF,mBACE;YACF,gBACE;YACF,iBACE;QACJ;QACAC,MAAM;IACR;IACAE,iBAAiB;QACfJ,aACE;QACFC,SAAS;YACP,UACE;YACF,YAAY;YACZ,UAAU;QACZ;QACAC,MAAM;QACNG,SAAS,CAACC;YACR,IAAI;gBACF,MAAMC,SAASC,KAAKC,KAAK,CAACH;gBAC1B,OACE,OAAOC,WAAW,YACjBG,MAAMC,OAAO,CAACJ,WAAW,CAACA,OAAOK,IAAI,CAAC,CAACC,IAAM,OAAOA,MAAM;YAE/D,EAAE,OAAOC,KAAK;gBACZ,OAAO;YACT;QACF;QACAC,SAAS,CAACT;YACR,IAAIA,UAAU,QAAQ,OAAO,CAAC,gCAAgC,CAAC;YAC/D,IAAIA,UAAU,UAAU,OAAO,CAAC,0BAA0B,CAAC;YAC3D,IAAIA,UAAU,QAAQ,OAAO,CAAC,oCAAoC,CAAC;YACnE,IAAII,MAAMC,OAAO,CAACL,QAAQ,OAAO,CAAC,mBAAmB,EAAEA,MAAMU,IAAI,CAAC,MAAM,CAAC,C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F;wBACF;oBACF;gBACF;YACF;QACF;QAEA,OAAO4B;IACT;AACF;MAEA,WAAezD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/entry.d.ts b/e-commerce/node_modules/next/dist/server/typescript/rules/entry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..837ca2fb275968a04f89e5d5302d824cefe0237c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/entry.d.ts @@ -0,0 +1,6 @@ +import type tsModule from 'typescript/lib/tsserverlibrary'; +declare const entry: { + getCompletionsAtPosition(fileName: string, node: tsModule.FunctionDeclaration, position: number): tsModule.CompletionEntry[]; + getSemanticDiagnostics(fileName: string, source: tsModule.SourceFile, node: tsModule.FunctionDeclaration): tsModule.Diagnostic[]; +}; +export default entry; diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/entry.js b/e-commerce/node_modules/next/dist/server/typescript/rules/entry.js new file mode 100644 index 0000000000000000000000000000000000000000..ad74944ef178c42d06d95f05858285952debb2a1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/entry.js @@ -0,0 +1,149 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _constant = require("../constant"); +const _utils = require("../utils"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +const entry = { + // Give auto completion for the component's props + getCompletionsAtPosition (fileName, node, position) { + var _node_parameters; + const ts = (0, _utils.getTs)(); + const entries = []; + // Default export function might not accept parameters + const paramNode = (_node_parameters = node.parameters) == null ? void 0 : _node_parameters[0]; + if (paramNode && (0, _utils.isPositionInsideNode)(position, paramNode)) { + const props = paramNode == null ? void 0 : paramNode.name; + if (props && ts.isObjectBindingPattern(props)) { + let validProps = []; + let validPropsWithType = []; + let type; + if ((0, _utils.isPageFile)(fileName)) { + // For page entries (page.js), it can only have `params` and `searchParams` + // as the prop names. + validProps = _constant.ALLOWED_PAGE_PROPS; + validPropsWithType = _constant.ALLOWED_PAGE_PROPS; + type = 'page'; + } else { + // For layout entires, check if it has any named slots. + const currentDir = _path.default.dirname(fileName); + const items = _fs.default.readdirSync(currentDir, { + withFileTypes: true + }); + const slots = []; + for (const item of items){ + if (item.isDirectory() && item.name.startsWith('@')) { + slots.push(item.name.slice(1)); + } + } + validProps = _constant.ALLOWED_LAYOUT_PROPS.concat(slots); + validPropsWithType = _constant.ALLOWED_LAYOUT_PROPS.concat(slots.map((s)=>`${s}: React.ReactNode`)); + type = 'layout'; + } + // Auto completion for props + for (const element of props.elements){ + if ((0, _utils.isPositionInsideNode)(position, element)) { + const nameNode = element.propertyName || element.name; + if ((0, _utils.isPositionInsideNode)(position, nameNode)) { + for (const name of validProps){ + entries.push({ + name, + insertText: name, + sortText: '_' + name, + kind: ts.ScriptElementKind.memberVariableElement, + kindModifiers: ts.ScriptElementKindModifier.none, + labelDetails: { + description: `Next.js ${type} prop` + } + }); + } + } + break; + } + } + // Auto completion for types + if (paramNode.type && ts.isTypeLiteralNode(paramNode.type)) { + for (const member of paramNode.type.members){ + if ((0, _utils.isPositionInsideNode)(position, member)) { + for (const name of validPropsWithType){ + entries.push({ + name, + insertText: name, + sortText: '_' + name, + kind: ts.ScriptElementKind.memberVariableElement, + kindModifiers: ts.ScriptElementKindModifier.none, + labelDetails: { + description: `Next.js ${type} prop type` + } + }); + } + break; + } + } + } + } + } + return entries; + }, + // Give error diagnostics for the component + getSemanticDiagnostics (fileName, source, node) { + var _node_parameters_, _node_parameters; + const ts = (0, _utils.getTs)(); + let validProps = []; + let type; + if ((0, _utils.isPageFile)(fileName)) { + // For page entries (page.js), it can only have `params` and `searchParams` + // as the prop names. + validProps = _constant.ALLOWED_PAGE_PROPS; + type = 'page'; + } else { + // For layout entires, check if it has any named slots. + const currentDir = _path.default.dirname(fileName); + const items = _fs.default.readdirSync(currentDir, { + withFileTypes: true + }); + const slots = []; + for (const item of items){ + if (item.isDirectory() && item.name.startsWith('@')) { + slots.push(item.name.slice(1)); + } + } + validProps = _constant.ALLOWED_LAYOUT_PROPS.concat(slots); + type = 'layout'; + } + const diagnostics = []; + const props = (_node_parameters = node.parameters) == null ? void 0 : (_node_parameters_ = _node_parameters[0]) == null ? void 0 : _node_parameters_.name; + if (props && ts.isObjectBindingPattern(props)) { + for (const prop of props.elements){ + const propName = (prop.propertyName || prop.name).getText(); + if (!validProps.includes(propName)) { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_PAGE_PROP, + messageText: `"${propName}" is not a valid ${type} prop.`, + start: prop.getStart(), + length: prop.getWidth() + }); + } + } + } + return diagnostics; + } +}; +const _default = entry; + +//# sourceMappingURL=entry.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/entry.js.map b/e-commerce/node_modules/next/dist/server/typescript/rules/entry.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6bf5f39eb05451a43cc66b8b22ac84cd7668162b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/entry.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/typescript/rules/entry.ts"],"sourcesContent":["import path from 'path'\nimport fs from 'fs'\n\nimport {\n ALLOWED_LAYOUT_PROPS,\n ALLOWED_PAGE_PROPS,\n NEXT_TS_ERRORS,\n} from '../constant'\nimport { getTs, isPageFile, isPositionInsideNode } from '../utils'\n\nimport type tsModule from 'typescript/lib/tsserverlibrary'\n\nconst entry = {\n // Give auto completion for the component's props\n getCompletionsAtPosition(\n fileName: string,\n node: tsModule.FunctionDeclaration,\n position: number\n ) {\n const ts = getTs()\n const entries: tsModule.CompletionEntry[] = []\n\n // Default export function might not accept parameters\n const paramNode = node.parameters?.[0] as\n | tsModule.ParameterDeclaration\n | undefined\n\n if (paramNode && isPositionInsideNode(position, paramNode)) {\n const props = paramNode?.name\n if (props && ts.isObjectBindingPattern(props)) {\n let validProps = []\n let validPropsWithType = []\n let type: string\n\n if (isPageFile(fileName)) {\n // For page entries (page.js), it can only have `params` and `searchParams`\n // as the prop names.\n validProps = ALLOWED_PAGE_PROPS\n validPropsWithType = ALLOWED_PAGE_PROPS\n type = 'page'\n } else {\n // For layout entires, check if it has any named slots.\n const currentDir = path.dirname(fileName)\n const items = fs.readdirSync(currentDir, {\n withFileTypes: true,\n })\n const slots = []\n for (const item of items) {\n if (item.isDirectory() && item.name.startsWith('@')) {\n slots.push(item.name.slice(1))\n }\n }\n validProps = ALLOWED_LAYOUT_PROPS.concat(slots)\n validPropsWithType = ALLOWED_LAYOUT_PROPS.concat(\n slots.map((s) => `${s}: React.ReactNode`)\n )\n type = 'layout'\n }\n\n // Auto completion for props\n for (const element of props.elements) {\n if (isPositionInsideNode(position, element)) {\n const nameNode = element.propertyName || element.name\n\n if (isPositionInsideNode(position, nameNode)) {\n for (const name of validProps) {\n entries.push({\n name,\n insertText: name,\n sortText: '_' + name,\n kind: ts.ScriptElementKind.memberVariableElement,\n kindModifiers: ts.ScriptElementKindModifier.none,\n labelDetails: {\n description: `Next.js ${type} prop`,\n },\n } as tsModule.CompletionEntry)\n }\n }\n\n break\n }\n }\n\n // Auto completion for types\n if (paramNode.type && ts.isTypeLiteralNode(paramNode.type)) {\n for (const member of paramNode.type.members) {\n if (isPositionInsideNode(position, member)) {\n for (const name of validPropsWithType) {\n entries.push({\n name,\n insertText: name,\n sortText: '_' + name,\n kind: ts.ScriptElementKind.memberVariableElement,\n kindModifiers: ts.ScriptElementKindModifier.none,\n labelDetails: {\n description: `Next.js ${type} prop type`,\n },\n } as tsModule.CompletionEntry)\n }\n\n break\n }\n }\n }\n }\n }\n\n return entries\n },\n\n // Give error diagnostics for the component\n getSemanticDiagnostics(\n fileName: string,\n source: tsModule.SourceFile,\n node: tsModule.FunctionDeclaration\n ) {\n const ts = getTs()\n\n let validProps = []\n let type: string\n\n if (isPageFile(fileName)) {\n // For page entries (page.js), it can only have `params` and `searchParams`\n // as the prop names.\n validProps = ALLOWED_PAGE_PROPS\n type = 'page'\n } else {\n // For layout entires, check if it has any named slots.\n const currentDir = path.dirname(fileName)\n const items = fs.readdirSync(currentDir, { withFileTypes: true })\n const slots = []\n for (const item of items) {\n if (item.isDirectory() && item.name.startsWith('@')) {\n slots.push(item.name.slice(1))\n }\n }\n validProps = ALLOWED_LAYOUT_PROPS.concat(slots)\n type = 'layout'\n }\n\n const diagnostics: tsModule.Diagnostic[] = []\n\n const props = node.parameters?.[0]?.name\n if (props && ts.isObjectBindingPattern(props)) {\n for (const prop of props.elements) {\n const propName = (prop.propertyName || prop.name).getText()\n if (!validProps.includes(propName)) {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_PAGE_PROP,\n messageText: `\"${propName}\" is not a valid ${type} prop.`,\n start: prop.getStart(),\n length: prop.getWidth(),\n })\n }\n }\n }\n\n return diagnostics\n },\n}\n\nexport default entry\n"],"names":["entry","getCompletionsAtPosition","fileName","node","position","ts","getTs","entries","paramNode","parameters","isPositionInsideNode","props","name","isObjectBindingPattern","validProps","validPropsWithType","type","isPageFile","ALLOWED_PAGE_PROPS","currentDir","path","dirname","items","fs","readdirSync","withFileTypes","slots","item","isDirectory","startsWith","push","slice","ALLOWED_LAYOUT_PROPS","concat","map","s","element","elements","nameNode","propertyName","insertText","sortText","kind","ScriptElementKind","memberVariableElement","kindModifiers","ScriptElementKindModifier","none","labelDetails","description","isTypeLiteralNode","member","members","getSemanticDiagnostics","source","diagnostics","prop","propName","getText","includes","file","category","DiagnosticCategory","Error","code","NEXT_TS_ERRORS","INVALID_PAGE_PROP","messageText","start","getStart","length","getWidth"],"mappings":";;;;+BAmKA;;;eAAA;;;6DAnKiB;2DACF;0BAMR;uBACiD;;;;;;AAIxD,MAAMA,QAAQ;IACZ,iDAAiD;IACjDC,0BAC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BF,OAAO;QACT,OAAO;YACL,uDAAuD;YACvD,MAAMG,aAAaC,aAAI,CAACC,OAAO,CAACnB;YAChC,MAAMoB,QAAQC,WAAE,CAACC,WAAW,CAACL,YAAY;gBAAEM,eAAe;YAAK;YAC/D,MAAMC,QAAQ,EAAE;YAChB,KAAK,MAAMC,QAAQL,MAAO;gBACxB,IAAIK,KAAKC,WAAW,MAAMD,KAAKf,IAAI,CAACiB,UAAU,CAAC,MAAM;oBACnDH,MAAMI,IAAI,CAACH,KAAKf,IAAI,CAACmB,KAAK,CAAC;gBAC7B;YACF;YACAjB,aAAakB,8BAAoB,CAACC,MAAM,CAACP;YACzCV,OAAO;QACT;QAEA,MAAMuC,cAAqC,EAAE;QAE7C,MAAM5C,SAAQR,mBAAAA,KAAKM,UAAU,sBAAfN,oBAAAA,gBAAiB,CAAC,EAAE,qBAApBA,kBAAsBS,IAAI;QACxC,IAAID,SAASN,GAAGQ,sBAAsB,CAACF,QAAQ;YAC7C,KAAK,MAAM6C,QAAQ7C,MAAM0B,QAAQ,CAAE;gBACjC,MAAMoB,WAAW,AAACD,CAAAA,KAAKjB,YAAY,IAAIiB,KAAK5C,IAAI,AAAD,EAAG8C,OAAO;gBACzD,IAAI,CAAC5C,WAAW6C,QAAQ,CAACF,WAAW;oBAClCF,YAAYzB,IAAI,CAAC;wBACf8B,MAAMN;wBACNO,UAAUxD,GAAGyD,kBAAkB,CAACC,KAAK;wBACrCC,MAAMC,wBAAc,CAACC,iBAAiB;wBACtCC,aAAa,CAAC,CAAC,EAAEV,SAAS,iBAAiB,EAAEzC,KAAK,MAAM,CAAC;wBACzDoD,OAAOZ,KAAKa,QAAQ;wBACpBC,QAAQd,KAAKe,QAAQ;oBACvB;gBACF;YACF;QACF;QAEA,OAAOhB;IACT;AACF;MAEA,WAAevD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/error.d.ts b/e-commerce/node_modules/next/dist/server/typescript/rules/error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..416d86ced147de3a9b08fab4e6e7163617767d4c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/error.d.ts @@ -0,0 +1,5 @@ +import type tsModule from 'typescript/lib/tsserverlibrary'; +declare const errorEntry: { + getSemanticDiagnostics(source: tsModule.SourceFile, isClientEntry: boolean): tsModule.Diagnostic[]; +}; +export default errorEntry; diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/error.js b/e-commerce/node_modules/next/dist/server/typescript/rules/error.js new file mode 100644 index 0000000000000000000000000000000000000000..372d6e392e73dc61859a2c891059cd267f49122b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/error.js @@ -0,0 +1,38 @@ +// This module provides intellisense for all components that has the `"use client"` directive. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _constant = require("../constant"); +const _utils = require("../utils"); +const errorEntry = { + getSemanticDiagnostics (source, isClientEntry) { + const isErrorFile = /[\\/]error\.tsx?$/.test(source.fileName); + const isGlobalErrorFile = /[\\/]global-error\.tsx?$/.test(source.fileName); + if (!isErrorFile && !isGlobalErrorFile) return []; + const ts = (0, _utils.getTs)(); + if (!isClientEntry) { + // Error components must be Client Components + return [ + { + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_ERROR_COMPONENT, + messageText: `Error Components must be Client Components, please add the "use client" directive: https://nextjs.org/docs/app/api-reference/file-conventions/error`, + start: 0, + length: source.text.length + } + ]; + } + return []; + } +}; +const _default = errorEntry; + +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/error.js.map b/e-commerce/node_modules/next/dist/server/typescript/rules/error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..52d7035a279ae052b69480f4fd74af97db43bbe7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/typescript/rules/error.ts"],"sourcesContent":["// This module provides intellisense for all components that has the `\"use client\"` directive.\n\nimport { NEXT_TS_ERRORS } from '../constant'\nimport { getTs } from '../utils'\nimport type tsModule from 'typescript/lib/tsserverlibrary'\n\nconst errorEntry = {\n getSemanticDiagnostics(\n source: tsModule.SourceFile,\n isClientEntry: boolean\n ): tsModule.Diagnostic[] {\n const isErrorFile = /[\\\\/]error\\.tsx?$/.test(source.fileName)\n const isGlobalErrorFile = /[\\\\/]global-error\\.tsx?$/.test(source.fileName)\n\n if (!isErrorFile && !isGlobalErrorFile) return []\n\n const ts = getTs()\n\n if (!isClientEntry) {\n // Error components must be Client Components\n return [\n {\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_ERROR_COMPONENT,\n messageText: `Error Components must be Client Components, please add the \"use client\" directive: https://nextjs.org/docs/app/api-reference/file-conventions/error`,\n start: 0,\n length: source.text.length,\n },\n ]\n }\n return []\n },\n}\n\nexport default errorEntry\n"],"names":["errorEntry","getSemanticDiagnostics","source","isClientEntry","isErrorFile","test","fileName","isGlobalErrorFile","ts","getTs","file","category","DiagnosticCategory","Error","code","NEXT_TS_ERRORS","INVALID_ERROR_COMPONENT","messageText","start","length","text"],"mappings":"AAAA,8FAA8F;;;;;+BAmC9F;;;eAAA;;;0BAjC+B;uBACT;AAGtB,MAAMA,aAAa;IACjBC,wBACEC,MAA2B,EAC3BC,aAAsB;QAEtB,MAAMC,cAAc,oBAAoBC,IAAI,CAACH,OAAOI,QAAQ;QAC5D,MAAMC,oBAAoB,2BAA2BF,IAAI,CAACH,OAAOI,QAAQ;QAEzE,IAAI,CAACF,eAAe,CAACG,mBAAmB,OAAO,EAAE;QAEjD,MAAMC,KAAKC,IAAAA,YAAK;QAEhB,IAAI,CAACN,eAAe;YAClB,6CAA6C;YAC7C,OAAO;gBACL;oBACEO,MAAMR;oBACNS,UAAUH,GAAGI,kBAAkB,CAACC,KAAK;oBACrCC,MAAMC,wBAAc,CAACC,uBAAuB;oBAC5CC,aAAa,CAAC,mJAAmJ,CAAC;oBAClKC,OAAO;oBACPC,QAAQjB,OAAOkB,IAAI,CAACD,MAAM;gBAC5B;aACD;QACH;QACA,OAAO,EAAE;IACX;AACF;MAEA,WAAenB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/metadata.d.ts b/e-commerce/node_modules/next/dist/server/typescript/rules/metadata.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d59500567e11f2b4a2cce7e5905bfc7b5508dee --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/metadata.d.ts @@ -0,0 +1,12 @@ +import type tsModule from 'typescript/lib/tsserverlibrary'; +declare const metadata: { + client: { + getSemanticDiagnosticsForExportVariableStatement(fileName: string, node: tsModule.VariableStatement | tsModule.FunctionDeclaration): tsModule.Diagnostic[]; + getSemanticDiagnosticsForExportDeclaration(fileName: string, node: tsModule.ExportDeclaration): tsModule.Diagnostic[]; + }; + server: { + getSemanticDiagnosticsForExportVariableStatement(fileName: string, node: tsModule.VariableStatement | tsModule.FunctionDeclaration): tsModule.Diagnostic[]; + getSemanticDiagnosticsForExportDeclaration(fileName: string, node: tsModule.ExportDeclaration): tsModule.Diagnostic[]; + }; +}; +export default metadata; diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/metadata.js b/e-commerce/node_modules/next/dist/server/typescript/rules/metadata.js new file mode 100644 index 0000000000000000000000000000000000000000..921cf3edae2f5e97788f051f9788f066860c07f2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/metadata.js @@ -0,0 +1,234 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _constant = require("../constant"); +const _utils = require("../utils"); +const metadata = { + client: { + getSemanticDiagnosticsForExportVariableStatement (fileName, node) { + const source = (0, _utils.getSource)(fileName); + const ts = (0, _utils.getTs)(); + // It is not allowed to export `metadata` or `generateMetadata` in client entry + if (ts.isFunctionDeclaration(node)) { + var _node_name; + if (((_node_name = node.name) == null ? void 0 : _node_name.getText()) === 'generateMetadata') { + return [ + { + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_METADATA_EXPORT, + messageText: `The Next.js 'generateMetadata' API is not allowed in a Client Component.`, + start: node.name.getStart(), + length: node.name.getWidth() + } + ]; + } + } else { + for (const declaration of node.declarationList.declarations){ + const name = declaration.name.getText(); + if (name === 'metadata') { + return [ + { + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_METADATA_EXPORT, + messageText: `The Next.js 'metadata' API is not allowed in a Client Component.`, + start: declaration.name.getStart(), + length: declaration.name.getWidth() + } + ]; + } + } + } + return []; + }, + getSemanticDiagnosticsForExportDeclaration (fileName, node) { + const ts = (0, _utils.getTs)(); + const source = (0, _utils.getSource)(fileName); + const diagnostics = []; + const exportClause = node.exportClause; + if (exportClause && ts.isNamedExports(exportClause)) { + for (const e of exportClause.elements){ + if ([ + 'generateMetadata', + 'metadata' + ].includes(e.name.getText())) { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_METADATA_EXPORT, + messageText: `The Next.js '${e.name.getText()}' API is not allowed in a Client Component.`, + start: e.name.getStart(), + length: e.name.getWidth() + }); + } + } + } + return diagnostics; + } + }, + server: { + getSemanticDiagnosticsForExportVariableStatement (fileName, node) { + const source = (0, _utils.getSource)(fileName); + const ts = (0, _utils.getTs)(); + if (ts.isFunctionDeclaration(node)) { + var _node_name; + if (((_node_name = node.name) == null ? void 0 : _node_name.getText()) === 'generateMetadata') { + var _node_modifiers; + if (hasType(node)) { + return []; + } + const isAsync = (_node_modifiers = node.modifiers) == null ? void 0 : _node_modifiers.some((m)=>m.kind === ts.SyntaxKind.AsyncKeyword); + return [ + { + file: source, + category: ts.DiagnosticCategory.Warning, + code: _constant.NEXT_TS_ERRORS.INVALID_METADATA_EXPORT, + messageText: `The Next.js "generateMetadata" export should have a return type of ${isAsync ? '"Promise"' : '"Metadata"'} from "next".`, + start: node.name.getStart(), + length: node.name.getWidth() + } + ]; + } + } else { + for (const declaration of node.declarationList.declarations){ + if (hasType(declaration)) { + return []; + } + const name = declaration.name.getText(); + if (name === 'metadata') { + return [ + { + file: source, + category: ts.DiagnosticCategory.Warning, + code: _constant.NEXT_TS_ERRORS.INVALID_METADATA_EXPORT, + messageText: `The Next.js "metadata" export should be type of "Metadata" from "next".`, + start: declaration.name.getStart(), + length: declaration.name.getWidth() + } + ]; + } + if (name === 'generateMetadata') { + // Check if it's a function expression or arrow function + if (declaration.initializer && (ts.isFunctionExpression(declaration.initializer) || ts.isArrowFunction(declaration.initializer))) { + var _declaration_initializer_modifiers; + const isAsync = (_declaration_initializer_modifiers = declaration.initializer.modifiers) == null ? void 0 : _declaration_initializer_modifiers.some((m)=>m.kind === ts.SyntaxKind.AsyncKeyword); + return [ + { + file: source, + category: ts.DiagnosticCategory.Warning, + code: _constant.NEXT_TS_ERRORS.INVALID_METADATA_EXPORT, + messageText: `The Next.js "generateMetadata" export should have a return type of ${isAsync ? '"Promise"' : '"Metadata"'} from "next".`, + start: declaration.name.getStart(), + length: declaration.name.getWidth() + } + ]; + } + } + } + } + return []; + }, + getSemanticDiagnosticsForExportDeclaration (fileName, node) { + const typeChecker = (0, _utils.getTypeChecker)(); + if (!typeChecker) { + return []; + } + const ts = (0, _utils.getTs)(); + const source = (0, _utils.getSource)(fileName); + const diagnostics = []; + const exportClause = node.exportClause; + if (!node.isTypeOnly && exportClause && ts.isNamedExports(exportClause)) { + for (const e of exportClause.elements){ + if (e.isTypeOnly) { + continue; + } + const exportName = e.name.getText(); + if (exportName !== 'metadata' && exportName !== 'generateMetadata') { + continue; + } + const symbol = typeChecker.getSymbolAtLocation(e.name); + if (!symbol) { + continue; + } + const originalSymbol = typeChecker.getAliasedSymbol(symbol); + const declarations = originalSymbol.getDeclarations(); + if (!declarations) { + continue; + } + const declaration = declarations[0]; + if (hasType(declaration)) { + continue; + } + if (exportName === 'generateMetadata') { + let isAsync = false; + // async function() {} + if (ts.isFunctionDeclaration(declaration)) { + var _declaration_modifiers; + isAsync = ((_declaration_modifiers = declaration.modifiers) == null ? void 0 : _declaration_modifiers.some((m)=>m.kind === ts.SyntaxKind.AsyncKeyword)) ?? false; + } + // foo = async function() {} + // foo = async () => {} + if (ts.isVariableDeclaration(declaration) && declaration.initializer) { + const initializer = declaration.initializer; + const isFunction = ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer); + if (isFunction) { + var _initializer_modifiers; + isAsync = ((_initializer_modifiers = initializer.modifiers) == null ? void 0 : _initializer_modifiers.some((m)=>m.kind === ts.SyntaxKind.AsyncKeyword)) ?? false; + } + } + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Warning, + code: _constant.NEXT_TS_ERRORS.INVALID_METADATA_EXPORT, + messageText: `The Next.js "generateMetadata" export should have a return type of ${isAsync ? '"Promise"' : '"Metadata"'} from "next".`, + start: e.name.getStart(), + length: e.name.getWidth() + }); + } else { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Warning, + code: _constant.NEXT_TS_ERRORS.INVALID_METADATA_EXPORT, + messageText: `The Next.js "metadata" export should be type of "Metadata" from "next".`, + start: e.name.getStart(), + length: e.name.getWidth() + }); + } + } + } + return diagnostics; + } + } +}; +function hasType(node) { + const ts = (0, _utils.getTs)(); + if (!ts.isVariableDeclaration(node) && !ts.isFunctionDeclaration(node) && !ts.isArrowFunction(node) && !ts.isFunctionExpression(node)) { + return false; + } + // For function declarations, expressions, and arrow functions, check if they have return type + if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node)) { + return !!node.type; + } + // For variable declarations + if (!node.name) return false; + const name = node.name.getText(); + if (name === 'generateMetadata') { + // If it's a function expression or arrow function, check if it has return type + if (node.initializer && (ts.isFunctionExpression(node.initializer) || ts.isArrowFunction(node.initializer))) { + return !!node.initializer.type; + } + } + // For all other cases, check if the node has a type annotation + return !!node.type; +} +const _default = metadata; + +//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/metadata.js.map b/e-commerce/node_modules/next/dist/server/typescript/rules/metadata.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d4fd6b709b379f9fcce2f903bd77e900cee91662 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/metadata.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/typescript/rules/metadata.ts"],"sourcesContent":["import { NEXT_TS_ERRORS } from '../constant'\nimport { getSource, getTs, getTypeChecker } from '../utils'\n\nimport type tsModule from 'typescript/lib/tsserverlibrary'\n\nconst metadata = {\n client: {\n getSemanticDiagnosticsForExportVariableStatement(\n fileName: string,\n node: tsModule.VariableStatement | tsModule.FunctionDeclaration\n ): tsModule.Diagnostic[] {\n const source = getSource(fileName)\n const ts = getTs()\n\n // It is not allowed to export `metadata` or `generateMetadata` in client entry\n if (ts.isFunctionDeclaration(node)) {\n if (node.name?.getText() === 'generateMetadata') {\n return [\n {\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_METADATA_EXPORT,\n messageText: `The Next.js 'generateMetadata' API is not allowed in a Client Component.`,\n start: node.name.getStart(),\n length: node.name.getWidth(),\n },\n ]\n }\n } else {\n for (const declaration of node.declarationList.declarations) {\n const name = declaration.name.getText()\n if (name === 'metadata') {\n return [\n {\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_METADATA_EXPORT,\n messageText: `The Next.js 'metadata' API is not allowed in a Client Component.`,\n start: declaration.name.getStart(),\n length: declaration.name.getWidth(),\n },\n ]\n }\n }\n }\n return []\n },\n getSemanticDiagnosticsForExportDeclaration(\n fileName: string,\n node: tsModule.ExportDeclaration\n ): tsModule.Diagnostic[] {\n const ts = getTs()\n const source = getSource(fileName)\n const diagnostics: tsModule.Diagnostic[] = []\n\n const exportClause = node.exportClause\n if (exportClause && ts.isNamedExports(exportClause)) {\n for (const e of exportClause.elements) {\n if (['generateMetadata', 'metadata'].includes(e.name.getText())) {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_METADATA_EXPORT,\n messageText: `The Next.js '${e.name.getText()}' API is not allowed in a Client Component.`,\n start: e.name.getStart(),\n length: e.name.getWidth(),\n })\n }\n }\n }\n\n return diagnostics\n },\n },\n server: {\n getSemanticDiagnosticsForExportVariableStatement(\n fileName: string,\n node: tsModule.VariableStatement | tsModule.FunctionDeclaration\n ): tsModule.Diagnostic[] {\n const source = getSource(fileName)\n const ts = getTs()\n\n if (ts.isFunctionDeclaration(node)) {\n if (node.name?.getText() === 'generateMetadata') {\n if (hasType(node)) {\n return []\n }\n\n const isAsync = node.modifiers?.some(\n (m) => m.kind === ts.SyntaxKind.AsyncKeyword\n )\n\n return [\n {\n file: source,\n category: ts.DiagnosticCategory.Warning,\n code: NEXT_TS_ERRORS.INVALID_METADATA_EXPORT,\n messageText: `The Next.js \"generateMetadata\" export should have a return type of ${isAsync ? '\"Promise\"' : '\"Metadata\"'} from \"next\".`,\n start: node.name.getStart(),\n length: node.name.getWidth(),\n },\n ]\n }\n } else {\n for (const declaration of node.declarationList.declarations) {\n if (hasType(declaration)) {\n return []\n }\n\n const name = declaration.name.getText()\n if (name === 'metadata') {\n return [\n {\n file: source,\n category: ts.DiagnosticCategory.Warning,\n code: NEXT_TS_ERRORS.INVALID_METADATA_EXPORT,\n messageText: `The Next.js \"metadata\" export should be type of \"Metadata\" from \"next\".`,\n start: declaration.name.getStart(),\n length: declaration.name.getWidth(),\n },\n ]\n }\n if (name === 'generateMetadata') {\n // Check if it's a function expression or arrow function\n if (\n declaration.initializer &&\n (ts.isFunctionExpression(declaration.initializer) ||\n ts.isArrowFunction(declaration.initializer))\n ) {\n const isAsync = declaration.initializer.modifiers?.some(\n (m) => m.kind === ts.SyntaxKind.AsyncKeyword\n )\n return [\n {\n file: source,\n category: ts.DiagnosticCategory.Warning,\n code: NEXT_TS_ERRORS.INVALID_METADATA_EXPORT,\n messageText: `The Next.js \"generateMetadata\" export should have a return type of ${isAsync ? '\"Promise\"' : '\"Metadata\"'} from \"next\".`,\n start: declaration.name.getStart(),\n length: declaration.name.getWidth(),\n },\n ]\n }\n }\n }\n }\n return []\n },\n getSemanticDiagnosticsForExportDeclaration(\n fileName: string,\n node: tsModule.ExportDeclaration\n ) {\n const typeChecker = getTypeChecker()\n if (!typeChecker) {\n return []\n }\n\n const ts = getTs()\n const source = getSource(fileName)\n const diagnostics: tsModule.Diagnostic[] = []\n\n const exportClause = node.exportClause\n if (!node.isTypeOnly && exportClause && ts.isNamedExports(exportClause)) {\n for (const e of exportClause.elements) {\n if (e.isTypeOnly) {\n continue\n }\n const exportName = e.name.getText()\n if (exportName !== 'metadata' && exportName !== 'generateMetadata') {\n continue\n }\n\n const symbol = typeChecker.getSymbolAtLocation(e.name)\n if (!symbol) {\n continue\n }\n\n const originalSymbol = typeChecker.getAliasedSymbol(symbol)\n const declarations = originalSymbol.getDeclarations()\n if (!declarations) {\n continue\n }\n\n const declaration = declarations[0]\n if (hasType(declaration)) {\n continue\n }\n\n if (exportName === 'generateMetadata') {\n let isAsync = false\n\n // async function() {}\n if (ts.isFunctionDeclaration(declaration)) {\n isAsync =\n declaration.modifiers?.some(\n (m) => m.kind === ts.SyntaxKind.AsyncKeyword\n ) ?? false\n }\n\n // foo = async function() {}\n // foo = async () => {}\n if (\n ts.isVariableDeclaration(declaration) &&\n declaration.initializer\n ) {\n const initializer = declaration.initializer\n const isFunction =\n ts.isArrowFunction(initializer) ||\n ts.isFunctionExpression(initializer)\n\n if (isFunction) {\n isAsync =\n initializer.modifiers?.some(\n (m) => m.kind === ts.SyntaxKind.AsyncKeyword\n ) ?? false\n }\n }\n\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Warning,\n code: NEXT_TS_ERRORS.INVALID_METADATA_EXPORT,\n messageText: `The Next.js \"generateMetadata\" export should have a return type of ${isAsync ? '\"Promise\"' : '\"Metadata\"'} from \"next\".`,\n start: e.name.getStart(),\n length: e.name.getWidth(),\n })\n } else {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Warning,\n code: NEXT_TS_ERRORS.INVALID_METADATA_EXPORT,\n messageText: `The Next.js \"metadata\" export should be type of \"Metadata\" from \"next\".`,\n start: e.name.getStart(),\n length: e.name.getWidth(),\n })\n }\n }\n }\n return diagnostics\n },\n },\n}\n\nfunction hasType(node: tsModule.Declaration): boolean {\n const ts = getTs()\n\n if (\n !ts.isVariableDeclaration(node) &&\n !ts.isFunctionDeclaration(node) &&\n !ts.isArrowFunction(node) &&\n !ts.isFunctionExpression(node)\n ) {\n return false\n }\n\n // For function declarations, expressions, and arrow functions, check if they have return type\n if (\n ts.isFunctionDeclaration(node) ||\n ts.isFunctionExpression(node) ||\n ts.isArrowFunction(node)\n ) {\n return !!node.type\n }\n\n // For variable declarations\n if (!node.name) return false\n const name = node.name.getText()\n if (name === 'generateMetadata') {\n // If it's a function expression or arrow function, check if it has return type\n if (\n node.initializer &&\n (ts.isFunctionExpression(node.initializer) ||\n ts.isArrowFunction(node.initializer))\n ) {\n return !!node.initializer.type\n }\n }\n\n // For all other cases, check if the node has a type annotation\n return !!node.type\n}\n\nexport default metadata\n"],"names":["metadata","client","getSemanticDiagnosticsForExportVariableStatement","fileName","node","source","getSource","ts","getTs","isFunctionDeclaration","name","getText","file","category","DiagnosticCategory","Error","code","NEXT_TS_ERRORS","INVALID_METADATA_EXPORT","messageText","start","getStart","length","getWidth","declaration","declarationList","declarations","getSemanticDiagnosticsForExportDeclaration","diagnostics","exportClause","isNamedExports","e","elements","includes","push","server","hasType","isAsync","modifiers","some","m","kind","SyntaxKind","AsyncKeyword","Warning","initializer","isFunctionExpression","isArrowFunction","typeChecker","getTypeChecker","isTypeOnly","exportName","symbol","getSymbolAtLocation","originalSymbol","getAliasedSymbol","getDeclarations","isVariableDeclaration","isFunction","type"],"mappings":";;;;+BA0RA;;;eAAA;;;0BA1R+B;uBACkB;AAIjD,MAAMA,WAAW;IACfC,QAAQ;QACNC,kDACEC,QAAgB,EAChBC,IAA+D;YAE/D,MAAMC,SAASC,IAAAA,gBAAS,EAACH;YACzB,MAAMI,KAAKC,IAAAA,YAAK;YAEhB,+EAA+E;YAC/E,IAAID,GAAGE,qBAAqB,CAACL,OAAO;oBAC9BA;gBAAJ,IAAIA,EAAAA,aAAAA,KAAKM,IAAI,qBAATN,WAAWO,OAAO,QAAO,oBAAoB;oBAC/C,OAAO;wBACL;4BACEC,MAAMP;4BACNQ,UAAUN,GAAGO,kBAAkB,CAACC,KAAK;4BACrCC,MAAMC,wBAAc,CAACC,uBAAuB;4BAC5CC,aAAa,CAAC,wEAAwE,CAAC;4BACvFC,OAAOhB,KAAKM,IAAI,CAACW,QAAQ;4BACzBC,QAAQlB,KAAKM,IAAI,CAACa,QAAQ;wBAC5B;qBACD;gBACH;YACF,OAAO;gBACL,KAAK,MAAMC,eAAepB,KAAKqB,eAAe,CAACC,YAAY,CAAE;oBAC3D,MAAMhB,OAAOc,YAAYd,IAAI,CAACC,OAAO;oBACrC,IAAID,SAAS,YAAY;wBACvB,OAAO;4BACL;gCACEE,MAAMP;gCACNQ,UAAUN,GAAGO,kBAAkB,CAACC,KAAK;gCACrCC,MAAMC,wBAAc,CAACC,uBAAuB;gCAC5CC,aAAa,CAAC,gEAAgE,CAAC;gCAC/EC,OAAOI,YAAYd,IAAI,CAACW,QAAQ;gCAChCC,QAAQE,YAAYd,IAAI,CAACa,QAAQ;4BACnC;yBACD;oBACH;gBACF;YACF;YACA,OAAO,EAAE;QACX;QACAI,4CACExB,QAAgB,EAChBC,IAAgC;YAEhC,MAAMG,KAAKC,IAAAA,YAAK;YAChB,MAAMH,SAASC,IAAAA,gBAAS,E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B;QACA,OAAO,CAAC,CAACA,KAAKuD,IAAI;IACpB;IAEA,4BAA4B;IAC5B,IAAI,CAACvD,KAAKM,IAAI,EAAE,OAAO;IACvB,MAAMA,OAAON,KAAKM,IAAI,CAACC,OAAO;IAC9B,IAAID,SAAS,oBAAoB;QAC/B,+EAA+E;QAC/E,IACEN,KAAKyC,WAAW,IACftC,CAAAA,GAAGuC,oBAAoB,CAAC1C,KAAKyC,WAAW,KACvCtC,GAAGwC,eAAe,CAAC3C,KAAKyC,WAAW,CAAA,GACrC;YACA,OAAO,CAAC,CAACzC,KAAKyC,WAAW,CAACc,IAAI;QAChC;IACF;IAEA,+DAA+D;IAC/D,OAAO,CAAC,CAACvD,KAAKuD,IAAI;AACpB;MAEA,WAAe3D","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/server-boundary.d.ts b/e-commerce/node_modules/next/dist/server/typescript/rules/server-boundary.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0cbc33ba6f149c6325e403af3732adcf4571bb23 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/server-boundary.d.ts @@ -0,0 +1,7 @@ +import type tsModule from 'typescript/lib/tsserverlibrary'; +declare const serverBoundary: { + getSemanticDiagnosticsForExportDeclaration(source: tsModule.SourceFile, node: tsModule.ExportDeclaration): tsModule.Diagnostic[]; + getSemanticDiagnosticsForExportVariableStatement(source: tsModule.SourceFile, node: tsModule.VariableStatement): tsModule.Diagnostic[]; + getSemanticDiagnosticsForFunctionExport(source: tsModule.SourceFile, node: tsModule.FunctionDeclaration | tsModule.ArrowFunction | tsModule.FunctionExpression | tsModule.CallExpression | tsModule.Identifier): tsModule.Diagnostic[]; +}; +export default serverBoundary; diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/server-boundary.js b/e-commerce/node_modules/next/dist/server/typescript/rules/server-boundary.js new file mode 100644 index 0000000000000000000000000000000000000000..6884b0bfcbf3b08b957658811ab686028e97211e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/server-boundary.js @@ -0,0 +1,115 @@ +// This module provides intellisense for all exports from `"use server"` directive. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _constant = require("../constant"); +const _utils = require("../utils"); +// Check if the type is `Promise`. +function isPromiseType(type, typeChecker) { + const typeReferenceType = type; + if (!typeReferenceType.target) return false; + // target should be Promise or Promise<...> + if (!/^Promise(<.+>)?$/.test(typeChecker.typeToString(typeReferenceType.target))) { + return false; + } + return true; +} +function isFunctionReturningPromise(node, typeChecker, ts) { + const type = typeChecker.getTypeAtLocation(node); + const signatures = typeChecker.getSignaturesOfType(type, ts.SignatureKind.Call); + let isPromise = true; + if (signatures.length) { + for (const signature of signatures){ + const returnType = signature.getReturnType(); + if (returnType.isUnion()) { + for (const t of returnType.types){ + if (!isPromiseType(t, typeChecker)) { + isPromise = false; + break; + } + } + } else { + isPromise = isPromiseType(returnType, typeChecker); + } + } + } else { + isPromise = false; + } + return isPromise; +} +const serverBoundary = { + getSemanticDiagnosticsForExportDeclaration (source, node) { + const ts = (0, _utils.getTs)(); + const typeChecker = (0, _utils.getTypeChecker)(); + if (!typeChecker) return []; + const diagnostics = []; + const exportClause = node.exportClause; + if (!node.isTypeOnly && exportClause && ts.isNamedExports(exportClause)) { + for (const e of exportClause.elements){ + if (e.isTypeOnly) { + continue; + } + if (!isFunctionReturningPromise(e, typeChecker, ts)) { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_SERVER_ENTRY_RETURN, + messageText: `The "use server" file can only export async functions.`, + start: e.getStart(), + length: e.getWidth() + }); + } + } + } + return diagnostics; + }, + getSemanticDiagnosticsForExportVariableStatement (source, node) { + const ts = (0, _utils.getTs)(); + const diagnostics = []; + if (ts.isVariableDeclarationList(node.declarationList)) { + for (const declaration of node.declarationList.declarations){ + const initializer = declaration.initializer; + if (initializer && (ts.isArrowFunction(initializer) || ts.isFunctionDeclaration(initializer) || ts.isFunctionExpression(initializer) || ts.isCallExpression(initializer) || ts.isIdentifier(initializer))) { + diagnostics.push(...serverBoundary.getSemanticDiagnosticsForFunctionExport(source, initializer)); + } else { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_SERVER_ENTRY_RETURN, + messageText: `The "use server" file can only export async functions.`, + start: declaration.getStart(), + length: declaration.getWidth() + }); + } + } + } + return diagnostics; + }, + getSemanticDiagnosticsForFunctionExport (source, node) { + const ts = (0, _utils.getTs)(); + const typeChecker = (0, _utils.getTypeChecker)(); + if (!typeChecker) return []; + const diagnostics = []; + if (!isFunctionReturningPromise(node, typeChecker, ts)) { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_SERVER_ENTRY_RETURN, + messageText: `The "use server" file can only export async functions. Add "async" to the function declaration or return a Promise.`, + start: node.getStart(), + length: node.getWidth() + }); + } + return diagnostics; + } +}; +const _default = serverBoundary; + +//# sourceMappingURL=server-boundary.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/server-boundary.js.map b/e-commerce/node_modules/next/dist/server/typescript/rules/server-boundary.js.map new file mode 100644 index 0000000000000000000000000000000000000000..81f81a18371d70cfbfce6abd29c221a801be97f9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/server-boundary.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/typescript/rules/server-boundary.ts"],"sourcesContent":["// This module provides intellisense for all exports from `\"use server\"` directive.\n\nimport { NEXT_TS_ERRORS } from '../constant'\nimport { getTs, getTypeChecker } from '../utils'\nimport type tsModule from 'typescript/lib/tsserverlibrary'\n\n// Check if the type is `Promise`.\nfunction isPromiseType(type: tsModule.Type, typeChecker: tsModule.TypeChecker) {\n const typeReferenceType = type as tsModule.TypeReference\n if (!typeReferenceType.target) return false\n\n // target should be Promise or Promise<...>\n if (\n !/^Promise(<.+>)?$/.test(typeChecker.typeToString(typeReferenceType.target))\n ) {\n return false\n }\n\n return true\n}\n\nfunction isFunctionReturningPromise(\n node: tsModule.Node,\n typeChecker: tsModule.TypeChecker,\n ts: typeof tsModule\n) {\n const type = typeChecker.getTypeAtLocation(node)\n const signatures = typeChecker.getSignaturesOfType(\n type,\n ts.SignatureKind.Call\n )\n\n let isPromise = true\n if (signatures.length) {\n for (const signature of signatures) {\n const returnType = signature.getReturnType()\n if (returnType.isUnion()) {\n for (const t of returnType.types) {\n if (!isPromiseType(t, typeChecker)) {\n isPromise = false\n break\n }\n }\n } else {\n isPromise = isPromiseType(returnType, typeChecker)\n }\n }\n } else {\n isPromise = false\n }\n\n return isPromise\n}\n\nconst serverBoundary = {\n getSemanticDiagnosticsForExportDeclaration(\n source: tsModule.SourceFile,\n node: tsModule.ExportDeclaration\n ) {\n const ts = getTs()\n const typeChecker = getTypeChecker()\n if (!typeChecker) return []\n\n const diagnostics: tsModule.Diagnostic[] = []\n\n const exportClause = node.exportClause\n if (!node.isTypeOnly && exportClause && ts.isNamedExports(exportClause)) {\n for (const e of exportClause.elements) {\n if (e.isTypeOnly) {\n continue\n }\n if (!isFunctionReturningPromise(e, typeChecker, ts)) {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_SERVER_ENTRY_RETURN,\n messageText: `The \"use server\" file can only export async functions.`,\n start: e.getStart(),\n length: e.getWidth(),\n })\n }\n }\n }\n\n return diagnostics\n },\n\n getSemanticDiagnosticsForExportVariableStatement(\n source: tsModule.SourceFile,\n node: tsModule.VariableStatement\n ) {\n const ts = getTs()\n\n const diagnostics: tsModule.Diagnostic[] = []\n\n if (ts.isVariableDeclarationList(node.declarationList)) {\n for (const declaration of node.declarationList.declarations) {\n const initializer = declaration.initializer\n if (\n initializer &&\n (ts.isArrowFunction(initializer) ||\n ts.isFunctionDeclaration(initializer) ||\n ts.isFunctionExpression(initializer) ||\n ts.isCallExpression(initializer) ||\n ts.isIdentifier(initializer))\n ) {\n diagnostics.push(\n ...serverBoundary.getSemanticDiagnosticsForFunctionExport(\n source,\n initializer\n )\n )\n } else {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_SERVER_ENTRY_RETURN,\n messageText: `The \"use server\" file can only export async functions.`,\n start: declaration.getStart(),\n length: declaration.getWidth(),\n })\n }\n }\n }\n\n return diagnostics\n },\n\n getSemanticDiagnosticsForFunctionExport(\n source: tsModule.SourceFile,\n node:\n | tsModule.FunctionDeclaration\n | tsModule.ArrowFunction\n | tsModule.FunctionExpression\n | tsModule.CallExpression\n | tsModule.Identifier\n ) {\n const ts = getTs()\n const typeChecker = getTypeChecker()\n if (!typeChecker) return []\n\n const diagnostics: tsModule.Diagnostic[] = []\n\n if (!isFunctionReturningPromise(node, typeChecker, ts)) {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_SERVER_ENTRY_RETURN,\n messageText: `The \"use server\" file can only export async functions. Add \"async\" to the function declaration or return a Promise.`,\n start: node.getStart(),\n length: node.getWidth(),\n })\n }\n\n return diagnostics\n },\n}\n\nexport default serverBoundary\n"],"names":["isPromiseType","type","typeChecker","typeReferenceType","target","test","typeToString","isFunctionReturningPromise","node","ts","getTypeAtLocation","signatures","getSignaturesOfType","SignatureKind","Call","isPromise","length","signature","returnType","getReturnType","isUnion","t","types","serverBoundary","getSemanticDiagnosticsForExportDeclaration","source","getTs","getTypeChecker","diagnostics","exportClause","isTypeOnly","isNamedExports","e","elements","push","file","category","DiagnosticCategory","Error","code","NEXT_TS_ERRORS","INVALID_SERVER_ENTRY_RETURN","messageText","start","getStart","getWidth","getSemanticDiagnosticsForExportVariableStatement","isVariableDeclarationList","declarationList","declaration","declarations","initializer","isArrowFunction","isFunctionDeclaration","isFunctionExpression","isCallExpression","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AAMC,KAAKiB,IAAAA,YAAK;QAChB,MAAMxB,cAAcyB,IAAAA,qBAAc;QAClC,IAAI,CAACzB,aAAa,OAAO,EAAE;QAE3B,MAAM0B,cAAqC,EAAE;QAE7C,IAAI,CAACrB,2BAA2BC,MAAMN,aAAaO,KAAK;YACtDmB,YAAYM,IAAI,CAAC;gBACfC,MAAMV;gBACNW,UAAU3B,GAAG4B,kBAAkB,CAACC,KAAK;gBACrCC,MAAMC,wBAAc,CAACC,2BAA2B;gBAChDC,aAAa,CAAC,mHAAmH,CAAC;gBAClIC,OAAOnC,KAAKoC,QAAQ;gBACpB5B,QAAQR,KAAKqC,QAAQ;YACvB;QACF;QAEA,OAAOjB;IACT;AACF;MAEA,WAAeL","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/server.d.ts b/e-commerce/node_modules/next/dist/server/typescript/rules/server.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a46cfccdda43a99ad7df98cf87d47f68d65cd54 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/server.d.ts @@ -0,0 +1,7 @@ +import type tsModule from 'typescript/lib/tsserverlibrary'; +declare const serverLayer: { + filterCompletionsAtPosition(entries: tsModule.CompletionEntry[]): tsModule.CompletionEntry[]; + hasDisallowedReactAPIDefinition(definitions: readonly tsModule.DefinitionInfo[]): boolean; + getSemanticDiagnosticsForImportDeclaration(source: tsModule.SourceFile, node: tsModule.ImportDeclaration): tsModule.Diagnostic[]; +}; +export default serverLayer; diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/server.js b/e-commerce/node_modules/next/dist/server/typescript/rules/server.js new file mode 100644 index 0000000000000000000000000000000000000000..bca5eaf784703b4d61d98dabee3eba47493a9043 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/server.js @@ -0,0 +1,79 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _constant = require("../constant"); +const _utils = require("../utils"); +const serverLayer = { + // On the server layer we need to filter out some invalid completion results. + filterCompletionsAtPosition (entries) { + return entries.filter((e)=>{ + // Remove disallowed React APIs. + if (_constant.DISALLOWED_SERVER_REACT_APIS.includes(e.name) && e.source === 'react') { + return false; + } + return true; + }); + }, + // Filter out quick info for some React APIs. + hasDisallowedReactAPIDefinition (definitions) { + return definitions == null ? void 0 : definitions.some((d)=>_constant.DISALLOWED_SERVER_REACT_APIS.includes(d.name) && d.containerName === 'React'); + }, + // Give errors about disallowed imports such as `useState`. + getSemanticDiagnosticsForImportDeclaration (source, node) { + const ts = (0, _utils.getTs)(); + const diagnostics = []; + const importPath = node.moduleSpecifier.getText(source); + const importClause = node.importClause; + const namedBindings = importClause == null ? void 0 : importClause.namedBindings; + if (importClause) { + if (/^['"]react['"]$/.test(importPath)) { + // Check if it imports "useState" + if (namedBindings && ts.isNamedImports(namedBindings)) { + const elements = namedBindings.elements; + for (const element of elements){ + const name = element.name.getText(source); + if (_constant.DISALLOWED_SERVER_REACT_APIS.includes(name)) { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_SERVER_API, + messageText: `"${name}" is not allowed in Server Components.`, + start: element.name.getStart(), + length: element.name.getWidth() + }); + } + } + } + } else if (/^['"]react-dom['"]$/.test(importPath)) { + // Check if it imports "useFormState" + if (namedBindings && ts.isNamedImports(namedBindings)) { + const elements = namedBindings.elements; + for (const element of elements){ + const name = element.name.getText(source); + if (_constant.DISALLOWED_SERVER_REACT_DOM_APIS.includes(name)) { + diagnostics.push({ + file: source, + category: ts.DiagnosticCategory.Error, + code: _constant.NEXT_TS_ERRORS.INVALID_SERVER_API, + messageText: `"${name}" is not allowed in Server Components.`, + start: element.name.getStart(), + length: element.name.getWidth() + }); + } + } + } + } + } + return diagnostics; + } +}; +const _default = serverLayer; + +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/rules/server.js.map b/e-commerce/node_modules/next/dist/server/typescript/rules/server.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a2a3688266a7f9e7ae8d19849ecbb304e810ca8a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/rules/server.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/typescript/rules/server.ts"],"sourcesContent":["import {\n DISALLOWED_SERVER_REACT_APIS,\n DISALLOWED_SERVER_REACT_DOM_APIS,\n NEXT_TS_ERRORS,\n} from '../constant'\nimport { getTs } from '../utils'\nimport type tsModule from 'typescript/lib/tsserverlibrary'\n\nconst serverLayer = {\n // On the server layer we need to filter out some invalid completion results.\n filterCompletionsAtPosition(entries: tsModule.CompletionEntry[]) {\n return entries.filter((e: tsModule.CompletionEntry) => {\n // Remove disallowed React APIs.\n if (\n DISALLOWED_SERVER_REACT_APIS.includes(e.name) &&\n e.source === 'react'\n ) {\n return false\n }\n return true\n })\n },\n\n // Filter out quick info for some React APIs.\n hasDisallowedReactAPIDefinition(\n definitions: readonly tsModule.DefinitionInfo[]\n ) {\n return definitions?.some(\n (d) =>\n DISALLOWED_SERVER_REACT_APIS.includes(d.name) &&\n d.containerName === 'React'\n )\n },\n\n // Give errors about disallowed imports such as `useState`.\n getSemanticDiagnosticsForImportDeclaration(\n source: tsModule.SourceFile,\n node: tsModule.ImportDeclaration\n ) {\n const ts = getTs()\n\n const diagnostics: tsModule.Diagnostic[] = []\n\n const importPath = node.moduleSpecifier.getText(source!)\n const importClause = node.importClause\n const namedBindings = importClause?.namedBindings\n\n if (importClause) {\n if (/^['\"]react['\"]$/.test(importPath)) {\n // Check if it imports \"useState\"\n if (namedBindings && ts.isNamedImports(namedBindings)) {\n const elements = namedBindings.elements\n for (const element of elements) {\n const name = element.name.getText(source!)\n if (DISALLOWED_SERVER_REACT_APIS.includes(name)) {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_SERVER_API,\n messageText: `\"${name}\" is not allowed in Server Components.`,\n start: element.name.getStart(),\n length: element.name.getWidth(),\n })\n }\n }\n }\n } else if (/^['\"]react-dom['\"]$/.test(importPath)) {\n // Check if it imports \"useFormState\"\n if (namedBindings && ts.isNamedImports(namedBindings)) {\n const elements = namedBindings.elements\n for (const element of elements) {\n const name = element.name.getText(source!)\n if (DISALLOWED_SERVER_REACT_DOM_APIS.includes(name)) {\n diagnostics.push({\n file: source,\n category: ts.DiagnosticCategory.Error,\n code: NEXT_TS_ERRORS.INVALID_SERVER_API,\n messageText: `\"${name}\" is not allowed in Server Components.`,\n start: element.name.getStart(),\n length: element.name.getWidth(),\n })\n }\n }\n }\n }\n }\n\n return diagnostics\n },\n}\n\nexport default serverLayer\n"],"names":["serverLayer","filterCompletionsAtPosition","entries","filter","e","DISALLOWED_SERVER_REACT_APIS","includes","name","source","hasDisallowedReactAPIDefinition","definitions","some","d","containerName","getSemanticDiagnosticsForImportDeclaration","node","ts","getTs","diagnostics","importPath","moduleSpecifier","getText","importClause","namedBindings","test","isNamedImports","elements","element","push","file","category","DiagnosticCategory","Error","code","NEXT_TS_ERRORS","INVALID_SERVER_API","messageText","start","getStart","length","getWidth","DISALLOWED_SERVER_REACT_DOM_APIS"],"mappings":";;;;+BA2FA;;;eAAA;;;0BAvFO;uBACe;AAGtB,MAAMA,cAAc;IAClB,6EAA6E;IAC7EC,6BAA4BC,OAAmC;QAC7D,OAAOA,QAAQC,MAAM,CAAC,CAACC;YACrB,gCAAgC;YAChC,IACEC,sCAA4B,CAACC,QAAQ,CAACF,EAAEG,IAAI,KAC5CH,EAAEI,MAAM,KAAK,SACb;gBACA,OAAO;YACT;YACA,OAAO;QACT;IACF;IAEA,6CAA6C;IAC7CC,iCACEC,WAA+C;QAE/C,OAAOA,+BAAAA,YAAaC,IAAI,CACtB,CAACC,IACCP,sCAA4B,CAACC,QAAQ,CAACM,EAAEL,IAAI,KAC5CK,EAAEC,aAAa,KAAK;IAE1B;I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C,MAAMC,wBAAc,CAACC,kBAAkB;gCACvCC,aAAa,CAAC,CAAC,EAAE7B,KAAK,sCAAsC,CAAC;gCAC7D8B,OAAOV,QAAQpB,IAAI,CAAC+B,QAAQ;gCAC5BC,QAAQZ,QAAQpB,IAAI,CAACiC,QAAQ;4BAC/B;wBACF;oBACF;gBACF;YACF;QACF;QAEA,OAAOtB;IACT;AACF;MAEA,WAAelB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/utils.d.ts b/e-commerce/node_modules/next/dist/server/typescript/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f413eb7f7e54ea653490caaa9a74fafb5f28d850 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/utils.d.ts @@ -0,0 +1,22 @@ +import type tsModule from 'typescript/lib/tsserverlibrary'; +type TypeScript = typeof import('typescript/lib/tsserverlibrary'); +export declare function log(message: string): void; +export declare function init(opts: { + ts: TypeScript; + info: tsModule.server.PluginCreateInfo; +}): void; +export declare function getTs(): typeof tsModule; +export declare function getInfo(): tsModule.server.PluginCreateInfo; +export declare function getTypeChecker(): tsModule.TypeChecker | undefined; +export declare function getSource(fileName: string): tsModule.SourceFile | undefined; +export declare function removeStringQuotes(str: string): string; +export declare const isPositionInsideNode: (position: number, node: tsModule.Node) => boolean; +export declare const isDefaultFunctionExport: (node: tsModule.Node) => node is tsModule.FunctionDeclaration; +export declare const isInsideApp: (filePath: string) => boolean; +export declare const isAppEntryFile: (filePath: string) => boolean; +export declare const isPageFile: (filePath: string) => boolean; +export declare function getEntryInfo(fileName: string, throwOnInvalidDirective?: boolean): { + client: boolean; + server: boolean; +}; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/typescript/utils.js b/e-commerce/node_modules/next/dist/server/typescript/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..25b9f816c4a9c09d767035df91dc6f84e9cf0063 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/utils.js @@ -0,0 +1,212 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getEntryInfo: null, + getInfo: null, + getSource: null, + getTs: null, + getTypeChecker: null, + init: null, + isAppEntryFile: null, + isDefaultFunctionExport: null, + isInsideApp: null, + isPageFile: null, + isPositionInsideNode: null, + log: null, + removeStringQuotes: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getEntryInfo: function() { + return getEntryInfo; + }, + getInfo: function() { + return getInfo; + }, + getSource: function() { + return getSource; + }, + getTs: function() { + return getTs; + }, + getTypeChecker: function() { + return getTypeChecker; + }, + init: function() { + return init; + }, + isAppEntryFile: function() { + return isAppEntryFile; + }, + isDefaultFunctionExport: function() { + return isDefaultFunctionExport; + }, + isInsideApp: function() { + return isInsideApp; + }, + isPageFile: function() { + return isPageFile; + }, + isPositionInsideNode: function() { + return isPositionInsideNode; + }, + log: function() { + return log; + }, + removeStringQuotes: function() { + return removeStringQuotes; + } +}); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +let ts; +let info; +let appDirRegExp; +function log(message) { + info.project.projectService.logger.info('[next] ' + message); +} +function init(opts) { + const projectDir = opts.info.project.getCurrentDirectory(); + ts = opts.ts; + info = opts.info; + appDirRegExp = new RegExp('^' + (projectDir + '(/src)?/app').replace(/[\\/]/g, '[\\/]')); + log('Initialized Next.js TypeScript plugin: ' + projectDir); +} +function getTs() { + return ts; +} +function getInfo() { + return info; +} +function getTypeChecker() { + const program = info.languageService.getProgram(); + if (!program) { + log('Failed to get program while while running getTypeChecker.'); + return; + } + const typeChecker = program.getTypeChecker(); + if (!typeChecker) { + log('Failed to get type checker while running getTypeChecker.'); + return; + } + return typeChecker; +} +function getSource(fileName) { + const program = info.languageService.getProgram(); + if (!program) { + log('Failed to get program while running getSource for: ' + fileName); + return; + } + const sourceFile = program.getSourceFile(fileName); + if (!sourceFile) { + log('Failed to get source file while running getSource for: ' + fileName); + return; + } + return sourceFile; +} +function removeStringQuotes(str) { + return str.replace(/^['"`]|['"`]$/g, ''); +} +const isPositionInsideNode = (position, node)=>{ + const start = node.getFullStart(); + return start <= position && position <= node.getFullWidth() + start; +}; +const isDefaultFunctionExport = (node)=>{ + if (ts.isFunctionDeclaration(node)) { + let hasExportKeyword = false; + let hasDefaultKeyword = false; + if (node.modifiers) { + for (const modifier of node.modifiers){ + if (modifier.kind === ts.SyntaxKind.ExportKeyword) { + hasExportKeyword = true; + } else if (modifier.kind === ts.SyntaxKind.DefaultKeyword) { + hasDefaultKeyword = true; + } + } + } + // `export default function` + if (hasExportKeyword && hasDefaultKeyword) { + return true; + } + } + return false; +}; +const isInsideApp = (filePath)=>{ + return appDirRegExp.test(filePath); +}; +const isAppEntryFile = (filePath)=>{ + return appDirRegExp.test(filePath) && /^(page|layout)\.(mjs|js|jsx|ts|tsx)$/.test(_path.default.basename(filePath)); +}; +const isPageFile = (filePath)=>{ + return appDirRegExp.test(filePath) && /^page\.(mjs|js|jsx|ts|tsx)$/.test(_path.default.basename(filePath)); +}; +function getEntryInfo(fileName, throwOnInvalidDirective) { + const source = getSource(fileName); + if (source) { + let isDirective = true; + let isClientEntry = false; + let isServerEntry = false; + ts.forEachChild(source, (node)=>{ + if (ts.isExpressionStatement(node) && ts.isStringLiteral(node.expression)) { + if (node.expression.text === 'use client') { + if (isDirective) { + isClientEntry = true; + } else { + if (throwOnInvalidDirective) { + const e = { + messageText: 'The `"use client"` directive must be put at the top of the file.', + start: node.expression.getStart(), + length: node.expression.getWidth() + }; + throw e; + } + } + } else if (node.expression.text === 'use server') { + if (isDirective) { + isServerEntry = true; + } else { + if (throwOnInvalidDirective) { + const e = { + messageText: 'The `"use server"` directive must be put at the top of the file.', + start: node.expression.getStart(), + length: node.expression.getWidth() + }; + throw e; + } + } + } + if (isClientEntry && isServerEntry) { + const e = { + messageText: 'Cannot use both "use client" and "use server" directives in the same file.', + start: node.expression.getStart(), + length: node.expression.getWidth() + }; + throw e; + } + } else { + isDirective = false; + } + }); + return { + client: isClientEntry, + server: isServerEntry + }; + } + return { + client: false, + server: false + }; +} + +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/typescript/utils.js.map b/e-commerce/node_modules/next/dist/server/typescript/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..37c9a88d70a62e09b4a07f3e82ff36327e504aed --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/typescript/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/typescript/utils.ts"],"sourcesContent":["import path from 'path'\n\nimport type tsModule from 'typescript/lib/tsserverlibrary'\ntype TypeScript = typeof import('typescript/lib/tsserverlibrary')\n\nlet ts: TypeScript\nlet info: tsModule.server.PluginCreateInfo\nlet appDirRegExp: RegExp\n\nexport function log(message: string) {\n info.project.projectService.logger.info('[next] ' + message)\n}\n\n// This function has to be called initially.\nexport function init(opts: {\n ts: TypeScript\n info: tsModule.server.PluginCreateInfo\n}) {\n const projectDir = opts.info.project.getCurrentDirectory()\n ts = opts.ts\n info = opts.info\n appDirRegExp = new RegExp(\n '^' + (projectDir + '(/src)?/app').replace(/[\\\\/]/g, '[\\\\/]')\n )\n\n log('Initialized Next.js TypeScript plugin: ' + projectDir)\n}\n\nexport function getTs() {\n return ts\n}\n\nexport function getInfo() {\n return info\n}\n\nexport function getTypeChecker() {\n const program = info.languageService.getProgram()\n if (!program) {\n log('Failed to get program while while running getTypeChecker.')\n return\n }\n const typeChecker = program.getTypeChecker()\n if (!typeChecker) {\n log('Failed to get type checker while running getTypeChecker.')\n return\n }\n return typeChecker\n}\n\nexport function getSource(fileName: string) {\n const program = info.languageService.getProgram()\n if (!program) {\n log('Failed to get program while running getSource for: ' + fileName)\n return\n }\n\n const sourceFile = program.getSourceFile(fileName)\n if (!sourceFile) {\n log('Failed to get source file while running getSource for: ' + fileName)\n return\n }\n\n return sourceFile\n}\n\nexport function removeStringQuotes(str: string): string {\n return str.replace(/^['\"`]|['\"`]$/g, '')\n}\n\nexport const isPositionInsideNode = (position: number, node: tsModule.Node) => {\n const start = node.getFullStart()\n return start <= position && position <= node.getFullWidth() + start\n}\n\nexport const isDefaultFunctionExport = (\n node: tsModule.Node\n): node is tsModule.FunctionDeclaration => {\n if (ts.isFunctionDeclaration(node)) {\n let hasExportKeyword = false\n let hasDefaultKeyword = false\n\n if (node.modifiers) {\n for (const modifier of node.modifiers) {\n if (modifier.kind === ts.SyntaxKind.ExportKeyword) {\n hasExportKeyword = true\n } else if (modifier.kind === ts.SyntaxKind.DefaultKeyword) {\n hasDefaultKeyword = true\n }\n }\n }\n\n // `export default function`\n if (hasExportKeyword && hasDefaultKeyword) {\n return true\n }\n }\n return false\n}\n\nexport const isInsideApp = (filePath: string) => {\n return appDirRegExp.test(filePath)\n}\nexport const isAppEntryFile = (filePath: string) => {\n return (\n appDirRegExp.test(filePath) &&\n /^(page|layout)\\.(mjs|js|jsx|ts|tsx)$/.test(path.basename(filePath))\n )\n}\nexport const isPageFile = (filePath: string) => {\n return (\n appDirRegExp.test(filePath) &&\n /^page\\.(mjs|js|jsx|ts|tsx)$/.test(path.basename(filePath))\n )\n}\n\n// Check if a module is a client entry.\nexport function getEntryInfo(\n fileName: string,\n throwOnInvalidDirective?: boolean\n) {\n const source = getSource(fileName)\n if (source) {\n let isDirective = true\n let isClientEntry = false\n let isServerEntry = false\n\n ts.forEachChild(source!, (node) => {\n if (\n ts.isExpressionStatement(node) &&\n ts.isStringLiteral(node.expression)\n ) {\n if (node.expression.text === 'use client') {\n if (isDirective) {\n isClientEntry = true\n } else {\n if (throwOnInvalidDirective) {\n const e = {\n messageText:\n 'The `\"use client\"` directive must be put at the top of the file.',\n start: node.expression.getStart(),\n length: node.expression.getWidth(),\n }\n throw e\n }\n }\n } else if (node.expression.text === 'use server') {\n if (isDirective) {\n isServerEntry = true\n } else {\n if (throwOnInvalidDirective) {\n const e = {\n messageText:\n 'The `\"use server\"` directive must be put at the top of the file.',\n start: node.expression.getStart(),\n length: node.expression.getWidth(),\n }\n throw e\n }\n }\n }\n\n if (isClientEntry && isServerEntry) {\n const e = {\n messageText:\n 'Cannot use both \"use client\" and \"use server\" directives in the same file.',\n start: node.expression.getStart(),\n length: node.expression.getWidth(),\n }\n throw e\n }\n } else {\n isDirective = false\n }\n })\n\n return { client: isClientEntry, server: isServerEntry }\n }\n\n return { client: false, server: false }\n}\n"],"names":["getEntryInfo","getInfo","getSource","getTs","getTypeChecker","init","isAppEntryFile","isDefaultFunctionExport","isInsideApp","isPageFile","isPositionInsideNode","log","removeStringQuotes","ts","info","appDirRegExp","message","project","projectService","logger","opts","projectDir","getCurrentDirectory","RegExp","replace","program","languageService","getProgram","typeChecker","fileName","sourceFile","getSourceFile","str","position","node","start","getFullStart","getFullWidth","isFunctionDeclaration","hasExportKeyword","hasDefaultKeyword","modifiers","modifier","kind","SyntaxKind","ExportKeyword","DefaultKeyword","filePath","test","path","basename","throwOnInvalidDirective","source","isDirective","isClientEntry","isServerEntry","forEachChild","isExpressionStatement","isStringLiteral","expression","text","e","messageText","getStart","length","getWidth","client","server"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;IAqHgBA,YAAY;eAAZA;;IArFAC,OAAO;eAAPA;;IAkBAC,SAAS;eAATA;;IAtBAC,KAAK;eAALA;;IAQAC,cAAc;eAAdA;;IAtBAC,IAAI;eAAJA;;IAyFHC,cAAc;eAAdA;;IA5BAC,uBAAuB;eAAvBA;;IAyBAC,WAAW;eAAXA;;IASAC,UAAU;eAAVA;;IAvCAC,oBAAoB;eAApBA;;IA7DGC,GAAG;eAAHA;;IAyDAC,kBAAkB;eAAlBA;;;6DAlEC;;;;;;AAKjB,IAAIC;AACJ,IAAIC;AACJ,IAAIC;AAEG,SAASJ,IAAIK,OAAe;IACjCF,KAAKG,OAAO,CAACC,cAAc,CAACC,MAAM,CAACL,IAAI,CAAC,YAAYE;AACtD;AAGO,SA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AyB;4BAC3B,MAAMU,IAAI;gCACRC,aACE;gCACF3B,OAAOD,KAAKyB,UAAU,CAACI,QAAQ;gCAC/BC,QAAQ9B,KAAKyB,UAAU,CAACM,QAAQ;4BAClC;4BACA,MAAMJ;wBACR;oBACF;gBACF;gBAEA,IAAIP,iBAAiBC,eAAe;oBAClC,MAAMM,IAAI;wBACRC,aACE;wBACF3B,OAAOD,KAAKyB,UAAU,CAACI,QAAQ;wBAC/BC,QAAQ9B,KAAKyB,UAAU,CAACM,QAAQ;oBAClC;oBACA,MAAMJ;gBACR;YACF,OAAO;gBACLR,cAAc;YAChB;QACF;QAEA,OAAO;YAAEa,QAAQZ;YAAea,QAAQZ;QAAc;IACxD;IAEA,OAAO;QAAEW,QAAQ;QAAOC,QAAQ;IAAM;AACxC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/cache-life-profile.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/cache-life-profile.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b64123d2bbac70b009b60d5036a8210fd461478 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/cache-life-profile.d.ts @@ -0,0 +1,13 @@ +export type CacheLife = { + stale?: number; + revalidate?: number; + expire?: number; +}; +type CacheLifeProfileContext = { + kind: 'inline'; +} | { + kind: 'config'; + profileName: string; +}; +export declare function validateAndNormalizeCacheLifeProfile(profile: CacheLife, context: CacheLifeProfileContext): CacheLife; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/use-cache/cache-life-profile.js b/e-commerce/node_modules/next/dist/server/use-cache/cache-life-profile.js new file mode 100644 index 0000000000000000000000000000000000000000..3a13d30ac35e0822f5d00609108bb9bb7523fcb0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/cache-life-profile.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "validateAndNormalizeCacheLifeProfile", { + enumerable: true, + get: function() { + return validateAndNormalizeCacheLifeProfile; + } +}); +const _constants = require("../../lib/constants"); +function normalizeCacheLifeValue(key, value, context) { + if (value === undefined) { + return undefined; + } + if (value === false) { + if (key === 'stale') { + throw new Error('Pass `Infinity` instead of `false` if you want to cache on the client forever ' + 'without checking with the server.'); + } else if (key === 'revalidate') { + throw new Error('Pass `Infinity` instead of `false` if you do not want to revalidate by time.'); + } else { + throw new Error('Pass `Infinity` instead of `false` if you want to cache on the server forever ' + 'without checking with the origin.'); + } + } + if (typeof value !== 'number') { + throw new Error(`The ${key} option must be a number of seconds.`); + } + if (value === Infinity) { + // Infinity means "never", but turns into null when serialized as JSON + // (e.g. for build workers or cache handlers), unlike INFINITE_CACHE. + return _constants.INFINITE_CACHE; + } + if (!Number.isFinite(value)) { + throw new Error(context.kind === 'config' ? `Invalid "cacheLife.${context.profileName}.${key}" provided, expected a finite number of seconds or Infinity, received ${value}` : `Invalid \`cacheLife()\` option "${key}" provided, expected a finite number of seconds or Infinity, received ${value}.`); + } + return value; +} +function validateAndNormalizeCacheLifeProfile(profile, context) { + // Don't mutate the profile; it may be shared, e.g. as part of the user's + // config object. + const normalizedProfile = { + ...profile + }; + for (const key of [ + 'stale', + 'revalidate', + 'expire' + ]){ + const value = normalizeCacheLifeValue(key, profile[key], context); + if (value !== undefined) { + normalizedProfile[key] = value; + } + } + if (normalizedProfile.revalidate !== undefined && normalizedProfile.expire !== undefined && normalizedProfile.revalidate > normalizedProfile.expire) { + throw new Error('If providing both the revalidate and expire options, ' + 'the expire option must be greater than the revalidate option. ' + 'The expire option indicates how many seconds from the start ' + 'until it can no longer be used.'); + } + return normalizedProfile; +} + +//# sourceMappingURL=cache-life-profile.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/cache-life-profile.js.map b/e-commerce/node_modules/next/dist/server/use-cache/cache-life-profile.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bc121f9a3463e439dac10bb8b0b7c7b787f446c0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/cache-life-profile.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/cache-life-profile.ts"],"sourcesContent":["import { INFINITE_CACHE } from '../../lib/constants'\n\nexport type CacheLife = {\n // How long the client can cache a value without checking with the server.\n stale?: number\n // How frequently you want the cache to refresh on the server.\n // Stale values may be served while revalidating.\n revalidate?: number\n // In the worst case scenario, where you haven't had traffic in a while,\n // how stale can a value be until you prefer deopting to dynamic.\n // Must be longer than revalidate.\n expire?: number\n}\n\ntype CacheLifeProfileContext =\n | { kind: 'inline' }\n | { kind: 'config'; profileName: string }\n\nfunction normalizeCacheLifeValue(\n key: keyof CacheLife,\n value: unknown,\n context: CacheLifeProfileContext\n): number | undefined {\n if (value === undefined) {\n return undefined\n }\n\n if (value === false) {\n if (key === 'stale') {\n throw new Error(\n 'Pass `Infinity` instead of `false` if you want to cache on the client forever ' +\n 'without checking with the server.'\n )\n } else if (key === 'revalidate') {\n throw new Error(\n 'Pass `Infinity` instead of `false` if you do not want to revalidate by time.'\n )\n } else {\n throw new Error(\n 'Pass `Infinity` instead of `false` if you want to cache on the server forever ' +\n 'without checking with the origin.'\n )\n }\n }\n\n if (typeof value !== 'number') {\n throw new Error(`The ${key} option must be a number of seconds.`)\n }\n\n if (value === Infinity) {\n // Infinity means \"never\", but turns into null when serialized as JSON\n // (e.g. for build workers or cache handlers), unlike INFINITE_CACHE.\n return INFINITE_CACHE\n }\n\n if (!Number.isFinite(value)) {\n throw new Error(\n context.kind === 'config'\n ? `Invalid \"cacheLife.${context.profileName}.${key}\" provided, expected a finite number of seconds or Infinity, received ${value}`\n : `Invalid \\`cacheLife()\\` option \"${key}\" provided, expected a finite number of seconds or Infinity, received ${value}.`\n )\n }\n\n return value\n}\n\nexport function validateAndNormalizeCacheLifeProfile(\n profile: CacheLife,\n context: CacheLifeProfileContext\n): CacheLife {\n // Don't mutate the profile; it may be shared, e.g. as part of the user's\n // config object.\n const normalizedProfile = { ...profile }\n\n for (const key of ['stale', 'revalidate', 'expire'] as const) {\n const value = normalizeCacheLifeValue(key, profile[key], context)\n if (value !== undefined) {\n normalizedProfile[key] = value\n }\n }\n\n if (\n normalizedProfile.revalidate !== undefined &&\n normalizedProfile.expire !== undefined &&\n normalizedProfile.revalidate > normalizedProfile.expire\n ) {\n throw new Error(\n 'If providing both the revalidate and expire options, ' +\n 'the expire option must be greater than the revalidate option. ' +\n 'The expire option indicates how many seconds from the start ' +\n 'until it can no longer be used.'\n )\n }\n\n return normalizedProfile\n}\n"],"names":["validateAndNormalizeCacheLifeProfile","normalizeCacheLifeValue","key","value","context","undefined","Error","Infinity","INFINITE_CACHE","Number","isFinite","kind","profileName","profile","normalizedProfile","revalidate","expire"],"mappings":";;;;+BAkEgBA;;;eAAAA;;;2BAlEe;AAkB/B,SAASC,wBACPC,GAAoB,EACpBC,KAAc,EACdC,OAAgC;IAEhC,IAAID,UAAUE,WAAW;QACvB,OAAOA;IACT;IAEA,IAAIF,UAAU,OAAO;QACnB,IAAID,QAAQ,SAAS;YACnB,MAAM,IAAII,MACR,mFACE;QAEN,OAAO,IAAIJ,QAAQ,cAAc;YAC/B,MAAM,IAAII,MACR;QAEJ,OAAO;YACL,MAAM,IAAIA,MACR,mFACE;QAEN;IACF;IAEA,IAAI,OAAOH,UAAU,UAAU;QAC7B,MAAM,IAAIG,MAAM,CAAC,IAAI,EAAEJ,IAAI,oCAAoC,CAAC;IAClE;IAEA,IAAIC,UAAUI,UAAU;QACtB,sEAAsE;QACtE,qEAAqE;QACrE,OAAOC,yBAAc;IACvB;IAEA,IAAI,CAACC,OAAOC,QAAQ,CAACP,QAAQ;QAC3B,MAAM,IAAIG,MACRF,QAAQO,IAAI,KAAK,WACb,CAAC,mBAAmB,EAAEP,QAAQQ,WAAW,CAAC,CAAC,EAAEV,IAAI,sEAAsE,EAAEC,OAAO,GAChI,CAAC,gCAAgC,EAAED,IAAI,sEAAsE,EAAEC,MAAM,CAAC,CAAC;IAE/H;IAEA,OAAOA;AACT;AAEO,SAASH,qCACda,OAAkB,EAClBT,OAAgC;IAEhC,yEAAyE;IACzE,iBAAiB;IACjB,MAAMU,oBAAoB;QAAE,GAAGD,OAAO;IAAC;IAEvC,KAAK,MAAMX,OAAO;QAAC;QAAS;QAAc;KAAS,CAAW;QAC5D,MAAMC,QAAQF,wBAAwBC,KAAKW,OAAO,CAACX,IAAI,EAAEE;QACzD,IAAID,UAAUE,WAAW;YACvBS,iBAAiB,CAACZ,IAAI,GAAGC;QAC3B;IACF;IAEA,IACEW,kBAAkBC,UAAU,KAAKV,aACjCS,kBAAkBE,MAAM,KAAKX,aAC7BS,kBAAkBC,UAAU,GAAGD,kBAAkBE,MAAM,EACvD;QACA,MAAM,IAAIV,MACR,0DACE,mEACA,iEACA;IAEN;IAEA,OAAOQ;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/cache-life.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/cache-life.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7d32e9b012e1abb42b7e0afcfd49bd4143be938 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/cache-life.d.ts @@ -0,0 +1,4 @@ +import type { CacheLife } from './cache-life-profile'; +export type { CacheLife }; +type CacheLifeProfiles = 'default' | 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks' | 'max' | (string & {}); +export declare function cacheLife(profile: CacheLifeProfiles | CacheLife): void; diff --git a/e-commerce/node_modules/next/dist/server/use-cache/cache-life.js b/e-commerce/node_modules/next/dist/server/use-cache/cache-life.js new file mode 100644 index 0000000000000000000000000000000000000000..53c025c6c94b1830f8b3c92dbd9f9a591a172e1c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/cache-life.js @@ -0,0 +1,79 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "cacheLife", { + enumerable: true, + get: function() { + return cacheLife; + } +}); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _usecachemessages = require("./use-cache-messages"); +const _cachelifeprofile = require("./cache-life-profile"); +function cacheLife(profile) { + if (!process.env.__NEXT_USE_CACHE) { + throw new Error('`cacheLife()` is only available with the `cacheComponents` config.'); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + switch(workUnitStore == null ? void 0 : workUnitStore.type){ + case 'prerender': + case 'prerender-client': + case 'validation-client': + case 'prerender-runtime': + case 'prerender-legacy': + case 'request': + case 'unstable-cache': + case 'build-time-generator': + case undefined: + var _workAsyncStorage_getStore; + throw (0, _usecachemessages.createCacheLifeOutsideUseCacheError)((_workAsyncStorage_getStore = _workasyncstorageexternal.workAsyncStorage.getStore()) == null ? void 0 : _workAsyncStorage_getStore.route); + case 'cache': + case 'private-cache': + break; + default: + workUnitStore; + } + if (typeof profile === 'string') { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!workStore) { + throw new Error('`cacheLife()` can only be called during App Router rendering at the moment.'); + } + // TODO: This should be globally available and not require an AsyncLocalStorage. + const configuredProfile = workStore.cacheLifeProfiles[profile]; + if (configuredProfile === undefined) { + if (workStore.cacheLifeProfiles[profile.trim()]) { + throw new Error(`Unknown \`cacheLife()\` profile "${profile}" is not configured in next.config.js\n` + `Did you mean "${profile.trim()}" without the spaces?`); + } + throw new Error(`Unknown \`cacheLife()\` profile "${profile}" is not configured in next.config.js\n` + 'module.exports = {\n' + ' cacheLife: {\n' + ` "${profile}": ...\n` + ' }\n' + '}'); + } + profile = configuredProfile; + } else if (typeof profile !== 'object' || profile === null || Array.isArray(profile)) { + throw new Error('Invalid `cacheLife()` option. Either pass a profile name or object.'); + } else { + profile = (0, _cachelifeprofile.validateAndNormalizeCacheLifeProfile)(profile, { + kind: 'inline' + }); + } + if (profile.revalidate !== undefined) { + // Track the explicit revalidate time. + if (workUnitStore.explicitRevalidate === undefined || workUnitStore.explicitRevalidate > profile.revalidate) { + workUnitStore.explicitRevalidate = profile.revalidate; + } + } + if (profile.expire !== undefined) { + // Track the explicit expire time. + if (workUnitStore.explicitExpire === undefined || workUnitStore.explicitExpire > profile.expire) { + workUnitStore.explicitExpire = profile.expire; + } + } + if (profile.stale !== undefined) { + // Track the explicit stale time. + if (workUnitStore.explicitStale === undefined || workUnitStore.explicitStale > profile.stale) { + workUnitStore.explicitStale = profile.stale; + } + } +} + +//# sourceMappingURL=cache-life.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/cache-life.js.map b/e-commerce/node_modules/next/dist/server/use-cache/cache-life.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a71047a0f1d7186b1c942193338f9ff809911234 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/cache-life.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/cache-life.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createCacheLifeOutsideUseCacheError } from './use-cache-messages'\nimport { validateAndNormalizeCacheLifeProfile } from './cache-life-profile'\nimport type { CacheLife } from './cache-life-profile'\n\nexport type { CacheLife }\n\n// The equivalent header is kind of like:\n// Cache-Control: max-age=[stale],s-max-age=[revalidate],stale-while-revalidate=[expire-revalidate],stale-if-error=[expire-revalidate]\n// Except that stale-while-revalidate/stale-if-error only applies to shared caches - not private caches.\n\n// The default revalidates relatively frequently but doesn't expire to ensure it's always\n// able to serve fast results but by default doesn't hang.\n\n// This gets overridden by the next-types-plugin\ntype CacheLifeProfiles =\n | 'default'\n | 'seconds'\n | 'minutes'\n | 'hours'\n | 'days'\n | 'weeks'\n | 'max'\n | (string & {})\n\nexport function cacheLife(profile: CacheLifeProfiles | CacheLife): void {\n if (!process.env.__NEXT_USE_CACHE) {\n throw new Error(\n '`cacheLife()` is only available with the `cacheComponents` config.'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n case 'build-time-generator':\n case undefined:\n throw createCacheLifeOutsideUseCacheError(\n workAsyncStorage.getStore()?.route\n )\n case 'cache':\n case 'private-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n if (typeof profile === 'string') {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new Error(\n '`cacheLife()` can only be called during App Router rendering at the moment.'\n )\n }\n\n // TODO: This should be globally available and not require an AsyncLocalStorage.\n const configuredProfile = workStore.cacheLifeProfiles[profile]\n if (configuredProfile === undefined) {\n if (workStore.cacheLifeProfiles[profile.trim()]) {\n throw new Error(\n `Unknown \\`cacheLife()\\` profile \"${profile}\" is not configured in next.config.js\\n` +\n `Did you mean \"${profile.trim()}\" without the spaces?`\n )\n }\n throw new Error(\n `Unknown \\`cacheLife()\\` profile \"${profile}\" is not configured in next.config.js\\n` +\n 'module.exports = {\\n' +\n ' cacheLife: {\\n' +\n ` \"${profile}\": ...\\n` +\n ' }\\n' +\n '}'\n )\n }\n profile = configuredProfile\n } else if (\n typeof profile !== 'object' ||\n profile === null ||\n Array.isArray(profile)\n ) {\n throw new Error(\n 'Invalid `cacheLife()` option. Either pass a profile name or object.'\n )\n } else {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n\n if (profile.revalidate !== undefined) {\n // Track the explicit revalidate time.\n if (\n workUnitStore.explicitRevalidate === undefined ||\n workUnitStore.explicitRevalidate > profile.revalidate\n ) {\n workUnitStore.explicitRevalidate = profile.revalidate\n }\n }\n if (profile.expire !== undefined) {\n // Track the explicit expire time.\n if (\n workUnitStore.explicitExpire === undefined ||\n workUnitStore.explicitExpire > profile.expire\n ) {\n workUnitStore.explicitExpire = profile.expire\n }\n }\n if (profile.stale !== undefined) {\n // Track the explicit stale time.\n if (\n workUnitStore.explicitStale === undefined ||\n workUnitStore.explicitStale > profile.stale\n ) {\n workUnitStore.explicitStale = profile.stale\n }\n }\n}\n"],"names":["cacheLife","profile","process","env","__NEXT_USE_CACHE","Error","workUnitStore","workUnitAsyncStorage","getStore","type","undefined","workAsyncStorage","createCacheLifeOutsideUseCacheError","route","workStore","configuredProfile","cacheLifeProfiles","trim","Array","isArray","validateAndNormalizeCacheLifeProfile","kind","revalidate","explicitRevalidate","expire","explicitExpire","stale","explicitStale"],"mappings":";;;;+BA0BgBA;;;eAAAA;;;0CA1BiB;8CACI;kCACe;kCACC;AAuB9C,SAASA,UAAUC,OAAsC;IAC9D,IAAI,CAACC,QAAQC,GAAG,CAACC,gBAAgB,EAAE;QACjC,MAAM,IAAIC,MACR;IAEJ;IAEA,MAAMC,gBAAgBC,kDAAoB,CAACC,QAAQ;IAEnD,OAAQF,iCAAAA,cAAeG,IAAI;QACzB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKC;gBAEDC;YADF,MAAMC,IAAAA,qDAAmC,GACvCD,6BAAAA,0CAAgB,CAACH,QAAQ,uBAAzBG,2BAA6BE,KAAK;QAEtC,KAAK;QACL,KAAK;YACH;QACF;YACEP;IACJ;IAEA,IAAI,OAAOL,YAAY,UAAU;QAC/B,MAAMa,YAAYH,0CAAgB,CAACH,QAAQ;QAC3C,IAAI,CAACM,WAAW;YACd,MAAM,IAAIT,MACR;QAEJ;QAEA,gFAAgF;QAChF,MAAMU,oBAAoBD,UAAUE,iBAAiB,CAACf,QAAQ;QAC9D,IAAIc,sBAAsBL,WAAW;YACnC,IAAII,UAAUE,iBAAiB,CAACf,QAAQgB,IAAI,GAAG,EAAE;gBAC/C,MAAM,IAAIZ,MACR,CAAC,iCAAiC,EAAEJ,QAAQ,uCAAuC,CAAC,GAClF,CAAC,cAAc,EAAEA,QAAQgB,IAAI,GAAG,qBAAqB,CAAC;YAE5D;YACA,MAAM,IAAIZ,MACR,CAAC,iCAAiC,EAAEJ,QAAQ,uCAAuC,CAAC,GAClF,yBACA,qBACA,CAAC,KAAK,EAAEA,QAAQ,QAAQ,CAAC,GACzB,UACA;QAEN;QACAA,UAAUc;IACZ,OAAO,IACL,OAAOd,YAAY,YACnBA,YAAY,QACZiB,MAAMC,OAAO,CAAClB,UACd;QACA,MAAM,IAAII,MACR;IAEJ,OAAO;QACLJ,UAAUmB,IAAAA,sDAAoC,EAACnB,SAAS;YAAEoB,MAAM;QAAS;IAC3E;IAEA,IAAIpB,QAAQqB,UAAU,KAAKZ,WAAW;QACpC,sCAAsC;QACtC,IACEJ,cAAciB,kBAAkB,KAAKb,aACrCJ,cAAciB,kBAAkB,GAAGtB,QAAQqB,UAAU,EACrD;YACAhB,cAAciB,kBAAkB,GAAGtB,QAAQqB,UAAU;QACvD;IACF;IACA,IAAIrB,QAAQuB,MAAM,KAAKd,WAAW;QAChC,kCAAkC;QAClC,IACEJ,cAAcmB,cAAc,KAAKf,aACjCJ,cAAcmB,cAAc,GAAGxB,QAAQuB,MAAM,EAC7C;YACAlB,cAAcmB,cAAc,GAAGxB,QAAQuB,MAAM;QAC/C;IACF;IACA,IAAIvB,QAAQyB,KAAK,KAAKhB,WAAW;QAC/B,iCAAiC;QACjC,IACEJ,cAAcqB,aAAa,KAAKjB,aAChCJ,cAAcqB,aAAa,GAAG1B,QAAQyB,KAAK,EAC3C;YACApB,cAAcqB,aAAa,GAAG1B,QAAQyB,KAAK;QAC7C;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/cache-tag.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/cache-tag.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d0d286e490fc0767c3d48abc3d396b6b5c72826 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/cache-tag.d.ts @@ -0,0 +1 @@ +export declare function cacheTag(...tags: string[]): void; diff --git a/e-commerce/node_modules/next/dist/server/use-cache/cache-tag.js b/e-commerce/node_modules/next/dist/server/use-cache/cache-tag.js new file mode 100644 index 0000000000000000000000000000000000000000..c2308fc4854f4f47724d67fbe1c1ba01b2407dc3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/cache-tag.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "cacheTag", { + enumerable: true, + get: function() { + return cacheTag; + } +}); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _patchfetch = require("../lib/patch-fetch"); +const _usecachemessages = require("./use-cache-messages"); +function cacheTag(...tags) { + if (!process.env.__NEXT_USE_CACHE) { + throw new Error('`cacheTag()` is only available with the `cacheComponents` config.'); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + switch(workUnitStore == null ? void 0 : workUnitStore.type){ + case 'prerender': + case 'prerender-client': + case 'validation-client': + case 'prerender-runtime': + case 'prerender-legacy': + case 'request': + case 'unstable-cache': + case 'build-time-generator': + case undefined: + var _workAsyncStorage_getStore; + throw (0, _usecachemessages.createCacheTagOutsideUseCacheError)((_workAsyncStorage_getStore = _workasyncstorageexternal.workAsyncStorage.getStore()) == null ? void 0 : _workAsyncStorage_getStore.route); + case 'cache': + case 'private-cache': + break; + default: + workUnitStore; + } + const validTags = (0, _patchfetch.validateTags)(tags, '`cacheTag()`'); + if (!workUnitStore.tags) { + workUnitStore.tags = validTags; + } else { + workUnitStore.tags.push(...validTags); + } +} + +//# sourceMappingURL=cache-tag.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/cache-tag.js.map b/e-commerce/node_modules/next/dist/server/use-cache/cache-tag.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cf9ec7c43f6c6e2c29a0f94ea94ca48dff3c451f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/cache-tag.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/cache-tag.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { validateTags } from '../lib/patch-fetch'\nimport { createCacheTagOutsideUseCacheError } from './use-cache-messages'\n\nexport function cacheTag(...tags: string[]): void {\n if (!process.env.__NEXT_USE_CACHE) {\n throw new Error(\n '`cacheTag()` is only available with the `cacheComponents` config.'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n case 'build-time-generator':\n case undefined:\n throw createCacheTagOutsideUseCacheError(\n workAsyncStorage.getStore()?.route\n )\n case 'cache':\n case 'private-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n const validTags = validateTags(tags, '`cacheTag()`')\n\n if (!workUnitStore.tags) {\n workUnitStore.tags = validTags\n } else {\n workUnitStore.tags.push(...validTags)\n }\n}\n"],"names":["cacheTag","tags","process","env","__NEXT_USE_CACHE","Error","workUnitStore","workUnitAsyncStorage","getStore","type","undefined","workAsyncStorage","createCacheTagOutsideUseCacheError","route","validTags","validateTags","push"],"mappings":";;;;+BAKgBA;;;eAAAA;;;0CALiB;8CACI;4BACR;kCACsB;AAE5C,SAASA,SAAS,GAAGC,IAAc;IACxC,IAAI,CAACC,QAAQC,GAAG,CAACC,gBAAgB,EAAE;QACjC,MAAM,IAAIC,MACR;IAEJ;IAEA,MAAMC,gBAAgBC,kDAAoB,CAACC,QAAQ;IAEnD,OAAQF,iCAAAA,cAAeG,IAAI;QACzB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAKC;gBAEDC;YADF,MAAMC,IAAAA,oDAAkC,GACtCD,6BAAAA,0CAAgB,CAACH,QAAQ,uBAAzBG,2BAA6BE,KAAK;QAEtC,KAAK;QACL,KAAK;YACH;QACF;YACEP;IACJ;IAEA,MAAMQ,YAAYC,IAAAA,wBAAY,EAACd,MAAM;IAErC,IAAI,CAACK,cAAcL,IAAI,EAAE;QACvBK,cAAcL,IAAI,GAAGa;IACvB,OAAO;QACLR,cAAcL,IAAI,CAACe,IAAI,IAAIF;IAC7B;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/clone-cache-entry.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/clone-cache-entry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4ab4119066cfc290f82cd92d37b1f29118e9d2d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/clone-cache-entry.d.ts @@ -0,0 +1,7 @@ +import type { CacheEntry } from '../lib/cache-handlers/types'; +/** + * Tees a cache entry's single-use value stream into two independent entries. + * The original entry is mutated to hold one branch of the tee, and a clone is + * returned holding the other, so both can be consumed independently. + */ +export declare function cloneCacheEntry(entry: CacheEntry): [CacheEntry, CacheEntry]; diff --git a/e-commerce/node_modules/next/dist/server/use-cache/clone-cache-entry.js b/e-commerce/node_modules/next/dist/server/use-cache/clone-cache-entry.js new file mode 100644 index 0000000000000000000000000000000000000000..36095a7aec2e22b3d3ca3bce62a8d1370bae2118 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/clone-cache-entry.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "cloneCacheEntry", { + enumerable: true, + get: function() { + return cloneCacheEntry; + } +}); +function cloneCacheEntry(entry) { + const [streamA, streamB] = entry.value.tee(); + entry.value = streamA; + const clonedEntry = { + value: streamB, + timestamp: entry.timestamp, + revalidate: entry.revalidate, + expire: entry.expire, + stale: entry.stale, + tags: entry.tags + }; + return [ + entry, + clonedEntry + ]; +} + +//# sourceMappingURL=clone-cache-entry.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/clone-cache-entry.js.map b/e-commerce/node_modules/next/dist/server/use-cache/clone-cache-entry.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8512abfcdf62ec51625ce5d1ab74f8e551ffa459 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/clone-cache-entry.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/clone-cache-entry.ts"],"sourcesContent":["import type { CacheEntry } from '../lib/cache-handlers/types'\n\n/**\n * Tees a cache entry's single-use value stream into two independent entries.\n * The original entry is mutated to hold one branch of the tee, and a clone is\n * returned holding the other, so both can be consumed independently.\n */\nexport function cloneCacheEntry(entry: CacheEntry): [CacheEntry, CacheEntry] {\n const [streamA, streamB] = entry.value.tee()\n entry.value = streamA\n const clonedEntry: CacheEntry = {\n value: streamB,\n timestamp: entry.timestamp,\n revalidate: entry.revalidate,\n expire: entry.expire,\n stale: entry.stale,\n tags: entry.tags,\n }\n return [entry, clonedEntry]\n}\n"],"names":["cloneCacheEntry","entry","streamA","streamB","value","tee","clonedEntry","timestamp","revalidate","expire","stale","tags"],"mappings":";;;;+BAOgBA;;;eAAAA;;;AAAT,SAASA,gBAAgBC,KAAiB;IAC/C,MAAM,CAACC,SAASC,QAAQ,GAAGF,MAAMG,KAAK,CAACC,GAAG;IAC1CJ,MAAMG,KAAK,GAAGF;IACd,MAAMI,cAA0B;QAC9BF,OAAOD;QACPI,WAAWN,MAAMM,SAAS;QAC1BC,YAAYP,MAAMO,UAAU;QAC5BC,QAAQR,MAAMQ,MAAM;QACpBC,OAAOT,MAAMS,KAAK;QAClBC,MAAMV,MAAMU,IAAI;IAClB;IACA,OAAO;QAACV;QAAOK;KAAY;AAC7B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/constants.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a20e75c211c3e6a64bab4a3f282f686120e41e8f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/constants.d.ts @@ -0,0 +1,3 @@ +export declare const MIN_PRERENDERABLE_EXPIRE = 300; +export declare const MIN_PREFETCHABLE_STALE = 30; +export declare const MIN_SHELL_STALE = 300; diff --git a/e-commerce/node_modules/next/dist/server/use-cache/constants.js b/e-commerce/node_modules/next/dist/server/use-cache/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..9a99ffe321337c8f53a2a609de0e87ad16679adf --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/constants.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + MIN_PREFETCHABLE_STALE: null, + MIN_PRERENDERABLE_EXPIRE: null, + MIN_SHELL_STALE: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + MIN_PREFETCHABLE_STALE: function() { + return MIN_PREFETCHABLE_STALE; + }, + MIN_PRERENDERABLE_EXPIRE: function() { + return MIN_PRERENDERABLE_EXPIRE; + }, + MIN_SHELL_STALE: function() { + return MIN_SHELL_STALE; + } +}); +const _invarianterror = require("../../shared/lib/invariant-error"); +const MIN_PRERENDERABLE_EXPIRE = 300 // 5 minutes +; +const MIN_PREFETCHABLE_STALE = 30 // 30 seconds +; +const MIN_SHELL_STALE = 300 // 5 minutes +; +if (process.env.NODE_ENV !== 'production') { + if (MIN_PREFETCHABLE_STALE > MIN_SHELL_STALE) { + throw new _invarianterror.InvariantError('MIN_PREFETCHABLE_STALE must not exceed MIN_SHELL_STALE.'); + } +} + +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/constants.js.map b/e-commerce/node_modules/next/dist/server/use-cache/constants.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d392bc181a289535a9578f4749c29498e0308733 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/constants.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/constants.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\n\nexport const MIN_PRERENDERABLE_EXPIRE = 300 // 5 minutes\nexport const MIN_PREFETCHABLE_STALE = 30 // 30 seconds\nexport const MIN_SHELL_STALE = 300 // 5 minutes\n\nif (process.env.NODE_ENV !== 'production') {\n if (MIN_PREFETCHABLE_STALE > MIN_SHELL_STALE) {\n throw new InvariantError(\n 'MIN_PREFETCHABLE_STALE must not exceed MIN_SHELL_STALE.'\n )\n }\n}\n"],"names":["MIN_PREFETCHABLE_STALE","MIN_PRERENDERABLE_EXPIRE","MIN_SHELL_STALE","process","env","NODE_ENV","InvariantError"],"mappings":";;;;;;;;;;;;;;;;IAGaA,sBAAsB;eAAtBA;;IADAC,wBAAwB;eAAxBA;;IAEAC,eAAe;eAAfA;;;gCAJkB;AAExB,MAAMD,2BAA2B,IAAI,YAAY;;AACjD,MAAMD,yBAAyB,GAAG,aAAa;;AAC/C,MAAME,kBAAkB,IAAI,YAAY;;AAE/C,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzC,IAAIL,yBAAyBE,iBAAiB;QAC5C,MAAM,IAAII,8BAAc,CACtB;IAEJ;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/handlers.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/handlers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e32d231574ec5ca9d872e89a611402c95d84f6e0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/handlers.d.ts @@ -0,0 +1,80 @@ +import type { CacheHandler } from '../lib/cache-handlers/types'; +import { type CacheReadWriteHandler } from './tiered-cache-handler'; +/** + * Initialize the cache handlers. + * @param cacheMaxMemorySize - The maximum memory size of the cache in bytes, if + * not provided, the default memory size will be used. + */ +export declare function initializeCacheHandlers(cacheMaxMemorySize: number): void; +export declare function registerCustomCacheHandlers(register: () => Promise): Promise; +/** + * Get a cache handler by kind. + * @param kind - The kind of cache handler to get. + * @returns The cache handler, or `undefined` if it does not exist. + * @throws If the cache handlers are not initialized. + */ +export declare function getCacheHandler(kind: string): CacheHandler | undefined; +/** + * Get the dedicated in-memory cache handler that persists private caches in + * development. Returns `undefined` outside the dev server, where private caches + * must not be persisted. This is intentionally not part of the kind-keyed + * handlers map so that it can never be replaced by a user-configured handler. + */ +export declare function getPrivateCacheHandler(): CacheHandler | undefined; +/** + * Whether the in-memory cache is disabled (`cacheMaxMemorySize: 0`). Dev-only + * signal used to force a dynamic cache life so that the size-0 case still + * serves stale and regenerates in the background. Always `false` in production. + */ +export declare function isMemoryCacheDisabled(): boolean; +/** + * Whether `kind` is backed by a real user-configured handler rather than the + * built-in in-memory default. Such a handler may be slow or remote, so in + * development a built-in front handler is placed in front of it (see + * `getDevTieredCacheHandler`) to keep cache hits microtask-fast. The presence + * of a dev front handler is the signal, since front handlers are created + * exactly for user-registered kinds. Always `false` in production. + */ +export declare function isCustomCacheHandler(kind: string): boolean; +/** + * Whether `kind` resolves to one of the in-memory handlers that + * `initializeCacheHandlers` constructs itself, rather than one supplied by the + * platform through the `@next/cache-handlers` global or by `cacheHandlers` + * config. Reads from a built-in handler are map lookups, so repeating one + * within a request costs nothing; reads from a supplied handler may be a + * network round trip. Unlike `isCustomCacheHandler`, this holds in production. + * + * Tracking the instances rather than the kinds is what keeps aliasing correct: + * self-hosted, `remote` resolves to the same handler as `default` and so + * reports as built-in, while a platform-supplied `remote` does not. + */ +export declare function isBuiltInCacheHandler(kind: string): boolean; +/** + * Get the dev-only tiered cache handler for a custom `kind`: a fast built-in + * in-memory front handler in front of the user-configured backing handler, so + * cache hits resolve in a microtask. Returns `undefined` if there is none (a + * built-in kind, or production). + */ +export declare function getDevTieredCacheHandler(kind: string): CacheReadWriteHandler | undefined; +/** + * Get the cache handlers. In dev, this also includes the built-in handlers (the + * private handler and the per-kind front handlers). The built-in handlers are + * not part of the registered set, but tag operations must still reach them: + * their `updateTags` writes the shared tags manifest that their `get` consults, + * so `revalidateTag` can invalidate their entries. + * @returns The cache handlers, or `undefined` if they are not initialized. + */ +export declare function getCacheHandlers(): CacheHandler[] | undefined; +/** + * Get a map iterator over the cache handlers (keyed by kind). + * @returns An iterator over the cache handler entries, or `undefined` if they + * are not initialized. + * @throws If the cache handlers are not initialized. + */ +export declare function getCacheHandlerEntries(): IterableIterator<[string, CacheHandler]> | undefined; +/** + * Set a cache handler by kind. + * @param kind - The kind of cache handler to set. + * @param cacheHandler - The cache handler to set. + */ +export declare function setCacheHandler(kind: string, cacheHandler: CacheHandler): void; diff --git a/e-commerce/node_modules/next/dist/server/use-cache/handlers.js b/e-commerce/node_modules/next/dist/server/use-cache/handlers.js new file mode 100644 index 0000000000000000000000000000000000000000..3a0164d849b4a652b6e9e7168552446091908202 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/handlers.js @@ -0,0 +1,265 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getCacheHandler: null, + getCacheHandlerEntries: null, + getCacheHandlers: null, + getDevTieredCacheHandler: null, + getPrivateCacheHandler: null, + initializeCacheHandlers: null, + isBuiltInCacheHandler: null, + isCustomCacheHandler: null, + isMemoryCacheDisabled: null, + registerCustomCacheHandlers: null, + setCacheHandler: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getCacheHandler: function() { + return getCacheHandler; + }, + getCacheHandlerEntries: function() { + return getCacheHandlerEntries; + }, + getCacheHandlers: function() { + return getCacheHandlers; + }, + getDevTieredCacheHandler: function() { + return getDevTieredCacheHandler; + }, + getPrivateCacheHandler: function() { + return getPrivateCacheHandler; + }, + initializeCacheHandlers: function() { + return initializeCacheHandlers; + }, + isBuiltInCacheHandler: function() { + return isBuiltInCacheHandler; + }, + isCustomCacheHandler: function() { + return isCustomCacheHandler; + }, + isMemoryCacheDisabled: function() { + return isMemoryCacheDisabled; + }, + registerCustomCacheHandlers: function() { + return registerCustomCacheHandlers; + }, + setCacheHandler: function() { + return setCacheHandler; + } +}); +const _default = require("../lib/cache-handlers/default"); +const _tieredcachehandler = require("./tiered-cache-handler"); +const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE ? (message, ...args)=>{ + console.log(`use-cache: ${message}`, ...args); +} : undefined; +const handlersSymbol = Symbol.for('@next/cache-handlers'); +const handlersMapSymbol = Symbol.for('@next/cache-handlers-map'); +const handlersSetSymbol = Symbol.for('@next/cache-handlers-set'); +const customCacheHandlersRegistrationSymbol = Symbol.for('@next/custom-cache-handlers-registration'); +const privateHandlerSymbol = Symbol.for('@next/cache-handlers-private'); +const builtInHandlersSymbol = Symbol.for('@next/cache-handlers-built-in'); +const devFrontHandlersSymbol = Symbol.for('@next/cache-handlers-dev-fronts'); +const devTieredHandlersSymbol = Symbol.for('@next/cache-handlers-dev-tiered'); +const memoryCacheDisabledSymbol = Symbol.for('@next/cache-handlers-memory-disabled'); +/** + * The in-memory size used for the dev-only built-in handlers (the private + * handler, the size-0 replacement, and the per-kind front handlers for custom + * kinds). Mirrors the framework default so `cacheMaxMemorySize: 0` does not + * disable caching in development. + */ const DEV_MEMORY_CACHE_SIZE = 50 * 1024 * 1024; +/** + * The reference to the cache handlers. We store the cache handlers on the + * global object so that we can access the same instance across different + * boundaries (such as different copies of the same module). + */ const reference = globalThis; +function initializeCacheHandlers(cacheMaxMemorySize) { + // If the cache handlers have already been initialized, don't do it again. + if (reference[handlersMapSymbol]) { + debug == null ? void 0 : debug('cache handlers already initialized'); + return; + } + debug == null ? void 0 : debug('initializing cache handlers'); + const handlersMap = new Map(); + reference[handlersMapSymbol] = handlersMap; + const builtInHandlers = new Set(); + reference[builtInHandlersSymbol] = builtInHandlers; + // In development, `cacheMaxMemorySize: 0` would make the built-in default + // handler a no-op, so every reload would miss. Use a real in-memory size + // instead so dev stays fast; the "use cache" wrapper forces a dynamic cache + // life for this case so it still behaves close to "no cache" (serve stale, + // regenerate in the background). Production keeps the no-op handler. + const builtInSize = process.env.__NEXT_DEV_SERVER && cacheMaxMemorySize === 0 ? DEV_MEMORY_CACHE_SIZE : cacheMaxMemorySize; + // Initialize the cache from the symbol contents first. + if (reference[handlersSymbol]) { + let fallback; + if (reference[handlersSymbol].DefaultCache) { + debug == null ? void 0 : debug('setting "default" cache handler from symbol'); + fallback = reference[handlersSymbol].DefaultCache; + } else { + debug == null ? void 0 : debug('setting "default" cache handler from default'); + fallback = (0, _default.createDefaultCacheHandler)(builtInSize); + builtInHandlers.add(fallback); + } + handlersMap.set('default', fallback); + if (reference[handlersSymbol].RemoteCache) { + debug == null ? void 0 : debug('setting "remote" cache handler from symbol'); + handlersMap.set('remote', reference[handlersSymbol].RemoteCache); + } else { + debug == null ? void 0 : debug('setting "remote" cache handler from default'); + handlersMap.set('remote', fallback); + } + } else { + const handler = (0, _default.createDefaultCacheHandler)(builtInSize); + builtInHandlers.add(handler); + debug == null ? void 0 : debug('setting "default" cache handler from default'); + handlersMap.set('default', handler); + debug == null ? void 0 : debug('setting "remote" cache handler from default'); + handlersMap.set('remote', handler); + } + // Create a set of the cache handlers. + reference[handlersSetSymbol] = new Set(handlersMap.values()); + // In development we add dedicated built-in in-memory handlers so that reloads + // are fast. These are always built-in handlers, never a user-configured one, + // and are gated on the dev server so production behaves exactly as + // configured. + if (process.env.__NEXT_DEV_SERVER) { + reference[memoryCacheDisabledSymbol] = cacheMaxMemorySize === 0; + // Private caches are persisted here so reloads are fast. Private entries + // can hold data specific to the incoming request (for example, derived from + // its cookies or headers), so this is never the user-configured `default` + // alias. Sized so it still caches under `cacheMaxMemorySize: 0` (otherwise + // it would become the no-op stub and private reloads would miss). + reference[privateHandlerSymbol] = (0, _default.createDefaultCacheHandler)(DEV_MEMORY_CACHE_SIZE); + // Built-in front handlers, one per custom kind, and the tiered handlers + // that place a front in front of a (possibly slow or remote) backing + // handler so cache hits resolve in a microtask, are both created per kind + // in `setCacheHandler`. + reference[devFrontHandlersSymbol] = new Map(); + reference[devTieredHandlersSymbol] = new Map(); + } +} +function registerCustomCacheHandlers(register) { + let pendingPromise = reference[customCacheHandlersRegistrationSymbol]; + if (!pendingPromise) { + pendingPromise = register(); + reference[customCacheHandlersRegistrationSymbol] = pendingPromise; + } + return pendingPromise; +} +function getCacheHandler(kind) { + // This should never be called before initializeCacheHandlers. + if (!reference[handlersMapSymbol]) { + throw new Error('Cache handlers not initialized'); + } + return reference[handlersMapSymbol].get(kind); +} +function getPrivateCacheHandler() { + // This should never be called before initializeCacheHandlers. + if (!reference[handlersMapSymbol]) { + throw new Error('Cache handlers not initialized'); + } + return reference[privateHandlerSymbol]; +} +function isMemoryCacheDisabled() { + return reference[memoryCacheDisabledSymbol] ?? false; +} +function isCustomCacheHandler(kind) { + var _reference_devFrontHandlersSymbol; + if (!process.env.__NEXT_DEV_SERVER) { + return false; + } + return ((_reference_devFrontHandlersSymbol = reference[devFrontHandlersSymbol]) == null ? void 0 : _reference_devFrontHandlersSymbol.has(kind)) ?? false; +} +function isBuiltInCacheHandler(kind) { + var _reference_handlersMapSymbol, _reference_builtInHandlersSymbol; + const handler = (_reference_handlersMapSymbol = reference[handlersMapSymbol]) == null ? void 0 : _reference_handlersMapSymbol.get(kind); + return handler !== undefined && Boolean((_reference_builtInHandlersSymbol = reference[builtInHandlersSymbol]) == null ? void 0 : _reference_builtInHandlersSymbol.has(handler)); +} +function getDevTieredCacheHandler(kind) { + var _reference_devTieredHandlersSymbol; + if (!process.env.__NEXT_DEV_SERVER) { + return undefined; + } + return (_reference_devTieredHandlersSymbol = reference[devTieredHandlersSymbol]) == null ? void 0 : _reference_devTieredHandlersSymbol.get(kind); +} +function getCacheHandlers() { + const handlersSet = reference[handlersSetSymbol]; + if (!handlersSet) { + return undefined; + } + const handlers = Array.from(handlersSet); + if (process.env.__NEXT_DEV_SERVER) { + const privateHandler = reference[privateHandlerSymbol]; + if (privateHandler) { + handlers.push(privateHandler); + } + const devFrontHandlers = reference[devFrontHandlersSymbol]; + if (devFrontHandlers) { + handlers.push(...devFrontHandlers.values()); + } + } + return handlers; +} +function getCacheHandlerEntries() { + const handlersMap = reference[handlersMapSymbol]; + if (!handlersMap) { + return undefined; + } + if (process.env.__NEXT_DEV_SERVER) { + return iterateCacheHandlerEntriesWithDevBuiltIns(handlersMap); + } + return handlersMap.entries(); +} +/** + * Yields the registered entries plus the dev-only private handler under its + * kind, so that per-kind tag operations (`refreshTags` / `getExpiration` for + * implicit tags) apply to private entries. Custom-kind front handlers are + * intentionally omitted: the backing handler (already in the map) is + * authoritative for that kind's `getExpiration`, and a front entry is discarded + * via that same value. + */ function* iterateCacheHandlerEntriesWithDevBuiltIns(handlersMap) { + yield* handlersMap.entries(); + const privateHandler = reference[privateHandlerSymbol]; + if (privateHandler) { + const privateEntry = [ + 'private', + privateHandler + ]; + yield privateEntry; + } +} +function setCacheHandler(kind, cacheHandler) { + // This should never be called before initializeCacheHandlers. + if (!reference[handlersMapSymbol] || !reference[handlersSetSymbol]) { + throw new Error('Cache handlers not initialized'); + } + debug == null ? void 0 : debug('setting cache handler for "%s"', kind); + reference[handlersMapSymbol].set(kind, cacheHandler); + reference[handlersSetSymbol].add(cacheHandler); + // A user-configured handler may be slow or remote. In development, give it a + // dedicated built-in in-memory front handler so cache hits resolve in a + // microtask, and pair the two into a tiered handler the wrapper reads + // through. Both are created alongside registration so their lifecycle matches + // the backing handler's, and the front handler's presence is the signal that + // this kind is backed by a real handler (see `isCustomCacheHandler`). Being a + // built-in default handler, the front inherits the dev minimum retention, so + // a short-`expire` value still hits the front instead of falling through to + // the slow backing on every read. + if (process.env.__NEXT_DEV_SERVER) { + var _reference_devFrontHandlersSymbol, _reference_devTieredHandlersSymbol; + const frontHandler = (0, _default.createDefaultCacheHandler)(DEV_MEMORY_CACHE_SIZE); + (_reference_devFrontHandlersSymbol = reference[devFrontHandlersSymbol]) == null ? void 0 : _reference_devFrontHandlersSymbol.set(kind, frontHandler); + (_reference_devTieredHandlersSymbol = reference[devTieredHandlersSymbol]) == null ? void 0 : _reference_devTieredHandlersSymbol.set(kind, (0, _tieredcachehandler.createTieredCacheHandler)(frontHandler, cacheHandler)); + } +} + +//# sourceMappingURL=handlers.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/handlers.js.map b/e-commerce/node_modules/next/dist/server/use-cache/handlers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6348c4a6b1a6e06bde7a091f3b9fe0cfa661645e --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/handlers.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/handlers.ts"],"sourcesContent":["import { createDefaultCacheHandler } from '../lib/cache-handlers/default'\nimport type { CacheHandler } from '../lib/cache-handlers/types'\nimport {\n createTieredCacheHandler,\n type CacheReadWriteHandler,\n} from './tiered-cache-handler'\n\nconst debug = process.env.NEXT_PRIVATE_DEBUG_CACHE\n ? (message: string, ...args: any[]) => {\n console.log(`use-cache: ${message}`, ...args)\n }\n : undefined\n\nconst handlersSymbol = Symbol.for('@next/cache-handlers')\nconst handlersMapSymbol = Symbol.for('@next/cache-handlers-map')\nconst handlersSetSymbol = Symbol.for('@next/cache-handlers-set')\nconst customCacheHandlersRegistrationSymbol = Symbol.for(\n '@next/custom-cache-handlers-registration'\n)\nconst privateHandlerSymbol = Symbol.for('@next/cache-handlers-private')\nconst builtInHandlersSymbol = Symbol.for('@next/cache-handlers-built-in')\nconst devFrontHandlersSymbol = Symbol.for('@next/cache-handlers-dev-fronts')\nconst devTieredHandlersSymbol = Symbol.for('@next/cache-handlers-dev-tiered')\nconst memoryCacheDisabledSymbol = Symbol.for(\n '@next/cache-handlers-memory-disabled'\n)\n\n/**\n * The in-memory size used for the dev-only built-in handlers (the private\n * handler, the size-0 replacement, and the per-kind front handlers for custom\n * kinds). Mirrors the framework default so `cacheMaxMemorySize: 0` does not\n * disable caching in development.\n */\nconst DEV_MEMORY_CACHE_SIZE = 50 * 1024 * 1024\n\n/**\n * The reference to the cache handlers. We store the cache handlers on the\n * global object so that we can access the same instance across different\n * boundaries (such as different copies of the same module).\n */\nconst reference: typeof globalThis & {\n [handlersSymbol]?: {\n RemoteCache?: CacheHandler\n DefaultCache?: CacheHandler\n }\n [handlersMapSymbol]?: Map\n [handlersSetSymbol]?: Set\n [customCacheHandlersRegistrationSymbol]?: Promise\n [builtInHandlersSymbol]?: Set\n // DEV-only\n [privateHandlerSymbol]?: CacheHandler\n [devFrontHandlersSymbol]?: Map\n [devTieredHandlersSymbol]?: Map\n [memoryCacheDisabledSymbol]?: boolean\n} = globalThis\n\n/**\n * Initialize the cache handlers.\n * @param cacheMaxMemorySize - The maximum memory size of the cache in bytes, if\n * not provided, the default memory size will be used.\n */\nexport function initializeCacheHandlers(cacheMaxMemorySize: number): void {\n // If the cache handlers have already been initialized, don't do it again.\n if (reference[handlersMapSymbol]) {\n debug?.('cache handlers already initialized')\n return\n }\n\n debug?.('initializing cache handlers')\n const handlersMap = new Map()\n reference[handlersMapSymbol] = handlersMap\n const builtInHandlers = new Set()\n reference[builtInHandlersSymbol] = builtInHandlers\n\n // In development, `cacheMaxMemorySize: 0` would make the built-in default\n // handler a no-op, so every reload would miss. Use a real in-memory size\n // instead so dev stays fast; the \"use cache\" wrapper forces a dynamic cache\n // life for this case so it still behaves close to \"no cache\" (serve stale,\n // regenerate in the background). Production keeps the no-op handler.\n const builtInSize =\n process.env.__NEXT_DEV_SERVER && cacheMaxMemorySize === 0\n ? DEV_MEMORY_CACHE_SIZE\n : cacheMaxMemorySize\n\n // Initialize the cache from the symbol contents first.\n if (reference[handlersSymbol]) {\n let fallback: CacheHandler\n if (reference[handlersSymbol].DefaultCache) {\n debug?.('setting \"default\" cache handler from symbol')\n fallback = reference[handlersSymbol].DefaultCache\n } else {\n debug?.('setting \"default\" cache handler from default')\n fallback = createDefaultCacheHandler(builtInSize)\n builtInHandlers.add(fallback)\n }\n\n handlersMap.set('default', fallback)\n\n if (reference[handlersSymbol].RemoteCache) {\n debug?.('setting \"remote\" cache handler from symbol')\n handlersMap.set('remote', reference[handlersSymbol].RemoteCache)\n } else {\n debug?.('setting \"remote\" cache handler from default')\n handlersMap.set('remote', fallback)\n }\n } else {\n const handler = createDefaultCacheHandler(builtInSize)\n builtInHandlers.add(handler)\n\n debug?.('setting \"default\" cache handler from default')\n handlersMap.set('default', handler)\n debug?.('setting \"remote\" cache handler from default')\n handlersMap.set('remote', handler)\n }\n\n // Create a set of the cache handlers.\n reference[handlersSetSymbol] = new Set(handlersMap.values())\n\n // In development we add dedicated built-in in-memory handlers so that reloads\n // are fast. These are always built-in handlers, never a user-configured one,\n // and are gated on the dev server so production behaves exactly as\n // configured.\n if (process.env.__NEXT_DEV_SERVER) {\n reference[memoryCacheDisabledSymbol] = cacheMaxMemorySize === 0\n\n // Private caches are persisted here so reloads are fast. Private entries\n // can hold data specific to the incoming request (for example, derived from\n // its cookies or headers), so this is never the user-configured `default`\n // alias. Sized so it still caches under `cacheMaxMemorySize: 0` (otherwise\n // it would become the no-op stub and private reloads would miss).\n reference[privateHandlerSymbol] = createDefaultCacheHandler(\n DEV_MEMORY_CACHE_SIZE\n )\n\n // Built-in front handlers, one per custom kind, and the tiered handlers\n // that place a front in front of a (possibly slow or remote) backing\n // handler so cache hits resolve in a microtask, are both created per kind\n // in `setCacheHandler`.\n reference[devFrontHandlersSymbol] = new Map()\n reference[devTieredHandlersSymbol] = new Map()\n }\n}\n\nexport function registerCustomCacheHandlers(\n register: () => Promise\n): Promise {\n let pendingPromise = reference[customCacheHandlersRegistrationSymbol]\n if (!pendingPromise) {\n pendingPromise = register()\n reference[customCacheHandlersRegistrationSymbol] = pendingPromise\n }\n\n return pendingPromise\n}\n\n/**\n * Get a cache handler by kind.\n * @param kind - The kind of cache handler to get.\n * @returns The cache handler, or `undefined` if it does not exist.\n * @throws If the cache handlers are not initialized.\n */\nexport function getCacheHandler(kind: string): CacheHandler | undefined {\n // This should never be called before initializeCacheHandlers.\n if (!reference[handlersMapSymbol]) {\n throw new Error('Cache handlers not initialized')\n }\n\n return reference[handlersMapSymbol].get(kind)\n}\n\n/**\n * Get the dedicated in-memory cache handler that persists private caches in\n * development. Returns `undefined` outside the dev server, where private caches\n * must not be persisted. This is intentionally not part of the kind-keyed\n * handlers map so that it can never be replaced by a user-configured handler.\n */\nexport function getPrivateCacheHandler(): CacheHandler | undefined {\n // This should never be called before initializeCacheHandlers.\n if (!reference[handlersMapSymbol]) {\n throw new Error('Cache handlers not initialized')\n }\n\n return reference[privateHandlerSymbol]\n}\n\n/**\n * Whether the in-memory cache is disabled (`cacheMaxMemorySize: 0`). Dev-only\n * signal used to force a dynamic cache life so that the size-0 case still\n * serves stale and regenerates in the background. Always `false` in production.\n */\nexport function isMemoryCacheDisabled(): boolean {\n return reference[memoryCacheDisabledSymbol] ?? false\n}\n\n/**\n * Whether `kind` is backed by a real user-configured handler rather than the\n * built-in in-memory default. Such a handler may be slow or remote, so in\n * development a built-in front handler is placed in front of it (see\n * `getDevTieredCacheHandler`) to keep cache hits microtask-fast. The presence\n * of a dev front handler is the signal, since front handlers are created\n * exactly for user-registered kinds. Always `false` in production.\n */\nexport function isCustomCacheHandler(kind: string): boolean {\n if (!process.env.__NEXT_DEV_SERVER) {\n return false\n }\n\n return reference[devFrontHandlersSymbol]?.has(kind) ?? false\n}\n\n/**\n * Whether `kind` resolves to one of the in-memory handlers that\n * `initializeCacheHandlers` constructs itself, rather than one supplied by the\n * platform through the `@next/cache-handlers` global or by `cacheHandlers`\n * config. Reads from a built-in handler are map lookups, so repeating one\n * within a request costs nothing; reads from a supplied handler may be a\n * network round trip. Unlike `isCustomCacheHandler`, this holds in production.\n *\n * Tracking the instances rather than the kinds is what keeps aliasing correct:\n * self-hosted, `remote` resolves to the same handler as `default` and so\n * reports as built-in, while a platform-supplied `remote` does not.\n */\nexport function isBuiltInCacheHandler(kind: string): boolean {\n const handler = reference[handlersMapSymbol]?.get(kind)\n\n return (\n handler !== undefined &&\n Boolean(reference[builtInHandlersSymbol]?.has(handler))\n )\n}\n\n/**\n * Get the dev-only tiered cache handler for a custom `kind`: a fast built-in\n * in-memory front handler in front of the user-configured backing handler, so\n * cache hits resolve in a microtask. Returns `undefined` if there is none (a\n * built-in kind, or production).\n */\nexport function getDevTieredCacheHandler(\n kind: string\n): CacheReadWriteHandler | undefined {\n if (!process.env.__NEXT_DEV_SERVER) {\n return undefined\n }\n\n return reference[devTieredHandlersSymbol]?.get(kind)\n}\n\n/**\n * Get the cache handlers. In dev, this also includes the built-in handlers (the\n * private handler and the per-kind front handlers). The built-in handlers are\n * not part of the registered set, but tag operations must still reach them:\n * their `updateTags` writes the shared tags manifest that their `get` consults,\n * so `revalidateTag` can invalidate their entries.\n * @returns The cache handlers, or `undefined` if they are not initialized.\n */\nexport function getCacheHandlers(): CacheHandler[] | undefined {\n const handlersSet = reference[handlersSetSymbol]\n if (!handlersSet) {\n return undefined\n }\n\n const handlers = Array.from(handlersSet)\n\n if (process.env.__NEXT_DEV_SERVER) {\n const privateHandler = reference[privateHandlerSymbol]\n if (privateHandler) {\n handlers.push(privateHandler)\n }\n\n const devFrontHandlers = reference[devFrontHandlersSymbol]\n if (devFrontHandlers) {\n handlers.push(...devFrontHandlers.values())\n }\n }\n\n return handlers\n}\n\n/**\n * Get a map iterator over the cache handlers (keyed by kind).\n * @returns An iterator over the cache handler entries, or `undefined` if they\n * are not initialized.\n * @throws If the cache handlers are not initialized.\n */\nexport function getCacheHandlerEntries():\n | IterableIterator<[string, CacheHandler]>\n | undefined {\n const handlersMap = reference[handlersMapSymbol]\n if (!handlersMap) {\n return undefined\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n return iterateCacheHandlerEntriesWithDevBuiltIns(handlersMap)\n }\n\n return handlersMap.entries()\n}\n\n/**\n * Yields the registered entries plus the dev-only private handler under its\n * kind, so that per-kind tag operations (`refreshTags` / `getExpiration` for\n * implicit tags) apply to private entries. Custom-kind front handlers are\n * intentionally omitted: the backing handler (already in the map) is\n * authoritative for that kind's `getExpiration`, and a front entry is discarded\n * via that same value.\n */\nfunction* iterateCacheHandlerEntriesWithDevBuiltIns(\n handlersMap: Map\n): IterableIterator<[string, CacheHandler]> {\n yield* handlersMap.entries()\n\n const privateHandler = reference[privateHandlerSymbol]\n if (privateHandler) {\n const privateEntry: [string, CacheHandler] = ['private', privateHandler]\n yield privateEntry\n }\n}\n\n/**\n * Set a cache handler by kind.\n * @param kind - The kind of cache handler to set.\n * @param cacheHandler - The cache handler to set.\n */\nexport function setCacheHandler(\n kind: string,\n cacheHandler: CacheHandler\n): void {\n // This should never be called before initializeCacheHandlers.\n if (!reference[handlersMapSymbol] || !reference[handlersSetSymbol]) {\n throw new Error('Cache handlers not initialized')\n }\n\n debug?.('setting cache handler for \"%s\"', kind)\n reference[handlersMapSymbol].set(kind, cacheHandler)\n reference[handlersSetSymbol].add(cacheHandler)\n\n // A user-configured handler may be slow or remote. In development, give it a\n // dedicated built-in in-memory front handler so cache hits resolve in a\n // microtask, and pair the two into a tiered handler the wrapper reads\n // through. Both are created alongside registration so their lifecycle matches\n // the backing handler's, and the front handler's presence is the signal that\n // this kind is backed by a real handler (see `isCustomCacheHandler`). Being a\n // built-in default handler, the front inherits the dev minimum retention, so\n // a short-`expire` value still hits the front instead of falling through to\n // the slow backing on every read.\n if (process.env.__NEXT_DEV_SERVER) {\n const frontHandler = createDefaultCacheHandler(DEV_MEMORY_CACHE_SIZE)\n reference[devFrontHandlersSymbol]?.set(kind, frontHandler)\n reference[devTieredHandlersSymbol]?.set(\n kind,\n createTieredCacheHandler(frontHandler, cacheHandler)\n )\n }\n}\n"],"names":["getCacheHandler","getCacheHandlerEntries","getCacheHandlers","getDevTieredCacheHandler","getPrivateCacheHandler","initializeCacheHandlers","isBuiltInCacheHandler","isCustomCacheHandler","isMemoryCacheDisabled","registerCustomCacheHandlers","setCacheHandler","debug","process","env","NEXT_PRIVATE_DEBUG_CACHE","message","args","console","log","undefined","handlersSymbol","Symbol","for","handlersMapSymbol","handlersSetSymbol","customCacheHandlersRegistrationSymbol","privateHandlerSymbol","builtInHandlersSymbol","devFrontHandlersSymbol","devTieredHandlersSymbol","memoryCacheDisabledSymbol","DEV_MEMORY_CACHE_SIZE","reference","globalThis","cacheMaxMemorySize","handlersMap","Map","builtInHandlers","Set","builtInSize","__NEXT_DEV_SERVER","fallback","DefaultCache","createDefaultCacheHandler","add","set","RemoteCache","handler","values","register","pendingPromise","kind","Error","get","has","Boolean","handlersSet","handlers","Array","from","privateHandler","push","devFrontHandlers","iterateCacheHandlerEntriesWithDevBuiltIns","entries","privateEntry","cacheHandler","frontHandler","createTieredCacheHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;IAiKgBA,eAAe;eAAfA;;IA2HAC,sBAAsB;eAAtBA;;IA7BAC,gBAAgB;eAAhBA;;IAlBAC,wBAAwB;eAAxBA;;IA7DAC,sBAAsB;eAAtBA;;IAnHAC,uBAAuB;eAAvBA;;IAiKAC,qBAAqB;eAArBA;;IApBAC,oBAAoB;eAApBA;;IAZAC,qBAAqB;eAArBA;;IA/CAC,2BAA2B;eAA3BA;;IAqLAC,eAAe;eAAfA;;;yBApU0B;oCAKnC;AAEP,MAAMC,QAAQC,QAAQC,GAAG,CAACC,wBAAwB,GAC9C,CAACC,SAAiB,GAAGC;IACnBC,QAAQC,GAAG,CAAC,CAAC,WAAW,EAAEH,SAAS,KAAKC;AAC1C,IACAG;AAEJ,MAAMC,iBAAiBC,OAAOC,GAAG,CAAC;AAClC,MAAMC,oBAAoBF,OAAOC,GAAG,CAAC;AACrC,MAAME,oBAAoBH,OAAOC,GAAG,CAAC;AACrC,MAAMG,wCAAwCJ,OAAOC,GAAG,CACtD;AAEF,MAAMI,uBAAuBL,OAAOC,GAAG,CAAC;AACxC,MAAMK,wBAAwBN,OAAOC,GAAG,CAAC;AACzC,MAAMM,yBAAyBP,OAAOC,GAAG,CAAC;AAC1C,MAAMO,0BAA0BR,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,OAAOA,YAAY6B,OAAO;AAC5B;AAEA;;;;;;;CAOC,GACD,UAAUD,0CACR5B,WAAsC;IAEtC,OAAOA,YAAY6B,OAAO;IAE1B,MAAMJ,iBAAiB5B,SAAS,CAACN,qBAAqB;IACtD,IAAIkC,gBAAgB;QAClB,MAAMK,eAAuC;YAAC;YAAWL;SAAe;QACxE,MAAMK;IACR;AACF;AAOO,SAASvD,gBACdyC,IAAY,EACZe,YAA0B;IAE1B,8DAA8D;IAC9D,IAAI,CAAClC,SAAS,CAACT,kBAAkB,IAAI,CAACS,SAAS,CAACR,kBAAkB,EAAE;QAClE,MAAM,IAAI4B,MAAM;IAClB;IAEAzC,yBAAAA,MAAQ,kCAAkCwC;IAC1CnB,SAAS,CAACT,kBAAkB,CAACsB,GAAG,CAACM,MAAMe;IACvClC,SAAS,CAACR,kBAAkB,CAACoB,GAAG,CAACsB;IAEjC,6EAA6E;IAC7E,wEAAwE;IACxE,sEAAsE;IACtE,8EAA8E;IAC9E,6EAA6E;IAC7E,8EAA8E;IAC9E,6EAA6E;IAC7E,4EAA4E;IAC5E,kCAAkC;IAClC,IAAItD,QAAQC,GAAG,CAAC2B,iBAAiB,EAAE;YAEjCR,mCACAA;QAFA,MAAMmC,eAAexB,IAAAA,kCAAyB,EAACZ;SAC/CC,oCAAAA,SAAS,CAACJ,uBAAuB,qBAAjCI,kCAAmCa,GAAG,CAACM,MAAMgB;SAC7CnC,qCAAAA,SAAS,CAACH,wBAAwB,qBAAlCG,mCAAoCa,GAAG,CACrCM,MACAiB,IAAAA,4CAAwB,EAACD,cAAcD;IAE3C;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/tiered-cache-handler.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/tiered-cache-handler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a8e4cf2ccd9c1e7f45bb290f85e595a5de94017 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/tiered-cache-handler.d.ts @@ -0,0 +1,25 @@ +import type { CacheHandler } from '../lib/cache-handlers/types'; +/** + * The subset of the cache-handler interface used on the per-invocation + * read/write path in the "use cache" wrapper. Tag operations are intentionally + * excluded: they are applied to the front and backing handlers individually by + * the registry accessors (`getCacheHandlers` / `getCacheHandlerEntries`), never + * through this composite, so the composite is never registered. + */ +export type CacheReadWriteHandler = Pick; +/** + * Development-only. Puts a fast built-in in-memory `front` handler in front of + * a slower or persistent user-configured `backing` handler. Its only job is to + * guarantee that cache hits resolve in a microtask (so they aren't counted as + * cache misses at a staged-render boundary, which would otherwise surface a + * cold cache indicator), while keeping the front in sync with the backing. + * + * It implements only `get` and `set` because that is all the wrapper calls on + * its handler. Regeneration is never done here; this only reads, mirrors, and + * writes through. + * + * The handler is a per-kind singleton (the front and backing are both shared), + * so its in-flight map can serialize background front syncs for a key across + * concurrent reads, running them one at a time instead of in parallel. + */ +export declare function createTieredCacheHandler(front: CacheHandler, backing: CacheHandler): CacheReadWriteHandler; diff --git a/e-commerce/node_modules/next/dist/server/use-cache/tiered-cache-handler.js b/e-commerce/node_modules/next/dist/server/use-cache/tiered-cache-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..efb457ef8ff959824ec1e18ddc129e6db4637d7a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/tiered-cache-handler.js @@ -0,0 +1,147 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "createTieredCacheHandler", { + enumerable: true, + get: function() { + return createTieredCacheHandler; + } +}); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _clonecacheentry = require("./clone-cache-entry"); +function createTieredCacheHandler(front, backing) { + // Holds the in-flight (or chained) background sync per key, so a sync for a + // key runs after any earlier one for that key rather than in parallel. + const inFlightSyncs = new Map(); + function scheduleBackgroundSync(cacheKey, sync) { + // Serialize syncs per key: chain this one after any in-flight sync rather + // than running a second in parallel. The trailing sync still re-reads the + // backing, so the front converges to the latest state; a later read is + // never dropped in favor of an earlier, possibly stale, in-flight read. + const previous = inFlightSyncs.get(cacheKey); + let pending; + if (previous) { + pending = previous.then(sync); + } else { + pending = sync(); + } + pending = pending.finally(()=>{ + if (inFlightSyncs.get(cacheKey) === pending) { + inFlightSyncs.delete(cacheKey); + } + }); + inFlightSyncs.set(cacheKey, pending); + // Register the sync on the current request's revalidation writes so it is + // awaited rather than left untracked. Reading the work store here (rather + // than capturing it at construction) is what lets the handler be a shared + // singleton; `get` always runs within the request's async context, so the + // store is present. + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (workStore) { + workStore.pendingRevalidateWrites ??= []; + workStore.pendingRevalidateWrites.push(pending); + } + } + return { + async get (cacheKey, softTags) { + const frontEntry = await front.get(cacheKey, softTags); + if (frontEntry) { + // Cache hit: serve immediately (in a microtask). A background reconcile + // keeps the front in sync with the backing for the next read; + // reconciles for the same key are serialized, so concurrent cache hits + // don't hit the backing in parallel. + scheduleBackgroundSync(cacheKey, ()=>reconcileFrontFromBacking(front, backing, cacheKey, softTags, frontEntry)); + return frontEntry; + } + // Cold or evicted front entry: we pay the backing latency here (this is a + // read that may legitimately surface a cold cache indicator). A miss + // returns undefined and the "use cache" wrapper generates the entry and + // writes it through both tiers via `set`. + const backingEntry = await backing.get(cacheKey, softTags); + if (!backingEntry) { + return undefined; + } + // Mirror this freshly read backing entry into the front so the next read + // hits it. The mirror is serialized per key: if a sync is already + // running, this chains after it, so the front converges to this read even + // if the backing changed since that sync started. + const [servedEntry, mirroredEntry] = (0, _clonecacheentry.cloneCacheEntry)(backingEntry); + scheduleBackgroundSync(cacheKey, ()=>mirrorIntoFront(front, cacheKey, mirroredEntry)); + return servedEntry; + }, + async set (cacheKey, pendingEntry) { + // Write through to both tiers. The entry's value stream is single-use, so + // tee it into one entry per tier. + const entry = await pendingEntry; + const [frontEntry, backingEntry] = (0, _clonecacheentry.cloneCacheEntry)(entry); + await Promise.all([ + front.set(cacheKey, Promise.resolve(frontEntry)), + backing.set(cacheKey, Promise.resolve(backingEntry)) + ]); + } + }; +} +/** + * After serving a cache hit from the front, consult the backing and mirror a + * newer entry into the front for the next read. Runs in the background; + * failures are non-fatal. + */ async function reconcileFrontFromBacking(front, backing, cacheKey, softTags, frontEntry) { + try { + const backingEntry = await backing.get(cacheKey, softTags); + if (!backingEntry) { + // The backing no longer has this entry (it was purged out-of-band). The + // cache-handler interface has no per-key delete, so evict the front entry + // by overwriting it with an already-expired copy: the next read sees a + // front miss, falls through to the (also empty) backing, and the wrapper + // regenerates. The entry we just served was the last stale read. + await front.set(cacheKey, Promise.resolve(toExpiredEntry(frontEntry))); + return; + } + if (backingEntry.timestamp > frontEntry.timestamp) { + await front.set(cacheKey, Promise.resolve(backingEntry)); + } else { + // The front is already up to date, so the backing entry goes unused. This + // code releases its stream and does not await the result. The backing + // handler is user-configured, and it can return one branch of a teed + // stream. `cancel()` on such a branch settles only after the sibling + // branch is cancelled too, and the handler retains that sibling, so an + // await here would hang the reconcile. + void backingEntry.value.cancel(); + } + } catch { + // Background warming; failures are non-fatal. + } +} +/** + * Mirror a backing entry into the front. + */ async function mirrorIntoFront(front, cacheKey, entry) { + try { + await front.set(cacheKey, Promise.resolve(entry)); + } catch { + // Background warming; failures are non-fatal. + } +} +/** + * Build an already-expired copy of an entry, used to evict it from the front + * handler (which has no per-key delete) once the backing no longer has it. The + * default handler treats a negative `expire` as an eviction sentinel and + * reports the entry as missing on the next read. A negative `expire` is used + * rather than `0` because the dev front handler enforces a minimum retention, + * so a `0` `expire` would be kept alive by that minimum instead of evicted. The + * value is never read once the entry is evicted, but it must carry at least one + * byte because the built-in LRU cache refuses to store size-0 entries. + */ function toExpiredEntry(entry) { + return { + ...entry, + expire: -1, + value: new ReadableStream({ + start (controller) { + controller.enqueue(new Uint8Array(1)); + controller.close(); + } + }) + }; +} + +//# sourceMappingURL=tiered-cache-handler.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/tiered-cache-handler.js.map b/e-commerce/node_modules/next/dist/server/use-cache/tiered-cache-handler.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7b8494c9b01d284240dcb612f119dc1f93749fcf --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/tiered-cache-handler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/tiered-cache-handler.ts"],"sourcesContent":["import type { CacheEntry, CacheHandler } from '../lib/cache-handlers/types'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { cloneCacheEntry } from './clone-cache-entry'\n\n/**\n * The subset of the cache-handler interface used on the per-invocation\n * read/write path in the \"use cache\" wrapper. Tag operations are intentionally\n * excluded: they are applied to the front and backing handlers individually by\n * the registry accessors (`getCacheHandlers` / `getCacheHandlerEntries`), never\n * through this composite, so the composite is never registered.\n */\nexport type CacheReadWriteHandler = Pick\n\n/**\n * Development-only. Puts a fast built-in in-memory `front` handler in front of\n * a slower or persistent user-configured `backing` handler. Its only job is to\n * guarantee that cache hits resolve in a microtask (so they aren't counted as\n * cache misses at a staged-render boundary, which would otherwise surface a\n * cold cache indicator), while keeping the front in sync with the backing.\n *\n * It implements only `get` and `set` because that is all the wrapper calls on\n * its handler. Regeneration is never done here; this only reads, mirrors, and\n * writes through.\n *\n * The handler is a per-kind singleton (the front and backing are both shared),\n * so its in-flight map can serialize background front syncs for a key across\n * concurrent reads, running them one at a time instead of in parallel.\n */\nexport function createTieredCacheHandler(\n front: CacheHandler,\n backing: CacheHandler\n): CacheReadWriteHandler {\n // Holds the in-flight (or chained) background sync per key, so a sync for a\n // key runs after any earlier one for that key rather than in parallel.\n const inFlightSyncs = new Map>()\n\n function scheduleBackgroundSync(\n cacheKey: string,\n sync: () => Promise\n ): void {\n // Serialize syncs per key: chain this one after any in-flight sync rather\n // than running a second in parallel. The trailing sync still re-reads the\n // backing, so the front converges to the latest state; a later read is\n // never dropped in favor of an earlier, possibly stale, in-flight read.\n const previous = inFlightSyncs.get(cacheKey)\n\n let pending: Promise\n if (previous) {\n pending = previous.then(sync)\n } else {\n pending = sync()\n }\n\n pending = pending.finally(() => {\n if (inFlightSyncs.get(cacheKey) === pending) {\n inFlightSyncs.delete(cacheKey)\n }\n })\n\n inFlightSyncs.set(cacheKey, pending)\n\n // Register the sync on the current request's revalidation writes so it is\n // awaited rather than left untracked. Reading the work store here (rather\n // than capturing it at construction) is what lets the handler be a shared\n // singleton; `get` always runs within the request's async context, so the\n // store is present.\n const workStore = workAsyncStorage.getStore()\n if (workStore) {\n workStore.pendingRevalidateWrites ??= []\n workStore.pendingRevalidateWrites.push(pending)\n }\n }\n\n return {\n async get(cacheKey, softTags) {\n const frontEntry = await front.get(cacheKey, softTags)\n\n if (frontEntry) {\n // Cache hit: serve immediately (in a microtask). A background reconcile\n // keeps the front in sync with the backing for the next read;\n // reconciles for the same key are serialized, so concurrent cache hits\n // don't hit the backing in parallel.\n scheduleBackgroundSync(cacheKey, () =>\n reconcileFrontFromBacking(\n front,\n backing,\n cacheKey,\n softTags,\n frontEntry\n )\n )\n\n return frontEntry\n }\n\n // Cold or evicted front entry: we pay the backing latency here (this is a\n // read that may legitimately surface a cold cache indicator). A miss\n // returns undefined and the \"use cache\" wrapper generates the entry and\n // writes it through both tiers via `set`.\n const backingEntry = await backing.get(cacheKey, softTags)\n\n if (!backingEntry) {\n return undefined\n }\n\n // Mirror this freshly read backing entry into the front so the next read\n // hits it. The mirror is serialized per key: if a sync is already\n // running, this chains after it, so the front converges to this read even\n // if the backing changed since that sync started.\n const [servedEntry, mirroredEntry] = cloneCacheEntry(backingEntry)\n scheduleBackgroundSync(cacheKey, () =>\n mirrorIntoFront(front, cacheKey, mirroredEntry)\n )\n\n return servedEntry\n },\n\n async set(cacheKey, pendingEntry) {\n // Write through to both tiers. The entry's value stream is single-use, so\n // tee it into one entry per tier.\n const entry = await pendingEntry\n const [frontEntry, backingEntry] = cloneCacheEntry(entry)\n\n await Promise.all([\n front.set(cacheKey, Promise.resolve(frontEntry)),\n backing.set(cacheKey, Promise.resolve(backingEntry)),\n ])\n },\n }\n}\n\n/**\n * After serving a cache hit from the front, consult the backing and mirror a\n * newer entry into the front for the next read. Runs in the background;\n * failures are non-fatal.\n */\nasync function reconcileFrontFromBacking(\n front: CacheHandler,\n backing: CacheHandler,\n cacheKey: string,\n softTags: string[],\n frontEntry: CacheEntry\n): Promise {\n try {\n const backingEntry = await backing.get(cacheKey, softTags)\n\n if (!backingEntry) {\n // The backing no longer has this entry (it was purged out-of-band). The\n // cache-handler interface has no per-key delete, so evict the front entry\n // by overwriting it with an already-expired copy: the next read sees a\n // front miss, falls through to the (also empty) backing, and the wrapper\n // regenerates. The entry we just served was the last stale read.\n await front.set(cacheKey, Promise.resolve(toExpiredEntry(frontEntry)))\n\n return\n }\n\n if (backingEntry.timestamp > frontEntry.timestamp) {\n await front.set(cacheKey, Promise.resolve(backingEntry))\n } else {\n // The front is already up to date, so the backing entry goes unused. This\n // code releases its stream and does not await the result. The backing\n // handler is user-configured, and it can return one branch of a teed\n // stream. `cancel()` on such a branch settles only after the sibling\n // branch is cancelled too, and the handler retains that sibling, so an\n // await here would hang the reconcile.\n void backingEntry.value.cancel()\n }\n } catch {\n // Background warming; failures are non-fatal.\n }\n}\n\n/**\n * Mirror a backing entry into the front.\n */\nasync function mirrorIntoFront(\n front: CacheHandler,\n cacheKey: string,\n entry: CacheEntry\n): Promise {\n try {\n await front.set(cacheKey, Promise.resolve(entry))\n } catch {\n // Background warming; failures are non-fatal.\n }\n}\n\n/**\n * Build an already-expired copy of an entry, used to evict it from the front\n * handler (which has no per-key delete) once the backing no longer has it. The\n * default handler treats a negative `expire` as an eviction sentinel and\n * reports the entry as missing on the next read. A negative `expire` is used\n * rather than `0` because the dev front handler enforces a minimum retention,\n * so a `0` `expire` would be kept alive by that minimum instead of evicted. The\n * value is never read once the entry is evicted, but it must carry at least one\n * byte because the built-in LRU cache refuses to store size-0 entries.\n */\nfunction toExpiredEntry(entry: CacheEntry): CacheEntry {\n return {\n ...entry,\n expire: -1,\n value: new ReadableStream({\n start(controller) {\n controller.enqueue(new Uint8Array(1))\n controller.close()\n },\n }),\n }\n}\n"],"names":["createTieredCacheHandler","front","backing","inFlightSyncs","Map","scheduleBackgroundSync","cacheKey","sync","previous","get","pending","then","finally","delete","set","workStore","workAsyncStorage","getStore","pendingRevalidateWrites","push","softTags","frontEntry","reconcileFrontFromBacking","backingEntry","undefined","servedEntry","mirroredEntry","cloneCacheEntry","mirrorIntoFront","pendingEntry","entry","Promise","all","resolve","toExpiredEntry","timestamp","value","cancel","expire","ReadableStream","start","controller","enqueue","Uint8Array","close"],"mappings":";;;;+BA4BgBA;;;eAAAA;;;0CA3BiB;iCACD;AA0BzB,SAASA,yBACdC,KAAmB,EACnBC,OAAqB;IAErB,4EAA4E;IAC5E,uEAAuE;IACvE,MAAMC,gBAAgB,IAAIC;IAE1B,SAASC,uBACPC,QAAgB,EAChBC,IAAyB;QAEzB,0EAA0E;QAC1E,0EAA0E;QAC1E,uEAAuE;QACvE,wEAAwE;QACxE,MAAMC,WAAWL,cAAcM,GAAG,CAACH;QAEnC,IAAII;QACJ,IAAIF,UAAU;YACZE,UAAUF,SAASG,IAAI,CAACJ;QAC1B,OAAO;YACLG,UAAUH;QACZ;QAEAG,UAAUA,QAAQE,OAAO,CAAC;YACxB,IAAIT,cAAcM,GAAG,CAACH,cAAcI,SAAS;gBAC3CP,cAAcU,MAAM,CAACP;YACvB;QACF;QAEAH,cAAcW,GAAG,CAACR,UAAUI;QAE5B,0EAA0E;QAC1E,0EAA0E;QAC1E,0EAA0E;QAC1E,0EAA0E;QAC1E,oBAAoB;QACpB,MAAMK,YAAYC,0CAAgB,CAACC,QAAQ;QAC3C,IAAIF,WAAW;YACbA,UAAUG,uBAAuB,KAAK,EAAE;YACxCH,UAAUG,uBAAuB,CAACC,IAAI,CAACT;QACzC;IACF;IAEA,OAAO;QACL,MAAMD,KAAIH,QAAQ,EAAEc,QAAQ;YAC1B,MAAMC,aAAa,MAAMpB,MAAMQ,GAAG,CA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AS,GAAGd,WAAWc,SAAS,EAAE;YACjD,MAAMlC,MAAMa,GAAG,CAACR,UAAUyB,QAAQE,OAAO,CAACV;QAC5C,OAAO;YACL,0EAA0E;YAC1E,sEAAsE;YACtE,qEAAqE;YACrE,qEAAqE;YACrE,uEAAuE;YACvE,uCAAuC;YACvC,KAAKA,aAAaa,KAAK,CAACC,MAAM;QAChC;IACF,EAAE,OAAM;IACN,8CAA8C;IAChD;AACF;AAEA;;CAEC,GACD,eAAeT,gBACb3B,KAAmB,EACnBK,QAAgB,EAChBwB,KAAiB;IAEjB,IAAI;QACF,MAAM7B,MAAMa,GAAG,CAACR,UAAUyB,QAAQE,OAAO,CAACH;IAC5C,EAAE,OAAM;IACN,8CAA8C;IAChD;AACF;AAEA;;;;;;;;;CASC,GACD,SAASI,eAAeJ,KAAiB;IACvC,OAAO;QACL,GAAGA,KAAK;QACRQ,QAAQ,CAAC;QACTF,OAAO,IAAIG,eAAe;YACxBC,OAAMC,UAAU;gBACdA,WAAWC,OAAO,CAAC,IAAIC,WAAW;gBAClCF,WAAWG,KAAK;YAClB;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-errors.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f84be296f41b44b4e99136f9860d36c16bf63b3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-errors.d.ts @@ -0,0 +1,20 @@ +export declare class UseCacheTimeoutError extends Error { + constructor(route: string); +} +export declare class UseCacheDeadlockError extends Error { + constructor(route: string); +} +/** + * Used purely as `cause` for the nested-dynamic cache error: its captured stack + * points at the inner `"use cache"` invocation that propagated a dynamic cache + * life up to the outer cache. Constructed eagerly in `cache()` while the caller + * is still on the synchronous stack — see use-cache-wrapper.ts. + */ +export declare class NestedDynamicUseCacheError extends Error { + constructor(); +} +/** Exported separately because tests assert on it */ +export declare const UNEXPECTED_CACHE_MISS_MESSAGE = "Unexpected cache miss after cache warming phase during prerendering. This is likely caused by non-deterministic arguments that differ between the cache warming phase and the final prerender phase (e.g. unstable array order). Ensure that arguments passed to cached functions are deterministic."; +export declare class UnexpectedCacheMissError extends Error { + constructor(route: string); +} diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-errors.js b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-errors.js new file mode 100644 index 0000000000000000000000000000000000000000..949e5860b0bb4cbfeda64db5b6e448d9c313ff71 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-errors.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + NestedDynamicUseCacheError: null, + UNEXPECTED_CACHE_MISS_MESSAGE: null, + UnexpectedCacheMissError: null, + UseCacheDeadlockError: null, + UseCacheTimeoutError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + NestedDynamicUseCacheError: function() { + return NestedDynamicUseCacheError; + }, + UNEXPECTED_CACHE_MISS_MESSAGE: function() { + return UNEXPECTED_CACHE_MISS_MESSAGE; + }, + UnexpectedCacheMissError: function() { + return UnexpectedCacheMissError; + }, + UseCacheDeadlockError: function() { + return UseCacheDeadlockError; + }, + UseCacheTimeoutError: function() { + return UseCacheTimeoutError; + } +}); +class UseCacheTimeoutError extends Error { + constructor(route){ + super(`Route "${route}": ` + `A \`"use cache"\` function took too long during prerendering. The most common cause is passing unresolved request-specific arguments, such as \`params\` or \`searchParams\`, into the cached function. Resolve the data before calling the function and pass only the values you need.\nLearn more: https://nextjs.org/docs/messages/next-request-in-use-cache`); + } +} +class UseCacheDeadlockError extends Error { + constructor(route){ + super(`Route "${route}": ` + `A \`"use cache"\` function is awaiting a promise created outside it. The same call completed when run in isolation, so a module-scoped value (often a top-level \`Map\` used to dedupe fetches) is most likely blocking it. \`"use cache"\` already dedupes calls with the same arguments. Remove the surrounding dedupe layer.\nLearn more: https://nextjs.org/docs/messages/next-request-in-use-cache`); + } +} +class NestedDynamicUseCacheError extends Error { + constructor(){ + super('This "use cache" has a dynamic cache life that was propagated to its parent.'); + this.name = 'Nested dynamic "use cache"'; + } +} +const UNEXPECTED_CACHE_MISS_MESSAGE = `Unexpected cache miss after cache warming phase during prerendering. This is likely caused by non-deterministic arguments that differ between the cache warming phase and the final prerender phase (e.g. unstable array order). Ensure that arguments passed to cached functions are deterministic.`; +class UnexpectedCacheMissError extends Error { + constructor(route){ + super(`Route "${route}": ` + UNEXPECTED_CACHE_MISS_MESSAGE); + } +} + +//# sourceMappingURL=use-cache-errors.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-errors.js.map b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-errors.js.map new file mode 100644 index 0000000000000000000000000000000000000000..32bb7ceacefaf9975a22bbb3516d4213990d6fe0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-errors.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/use-cache-errors.ts"],"sourcesContent":["export class UseCacheTimeoutError extends Error {\n constructor(route: string) {\n super(\n `Route \"${route}\": ` +\n `A \\`\"use cache\"\\` function took too long during prerendering. The most common cause is passing unresolved request-specific arguments, such as \\`params\\` or \\`searchParams\\`, into the cached function. Resolve the data before calling the function and pass only the values you need.\\nLearn more: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n }\n}\n\nexport class UseCacheDeadlockError extends Error {\n constructor(route: string) {\n super(\n `Route \"${route}\": ` +\n `A \\`\"use cache\"\\` function is awaiting a promise created outside it. The same call completed when run in isolation, so a module-scoped value (often a top-level \\`Map\\` used to dedupe fetches) is most likely blocking it. \\`\"use cache\"\\` already dedupes calls with the same arguments. Remove the surrounding dedupe layer.\\nLearn more: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n }\n}\n\n/**\n * Used purely as `cause` for the nested-dynamic cache error: its captured stack\n * points at the inner `\"use cache\"` invocation that propagated a dynamic cache\n * life up to the outer cache. Constructed eagerly in `cache()` while the caller\n * is still on the synchronous stack — see use-cache-wrapper.ts.\n */\nexport class NestedDynamicUseCacheError extends Error {\n constructor() {\n super(\n 'This \"use cache\" has a dynamic cache life that was propagated to its parent.'\n )\n this.name = 'Nested dynamic \"use cache\"'\n }\n}\n\n/** Exported separately because tests assert on it */\nexport const UNEXPECTED_CACHE_MISS_MESSAGE = `Unexpected cache miss after cache warming phase during prerendering. This is likely caused by non-deterministic arguments that differ between the cache warming phase and the final prerender phase (e.g. unstable array order). Ensure that arguments passed to cached functions are deterministic.`\n\nexport class UnexpectedCacheMissError extends Error {\n constructor(route: string) {\n super(`Route \"${route}\": ` + UNEXPECTED_CACHE_MISS_MESSAGE)\n }\n}\n"],"names":["NestedDynamicUseCacheError","UNEXPECTED_CACHE_MISS_MESSAGE","UnexpectedCacheMissError","UseCacheDeadlockError","UseCacheTimeoutError","Error","constructor","route","name"],"mappings":";;;;;;;;;;;;;;;;;;IAwBaA,0BAA0B;eAA1BA;;IAUAC,6BAA6B;eAA7BA;;IAEAC,wBAAwB;eAAxBA;;IA3BAC,qBAAqB;eAArBA;;IATAC,oBAAoB;eAApBA;;;AAAN,MAAMA,6BAA6BC;IACxCC,YAAYC,KAAa,CAAE;QACzB,KAAK,CACH,CAAC,OAAO,EAAEA,MAAM,GAAG,CAAC,GAClB,CAAC,+VAA+V,CAAC;IAEvW;AACF;AAEO,MAAMJ,8BAA8BE;IACzCC,YAAYC,KAAa,CAAE;QACzB,KAAK,CACH,CAAC,OAAO,EAAEA,MAAM,GAAG,CAAC,GAClB,CAAC,uYAAuY,CAAC;IAE/Y;AACF;AAQO,MAAMP,mCAAmCK;IAC9CC,aAAc;QACZ,KAAK,CACH;QAEF,IAAI,CAACE,IAAI,GAAG;IACd;AACF;AAGO,MAAMP,gCAAgC,CAAC,oSAAoS,CAAC;AAE5U,MAAMC,iCAAiCG;IAC5CC,YAAYC,KAAa,CAAE;QACzB,KAAK,CAAC,CAAC,OAAO,EAAEA,MAAM,GAAG,CAAC,GAAGN;IAC/B;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-messages.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-messages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a7f63cdb5f9e522262e159083ec22e8bebde81d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-messages.d.ts @@ -0,0 +1,33 @@ +/** + * Centralized error factories for cached function and revalidation misuse. + * State the scope and constraint, explain non-obvious boundaries, give the + * immediate fix, then link to the relevant docs. + */ +import type { BuildTimeGeneratorName } from '../app-render/work-unit-async-storage.external'; +export declare function createCookiesInUseCacheError(route: string): Error; +export declare function createCookiesInUnstableCacheError(route: string): Error; +export declare function createHeadersInUseCacheError(route: string): Error; +export declare function createHeadersInUnstableCacheError(route: string): Error; +export declare function createSearchParamsInUseCacheError(route: string): Error; +export declare function createConnectionInPublicUseCacheError(route: string): Error; +export declare function createConnectionInPrivateUseCacheError(route: string): Error; +export declare function createConnectionInUnstableCacheError(route: string): Error; +export declare function createRouteHandlerRequestInUseCacheError(route: string, expression: string): Error; +export declare function createRouteHandlerRequestInUnstableCacheError(route: string, expression: string): Error; +/** + * Used when `draftMode().enable()` or `.disable()` is called inside + * `"use cache"` or `"use cache: private"`. Reading `draftMode()` is fine + * inside a cached function, but toggling it is not. + */ +export declare function createDraftModeMutationInUseCacheError(route: string, expression: string): Error; +export declare function createDraftModeMutationInUnstableCacheError(route: string, expression: string): Error; +export declare function createRevalidateDuringRenderError(route: string, expression: string): Error; +export declare function createRevalidateInCachedFunctionError(route: string, expression: string): Error; +export declare function createRevalidateInBuildTimeGeneratorError(route: string, expression: string, generatorName: BuildTimeGeneratorName): Error; +export declare function createCacheTagOutsideUseCacheError(route: string | undefined): Error; +export declare function createCacheLifeOutsideUseCacheError(route: string | undefined): Error; +export declare function createNestedCacheZeroRevalidateError(route: string, cause: Error | undefined): Error; +export declare function createNestedCacheShortExpireError(route: string, cause: Error | undefined): Error; +export declare function createUseCachePrivateInsidePublicUseCacheError(route: string): Error; +export declare function createUseCachePrivateInsideUnstableCacheError(route: string): Error; +export declare function createUseCachePrivateOutsideRequestContextError(route: string, functionName: string): Error; diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-messages.js b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-messages.js new file mode 100644 index 0000000000000000000000000000000000000000..a0aab81e4eafe68c5e808ade1d1bce4a5064e417 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-messages.js @@ -0,0 +1,190 @@ +/** + * Centralized error factories for cached function and revalidation misuse. + * State the scope and constraint, explain non-obvious boundaries, give the + * immediate fix, then link to the relevant docs. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + createCacheLifeOutsideUseCacheError: null, + createCacheTagOutsideUseCacheError: null, + createConnectionInPrivateUseCacheError: null, + createConnectionInPublicUseCacheError: null, + createConnectionInUnstableCacheError: null, + createCookiesInUnstableCacheError: null, + createCookiesInUseCacheError: null, + createDraftModeMutationInUnstableCacheError: null, + createDraftModeMutationInUseCacheError: null, + createHeadersInUnstableCacheError: null, + createHeadersInUseCacheError: null, + createNestedCacheShortExpireError: null, + createNestedCacheZeroRevalidateError: null, + createRevalidateDuringRenderError: null, + createRevalidateInBuildTimeGeneratorError: null, + createRevalidateInCachedFunctionError: null, + createRouteHandlerRequestInUnstableCacheError: null, + createRouteHandlerRequestInUseCacheError: null, + createSearchParamsInUseCacheError: null, + createUseCachePrivateInsidePublicUseCacheError: null, + createUseCachePrivateInsideUnstableCacheError: null, + createUseCachePrivateOutsideRequestContextError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + createCacheLifeOutsideUseCacheError: function() { + return createCacheLifeOutsideUseCacheError; + }, + createCacheTagOutsideUseCacheError: function() { + return createCacheTagOutsideUseCacheError; + }, + createConnectionInPrivateUseCacheError: function() { + return createConnectionInPrivateUseCacheError; + }, + createConnectionInPublicUseCacheError: function() { + return createConnectionInPublicUseCacheError; + }, + createConnectionInUnstableCacheError: function() { + return createConnectionInUnstableCacheError; + }, + createCookiesInUnstableCacheError: function() { + return createCookiesInUnstableCacheError; + }, + createCookiesInUseCacheError: function() { + return createCookiesInUseCacheError; + }, + createDraftModeMutationInUnstableCacheError: function() { + return createDraftModeMutationInUnstableCacheError; + }, + createDraftModeMutationInUseCacheError: function() { + return createDraftModeMutationInUseCacheError; + }, + createHeadersInUnstableCacheError: function() { + return createHeadersInUnstableCacheError; + }, + createHeadersInUseCacheError: function() { + return createHeadersInUseCacheError; + }, + createNestedCacheShortExpireError: function() { + return createNestedCacheShortExpireError; + }, + createNestedCacheZeroRevalidateError: function() { + return createNestedCacheZeroRevalidateError; + }, + createRevalidateDuringRenderError: function() { + return createRevalidateDuringRenderError; + }, + createRevalidateInBuildTimeGeneratorError: function() { + return createRevalidateInBuildTimeGeneratorError; + }, + createRevalidateInCachedFunctionError: function() { + return createRevalidateInCachedFunctionError; + }, + createRouteHandlerRequestInUnstableCacheError: function() { + return createRouteHandlerRequestInUnstableCacheError; + }, + createRouteHandlerRequestInUseCacheError: function() { + return createRouteHandlerRequestInUseCacheError; + }, + createSearchParamsInUseCacheError: function() { + return createSearchParamsInUseCacheError; + }, + createUseCachePrivateInsidePublicUseCacheError: function() { + return createUseCachePrivateInsidePublicUseCacheError; + }, + createUseCachePrivateInsideUnstableCacheError: function() { + return createUseCachePrivateInsideUnstableCacheError; + }, + createUseCachePrivateOutsideRequestContextError: function() { + return createUseCachePrivateOutsideRequestContextError; + } +}); +const NEXT_REQUEST_IN_USE_CACHE = 'https://nextjs.org/docs/messages/next-request-in-use-cache'; +const UNSTABLE_CACHE_API_DOCS = 'https://nextjs.org/docs/app/api-reference/functions/unstable_cache'; +const USE_CACHE_PRIVATE_API_DOCS = 'https://nextjs.org/docs/app/api-reference/directives/use-cache-private'; +const CACHE_TAG_OUTSIDE_USE_CACHE = 'https://nextjs.org/docs/messages/cache-tag-outside-use-cache'; +const CACHE_LIFE_OUTSIDE_USE_CACHE = 'https://nextjs.org/docs/messages/cache-life-outside-use-cache'; +const USE_CACHE_PRIVATE_COMPOSITION = 'https://nextjs.org/docs/messages/use-cache-private-composition'; +const REVALIDATE_IN_USE_CACHE = 'https://nextjs.org/docs/messages/revalidate-in-use-cache'; +const NESTED_USE_CACHE_NO_EXPLICIT_CACHELIFE = 'https://nextjs.org/docs/messages/nested-use-cache-no-explicit-cachelife'; +function createCookiesInUseCacheError(route) { + return new Error(`Route "${route}": \`cookies()\` can't be read inside \`"use cache"\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`); +} +function createCookiesInUnstableCacheError(route) { + return new Error(`Route "${route}": \`cookies()\` can't be read inside \`unstable_cache()\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`); +} +function createHeadersInUseCacheError(route) { + return new Error(`Route "${route}": \`headers()\` can't be read inside \`"use cache"\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`); +} +function createHeadersInUnstableCacheError(route) { + return new Error(`Route "${route}": \`headers()\` can't be read inside \`unstable_cache()\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`); +} +function createSearchParamsInUseCacheError(route) { + return new Error(`Route "${route}": \`searchParams\` can't be read inside \`"use cache"\`. Await it outside the cached function and pass what you need as an argument.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`); +} +function createConnectionInPublicUseCacheError(route) { + return new Error(`Route "${route}": \`connection()\` can't be called inside \`"use cache"\` because cached functions may run during prerendering, without an incoming request. Call it outside the cached function.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`); +} +function createConnectionInPrivateUseCacheError(route) { + return new Error(`Route "${route}": \`connection()\` can't be called inside \`"use cache: private"\` because private cached functions may run during prefetching, without a navigation request. Call it outside the cached function.\nLearn more: ${USE_CACHE_PRIVATE_API_DOCS}`); +} +function createConnectionInUnstableCacheError(route) { + return new Error(`Route "${route}": \`connection()\` can't be called inside \`unstable_cache()\` because cached functions may run during prerendering, without an incoming request. Call it outside the cached function.\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`); +} +function createRouteHandlerRequestInUseCacheError(route, expression) { + return new Error(`Route "${route}": \`${expression}\` can't be read inside \`"use cache"\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`); +} +function createRouteHandlerRequestInUnstableCacheError(route, expression) { + return new Error(`Route "${route}": \`${expression}\` can't be read inside \`unstable_cache()\`. Read it outside the cached function and pass what you need as an argument.\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`); +} +function createDraftModeMutationInUseCacheError(route, expression) { + return new Error(`Route "${route}": \`${expression}\` can't be called inside \`"use cache"\`. Draft mode can be read inside a cached function, but enabling or disabling it must happen outside.\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`); +} +function createDraftModeMutationInUnstableCacheError(route, expression) { + return new Error(`Route "${route}": \`${expression}\` can't be called inside \`unstable_cache()\`. Draft mode can be read inside a cached function, but enabling or disabling it must happen outside.\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`); +} +function createRevalidateDuringRenderError(route, expression) { + return new Error(`Route "${route}": \`${expression}\` can't be called during render. Call it from a Server Action or Route Handler instead.\nLearn more: ${REVALIDATE_IN_USE_CACHE}`); +} +function createRevalidateInCachedFunctionError(route, expression) { + return new Error(`Route "${route}": \`${expression}\` can't be called inside a cached function. Call it from a Server Action or Route Handler instead.\nLearn more: ${REVALIDATE_IN_USE_CACHE}`); +} +function createRevalidateInBuildTimeGeneratorError(route, expression, generatorName) { + return new Error(`Route "${route}": \`${expression}\` can't be called inside \`${generatorName}\`. Call it from a Server Action or Route Handler instead.\nLearn more: ${REVALIDATE_IN_USE_CACHE}`); +} +// Cache configuration and nesting +function routePrefix(route) { + return route === undefined ? '' : `Route "${route}": `; +} +function createCacheTagOutsideUseCacheError(route) { + return new Error(`${routePrefix(route)}\`cacheTag()\` can only be called inside a \`"use cache"\` or \`"use cache: private"\` function.\nLearn more: ${CACHE_TAG_OUTSIDE_USE_CACHE}`); +} +function createCacheLifeOutsideUseCacheError(route) { + return new Error(`${routePrefix(route)}\`cacheLife()\` can only be called inside a \`"use cache"\` or \`"use cache: private"\` function.\nLearn more: ${CACHE_LIFE_OUTSIDE_USE_CACHE}`); +} +function createNestedCacheZeroRevalidateError(route, cause) { + return new Error(`Route "${route}": A nested \`"use cache"\` with \`revalidate: 0\` is inside an outer \`"use cache"\` that has no \`cacheLife()\`. Add \`cacheLife()\` to the outer one to choose whether to prerender it with a non-zero \`revalidate\` or keep it dynamic with \`revalidate: 0\`.\nLearn more: ${NESTED_USE_CACHE_NO_EXPLICIT_CACHELIFE}`, { + cause + }); +} +function createNestedCacheShortExpireError(route, cause) { + return new Error(`Route "${route}": A nested \`"use cache"\` with a short \`expire\` (under 5 minutes) is inside an outer \`"use cache"\` that has no \`cacheLife()\`. Add \`cacheLife()\` to the outer one to choose whether to prerender it with a longer \`expire\` or keep it dynamic with a short \`expire\`.\nLearn more: ${NESTED_USE_CACHE_NO_EXPLICIT_CACHELIFE}`, { + cause + }); +} +function createUseCachePrivateInsidePublicUseCacheError(route) { + return new Error(`Route "${route}": \`"use cache: private"\` can't be nested inside \`"use cache"\` because a shared cached function can't depend on private request data. Nest it only inside another \`"use cache: private"\`.\nLearn more: ${USE_CACHE_PRIVATE_COMPOSITION}`); +} +function createUseCachePrivateInsideUnstableCacheError(route) { + return new Error(`Route "${route}": \`"use cache: private"\` can't be used inside \`unstable_cache()\` because \`unstable_cache()\` uses a shared cache that can't contain private request data. Call the private cached function outside \`unstable_cache()\`.\nLearn more: ${USE_CACHE_PRIVATE_COMPOSITION}`); +} +function createUseCachePrivateOutsideRequestContextError(route, functionName) { + return new Error(`Route "${route}": \`"use cache: private"\` needs an active request, so it can't be used during \`${functionName}\` or other build-time contexts. Move it to a request-time component or function.\nLearn more: ${USE_CACHE_PRIVATE_COMPOSITION}`); +} + +//# sourceMappingURL=use-cache-messages.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-messages.js.map b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-messages.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d24bc7c444da6b2df541980c34877edb91c581d9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-messages.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/use-cache-messages.ts"],"sourcesContent":["/**\n * Centralized error factories for cached function and revalidation misuse.\n * State the scope and constraint, explain non-obvious boundaries, give the\n * immediate fix, then link to the relevant docs.\n */\n\nimport type { BuildTimeGeneratorName } from '../app-render/work-unit-async-storage.external'\n\nconst NEXT_REQUEST_IN_USE_CACHE =\n 'https://nextjs.org/docs/messages/next-request-in-use-cache'\n\nconst UNSTABLE_CACHE_API_DOCS =\n 'https://nextjs.org/docs/app/api-reference/functions/unstable_cache'\n\nconst USE_CACHE_PRIVATE_API_DOCS =\n 'https://nextjs.org/docs/app/api-reference/directives/use-cache-private'\n\nconst CACHE_TAG_OUTSIDE_USE_CACHE =\n 'https://nextjs.org/docs/messages/cache-tag-outside-use-cache'\n\nconst CACHE_LIFE_OUTSIDE_USE_CACHE =\n 'https://nextjs.org/docs/messages/cache-life-outside-use-cache'\n\nconst USE_CACHE_PRIVATE_COMPOSITION =\n 'https://nextjs.org/docs/messages/use-cache-private-composition'\n\nconst REVALIDATE_IN_USE_CACHE =\n 'https://nextjs.org/docs/messages/revalidate-in-use-cache'\n\nconst NESTED_USE_CACHE_NO_EXPLICIT_CACHELIFE =\n 'https://nextjs.org/docs/messages/nested-use-cache-no-explicit-cachelife'\n\n// Request data accessed in caches\n\nexport function createCookiesInUseCacheError(route: string): Error {\n return new Error(\n `Route \"${route}\": \\`cookies()\\` can't be read inside \\`\"use cache\"\\`. Read it outside the cached function and pass what you need as an argument.\\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`\n )\n}\n\nexport function createCookiesInUnstableCacheError(route: string): Error {\n return new Error(\n `Route \"${route}\": \\`cookies()\\` can't be read inside \\`unstable_cache()\\`. Read it outside the cached function and pass what you need as an argument.\\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`\n )\n}\n\nexport function createHeadersInUseCacheError(route: string): Error {\n return new Error(\n `Route \"${route}\": \\`headers()\\` can't be read inside \\`\"use cache\"\\`. Read it outside the cached function and pass what you need as an argument.\\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`\n )\n}\n\nexport function createHeadersInUnstableCacheError(route: string): Error {\n return new Error(\n `Route \"${route}\": \\`headers()\\` can't be read inside \\`unstable_cache()\\`. Read it outside the cached function and pass what you need as an argument.\\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`\n )\n}\n\nexport function createSearchParamsInUseCacheError(route: string): Error {\n return new Error(\n `Route \"${route}\": \\`searchParams\\` can't be read inside \\`\"use cache\"\\`. Await it outside the cached function and pass what you need as an argument.\\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`\n )\n}\n\nexport function createConnectionInPublicUseCacheError(route: string): Error {\n return new Error(\n `Route \"${route}\": \\`connection()\\` can't be called inside \\`\"use cache\"\\` because cached functions may run during prerendering, without an incoming request. Call it outside the cached function.\\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`\n )\n}\n\nexport function createConnectionInPrivateUseCacheError(route: string): Error {\n return new Error(\n `Route \"${route}\": \\`connection()\\` can't be called inside \\`\"use cache: private\"\\` because private cached functions may run during prefetching, without a navigation request. Call it outside the cached function.\\nLearn more: ${USE_CACHE_PRIVATE_API_DOCS}`\n )\n}\n\nexport function createConnectionInUnstableCacheError(route: string): Error {\n return new Error(\n `Route \"${route}\": \\`connection()\\` can't be called inside \\`unstable_cache()\\` because cached functions may run during prerendering, without an incoming request. Call it outside the cached function.\\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`\n )\n}\n\nexport function createRouteHandlerRequestInUseCacheError(\n route: string,\n expression: string\n): Error {\n return new Error(\n `Route \"${route}\": \\`${expression}\\` can't be read inside \\`\"use cache\"\\`. Read it outside the cached function and pass what you need as an argument.\\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`\n )\n}\n\nexport function createRouteHandlerRequestInUnstableCacheError(\n route: string,\n expression: string\n): Error {\n return new Error(\n `Route \"${route}\": \\`${expression}\\` can't be read inside \\`unstable_cache()\\`. Read it outside the cached function and pass what you need as an argument.\\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`\n )\n}\n\n// Mutations inside caches and render\n\n/**\n * Used when `draftMode().enable()` or `.disable()` is called inside\n * `\"use cache\"` or `\"use cache: private\"`. Reading `draftMode()` is fine\n * inside a cached function, but toggling it is not.\n */\nexport function createDraftModeMutationInUseCacheError(\n route: string,\n expression: string\n): Error {\n return new Error(\n `Route \"${route}\": \\`${expression}\\` can't be called inside \\`\"use cache\"\\`. Draft mode can be read inside a cached function, but enabling or disabling it must happen outside.\\nLearn more: ${NEXT_REQUEST_IN_USE_CACHE}`\n )\n}\n\nexport function createDraftModeMutationInUnstableCacheError(\n route: string,\n expression: string\n): Error {\n return new Error(\n `Route \"${route}\": \\`${expression}\\` can't be called inside \\`unstable_cache()\\`. Draft mode can be read inside a cached function, but enabling or disabling it must happen outside.\\nLearn more: ${UNSTABLE_CACHE_API_DOCS}`\n )\n}\n\nexport function createRevalidateDuringRenderError(\n route: string,\n expression: string\n): Error {\n return new Error(\n `Route \"${route}\": \\`${expression}\\` can't be called during render. Call it from a Server Action or Route Handler instead.\\nLearn more: ${REVALIDATE_IN_USE_CACHE}`\n )\n}\n\nexport function createRevalidateInCachedFunctionError(\n route: string,\n expression: string\n): Error {\n return new Error(\n `Route \"${route}\": \\`${expression}\\` can't be called inside a cached function. Call it from a Server Action or Route Handler instead.\\nLearn more: ${REVALIDATE_IN_USE_CACHE}`\n )\n}\n\nexport function createRevalidateInBuildTimeGeneratorError(\n route: string,\n expression: string,\n generatorName: BuildTimeGeneratorName\n): Error {\n return new Error(\n `Route \"${route}\": \\`${expression}\\` can't be called inside \\`${generatorName}\\`. Call it from a Server Action or Route Handler instead.\\nLearn more: ${REVALIDATE_IN_USE_CACHE}`\n )\n}\n\n// Cache configuration and nesting\n\nfunction routePrefix(route: string | undefined): string {\n return route === undefined ? '' : `Route \"${route}\": `\n}\n\nexport function createCacheTagOutsideUseCacheError(\n route: string | undefined\n): Error {\n return new Error(\n `${routePrefix(route)}\\`cacheTag()\\` can only be called inside a \\`\"use cache\"\\` or \\`\"use cache: private\"\\` function.\\nLearn more: ${CACHE_TAG_OUTSIDE_USE_CACHE}`\n )\n}\n\nexport function createCacheLifeOutsideUseCacheError(\n route: string | undefined\n): Error {\n return new Error(\n `${routePrefix(route)}\\`cacheLife()\\` can only be called inside a \\`\"use cache\"\\` or \\`\"use cache: private\"\\` function.\\nLearn more: ${CACHE_LIFE_OUTSIDE_USE_CACHE}`\n )\n}\n\nexport function createNestedCacheZeroRevalidateError(\n route: string,\n cause: Error | undefined\n): Error {\n return new Error(\n `Route \"${route}\": A nested \\`\"use cache\"\\` with \\`revalidate: 0\\` is inside an outer \\`\"use cache\"\\` that has no \\`cacheLife()\\`. Add \\`cacheLife()\\` to the outer one to choose whether to prerender it with a non-zero \\`revalidate\\` or keep it dynamic with \\`revalidate: 0\\`.\\nLearn more: ${NESTED_USE_CACHE_NO_EXPLICIT_CACHELIFE}`,\n { cause }\n )\n}\n\nexport function createNestedCacheShortExpireError(\n route: string,\n cause: Error | undefined\n): Error {\n return new Error(\n `Route \"${route}\": A nested \\`\"use cache\"\\` with a short \\`expire\\` (under 5 minutes) is inside an outer \\`\"use cache\"\\` that has no \\`cacheLife()\\`. Add \\`cacheLife()\\` to the outer one to choose whether to prerender it with a longer \\`expire\\` or keep it dynamic with a short \\`expire\\`.\\nLearn more: ${NESTED_USE_CACHE_NO_EXPLICIT_CACHELIFE}`,\n { cause }\n )\n}\n\n// Private cache composition and request context\n\nexport function createUseCachePrivateInsidePublicUseCacheError(\n route: string\n): Error {\n return new Error(\n `Route \"${route}\": \\`\"use cache: private\"\\` can't be nested inside \\`\"use cache\"\\` because a shared cached function can't depend on private request data. Nest it only inside another \\`\"use cache: private\"\\`.\\nLearn more: ${USE_CACHE_PRIVATE_COMPOSITION}`\n )\n}\n\nexport function createUseCachePrivateInsideUnstableCacheError(\n route: string\n): Error {\n return new Error(\n `Route \"${route}\": \\`\"use cache: private\"\\` can't be used inside \\`unstable_cache()\\` because \\`unstable_cache()\\` uses a shared cache that can't contain private request data. Call the private cached function outside \\`unstable_cache()\\`.\\nLearn more: ${USE_CACHE_PRIVATE_COMPOSITION}`\n )\n}\n\nexport function createUseCachePrivateOutsideRequestContextError(\n route: string,\n functionName: string\n): Error {\n return new Error(\n `Route \"${route}\": \\`\"use cache: private\"\\` needs an active request, so it can't be used during \\`${functionName}\\` or other build-time contexts. Move it to a request-time component or function.\\nLearn more: ${USE_CACHE_PRIVATE_COMPOSITION}`\n )\n}\n"],"names":["createCacheLifeOutsideUseCacheError","createCacheTagOutsideUseCacheError","createConnectionInPrivateUseCacheError","createConnectionInPublicUseCacheError","createConnectionInUnstableCacheError","createCookiesInUnstableCacheError","createCookiesInUseCacheError","createDraftModeMutationInUnstableCacheError","createDraftModeMutationInUseCacheError","createHeadersInUnstableCacheError","createHeadersInUseCacheError","createNestedCacheShortExpireError","createNestedCacheZeroRevalidateError","createRevalidateDuringRenderError","createRevalidateInBuildTimeGeneratorError","createRevalidateInCachedFunctionError","createRouteHandlerRequestInUnstableCacheError","createRouteHandlerRequestInUseCacheError","createSearchParamsInUseCacheError","createUseCachePrivateInsidePublicUseCacheError","createUseCachePrivateInsideUnstableCacheError","createUseCachePrivateOutsideRequestContextError","NEXT_REQUEST_IN_USE_CACHE","UNSTABLE_CACHE_API_DOCS","USE_CACHE_PRIVATE_API_DOCS","CACHE_TAG_OUTSIDE_USE_CACHE","CACHE_LIFE_OUTSIDE_USE_CACHE","USE_CACHE_PRIVATE_COMPOSITION","REVALIDATE_IN_USE_CACHE","NESTED_USE_CACHE_NO_EXPLICIT_CACHELIFE","route","Error","expression","generatorName","routePrefix","undefined","cause","functionName"],"mappings":"AAAA;;;;CAIC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAmKeA,mCAAmC;eAAnCA;;IARAC,kCAAkC;eAAlCA;;IAzFAC,sCAAsC;eAAtCA;;IANAC,qCAAqC;eAArCA;;IAYAC,oCAAoC;eAApCA;;IApCAC,iCAAiC;eAAjCA;;IANAC,4BAA4B;eAA5BA;;IAkFAC,2CAA2C;eAA3CA;;IATAC,sCAAsC;eAAtCA;;IAvDAC,iCAAiC;eAAjCA;;IANAC,4BAA4B;eAA5BA;;IA2IAC,iCAAiC;eAAjCA;;IAVAC,oCAAoC;eAApCA;;IAlDAC,iCAAiC;eAAjCA;;IAkBAC,yCAAyC;eAAzCA;;IATAC,qCAAqC;eAArCA;;IA3CAC,6CAA6C;eAA7CA;;IATAC,wCAAwC;eAAxCA;;IAxBAC,iCAAiC;eAAjCA;;IA2IAC,8CAA8C;eAA9CA;;IAQAC,6CAA6C;eAA7CA;;IAQAC,+CAA+C;eAA/CA;;;AA7MhB,MAAMC,4BACJ;AAEF,MAAMC,0BACJ;AAEF,MAAMC,6BACJ;AAEF,MAAMC,8BACJ;AAEF,MAAMC,+BACJ;AAEF,MAAMC,gCACJ;AAEF,MAAMC,0BACJ;AAEF,MAAMC,yCACJ;AAIK,SAASvB,6BAA6BwB,KAAa;IACxD,OAAO,IAAIC,MACT,CAAC,OAAO,EAAED,MAAM,+IAA+I,EAAER,2BAA2B;AAEhM;AAEO,SAASjB,kCAAkCyB,KAAa;IAC7D,OAAO,IAAIC,MACT,CAAC,OAAO,EAAED,MAAM,oJAAoJ,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EAAEH,+BAA+B;AAEjS;AAEO,SAASN,gDACdS,KAAa,EACbO,YAAoB;IAEpB,OAAO,IAAIN,MACT,CAAC,OAAO,EAAED,MAAM,kFAAkF,EAAEO,aAAa,+FAA+F,EAAEV,+BAA+B;AAErP","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-globals.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-globals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e2dcfe5118f6156aa9086920703572bf8ec0971 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-globals.d.ts @@ -0,0 +1,42 @@ +import type { Params } from '../request/params'; +/** + * Serializable view of the outer `RequestStore` forwarded to the probe + * worker. The worker rebuilds a real `RequestStore` from this so cache + * bodies that read `cookies()`, `headers()`, or `draftMode()` behave the + * same as in a real fill — without it, those reads would diverge from + * production behaviour and could mask the actual deadlock. + */ +export type UseCacheProbeRequestSnapshot = { + headers: [string, string][]; + cookieHeader: string | undefined; + urlPathname: string; + urlSearch: string; + rootParams: Params; + isDraftMode: boolean; + isHmrRefresh: boolean; + hmrRefreshHash: string | undefined; + requestStartTime: number; +}; +/** + * Probe hook installed by the dev server. Resolves to `true` if the cache + * function ran to completion in isolation — the strong signal that shared + * outer-scope state is deadlocking the main fill. Resolves to `false` for + * any other outcome (probe timeout, decode failure, missing module, etc.). + */ +export type UseCacheProbe = (args: { + /** + * Page key as it appears in the build manifest, e.g. `/static/page` for + * `app/static/page.tsx`. The trailing `/page` (or `/route`) suffix is + * load-bearing — the worker passes this directly to `loadComponents()`. + */ + page: string; + /** Route pathname; used to populate the worker's `WorkStore.route`. */ + route: string; + id: string; + kind: string; + encodedArguments: string | FormData; + request: UseCacheProbeRequestSnapshot; + timeoutMs: number; +}) => Promise; +export declare function setUseCacheProbe(fn: UseCacheProbe | undefined): void; +export declare function getUseCacheProbe(): UseCacheProbe | undefined; diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-globals.js b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-globals.js new file mode 100644 index 0000000000000000000000000000000000000000..1a06a058de0c6b2e36d0b288d16109ef9e29c94a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-globals.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getUseCacheProbe: null, + setUseCacheProbe: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getUseCacheProbe: function() { + return getUseCacheProbe; + }, + setUseCacheProbe: function() { + return setUseCacheProbe; + } +}); +// Cross-module handoff for the `'use cache'` hang-detection probe. A symbol on +// `globalThis` decouples the dev-server entry point (which installs the +// jest-worker pool) from the read site inside `use-cache-wrapper.ts` — avoiding +// a direct import of dev-only code from the use-cache module. In any process +// where the symbol is not set (prod, edge, unit tests, the probe worker itself) +// `getUseCacheProbe()` returns undefined, which doubles as the recursion guard +// against a probe spawning another probe. +const SYMBOL = Symbol.for('next.dev.useCacheProbe'); +function setUseCacheProbe(fn) { + ; + globalThis[SYMBOL] = fn; +} +function getUseCacheProbe() { + return globalThis[SYMBOL]; +} + +//# sourceMappingURL=use-cache-probe-globals.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-globals.js.map b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-globals.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f1cc165c7d93f3a591060caf9b26ef78cd30afe8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-globals.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/use-cache-probe-globals.ts"],"sourcesContent":["import type { Params } from '../request/params'\n\n// Cross-module handoff for the `'use cache'` hang-detection probe. A symbol on\n// `globalThis` decouples the dev-server entry point (which installs the\n// jest-worker pool) from the read site inside `use-cache-wrapper.ts` — avoiding\n// a direct import of dev-only code from the use-cache module. In any process\n// where the symbol is not set (prod, edge, unit tests, the probe worker itself)\n// `getUseCacheProbe()` returns undefined, which doubles as the recursion guard\n// against a probe spawning another probe.\nconst SYMBOL: unique symbol = Symbol.for('next.dev.useCacheProbe')\n\n/**\n * Serializable view of the outer `RequestStore` forwarded to the probe\n * worker. The worker rebuilds a real `RequestStore` from this so cache\n * bodies that read `cookies()`, `headers()`, or `draftMode()` behave the\n * same as in a real fill — without it, those reads would diverge from\n * production behaviour and could mask the actual deadlock.\n */\nexport type UseCacheProbeRequestSnapshot = {\n headers: [string, string][]\n cookieHeader: string | undefined\n urlPathname: string\n urlSearch: string\n rootParams: Params\n isDraftMode: boolean\n isHmrRefresh: boolean\n hmrRefreshHash: string | undefined\n requestStartTime: number\n}\n\n/**\n * Probe hook installed by the dev server. Resolves to `true` if the cache\n * function ran to completion in isolation — the strong signal that shared\n * outer-scope state is deadlocking the main fill. Resolves to `false` for\n * any other outcome (probe timeout, decode failure, missing module, etc.).\n */\nexport type UseCacheProbe = (args: {\n /**\n * Page key as it appears in the build manifest, e.g. `/static/page` for\n * `app/static/page.tsx`. The trailing `/page` (or `/route`) suffix is\n * load-bearing — the worker passes this directly to `loadComponents()`.\n */\n page: string\n /** Route pathname; used to populate the worker's `WorkStore.route`. */\n route: string\n id: string\n kind: string\n encodedArguments: string | FormData\n request: UseCacheProbeRequestSnapshot\n timeoutMs: number\n}) => Promise\n\ninterface ProbeHolder {\n [SYMBOL]?: UseCacheProbe\n}\n\nexport function setUseCacheProbe(fn: UseCacheProbe | undefined): void {\n ;(globalThis as ProbeHolder)[SYMBOL] = fn\n}\n\nexport function getUseCacheProbe(): UseCacheProbe | undefined {\n return (globalThis as ProbeHolder)[SYMBOL]\n}\n"],"names":["getUseCacheProbe","setUseCacheProbe","SYMBOL","Symbol","for","fn","globalThis"],"mappings":";;;;;;;;;;;;;;;IA4DgBA,gBAAgB;eAAhBA;;IAJAC,gBAAgB;eAAhBA;;;AAtDhB,+EAA+E;AAC/E,wEAAwE;AACxE,gFAAgF;AAChF,6EAA6E;AAC7E,gFAAgF;AAChF,+EAA+E;AAC/E,0CAA0C;AAC1C,MAAMC,SAAwBC,OAAOC,GAAG,CAAC;AA+ClC,SAASH,iBAAiBI,EAA6B;;IAC1DC,UAA0B,CAACJ,OAAO,GAAGG;AACzC;AAEO,SAASL;IACd,OAAO,AAACM,UAA0B,CAACJ,OAAO;AAC5C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-scheduler.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-scheduler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5df0671fbdf2849c291402e5d63355b28c390623 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-scheduler.d.ts @@ -0,0 +1,53 @@ +import type { WorkStore } from '../app-render/work-async-storage.external'; +import type { RequestStore } from '../app-render/work-unit-async-storage.external'; +interface CacheContextWithProbeFields { + readonly functionId: string; + readonly handlerKind: string; +} +interface SetupOptions { + workStore: WorkStore; + outerRequestStore: RequestStore; + cacheContext: CacheContextWithProbeFields; + encodedArguments: string | FormData; + /** + * Absolute monotonic deadline (in `performance.now()` units) at which the + * outer cache fill will be aborted by the dev render-timeout timer. The + * scheduler derives the up-front budget check, every reschedule budget check, + * and each probe's internal timeout from this single value. + */ + fillDeadlineAt: number; + /** + * Cache stream to track. Each chunk that flows through resets the idle timer; + * the returned stream is the same data, transparently observed. + */ + stream: ReadableStream; + /** + * Aborts when the probe should stop watching: the cache fill bailed (timeout, + * upstream cancel, deadlock detection), or it settled normally. + */ + abortSignal: AbortSignal; + /** + * Called once if the probe ran the cache function to completion in isolation + * while the main fill was still pending. Strong signal that shared state from + * the outer scope is preventing the body from progressing — the caller + * decides what to do with that (typically abort the fill and surface a + * deadlock error). + */ + onProbeCompleted: () => void; +} +/** + * Schedule an idle-deadline probe over a cache fill stream (dev-only). + * + * Fires the probe when the stream has been idle for `PROBE_THRESHOLD_MS`. The + * probe re-runs the cache function in a fresh V8 isolate so module-scoped state + * from the outer render — e.g. a top-level `Map` deduping + * fetches — can't poison the body. If the function completes in isolation, the + * hang is attributable to that shared state and the caller surfaces a specific + * error instead of waiting out the generic timeout. + * + * Returns the input stream unchanged when the scheduler should be skipped: no + * probe hook installed, or the remaining time until `fillDeadlineAt` is too + * short to leave room for both the idle threshold and a minimum probe budget. + */ +export declare function setupProbeScheduler(opts: SetupOptions): ReadableStream; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-scheduler.js b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-scheduler.js new file mode 100644 index 0000000000000000000000000000000000000000..698ff8639c75726c4d2431fe43caf3032a70fe9b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-scheduler.js @@ -0,0 +1,117 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "setupProbeScheduler", { + enumerable: true, + get: function() { + return setupProbeScheduler; + } +}); +const _usecacheprobeglobals = require("./use-cache-probe-globals"); +const PROBE_THRESHOLD_MS = 10000; +const MIN_PROBE_BUDGET_MS = 3000; +function setupProbeScheduler(opts) { + const { workStore, outerRequestStore, cacheContext, encodedArguments, fillDeadlineAt, stream, abortSignal, onProbeCompleted } = opts; + if (fillDeadlineAt - performance.now() < PROBE_THRESHOLD_MS + MIN_PROBE_BUDGET_MS) { + return stream; + } + const probe = (0, _usecacheprobeglobals.getUseCacheProbe)(); + if (!probe) { + return stream; + } + let lastChunkAt = performance.now(); + let idleTimer; + const startProbe = ()=>{ + if (abortSignal.aborted) { + return; + } + const probeStartedAtChunk = lastChunkAt; + // Computed when the probe is about to run so it gets the actual remaining + // budget, not a stale value baked in at scheduler setup. Reserves a 1s + // buffer so the probe's internal timeout fires before the outer render + // timeout. + const probeInternalTimeoutMs = fillDeadlineAt - performance.now() - 1000; + probe({ + page: workStore.page, + route: workStore.route, + id: cacheContext.functionId, + kind: cacheContext.handlerKind, + encodedArguments, + // Built lazily because most fills complete before the idle timer fires; + // only worth assembling once we know the probe is running. + request: { + headers: Array.from(outerRequestStore.headers.entries()), + cookieHeader: outerRequestStore.headers.get('cookie') ?? undefined, + urlPathname: outerRequestStore.url.pathname, + urlSearch: outerRequestStore.url.search, + rootParams: outerRequestStore.rootParams ?? {}, + isDraftMode: workStore.isDraftMode ?? false, + isHmrRefresh: outerRequestStore.isHmrRefresh ?? false, + hmrRefreshHash: outerRequestStore.hmrRefreshHash, + requestStartTime: workStore.requestStartTime + }, + timeoutMs: probeInternalTimeoutMs + }).then((completed)=>{ + // Mid-probe recovery: chunks arrived while the probe was running, so + // the main stream is making progress. Discard the probe's result rather + // than reporting a deadlock that no longer holds. + if (lastChunkAt > probeStartedAtChunk) { + return; + } + if (completed && !abortSignal.aborted) { + onProbeCompleted(); + } + }, ()=>{ + // Probe failures are inconclusive; fall back to the regular cache-fill + // timeout. + }); + }; + const scheduleAfterIdle = ()=>{ + if (idleTimer !== undefined || abortSignal.aborted) { + return; + } + const now = performance.now(); + const idleFor = now - lastChunkAt; + const wait = Math.max(0, PROBE_THRESHOLD_MS - idleFor); + // Skip scheduling if the outer fill timeout will fire before the probe + // could even start running with at least a minimum useful budget. Without + // this check, a chunk arriving late in the fill could reschedule a probe + // that the outer timeout would then abort — wasted worker spawn for a probe + // that can't meaningfully complete. + if (fillDeadlineAt - now < wait + MIN_PROBE_BUDGET_MS) { + return; + } + idleTimer = setTimeout(()=>{ + idleTimer = undefined; + if (abortSignal.aborted) { + return; + } + const idleNow = performance.now() - lastChunkAt; + if (idleNow < PROBE_THRESHOLD_MS) { + // A chunk arrived since we set this timer; reschedule. + scheduleAfterIdle(); + return; + } + startProbe(); + }, wait); + }; + abortSignal.addEventListener('abort', ()=>{ + if (idleTimer !== undefined) { + clearTimeout(idleTimer); + idleTimer = undefined; + } + }, { + once: true + }); + scheduleAfterIdle(); + return stream.pipeThrough(new TransformStream({ + transform (chunk, controller) { + lastChunkAt = performance.now(); + scheduleAfterIdle(); + controller.enqueue(chunk); + } + })); +} + +//# sourceMappingURL=use-cache-probe-scheduler.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-scheduler.js.map b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-scheduler.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4dbf1b978aa817237b078f4853562449dbfda072 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-probe-scheduler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/use-cache-probe-scheduler.ts"],"sourcesContent":["import type { WorkStore } from '../app-render/work-async-storage.external'\nimport type { RequestStore } from '../app-render/work-unit-async-storage.external'\n\nimport { getUseCacheProbe } from './use-cache-probe-globals'\n\nconst PROBE_THRESHOLD_MS = 10_000\nconst MIN_PROBE_BUDGET_MS = 3_000\n\ninterface CacheContextWithProbeFields {\n readonly functionId: string\n readonly handlerKind: string\n}\n\ninterface SetupOptions {\n workStore: WorkStore\n outerRequestStore: RequestStore\n cacheContext: CacheContextWithProbeFields\n encodedArguments: string | FormData\n /**\n * Absolute monotonic deadline (in `performance.now()` units) at which the\n * outer cache fill will be aborted by the dev render-timeout timer. The\n * scheduler derives the up-front budget check, every reschedule budget check,\n * and each probe's internal timeout from this single value.\n */\n fillDeadlineAt: number\n /**\n * Cache stream to track. Each chunk that flows through resets the idle timer;\n * the returned stream is the same data, transparently observed.\n */\n stream: ReadableStream\n /**\n * Aborts when the probe should stop watching: the cache fill bailed (timeout,\n * upstream cancel, deadlock detection), or it settled normally.\n */\n abortSignal: AbortSignal\n /**\n * Called once if the probe ran the cache function to completion in isolation\n * while the main fill was still pending. Strong signal that shared state from\n * the outer scope is preventing the body from progressing — the caller\n * decides what to do with that (typically abort the fill and surface a\n * deadlock error).\n */\n onProbeCompleted: () => void\n}\n\n/**\n * Schedule an idle-deadline probe over a cache fill stream (dev-only).\n *\n * Fires the probe when the stream has been idle for `PROBE_THRESHOLD_MS`. The\n * probe re-runs the cache function in a fresh V8 isolate so module-scoped state\n * from the outer render — e.g. a top-level `Map` deduping\n * fetches — can't poison the body. If the function completes in isolation, the\n * hang is attributable to that shared state and the caller surfaces a specific\n * error instead of waiting out the generic timeout.\n *\n * Returns the input stream unchanged when the scheduler should be skipped: no\n * probe hook installed, or the remaining time until `fillDeadlineAt` is too\n * short to leave room for both the idle threshold and a minimum probe budget.\n */\nexport function setupProbeScheduler(\n opts: SetupOptions\n): ReadableStream {\n const {\n workStore,\n outerRequestStore,\n cacheContext,\n encodedArguments,\n fillDeadlineAt,\n stream,\n abortSignal,\n onProbeCompleted,\n } = opts\n\n if (\n fillDeadlineAt - performance.now() <\n PROBE_THRESHOLD_MS + MIN_PROBE_BUDGET_MS\n ) {\n return stream\n }\n\n const probe = getUseCacheProbe()\n if (!probe) {\n return stream\n }\n\n let lastChunkAt = performance.now()\n let idleTimer: ReturnType | undefined\n\n const startProbe = () => {\n if (abortSignal.aborted) {\n return\n }\n\n const probeStartedAtChunk = lastChunkAt\n\n // Computed when the probe is about to run so it gets the actual remaining\n // budget, not a stale value baked in at scheduler setup. Reserves a 1s\n // buffer so the probe's internal timeout fires before the outer render\n // timeout.\n const probeInternalTimeoutMs = fillDeadlineAt - performance.now() - 1_000\n\n probe({\n page: workStore.page,\n route: workStore.route,\n id: cacheContext.functionId,\n kind: cacheContext.handlerKind,\n encodedArguments,\n // Built lazily because most fills complete before the idle timer fires;\n // only worth assembling once we know the probe is running.\n request: {\n headers: Array.from(outerRequestStore.headers.entries()),\n cookieHeader: outerRequestStore.headers.get('cookie') ?? undefined,\n urlPathname: outerRequestStore.url.pathname,\n urlSearch: outerRequestStore.url.search,\n rootParams: outerRequestStore.rootParams ?? {},\n isDraftMode: workStore.isDraftMode ?? false,\n isHmrRefresh: outerRequestStore.isHmrRefresh ?? false,\n hmrRefreshHash: outerRequestStore.hmrRefreshHash,\n requestStartTime: workStore.requestStartTime,\n },\n timeoutMs: probeInternalTimeoutMs,\n }).then(\n (completed) => {\n // Mid-probe recovery: chunks arrived while the probe was running, so\n // the main stream is making progress. Discard the probe's result rather\n // than reporting a deadlock that no longer holds.\n if (lastChunkAt > probeStartedAtChunk) {\n return\n }\n if (completed && !abortSignal.aborted) {\n onProbeCompleted()\n }\n },\n () => {\n // Probe failures are inconclusive; fall back to the regular cache-fill\n // timeout.\n }\n )\n }\n\n const scheduleAfterIdle = () => {\n if (idleTimer !== undefined || abortSignal.aborted) {\n return\n }\n const now = performance.now()\n const idleFor = now - lastChunkAt\n const wait = Math.max(0, PROBE_THRESHOLD_MS - idleFor)\n\n // Skip scheduling if the outer fill timeout will fire before the probe\n // could even start running with at least a minimum useful budget. Without\n // this check, a chunk arriving late in the fill could reschedule a probe\n // that the outer timeout would then abort — wasted worker spawn for a probe\n // that can't meaningfully complete.\n if (fillDeadlineAt - now < wait + MIN_PROBE_BUDGET_MS) {\n return\n }\n\n idleTimer = setTimeout(() => {\n idleTimer = undefined\n if (abortSignal.aborted) {\n return\n }\n const idleNow = performance.now() - lastChunkAt\n if (idleNow < PROBE_THRESHOLD_MS) {\n // A chunk arrived since we set this timer; reschedule.\n scheduleAfterIdle()\n return\n }\n startProbe()\n }, wait)\n }\n\n abortSignal.addEventListener(\n 'abort',\n () => {\n if (idleTimer !== undefined) {\n clearTimeout(idleTimer)\n idleTimer = undefined\n }\n },\n { once: true }\n )\n\n scheduleAfterIdle()\n\n return stream.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n lastChunkAt = performance.now()\n scheduleAfterIdle()\n controller.enqueue(chunk)\n },\n })\n )\n}\n"],"names":["setupProbeScheduler","PROBE_THRESHOLD_MS","MIN_PROBE_BUDGET_MS","opts","workStore","outerRequestStore","cacheContext","encodedArguments","fillDeadlineAt","stream","abortSignal","onProbeCompleted","performance","now","probe","getUseCacheProbe","lastChunkAt","idleTimer","startProbe","aborted","probeStartedAtChunk","probeInternalTimeoutMs","page","route","id","functionId","kind","handlerKind","request","headers","Array","from","entries","cookieHeader","get","undefined","urlPathname","url","pathname","urlSearch","search","rootParams","isDraftMode","isHmrRefresh","hmrRefreshHash","requestStartTime","timeoutMs","then","completed","scheduleAfterIdle","idleFor","wait","Math","max","setTimeout","idleNow","addEventListener","clearTimeout","once","pipeThrough","TransformStream","transform","chunk","controller","enqueue"],"mappings":";;;;+BA2DgBA;;;eAAAA;;;sCAxDiB;AAEjC,MAAMC,qBAAqB;AAC3B,MAAMC,sBAAsB;AAqDrB,SAASF,oBACdG,IAAkB;IAElB,MAAM,EACJC,SAAS,EACTC,iBAAiB,EACjBC,YAAY,EACZC,gBAAgB,EAChBC,cAAc,EACdC,MAAM,EACNC,WAAW,EACXC,gBAAgB,EACjB,GAAGR;IAEJ,IACEK,iBAAiBI,YAAYC,GAAG,KAChCZ,qBAAqBC,qBACrB;QACA,OAAOO;IACT;IAEA,MAAMK,QAAQC,IAAAA,sCAAgB;IAC9B,IAAI,CAACD,OAAO;QACV,OAAOL;IACT;IAEA,IAAIO,cAAcJ,YAAYC,GAAG;IACjC,IAAII;IAEJ,MAAMC,aAAa;QACjB,IAAIR,YAAYS,OAAO,EAAE;YACvB;QACF;QAEA,MAAMC,sBAAsBJ;QAE5B,0EAA0E;QAC1E,uEAAuE;QACvE,uEAAuE;QACvE,WAAW;QACX,MAAMK,yBAAyBb,iBAAiBI,YAAYC,GAAG,KAAK;QAEpEC,MAAM;YACJQ,MAAMlB,UAAUkB,IAAI;YACpBC,OAAOnB,UAAUmB,KAAK;YACtBC,IAAIlB,aAAamB,UAAU;YAC3BC,MAAMpB,aAAaqB,WAAW;YAC9BpB;YACA,wEAAwE;YACxE,2DAA2D;YAC3DqB,SAAS;gBACPC,SAASC,MAAMC,IAAI,CAAC1B,kBAAkBwB,OAAO,CAACG,OAAO;gBACrDC,cAAc5B,kBAAkBwB,OAAO,CAACK,GAAG,CAAC,aAAaC;g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OAAOxC,OAAOkD,WAAW,CACvB,IAAIC,gBAAwC;QAC1CC,WAAUC,KAAK,EAAEC,UAAU;YACzB/C,cAAcJ,YAAYC,GAAG;YAC7BoC;YACAc,WAAWC,OAAO,CAACF;QACrB;IACF;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-wrapper.d.ts b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-wrapper.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc76593264f1fa324b20e0c99a37c176ab462601 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-wrapper.d.ts @@ -0,0 +1,106 @@ +import type { CacheEntry } from '../lib/cache-handlers/types'; +import { type SearchParams } from '../request/search-params'; +import type { Params } from '../request/params'; +import { FALLBACK_PARAMS, RUNTIME_DATA, SESSION_DATA } from '../resume-data-cache/cache-store'; +export type CacheKeyParts = [ + id: string, + args: unknown[], + implementationHash: unknown +]; +export interface UseCachePageProps { + params: Promise; + searchParams: Promise; + $$isPage: true; +} +export type UseCacheLayoutProps = { + params: Promise; + $$isLayout: true; +} & { + [slot: string]: any; +}; +/** + * Cache entry metadata for propagation. Separated from the stream to make + * ownership clear: metadata is freely shareable, streams must be explicitly + * tee'd for each consumer. + */ +interface CacheResultMetadata { + readonly tags: string[]; + readonly revalidate: number; + readonly expire: number; + readonly stale: number; + readonly timestamp: number; + readonly readRootParamNames: ReadonlySet | undefined; + readonly hasExplicitRevalidate: boolean | undefined; + readonly hasExplicitExpire: boolean | undefined; + readonly dynamicNestedCacheError: Error | undefined; +} +/** + * Encapsulates a pending cache invocation for deduping. Manages lazy stream + * tee-ing (via fork()) and metadata access for both intra-request and + * cross-request joiners. + */ +declare class SharedCacheEntry { + private stream; + /** + * Resolves when collection finishes, without waiting for handler writes. + */ + readonly pendingMetadata: Promise; + /** + * Resolves with collected metadata after any handler writes settle. Write + * failures do not discard the metadata. Collection failures still reject this + * promise. + */ + readonly pendingCompletion: Promise; + constructor(stream: ReadableStream, pendingMetadata: Promise, pendingWrite: Promise | undefined); + /** + * Tee the stream: returns a copy for the caller, replaces the internal stream + * with the remaining branch for future callers. Both the leader and joiners + * call this — everyone gets a fork. + */ + fork(): ReadableStream; +} +export type SharedCacheResult = { + readonly type: 'cached'; + readonly entry: SharedCacheEntry; +} | { + readonly type: 'prerender-dynamic'; + readonly reason: typeof FALLBACK_PARAMS | typeof RUNTIME_DATA | typeof SESSION_DATA; + readonly hangingPromise: Promise; +}; +export interface CollectedCacheResult { + entry: CacheEntry; + /** + * Whether the revalidate value was explicitly set via `cacheLife()`. + * - `true`: explicitly set + * - `false`: implicit (propagated from a nested cache or implicitly using the + * default profile) + * - `undefined`: unknown (e.g. pre-existing entry from a cache handler) + */ + hasExplicitRevalidate: boolean | undefined; + /** + * Whether the expire value was explicitly set via `cacheLife()`. + * - `true`: explicitly set + * - `false`: implicit (propagated from a nested cache or implicitly using the + * default profile) + * - `undefined`: unknown (e.g. pre-existing entry from a cache handler) + */ + hasExplicitExpire: boolean | undefined; + /** + * The root param names that were read during cache entry generation. + * Used to compute the specific cache key after generation completes. + * `undefined` for pre-existing entries from cache handlers where we + * don't have this information. + */ + readRootParamNames: ReadonlySet | undefined; + /** + * The `Error` carried up from the first nested public `'use cache'` + * invocation that propagated a dynamic cache life into this entry, captured + * eagerly at that inner invocation's `cache()` entry. Used as `cause` for the + * nested-dynamic cache error so the redbox can point at the inner invocation + * site, not just the outer one. Lives in-memory only — intentionally dropped + * from the serialized RDC because dynamic entries aren't serialized either. + */ + dynamicNestedCacheError: Error | undefined; +} +export declare function cache(kind: string, id: string, boundArgsLength: number, originalFn: (...args: unknown[]) => Promise, args: unknown[]): Promise; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-wrapper.js b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-wrapper.js new file mode 100644 index 0000000000000000000000000000000000000000..801d1f687fecbd774e9601f1dab1526c9d127652 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-wrapper.js @@ -0,0 +1,2689 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "cache", { + enumerable: true, + get: function() { + return cache; + } +}); +const _server = require("react-server-dom-webpack/server"); +const _client = require("react-server-dom-webpack/client"); +const _static = require("react-server-dom-webpack/static"); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _varyparams = require("../app-render/vary-params"); +const _dynamicrenderingutils = require("../dynamic-rendering-utils"); +const _manifestssingleton = require("../app-render/manifests-singleton"); +const _encryption = require("../app-render/encryption"); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _createerrorhandler = require("../app-render/create-error-handler"); +const _stringhash = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/string-hash")); +const _constants = require("./constants"); +const _constants1 = require("../../lib/constants"); +const _handlers = require("./handlers"); +const _clonecacheentry = require("./clone-cache-entry"); +const _approuterheaders = require("../../client/components/app-router-headers"); +const _requestcookies = require("../web/spec-extension/adapters/request-cookies"); +const _headers = require("../web/spec-extension/adapters/headers"); +const _usecacheerrors = require("./use-cache-errors"); +const _usecachemessages = require("./use-cache-messages"); +const _dynamicrendering = require("../app-render/dynamic-rendering"); +const _searchparams = require("../request/search-params"); +const _cachestore = require("../resume-data-cache/cache-store"); +const _lazyresult = require("../lib/lazy-result"); +const _dynamicaccessasyncstorageexternal = require("../app-render/dynamic-access-async-storage.external"); +const _stagedrendering = require("../app-render/staged-rendering"); +const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log")); +const _runtimereactsexternal = require("../runtime-reacts.external"); +const _promisewithresolvers = require("../../shared/lib/promise-with-resolvers"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = { + __proto__: null + }; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +const nextVersion = "16.4.0"; +/** + * Encapsulates a pending cache invocation for deduping. Manages lazy stream + * tee-ing (via fork()) and metadata access for both intra-request and + * cross-request joiners. + */ class SharedCacheEntry { + constructor(stream, pendingMetadata, pendingWrite){ + this.stream = stream; + this.pendingMetadata = pendingMetadata; + this.pendingCompletion = pendingWrite === undefined ? pendingMetadata : pendingWrite.then(()=>pendingMetadata, ()=>pendingMetadata); + } + /** + * Tee the stream: returns a copy for the caller, replaces the internal stream + * with the remaining branch for future callers. Both the leader and joiners + * call this — everyone gets a fork. + */ fork() { + const [forked, remaining] = this.stream.tee(); + this.stream = remaining; + return forked; + } +} +function ignoreReject() {} +/** + * Manages the deferred promise for a shared cache result, tracks which maps + * it's registered in, and drives cleanup from resolve/reject. + * + * Cached results stay in the maps until collection finishes and handler writes + * settle. Later invocations can join while either remains pending. For + * 'prerender-dynamic' and errors, cleanup is immediate. + */ class ResolvableSharedCacheResult { + registerIn(map, key, retentionMap) { + map.set(key, this.deferred.promise); + this.registrations.push({ + map, + key, + retentionMap + }); + } + resolve(result) { + this.deferred.resolve(result); + if (result.type === 'cached') { + // Retain only an entry that collected successfully. A failed collection + // leaves metadata a later invocation cannot read, so it is dropped like + // any other failure and the next invocation regenerates. + result.entry.pendingCompletion.then(()=>this.cleanupAndRetain(), ()=>this.cleanup()); + } else { + this.cleanup(); + } + } + reject(error) { + // The promise stored in the dedup maps has no consumer unless a concurrent + // invocation joined it, so we attach a noop catch handler to prevent the + // rejection from being reported as unhandled. The leader rethrows the + // error into the render, which is where it's surfaced. + this.deferred.promise.catch(ignoreReject); + this.deferred.reject(error); + this.cleanup(); + } + /** + * Drops the pending registrations, leaving nothing for a later invocation to + * join. Used when the invocation produced no entry that a later one could + * serve: an error has no value, and a 'prerender-dynamic' result is a hanging + * promise bound to the leader's render signal. + */ cleanup() { + for (const { map, key } of this.registrations){ + map.delete(key); + } + } + /** + * Drops the pending registrations and moves the entry into the retention map + * where one was given, so a later invocation in the same request can reuse it + * instead of repeating the lookup and, on a miss, the work. + */ cleanupAndRetain() { + for (const { map, key, retentionMap } of this.registrations){ + map.delete(key); + retentionMap == null ? void 0 : retentionMap.set(key, this.deferred.promise); + } + } + constructor(){ + this.deferred = (0, _promisewithresolvers.createPromiseWithResolvers)(); + this.registrations = []; + } +} +/** + * Module-scope map for cross-request deduplication. Keyed by `cacheHandlerKey` + * (specific key on warm path, coarse key on cold path). Entries live only for + * the duration of the leader's invocation. + */ const crossRequestPendingCacheInvocations = new Map(); +// Prevent duplicate background revalidations for the same key until generation +// and cache writes finish. +const backgroundRevalidations = new Map(); +// The first argument at each call site is the full directive that produced +// the invocation, e.g. "'use cache'" or "'use cache: remote'". +const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE ? console.debug.bind(console) : undefined; +const filterStackFrame = process.env.NODE_ENV !== 'production' ? require('../lib/source-maps').filterStackFrameDEV : undefined; +const findSourceMapURL = process.env.NODE_ENV !== 'production' ? require('../lib/source-maps').findSourceMapURLDEV : undefined; +// Tracks which root params each cache function has historically read. Used to +// compute the specific cache key upfront on subsequent invocations. In-memory +// only — after server restart, the coarse-key redirect entry in the cache +// handler provides fallback. +const knownRootParamsByFunctionId = new Map(); +function addKnownRootParamNames(id, names) { + const existing = knownRootParamsByFunctionId.get(id); + if (existing) { + for (const name of names){ + existing.add(name); + } + return existing; + } + const created = new Set(names); + knownRootParamsByFunctionId.set(id, created); + return created; +} +function computeRootParamsCacheKeySuffix(rootParams, paramNames) { + if (paramNames.size === 0) { + return ''; + } + return JSON.stringify([ + ...paramNames + ].sort().map((paramName)=>[ + paramName, + rootParams[paramName] + ])); +} +// Next-internal cookies that must not vary the private cache key, since they're +// not part of the application's own cookie state. The instant-navigation cookie +// toggles while a navigation lock is held, so including it would force spurious +// misses. +const COOKIES_EXCLUDED_FROM_PRIVATE_CACHE_KEY = new Set([ + _approuterheaders.NEXT_INSTANT_TEST_COOKIE +]); +// Request and transport headers that must not vary the private cache key. They +// either differ between otherwise-equivalent requests, which would cause +// spurious misses (a browser reload adds `cache-control`/`pragma` that an +// initial navigation doesn't, and `accept`/`sec-fetch-*` differ between an HTML +// navigation and an RSC or prefetch request for the same page), or are +// connection- and proxy-level rather than application data. The `cookie` header +// is excluded because cookies are keyed separately below (via the dedicated +// cookie path, which applies `COOKIES_EXCLUDED_FROM_PRIVATE_CACHE_KEY`); +// including the raw header would duplicate them and reintroduce the cookies +// that path excludes. Header names are lowercased by `HeadersAdapter`, so every +// entry here is lowercase. +const HEADERS_EXCLUDED_FROM_PRIVATE_CACHE_KEY = new Set([ + 'accept', + 'accept-encoding', + 'cache-control', + 'connection', + 'cookie', + 'if-match', + 'if-modified-since', + 'if-none-match', + 'if-range', + 'if-unmodified-since', + 'keep-alive', + 'pragma', + 'priority', + 'purpose', + 'range', + 'sec-fetch-dest', + 'sec-fetch-mode', + 'sec-fetch-site', + 'sec-fetch-user', + 'sec-purpose', + 'te', + 'upgrade', + 'upgrade-insecure-requests', + 'x-forwarded-for', + 'x-forwarded-host', + 'x-forwarded-port', + 'x-forwarded-proto' +]); +// TODO: This varies the dev private cache key by the request's cookies and +// headers (minus the transport and content-negotiation headers excluded above). +// It's a heuristic: it still over-keys (a cache that reads only one cookie or +// header varies by all of them) and the header denylist is necessarily +// incomplete. Follow up by tracking which cookies and headers a cache function +// actually reads (the same mechanism root params use via `readRootParamNames`) +// and keying by only those. Note that Next-internal flight headers such as +// `rsc` and `next-router-state-tree` are already stripped upstream in +// `getHeaders`, so they never appear here. +function computePrivateCacheKeyRequestSuffix(cookies, headers) { + const relevantCookies = cookies.getAll().filter((cookie)=>!COOKIES_EXCLUDED_FROM_PRIVATE_CACHE_KEY.has(cookie.name)).map((cookie)=>[ + cookie.name, + cookie.value + ]).sort(([nameA], [nameB])=>nameA < nameB ? -1 : nameA > nameB ? 1 : 0); + const relevantHeaders = [ + ...headers.entries() + ].filter(([name])=>!HEADERS_EXCLUDED_FROM_PRIVATE_CACHE_KEY.has(name)).sort(([nameA], [nameB])=>nameA < nameB ? -1 : nameA > nameB ? 1 : 0); + if (relevantCookies.length === 0 && relevantHeaders.length === 0) { + return ''; + } + return JSON.stringify({ + cookies: relevantCookies, + headers: relevantHeaders + }); +} +function saveToResumeDataCache(resumeDataCache, serializedCacheKey, pendingCacheResult, logPrefix) { + if (!(resumeDataCache == null ? void 0 : resumeDataCache.mutable)) { + return pendingCacheResult; + } + const split = clonePendingCacheResult(pendingCacheResult); + const savedCacheResult = getNthCacheResult(split, 0); + const rdcResult = getNthCacheResult(split, 1); + // The RDC is per-page and root params are fixed within a page, so we always + // use the coarse key (without root param suffix). Unlike the cache handler, + // the RDC doesn't need root-param-specific keys for isolation. + resumeDataCache.cache.set(serializedCacheKey, rdcResult); + debug == null ? void 0 : debug(logPrefix, 'Resume Data Cache entry saved', serializedCacheKey); + return savedCacheResult; +} +/** + * A joiner's RDC context may differ from the leader's: + * + * - Intra-request: the leader was nested inside another cache (no accessible + * RDC) while this joiner is top-level and has one. + * - Cross-request: the leader belongs to a different request entirely — this + * request's RDC has never seen the entry. + * + * In both cases the joiner must save to its own RDC so its final prerender can + * resume from the entry. Constructs a `CollectedCacheResult` from a forked + * stream branch of the shared entry and the awaited metadata. + * + * An existing entry avoids redundant saves when the intra-request leader + * already saved to the same RDC. A marker, however, can be replaced by a + * successful fill. + */ function saveSharedCacheEntryToResumeDataCache(serializedCacheKey, sharedCacheEntry, resumeDataCache, logPrefix) { + if (!(resumeDataCache == null ? void 0 : resumeDataCache.mutable)) { + return; + } + const existingEntry = resumeDataCache.cache.get(serializedCacheKey); + if (existingEntry !== undefined && existingEntry !== _cachestore.FALLBACK_PARAMS && existingEntry !== _cachestore.RUNTIME_DATA && existingEntry !== _cachestore.SESSION_DATA) { + return; + } + const rdcResult = sharedCacheEntry.pendingMetadata.then((metadata)=>({ + entry: { + value: sharedCacheEntry.fork(), + tags: metadata.tags, + revalidate: metadata.revalidate, + expire: metadata.expire, + stale: metadata.stale, + timestamp: metadata.timestamp + }, + readRootParamNames: metadata.readRootParamNames, + hasExplicitRevalidate: metadata.hasExplicitRevalidate, + hasExplicitExpire: metadata.hasExplicitExpire, + dynamicNestedCacheError: metadata.dynamicNestedCacheError + })); + resumeDataCache.cache.set(serializedCacheKey, rdcResult); + debug == null ? void 0 : debug(logPrefix, 'Resume Data Cache entry saved by joiner', serializedCacheKey); +} +/** + * Completes a join onto another invocation's entry, whether that invocation is + * still filling or has already finished: forks the stream, saves to this + * invocation's RDC if the leader had none, and balances the cache signal read + * once the entry is fully collected. + */ function serveJoinedCacheEntry(sharedCacheEntry, serializedCacheKey, resumeDataCache, cacheContext, cacheSignal, logPrefix) { + const stream = sharedCacheEntry.fork(); + // If the leader was nested inside another cache (no accessible RDC), it + // couldn't save to the RDC. This joiner may be top-level with an RDC, in + // which case it must save here; otherwise the RDC lookup during the final + // prerender will miss. + saveSharedCacheEntryToResumeDataCache(serializedCacheKey, sharedCacheEntry, resumeDataCache, logPrefix); + // End the cache read after collection and metadata propagation, not when the + // value stream becomes available. This does not wait for handler persistence. + // A failed collection or propagation must still end the read so it cannot + // stall prerendering. The catch prevents an unhandled rejection after the + // stream has been returned. + sharedCacheEntry.pendingMetadata.then((metadata)=>{ + maybePropagateCacheEntryMetadata(cacheContext, metadata); + }).finally(()=>{ + cacheSignal == null ? void 0 : cacheSignal.endRead(); + }).catch(ignoreReject); + return stream; +} +function saveToCacheHandler(cacheHandler, id, cacheHandlerKeyBase, savedCacheResult, rootParams) { + // Write the entry to the cache handler. With root params, this is a redirect + // entry at the coarse key plus the actual entry at the specific key; + // otherwise just the entry at the coarse key. Both set calls are fired + // together and awaited in parallel. + return savedCacheResult.then(async (collectedResult)=>{ + const { entry: fullEntry, readRootParamNames } = collectedResult; + // Use the combined set (union of all historically observed reads) for both + // the specific key and the redirect entry's tags. The read path computes + // cacheHandlerKey from this same union (knownRootParamsByFunctionId), so + // the write path must use the identical set to land on the same specific + // key. If we used only the current invocation's reads, a function that + // conditionally reads different root params across invocations would + // scatter entries across different specific keys, making previous entries + // unreachable from the read path's union-based lookup. + const rootParamNames = readRootParamNames ? addKnownRootParamNames(id, readRootParamNames) : knownRootParamsByFunctionId.get(id); + const setPromises = []; + let coarseEntry = fullEntry; + if (rootParamNames && rootParamNames.size > 0 && rootParams) { + const specificKey = cacheHandlerKeyBase + computeRootParamsCacheKeySuffix(rootParams, rootParamNames); + setPromises.push(// Capture synchronous `set()` throws as rejected write promises. + new Promise((resolve)=>{ + resolve(cacheHandler.set(specificKey, Promise.resolve(fullEntry))); + })); + // The coarse key gets a redirect entry instead. On a cold server (empty + // knownRootParamsByFunctionId), its tags tell a reader which root params + // to include in the specific-key lookup. + const rootParamTags = [ + ...rootParamNames + ].map((paramName)=>_constants1.NEXT_CACHE_ROOT_PARAM_TAG_ID + paramName); + coarseEntry = { + value: new ReadableStream({ + start (controller) { + // Single byte so the entry has non-zero size in LRU caches. + controller.enqueue(new Uint8Array([ + 0 + ])); + controller.close(); + } + }), + tags: [ + ...fullEntry.tags, + ...rootParamTags + ], + stale: fullEntry.stale, + timestamp: fullEntry.timestamp, + expire: fullEntry.expire, + revalidate: fullEntry.revalidate + }; + } + setPromises.push(// Capture synchronous `set()` throws as rejected write promises. + new Promise((resolve)=>{ + resolve(cacheHandler.set(cacheHandlerKeyBase, Promise.resolve(coarseEntry))); + })); + // A failed write must not finish the operation while another write is + // pending. + for (const result of (await Promise.allSettled(setPromises))){ + if (result.status === 'rejected') { + throw result.reason; + } + } + }); +} +function generateCacheEntry(workStore, cacheContext, clientReferenceManifest, encodedArguments, fn, timeoutError, deadlockError) { + // We need to run this inside a clean AsyncLocalStorage snapshot so that the cache + // generation cannot read anything from the context we're currently executing which + // might include request specific things like cookies() inside a React.cache(). + // Note: It is important that we await at least once before this because it lets us + // pop out of any stack specific contexts as well - aka "Sync" Local Storage. + return workStore.runInCleanSnapshot(generateCacheEntryWithRestoredWorkStore, workStore, cacheContext, clientReferenceManifest, encodedArguments, fn, timeoutError, deadlockError); +} +function generateCacheEntryWithRestoredWorkStore(workStore, cacheContext, clientReferenceManifest, encodedArguments, fn, timeoutError, deadlockError) { + // Since we cleared the AsyncLocalStorage we need to restore the workStore. + // Note: We explicitly don't restore the RequestStore nor the PrerenderStore. + // We don't want any request specific information leaking an we don't want to create a + // bloated fake request mock for every cache call. So any feature that currently lives + // in RequestStore but should be available to Caches need to move to WorkStore. + // PrerenderStore is not needed inside the cache scope because the outer most one will + // be the one to report its result to the outer Prerender. + return _workasyncstorageexternal.workAsyncStorage.run(workStore, generateCacheEntryWithCacheContext, workStore, cacheContext, clientReferenceManifest, encodedArguments, fn, timeoutError, deadlockError); +} +function createUseCacheStore(workStore, cacheContext, defaultCacheLife) { + if (cacheContext.kind === 'private') { + const outerWorkUnitStore = cacheContext.outerWorkUnitStore; + return { + type: 'private-cache', + phase: 'render', + consumerWillServerCache: true, + implicitTags: outerWorkUnitStore == null ? void 0 : outerWorkUnitStore.implicitTags, + revalidate: defaultCacheLife.revalidate, + expire: defaultCacheLife.expire, + stale: defaultCacheLife.stale, + explicitRevalidate: undefined, + explicitExpire: undefined, + explicitStale: undefined, + tags: null, + hmrRefreshHash: (0, _workunitasyncstorageexternal.getHmrRefreshHash)(outerWorkUnitStore), + isHmrRefresh: (0, _workunitasyncstorageexternal.isHmrRefresh)(outerWorkUnitStore), + serverComponentsHmrCache: (0, _workunitasyncstorageexternal.getServerComponentsHmrCache)(outerWorkUnitStore), + forceRevalidate: shouldForceRevalidate(workStore, outerWorkUnitStore), + draftMode: (0, _workunitasyncstorageexternal.getDraftModeProviderForCacheScope)(workStore, outerWorkUnitStore), + rootParams: outerWorkUnitStore.rootParams, + readRootParamNames: new Set(), + // Every private cache scope is its own work unit. Any cache keyed on + // headers() or cookies() needs to be invalidated. Otherwise some + // Next.js API semantics leak across render passes. + headers: _headers.HeadersAdapter.fresh(outerWorkUnitStore.headers), + cookies: _requestcookies.RequestCookiesAdapter.fresh(outerWorkUnitStore.cookies), + outerOwnerStack: cacheContext.outerOwnerStack + }; + } else { + let useCacheOrRequestStore; + const outerWorkUnitStore = cacheContext.outerWorkUnitStore; + switch(outerWorkUnitStore.type){ + case 'cache': + case 'private-cache': + case 'request': + useCacheOrRequestStore = outerWorkUnitStore; + break; + case 'prerender-runtime': + case 'prerender': + case 'prerender-legacy': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + outerWorkUnitStore; + } + let fallbackRootParamsPrerender = null; + if (outerWorkUnitStore.type === 'cache') { + fallbackRootParamsPrerender = outerWorkUnitStore.fallbackRootParamsPrerender; + } else if (outerWorkUnitStore.type === 'prerender') { + const { fallbackRouteParams } = outerWorkUnitStore; + if (fallbackRouteParams !== null && Object.keys(outerWorkUnitStore.rootParams).some((name)=>fallbackRouteParams.has(name))) { + fallbackRootParamsPrerender = outerWorkUnitStore; + } + } + return { + type: 'cache', + phase: 'render', + fallbackRootParamsPrerender, + consumerWillServerCache: true, + implicitTags: outerWorkUnitStore.implicitTags, + revalidate: defaultCacheLife.revalidate, + expire: defaultCacheLife.expire, + stale: defaultCacheLife.stale, + explicitRevalidate: undefined, + explicitExpire: undefined, + explicitStale: undefined, + tags: null, + hmrRefreshHash: (0, _workunitasyncstorageexternal.getHmrRefreshHash)(outerWorkUnitStore), + isHmrRefresh: (useCacheOrRequestStore == null ? void 0 : useCacheOrRequestStore.isHmrRefresh) ?? false, + serverComponentsHmrCache: useCacheOrRequestStore == null ? void 0 : useCacheOrRequestStore.serverComponentsHmrCache, + forceRevalidate: shouldForceRevalidate(workStore, outerWorkUnitStore), + draftMode: (0, _workunitasyncstorageexternal.getDraftModeProviderForCacheScope)(workStore, outerWorkUnitStore), + rootParams: outerWorkUnitStore.rootParams, + readRootParamNames: new Set(), + outerOwnerStack: cacheContext.outerOwnerStack, + dynamicNestedCacheError: undefined + }; + } +} +/** + * Captures the owner stack from the outer component tree before entering a + * cache boundary. When nested inside another cache scope, the parent's + * outerOwnerStack is concatenated so that the full component tree is preserved + * across multiple cache boundaries. + */ function captureOuterOwnerStack(workUnitStore) { + var _getClientReact_captureOwnerStack, _getClientReact, _getServerReact_captureOwnerStack, _getServerReact; + const capturedOwnerStack = (((_getClientReact = (0, _runtimereactsexternal.getClientReact)()) == null ? void 0 : (_getClientReact_captureOwnerStack = _getClientReact.captureOwnerStack) == null ? void 0 : _getClientReact_captureOwnerStack.call(_getClientReact)) ?? ((_getServerReact = (0, _runtimereactsexternal.getServerReact)()) == null ? void 0 : (_getServerReact_captureOwnerStack = _getServerReact.captureOwnerStack) == null ? void 0 : _getServerReact_captureOwnerStack.call(_getServerReact))) || ''; + let parentOuterOwnerStack; + switch(workUnitStore.type){ + case 'cache': + case 'private-cache': + parentOuterOwnerStack = workUnitStore.outerOwnerStack; + break; + case 'unstable-cache': + case 'request': + case 'prerender': + case 'prerender-legacy': + case 'prerender-runtime': + case 'prerender-client': + case 'validation-client': + case 'build-time-generator': + break; + default: + workUnitStore; + } + return capturedOwnerStack + (parentOuterOwnerStack || '') || undefined; +} +// The maximum time we allow a `'use cache'` entry to fill. After this, we +// assume the fill is stalled — either on hanging input to the cached function, +// or on hanging I/O inside of it — and de-opt with an error. +// +// For prerender, the effective value is clamped to 90% of the configured +// `staticPageGenerationTimeout` so the cache-fill error surfaces before the +// build worker kills the page. In dev (`request`), the configured +// `experimental.useCacheTimeout` is used straight. +function getUseCacheFillTimeoutMs(workStore, workUnitStoreType) { + const { useCacheTimeout, staticPageGenerationTimeout } = workStore; + const effectiveTimeout = workUnitStoreType === 'request' ? useCacheTimeout : Math.min(useCacheTimeout, staticPageGenerationTimeout * 0.9); + return effectiveTimeout * 1000; +} +function generateCacheEntryWithCacheContext(workStore, cacheContext, clientReferenceManifest, encodedArguments, fn, timeoutError, deadlockError) { + const defaultCacheLife = workStore.cacheLifeProfiles.default; + // Initialize the Store for this Cache entry. + const cacheStore = createUseCacheStore(workStore, cacheContext, defaultCacheLife); + return _workunitasyncstorageexternal.workUnitAsyncStorage.run(cacheStore, ()=>_dynamicaccessasyncstorageexternal.dynamicAccessAsyncStorage.run({ + abortController: new AbortController(), + reason: null + }, generateCacheEntryImpl, workStore, cacheContext, cacheStore, clientReferenceManifest, encodedArguments, fn, timeoutError, deadlockError)); +} +function propagateCacheLifeAndTagsToRevalidateStore(revalidateStore, metadata) { + const outerTags = revalidateStore.tags ??= []; + for (const tag of metadata.tags){ + if (!outerTags.includes(tag)) { + outerTags.push(tag); + } + } + if (revalidateStore.stale > metadata.stale) { + revalidateStore.stale = metadata.stale; + } + if (revalidateStore.revalidate > metadata.revalidate) { + revalidateStore.revalidate = metadata.revalidate; + } + if (revalidateStore.expire > metadata.expire) { + revalidateStore.expire = metadata.expire; + } +} +function propagateCacheStaleTimeToRequestStore(requestStore, metadata) { + if (requestStore.stale !== undefined && requestStore.stale > metadata.stale) { + requestStore.stale = metadata.stale; + } +} +function propagateCacheEntryMetadata(cacheContext, metadata) { + if (cacheContext.kind === 'private') { + switch(cacheContext.outerWorkUnitStore.type){ + case 'private-cache': + if (metadata.readRootParamNames) { + for (const paramName of metadata.readRootParamNames){ + cacheContext.outerWorkUnitStore.readRootParamNames.add(paramName); + } + } + // fallthrough + case 'prerender-runtime': + propagateCacheLifeAndTagsToRevalidateStore(cacheContext.outerWorkUnitStore, metadata); + break; + case 'request': + propagateCacheStaleTimeToRequestStore(cacheContext.outerWorkUnitStore, metadata); + break; + case undefined: + break; + default: + cacheContext.outerWorkUnitStore; + } + } else { + switch(cacheContext.outerWorkUnitStore.type){ + case 'cache': + // If this entry's cache life is dynamic, record this invocation as the + // origin to use as `cause` when the outer cache surfaces the + // nested-dynamic cache error. `??=` keeps the first occurrence so the + // cause points at the immediate dynamic child. + if (cacheContext.dynamicNestedCacheError !== undefined && (metadata.revalidate === 0 || metadata.expire < _constants.MIN_PRERENDERABLE_EXPIRE)) { + cacheContext.outerWorkUnitStore.dynamicNestedCacheError ??= cacheContext.dynamicNestedCacheError; + } + // fallthrough + case 'private-cache': + if (metadata.readRootParamNames) { + for (const paramName of metadata.readRootParamNames){ + cacheContext.outerWorkUnitStore.readRootParamNames.add(paramName); + } + } + // fallthrough + case 'prerender': + case 'prerender-runtime': + case 'prerender-legacy': + propagateCacheLifeAndTagsToRevalidateStore(cacheContext.outerWorkUnitStore, metadata); + break; + case 'request': + propagateCacheStaleTimeToRequestStore(cacheContext.outerWorkUnitStore, metadata); + break; + case 'unstable-cache': + case 'build-time-generator': + break; + default: + cacheContext.outerWorkUnitStore; + } + } + if (metadata.readRootParamNames) { + const varyParamsAccumulator = (0, _workunitasyncstorageexternal.getVaryParamsAccumulator)(cacheContext.outerWorkUnitStore); + if (varyParamsAccumulator) { + for (const paramName of metadata.readRootParamNames){ + (0, _varyparams.accumulateVaryParam)(varyParamsAccumulator.rootParams, paramName); + } + } + } +} +/** + * Conditionally propagates cache life, tags, and root param names to the outer + * context. During prerenders (`prerender` / `prerender-runtime`) and dev + * cache-filling requests, propagation is deferred because the entry might be + * omitted from the final prerender due to short expire/stale times. If omitted, + * it should not affect the prerender. The final decision happens when the entry + * is read from the resume data cache in the final render phase — at that point + * `propagateCacheEntryMetadata` is called unconditionally (after the omission + * checks have already filtered out short-lived entries). + * + * Nested caches propagate root param names into the enclosing cache's + * `readRootParamNames` set. This propagation is never deferred. Prerender + * contexts also register known root param names when they read the resume + * data cache. A response accumulator records the consumed entry's root vary + * params to prevent segment reuse across different values. + */ function maybePropagateCacheEntryMetadata(cacheContext, metadata) { + const outerWorkUnitStore = cacheContext.outerWorkUnitStore; + switch(outerWorkUnitStore.type){ + case 'prerender': + case 'prerender-runtime': + { + break; + } + case 'request': + { + if (isValidationRender(outerWorkUnitStore) && outerWorkUnitStore.cacheSignal) { + break; + } + // fallthrough + } + case 'private-cache': + case 'cache': + case 'unstable-cache': + case 'prerender-legacy': + { + propagateCacheEntryMetadata(cacheContext, metadata); + break; + } + case 'build-time-generator': + break; + default: + { + outerWorkUnitStore; + } + } +} +async function collectResult(savedStream, workStore, cacheContext, innerCacheStore, startTime, errors) { + // We create a buffered stream that collects all chunks until the end to + // ensure that RSC has finished rendering and therefore we have collected + // all tags. In the future the RSC API might allow for the equivalent of + // the allReady Promise that exists on SSR streams. + // + // If something errored or rejected anywhere in the render, we close + // the stream as errored. This lets a CacheHandler choose to save the + // partial result up until that point for future hits for a while to avoid + // unnecessary retries or not to retry. We use the end of the stream for + // this to avoid another complicated side-channel. A receiver has to consider + // that the stream might also error for other reasons anyway such as losing + // connection. + const buffer = []; + const reader = savedStream.getReader(); + try { + for(let entry; !(entry = await reader.read()).done;){ + buffer.push(entry.value); + } + } catch (error) { + errors.push(error); + } + let idx = 0; + const bufferStream = new ReadableStream({ + pull (controller) { + if (workStore.invalidDynamicUsageError) { + controller.error(workStore.invalidDynamicUsageError); + } else if (idx < buffer.length) { + controller.enqueue(buffer[idx++]); + } else if (errors.length > 0) { + // TODO: Should we use AggregateError here? + controller.error(errors[0]); + } else { + controller.close(); + } + } + }); + const collectedTags = innerCacheStore.tags; + const isPrivateCacheInDev = Boolean(process.env.__NEXT_DEV_SERVER && cacheContext.kind === 'private'); + // In development, force a dynamic cache life (`revalidate: 0`, `expire: + // MIN_PRERENDERABLE_EXPIRE`) for private caches, which have no real backing + // handler. The zero revalidate makes every read serve stale-while-revalidate + // (regenerating a fresh entry in the background), and + // `MIN_PRERENDERABLE_EXPIRE` (5 minutes) caps how long an entry lingers in + // the dedicated in-memory private handler. It is the shortest `expire` that + // isn't treated as dynamic; a smaller `expire` would exclude the entry from + // prerenders. Two other cases deliberately do NOT force this and keep their + // resolved cache life, relying instead on the dev handler's minimum retention + // and a dev revalidation (see the cache-hit path below) to keep reloads fast + // and fresh. The size-0 case (`cacheMaxMemorySize: 0`) keeps its life so the + // entry can be considered prerenderable instead of being misread as a dynamic + // hole. An explicit short-`expire` public cache (e.g. `cacheLife({ expire: 0 + // })`) keeps its life so it stays correctly excluded from static prerenders + // via its real `expire` while a reload still hits the cache; forcing + // `revalidate: 0` here would instead corrupt the cache life propagated to an + // enclosing cache and trigger the nested-dynamic error. A cache backed by a + // custom handler keeps its real cache life too, since that handler owns it. + const forceDynamicCacheLifeInDev = isPrivateCacheInDev; + // If cacheLife() was used to set an explicit revalidate/expire/stale time we + // use that. Otherwise, we use the lowest of all inner fetch(), + // unstable_cache() or nested "use cache", if they're lower than our default. + const collectedRevalidate = forceDynamicCacheLifeInDev ? 0 : innerCacheStore.explicitRevalidate !== undefined ? innerCacheStore.explicitRevalidate : innerCacheStore.revalidate; + const collectedExpire = forceDynamicCacheLifeInDev ? _constants.MIN_PRERENDERABLE_EXPIRE : innerCacheStore.explicitExpire !== undefined ? innerCacheStore.explicitExpire : innerCacheStore.expire; + const collectedStale = innerCacheStore.explicitStale !== undefined ? innerCacheStore.explicitStale : innerCacheStore.stale; + const entry = { + value: bufferStream, + timestamp: startTime, + revalidate: collectedRevalidate, + expire: collectedExpire, + stale: collectedStale, + tags: collectedTags === null ? [] : collectedTags + }; + const collected = { + entry, + hasExplicitRevalidate: innerCacheStore.explicitRevalidate !== undefined, + hasExplicitExpire: innerCacheStore.explicitExpire !== undefined, + readRootParamNames: innerCacheStore.readRootParamNames, + // The store accumulates this from nested public caches that propagated a + // dynamic life into us. + dynamicNestedCacheError: innerCacheStore.type === 'cache' ? innerCacheStore.dynamicNestedCacheError : undefined + }; + if (!cacheContext.skipPropagation) { + maybePropagateCacheEntryMetadata(cacheContext, { + tags: collected.entry.tags, + revalidate: collected.entry.revalidate, + expire: collected.entry.expire, + stale: collected.entry.stale, + timestamp: collected.entry.timestamp, + hasExplicitRevalidate: collected.hasExplicitRevalidate, + hasExplicitExpire: collected.hasExplicitExpire, + readRootParamNames: collected.readRootParamNames, + dynamicNestedCacheError: collected.dynamicNestedCacheError + }); + const cacheSignal = (0, _workunitasyncstorageexternal.getCacheSignal)(cacheContext.outerWorkUnitStore); + if (cacheSignal) { + cacheSignal.endRead(); + } + } + return collected; +} +async function generateCacheEntryImpl(workStore, cacheContext, innerCacheStore, clientReferenceManifest, encodedArguments, fn, timeoutError, deadlockError) { + const temporaryReferences = (0, _server.createTemporaryReferenceSet)(); + const outerWorkUnitStore = cacheContext.outerWorkUnitStore; + const [, args] = typeof encodedArguments === 'string' ? await (0, _server.decodeReply)(encodedArguments, (0, _manifestssingleton.getServerModuleMap)(), { + temporaryReferences + }) : await (0, _server.decodeReplyFromAsyncIterable)({ + async *[Symbol.asyncIterator] () { + for (const entry of encodedArguments){ + yield entry; + } + switch(outerWorkUnitStore.type){ + case 'prerender-runtime': + case 'prerender': + // The encoded arguments might contain hanging promises. In + // this case we don't want to reject with "Error: Connection + // closed.", so we intentionally keep the iterable alive. This + // is similar to the halting trick that we do while rendering. + await new Promise((resolve)=>{ + if (outerWorkUnitStore.renderSignal.aborted) { + resolve(); + } else { + outerWorkUnitStore.renderSignal.addEventListener('abort', ()=>resolve(), { + once: true + }); + } + }); + break; + case 'prerender-legacy': + case 'request': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + outerWorkUnitStore; + } + } + }, (0, _manifestssingleton.getServerModuleMap)(), { + temporaryReferences + }); + // Track the timestamp when we started computing the result. + const startTime = performance.timeOrigin + performance.now(); + // Invoke the inner function to load a new result. We delay the invocation + // though, until React awaits the promise so that React's request store (ALS) + // is available when the function is invoked. This allows us, for example, to + // capture logs so that we can later replay them. + const resultPromise = (0, _lazyresult.createLazyResult)(fn.bind(null, ...args)); + const errors = []; + // In the "Cache" environment, we only need to make sure that the error + // digests are handled correctly. Error formatting and reporting is not + // necessary here; the errors are encoded in the stream, and will be reported + // in the "Server" environment. + const handleError = (0, _createerrorhandler.createReactServerErrorHandler)(process.env.NODE_ENV === 'development', workStore.isBuildTimePrerendering ?? false, workStore.reactServerErrorsByDigest, (error)=>{ + // In production, we log the original error here. It gets a digest that + // can be used to associate the error with the obfuscated error that might + // be logged if the error is caught. In development, we prefer logging the + // transported error in the server environment. It's not obfuscated and + // also includes the (dev-only) environment name. + if (process.env.NODE_ENV === 'production') { + _log.error(error); + } + errors.push(error); + }); + let stream; + let devTimeoutAbortController; + switch(outerWorkUnitStore.type){ + case 'cache': + case 'prerender-runtime': + case 'prerender': + { + const prerenderStore = outerWorkUnitStore.type === 'cache' ? outerWorkUnitStore.fallbackRootParamsPrerender : outerWorkUnitStore; + if (prerenderStore === null) { + stream = (0, _server.renderToReadableStream)(resultPromise, clientReferenceManifest.clientModules, { + environmentName: 'Cache', + filterStackFrame, + temporaryReferences, + onError: handleError + }); + break; + } + const timeoutAbortController = new AbortController(); + const timer = setTimeout(()=>{ + workStore.invalidDynamicUsageError = timeoutError; + timeoutAbortController.abort(timeoutError); + }, getUseCacheFillTimeoutMs(workStore, prerenderStore.type)); + const dynamicAccessStore = _dynamicaccessasyncstorageexternal.dynamicAccessAsyncStorage.getStore(); + const dynamicAccessAbortSignal = dynamicAccessStore == null ? void 0 : dynamicAccessStore.abortController.signal; + const abortSignal = dynamicAccessAbortSignal ? AbortSignal.any([ + dynamicAccessAbortSignal, + timeoutAbortController.signal + ]) : timeoutAbortController.signal; + const { prelude } = await (0, _static.prerender)(resultPromise, clientReferenceManifest.clientModules, { + environmentName: 'Cache', + filterStackFrame, + signal: abortSignal, + temporaryReferences, + onError (error) { + if (abortSignal.aborted && abortSignal.reason === error) { + return undefined; + } + return handleError(error); + } + }); + clearTimeout(timer); + const didTimeout = timeoutAbortController.signal.aborted; + if (dynamicAccessAbortSignal) { + // Release React's listener from the composite signal. + timeoutAbortController.abort(); + } + if (didTimeout) { + // When the timeout is reached we always error the stream. Even for + // fallback shell prerenders we don't want to return a hanging promise, + // which would allow the function to become a dynamic hole. Because that + // would mean that a non-empty shell could be generated which would be + // subject to revalidation, and we don't want to create long + // revalidation times. + stream = new ReadableStream({ + start (controller) { + controller.error(timeoutAbortController.signal.reason); + } + }); + } else if (dynamicAccessAbortSignal == null ? void 0 : dynamicAccessAbortSignal.aborted) { + var _getCacheSignal; + const reason = (dynamicAccessStore == null ? void 0 : dynamicAccessStore.reason) ?? 'runtime'; + const makeHangingPromise = reason === 'fallback-params' ? _dynamicrenderingutils.makeFallbackParamsHangingPromise : _dynamicrenderingutils.makeURLDataHangingPromise; + if (innerCacheStore.type === 'cache' && innerCacheStore.fallbackRootParamsPrerender !== null) { + var _getCacheSignal1; + // No entry is collected for an aborted fill. Still remember the + // roots actually read so a concrete request won't join this result + // under the coarse key. Propagate them through aborted parents too. + addKnownRootParamNames(cacheContext.functionId, innerCacheStore.readRootParamNames); + const hangingPromise = (0, _dynamicrenderingutils.trackPromiseUsed)(makeHangingPromise(prerenderStore.renderSignal, workStore.route, 'dynamic "use cache"', // The single wrapper below tracks access when consumed. + null), ()=>{ + if (reason === 'fallback-params') { + (0, _dynamicrenderingutils.trackFallbackParamsAccessed)(prerenderStore, 'dynamic "use cache"'); + } else { + (0, _dynamicrenderingutils.trackURLDataAccessed)(prerenderStore, 'dynamic "use cache"'); + } + // The result may also be consumed by a deduped invocation, so + // record dependencies against the cache consuming it now. + const consumer = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (consumer !== undefined && consumer.type === 'cache') { + for (const name of innerCacheStore.readRootParamNames){ + consumer.readRootParamNames.add(name); + } + } + // Only a cache consuming this result must suspend. Do not share + // cancellation with independent sibling cache fills. + (0, _dynamicaccessasyncstorageexternal.abortOnDynamicAccess)(reason, dynamicAccessAbortSignal.reason); + }); + (_getCacheSignal1 = (0, _workunitasyncstorageexternal.getCacheSignal)(outerWorkUnitStore)) == null ? void 0 : _getCacheSignal1.endRead(); + return { + type: 'prerender-dynamic', + reason: reason === 'fallback-params' ? _cachestore.FALLBACK_PARAMS : _cachestore.RUNTIME_DATA, + hangingPromise + }; + } + // If the prerender is aborted because of dynamic access (e.g. reading + // fallback params), we return a hanging promise. This essentially makes + // the "use cache" function dynamic. + const hangingPromise = makeHangingPromise(prerenderStore.renderSignal, workStore.route, 'dynamic "use cache"', outerWorkUnitStore); + (_getCacheSignal = (0, _workunitasyncstorageexternal.getCacheSignal)(outerWorkUnitStore)) == null ? void 0 : _getCacheSignal.endRead(); + return { + type: 'prerender-dynamic', + reason: reason === 'fallback-params' ? _cachestore.FALLBACK_PARAMS : _cachestore.RUNTIME_DATA, + hangingPromise + }; + } else { + stream = prelude; + } + break; + } + case 'request': + // TODO: We should just check if the render is abandonable. This is + // relevant in restart-on-cache-miss in general, so when we implement that + // for cached navs, it'll also be needed in prod + if (process.env.__NEXT_DEV_SERVER && outerWorkUnitStore.cacheSignal) { + const stagedRendering = outerWorkUnitStore.stagedRendering; + // Capture the render stage at the start of this cache read, before the + // yield below. A streamed staged render advances its controller on its + // own schedule, independently of this read, so by the time the yield + // resolves the controller may have raced ahead to the Dynamic stage even + // though the read began in an earlier (prerender) stage. + const stageAtReadStart = stagedRendering == null ? void 0 : stagedRendering.currentStage; + // If we're filling caches for a staged render, make sure that it takes + // at least a task, so we'll always notice a cache miss between stages. + // + // TODO(restart-on-cache-miss): This is suboptimal. Ideally microtasky + // caches wouldn't register as a miss, but short-lived caches are only + // omitted correctly when read back in a separate render (now the + // background validation render, not a restart of the streamed + // response), so forcing the miss is the best we can do until that's + // refactored. + await new Promise((resolve)=>setTimeout(resolve)); + // Start a cache-fill timeout so a hanging `'use cache'` entry surfaces + // the same error in dev as during prerender. Cleared when + // pendingCacheResult settles. + // + // Skip the timeout only when the read began in the Dynamic stage, which + // mirrors prerender: a cache guarded by e.g. `await connection()` is a + // legitimate dynamic hole and isn't executed there. We use the stage + // captured at read start, not the current one, because the staged render + // may have advanced past it during the yield above. + if (stageAtReadStart !== _stagedrendering.RenderStage.Dynamic) { + const devRenderAbortController = new AbortController(); + const fillTimeoutMs = getUseCacheFillTimeoutMs(workStore, outerWorkUnitStore.type); + const fillDeadlineAt = performance.now() + fillTimeoutMs; + const devRenderTimeoutTimer = setTimeout(()=>{ + workStore.invalidDynamicUsageError = timeoutError; + devRenderAbortController.abort(timeoutError); + }, fillTimeoutMs); + devTimeoutAbortController = new AbortController(); + devTimeoutAbortController.signal.addEventListener('abort', ()=>{ + clearTimeout(devRenderTimeoutTimer); + }, { + once: true + }); + stream = (0, _server.renderToReadableStream)(resultPromise, clientReferenceManifest.clientModules, { + environmentName: 'Cache', + filterStackFrame, + signal: devRenderAbortController.signal, + temporaryReferences, + onError (error) { + if (devRenderAbortController.signal.aborted && devRenderAbortController.signal.reason === error && error instanceof Error) { + // The abort reason is the same error stored as + // `workStore.invalidDynamicUsageError` (a fill timeout or + // deadlock). Register it under a digest and return that + // digest, so the error that surfaces on the consumer side of + // this Flight boundary carries it and the outer render's + // handler can recover *this* object via + // `reactServerErrorsByDigest`. + // + // We deliberately do not set `error.digest` here: whether the + // error actually surfaces (vs. being caught in userland) is + // the consumer's decision, so the "surfaced" mark is left to + // the outer handler. + const digest = (0, _stringhash.default)(error.message + (error.stack || '')).toString(); + workStore.reactServerErrorsByDigest.set(digest, error); + return digest; + } + return handleError(error); + } + }); + // `require` (rather than a top-level import) so the bundler can + // tree-shake the probe scheduler out of the production runtime, where + // this whole dev-server-gated branch is dead code. + const { setupProbeScheduler } = require('./use-cache-probe-scheduler'); + stream = setupProbeScheduler({ + workStore, + outerRequestStore: outerWorkUnitStore, + cacheContext, + encodedArguments, + fillDeadlineAt, + stream, + abortSignal: AbortSignal.any([ + devRenderAbortController.signal, + devTimeoutAbortController.signal + ]), + onProbeCompleted () { + const error = deadlockError ?? new _invarianterror.InvariantError('`deadlockError` should be constructed inside `cache()` before reaching the probe scheduler.'); + workStore.invalidDynamicUsageError = error; + devRenderAbortController.abort(error); + } + }); + break; + } + } + // fallthrough + case 'prerender-legacy': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + stream = (0, _server.renderToReadableStream)(resultPromise, clientReferenceManifest.clientModules, { + environmentName: 'Cache', + filterStackFrame, + temporaryReferences, + onError: handleError + }); + break; + default: + return outerWorkUnitStore; + } + const [returnStream, savedStream] = stream.tee(); + const pendingCacheResult = collectResult(savedStream, workStore, cacheContext, innerCacheStore, startTime, errors).finally(()=>{ + devTimeoutAbortController == null ? void 0 : devTimeoutAbortController.abort(); + }); + if (process.env.NODE_ENV === 'development') { + // Name the stream for React DevTools. + // @ts-expect-error + returnStream.name = 'use cache'; + } + return { + type: 'cached', + // Return the stream as we're creating it. This means that if it ends up + // erroring we cannot return a stale-if-error version but it allows + // streaming back the result earlier. + stream: returnStream, + pendingCacheResult + }; +} +function cloneCacheResult(result) { + const [entryA, entryB] = (0, _clonecacheentry.cloneCacheEntry)(result.entry); + return [ + { + entry: entryA, + hasExplicitRevalidate: result.hasExplicitRevalidate, + hasExplicitExpire: result.hasExplicitExpire, + readRootParamNames: result.readRootParamNames, + dynamicNestedCacheError: result.dynamicNestedCacheError + }, + { + entry: entryB, + hasExplicitRevalidate: result.hasExplicitRevalidate, + hasExplicitExpire: result.hasExplicitExpire, + readRootParamNames: result.readRootParamNames, + dynamicNestedCacheError: result.dynamicNestedCacheError + } + ]; +} +async function clonePendingCacheResult(pendingCacheResult) { + const result = await pendingCacheResult; + return cloneCacheResult(result); +} +async function getNthCacheResult(split, i) { + return (await split)[i]; +} +async function encodeFormData(formData) { + let result = ''; + for (let [key, value] of formData){ + // We don't need this key to be serializable but from a security perspective it should not be + // possible to generate a string that looks the same from a different structure. To ensure this + // we need a delimeter between fields but just using a delimeter is not enough since a string + // might contain that delimeter. We use the length of each field as the delimeter to avoid + // escaping the values. + result += key.length.toString(16) + ':' + key; + let stringValue; + if (typeof value === 'string') { + stringValue = value; + } else { + // The FormData might contain binary data that is not valid UTF-8 so this cache + // key may generate a UCS-2 string. Passing this to another service needs to be + // aware that the key might not be compatible. + const arrayBuffer = await value.arrayBuffer(); + if (arrayBuffer.byteLength % 2 === 0) { + stringValue = String.fromCodePoint(...new Uint16Array(arrayBuffer)); + } else { + stringValue = String.fromCodePoint(...new Uint16Array(arrayBuffer, 0, (arrayBuffer.byteLength - 1) / 2)) + String.fromCodePoint(new Uint8Array(arrayBuffer, arrayBuffer.byteLength - 1, 1)[0]); + } + } + result += stringValue.length.toString(16) + ':' + stringValue; + } + return result; +} +function createTrackedReadableStream(stream, cacheSignal) { + const reader = stream.getReader(); + return new ReadableStream({ + async pull (controller) { + const { done, value } = await reader.read(); + if (done) { + controller.close(); + cacheSignal.endRead(); + } else { + controller.enqueue(value); + } + } + }); +} +async function cache(kind, id, boundArgsLength, originalFn, args) { + var _workUnitStore_implicitTags; + const isPrivate = kind === 'private'; + // The default handler kind corresponds to the bare 'use cache' directive. + const logPrefix = kind === 'default' ? `'use cache'` : `'use cache: ${kind}'`; + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (workStore === undefined) { + throw new Error('"use cache" cannot be used outside of App Router. Expected a WorkStore.'); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore === undefined) { + throw new _invarianterror.InvariantError('"use cache" cannot be used outside of App Router. Expected a WorkUnitStore.'); + } + // In a prerender, tasky IO may result in cache reads that start + // after the prerender has already been aborted: + // + // await setTimeout(100) // we can't abort this uncached IO... + // await cachedData() // ...so we'll still get here even though the prerender aborted + // + // The prerender is over, so we should just return an erroring promise. + // (NOTE: we also shouldn't fill this cache, because it's behind uncached IO, + // so semantically it is not part of the prerender) + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-runtime': + { + if (workUnitStore.renderSignal.aborted) { + // We don't know if the cache itself is dynamic or runtime data, + // but the prerender is over, so it doesn't need to participate + // in runtime data tracking at all. + return (0, _dynamicrenderingutils.makeUntrackedHangingPromise)(workUnitStore.renderSignal, workStore.route, '"use cache" called after prerender ended'); + } + break; + } + case 'prerender-legacy': + case 'prerender-client': + case 'validation-client': + case 'request': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + // Probe re-executions (the dev-server's hang-detection worker) short-circuit + // further down before any handler is consulted, so we skip handler selection + // entirely and the worker can boot without registering handlers at all. + let cacheHandler; + if (workStore.useCacheProbeMode === undefined) { + if (isPrivate) { + // Private caches normally go to the Resume Data Cache (RDC), not a cache + // handler. In development we additionally persist them in a dedicated + // built-in in-memory handler so that reloads are fast. + if (process.env.__NEXT_DEV_SERVER) { + cacheHandler = (0, _handlers.getPrivateCacheHandler)(); + } + } else { + const handler = (0, _handlers.getCacheHandler)(kind); + if (!handler) { + throw new Error('Unknown cache handler: ' + kind); + } + // In development, a user-configured (custom) handler may be slow or + // remote, so we read through a tiered handler that puts a built-in + // in-memory front in front of it to keep cache hits microtask-fast. + // Built-in handlers (the default handler, and its size-0 replacement) are + // already in-memory and used directly. + if (process.env.__NEXT_DEV_SERVER && (0, _handlers.isCustomCacheHandler)(kind)) { + // A custom kind always has a dev tiered handler: it is created in the + // same `setCacheHandler` call that makes `isCustomCacheHandler` true. + const tieredCacheHandler = (0, _handlers.getDevTieredCacheHandler)(kind); + if (!tieredCacheHandler) { + throw new _invarianterror.InvariantError(`Expected a dev tiered cache handler for kind "${kind}".`); + } + cacheHandler = tieredCacheHandler; + } else { + cacheHandler = handler; + } + } + } + const timeoutError = new _usecacheerrors.UseCacheTimeoutError(workStore.route); + Error.captureStackTrace(timeoutError, cache); + (0, _dynamicrenderingutils.applyOwnerStack)(timeoutError); + // Only ever thrown by the dev-server's hang-detection probe. + // `Error.captureStackTrace` has to run while `cache()` is still on the + // synchronous stack, otherwise the user's `'use cache'` invocation frames + // would already be gone — that's why the construction sits up here rather + // than next to the trigger that actually consumes it. The `__NEXT_DEV_SERVER` + // gate lets the error class drop out of the production runtime bundle. + let deadlockError; + if (process.env.__NEXT_DEV_SERVER) { + deadlockError = new _usecacheerrors.UseCacheDeadlockError(workStore.route); + Error.captureStackTrace(deadlockError, cache); + (0, _dynamicrenderingutils.applyOwnerStack)(deadlockError); + } + const wrapAsInvalidDynamicUsageError = (error)=>{ + Error.captureStackTrace(error, cache); + workStore.invalidDynamicUsageError ??= error; + return error; + }; + const outerOwnerStack = process.env.NODE_ENV !== 'production' ? captureOuterOwnerStack(workUnitStore) : undefined; + const name = originalFn.name; + let fn = originalFn; + let cacheContext; + if (isPrivate) { + const expression = '"use cache: private"'; + switch(workUnitStore.type){ + // "use cache: private" is dynamic in prerendering contexts. + case 'prerender': + // Private caches can read request data. At this point we don't know + // Whether it's going to use session data or URL data. + // TODO(app-shells): This could be narrowed (and thus optimized) if we checked whether URL data + // is included in the cache key, because it can only be passed in as arguments. + return (0, _dynamicrenderingutils.makeUnknownRuntimeDataHangingPromise)(workUnitStore.renderSignal, workStore.route, expression, workUnitStore); + case 'prerender-legacy': + return (0, _dynamicrendering.throwToInterruptStaticGeneration)(expression, workStore, workUnitStore); + case 'prerender-client': + case 'validation-client': + throw new _invarianterror.InvariantError(`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being allowed in client components statically, but did not in this case.`); + case 'unstable-cache': + { + throw wrapAsInvalidDynamicUsageError((0, _usecachemessages.createUseCachePrivateInsideUnstableCacheError)(workStore.route)); + } + case 'cache': + { + throw wrapAsInvalidDynamicUsageError((0, _usecachemessages.createUseCachePrivateInsidePublicUseCacheError)(workStore.route)); + } + case 'request': + case 'prerender-runtime': + case 'private-cache': + cacheContext = { + kind: 'private', + outerWorkUnitStore: workUnitStore, + skipPropagation: false, + outerOwnerStack, + functionId: id, + handlerKind: kind + }; + break; + case 'build-time-generator': + throw wrapAsInvalidDynamicUsageError((0, _usecachemessages.createUseCachePrivateOutsideRequestContextError)(workStore.route, workUnitStore.functionName)); + default: + workUnitStore; + // This is dead code, but without throwing an error here, TypeScript + // will assume that cacheContext is used before being assigned. + throw new _invarianterror.InvariantError(`Unexpected work unit store.`); + } + } else { + switch(workUnitStore.type){ + case 'prerender-client': + case 'validation-client': + const expression = '"use cache"'; + throw new _invarianterror.InvariantError(`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being allowed in client components statically, but did not in this case.`); + case 'cache': + { + // Eagerly capture this invocation's call site while still synchronous + // in `cache()`. Used as `cause` of the nested-dynamic cache error + // when the outer cache (whose body never re-runs during the final + // prerender) throws. Only constructed when the parent is itself a + // public `'use cache'` — otherwise this entry can never propagate + // dynamism into that error and the allocation would be wasted. Private + // parents are intentionally excluded: `'use cache: private'` is + // dynamic-by-definition in prerendering and deferred to the runtime + // stage in dev requests, so a public cache nested inside one never + // triggers the throw upstream. + const dynamicNestedCacheError = new _usecacheerrors.NestedDynamicUseCacheError(); + Error.captureStackTrace(dynamicNestedCacheError, cache); + (0, _dynamicrenderingutils.applyOwnerStack)(dynamicNestedCacheError); + cacheContext = { + kind: 'public', + outerWorkUnitStore: workUnitStore, + skipPropagation: false, + outerOwnerStack, + functionId: id, + handlerKind: kind, + dynamicNestedCacheError + }; + break; + } + case 'prerender': + case 'prerender-runtime': + case 'prerender-legacy': + case 'request': + case 'private-cache': + // TODO: We should probably forbid nesting "use cache" inside + // unstable_cache. (fallthrough) + case 'unstable-cache': + case 'build-time-generator': + cacheContext = { + kind: 'public', + outerWorkUnitStore: workUnitStore, + skipPropagation: false, + outerOwnerStack, + functionId: id, + handlerKind: kind, + dynamicNestedCacheError: undefined + }; + break; + default: + workUnitStore; + // This is dead code, but without throwing an error here, TypeScript + // will assume that cacheContext is used before being assigned. + throw new _invarianterror.InvariantError(`Unexpected work unit store.`); + } + } + // Get the clientReferenceManifest while we're still in the outer Context. + // In case getClientReferenceManifestSingleton is implemented using AsyncLocalStorage. + const clientReferenceManifest = (0, _manifestssingleton.getClientReferenceManifest)(); + const hangingInputAbortSignal = (0, _dynamicrendering.createHangingInputAbortSignal)(workUnitStore); + if (cacheContext.kind === 'private') { + const { outerWorkUnitStore } = cacheContext; + switch(outerWorkUnitStore.type){ + case 'prerender-runtime': + { + // In a runtime prerender, we have to make sure that APIs that would hang during a static prerender + // are resolved with a delay, in the appropriate runtime stage. + const stagedRendering = outerWorkUnitStore.stagedRendering; + if (stagedRendering) { + await stagedRendering.waitForStage(_dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.sessionData); + } + break; + } + case 'request': + { + if (isValidationRender(outerWorkUnitStore)) { + // Similar to runtime prerenders, private caches should not resolve in the static stage + // of a validation request, so we delay them. + await (0, _dynamicrenderingutils.makeDevtoolsIOAwarePromise)(undefined, outerWorkUnitStore, _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.sessionData); + } + break; + } + case 'private-cache': + break; + default: + { + outerWorkUnitStore; + } + } + } + let isPageOrLayoutSegmentFunction = false; + // For page and layout segment functions (i.e. the page/layout component, + // or generateMetadata/generateViewport), the cache function is + // overwritten, which allows us to apply special handling for params and + // searchParams. For pages and layouts we're using the outer params prop, + // and not the inner one that was serialized/deserialized. While it's not + // generally true for "use cache" args, in the case of `params` the inner + // and outer object are essentially equivalent, so this is safe to do + // (including fallback params that are hanging promises). It allows us to + // avoid waiting for the timeout, when prerendering a fallback shell of a + // cached page or layout that awaits params. + if (isPageSegmentFunction(args)) { + isPageOrLayoutSegmentFunction = true; + const [{ params: outerParams, searchParams: outerSearchParams }, ...otherOuterArgs] = args; + const props = { + params: outerParams + }; + if (isPrivate) { + // Private caches allow accessing search params. We need to include + // them in the serialized args and when generating the cache key. + props.searchParams = outerSearchParams; + } + args = [ + props, + ...otherOuterArgs + ]; + fn = ({ + [name]: async (_, ...otherInnerArgs)=>originalFn.apply(null, [ + { + params: props.params, + searchParams: // Preserve the original search params, if this cache can access them. + // Notably, in a runtime shell private caches can resolve, but search params + // will be hanging, and we need to preserve the original proxied promise object + // to trigger `dynamicAccessAbortSignal` when they're accessed. + props.searchParams ?? // For public caches, search params are omitted from the cache + // key (and the serialized args) to avoid mismatches between + // prerendering and resuming a cached page that does not + // access search params. This is also the reason why we're not + // using a hanging promise for search params. For cached pages + // that do access them, which is an invalid dynamic usage, we + // need to ensure that an error is shown. + (0, _searchparams.makeErroringSearchParamsForUseCache)() + }, + ...otherInnerArgs + ]) + })[name]; + } else if (isLayoutSegmentFunction(args)) { + isPageOrLayoutSegmentFunction = true; + const [{ params: outerParams, $$isLayout, ...outerSlots }, ...otherOuterArgs] = args; + // Overwrite the props to omit $$isLayout. Note that slots are only + // passed to the layout component (if any are defined), and not to + // generateMetadata nor generateViewport. For those functions, + // outerSlots/innerSlots is an empty object, which is fine because we're + // just spreading it into the props. + args = [ + { + params: outerParams, + ...outerSlots + }, + ...otherOuterArgs + ]; + fn = ({ + [name]: async ({ params: _innerParams, ...innerSlots }, ...otherInnerArgs)=>originalFn.apply(null, [ + { + params: outerParams, + ...innerSlots + }, + ...otherInnerArgs + ]) + })[name]; + } + if (boundArgsLength > 0) { + if (args.length === 0) { + throw new _invarianterror.InvariantError(`Expected the "use cache" function ${JSON.stringify(fn.name)} to receive its encrypted bound arguments as the first argument.`); + } + const encryptedBoundArgs = args.shift(); + const boundArgs = await (0, _encryption.decryptActionBoundArgs)(id, encryptedBoundArgs); + if (!Array.isArray(boundArgs)) { + throw new _invarianterror.InvariantError(`Expected the bound arguments of "use cache" function ${JSON.stringify(fn.name)} to deserialize into an array, got ${typeof boundArgs} instead.`); + } + if (boundArgsLength !== boundArgs.length) { + throw new _invarianterror.InvariantError(`Expected the "use cache" function ${JSON.stringify(fn.name)} to receive ${boundArgsLength} bound arguments, got ${boundArgs.length} instead.`); + } + args.unshift(boundArgs); + } + const temporaryReferences = (0, _client.createTemporaryReferenceSet)(); + // The base serialized cache key doesn't include runtime env var state or the + // cookies and headers that private caches are allowed to read. Env var state + // only scopes the cache handler because the RDC must reuse entries across + // rendering phases. In production private cache entries aren't stored in a + // cache handler, only in the Resume Data Cache (RDC): private caches are only + // used during dynamic requests and runtime prefetches; for dynamic requests + // the RDC is immutable and excludes private caches, and for runtime prefetches + // it's mutable but lives only as long as the request. In development private + // caches are persisted across requests, so `cacheHandlerKeyBase` (below) + // additionally scopes the handler key by the request's cookies and headers. + const { implementationPart, runtimeEnvVarStateHash } = await computeCacheKeyImplementationPart(workStore, workUnitStore, id); + const cacheKeyParts = [ + id, + args, + implementationPart + ]; + const encodeCacheKeyParts = ()=>(0, _client.encodeReply)(cacheKeyParts, { + temporaryReferences, + signal: hangingInputAbortSignal + }); + let encodedCacheKeyParts; + switch(workUnitStore.type){ + case 'prerender-runtime': + // A runtime prerender may be a runtime shell, which does not have access to + // params/searchParams, so we want to apply the same dynamic access logic + // as we do in static prerenders. + // fallthrough + case 'prerender': + if (!isPageOrLayoutSegmentFunction) { + // If the "use cache" function is not a page or layout segment + // function, we need to track dynamic access already when encoding + // the arguments. If params are passed explicitly into a "use cache" + // function (as opposed to receiving them automatically in a page or + // layout), we assume that the params are also accessed. This allows + // us to abort early, and treat the function as dynamic, instead of + // waiting for the timeout to be reached. + const dynamicAccessStore = { + abortController: new AbortController(), + reason: null + }; + encodedCacheKeyParts = await _dynamicaccessasyncstorageexternal.dynamicAccessAsyncStorage.run(dynamicAccessStore, encodeCacheKeyParts); + if (dynamicAccessStore.abortController.signal.aborted) { + const makeHangingPromise = dynamicAccessStore.reason === 'fallback-params' ? _dynamicrenderingutils.makeFallbackParamsHangingPromise : _dynamicrenderingutils.makeURLDataHangingPromise; + return makeHangingPromise(workUnitStore.renderSignal, workStore.route, 'dynamic "use cache"', workUnitStore); + } + break; + } + // fallthrough + case 'prerender-legacy': + case 'request': + // TODO(restart-on-cache-miss): We need to handle params/searchParams on page components. + // the promises will be tasky, so `encodeCacheKeyParts` will not resolve in the static stage. + // We have not started a cache read at this point, so we might just miss the cache completely. + // fallthrough + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + case undefined: + encodedCacheKeyParts = await encodeCacheKeyParts(); + break; + default: + return workUnitStore; + } + // Probe path: we're running inside a pooled worker spawned by the dev + // server to check whether a stalled cache fill would complete in an + // isolated module scope. Skip the RDC / cache-handler / leader-election + // machinery, call `generateCacheEntry` (same as a real cold fill), drain + // the returned stream via `pendingCacheResult`, and apply the probe's own + // timeout. The caller only cares whether the fill resolves; the result + // value is discarded. + // + // Gated on `__NEXT_DEV_SERVER` so the entire branch — including its + // `generateCacheEntry` call site and the threading of + // `deadlockError` — drops out of the production runtime + // bundle. + if (process.env.__NEXT_DEV_SERVER && workStore.useCacheProbeMode) { + // Both public and private caches probe via the same path. The worker + // reconstructs real `headers` / `cookies` / `draftMode` from the + // forwarded request snapshot, so private caches that legitimately read + // those work in the probe just like in the real fill. + const probeTimeoutMs = workStore.useCacheProbeMode.timeoutMs; + // The deadlock error never gets thrown from inside the worker: the + // worker's outer store has `cacheSignal: undefined`, so + // `generateCacheEntryImpl` skips the dev-request branch and the idle + // probe is never set up. + const result = await generateCacheEntry(workStore, cacheContext, clientReferenceManifest, encodedCacheKeyParts, fn, timeoutError, undefined); + if (result.type === 'prerender-dynamic') { + // Unreachable in the probe: outer store is `'request'`-typed, which + // never produces this variant. + throw new _invarianterror.InvariantError('Unexpected `prerender-dynamic` result in `use cache` probe mode.'); + } + // We don't consume the returned stream — `pendingCacheResult` is what + // completes when `collectResult` has drained `savedStream`. Cancel the + // unused copy so it doesn't buffer forever. + result.stream.cancel().catch(()=>{}); + let probeTimeoutTimer; + try { + await Promise.race([ + result.pendingCacheResult, + new Promise((_, reject)=>{ + probeTimeoutTimer = setTimeout(()=>reject(timeoutError), probeTimeoutMs); + }) + ]); + } finally{ + if (probeTimeoutTimer !== undefined) { + clearTimeout(probeTimeoutTimer); + } + } + return; + } + const serializedCacheKey = typeof encodedCacheKeyParts === 'string' ? // Convert it to an ArrayBuffer if it wants to. + encodedCacheKeyParts : await encodeFormData(encodedCacheKeyParts); + const rootParams = workUnitStore.rootParams; + const knownRootParamNames = knownRootParamsByFunctionId.get(id); + // The coarse cache-handler key. With no root params read, it locates the + // entry directly; otherwise it locates a redirect entry from which the + // specific key (this key + root params, computed below) is derived. It's + // scoped by runtime env var state and, for private caches in development + // (persisted in the built-in in-memory handler), the request's cookies and + // headers. Keys derived from it inherit that scoping. + const cacheHandlerKeyBase = serializedCacheKey + (runtimeEnvVarStateHash ?? '') + (process.env.__NEXT_DEV_SERVER && cacheContext.kind === 'private' ? computePrivateCacheKeyRequestSuffix(cacheContext.outerWorkUnitStore.cookies, cacheContext.outerWorkUnitStore.headers) : ''); + // If we already know which root params this function reads, include them in + // the cache handler key for a direct hit (skipping the redirect entry). + // rootParams is undefined when nested inside unstable_cache. + let cacheHandlerKey = knownRootParamNames && rootParams ? cacheHandlerKeyBase + computeRootParamsCacheKeySuffix(rootParams, knownRootParamNames) : cacheHandlerKeyBase; + let stream = undefined; + // Set when a short-lived cache hit ends its cache read up front (dev only) so + // the static-shell boundary doesn't count it as a phantom miss. Once set, the + // cache signal read is balanced, so serving must use a plain stream and skip + // any trailing cacheSignal.endRead() call. + let cacheSignalReadEnded = false; + const resumeDataCache = (0, _workunitasyncstorageexternal.getResumeDataCache)(workUnitStore); + const implicitTags = ((_workUnitStore_implicitTags = workUnitStore.implicitTags) == null ? void 0 : _workUnitStore_implicitTags.tags) ?? []; + if (resumeDataCache) { + // If this cache key was already determined to be dynamic during the + // prospective prerender (e.g. because it accessed fallback params), we + // return a hanging promise early to avoid trying to regenerate the entry, + // which would be aborted anyway. + let rdcEntry = resumeDataCache.cache.get(serializedCacheKey); + if (rdcEntry === _cachestore.FALLBACK_PARAMS || rdcEntry === _cachestore.RUNTIME_DATA || rdcEntry === _cachestore.SESSION_DATA) { + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-runtime': + { + let makeHangingPromise; + if (rdcEntry === _cachestore.FALLBACK_PARAMS) { + makeHangingPromise = _dynamicrenderingutils.makeFallbackParamsHangingPromise; + } else if (rdcEntry === _cachestore.SESSION_DATA) { + makeHangingPromise = _dynamicrenderingutils.makeSessionDataHangingPromise; + } else { + makeHangingPromise = _dynamicrenderingutils.makeURLDataHangingPromise; + } + return makeHangingPromise(workUnitStore.renderSignal, workStore.route, 'dynamic "use cache"', workUnitStore); + } + case 'prerender-legacy': + case 'request': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + // Requests may receive the in-memory cache too. Unlike a prerender, they + // can resolve these holes, so treat a marker as an ordinary cache miss. + rdcEntry = undefined; + } + const cacheSignal = (0, _workunitasyncstorageexternal.getCacheSignal)(workUnitStore); + if (cacheSignal) { + cacheSignal.beginRead(); + } + if (rdcEntry !== undefined) { + let rdcResult = await rdcEntry; + // Check if the RDC entry should be discarded due to recently revalidated + // tags. When a server action calls updateTag(), the re-render should see + // fresh data instead of stale RDC data. + if (rdcResult !== undefined) { + const { timestamp } = rdcResult.entry; + if (rdcResult.entry.tags.some((tag)=>isRevalidatedAfter(tag, timestamp, workStore, logPrefix)) || implicitTags.some((tag)=>isRevalidatedAfter(tag, timestamp, workStore, logPrefix))) { + debug == null ? void 0 : debug(logPrefix, 'discarding RDC entry due to recently revalidated tags', serializedCacheKey); + rdcResult = undefined; + } + } + if (rdcResult !== undefined) { + if (rdcResult.entry.revalidate === 0 || rdcResult.entry.expire < _constants.MIN_PRERENDERABLE_EXPIRE) { + // The nested-cache error only makes sense when a dynamic nested cache + // actually shortened an outer cache that has no explicit `cacheLife` + // (`dynamicNestedCacheError` is set), and only when the app's default + // profile is itself prerenderable. If the default profile is already + // dynamic (`revalidate: 0` or an `expire` under the prerenderable + // minimum), every cache is omitted from prerenders by default, so + // there is no silent degradation to warn about. A short life from the + // default profile, or from a dev private cache's self-imposed + // `revalidate: 0` (which never carries a nested error), therefore + // stays a dynamic hole rather than erroring. + const defaultCacheLife = workStore.cacheLifeProfiles.default; + const shouldReportNestedCacheError = rdcResult.dynamicNestedCacheError !== undefined && defaultCacheLife.revalidate !== 0 && defaultCacheLife.expire >= _constants.MIN_PRERENDERABLE_EXPIRE; + switch(workUnitStore.type){ + case 'prerender': + // In a Dynamic I/O prerender, if the cache entry has + // revalidate: 0 or if the expire time is under 5 minutes, + // then we consider this cache entry dynamic as it's not worth + // generating static pages for such data. It's better to leave + // a dynamic hole that can be filled in during the resume with + // a potentially cached entry. + if (rdcResult.entry.revalidate === 0) { + if (rdcResult.hasExplicitRevalidate === false && shouldReportNestedCacheError) { + throw wrapAsInvalidDynamicUsageError((0, _usecachemessages.createNestedCacheZeroRevalidateError)(workStore.route, rdcResult.dynamicNestedCacheError)); + } + debug == null ? void 0 : debug(logPrefix, 'omitting entry', serializedCacheKey, 'from static shell due to revalidate: 0'); + } else { + if (rdcResult.hasExplicitExpire === false && shouldReportNestedCacheError) { + throw wrapAsInvalidDynamicUsageError((0, _usecachemessages.createNestedCacheShortExpireError)(workStore.route, rdcResult.dynamicNestedCacheError)); + } + debug == null ? void 0 : debug(logPrefix, 'omitting entry', serializedCacheKey, 'from static shell due to short expire value:', rdcResult.entry.expire); + } + if (cacheSignal) { + cacheSignal.endRead(); + } + // The entry is only excluded from *static* prerenders — the + // 'prerender-runtime' case below serves it. + // TODO(app-shells): Does this handle the MIN_SHELL_STALE case below correctly? + return (0, _dynamicrenderingutils.makeSessionDataHangingPromise)(workUnitStore.renderSignal, workStore.route, 'dynamic "use cache"', workUnitStore); + case 'prerender-runtime': + { + // In the final phase of a runtime prerender, we have to make + // sure that APIs that would hang during a static prerender + // are resolved with a delay, in the appropriate runtime stage. + const stagedRendering = workUnitStore.stagedRendering; + if (stagedRendering) { + await stagedRendering.waitForStage(_dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.sessionData); + } + break; + } + case 'request': + { + if (isValidationRender(workUnitStore)) { + // These throws force an explicit cache life decision on an + // outer cache that a nested cache would otherwise silently + // shorten (see `shouldReportNestedCacheError` above). Otherwise + // the short-lived entry is deferred as a dynamic hole below. + if (rdcResult.entry.revalidate === 0 && rdcResult.hasExplicitRevalidate === false && shouldReportNestedCacheError) { + throw wrapAsInvalidDynamicUsageError((0, _usecachemessages.createNestedCacheZeroRevalidateError)(workStore.route, rdcResult.dynamicNestedCacheError)); + } + if (rdcResult.entry.expire < _constants.MIN_PRERENDERABLE_EXPIRE && rdcResult.hasExplicitExpire === false && shouldReportNestedCacheError) { + throw wrapAsInvalidDynamicUsageError((0, _usecachemessages.createNestedCacheShortExpireError)(workStore.route, rdcResult.dynamicNestedCacheError)); + } + // A short-lived entry is a dynamic hole, excluded from the + // static shell, so we end the cache signal read here (the + // prerender case does the same) to avoid this cache hit being + // considered a cache miss when checking for pending cache reads + // at staged rendering task boundaries. The value is deferred to + // the runtime stage. + if (cacheSignal && !cacheSignalReadEnded) { + cacheSignal.endRead(); + cacheSignalReadEnded = true; + } + await (0, _dynamicrenderingutils.makeDevtoolsIOAwarePromise)(undefined, workUnitStore, _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.sessionData); + } + break; + } + case 'prerender-legacy': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + } + if (rdcResult.entry.stale < _constants.MIN_SHELL_STALE) { + // The entry's stale time is short enough that it's excluded from + // shells. If it's below `MIN_PREFETCHABLE_STALE`, it's not worth + // prefetching at all and is excluded from prerenders entirely, + // leaving a dynamic hole that can be filled during the navigation. + // Otherwise, it's still included in prerenders and cached + // navigations, but it must not be part of an App Shell, which may + // be reused on the client for longer than the entry's stale time. + // We delay the entry to resolve in the post-shell (link data) + // stage, which excludes both its content and its stale time from + // the shell. + const isPrefetchable = rdcResult.entry.stale >= _constants.MIN_PREFETCHABLE_STALE; + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-runtime': + { + const prerenderStore = workUnitStore; + if (!isPrefetchable) { + debug == null ? void 0 : debug(logPrefix, 'omitting entry', serializedCacheKey, 'from shell due to short stale value:', rdcResult.entry.stale); + if (cacheSignal) { + cacheSignal.endRead(); + } + // An unprefetchable entry (stale < MIN_PREFETCHABLE_STALE) is + // excluded from all prerenders. + return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(prerenderStore.renderSignal, workStore.route, 'dynamic "use cache"'); + } else { + // This entry is prefetchable, but exluded from shells. + const stagedRendering = prerenderStore.stagedRendering; + if (stagedRendering === null) { + // Prospective prerender (no staging): do not delay, because if we didn't + // have this entry in the RDC already, we wouldn't delay it either. + } else { + // Final prerender (with staging). + // This entry cannot be part of the shell, so we delay it to the prefetch. + let prefetchStage; + if (prerenderStore.type === 'prerender') { + prefetchStage = _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.staticUrlData.static; + } else { + prefetchStage = _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.runtimeUrlData; + } + if (// If the prerender ends before the prefetch stage (because + // render that only produces an App Shell), this cache + // should be omitted entirely. + stagedRendering.finalStage !== null && stagedRendering.finalStage < prefetchStage) { + debug == null ? void 0 : debug(logPrefix, 'omitting entry', serializedCacheKey, 'from shell due to short stale value:', rdcResult.entry.stale); + if (cacheSignal) { + cacheSignal.endRead(); + } + // The entry was omitted only because this prerender ends + // before the prefetch stage. Neither static nor runtime + // app shells include it, so it does not count as a runtime + // data access. + return (0, _dynamicrenderingutils.makePrefetchHangingPromise)(prerenderStore.renderSignal, workStore.route, 'dynamic "use cache"'); + } else { + debug == null ? void 0 : debug(logPrefix, 'delaying entry', serializedCacheKey, 'until the prefetch stage due to short stale value:', rdcResult.entry.stale); + await stagedRendering.waitForStage(prefetchStage); + } + } + } + break; + } + case 'request': + { + if (isValidationRender(workUnitStore)) { + // End the cache signal read (once, in case an earlier block + // already did) so the delayed value isn't counted as a pending + // read at a staged rendering boundary. + if (cacheSignal && !cacheSignalReadEnded) { + cacheSignal.endRead(); + cacheSignalReadEnded = true; + } + let stage; + if (!isPrefetchable) { + // An unprefetchable entry is excluded from prerenders, so it + // resolves in the dynamic stage. + stage = _stagedrendering.RenderStage.Dynamic; + } else { + // If the entry would be be excluded from the shell, treat it as + // if it were static URL data. + // (Note that this is still correct without PPF or in static shell validation, + // where we don't use runtime shells and include static URL data) + (0, _dynamicrenderingutils.trackIncompatibleShellContent)(workUnitStore, '"use cache" excluded from app shells due to a short staletime'); + stage = _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.staticUrlData[workUnitStore.needsRuntimeShell ? 'runtime' : 'static']; + } + debug == null ? void 0 : debug(logPrefix, 'delaying entry', serializedCacheKey, `until after the ${_stagedrendering.RenderStage[stage]} stage due to short stale value:`, rdcResult.entry.stale); + await (0, _dynamicrenderingutils.makeDevtoolsIOAwarePromise)(undefined, workUnitStore, stage); + } + break; + } + case 'prerender-legacy': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + } + } + if (rdcResult !== undefined) { + debug == null ? void 0 : debug(logPrefix, 'Resume Data Cache entry found', serializedCacheKey); + if (rdcResult.readRootParamNames && rdcResult.readRootParamNames.size > 0) { + addKnownRootParamNames(id, rdcResult.readRootParamNames); + } + // We want to make sure we only propagate cache life & tags if the + // entry was *not* omitted from the prerender. So we only do this + // after the above early returns. + propagateCacheEntryMetadata(cacheContext, { + tags: rdcResult.entry.tags, + revalidate: rdcResult.entry.revalidate, + expire: rdcResult.entry.expire, + stale: rdcResult.entry.stale, + timestamp: rdcResult.entry.timestamp, + hasExplicitRevalidate: rdcResult.hasExplicitRevalidate, + hasExplicitExpire: rdcResult.hasExplicitExpire, + readRootParamNames: rdcResult.readRootParamNames, + dynamicNestedCacheError: rdcResult.dynamicNestedCacheError + }); + const [streamA, streamB] = rdcResult.entry.value.tee(); + rdcResult.entry.value = streamB; + if (cacheSignal && !cacheSignalReadEnded) { + // When we have a cacheSignal we need to block on reading the cache + // entry before ending the read. + stream = createTrackedReadableStream(streamA, cacheSignal); + } else { + // The cache signal read was already ended for a short-lived deferral + // (or there is no cacheSignal), so serve a plain stream. + stream = streamA; + } + } else { + // Entry was discarded (e.g. due to recently revalidated tags) + debug == null ? void 0 : debug(logPrefix, 'Resume Data Cache entry discarded', serializedCacheKey); + if (cacheSignal) { + cacheSignal.endRead(); + } + } + } else { + debug == null ? void 0 : debug(logPrefix, 'Resume Data Cache entry not found', serializedCacheKey, `(${resumeDataCache.cache.size} entries)`); + if (cacheSignal) { + cacheSignal.endRead(); + } + switch(workUnitStore.type){ + case 'prerender': + if ((resumeDataCache == null ? void 0 : resumeDataCache.mutable) === false) { + // We're prerendering a fallback shell whose Resume Data Cache is + // the prefilled, read-only seed from a phase-1 prerender of a more- + // specific sibling route. A miss here means the cache key depends + // on a fallback param. We short-circuit to a dynamic hole (which + // may produce an empty shell if there's no parent Suspense + // boundary). Currently this also catches layouts and pages that + // don't read params, which will be improved when we implement + // NAR-136. Compared to the instrumentation-based params bailout we + // also do here, this covers the case where params are transformed + // with an async function before being passed into the "use cache" + // function, which escapes the instrumentation. + // The cache key depends on fallback params, which are URL data. + return (0, _dynamicrenderingutils.makeURLDataHangingPromise)(workUnitStore.renderSignal, workStore.route, 'dynamic "use cache"', workUnitStore); + } + // fallthrough + case 'prerender-runtime': + if (!cacheSignal) { + // This is the final prerender (cacheSignal is null), which means + // all caches should have been warmed during the prospective + // prerender. A cache miss here indicates that the cache key is + // non-deterministic (e.g. due to unstable array order in the + // arguments). Known dynamic keys (e.g. from fallback params) are + // already handled by the early return above. We return a hanging + // promise so this becomes a dynamic hole rather than generating a + // broken cache entry that gets aborted. + console.warn(new _usecacheerrors.UnexpectedCacheMissError(workStore.route)); + // This is an anomaly (non-deterministic cache key), so we can't + // know whether a runtime prerender would resolve it. + return (0, _dynamicrenderingutils.makeUnknownRuntimeDataHangingPromise)(workUnitStore.renderSignal, workStore.route, 'dynamic "use cache"', workUnitStore); + } + break; + case 'prerender-legacy': + case 'request': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + } + } + // Intra-request deduplication: Within a single request, root params are + // fixed, so the coarse key (serializedCacheKey) is sufficient. If another + // invocation in this request is already handling the same cache entry + // (including the cache handler lookup and generation), we join it instead of + // doing redundant work. This also saves cache handler `get` calls which may + // be HTTP round-trips for remote handlers. + if (stream === undefined) { + var _workStore_pendingCacheInvocations, _workStore_completedCacheInvocations; + const pendingInvocation = (_workStore_pendingCacheInvocations = workStore.pendingCacheInvocations) == null ? void 0 : _workStore_pendingCacheInvocations.get(serializedCacheKey); + // A pending invocation is joined unconditionally: its fill is shared, so + // every joiner receives whatever that fill produces. A completed one is a + // stored entry instead, so it is only reused when the caller hasn't asked + // to bypass caches, and only if nothing has invalidated it since. + const completedInvocation = pendingInvocation === undefined && !shouldForceRevalidate(workStore, workUnitStore) ? (_workStore_completedCacheInvocations = workStore.completedCacheInvocations) == null ? void 0 : _workStore_completedCacheInvocations.get(serializedCacheKey) : undefined; + const joinedInvocation = pendingInvocation ?? completedInvocation; + if (joinedInvocation) { + const cacheSignal = (0, _workunitasyncstorageexternal.getCacheSignal)(workUnitStore); + cacheSignal == null ? void 0 : cacheSignal.beginRead(); + debug == null ? void 0 : debug(logPrefix, 'joining intra-request invocation', serializedCacheKey); + const sharedCacheResult = await joinedInvocation; + if (sharedCacheResult.type === 'prerender-dynamic') { + debug == null ? void 0 : debug(logPrefix, 'joined invocation is prerender-dynamic', serializedCacheKey); + if (resumeDataCache == null ? void 0 : resumeDataCache.mutable) { + // A nested-cache leader has no RDC. This consumer must carry the + // omission reason into the final prerender instead of leaving an + // unexplained miss that loses the fallback's prefetch hint. + resumeDataCache.cache.set(serializedCacheKey, sharedCacheResult.reason); + } + cacheSignal == null ? void 0 : cacheSignal.endRead(); + return sharedCacheResult.hangingPromise; + } + // A completed entry may have been invalidated since it was produced, by + // an `updateTag()` in a server action earlier in this request. The + // implicit tags expiration is passed as 0 because it cannot apply to a + // retained entry: it is memoized for the request, so re-checking it + // against an unchanged entry timestamp only repeats the answer the leader + // already got. + const metadata = completedInvocation === undefined ? undefined : await sharedCacheResult.entry.pendingMetadata; + if (metadata !== undefined && shouldDiscardCacheEntry(metadata, workStore, workUnitStore, implicitTags, 0, logPrefix)) { + var _workStore_completedCacheInvocations1; + debug == null ? void 0 : debug(logPrefix, 'discarding completed invocation', serializedCacheKey); + (_workStore_completedCacheInvocations1 = workStore.completedCacheInvocations) == null ? void 0 : _workStore_completedCacheInvocations1.delete(serializedCacheKey); + // This can take the signal's count to zero. The leader path below opens + // a read again synchronously, before it awaits anything, which is what + // stops a prerender from concluding that every cache read has settled + // while a fill is still about to start. + cacheSignal == null ? void 0 : cacheSignal.endRead(); + } else { + debug == null ? void 0 : debug(logPrefix, 'joined invocation resolved with cached entry', serializedCacheKey); + stream = serveJoinedCacheEntry(sharedCacheResult.entry, serializedCacheKey, resumeDataCache, cacheContext, cacheSignal, logPrefix); + } + } + } + // Leader path: no pending intra-request invocation found. Check for a + // cross-request pending invocation, or become the leader for both. + if (stream === undefined) { + const resolvableSharedCacheResult = new ResolvableSharedCacheResult(); + debug == null ? void 0 : debug(logPrefix, 'registering as intra-request invocation leader', serializedCacheKey); + const intraRequestPendingCacheInvocations = workStore.pendingCacheInvocations ??= new Map(); + // Retain the completed entry for the rest of the request where a later + // invocation would otherwise repeat real work: private caches have no cache + // handler to fall back on in production, and a platform- or config-supplied + // handler may be remote, so a second `get` can be a round trip. A built-in + // handler read is a map lookup, so retaining its entries would hold a + // forked stream buffer for nothing. + const completedCacheInvocations = isPrivate || !(0, _handlers.isBuiltInCacheHandler)(kind) ? workStore.completedCacheInvocations ??= new Map() : undefined; + resolvableSharedCacheResult.registerIn(intraRequestPendingCacheInvocations, serializedCacheKey, completedCacheInvocations); + // Cross-request deduplication lets concurrent requests for the same key + // share a single fill. Private caches are skipped in production, where they + // hold request-specific data that must not be shared across requests. In + // development they're persisted and keyed by the request's cookies and + // headers, so concurrent requests with identical request data should share + // a fill too; that request-scoped `cacheHandlerKey` keeps requests with + // different cookies or headers in separate entries. + // + // Draft mode requests are skipped as well, in both directions. A fill that + // runs with draft mode enabled can contain unpublished content, so it must + // not be registered for other requests to join. And a draft mode request + // must not join a pending public fill, because it would be served the + // published content instead of the draft. + const skipCrossRequestDedupe = isPrivate && !process.env.__NEXT_DEV_SERVER || workStore.isDraftMode; + try { + // The loop handles cross-request root param mismatches: when a + // cross-request joiner discovers that the leader's root params differ + // from its own, it retries with a recomputed cacheHandlerKey. The loop + // exits when stream is assigned (cross-request joiner match or leader + // path) or via early return (prerender-dynamic). + while(stream === undefined){ + const crossRequestPendingCacheInvocation = skipCrossRequestDedupe ? undefined : crossRequestPendingCacheInvocations.get(cacheHandlerKey); + if (crossRequestPendingCacheInvocation) { + const cacheSignal = (0, _workunitasyncstorageexternal.getCacheSignal)(workUnitStore); + cacheSignal == null ? void 0 : cacheSignal.beginRead(); + debug == null ? void 0 : debug(logPrefix, 'joining pending cross-request invocation', cacheHandlerKey); + const sharedCacheResult = await crossRequestPendingCacheInvocation; + if (sharedCacheResult.type === 'cached') { + // Verify root params before forking the stream. The shared + // invocation must complete first, including collection and write + // settlement. A changed key retries the handler lookup, which must + // not run before the write settles. + const metadata = await sharedCacheResult.entry.pendingCompletion; + // Ensure known root param names are up-to-date before verifying the + // key, since the leader's save path may not have updated them yet + // at this point. + if (metadata.readRootParamNames) { + addKnownRootParamNames(id, metadata.readRootParamNames); + } + const updatedRootParamNames = knownRootParamsByFunctionId.get(id); + if (updatedRootParamNames && rootParams) { + const newCacheHandlerKey = cacheHandlerKeyBase + computeRootParamsCacheKeySuffix(rootParams, updatedRootParamNames); + if (newCacheHandlerKey !== cacheHandlerKey) { + debug == null ? void 0 : debug(logPrefix, 'cross-request root param mismatch, retrying', cacheHandlerKey, '→', newCacheHandlerKey); + cacheSignal == null ? void 0 : cacheSignal.endRead(); + cacheHandlerKey = newCacheHandlerKey; + continue; // stream is not used → retry with new key + } + } + // Key matches — safe to fork. + debug == null ? void 0 : debug(logPrefix, 'cross-request invocation matched, forking result', cacheHandlerKey); + cacheSignal == null ? void 0 : cacheSignal.endRead(); + stream = sharedCacheResult.entry.fork(); + maybePropagateCacheEntryMetadata(cacheContext, metadata); + // The cross-request leader belongs to a different request with its + // own RDC. Save to this request's RDC so its final prerender can + // resume from the entry. + saveSharedCacheEntryToResumeDataCache(serializedCacheKey, sharedCacheResult.entry, resumeDataCache, logPrefix); + // Resolve for intra-request joiners in this request. They get + // a fork from the same SharedCacheEntry. + resolvableSharedCacheResult.resolve(sharedCacheResult); + break; + } else { + // prerender-dynamic — same root param check before hanging + const updatedRootParamNames = knownRootParamsByFunctionId.get(id); + if (updatedRootParamNames && rootParams) { + const newCacheHandlerKey = cacheHandlerKeyBase + computeRootParamsCacheKeySuffix(rootParams, updatedRootParamNames); + if (newCacheHandlerKey !== cacheHandlerKey) { + debug == null ? void 0 : debug(logPrefix, 'cross-request root param mismatch, retrying', cacheHandlerKey, '→', newCacheHandlerKey); + cacheSignal == null ? void 0 : cacheSignal.endRead(); + cacheHandlerKey = newCacheHandlerKey; + continue; + } + } + debug == null ? void 0 : debug(logPrefix, 'cross-request invocation is prerender-dynamic', cacheHandlerKey); + if (resumeDataCache == null ? void 0 : resumeDataCache.mutable) { + resumeDataCache.cache.set(serializedCacheKey, sharedCacheResult.reason); + } + cacheSignal == null ? void 0 : cacheSignal.endRead(); + resolvableSharedCacheResult.resolve(sharedCacheResult); + return sharedCacheResult.hangingPromise; + } + } + // No pending cross-request invocation — become the leader. + if (!skipCrossRequestDedupe) { + debug == null ? void 0 : debug(logPrefix, 'registering as cross-request invocation leader', cacheHandlerKey); + resolvableSharedCacheResult.registerIn(crossRequestPendingCacheInvocations, cacheHandlerKey); + } + const cacheSignal = (0, _workunitasyncstorageexternal.getCacheSignal)(workUnitStore); + if (cacheSignal) { + // Either the cache handler or the generation can be using I/O at this + // point. We need to track when they start and when they complete. + cacheSignal.beginRead(); + } + const lazyRefreshTags = workStore.refreshTagsByCacheKind.get(kind); + if (lazyRefreshTags && !(0, _lazyresult.isResolvedLazyResult)(lazyRefreshTags)) { + await lazyRefreshTags; + } + let entry; + let observedRevalidation; + // We ignore existing cache entries when force revalidating. + if (cacheHandler && !shouldForceRevalidate(workStore, workUnitStore)) { + // Record an existing revalidation before `get()` so a stale result + // does not start another revalidation. The existing revalidation may + // finish and remove its map entry before the lookup returns. + observedRevalidation = backgroundRevalidations.get(cacheHandlerKey); + entry = await cacheHandler.get(cacheHandlerKey, implicitTags); + // Check if this is a redirect entry (coarse key → specific key). + // Redirect entries have private tags encoding the root param names + // (one tag per param name, prefixed with _N_RP_). + if (entry && rootParams) { + const paramNames = new Set(); + for (const tag of entry.tags){ + if (tag.startsWith(_constants1.NEXT_CACHE_ROOT_PARAM_TAG_ID)) { + paramNames.add(tag.slice(_constants1.NEXT_CACHE_ROOT_PARAM_TAG_ID.length)); + } + } + if (paramNames.size > 0) { + addKnownRootParamNames(id, paramNames); + cacheHandlerKey = cacheHandlerKeyBase + computeRootParamsCacheKeySuffix(rootParams, paramNames); + observedRevalidation = backgroundRevalidations.get(cacheHandlerKey); + entry = await cacheHandler.get(cacheHandlerKey, implicitTags); + } + } + } + if (entry) { + let implicitTagsExpiration = 0; + if (workUnitStore.implicitTags) { + const lazyExpiration = workUnitStore.implicitTags.expirationsByCacheKind.get(kind); + if (lazyExpiration) { + const expiration = (0, _lazyresult.isResolvedLazyResult)(lazyExpiration) ? lazyExpiration.value : await lazyExpiration; + // If a cache handler returns an expiration time of Infinity, it + // signals to Next.js that it handles checking cache entries for + // staleness based on the expiration of the implicit tags passed + // into the `get` method. In this case, we keep the default of 0, + // which means that the implicit tags are not considered expired. + if (expiration < Infinity) { + implicitTagsExpiration = expiration; + } + } + } + if (shouldDiscardCacheEntry(entry, workStore, workUnitStore, implicitTags, implicitTagsExpiration, logPrefix)) { + debug == null ? void 0 : debug(logPrefix, 'discarding expired entry', cacheHandlerKey); + entry = undefined; + } + } + const currentTime = performance.timeOrigin + performance.now(); + if (entry !== undefined && (entry.revalidate === 0 || entry.expire < _constants.MIN_PRERENDERABLE_EXPIRE)) { + switch(workUnitStore.type){ + case 'prerender': + // In a Dynamic I/O prerender, if the cache entry has revalidate: + // 0 or if the expire time is under 5 minutes, then we consider + // this cache entry dynamic as it's not worth generating static + // pages for such data. It's better to leave a dynamic hole that + // can be filled in during the resume with a potentially cached + // entry. + if (entry.revalidate === 0) { + debug == null ? void 0 : debug(logPrefix, 'omitting entry', cacheHandlerKey, 'from static shell due to revalidate: 0'); + } else { + debug == null ? void 0 : debug(logPrefix, 'omitting entry', cacheHandlerKey, 'from static shell due to short expire value:', entry.expire); + } + if (cacheSignal) { + cacheSignal.endRead(); + } + // The entry is only excluded from *static* prerenders. A runtime + // shell or prefetch would include this content. + // TODO(app-shells): Does this handle the MIN_SHELL_STALE case below correctly? + const hangingPromise = (0, _dynamicrenderingutils.makeSessionDataHangingPromise)(workUnitStore.renderSignal, workStore.route, 'dynamic "use cache"', workUnitStore); + debug == null ? void 0 : debug(logPrefix, 'leader resolved as prerender-dynamic', cacheHandlerKey); + resolvableSharedCacheResult.resolve({ + type: 'prerender-dynamic', + reason: _cachestore.SESSION_DATA, + hangingPromise + }); + return hangingPromise; + case 'request': + { + if (isValidationRender(workUnitStore)) { + // A short-lived entry is a dynamic hole, excluded from the + // static shell, so we end the cache signal read here (the + // prerender case does the same) to avoid this cache hit being + // considered a cache miss when checking for pending cache reads + // at staged rendering task boundaries. The value is deferred to + // the runtime stage. + if (cacheSignal && !cacheSignalReadEnded) { + cacheSignal.endRead(); + cacheSignalReadEnded = true; + } + const stage = _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.sessionData; + debug == null ? void 0 : debug(logPrefix, 'delaying entry', serializedCacheKey, `until after the ${_stagedrendering.RenderStage[stage]} stage due to short expire value:`, entry.expire); + await (0, _dynamicrenderingutils.makeDevtoolsIOAwarePromise)(undefined, workUnitStore, _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.sessionData); + } + break; + } + case 'prerender-runtime': + case 'prerender-legacy': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + } + if (entry !== undefined && entry.stale < _constants.MIN_SHELL_STALE) { + const isPrefetchable = entry.stale >= _constants.MIN_PREFETCHABLE_STALE; + switch(workUnitStore.type){ + case 'request': + { + // Same as the resume data cache read path: the entry's stale + // time is short enough that it's excluded from shells, or, if + // it's below `MIN_PREFETCHABLE_STALE`, from prerenders + // entirely. + if (isValidationRender(workUnitStore)) { + // End the cache signal read (once, in case the expire block + // above already did) so the delayed value isn't counted as a + // pending read at a staged rendering boundary. + if (cacheSignal && !cacheSignalReadEnded) { + cacheSignal.endRead(); + cacheSignalReadEnded = true; + } + let stage; + if (!isPrefetchable) { + // An unprefetchable entry is excluded from prerenders, so it + // resolves in the dynamic stage. + stage = _stagedrendering.RenderStage.Dynamic; + } else { + // If the entry would be be excluded from the shell, treat it as + // if it were static URL data. + // (Note that this is still correct without PPF or in static shell validation, + // where we don't use runtime shells and include static URL data) + (0, _dynamicrenderingutils.trackIncompatibleShellContent)(workUnitStore, '"use cache" excluded from app shells due to a short staletime'); + stage = _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.staticUrlData[workUnitStore.needsRuntimeShell ? 'runtime' : 'static']; + } + debug == null ? void 0 : debug(logPrefix, 'delaying entry', serializedCacheKey, `until after the ${_stagedrendering.RenderStage[stage]} stage due to short stale value:`, entry.stale); + await (0, _dynamicrenderingutils.makeDevtoolsIOAwarePromise)(undefined, workUnitStore, stage); + } + break; + } + case 'prerender': + case 'prerender-runtime': + case 'prerender-legacy': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + } + if (entry === undefined || // In dev, the built-in default handler retains a short-`expire` entry + // for at least `MIN_PRERENDERABLE_EXPIRE`, both when used directly + // and when fronting a custom cache handler. Apply that same minimum + // here so the retained entry is served and re-warmed in the + // background (below), rather than blocking to regenerate it on every + // read. The entry's real `expire` is untouched, so staging still + // treats it as dynamic. + currentTime > entry.timestamp + (process.env.__NEXT_DEV_SERVER ? Math.max(entry.expire, _constants.MIN_PRERENDERABLE_EXPIRE) : entry.expire) * 1000 || (0, _workunitasyncstorageexternal.willConsumerServerCache)(workUnitStore) && currentTime > entry.timestamp + entry.revalidate * 1000) { + // Miss. Generate a new result. + // If the cache entry is stale and its consumer will persist the + // result in a server cache, don't persist the stale entry into a new + // cache. We're not time constrained here, so regenerate it now. + // We need to run this inside a clean AsyncLocalStorage snapshot so + // that the cache generation cannot read anything from the context + // we're currently executing which might include request specific + // things like cookies() inside a React.cache(). + // Note: It is important that we await at least once before this + // because it lets us pop out of any stack specific contexts as well - + // aka "Sync" Local Storage. + if (entry) { + if (currentTime > entry.timestamp + entry.expire * 1000) { + debug == null ? void 0 : debug(logPrefix, 'entry is expired', cacheHandlerKey); + } + if ((0, _workunitasyncstorageexternal.willConsumerServerCache)(workUnitStore) && currentTime > entry.timestamp + entry.revalidate * 1000) { + debug == null ? void 0 : debug(logPrefix, 'foreground revalidation, entry is stale', cacheHandlerKey); + } + } + if (cacheSignal && cacheSignalReadEnded) { + // A short-lived deferral above (a `revalidate` of zero or a short + // expire, or a short stale time) already ended this read. We're now + // regenerating the entry rather than serving it, and the generation + // ends the read again once its entry is collected. Re-begin the + // read here so the trailing `endRead` stays balanced instead of + // over-decrementing the cache signal. + cacheSignal.beginRead(); + cacheSignalReadEnded = false; + } + const result = await generateCacheEntry(workStore, cacheContext, clientReferenceManifest, encodedCacheKeyParts, fn, timeoutError, deadlockError); + if (result.type === 'prerender-dynamic') { + debug == null ? void 0 : debug(logPrefix, 'leader resolved as prerender-dynamic (generation)', cacheHandlerKey); + if (resumeDataCache == null ? void 0 : resumeDataCache.mutable) { + resumeDataCache.cache.set(serializedCacheKey, result.reason); + } + resolvableSharedCacheResult.resolve(result); + return result.hangingPromise; + } + const { stream: newStream, pendingCacheResult } = result; + let pendingWrite; + // When draft mode is enabled, we must not save the cache entry. + if (!workStore.isDraftMode) { + const savedCacheResult = saveToResumeDataCache(resumeDataCache, serializedCacheKey, pendingCacheResult, logPrefix); + if (cacheHandler) { + pendingWrite = saveToCacheHandler(cacheHandler, id, cacheHandlerKeyBase, savedCacheResult, rootParams); + workStore.pendingRevalidateWrites ??= []; + workStore.pendingRevalidateWrites.push(pendingWrite); + } + } + debug == null ? void 0 : debug(logPrefix, 'leader resolved with generated entry', cacheHandlerKey); + const pendingMetadata = pendingCacheResult.then((collected)=>({ + tags: collected.entry.tags, + revalidate: collected.entry.revalidate, + expire: collected.entry.expire, + stale: collected.entry.stale, + timestamp: collected.entry.timestamp, + hasExplicitRevalidate: collected.hasExplicitRevalidate, + hasExplicitExpire: collected.hasExplicitExpire, + readRootParamNames: collected.readRootParamNames, + dynamicNestedCacheError: collected.dynamicNestedCacheError + })); + const sharedCacheEntry = new SharedCacheEntry(newStream, pendingMetadata, pendingWrite); + stream = sharedCacheEntry.fork(); + resolvableSharedCacheResult.resolve({ + type: 'cached', + entry: sharedCacheEntry + }); + } else { + const entryMetadata = { + tags: entry.tags, + revalidate: entry.revalidate, + expire: entry.expire, + stale: entry.stale, + timestamp: entry.timestamp, + readRootParamNames: knownRootParamsByFunctionId.get(id), + // For pre-existing entries from cache handlers we don't know + // whether they had explicit cache life values or not. But we only + // need this information during prerendering when we produce new + // entries, where the cache life of an inner cache may be propagated + // to the outer one. In that case we use the RDC. So it's safe to + // set this to undefined here. + hasExplicitRevalidate: undefined, + hasExplicitExpire: undefined, + // The same applies to the dynamic nested cache error. + dynamicNestedCacheError: undefined + }; + maybePropagateCacheEntryMetadata(cacheContext, entryMetadata); + // We want to return this stream, even if it's stale. + stream = entry.value; + // If we have a mutable resume data cache, we need to clone the entry + // and add it to the resume data cache. + if (resumeDataCache == null ? void 0 : resumeDataCache.mutable) { + const [entryLeft, entryRight] = (0, _clonecacheentry.cloneCacheEntry)(entry); + if (cacheSignal && !cacheSignalReadEnded) { + stream = createTrackedReadableStream(entryLeft.value, cacheSignal); + } else { + // The read was already ended for a short-lived deferral (or there + // is no cacheSignal), so serve a plain stream. + stream = entryLeft.value; + } + // The RDC is per-page and root params are fixed within a page, so + // we always use the coarse key (without root param suffix). + resumeDataCache.cache.set(serializedCacheKey, Promise.resolve({ + entry: entryRight, + hasExplicitRevalidate: entryMetadata.hasExplicitRevalidate, + hasExplicitExpire: entryMetadata.hasExplicitExpire, + readRootParamNames: entryMetadata.readRootParamNames, + dynamicNestedCacheError: entryMetadata.dynamicNestedCacheError + })); + } else if (!cacheSignalReadEnded) { + // If we're not regenerating we need to signal that we've finished + // putting the entry into the cache scope at this point. Otherwise + // we do that inside generateCacheEntry. (Skipped when the read was + // already ended for a short-lived deferral.) + cacheSignal == null ? void 0 : cacheSignal.endRead(); + } + debug == null ? void 0 : debug(logPrefix, 'leader resolved with cache handler hit', cacheHandlerKey); + const sharedCacheEntry = new SharedCacheEntry(stream, Promise.resolve(entryMetadata), undefined); + stream = sharedCacheEntry.fork(); + resolvableSharedCacheResult.resolve({ + type: 'cached', + entry: sharedCacheEntry + }); + // Trigger a background revalidation when the entry is stale (past its + // `revalidate`), so the next read gets a fresh value without blocking + // this one. Development additionally re-warms on every dynamic + // request render in two cases where the dev in-memory entry would + // otherwise read back as fresh, so a subsequent reload still shows a + // fresh value. The first is with the in-memory cache disabled + // (`cacheMaxMemorySize: 0`), where built-in entries keep their + // resolved (potentially non-dynamic) cache life. The second is a + // short-`expire` entry (an explicit dynamic or client-only cache, + // e.g. `cacheLife({ expire: 0 })`), which is retained for at least + // `MIN_PRERENDERABLE_EXPIRE` so it is served from the cache; this + // also covers custom handlers, re-executing and writing through to + // the backing. + let shouldTriggerBackgroundRevalidation = currentTime > entry.timestamp + entry.revalidate * 1000; + if (!shouldTriggerBackgroundRevalidation && process.env.__NEXT_DEV_SERVER && (entry.expire < _constants.MIN_PRERENDERABLE_EXPIRE || (0, _handlers.isMemoryCacheDisabled)() && !(0, _handlers.isCustomCacheHandler)(kind))) { + switch(workUnitStore.type){ + case 'request': + shouldTriggerBackgroundRevalidation = true; + break; + case 'cache': + case 'private-cache': + case 'prerender': + case 'prerender-runtime': + case 'prerender-legacy': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + } + if (shouldTriggerBackgroundRevalidation && // The revalidation observed before the lookup may have finished. + observedRevalidation === undefined && // A new revalidation may have started since the lookup began. + !backgroundRevalidations.has(cacheHandlerKey)) { + const revalidateCacheHandlerKey = cacheHandlerKey; + // Defer the call so synchronous setup errors reject the background + // task instead of failing the stale response. This also lets us + // register the task before generation starts. + const revalidatePromise = Promise.resolve().then(()=>generateCacheEntry(workStore, // The background revalidation preserves the outer store for + // reading (e.g. implicitTags) but skips propagation of cache + // life and tags back to the outer scope. + { + ...cacheContext, + skipPropagation: true + }, clientReferenceManifest, encodedCacheKeyParts, fn, timeoutError, deadlockError)).then(async (result)=>{ + if (result.type === 'cached') { + const { stream: ignoredStream, pendingCacheResult } = result; + const savedCacheResult = saveToResumeDataCache(resumeDataCache, serializedCacheKey, pendingCacheResult, logPrefix); + const pendingWrite = cacheHandler ? saveToCacheHandler(cacheHandler, id, cacheHandlerKeyBase, savedCacheResult, rootParams) : savedCacheResult.then(()=>{}); + for (const completion of (await Promise.allSettled([ + ignoredStream.cancel(), + pendingWrite + ]))){ + if (completion.status === 'rejected') { + throw completion.reason; + } + } + } + }).finally(()=>{ + if (backgroundRevalidations.get(revalidateCacheHandlerKey) === revalidatePromise) { + backgroundRevalidations.delete(revalidateCacheHandlerKey); + } + }); + backgroundRevalidations.set(revalidateCacheHandlerKey, revalidatePromise); + revalidatePromise.catch((error)=>{ + debug == null ? void 0 : debug(logPrefix, 'background cache revalidation failed for', revalidateCacheHandlerKey, error); + }); + workStore.pendingRevalidateWrites ??= []; + workStore.pendingRevalidateWrites.push(revalidatePromise); + } + } + } + } catch (error) { + resolvableSharedCacheResult.reject(error); + throw error; + } + } + // Logs are replayed even if it's a hit - to ensure we see them on the client eventually. + // If we didn't then the client wouldn't see the logs if it was seeded from a prewarm that + // never made it to the client. However, this also means that you see logs even when the + // cached function isn't actually re-executed. We should instead ensure prewarms always + // make it to the client. Another issue is that this will cause double logging in the + // server terminal. Once while generating the cache entry and once when replaying it on + // the server, which is required to pick it up for replaying again on the client. + const replayConsoleLogs = true; + const serverConsumerManifest = { + // moduleLoading must be null because we don't want to trigger preloads of ClientReferences + // to be added to the consumer. Instead, we'll wait for any ClientReference to be emitted + // which themselves will handle the preloading. + moduleLoading: null, + moduleMap: (0, _manifestssingleton.getRscModuleMappingForUseCache)(), + serverModuleMap: (0, _manifestssingleton.getServerModuleMap)() + }; + return (0, _client.createFromReadableStream)(stream, { + findSourceMapURL, + serverConsumerManifest, + temporaryReferences, + replayConsoleLogs, + environmentName: 'Cache' + }); +} +/** + * This returns cache key parts that cover everything that can affect the result of the cached + * function (apart from the arguments). The implementation part is used by both the RDC and cache + * handler, while the runtime env var state hash is only used by the cache handler. The RDC is + * per-page and must reuse entries across rendering phases even if an env var changes between them. + * + * The parts cover: + * - codeHash: the code itself that generates the return value + * - Notably, this excludes the following modules. Those are included via the Next.js version anyway: + * - react, react-dom, private-next-rsc-server-reference, private-next-rsc-cache-wrapper + * - runtimeEnvVarsRead: the keys and values of runtime environment variables that the code reads + * - runtimeEnvVarExistence: the unset/falsy/truthy state of runtime environment variables used in boolean contexts + * - the version of Next.js (to account for RSC wire format changes, or use-cache-wrapper.ts changes) + * + * In case that granular information isn't available, fall back to + * buildId/deploymentId/hmrRefreshHash, which is a correct hash but over-invalidates way too often. + */ async function computeCacheKeyImplementationPart(workStore, workUnitStore, id) { + var _getServerActionsManifest_node_id_workers_normalizeWorkerPageName, _getServerActionsManifest_node_id_workers; + let durability = workStore.durableUseCacheEntries ? (_getServerActionsManifest_node_id_workers = (0, _manifestssingleton.getServerActionsManifest)().node[id].workers) == null ? void 0 : (_getServerActionsManifest_node_id_workers_normalizeWorkerPageName = _getServerActionsManifest_node_id_workers[(0, _manifestssingleton.normalizeWorkerPageName)(workStore.page)]) == null ? void 0 : _getServerActionsManifest_node_id_workers_normalizeWorkerPageName.durability : undefined; + if (durability) { + // use cache is only supported in Node.js runtime. So we can use the Node.js crypto module here. + const crypto = require('crypto'); + let runtimeEnvVarStateHash = crypto// Hash the env var values, to not leak secrets into the cache key. + .createHash('sha256').update([ + ...durability.runtimeEnvVarsRead.map((k)=>{ + // Make sure not to stringify `undefined` and `"undefined"` to the same value. + return process.env[k] != null ? `${k}==${process.env[k]}` : k; + }), + ...durability.runtimeEnvVarsExistence.map((k)=>{ + const value = process.env[k]; + const state = value == null ? 'unset' : value ? 'truthy' : 'falsy'; + return `${k}~=${state}`; + }) + ].join('\0') ?? '').digest('hex'); + // The env var state is added to the cache handler key separately so it + // doesn't affect RDC lookups between rendering phases. + return { + implementationPart: [ + durability.codeHash, + nextVersion + ], + runtimeEnvVarStateHash + }; + } else { + // Because the Action ID is not yet unique per implementation of that Action we can't + // safely reuse the results across builds yet. In the meantime we add the buildId to the + // arguments as a seed to ensure they're not reused. Remove this once Action IDs hash + // the implementation. + const buildId = workStore.deploymentId || workStore.buildId; + // In dev mode, when the HMR refresh hash is set, we include it in the + // cache key. This ensures that cache entries are not reused when server + // components have been edited. This is a very coarse approach. But it's + // also only a temporary solution until Action IDs are unique per + // implementation. Remove this once Action IDs hash the implementation. + const hmrRefreshHash = (0, _workunitasyncstorageexternal.getHmrRefreshHash)(workUnitStore); + // otherwise fall back to buildId and/or the HMR hash. + return { + implementationPart: hmrRefreshHash ? [ + buildId, + hmrRefreshHash + ] : [ + buildId + ], + runtimeEnvVarStateHash: undefined + }; + } +} +/** + * A request store in `next start` never delays caches. + * We only apply delays when the render will be used for + * validation purposes. + */ function isValidationRender(requestStore) { + return !!(process.env.__NEXT_CACHE_COMPONENTS && // In dev we're always running validation. + (process.env.__NEXT_DEV_SERVER || // Build-time instant validation also uses a 'request' store. + requestStore.validationSamples)); +} +/** + * Returns `true` if the `'use cache'` function is the page component itself, + * or `generateMetadata`/`generateViewport` in a page file. + */ function isPageSegmentFunction(args) { + const [maybeProps] = args; + return maybeProps !== null && typeof maybeProps === 'object' && maybeProps.$$isPage === true; +} +/** + * Returns `true` if the `'use cache'` function is the layout component itself, + * or `generateMetadata`/`generateViewport` in a layout file. + */ function isLayoutSegmentFunction(args) { + const [maybeProps] = args; + return maybeProps !== null && typeof maybeProps === 'object' && maybeProps.$$isLayout === true; +} +function shouldForceRevalidate(workStore, workUnitStore) { + if (workStore.isOnDemandRevalidate || workStore.isDraftMode) { + return true; + } + if (process.env.__NEXT_DEV_SERVER) { + switch(workUnitStore.type){ + case 'request': + return workUnitStore.headers.get('cache-control') === 'no-cache'; + case 'cache': + case 'private-cache': + return workUnitStore.forceRevalidate; + case 'prerender-runtime': + case 'prerender': + case 'prerender-client': + case 'validation-client': + case 'prerender-legacy': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + } + return false; +} +function shouldDiscardCacheEntry(entry, workStore, workUnitStore, implicitTags, implicitTagsExpiration, logPrefix) { + // If the cache entry was created before any of the implicit tags were + // revalidated last, we need to discard it. + if (entry.timestamp <= implicitTagsExpiration) { + debug == null ? void 0 : debug(logPrefix, 'entry was created at', entry.timestamp, 'before implicit tags were revalidated at', implicitTagsExpiration); + return true; + } + // During prerendering, we ignore recently revalidated tags. In dev mode, we + // can assume that the dynamic dev rendering will have discarded and recreated + // the affected cache entries, and we don't want to discard those again during + // the prerender validation. During build-time prerendering, there will never + // be any pending revalidated tags. + switch(workUnitStore.type){ + case 'prerender': + return false; + case 'prerender-runtime': + case 'prerender-client': + case 'validation-client': + case 'prerender-legacy': + case 'request': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + // If the cache entry contains revalidated tags that the cache handler might + // not know about yet, we need to discard it. + if (entry.tags.some((tag)=>isRevalidatedAfter(tag, entry.timestamp, workStore, logPrefix))) { + return true; + } + // Finally, if any of the implicit tags have been revalidated recently, we + // also need to discard the cache entry. + if (implicitTags.some((tag)=>isRevalidatedAfter(tag, entry.timestamp, workStore, logPrefix))) { + return true; + } + return false; +} +/** + * Whether `tag` was revalidated after an entry created at `entryTimestamp`, + * which makes that entry stale. An entry produced after the revalidation + * already reflects it and is still usable. + */ function isRevalidatedAfter(tag, entryTimestamp, workStore, logPrefix) { + const { previouslyRevalidatedTags, pendingRevalidatedTags, requestStartTime } = workStore; + // Was the tag previously revalidated (e.g. by a redirecting server action)? + // That happened in an earlier request and carries no timestamp of its own, so + // it counts as having happened when this request started. + if (entryTimestamp <= requestStartTime && previouslyRevalidatedTags.includes(tag)) { + debug == null ? void 0 : debug(logPrefix, 'tag', tag, 'was previously revalidated'); + return true; + } + // It could also have been revalidated by the currently running server action. + // In this case the revalidation might not have been fully propagated by a + // remote cache handler yet, so we read it from the pending tags in the work + // store. + if (pendingRevalidatedTags == null ? void 0 : pendingRevalidatedTags.some((item)=>item.tag === tag && item.revalidatedAt > entryTimestamp)) { + debug == null ? void 0 : debug(logPrefix, 'tag', tag, 'was just revalidated'); + return true; + } + return false; +} + +//# sourceMappingURL=use-cache-wrapper.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/use-cache/use-cache-wrapper.js.map b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-wrapper.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ae3190628b234fd4158fd4f7935ca20db5994161 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/use-cache/use-cache-wrapper.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/use-cache/use-cache-wrapper.ts"],"sourcesContent":["import type { DeepReadonly } from '../../shared/lib/deep-readonly'\n/* eslint-disable import/no-extraneous-dependencies */\nimport {\n renderToReadableStream,\n decodeReply,\n decodeReplyFromAsyncIterable,\n createTemporaryReferenceSet as createServerTemporaryReferenceSet,\n} from 'react-server-dom-webpack/server'\nimport {\n createFromReadableStream,\n encodeReply,\n createTemporaryReferenceSet as createClientTemporaryReferenceSet,\n} from 'react-server-dom-webpack/client'\nimport { prerender } from 'react-server-dom-webpack/static'\n\nimport type { WorkStore } from '../app-render/work-async-storage.external'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport type {\n PrerenderStoreModernClient,\n PrerenderStoreModernRuntime,\n PrerenderStoreModernServer,\n PrivateUseCacheStore,\n RequestStore,\n RevalidateStore,\n UseCacheStore,\n ValidationStoreClient,\n WorkUnitStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n getHmrRefreshHash,\n getResumeDataCache,\n getVaryParamsAccumulator,\n workUnitAsyncStorage,\n getDraftModeProviderForCacheScope,\n getCacheSignal,\n isHmrRefresh,\n getServerComponentsHmrCache,\n willConsumerServerCache,\n} from '../app-render/work-unit-async-storage.external'\nimport { accumulateVaryParam } from '../app-render/vary-params'\n\nimport {\n applyOwnerStack,\n makeDevtoolsIOAwarePromise,\n makeDynamicHangingPromise,\n makeFallbackParamsHangingPromise,\n makeUntrackedHangingPromise,\n makeSessionDataHangingPromise,\n makeURLDataHangingPromise,\n makePrefetchHangingPromise,\n makeUnknownRuntimeDataHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n trackFallbackParamsAccessed,\n trackURLDataAccessed,\n trackIncompatibleShellContent,\n trackPromiseUsed,\n} from '../dynamic-rendering-utils'\n\nimport type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'\n\nimport {\n getClientReferenceManifest,\n getRscModuleMappingForUseCache,\n getServerActionsManifest,\n getServerModuleMap,\n normalizeWorkerPageName,\n} from '../app-render/manifests-singleton'\nimport type { CacheEntry } from '../lib/cache-handlers/types'\nimport type { CacheSignal } from '../app-render/cache-signal'\nimport { decryptActionBoundArgs } from '../app-render/encryption'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n createReactServerErrorHandler,\n type DigestedError,\n} from '../app-render/create-error-handler'\nimport stringHash from 'next/dist/compiled/string-hash'\nimport {\n MIN_PRERENDERABLE_EXPIRE,\n MIN_PREFETCHABLE_STALE,\n MIN_SHELL_STALE,\n} from './constants'\nimport { NEXT_CACHE_ROOT_PARAM_TAG_ID } from '../../lib/constants'\nimport {\n getCacheHandler,\n getDevTieredCacheHandler,\n getPrivateCacheHandler,\n isBuiltInCacheHandler,\n isCustomCacheHandler,\n isMemoryCacheDisabled,\n} from './handlers'\nimport type { CacheReadWriteHandler } from './tiered-cache-handler'\nimport { cloneCacheEntry } from './clone-cache-entry'\nimport { NEXT_INSTANT_TEST_COOKIE } from '../../client/components/app-router-headers'\nimport {\n RequestCookiesAdapter,\n type ReadonlyRequestCookies,\n} from '../web/spec-extension/adapters/request-cookies'\nimport {\n HeadersAdapter,\n type ReadonlyHeaders,\n} from '../web/spec-extension/adapters/headers'\nimport {\n NestedDynamicUseCacheError,\n UnexpectedCacheMissError,\n UseCacheDeadlockError,\n UseCacheTimeoutError,\n} from './use-cache-errors'\nimport {\n createNestedCacheShortExpireError,\n createNestedCacheZeroRevalidateError,\n createUseCachePrivateInsidePublicUseCacheError,\n createUseCachePrivateInsideUnstableCacheError,\n createUseCachePrivateOutsideRequestContextError,\n} from './use-cache-messages'\nimport {\n createHangingInputAbortSignal,\n throwToInterruptStaticGeneration,\n} from '../app-render/dynamic-rendering'\nimport {\n makeErroringSearchParamsForUseCache,\n type SearchParams,\n} from '../request/search-params'\nimport type { Params } from '../request/params'\nimport type { ResumeDataCache } from '../resume-data-cache/resume-data-cache'\nimport {\n FALLBACK_PARAMS,\n RUNTIME_DATA,\n SESSION_DATA,\n} from '../resume-data-cache/cache-store'\nimport { createLazyResult, isResolvedLazyResult } from '../lib/lazy-result'\nimport {\n abortOnDynamicAccess,\n dynamicAccessAsyncStorage,\n type DynamicAccessAsyncStore,\n} from '../app-render/dynamic-access-async-storage.external'\nimport type { CacheLife } from './cache-life'\nimport {\n RenderStage,\n type AdvanceableRenderStage,\n} from '../app-render/staged-rendering'\nimport * as Log from '../../build/output/log'\nimport { getServerReact, getClientReact } from '../runtime-reacts.external'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\n\ninterface PrivateCacheContext {\n readonly kind: 'private'\n readonly outerWorkUnitStore:\n | RequestStore\n | PrivateUseCacheStore\n | PrerenderStoreModernRuntime\n readonly skipPropagation: boolean\n readonly outerOwnerStack: string | undefined\n /** The `'use cache'` function's server reference id (second arg of `cache()`). */\n readonly functionId: string\n /** The cache handler kind (first arg of `cache()`, e.g. 'default'). */\n readonly handlerKind: string\n}\n\ninterface PublicCacheContext {\n readonly kind: 'public'\n // TODO: We should probably forbid nesting \"use cache\" inside unstable_cache.\n readonly outerWorkUnitStore: Exclude<\n WorkUnitStore,\n PrerenderStoreModernClient | ValidationStoreClient\n >\n readonly skipPropagation: boolean\n readonly outerOwnerStack: string | undefined\n /** The `'use cache'` function's server reference id (second arg of `cache()`). */\n readonly functionId: string\n /** The cache handler kind (first arg of `cache()`, e.g. 'default'). */\n readonly handlerKind: string\n /**\n * Eagerly captured at `cache()` entry, pointing at this invocation's call\n * site. Only set when the outer is itself a public `'use cache'` (i.e. when\n * this entry could become the propagated origin of a nested-dynamic cache\n * error in the parent). When this cache resolves dynamic, this is copied into\n * `outerWorkUnitStore.dynamicNestedCacheError` so the parent's error can use\n * it as `cause`.\n */\n readonly dynamicNestedCacheError: Error | undefined\n}\n\ntype CacheContext = PrivateCacheContext | PublicCacheContext\n\nconst nextVersion = process.env.__NEXT_VERSION as string\n\nexport type CacheKeyParts = [\n id: string,\n args: unknown[],\n implementationHash: unknown,\n]\n\ninterface UseCachePageInnerProps {\n params: Promise\n searchParams?: Promise\n}\n\nexport interface UseCachePageProps {\n params: Promise\n searchParams: Promise\n $$isPage: true\n}\n\nexport type UseCacheLayoutProps = {\n params: Promise\n $$isLayout: true\n} & {\n // The value type should be React.ReactNode. But such an index signature would\n // be incompatible with the other two props.\n [slot: string]: any\n}\n\n/**\n * Cache entry metadata for propagation. Separated from the stream to make\n * ownership clear: metadata is freely shareable, streams must be explicitly\n * tee'd for each consumer.\n */\ninterface CacheResultMetadata {\n readonly tags: string[]\n readonly revalidate: number\n readonly expire: number\n readonly stale: number\n readonly timestamp: number\n readonly readRootParamNames: ReadonlySet | undefined\n readonly hasExplicitRevalidate: boolean | undefined\n readonly hasExplicitExpire: boolean | undefined\n readonly dynamicNestedCacheError: Error | undefined\n}\n\n/**\n * Encapsulates a pending cache invocation for deduping. Manages lazy stream\n * tee-ing (via fork()) and metadata access for both intra-request and\n * cross-request joiners.\n */\nclass SharedCacheEntry {\n private stream: ReadableStream\n\n /**\n * Resolves when collection finishes, without waiting for handler writes.\n */\n public readonly pendingMetadata: Promise\n\n /**\n * Resolves with collected metadata after any handler writes settle. Write\n * failures do not discard the metadata. Collection failures still reject this\n * promise.\n */\n public readonly pendingCompletion: Promise\n\n constructor(\n stream: ReadableStream,\n pendingMetadata: Promise,\n pendingWrite: Promise | undefined\n ) {\n this.stream = stream\n this.pendingMetadata = pendingMetadata\n this.pendingCompletion =\n pendingWrite === undefined\n ? pendingMetadata\n : pendingWrite.then(\n () => pendingMetadata,\n () => pendingMetadata\n )\n }\n\n /**\n * Tee the stream: returns a copy for the caller, replaces the internal stream\n * with the remaining branch for future callers. Both the leader and joiners\n * call this — everyone gets a fork.\n */\n fork(): ReadableStream {\n const [forked, remaining] = this.stream.tee()\n this.stream = remaining\n return forked\n }\n}\n\nexport type SharedCacheResult =\n | {\n readonly type: 'cached'\n readonly entry: SharedCacheEntry\n }\n | {\n readonly type: 'prerender-dynamic'\n readonly reason:\n | typeof FALLBACK_PARAMS\n | typeof RUNTIME_DATA\n | typeof SESSION_DATA\n readonly hangingPromise: Promise\n }\n\nfunction ignoreReject() {}\n\n/**\n * Manages the deferred promise for a shared cache result, tracks which maps\n * it's registered in, and drives cleanup from resolve/reject.\n *\n * Cached results stay in the maps until collection finishes and handler writes\n * settle. Later invocations can join while either remains pending. For\n * 'prerender-dynamic' and errors, cleanup is immediate.\n */\nclass ResolvableSharedCacheResult {\n private readonly deferred = createPromiseWithResolvers()\n\n private readonly registrations: Array<{\n map: Map>\n key: string\n /**\n * Where to move the entry once the invocation completes, instead of\n * dropping it. Only set for the request-scoped map, and only for kinds\n * whose entries are worth retaining; the module-scope cross-request map\n * must never retain, since its entries would outlive the request that\n * produced them.\n */\n retentionMap?: Map>\n }> = []\n\n registerIn(\n map: Map>,\n key: string,\n retentionMap?: Map>\n ): void {\n map.set(key, this.deferred.promise)\n this.registrations.push({ map, key, retentionMap })\n }\n\n resolve(result: SharedCacheResult): void {\n this.deferred.resolve(result)\n if (result.type === 'cached') {\n // Retain only an entry that collected successfully. A failed collection\n // leaves metadata a later invocation cannot read, so it is dropped like\n // any other failure and the next invocation regenerates.\n result.entry.pendingCompletion.then(\n () => this.cleanupAndRetain(),\n () => this.cleanup()\n )\n } else {\n this.cleanup()\n }\n }\n\n reject(error: unknown): void {\n // The promise stored in the dedup maps has no consumer unless a concurrent\n // invocation joined it, so we attach a noop catch handler to prevent the\n // rejection from being reported as unhandled. The leader rethrows the\n // error into the render, which is where it's surfaced.\n this.deferred.promise.catch(ignoreReject)\n this.deferred.reject(error)\n this.cleanup()\n }\n\n /**\n * Drops the pending registrations, leaving nothing for a later invocation to\n * join. Used when the invocation produced no entry that a later one could\n * serve: an error has no value, and a 'prerender-dynamic' result is a hanging\n * promise bound to the leader's render signal.\n */\n private cleanup(): void {\n for (const { map, key } of this.registrations) {\n map.delete(key)\n }\n }\n\n /**\n * Drops the pending registrations and moves the entry into the retention map\n * where one was given, so a later invocation in the same request can reuse it\n * instead of repeating the lookup and, on a miss, the work.\n */\n private cleanupAndRetain(): void {\n for (const { map, key, retentionMap } of this.registrations) {\n map.delete(key)\n retentionMap?.set(key, this.deferred.promise)\n }\n }\n}\n\n/**\n * Module-scope map for cross-request deduplication. Keyed by `cacheHandlerKey`\n * (specific key on warm path, coarse key on cold path). Entries live only for\n * the duration of the leader's invocation.\n */\nconst crossRequestPendingCacheInvocations = new Map<\n string,\n Promise\n>()\n\n// Prevent duplicate background revalidations for the same key until generation\n// and cache writes finish.\nconst backgroundRevalidations = new Map>()\n\n// The first argument at each call site is the full directive that produced\n// the invocation, e.g. \"'use cache'\" or \"'use cache: remote'\".\nconst debug = process.env.NEXT_PRIVATE_DEBUG_CACHE\n ? console.debug.bind(console)\n : undefined\n\nconst filterStackFrame =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .filterStackFrameDEV\n : undefined\nconst findSourceMapURL =\n process.env.NODE_ENV !== 'production'\n ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))\n .findSourceMapURLDEV\n : undefined\n\n// Tracks which root params each cache function has historically read. Used to\n// compute the specific cache key upfront on subsequent invocations. In-memory\n// only — after server restart, the coarse-key redirect entry in the cache\n// handler provides fallback.\nconst knownRootParamsByFunctionId = new Map>()\n\nfunction addKnownRootParamNames(\n id: string,\n names: ReadonlySet\n): Set {\n const existing = knownRootParamsByFunctionId.get(id)\n if (existing) {\n for (const name of names) {\n existing.add(name)\n }\n return existing\n }\n const created = new Set(names)\n knownRootParamsByFunctionId.set(id, created)\n return created\n}\n\nfunction computeRootParamsCacheKeySuffix(\n rootParams: Params,\n paramNames: ReadonlySet\n): string {\n if (paramNames.size === 0) {\n return ''\n }\n\n return JSON.stringify(\n [...paramNames]\n .sort()\n .map((paramName) => [paramName, rootParams[paramName]])\n )\n}\n\n// Next-internal cookies that must not vary the private cache key, since they're\n// not part of the application's own cookie state. The instant-navigation cookie\n// toggles while a navigation lock is held, so including it would force spurious\n// misses.\nconst COOKIES_EXCLUDED_FROM_PRIVATE_CACHE_KEY = new Set([\n NEXT_INSTANT_TEST_COOKIE,\n])\n\n// Request and transport headers that must not vary the private cache key. They\n// either differ between otherwise-equivalent requests, which would cause\n// spurious misses (a browser reload adds `cache-control`/`pragma` that an\n// initial navigation doesn't, and `accept`/`sec-fetch-*` differ between an HTML\n// navigation and an RSC or prefetch request for the same page), or are\n// connection- and proxy-level rather than application data. The `cookie` header\n// is excluded because cookies are keyed separately below (via the dedicated\n// cookie path, which applies `COOKIES_EXCLUDED_FROM_PRIVATE_CACHE_KEY`);\n// including the raw header would duplicate them and reintroduce the cookies\n// that path excludes. Header names are lowercased by `HeadersAdapter`, so every\n// entry here is lowercase.\nconst HEADERS_EXCLUDED_FROM_PRIVATE_CACHE_KEY = new Set([\n 'accept',\n 'accept-encoding',\n 'cache-control',\n 'connection',\n 'cookie',\n 'if-match',\n 'if-modified-since',\n 'if-none-match',\n 'if-range',\n 'if-unmodified-since',\n 'keep-alive',\n 'pragma',\n 'priority',\n 'purpose',\n 'range',\n 'sec-fetch-dest',\n 'sec-fetch-mode',\n 'sec-fetch-site',\n 'sec-fetch-user',\n 'sec-purpose',\n 'te',\n 'upgrade',\n 'upgrade-insecure-requests',\n 'x-forwarded-for',\n 'x-forwarded-host',\n 'x-forwarded-port',\n 'x-forwarded-proto',\n])\n\n// TODO: This varies the dev private cache key by the request's cookies and\n// headers (minus the transport and content-negotiation headers excluded above).\n// It's a heuristic: it still over-keys (a cache that reads only one cookie or\n// header varies by all of them) and the header denylist is necessarily\n// incomplete. Follow up by tracking which cookies and headers a cache function\n// actually reads (the same mechanism root params use via `readRootParamNames`)\n// and keying by only those. Note that Next-internal flight headers such as\n// `rsc` and `next-router-state-tree` are already stripped upstream in\n// `getHeaders`, so they never appear here.\nfunction computePrivateCacheKeyRequestSuffix(\n cookies: ReadonlyRequestCookies,\n headers: ReadonlyHeaders\n): string {\n const relevantCookies = cookies\n .getAll()\n .filter(\n (cookie) => !COOKIES_EXCLUDED_FROM_PRIVATE_CACHE_KEY.has(cookie.name)\n )\n .map((cookie): [string, string] => [cookie.name, cookie.value])\n .sort(([nameA], [nameB]) => (nameA < nameB ? -1 : nameA > nameB ? 1 : 0))\n\n const relevantHeaders = [...headers.entries()]\n .filter(([name]) => !HEADERS_EXCLUDED_FROM_PRIVATE_CACHE_KEY.has(name))\n .sort(([nameA], [nameB]) => (nameA < nameB ? -1 : nameA > nameB ? 1 : 0))\n\n if (relevantCookies.length === 0 && relevantHeaders.length === 0) {\n return ''\n }\n\n return JSON.stringify({ cookies: relevantCookies, headers: relevantHeaders })\n}\n\nfunction saveToResumeDataCache(\n resumeDataCache: ResumeDataCache | null,\n serializedCacheKey: string,\n pendingCacheResult: Promise,\n logPrefix: string\n): Promise {\n if (!resumeDataCache?.mutable) {\n return pendingCacheResult\n }\n\n const split = clonePendingCacheResult(pendingCacheResult)\n const savedCacheResult = getNthCacheResult(split, 0)\n const rdcResult = getNthCacheResult(split, 1)\n\n // The RDC is per-page and root params are fixed within a page, so we always\n // use the coarse key (without root param suffix). Unlike the cache handler,\n // the RDC doesn't need root-param-specific keys for isolation.\n resumeDataCache.cache.set(serializedCacheKey, rdcResult)\n debug?.(logPrefix, 'Resume Data Cache entry saved', serializedCacheKey)\n\n return savedCacheResult\n}\n\n/**\n * A joiner's RDC context may differ from the leader's:\n *\n * - Intra-request: the leader was nested inside another cache (no accessible\n * RDC) while this joiner is top-level and has one.\n * - Cross-request: the leader belongs to a different request entirely — this\n * request's RDC has never seen the entry.\n *\n * In both cases the joiner must save to its own RDC so its final prerender can\n * resume from the entry. Constructs a `CollectedCacheResult` from a forked\n * stream branch of the shared entry and the awaited metadata.\n *\n * An existing entry avoids redundant saves when the intra-request leader\n * already saved to the same RDC. A marker, however, can be replaced by a\n * successful fill.\n */\nfunction saveSharedCacheEntryToResumeDataCache(\n serializedCacheKey: string,\n sharedCacheEntry: SharedCacheEntry,\n resumeDataCache: ResumeDataCache | null,\n logPrefix: string\n): void {\n if (!resumeDataCache?.mutable) {\n return\n }\n\n const existingEntry = resumeDataCache.cache.get(serializedCacheKey)\n if (\n existingEntry !== undefined &&\n existingEntry !== FALLBACK_PARAMS &&\n existingEntry !== RUNTIME_DATA &&\n existingEntry !== SESSION_DATA\n ) {\n return\n }\n\n const rdcResult: Promise =\n sharedCacheEntry.pendingMetadata.then((metadata) => ({\n entry: {\n value: sharedCacheEntry.fork(),\n tags: metadata.tags,\n revalidate: metadata.revalidate,\n expire: metadata.expire,\n stale: metadata.stale,\n timestamp: metadata.timestamp,\n },\n readRootParamNames: metadata.readRootParamNames,\n hasExplicitRevalidate: metadata.hasExplicitRevalidate,\n hasExplicitExpire: metadata.hasExplicitExpire,\n dynamicNestedCacheError: metadata.dynamicNestedCacheError,\n }))\n\n resumeDataCache.cache.set(serializedCacheKey, rdcResult)\n debug?.(\n logPrefix,\n 'Resume Data Cache entry saved by joiner',\n serializedCacheKey\n )\n}\n\n/**\n * Completes a join onto another invocation's entry, whether that invocation is\n * still filling or has already finished: forks the stream, saves to this\n * invocation's RDC if the leader had none, and balances the cache signal read\n * once the entry is fully collected.\n */\nfunction serveJoinedCacheEntry(\n sharedCacheEntry: SharedCacheEntry,\n serializedCacheKey: string,\n resumeDataCache: ResumeDataCache | null,\n cacheContext: CacheContext,\n cacheSignal: CacheSignal | null,\n logPrefix: string\n): ReadableStream {\n const stream = sharedCacheEntry.fork()\n\n // If the leader was nested inside another cache (no accessible RDC), it\n // couldn't save to the RDC. This joiner may be top-level with an RDC, in\n // which case it must save here; otherwise the RDC lookup during the final\n // prerender will miss.\n saveSharedCacheEntryToResumeDataCache(\n serializedCacheKey,\n sharedCacheEntry,\n resumeDataCache,\n logPrefix\n )\n\n // End the cache read after collection and metadata propagation, not when the\n // value stream becomes available. This does not wait for handler persistence.\n // A failed collection or propagation must still end the read so it cannot\n // stall prerendering. The catch prevents an unhandled rejection after the\n // stream has been returned.\n sharedCacheEntry.pendingMetadata\n .then((metadata) => {\n maybePropagateCacheEntryMetadata(cacheContext, metadata)\n })\n .finally(() => {\n cacheSignal?.endRead()\n })\n .catch(ignoreReject)\n\n return stream\n}\n\nfunction saveToCacheHandler(\n cacheHandler: CacheReadWriteHandler,\n id: string,\n cacheHandlerKeyBase: string,\n savedCacheResult: Promise,\n rootParams: Params | undefined\n): Promise {\n // Write the entry to the cache handler. With root params, this is a redirect\n // entry at the coarse key plus the actual entry at the specific key;\n // otherwise just the entry at the coarse key. Both set calls are fired\n // together and awaited in parallel.\n return savedCacheResult.then(async (collectedResult) => {\n const { entry: fullEntry, readRootParamNames } = collectedResult\n\n // Use the combined set (union of all historically observed reads) for both\n // the specific key and the redirect entry's tags. The read path computes\n // cacheHandlerKey from this same union (knownRootParamsByFunctionId), so\n // the write path must use the identical set to land on the same specific\n // key. If we used only the current invocation's reads, a function that\n // conditionally reads different root params across invocations would\n // scatter entries across different specific keys, making previous entries\n // unreachable from the read path's union-based lookup.\n const rootParamNames = readRootParamNames\n ? addKnownRootParamNames(id, readRootParamNames)\n : knownRootParamsByFunctionId.get(id)\n\n const setPromises: Promise[] = []\n let coarseEntry: CacheEntry = fullEntry\n\n if (rootParamNames && rootParamNames.size > 0 && rootParams) {\n const specificKey =\n cacheHandlerKeyBase +\n computeRootParamsCacheKeySuffix(rootParams, rootParamNames)\n\n setPromises.push(\n // Capture synchronous `set()` throws as rejected write promises.\n new Promise((resolve) => {\n resolve(cacheHandler.set(specificKey, Promise.resolve(fullEntry)))\n })\n )\n\n // The coarse key gets a redirect entry instead. On a cold server (empty\n // knownRootParamsByFunctionId), its tags tell a reader which root params\n // to include in the specific-key lookup.\n const rootParamTags = [...rootParamNames].map(\n (paramName) => NEXT_CACHE_ROOT_PARAM_TAG_ID + paramName\n )\n\n coarseEntry = {\n value: new ReadableStream({\n start(controller) {\n // Single byte so the entry has non-zero size in LRU caches.\n controller.enqueue(new Uint8Array([0]))\n controller.close()\n },\n }),\n tags: [...fullEntry.tags, ...rootParamTags],\n stale: fullEntry.stale,\n timestamp: fullEntry.timestamp,\n expire: fullEntry.expire,\n revalidate: fullEntry.revalidate,\n } satisfies CacheEntry\n }\n\n setPromises.push(\n // Capture synchronous `set()` throws as rejected write promises.\n new Promise((resolve) => {\n resolve(\n cacheHandler.set(cacheHandlerKeyBase, Promise.resolve(coarseEntry))\n )\n })\n )\n\n // A failed write must not finish the operation while another write is\n // pending.\n for (const result of await Promise.allSettled(setPromises)) {\n if (result.status === 'rejected') {\n throw result.reason\n }\n }\n })\n}\n\nfunction generateCacheEntry(\n workStore: WorkStore,\n cacheContext: CacheContext,\n clientReferenceManifest: DeepReadonly,\n encodedArguments: FormData | string,\n fn: (...args: unknown[]) => Promise,\n timeoutError: UseCacheTimeoutError,\n deadlockError: UseCacheDeadlockError | undefined\n) {\n // We need to run this inside a clean AsyncLocalStorage snapshot so that the cache\n // generation cannot read anything from the context we're currently executing which\n // might include request specific things like cookies() inside a React.cache().\n // Note: It is important that we await at least once before this because it lets us\n // pop out of any stack specific contexts as well - aka \"Sync\" Local Storage.\n return workStore.runInCleanSnapshot(\n generateCacheEntryWithRestoredWorkStore,\n workStore,\n cacheContext,\n clientReferenceManifest,\n encodedArguments,\n fn,\n timeoutError,\n deadlockError\n )\n}\n\nfunction generateCacheEntryWithRestoredWorkStore(\n workStore: WorkStore,\n cacheContext: CacheContext,\n clientReferenceManifest: DeepReadonly,\n encodedArguments: FormData | string,\n fn: (...args: unknown[]) => Promise,\n timeoutError: UseCacheTimeoutError,\n deadlockError: UseCacheDeadlockError | undefined\n) {\n // Since we cleared the AsyncLocalStorage we need to restore the workStore.\n // Note: We explicitly don't restore the RequestStore nor the PrerenderStore.\n // We don't want any request specific information leaking an we don't want to create a\n // bloated fake request mock for every cache call. So any feature that currently lives\n // in RequestStore but should be available to Caches need to move to WorkStore.\n // PrerenderStore is not needed inside the cache scope because the outer most one will\n // be the one to report its result to the outer Prerender.\n return workAsyncStorage.run(\n workStore,\n generateCacheEntryWithCacheContext,\n workStore,\n cacheContext,\n clientReferenceManifest,\n encodedArguments,\n fn,\n timeoutError,\n deadlockError\n )\n}\n\nfunction createUseCacheStore(\n workStore: WorkStore,\n cacheContext: CacheContext,\n defaultCacheLife: Required\n): UseCacheStore {\n if (cacheContext.kind === 'private') {\n const outerWorkUnitStore = cacheContext.outerWorkUnitStore\n\n return {\n type: 'private-cache',\n phase: 'render',\n consumerWillServerCache: true,\n implicitTags: outerWorkUnitStore?.implicitTags,\n revalidate: defaultCacheLife.revalidate,\n expire: defaultCacheLife.expire,\n stale: defaultCacheLife.stale,\n explicitRevalidate: undefined,\n explicitExpire: undefined,\n explicitStale: undefined,\n tags: null,\n hmrRefreshHash: getHmrRefreshHash(outerWorkUnitStore),\n isHmrRefresh: isHmrRefresh(outerWorkUnitStore),\n serverComponentsHmrCache: getServerComponentsHmrCache(outerWorkUnitStore),\n forceRevalidate: shouldForceRevalidate(workStore, outerWorkUnitStore),\n draftMode: getDraftModeProviderForCacheScope(\n workStore,\n outerWorkUnitStore\n ),\n rootParams: outerWorkUnitStore.rootParams,\n readRootParamNames: new Set(),\n // Every private cache scope is its own work unit. Any cache keyed on\n // headers() or cookies() needs to be invalidated. Otherwise some\n // Next.js API semantics leak across render passes.\n headers: HeadersAdapter.fresh(outerWorkUnitStore.headers),\n cookies: RequestCookiesAdapter.fresh(outerWorkUnitStore.cookies),\n outerOwnerStack: cacheContext.outerOwnerStack,\n }\n } else {\n let useCacheOrRequestStore: RequestStore | UseCacheStore | undefined\n const outerWorkUnitStore = cacheContext.outerWorkUnitStore\n\n switch (outerWorkUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n useCacheOrRequestStore = outerWorkUnitStore\n break\n case 'prerender-runtime':\n case 'prerender':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n outerWorkUnitStore satisfies never\n }\n\n let fallbackRootParamsPrerender: PrerenderStoreModernServer | null = null\n if (outerWorkUnitStore.type === 'cache') {\n fallbackRootParamsPrerender =\n outerWorkUnitStore.fallbackRootParamsPrerender\n } else if (outerWorkUnitStore.type === 'prerender') {\n const { fallbackRouteParams } = outerWorkUnitStore\n if (\n fallbackRouteParams !== null &&\n Object.keys(outerWorkUnitStore.rootParams).some((name) =>\n fallbackRouteParams.has(name)\n )\n ) {\n fallbackRootParamsPrerender = outerWorkUnitStore\n }\n }\n\n return {\n type: 'cache',\n phase: 'render',\n fallbackRootParamsPrerender,\n consumerWillServerCache: true,\n implicitTags: outerWorkUnitStore.implicitTags,\n revalidate: defaultCacheLife.revalidate,\n expire: defaultCacheLife.expire,\n stale: defaultCacheLife.stale,\n explicitRevalidate: undefined,\n explicitExpire: undefined,\n explicitStale: undefined,\n tags: null,\n hmrRefreshHash: getHmrRefreshHash(outerWorkUnitStore),\n isHmrRefresh: useCacheOrRequestStore?.isHmrRefresh ?? false,\n serverComponentsHmrCache:\n useCacheOrRequestStore?.serverComponentsHmrCache,\n forceRevalidate: shouldForceRevalidate(workStore, outerWorkUnitStore),\n draftMode: getDraftModeProviderForCacheScope(\n workStore,\n outerWorkUnitStore\n ),\n rootParams: outerWorkUnitStore.rootParams,\n readRootParamNames: new Set(),\n outerOwnerStack: cacheContext.outerOwnerStack,\n dynamicNestedCacheError: undefined,\n }\n }\n}\n\n/**\n * Captures the owner stack from the outer component tree before entering a\n * cache boundary. When nested inside another cache scope, the parent's\n * outerOwnerStack is concatenated so that the full component tree is preserved\n * across multiple cache boundaries.\n */\nfunction captureOuterOwnerStack(\n workUnitStore: WorkUnitStore\n): string | undefined {\n const capturedOwnerStack =\n (getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()) ||\n ''\n\n let parentOuterOwnerStack: string | undefined\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n parentOuterOwnerStack = workUnitStore.outerOwnerStack\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n\n return capturedOwnerStack + (parentOuterOwnerStack || '') || undefined\n}\n\n// The maximum time we allow a `'use cache'` entry to fill. After this, we\n// assume the fill is stalled — either on hanging input to the cached function,\n// or on hanging I/O inside of it — and de-opt with an error.\n//\n// For prerender, the effective value is clamped to 90% of the configured\n// `staticPageGenerationTimeout` so the cache-fill error surfaces before the\n// build worker kills the page. In dev (`request`), the configured\n// `experimental.useCacheTimeout` is used straight.\nfunction getUseCacheFillTimeoutMs(\n workStore: WorkStore,\n workUnitStoreType: 'prerender' | 'prerender-runtime' | 'request'\n): number {\n const { useCacheTimeout, staticPageGenerationTimeout } = workStore\n\n const effectiveTimeout =\n workUnitStoreType === 'request'\n ? useCacheTimeout\n : Math.min(useCacheTimeout, staticPageGenerationTimeout * 0.9)\n\n return effectiveTimeout * 1000\n}\n\nfunction generateCacheEntryWithCacheContext(\n workStore: WorkStore,\n cacheContext: CacheContext,\n clientReferenceManifest: DeepReadonly,\n encodedArguments: FormData | string,\n fn: (...args: unknown[]) => Promise,\n timeoutError: UseCacheTimeoutError,\n deadlockError: UseCacheDeadlockError | undefined\n) {\n const defaultCacheLife = workStore.cacheLifeProfiles.default\n\n // Initialize the Store for this Cache entry.\n const cacheStore = createUseCacheStore(\n workStore,\n cacheContext,\n defaultCacheLife\n )\n\n return workUnitAsyncStorage.run(cacheStore, () =>\n dynamicAccessAsyncStorage.run(\n { abortController: new AbortController(), reason: null },\n generateCacheEntryImpl,\n workStore,\n cacheContext,\n cacheStore,\n clientReferenceManifest,\n encodedArguments,\n fn,\n timeoutError,\n deadlockError\n )\n )\n}\n\nfunction propagateCacheLifeAndTagsToRevalidateStore(\n revalidateStore: RevalidateStore,\n metadata: CacheResultMetadata\n): void {\n const outerTags = (revalidateStore.tags ??= [])\n\n for (const tag of metadata.tags) {\n if (!outerTags.includes(tag)) {\n outerTags.push(tag)\n }\n }\n\n if (revalidateStore.stale > metadata.stale) {\n revalidateStore.stale = metadata.stale\n }\n\n if (revalidateStore.revalidate > metadata.revalidate) {\n revalidateStore.revalidate = metadata.revalidate\n }\n\n if (revalidateStore.expire > metadata.expire) {\n revalidateStore.expire = metadata.expire\n }\n}\n\nfunction propagateCacheStaleTimeToRequestStore(\n requestStore: RequestStore,\n metadata: CacheResultMetadata\n): void {\n if (requestStore.stale !== undefined && requestStore.stale > metadata.stale) {\n requestStore.stale = metadata.stale\n }\n}\n\nfunction propagateCacheEntryMetadata(\n cacheContext: CacheContext,\n metadata: CacheResultMetadata\n): void {\n if (cacheContext.kind === 'private') {\n switch (cacheContext.outerWorkUnitStore.type) {\n case 'private-cache':\n if (metadata.readRootParamNames) {\n for (const paramName of metadata.readRootParamNames) {\n cacheContext.outerWorkUnitStore.readRootParamNames.add(paramName)\n }\n }\n // fallthrough\n case 'prerender-runtime':\n propagateCacheLifeAndTagsToRevalidateStore(\n cacheContext.outerWorkUnitStore,\n metadata\n )\n break\n case 'request':\n propagateCacheStaleTimeToRequestStore(\n cacheContext.outerWorkUnitStore,\n metadata\n )\n break\n case undefined:\n break\n default:\n cacheContext.outerWorkUnitStore satisfies never\n }\n } else {\n switch (cacheContext.outerWorkUnitStore.type) {\n case 'cache':\n // If this entry's cache life is dynamic, record this invocation as the\n // origin to use as `cause` when the outer cache surfaces the\n // nested-dynamic cache error. `??=` keeps the first occurrence so the\n // cause points at the immediate dynamic child.\n if (\n cacheContext.dynamicNestedCacheError !== undefined &&\n (metadata.revalidate === 0 ||\n metadata.expire < MIN_PRERENDERABLE_EXPIRE)\n ) {\n cacheContext.outerWorkUnitStore.dynamicNestedCacheError ??=\n cacheContext.dynamicNestedCacheError\n }\n // fallthrough\n case 'private-cache':\n if (metadata.readRootParamNames) {\n for (const paramName of metadata.readRootParamNames) {\n cacheContext.outerWorkUnitStore.readRootParamNames.add(paramName)\n }\n }\n // fallthrough\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-legacy':\n propagateCacheLifeAndTagsToRevalidateStore(\n cacheContext.outerWorkUnitStore,\n metadata\n )\n break\n case 'request':\n propagateCacheStaleTimeToRequestStore(\n cacheContext.outerWorkUnitStore,\n metadata\n )\n break\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n cacheContext.outerWorkUnitStore satisfies never\n }\n }\n\n if (metadata.readRootParamNames) {\n const varyParamsAccumulator = getVaryParamsAccumulator(\n cacheContext.outerWorkUnitStore\n )\n if (varyParamsAccumulator) {\n for (const paramName of metadata.readRootParamNames) {\n accumulateVaryParam(varyParamsAccumulator.rootParams, paramName)\n }\n }\n }\n}\n\n/**\n * Conditionally propagates cache life, tags, and root param names to the outer\n * context. During prerenders (`prerender` / `prerender-runtime`) and dev\n * cache-filling requests, propagation is deferred because the entry might be\n * omitted from the final prerender due to short expire/stale times. If omitted,\n * it should not affect the prerender. The final decision happens when the entry\n * is read from the resume data cache in the final render phase — at that point\n * `propagateCacheEntryMetadata` is called unconditionally (after the omission\n * checks have already filtered out short-lived entries).\n *\n * Nested caches propagate root param names into the enclosing cache's\n * `readRootParamNames` set. This propagation is never deferred. Prerender\n * contexts also register known root param names when they read the resume\n * data cache. A response accumulator records the consumed entry's root vary\n * params to prevent segment reuse across different values.\n */\nfunction maybePropagateCacheEntryMetadata(\n cacheContext: CacheContext,\n metadata: CacheResultMetadata\n): void {\n const outerWorkUnitStore = cacheContext.outerWorkUnitStore\n\n switch (outerWorkUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime': {\n // Don't propagate yet — the entry might be omitted from the final\n // prerender due to short expire/stale times. Propagation will happen when\n // the entry is read from the resume data cache.\n break\n }\n case 'request': {\n if (\n isValidationRender(outerWorkUnitStore) &&\n outerWorkUnitStore.cacheSignal\n ) {\n // If we're filling caches for a dev request, apply the same logic as\n // prerenders do above.\n break\n }\n // fallthrough\n }\n case 'private-cache':\n case 'cache':\n case 'unstable-cache':\n case 'prerender-legacy': {\n propagateCacheEntryMetadata(cacheContext, metadata)\n break\n }\n case 'build-time-generator':\n break\n default: {\n outerWorkUnitStore satisfies never\n }\n }\n}\n\nexport interface CollectedCacheResult {\n entry: CacheEntry\n /**\n * Whether the revalidate value was explicitly set via `cacheLife()`.\n * - `true`: explicitly set\n * - `false`: implicit (propagated from a nested cache or implicitly using the\n * default profile)\n * - `undefined`: unknown (e.g. pre-existing entry from a cache handler)\n */\n hasExplicitRevalidate: boolean | undefined\n /**\n * Whether the expire value was explicitly set via `cacheLife()`.\n * - `true`: explicitly set\n * - `false`: implicit (propagated from a nested cache or implicitly using the\n * default profile)\n * - `undefined`: unknown (e.g. pre-existing entry from a cache handler)\n */\n hasExplicitExpire: boolean | undefined\n /**\n * The root param names that were read during cache entry generation.\n * Used to compute the specific cache key after generation completes.\n * `undefined` for pre-existing entries from cache handlers where we\n * don't have this information.\n */\n readRootParamNames: ReadonlySet | undefined\n /**\n * The `Error` carried up from the first nested public `'use cache'`\n * invocation that propagated a dynamic cache life into this entry, captured\n * eagerly at that inner invocation's `cache()` entry. Used as `cause` for the\n * nested-dynamic cache error so the redbox can point at the inner invocation\n * site, not just the outer one. Lives in-memory only — intentionally dropped\n * from the serialized RDC because dynamic entries aren't serialized either.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nasync function collectResult(\n savedStream: ReadableStream,\n workStore: WorkStore,\n cacheContext: CacheContext,\n innerCacheStore: UseCacheStore,\n startTime: number,\n errors: Array // This is a live array that gets pushed into.\n): Promise {\n // We create a buffered stream that collects all chunks until the end to\n // ensure that RSC has finished rendering and therefore we have collected\n // all tags. In the future the RSC API might allow for the equivalent of\n // the allReady Promise that exists on SSR streams.\n //\n // If something errored or rejected anywhere in the render, we close\n // the stream as errored. This lets a CacheHandler choose to save the\n // partial result up until that point for future hits for a while to avoid\n // unnecessary retries or not to retry. We use the end of the stream for\n // this to avoid another complicated side-channel. A receiver has to consider\n // that the stream might also error for other reasons anyway such as losing\n // connection.\n\n const buffer: Uint8Array[] = []\n const reader = savedStream.getReader()\n\n try {\n for (let entry; !(entry = await reader.read()).done; ) {\n buffer.push(entry.value)\n }\n } catch (error) {\n errors.push(error)\n }\n\n let idx = 0\n const bufferStream = new ReadableStream({\n pull(controller) {\n if (workStore.invalidDynamicUsageError) {\n controller.error(workStore.invalidDynamicUsageError)\n } else if (idx < buffer.length) {\n controller.enqueue(buffer[idx++])\n } else if (errors.length > 0) {\n // TODO: Should we use AggregateError here?\n controller.error(errors[0])\n } else {\n controller.close()\n }\n },\n })\n\n const collectedTags = innerCacheStore.tags\n\n const isPrivateCacheInDev = Boolean(\n process.env.__NEXT_DEV_SERVER && cacheContext.kind === 'private'\n )\n\n // In development, force a dynamic cache life (`revalidate: 0`, `expire:\n // MIN_PRERENDERABLE_EXPIRE`) for private caches, which have no real backing\n // handler. The zero revalidate makes every read serve stale-while-revalidate\n // (regenerating a fresh entry in the background), and\n // `MIN_PRERENDERABLE_EXPIRE` (5 minutes) caps how long an entry lingers in\n // the dedicated in-memory private handler. It is the shortest `expire` that\n // isn't treated as dynamic; a smaller `expire` would exclude the entry from\n // prerenders. Two other cases deliberately do NOT force this and keep their\n // resolved cache life, relying instead on the dev handler's minimum retention\n // and a dev revalidation (see the cache-hit path below) to keep reloads fast\n // and fresh. The size-0 case (`cacheMaxMemorySize: 0`) keeps its life so the\n // entry can be considered prerenderable instead of being misread as a dynamic\n // hole. An explicit short-`expire` public cache (e.g. `cacheLife({ expire: 0\n // })`) keeps its life so it stays correctly excluded from static prerenders\n // via its real `expire` while a reload still hits the cache; forcing\n // `revalidate: 0` here would instead corrupt the cache life propagated to an\n // enclosing cache and trigger the nested-dynamic error. A cache backed by a\n // custom handler keeps its real cache life too, since that handler owns it.\n const forceDynamicCacheLifeInDev = isPrivateCacheInDev\n\n // If cacheLife() was used to set an explicit revalidate/expire/stale time we\n // use that. Otherwise, we use the lowest of all inner fetch(),\n // unstable_cache() or nested \"use cache\", if they're lower than our default.\n const collectedRevalidate = forceDynamicCacheLifeInDev\n ? 0\n : innerCacheStore.explicitRevalidate !== undefined\n ? innerCacheStore.explicitRevalidate\n : innerCacheStore.revalidate\n const collectedExpire = forceDynamicCacheLifeInDev\n ? MIN_PRERENDERABLE_EXPIRE\n : innerCacheStore.explicitExpire !== undefined\n ? innerCacheStore.explicitExpire\n : innerCacheStore.expire\n const collectedStale =\n innerCacheStore.explicitStale !== undefined\n ? innerCacheStore.explicitStale\n : innerCacheStore.stale\n\n const entry: CacheEntry = {\n value: bufferStream,\n timestamp: startTime,\n revalidate: collectedRevalidate,\n expire: collectedExpire,\n stale: collectedStale,\n tags: collectedTags === null ? [] : collectedTags,\n }\n\n const collected: CollectedCacheResult = {\n entry,\n hasExplicitRevalidate: innerCacheStore.explicitRevalidate !== undefined,\n hasExplicitExpire: innerCacheStore.explicitExpire !== undefined,\n readRootParamNames: innerCacheStore.readRootParamNames,\n // The store accumulates this from nested public caches that propagated a\n // dynamic life into us.\n dynamicNestedCacheError:\n innerCacheStore.type === 'cache'\n ? innerCacheStore.dynamicNestedCacheError\n : undefined,\n }\n\n if (!cacheContext.skipPropagation) {\n maybePropagateCacheEntryMetadata(cacheContext, {\n tags: collected.entry.tags,\n revalidate: collected.entry.revalidate,\n expire: collected.entry.expire,\n stale: collected.entry.stale,\n timestamp: collected.entry.timestamp,\n hasExplicitRevalidate: collected.hasExplicitRevalidate,\n hasExplicitExpire: collected.hasExplicitExpire,\n readRootParamNames: collected.readRootParamNames,\n dynamicNestedCacheError: collected.dynamicNestedCacheError,\n })\n\n const cacheSignal = getCacheSignal(cacheContext.outerWorkUnitStore)\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n }\n\n return collected\n}\n\ntype GenerateCacheEntryResult =\n | {\n readonly type: 'cached'\n readonly stream: ReadableStream\n readonly pendingCacheResult: Promise\n }\n | {\n readonly type: 'prerender-dynamic'\n readonly reason: typeof FALLBACK_PARAMS | typeof RUNTIME_DATA\n readonly hangingPromise: Promise\n }\n\nasync function generateCacheEntryImpl(\n workStore: WorkStore,\n cacheContext: CacheContext,\n innerCacheStore: UseCacheStore,\n clientReferenceManifest: DeepReadonly,\n encodedArguments: FormData | string,\n fn: (...args: unknown[]) => Promise,\n timeoutError: UseCacheTimeoutError,\n deadlockError: UseCacheDeadlockError | undefined\n): Promise {\n const temporaryReferences = createServerTemporaryReferenceSet()\n const outerWorkUnitStore = cacheContext.outerWorkUnitStore\n\n const [, args] =\n typeof encodedArguments === 'string'\n ? await decodeReply(\n encodedArguments,\n getServerModuleMap(),\n { temporaryReferences }\n )\n : await decodeReplyFromAsyncIterable(\n {\n async *[Symbol.asyncIterator]() {\n for (const entry of encodedArguments) {\n yield entry\n }\n\n switch (outerWorkUnitStore.type) {\n case 'prerender-runtime':\n case 'prerender':\n // The encoded arguments might contain hanging promises. In\n // this case we don't want to reject with \"Error: Connection\n // closed.\", so we intentionally keep the iterable alive. This\n // is similar to the halting trick that we do while rendering.\n await new Promise((resolve) => {\n if (outerWorkUnitStore.renderSignal.aborted) {\n resolve()\n } else {\n outerWorkUnitStore.renderSignal.addEventListener(\n 'abort',\n () => resolve(),\n { once: true }\n )\n }\n })\n break\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n outerWorkUnitStore satisfies never\n }\n },\n },\n getServerModuleMap(),\n { temporaryReferences }\n )\n\n // Track the timestamp when we started computing the result.\n const startTime = performance.timeOrigin + performance.now()\n\n // Invoke the inner function to load a new result. We delay the invocation\n // though, until React awaits the promise so that React's request store (ALS)\n // is available when the function is invoked. This allows us, for example, to\n // capture logs so that we can later replay them.\n const resultPromise = createLazyResult(fn.bind(null, ...args))\n\n const errors: Array = []\n\n // In the \"Cache\" environment, we only need to make sure that the error\n // digests are handled correctly. Error formatting and reporting is not\n // necessary here; the errors are encoded in the stream, and will be reported\n // in the \"Server\" environment.\n const handleError = createReactServerErrorHandler(\n process.env.NODE_ENV === 'development',\n workStore.isBuildTimePrerendering ?? false,\n workStore.reactServerErrorsByDigest,\n (error) => {\n // In production, we log the original error here. It gets a digest that\n // can be used to associate the error with the obfuscated error that might\n // be logged if the error is caught. In development, we prefer logging the\n // transported error in the server environment. It's not obfuscated and\n // also includes the (dev-only) environment name.\n if (process.env.NODE_ENV === 'production') {\n Log.error(error)\n }\n\n errors.push(error)\n }\n )\n\n let stream: ReadableStream\n let devTimeoutAbortController: AbortController | undefined\n\n switch (outerWorkUnitStore.type) {\n case 'cache':\n case 'prerender-runtime':\n case 'prerender': {\n const prerenderStore =\n outerWorkUnitStore.type === 'cache'\n ? outerWorkUnitStore.fallbackRootParamsPrerender\n : outerWorkUnitStore\n\n if (prerenderStore === null) {\n stream = renderToReadableStream(\n resultPromise,\n clientReferenceManifest.clientModules,\n {\n environmentName: 'Cache',\n filterStackFrame,\n temporaryReferences,\n onError: handleError,\n }\n )\n break\n }\n\n const timeoutAbortController = new AbortController()\n const timer = setTimeout(\n () => {\n workStore.invalidDynamicUsageError = timeoutError\n timeoutAbortController.abort(timeoutError)\n },\n getUseCacheFillTimeoutMs(workStore, prerenderStore.type)\n )\n\n const dynamicAccessStore = dynamicAccessAsyncStorage.getStore()\n const dynamicAccessAbortSignal =\n dynamicAccessStore?.abortController.signal\n\n const abortSignal = dynamicAccessAbortSignal\n ? AbortSignal.any([\n dynamicAccessAbortSignal,\n timeoutAbortController.signal,\n ])\n : timeoutAbortController.signal\n\n const { prelude } = await prerender(\n resultPromise,\n clientReferenceManifest.clientModules,\n {\n environmentName: 'Cache',\n filterStackFrame,\n signal: abortSignal,\n temporaryReferences,\n onError(error) {\n if (abortSignal.aborted && abortSignal.reason === error) {\n return undefined\n }\n\n return handleError(error)\n },\n }\n )\n\n clearTimeout(timer)\n const didTimeout = timeoutAbortController.signal.aborted\n if (dynamicAccessAbortSignal) {\n // Release React's listener from the composite signal.\n timeoutAbortController.abort()\n }\n\n if (didTimeout) {\n // When the timeout is reached we always error the stream. Even for\n // fallback shell prerenders we don't want to return a hanging promise,\n // which would allow the function to become a dynamic hole. Because that\n // would mean that a non-empty shell could be generated which would be\n // subject to revalidation, and we don't want to create long\n // revalidation times.\n stream = new ReadableStream({\n start(controller) {\n controller.error(timeoutAbortController.signal.reason)\n },\n })\n } else if (dynamicAccessAbortSignal?.aborted) {\n const reason = dynamicAccessStore?.reason ?? 'runtime'\n const makeHangingPromise =\n reason === 'fallback-params'\n ? makeFallbackParamsHangingPromise\n : makeURLDataHangingPromise\n if (\n innerCacheStore.type === 'cache' &&\n innerCacheStore.fallbackRootParamsPrerender !== null\n ) {\n // No entry is collected for an aborted fill. Still remember the\n // roots actually read so a concrete request won't join this result\n // under the coarse key. Propagate them through aborted parents too.\n addKnownRootParamNames(\n cacheContext.functionId,\n innerCacheStore.readRootParamNames\n )\n const hangingPromise = trackPromiseUsed(\n makeHangingPromise(\n prerenderStore.renderSignal,\n workStore.route,\n 'dynamic \"use cache\"',\n // The single wrapper below tracks access when consumed.\n null\n ),\n () => {\n if (reason === 'fallback-params') {\n trackFallbackParamsAccessed(\n prerenderStore,\n 'dynamic \"use cache\"'\n )\n } else {\n trackURLDataAccessed(prerenderStore, 'dynamic \"use cache\"')\n }\n // The result may also be consumed by a deduped invocation, so\n // record dependencies against the cache consuming it now.\n const consumer = workUnitAsyncStorage.getStore()\n if (consumer !== undefined && consumer.type === 'cache') {\n for (const name of innerCacheStore.readRootParamNames) {\n consumer.readRootParamNames.add(name)\n }\n }\n // Only a cache consuming this result must suspend. Do not share\n // cancellation with independent sibling cache fills.\n abortOnDynamicAccess(reason, dynamicAccessAbortSignal.reason)\n }\n )\n getCacheSignal(outerWorkUnitStore)?.endRead()\n return {\n type: 'prerender-dynamic',\n reason:\n reason === 'fallback-params' ? FALLBACK_PARAMS : RUNTIME_DATA,\n hangingPromise,\n }\n }\n\n // If the prerender is aborted because of dynamic access (e.g. reading\n // fallback params), we return a hanging promise. This essentially makes\n // the \"use cache\" function dynamic.\n const hangingPromise = makeHangingPromise(\n prerenderStore.renderSignal,\n workStore.route,\n 'dynamic \"use cache\"',\n outerWorkUnitStore\n )\n\n getCacheSignal(outerWorkUnitStore)?.endRead()\n\n return {\n type: 'prerender-dynamic',\n reason: reason === 'fallback-params' ? FALLBACK_PARAMS : RUNTIME_DATA,\n hangingPromise,\n }\n } else {\n stream = prelude\n }\n break\n }\n case 'request':\n // TODO: We should just check if the render is abandonable. This is\n // relevant in restart-on-cache-miss in general, so when we implement that\n // for cached navs, it'll also be needed in prod\n if (process.env.__NEXT_DEV_SERVER && outerWorkUnitStore.cacheSignal) {\n const stagedRendering = outerWorkUnitStore.stagedRendering\n\n // Capture the render stage at the start of this cache read, before the\n // yield below. A streamed staged render advances its controller on its\n // own schedule, independently of this read, so by the time the yield\n // resolves the controller may have raced ahead to the Dynamic stage even\n // though the read began in an earlier (prerender) stage.\n const stageAtReadStart = stagedRendering?.currentStage\n\n // If we're filling caches for a staged render, make sure that it takes\n // at least a task, so we'll always notice a cache miss between stages.\n //\n // TODO(restart-on-cache-miss): This is suboptimal. Ideally microtasky\n // caches wouldn't register as a miss, but short-lived caches are only\n // omitted correctly when read back in a separate render (now the\n // background validation render, not a restart of the streamed\n // response), so forcing the miss is the best we can do until that's\n // refactored.\n await new Promise((resolve) => setTimeout(resolve))\n\n // Start a cache-fill timeout so a hanging `'use cache'` entry surfaces\n // the same error in dev as during prerender. Cleared when\n // pendingCacheResult settles.\n //\n // Skip the timeout only when the read began in the Dynamic stage, which\n // mirrors prerender: a cache guarded by e.g. `await connection()` is a\n // legitimate dynamic hole and isn't executed there. We use the stage\n // captured at read start, not the current one, because the staged render\n // may have advanced past it during the yield above.\n if (stageAtReadStart !== RenderStage.Dynamic) {\n const devRenderAbortController = new AbortController()\n const fillTimeoutMs = getUseCacheFillTimeoutMs(\n workStore,\n outerWorkUnitStore.type\n )\n const fillDeadlineAt = performance.now() + fillTimeoutMs\n const devRenderTimeoutTimer = setTimeout(() => {\n workStore.invalidDynamicUsageError = timeoutError\n devRenderAbortController.abort(timeoutError)\n }, fillTimeoutMs)\n\n devTimeoutAbortController = new AbortController()\n devTimeoutAbortController.signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(devRenderTimeoutTimer)\n },\n { once: true }\n )\n\n stream = renderToReadableStream(\n resultPromise,\n clientReferenceManifest.clientModules,\n {\n environmentName: 'Cache',\n filterStackFrame,\n signal: devRenderAbortController.signal,\n temporaryReferences,\n onError(error) {\n if (\n devRenderAbortController.signal.aborted &&\n devRenderAbortController.signal.reason === error &&\n error instanceof Error\n ) {\n // The abort reason is the same error stored as\n // `workStore.invalidDynamicUsageError` (a fill timeout or\n // deadlock). Register it under a digest and return that\n // digest, so the error that surfaces on the consumer side of\n // this Flight boundary carries it and the outer render's\n // handler can recover *this* object via\n // `reactServerErrorsByDigest`.\n //\n // We deliberately do not set `error.digest` here: whether the\n // error actually surfaces (vs. being caught in userland) is\n // the consumer's decision, so the \"surfaced\" mark is left to\n // the outer handler.\n const digest = stringHash(\n error.message + (error.stack || '')\n ).toString()\n\n workStore.reactServerErrorsByDigest.set(\n digest,\n error as DigestedError\n )\n\n return digest\n }\n\n return handleError(error)\n },\n }\n )\n\n // `require` (rather than a top-level import) so the bundler can\n // tree-shake the probe scheduler out of the production runtime, where\n // this whole dev-server-gated branch is dead code.\n const { setupProbeScheduler } =\n require('./use-cache-probe-scheduler') as typeof import('./use-cache-probe-scheduler')\n stream = setupProbeScheduler({\n workStore,\n outerRequestStore: outerWorkUnitStore,\n cacheContext,\n encodedArguments,\n fillDeadlineAt,\n stream,\n abortSignal: AbortSignal.any([\n devRenderAbortController.signal,\n devTimeoutAbortController.signal,\n ]),\n onProbeCompleted() {\n const error =\n deadlockError ??\n new InvariantError(\n '`deadlockError` should be constructed inside `cache()` before reaching the probe scheduler.'\n )\n workStore.invalidDynamicUsageError = error\n devRenderAbortController.abort(error)\n },\n })\n break\n }\n }\n // fallthrough\n case 'prerender-legacy':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n stream = renderToReadableStream(\n resultPromise,\n clientReferenceManifest.clientModules,\n {\n environmentName: 'Cache',\n filterStackFrame,\n temporaryReferences,\n onError: handleError,\n }\n )\n break\n default:\n return outerWorkUnitStore satisfies never\n }\n\n const [returnStream, savedStream] = stream.tee()\n\n const pendingCacheResult = collectResult(\n savedStream,\n workStore,\n cacheContext,\n innerCacheStore,\n startTime,\n errors\n ).finally(() => {\n devTimeoutAbortController?.abort()\n })\n\n if (process.env.NODE_ENV === 'development') {\n // Name the stream for React DevTools.\n // @ts-expect-error\n returnStream.name = 'use cache'\n }\n\n return {\n type: 'cached',\n // Return the stream as we're creating it. This means that if it ends up\n // erroring we cannot return a stale-if-error version but it allows\n // streaming back the result earlier.\n stream: returnStream,\n pendingCacheResult,\n }\n}\n\nfunction cloneCacheResult(\n result: CollectedCacheResult\n): [CollectedCacheResult, CollectedCacheResult] {\n const [entryA, entryB] = cloneCacheEntry(result.entry)\n return [\n {\n entry: entryA,\n hasExplicitRevalidate: result.hasExplicitRevalidate,\n hasExplicitExpire: result.hasExplicitExpire,\n readRootParamNames: result.readRootParamNames,\n dynamicNestedCacheError: result.dynamicNestedCacheError,\n },\n {\n entry: entryB,\n hasExplicitRevalidate: result.hasExplicitRevalidate,\n hasExplicitExpire: result.hasExplicitExpire,\n readRootParamNames: result.readRootParamNames,\n dynamicNestedCacheError: result.dynamicNestedCacheError,\n },\n ]\n}\n\nasync function clonePendingCacheResult(\n pendingCacheResult: Promise\n): Promise<[CollectedCacheResult, CollectedCacheResult]> {\n const result = await pendingCacheResult\n return cloneCacheResult(result)\n}\n\nasync function getNthCacheResult(\n split: Promise<[CollectedCacheResult, CollectedCacheResult]>,\n i: number\n): Promise {\n return (await split)[i]\n}\n\nasync function encodeFormData(formData: FormData): Promise {\n let result = ''\n for (let [key, value] of formData) {\n // We don't need this key to be serializable but from a security perspective it should not be\n // possible to generate a string that looks the same from a different structure. To ensure this\n // we need a delimeter between fields but just using a delimeter is not enough since a string\n // might contain that delimeter. We use the length of each field as the delimeter to avoid\n // escaping the values.\n result += key.length.toString(16) + ':' + key\n let stringValue\n if (typeof value === 'string') {\n stringValue = value\n } else {\n // The FormData might contain binary data that is not valid UTF-8 so this cache\n // key may generate a UCS-2 string. Passing this to another service needs to be\n // aware that the key might not be compatible.\n const arrayBuffer = await value.arrayBuffer()\n if (arrayBuffer.byteLength % 2 === 0) {\n stringValue = String.fromCodePoint(...new Uint16Array(arrayBuffer))\n } else {\n stringValue =\n String.fromCodePoint(\n ...new Uint16Array(arrayBuffer, 0, (arrayBuffer.byteLength - 1) / 2)\n ) +\n String.fromCodePoint(\n new Uint8Array(arrayBuffer, arrayBuffer.byteLength - 1, 1)[0]\n )\n }\n }\n result += stringValue.length.toString(16) + ':' + stringValue\n }\n return result\n}\n\nfunction createTrackedReadableStream(\n stream: ReadableStream,\n cacheSignal: CacheSignal\n) {\n const reader = stream.getReader()\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read()\n if (done) {\n controller.close()\n cacheSignal.endRead()\n } else {\n controller.enqueue(value)\n }\n },\n })\n}\n\nexport async function cache(\n kind: string,\n id: string,\n boundArgsLength: number,\n originalFn: (...args: unknown[]) => Promise,\n args: unknown[]\n) {\n const isPrivate = kind === 'private'\n\n // The default handler kind corresponds to the bare 'use cache' directive.\n const logPrefix = kind === 'default' ? `'use cache'` : `'use cache: ${kind}'`\n\n const workStore = workAsyncStorage.getStore()\n if (workStore === undefined) {\n throw new Error(\n '\"use cache\" cannot be used outside of App Router. Expected a WorkStore.'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore === undefined) {\n throw new InvariantError(\n '\"use cache\" cannot be used outside of App Router. Expected a WorkUnitStore.'\n )\n }\n\n // In a prerender, tasky IO may result in cache reads that start\n // after the prerender has already been aborted:\n //\n // await setTimeout(100) // we can't abort this uncached IO...\n // await cachedData() // ...so we'll still get here even though the prerender aborted\n //\n // The prerender is over, so we should just return an erroring promise.\n // (NOTE: we also shouldn't fill this cache, because it's behind uncached IO,\n // so semantically it is not part of the prerender)\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime': {\n if (workUnitStore.renderSignal.aborted) {\n // We don't know if the cache itself is dynamic or runtime data,\n // but the prerender is over, so it doesn't need to participate\n // in runtime data tracking at all.\n return makeUntrackedHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '\"use cache\" called after prerender ended'\n )\n }\n break\n }\n case 'prerender-legacy':\n case 'prerender-client':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n\n // Probe re-executions (the dev-server's hang-detection worker) short-circuit\n // further down before any handler is consulted, so we skip handler selection\n // entirely and the worker can boot without registering handlers at all.\n let cacheHandler: CacheReadWriteHandler | undefined\n if (workStore.useCacheProbeMode === undefined) {\n if (isPrivate) {\n // Private caches normally go to the Resume Data Cache (RDC), not a cache\n // handler. In development we additionally persist them in a dedicated\n // built-in in-memory handler so that reloads are fast.\n if (process.env.__NEXT_DEV_SERVER) {\n cacheHandler = getPrivateCacheHandler()\n }\n } else {\n const handler = getCacheHandler(kind)\n if (!handler) {\n throw new Error('Unknown cache handler: ' + kind)\n }\n\n // In development, a user-configured (custom) handler may be slow or\n // remote, so we read through a tiered handler that puts a built-in\n // in-memory front in front of it to keep cache hits microtask-fast.\n // Built-in handlers (the default handler, and its size-0 replacement) are\n // already in-memory and used directly.\n if (process.env.__NEXT_DEV_SERVER && isCustomCacheHandler(kind)) {\n // A custom kind always has a dev tiered handler: it is created in the\n // same `setCacheHandler` call that makes `isCustomCacheHandler` true.\n const tieredCacheHandler = getDevTieredCacheHandler(kind)\n\n if (!tieredCacheHandler) {\n throw new InvariantError(\n `Expected a dev tiered cache handler for kind \"${kind}\".`\n )\n }\n\n cacheHandler = tieredCacheHandler\n } else {\n cacheHandler = handler\n }\n }\n }\n\n const timeoutError = new UseCacheTimeoutError(workStore.route)\n Error.captureStackTrace(timeoutError, cache)\n applyOwnerStack(timeoutError)\n\n // Only ever thrown by the dev-server's hang-detection probe.\n // `Error.captureStackTrace` has to run while `cache()` is still on the\n // synchronous stack, otherwise the user's `'use cache'` invocation frames\n // would already be gone — that's why the construction sits up here rather\n // than next to the trigger that actually consumes it. The `__NEXT_DEV_SERVER`\n // gate lets the error class drop out of the production runtime bundle.\n let deadlockError: UseCacheDeadlockError | undefined\n if (process.env.__NEXT_DEV_SERVER) {\n deadlockError = new UseCacheDeadlockError(workStore.route)\n Error.captureStackTrace(deadlockError, cache)\n applyOwnerStack(deadlockError)\n }\n\n const wrapAsInvalidDynamicUsageError = (error: Error) => {\n Error.captureStackTrace(error, cache)\n workStore.invalidDynamicUsageError ??= error\n\n return error\n }\n\n const outerOwnerStack =\n process.env.NODE_ENV !== 'production'\n ? captureOuterOwnerStack(workUnitStore)\n : undefined\n\n const name = originalFn.name\n let fn = originalFn\n let cacheContext: CacheContext\n\n if (isPrivate) {\n const expression = '\"use cache: private\"'\n\n switch (workUnitStore.type) {\n // \"use cache: private\" is dynamic in prerendering contexts.\n case 'prerender':\n // Private caches can read request data. At this point we don't know\n // Whether it's going to use session data or URL data.\n // TODO(app-shells): This could be narrowed (and thus optimized) if we checked whether URL data\n // is included in the cache key, because it can only be passed in as arguments.\n return makeUnknownRuntimeDataHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n expression,\n workUnitStore\n )\n case 'prerender-legacy':\n return throwToInterruptStaticGeneration(\n expression,\n workStore,\n workUnitStore\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being allowed in client components statically, but did not in this case.`\n )\n case 'unstable-cache': {\n throw wrapAsInvalidDynamicUsageError(\n createUseCachePrivateInsideUnstableCacheError(workStore.route)\n )\n }\n case 'cache': {\n throw wrapAsInvalidDynamicUsageError(\n createUseCachePrivateInsidePublicUseCacheError(workStore.route)\n )\n }\n case 'request':\n case 'prerender-runtime':\n case 'private-cache':\n cacheContext = {\n kind: 'private',\n outerWorkUnitStore: workUnitStore,\n skipPropagation: false,\n outerOwnerStack,\n functionId: id,\n handlerKind: kind,\n }\n break\n case 'build-time-generator':\n throw wrapAsInvalidDynamicUsageError(\n createUseCachePrivateOutsideRequestContextError(\n workStore.route,\n workUnitStore.functionName\n )\n )\n default:\n workUnitStore satisfies never\n // This is dead code, but without throwing an error here, TypeScript\n // will assume that cacheContext is used before being assigned.\n throw new InvariantError(`Unexpected work unit store.`)\n }\n } else {\n switch (workUnitStore.type) {\n case 'prerender-client':\n case 'validation-client':\n const expression = '\"use cache\"'\n throw new InvariantError(\n `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being allowed in client components statically, but did not in this case.`\n )\n case 'cache': {\n // Eagerly capture this invocation's call site while still synchronous\n // in `cache()`. Used as `cause` of the nested-dynamic cache error\n // when the outer cache (whose body never re-runs during the final\n // prerender) throws. Only constructed when the parent is itself a\n // public `'use cache'` — otherwise this entry can never propagate\n // dynamism into that error and the allocation would be wasted. Private\n // parents are intentionally excluded: `'use cache: private'` is\n // dynamic-by-definition in prerendering and deferred to the runtime\n // stage in dev requests, so a public cache nested inside one never\n // triggers the throw upstream.\n const dynamicNestedCacheError = new NestedDynamicUseCacheError()\n Error.captureStackTrace(dynamicNestedCacheError, cache)\n applyOwnerStack(dynamicNestedCacheError)\n cacheContext = {\n kind: 'public',\n outerWorkUnitStore: workUnitStore,\n skipPropagation: false,\n outerOwnerStack,\n functionId: id,\n handlerKind: kind,\n dynamicNestedCacheError,\n }\n break\n }\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'request':\n case 'private-cache':\n // TODO: We should probably forbid nesting \"use cache\" inside\n // unstable_cache. (fallthrough)\n case 'unstable-cache':\n case 'build-time-generator':\n cacheContext = {\n kind: 'public',\n outerWorkUnitStore: workUnitStore,\n skipPropagation: false,\n outerOwnerStack,\n functionId: id,\n handlerKind: kind,\n dynamicNestedCacheError: undefined,\n }\n break\n default:\n workUnitStore satisfies never\n // This is dead code, but without throwing an error here, TypeScript\n // will assume that cacheContext is used before being assigned.\n throw new InvariantError(`Unexpected work unit store.`)\n }\n }\n\n // Get the clientReferenceManifest while we're still in the outer Context.\n // In case getClientReferenceManifestSingleton is implemented using AsyncLocalStorage.\n const clientReferenceManifest = getClientReferenceManifest()\n\n const hangingInputAbortSignal = createHangingInputAbortSignal(workUnitStore)\n\n if (cacheContext.kind === 'private') {\n const { outerWorkUnitStore } = cacheContext\n switch (outerWorkUnitStore.type) {\n case 'prerender-runtime': {\n // In a runtime prerender, we have to make sure that APIs that would hang during a static prerender\n // are resolved with a delay, in the appropriate runtime stage.\n const stagedRendering = outerWorkUnitStore.stagedRendering\n if (stagedRendering) {\n await stagedRendering.waitForStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n }\n break\n }\n case 'request': {\n if (isValidationRender(outerWorkUnitStore)) {\n // Similar to runtime prerenders, private caches should not resolve in the static stage\n // of a validation request, so we delay them.\n await makeDevtoolsIOAwarePromise(\n undefined,\n outerWorkUnitStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n }\n break\n }\n case 'private-cache':\n break\n default: {\n outerWorkUnitStore satisfies never\n }\n }\n }\n\n let isPageOrLayoutSegmentFunction = false\n\n // For page and layout segment functions (i.e. the page/layout component,\n // or generateMetadata/generateViewport), the cache function is\n // overwritten, which allows us to apply special handling for params and\n // searchParams. For pages and layouts we're using the outer params prop,\n // and not the inner one that was serialized/deserialized. While it's not\n // generally true for \"use cache\" args, in the case of `params` the inner\n // and outer object are essentially equivalent, so this is safe to do\n // (including fallback params that are hanging promises). It allows us to\n // avoid waiting for the timeout, when prerendering a fallback shell of a\n // cached page or layout that awaits params.\n if (isPageSegmentFunction(args)) {\n isPageOrLayoutSegmentFunction = true\n\n const [\n { params: outerParams, searchParams: outerSearchParams },\n ...otherOuterArgs\n ] = args\n\n const props: UseCachePageInnerProps = {\n params: outerParams,\n // Omit searchParams and $$isPage.\n }\n\n if (isPrivate) {\n // Private caches allow accessing search params. We need to include\n // them in the serialized args and when generating the cache key.\n props.searchParams = outerSearchParams\n }\n\n args = [props, ...otherOuterArgs]\n\n fn = {\n [name]: async (_: UseCachePageInnerProps, ...otherInnerArgs: unknown[]) =>\n originalFn.apply(null, [\n {\n params: props.params,\n searchParams:\n // Preserve the original search params, if this cache can access them.\n // Notably, in a runtime shell private caches can resolve, but search params\n // will be hanging, and we need to preserve the original proxied promise object\n // to trigger `dynamicAccessAbortSignal` when they're accessed.\n props.searchParams ??\n // For public caches, search params are omitted from the cache\n // key (and the serialized args) to avoid mismatches between\n // prerendering and resuming a cached page that does not\n // access search params. This is also the reason why we're not\n // using a hanging promise for search params. For cached pages\n // that do access them, which is an invalid dynamic usage, we\n // need to ensure that an error is shown.\n makeErroringSearchParamsForUseCache(),\n },\n ...otherInnerArgs,\n ]),\n }[name] as (...args: unknown[]) => Promise\n } else if (isLayoutSegmentFunction(args)) {\n isPageOrLayoutSegmentFunction = true\n\n const [\n { params: outerParams, $$isLayout, ...outerSlots },\n ...otherOuterArgs\n ] = args\n\n // Overwrite the props to omit $$isLayout. Note that slots are only\n // passed to the layout component (if any are defined), and not to\n // generateMetadata nor generateViewport. For those functions,\n // outerSlots/innerSlots is an empty object, which is fine because we're\n // just spreading it into the props.\n args = [{ params: outerParams, ...outerSlots }, ...otherOuterArgs]\n\n fn = {\n [name]: async (\n {\n params: _innerParams,\n ...innerSlots\n }: Omit,\n ...otherInnerArgs: unknown[]\n ) =>\n originalFn.apply(null, [\n { params: outerParams, ...innerSlots },\n ...otherInnerArgs,\n ]),\n }[name] as (...args: unknown[]) => Promise\n }\n\n if (boundArgsLength > 0) {\n if (args.length === 0) {\n throw new InvariantError(\n `Expected the \"use cache\" function ${JSON.stringify(fn.name)} to receive its encrypted bound arguments as the first argument.`\n )\n }\n\n const encryptedBoundArgs = args.shift() as Promise\n const boundArgs = await decryptActionBoundArgs(id, encryptedBoundArgs)\n\n if (!Array.isArray(boundArgs)) {\n throw new InvariantError(\n `Expected the bound arguments of \"use cache\" function ${JSON.stringify(fn.name)} to deserialize into an array, got ${typeof boundArgs} instead.`\n )\n }\n\n if (boundArgsLength !== boundArgs.length) {\n throw new InvariantError(\n `Expected the \"use cache\" function ${JSON.stringify(fn.name)} to receive ${boundArgsLength} bound arguments, got ${boundArgs.length} instead.`\n )\n }\n\n args.unshift(boundArgs)\n }\n\n const temporaryReferences = createClientTemporaryReferenceSet()\n\n // The base serialized cache key doesn't include runtime env var state or the\n // cookies and headers that private caches are allowed to read. Env var state\n // only scopes the cache handler because the RDC must reuse entries across\n // rendering phases. In production private cache entries aren't stored in a\n // cache handler, only in the Resume Data Cache (RDC): private caches are only\n // used during dynamic requests and runtime prefetches; for dynamic requests\n // the RDC is immutable and excludes private caches, and for runtime prefetches\n // it's mutable but lives only as long as the request. In development private\n // caches are persisted across requests, so `cacheHandlerKeyBase` (below)\n // additionally scopes the handler key by the request's cookies and headers.\n const { implementationPart, runtimeEnvVarStateHash } =\n await computeCacheKeyImplementationPart(workStore, workUnitStore, id)\n const cacheKeyParts: CacheKeyParts = [id, args, implementationPart]\n\n const encodeCacheKeyParts = () =>\n encodeReply(cacheKeyParts, {\n temporaryReferences,\n signal: hangingInputAbortSignal,\n })\n\n let encodedCacheKeyParts: FormData | string\n\n switch (workUnitStore.type) {\n case 'prerender-runtime':\n // A runtime prerender may be a runtime shell, which does not have access to\n // params/searchParams, so we want to apply the same dynamic access logic\n // as we do in static prerenders.\n // fallthrough\n case 'prerender':\n if (!isPageOrLayoutSegmentFunction) {\n // If the \"use cache\" function is not a page or layout segment\n // function, we need to track dynamic access already when encoding\n // the arguments. If params are passed explicitly into a \"use cache\"\n // function (as opposed to receiving them automatically in a page or\n // layout), we assume that the params are also accessed. This allows\n // us to abort early, and treat the function as dynamic, instead of\n // waiting for the timeout to be reached.\n const dynamicAccessStore: DynamicAccessAsyncStore = {\n abortController: new AbortController(),\n reason: null,\n }\n\n encodedCacheKeyParts = await dynamicAccessAsyncStorage.run(\n dynamicAccessStore,\n encodeCacheKeyParts\n )\n\n if (dynamicAccessStore.abortController.signal.aborted) {\n const makeHangingPromise =\n dynamicAccessStore.reason === 'fallback-params'\n ? makeFallbackParamsHangingPromise\n : makeURLDataHangingPromise\n return makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n 'dynamic \"use cache\"',\n workUnitStore\n )\n }\n break\n }\n // fallthrough\n case 'prerender-legacy':\n case 'request':\n // TODO(restart-on-cache-miss): We need to handle params/searchParams on page components.\n // the promises will be tasky, so `encodeCacheKeyParts` will not resolve in the static stage.\n // We have not started a cache read at this point, so we might just miss the cache completely.\n // fallthrough\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n case undefined:\n encodedCacheKeyParts = await encodeCacheKeyParts()\n break\n default:\n return workUnitStore satisfies never\n }\n\n // Probe path: we're running inside a pooled worker spawned by the dev\n // server to check whether a stalled cache fill would complete in an\n // isolated module scope. Skip the RDC / cache-handler / leader-election\n // machinery, call `generateCacheEntry` (same as a real cold fill), drain\n // the returned stream via `pendingCacheResult`, and apply the probe's own\n // timeout. The caller only cares whether the fill resolves; the result\n // value is discarded.\n //\n // Gated on `__NEXT_DEV_SERVER` so the entire branch — including its\n // `generateCacheEntry` call site and the threading of\n // `deadlockError` — drops out of the production runtime\n // bundle.\n if (process.env.__NEXT_DEV_SERVER && workStore.useCacheProbeMode) {\n // Both public and private caches probe via the same path. The worker\n // reconstructs real `headers` / `cookies` / `draftMode` from the\n // forwarded request snapshot, so private caches that legitimately read\n // those work in the probe just like in the real fill.\n const probeTimeoutMs = workStore.useCacheProbeMode.timeoutMs\n // The deadlock error never gets thrown from inside the worker: the\n // worker's outer store has `cacheSignal: undefined`, so\n // `generateCacheEntryImpl` skips the dev-request branch and the idle\n // probe is never set up.\n const result = await generateCacheEntry(\n workStore,\n cacheContext,\n clientReferenceManifest,\n encodedCacheKeyParts,\n fn,\n timeoutError,\n undefined\n )\n if (result.type === 'prerender-dynamic') {\n // Unreachable in the probe: outer store is `'request'`-typed, which\n // never produces this variant.\n throw new InvariantError(\n 'Unexpected `prerender-dynamic` result in `use cache` probe mode.'\n )\n }\n // We don't consume the returned stream — `pendingCacheResult` is what\n // completes when `collectResult` has drained `savedStream`. Cancel the\n // unused copy so it doesn't buffer forever.\n result.stream.cancel().catch(() => {})\n let probeTimeoutTimer: ReturnType | undefined\n try {\n await Promise.race([\n result.pendingCacheResult,\n new Promise((_, reject) => {\n probeTimeoutTimer = setTimeout(\n () => reject(timeoutError),\n probeTimeoutMs\n )\n }),\n ])\n } finally {\n if (probeTimeoutTimer !== undefined) {\n clearTimeout(probeTimeoutTimer)\n }\n }\n return\n }\n\n const serializedCacheKey =\n typeof encodedCacheKeyParts === 'string'\n ? // Fast path for the simple case for simple inputs. We let the CacheHandler\n // Convert it to an ArrayBuffer if it wants to.\n encodedCacheKeyParts\n : await encodeFormData(encodedCacheKeyParts)\n\n const rootParams = workUnitStore.rootParams\n const knownRootParamNames = knownRootParamsByFunctionId.get(id)\n\n // The coarse cache-handler key. With no root params read, it locates the\n // entry directly; otherwise it locates a redirect entry from which the\n // specific key (this key + root params, computed below) is derived. It's\n // scoped by runtime env var state and, for private caches in development\n // (persisted in the built-in in-memory handler), the request's cookies and\n // headers. Keys derived from it inherit that scoping.\n const cacheHandlerKeyBase =\n serializedCacheKey +\n (runtimeEnvVarStateHash ?? '') +\n (process.env.__NEXT_DEV_SERVER && cacheContext.kind === 'private'\n ? computePrivateCacheKeyRequestSuffix(\n cacheContext.outerWorkUnitStore.cookies,\n cacheContext.outerWorkUnitStore.headers\n )\n : '')\n // If we already know which root params this function reads, include them in\n // the cache handler key for a direct hit (skipping the redirect entry).\n // rootParams is undefined when nested inside unstable_cache.\n let cacheHandlerKey =\n knownRootParamNames && rootParams\n ? cacheHandlerKeyBase +\n computeRootParamsCacheKeySuffix(rootParams, knownRootParamNames)\n : cacheHandlerKeyBase\n\n let stream: undefined | ReadableStream = undefined\n\n // Set when a short-lived cache hit ends its cache read up front (dev only) so\n // the static-shell boundary doesn't count it as a phantom miss. Once set, the\n // cache signal read is balanced, so serving must use a plain stream and skip\n // any trailing cacheSignal.endRead() call.\n let cacheSignalReadEnded = false\n\n const resumeDataCache = getResumeDataCache(workUnitStore)\n\n const implicitTags = workUnitStore.implicitTags?.tags ?? []\n\n if (resumeDataCache) {\n // If this cache key was already determined to be dynamic during the\n // prospective prerender (e.g. because it accessed fallback params), we\n // return a hanging promise early to avoid trying to regenerate the entry,\n // which would be aborted anyway.\n let rdcEntry = resumeDataCache.cache.get(serializedCacheKey)\n if (\n rdcEntry === FALLBACK_PARAMS ||\n rdcEntry === RUNTIME_DATA ||\n rdcEntry === SESSION_DATA\n ) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime': {\n let makeHangingPromise\n if (rdcEntry === FALLBACK_PARAMS) {\n makeHangingPromise = makeFallbackParamsHangingPromise\n } else if (rdcEntry === SESSION_DATA) {\n makeHangingPromise = makeSessionDataHangingPromise\n } else {\n makeHangingPromise = makeURLDataHangingPromise\n }\n return makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n 'dynamic \"use cache\"',\n workUnitStore\n )\n }\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n // Requests may receive the in-memory cache too. Unlike a prerender, they\n // can resolve these holes, so treat a marker as an ordinary cache miss.\n rdcEntry = undefined\n }\n\n const cacheSignal = getCacheSignal(workUnitStore)\n\n if (cacheSignal) {\n cacheSignal.beginRead()\n }\n if (rdcEntry !== undefined) {\n let rdcResult: CollectedCacheResult | undefined = await rdcEntry\n\n // Check if the RDC entry should be discarded due to recently revalidated\n // tags. When a server action calls updateTag(), the re-render should see\n // fresh data instead of stale RDC data.\n if (rdcResult !== undefined) {\n const { timestamp } = rdcResult.entry\n\n if (\n rdcResult.entry.tags.some((tag) =>\n isRevalidatedAfter(tag, timestamp, workStore, logPrefix)\n ) ||\n implicitTags.some((tag) =>\n isRevalidatedAfter(tag, timestamp, workStore, logPrefix)\n )\n ) {\n debug?.(\n logPrefix,\n 'discarding RDC entry due to recently revalidated tags',\n serializedCacheKey\n )\n rdcResult = undefined\n }\n }\n\n if (rdcResult !== undefined) {\n if (\n rdcResult.entry.revalidate === 0 ||\n rdcResult.entry.expire < MIN_PRERENDERABLE_EXPIRE\n ) {\n // The nested-cache error only makes sense when a dynamic nested cache\n // actually shortened an outer cache that has no explicit `cacheLife`\n // (`dynamicNestedCacheError` is set), and only when the app's default\n // profile is itself prerenderable. If the default profile is already\n // dynamic (`revalidate: 0` or an `expire` under the prerenderable\n // minimum), every cache is omitted from prerenders by default, so\n // there is no silent degradation to warn about. A short life from the\n // default profile, or from a dev private cache's self-imposed\n // `revalidate: 0` (which never carries a nested error), therefore\n // stays a dynamic hole rather than erroring.\n const defaultCacheLife = workStore.cacheLifeProfiles.default\n const shouldReportNestedCacheError =\n rdcResult.dynamicNestedCacheError !== undefined &&\n defaultCacheLife.revalidate !== 0 &&\n defaultCacheLife.expire >= MIN_PRERENDERABLE_EXPIRE\n\n switch (workUnitStore.type) {\n case 'prerender':\n // In a Dynamic I/O prerender, if the cache entry has\n // revalidate: 0 or if the expire time is under 5 minutes,\n // then we consider this cache entry dynamic as it's not worth\n // generating static pages for such data. It's better to leave\n // a dynamic hole that can be filled in during the resume with\n // a potentially cached entry.\n if (rdcResult.entry.revalidate === 0) {\n if (\n rdcResult.hasExplicitRevalidate === false &&\n shouldReportNestedCacheError\n ) {\n throw wrapAsInvalidDynamicUsageError(\n createNestedCacheZeroRevalidateError(\n workStore.route,\n rdcResult.dynamicNestedCacheError\n )\n )\n }\n debug?.(\n logPrefix,\n 'omitting entry',\n serializedCacheKey,\n 'from static shell due to revalidate: 0'\n )\n } else {\n if (\n rdcResult.hasExplicitExpire === false &&\n shouldReportNestedCacheError\n ) {\n throw wrapAsInvalidDynamicUsageError(\n createNestedCacheShortExpireError(\n workStore.route,\n rdcResult.dynamicNestedCacheError\n )\n )\n }\n debug?.(\n logPrefix,\n 'omitting entry',\n serializedCacheKey,\n 'from static shell due to short expire value:',\n rdcResult.entry.expire\n )\n }\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n // The entry is only excluded from *static* prerenders — the\n // 'prerender-runtime' case below serves it.\n // TODO(app-shells): Does this handle the MIN_SHELL_STALE case below correctly?\n return makeSessionDataHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n 'dynamic \"use cache\"',\n workUnitStore\n )\n case 'prerender-runtime': {\n // In the final phase of a runtime prerender, we have to make\n // sure that APIs that would hang during a static prerender\n // are resolved with a delay, in the appropriate runtime stage.\n const stagedRendering = workUnitStore.stagedRendering\n if (stagedRendering) {\n await stagedRendering.waitForStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n }\n break\n }\n case 'request': {\n if (isValidationRender(workUnitStore)) {\n // These throws force an explicit cache life decision on an\n // outer cache that a nested cache would otherwise silently\n // shorten (see `shouldReportNestedCacheError` above). Otherwise\n // the short-lived entry is deferred as a dynamic hole below.\n if (\n rdcResult.entry.revalidate === 0 &&\n rdcResult.hasExplicitRevalidate === false &&\n shouldReportNestedCacheError\n ) {\n throw wrapAsInvalidDynamicUsageError(\n createNestedCacheZeroRevalidateError(\n workStore.route,\n rdcResult.dynamicNestedCacheError\n )\n )\n }\n if (\n rdcResult.entry.expire < MIN_PRERENDERABLE_EXPIRE &&\n rdcResult.hasExplicitExpire === false &&\n shouldReportNestedCacheError\n ) {\n throw wrapAsInvalidDynamicUsageError(\n createNestedCacheShortExpireError(\n workStore.route,\n rdcResult.dynamicNestedCacheError\n )\n )\n }\n // A short-lived entry is a dynamic hole, excluded from the\n // static shell, so we end the cache signal read here (the\n // prerender case does the same) to avoid this cache hit being\n // considered a cache miss when checking for pending cache reads\n // at staged rendering task boundaries. The value is deferred to\n // the runtime stage.\n if (cacheSignal && !cacheSignalReadEnded) {\n cacheSignal.endRead()\n cacheSignalReadEnded = true\n }\n\n await makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n }\n break\n }\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (rdcResult.entry.stale < MIN_SHELL_STALE) {\n // The entry's stale time is short enough that it's excluded from\n // shells. If it's below `MIN_PREFETCHABLE_STALE`, it's not worth\n // prefetching at all and is excluded from prerenders entirely,\n // leaving a dynamic hole that can be filled during the navigation.\n // Otherwise, it's still included in prerenders and cached\n // navigations, but it must not be part of an App Shell, which may\n // be reused on the client for longer than the entry's stale time.\n // We delay the entry to resolve in the post-shell (link data)\n // stage, which excludes both its content and its stale time from\n // the shell.\n const isPrefetchable = rdcResult.entry.stale >= MIN_PREFETCHABLE_STALE\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime': {\n const prerenderStore = workUnitStore\n if (!isPrefetchable) {\n debug?.(\n logPrefix,\n 'omitting entry',\n serializedCacheKey,\n 'from shell due to short stale value:',\n rdcResult.entry.stale\n )\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n // An unprefetchable entry (stale < MIN_PREFETCHABLE_STALE) is\n // excluded from all prerenders.\n return makeDynamicHangingPromise(\n prerenderStore.renderSignal,\n workStore.route,\n 'dynamic \"use cache\"'\n )\n } else {\n // This entry is prefetchable, but exluded from shells.\n\n const stagedRendering = prerenderStore.stagedRendering\n if (stagedRendering === null) {\n // Prospective prerender (no staging): do not delay, because if we didn't\n // have this entry in the RDC already, we wouldn't delay it either.\n } else {\n // Final prerender (with staging).\n // This entry cannot be part of the shell, so we delay it to the prefetch.\n let prefetchStage: AdvanceableRenderStage\n if (prerenderStore.type === 'prerender') {\n prefetchStage =\n RENDER_STAGES_BY_DATA_KIND.staticUrlData.static\n } else {\n prefetchStage = RENDER_STAGES_BY_DATA_KIND.runtimeUrlData\n }\n if (\n // If the prerender ends before the prefetch stage (because\n // render that only produces an App Shell), this cache\n // should be omitted entirely.\n stagedRendering.finalStage !== null &&\n stagedRendering.finalStage < prefetchStage\n ) {\n debug?.(\n logPrefix,\n 'omitting entry',\n serializedCacheKey,\n 'from shell due to short stale value:',\n rdcResult.entry.stale\n )\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n // The entry was omitted only because this prerender ends\n // before the prefetch stage. Neither static nor runtime\n // app shells include it, so it does not count as a runtime\n // data access.\n return makePrefetchHangingPromise(\n prerenderStore.renderSignal,\n workStore.route,\n 'dynamic \"use cache\"'\n )\n } else {\n debug?.(\n logPrefix,\n 'delaying entry',\n serializedCacheKey,\n 'until the prefetch stage due to short stale value:',\n rdcResult.entry.stale\n )\n await stagedRendering.waitForStage(prefetchStage)\n }\n }\n }\n\n break\n }\n case 'request': {\n if (isValidationRender(workUnitStore)) {\n // End the cache signal read (once, in case an earlier block\n // already did) so the delayed value isn't counted as a pending\n // read at a staged rendering boundary.\n if (cacheSignal && !cacheSignalReadEnded) {\n cacheSignal.endRead()\n cacheSignalReadEnded = true\n }\n let stage: AdvanceableRenderStage\n if (!isPrefetchable) {\n // An unprefetchable entry is excluded from prerenders, so it\n // resolves in the dynamic stage.\n stage = RenderStage.Dynamic\n } else {\n // If the entry would be be excluded from the shell, treat it as\n // if it were static URL data.\n // (Note that this is still correct without PPF or in static shell validation,\n // where we don't use runtime shells and include static URL data)\n trackIncompatibleShellContent(\n workUnitStore,\n '\"use cache\" excluded from app shells due to a short staletime'\n )\n stage =\n RENDER_STAGES_BY_DATA_KIND.staticUrlData[\n workUnitStore.needsRuntimeShell ? 'runtime' : 'static'\n ]\n }\n debug?.(\n logPrefix,\n 'delaying entry',\n serializedCacheKey,\n `until after the ${RenderStage[stage]} stage due to short stale value:`,\n rdcResult.entry.stale\n )\n await makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n stage\n )\n }\n break\n }\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n if (rdcResult !== undefined) {\n debug?.(logPrefix, 'Resume Data Cache entry found', serializedCacheKey)\n\n if (\n rdcResult.readRootParamNames &&\n rdcResult.readRootParamNames.size > 0\n ) {\n addKnownRootParamNames(id, rdcResult.readRootParamNames)\n }\n\n // We want to make sure we only propagate cache life & tags if the\n // entry was *not* omitted from the prerender. So we only do this\n // after the above early returns.\n propagateCacheEntryMetadata(cacheContext, {\n tags: rdcResult.entry.tags,\n revalidate: rdcResult.entry.revalidate,\n expire: rdcResult.entry.expire,\n stale: rdcResult.entry.stale,\n timestamp: rdcResult.entry.timestamp,\n hasExplicitRevalidate: rdcResult.hasExplicitRevalidate,\n hasExplicitExpire: rdcResult.hasExplicitExpire,\n readRootParamNames: rdcResult.readRootParamNames,\n dynamicNestedCacheError: rdcResult.dynamicNestedCacheError,\n })\n\n const [streamA, streamB] = rdcResult.entry.value.tee()\n rdcResult.entry.value = streamB\n\n if (cacheSignal && !cacheSignalReadEnded) {\n // When we have a cacheSignal we need to block on reading the cache\n // entry before ending the read.\n stream = createTrackedReadableStream(streamA, cacheSignal)\n } else {\n // The cache signal read was already ended for a short-lived deferral\n // (or there is no cacheSignal), so serve a plain stream.\n stream = streamA\n }\n } else {\n // Entry was discarded (e.g. due to recently revalidated tags)\n debug?.(\n logPrefix,\n 'Resume Data Cache entry discarded',\n serializedCacheKey\n )\n\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n }\n } else {\n debug?.(\n logPrefix,\n 'Resume Data Cache entry not found',\n serializedCacheKey,\n `(${resumeDataCache.cache.size} entries)`\n )\n\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n\n switch (workUnitStore.type) {\n case 'prerender':\n if (resumeDataCache?.mutable === false) {\n // We're prerendering a fallback shell whose Resume Data Cache is\n // the prefilled, read-only seed from a phase-1 prerender of a more-\n // specific sibling route. A miss here means the cache key depends\n // on a fallback param. We short-circuit to a dynamic hole (which\n // may produce an empty shell if there's no parent Suspense\n // boundary). Currently this also catches layouts and pages that\n // don't read params, which will be improved when we implement\n // NAR-136. Compared to the instrumentation-based params bailout we\n // also do here, this covers the case where params are transformed\n // with an async function before being passed into the \"use cache\"\n // function, which escapes the instrumentation.\n // The cache key depends on fallback params, which are URL data.\n return makeURLDataHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n 'dynamic \"use cache\"',\n workUnitStore\n )\n }\n // fallthrough\n case 'prerender-runtime':\n if (!cacheSignal) {\n // This is the final prerender (cacheSignal is null), which means\n // all caches should have been warmed during the prospective\n // prerender. A cache miss here indicates that the cache key is\n // non-deterministic (e.g. due to unstable array order in the\n // arguments). Known dynamic keys (e.g. from fallback params) are\n // already handled by the early return above. We return a hanging\n // promise so this becomes a dynamic hole rather than generating a\n // broken cache entry that gets aborted.\n console.warn(new UnexpectedCacheMissError(workStore.route))\n // This is an anomaly (non-deterministic cache key), so we can't\n // know whether a runtime prerender would resolve it.\n return makeUnknownRuntimeDataHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n 'dynamic \"use cache\"',\n workUnitStore\n )\n }\n break\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // Intra-request deduplication: Within a single request, root params are\n // fixed, so the coarse key (serializedCacheKey) is sufficient. If another\n // invocation in this request is already handling the same cache entry\n // (including the cache handler lookup and generation), we join it instead of\n // doing redundant work. This also saves cache handler `get` calls which may\n // be HTTP round-trips for remote handlers.\n if (stream === undefined) {\n const pendingInvocation =\n workStore.pendingCacheInvocations?.get(serializedCacheKey)\n\n // A pending invocation is joined unconditionally: its fill is shared, so\n // every joiner receives whatever that fill produces. A completed one is a\n // stored entry instead, so it is only reused when the caller hasn't asked\n // to bypass caches, and only if nothing has invalidated it since.\n const completedInvocation =\n pendingInvocation === undefined &&\n !shouldForceRevalidate(workStore, workUnitStore)\n ? workStore.completedCacheInvocations?.get(serializedCacheKey)\n : undefined\n\n const joinedInvocation = pendingInvocation ?? completedInvocation\n\n if (joinedInvocation) {\n const cacheSignal = getCacheSignal(workUnitStore)\n cacheSignal?.beginRead()\n\n debug?.(logPrefix, 'joining intra-request invocation', serializedCacheKey)\n const sharedCacheResult = await joinedInvocation\n\n if (sharedCacheResult.type === 'prerender-dynamic') {\n debug?.(\n logPrefix,\n 'joined invocation is prerender-dynamic',\n serializedCacheKey\n )\n if (resumeDataCache?.mutable) {\n // A nested-cache leader has no RDC. This consumer must carry the\n // omission reason into the final prerender instead of leaving an\n // unexplained miss that loses the fallback's prefetch hint.\n resumeDataCache.cache.set(\n serializedCacheKey,\n sharedCacheResult.reason\n )\n }\n cacheSignal?.endRead()\n return sharedCacheResult.hangingPromise\n }\n\n // A completed entry may have been invalidated since it was produced, by\n // an `updateTag()` in a server action earlier in this request. The\n // implicit tags expiration is passed as 0 because it cannot apply to a\n // retained entry: it is memoized for the request, so re-checking it\n // against an unchanged entry timestamp only repeats the answer the leader\n // already got.\n const metadata =\n completedInvocation === undefined\n ? undefined\n : await sharedCacheResult.entry.pendingMetadata\n\n if (\n metadata !== undefined &&\n shouldDiscardCacheEntry(\n metadata,\n workStore,\n workUnitStore,\n implicitTags,\n 0,\n logPrefix\n )\n ) {\n debug?.(\n logPrefix,\n 'discarding completed invocation',\n serializedCacheKey\n )\n workStore.completedCacheInvocations?.delete(serializedCacheKey)\n\n // This can take the signal's count to zero. The leader path below opens\n // a read again synchronously, before it awaits anything, which is what\n // stops a prerender from concluding that every cache read has settled\n // while a fill is still about to start.\n cacheSignal?.endRead()\n } else {\n debug?.(\n logPrefix,\n 'joined invocation resolved with cached entry',\n serializedCacheKey\n )\n\n stream = serveJoinedCacheEntry(\n sharedCacheResult.entry,\n serializedCacheKey,\n resumeDataCache,\n cacheContext,\n cacheSignal,\n logPrefix\n )\n }\n }\n }\n\n // Leader path: no pending intra-request invocation found. Check for a\n // cross-request pending invocation, or become the leader for both.\n if (stream === undefined) {\n const resolvableSharedCacheResult = new ResolvableSharedCacheResult()\n\n debug?.(\n logPrefix,\n 'registering as intra-request invocation leader',\n serializedCacheKey\n )\n const intraRequestPendingCacheInvocations =\n (workStore.pendingCacheInvocations ??= new Map<\n string,\n Promise\n >())\n\n // Retain the completed entry for the rest of the request where a later\n // invocation would otherwise repeat real work: private caches have no cache\n // handler to fall back on in production, and a platform- or config-supplied\n // handler may be remote, so a second `get` can be a round trip. A built-in\n // handler read is a map lookup, so retaining its entries would hold a\n // forked stream buffer for nothing.\n const completedCacheInvocations =\n isPrivate || !isBuiltInCacheHandler(kind)\n ? (workStore.completedCacheInvocations ??= new Map<\n string,\n Promise\n >())\n : undefined\n\n resolvableSharedCacheResult.registerIn(\n intraRequestPendingCacheInvocations,\n serializedCacheKey,\n completedCacheInvocations\n )\n\n // Cross-request deduplication lets concurrent requests for the same key\n // share a single fill. Private caches are skipped in production, where they\n // hold request-specific data that must not be shared across requests. In\n // development they're persisted and keyed by the request's cookies and\n // headers, so concurrent requests with identical request data should share\n // a fill too; that request-scoped `cacheHandlerKey` keeps requests with\n // different cookies or headers in separate entries.\n //\n // Draft mode requests are skipped as well, in both directions. A fill that\n // runs with draft mode enabled can contain unpublished content, so it must\n // not be registered for other requests to join. And a draft mode request\n // must not join a pending public fill, because it would be served the\n // published content instead of the draft.\n const skipCrossRequestDedupe =\n (isPrivate && !process.env.__NEXT_DEV_SERVER) || workStore.isDraftMode\n\n try {\n // The loop handles cross-request root param mismatches: when a\n // cross-request joiner discovers that the leader's root params differ\n // from its own, it retries with a recomputed cacheHandlerKey. The loop\n // exits when stream is assigned (cross-request joiner match or leader\n // path) or via early return (prerender-dynamic).\n while (stream === undefined) {\n const crossRequestPendingCacheInvocation = skipCrossRequestDedupe\n ? undefined\n : crossRequestPendingCacheInvocations.get(cacheHandlerKey)\n\n if (crossRequestPendingCacheInvocation) {\n const cacheSignal = getCacheSignal(workUnitStore)\n cacheSignal?.beginRead()\n\n debug?.(\n logPrefix,\n 'joining pending cross-request invocation',\n cacheHandlerKey\n )\n const sharedCacheResult = await crossRequestPendingCacheInvocation\n\n if (sharedCacheResult.type === 'cached') {\n // Verify root params before forking the stream. The shared\n // invocation must complete first, including collection and write\n // settlement. A changed key retries the handler lookup, which must\n // not run before the write settles.\n const metadata = await sharedCacheResult.entry.pendingCompletion\n\n // Ensure known root param names are up-to-date before verifying the\n // key, since the leader's save path may not have updated them yet\n // at this point.\n if (metadata.readRootParamNames) {\n addKnownRootParamNames(id, metadata.readRootParamNames)\n }\n\n const updatedRootParamNames = knownRootParamsByFunctionId.get(id)\n if (updatedRootParamNames && rootParams) {\n const newCacheHandlerKey =\n cacheHandlerKeyBase +\n computeRootParamsCacheKeySuffix(\n rootParams,\n updatedRootParamNames\n )\n\n if (newCacheHandlerKey !== cacheHandlerKey) {\n debug?.(\n logPrefix,\n 'cross-request root param mismatch, retrying',\n cacheHandlerKey,\n '→',\n newCacheHandlerKey\n )\n cacheSignal?.endRead()\n cacheHandlerKey = newCacheHandlerKey\n continue // stream is not used → retry with new key\n }\n }\n\n // Key matches — safe to fork.\n debug?.(\n logPrefix,\n 'cross-request invocation matched, forking result',\n cacheHandlerKey\n )\n cacheSignal?.endRead()\n stream = sharedCacheResult.entry.fork()\n maybePropagateCacheEntryMetadata(cacheContext, metadata)\n\n // The cross-request leader belongs to a different request with its\n // own RDC. Save to this request's RDC so its final prerender can\n // resume from the entry.\n saveSharedCacheEntryToResumeDataCache(\n serializedCacheKey,\n sharedCacheResult.entry,\n resumeDataCache,\n logPrefix\n )\n\n // Resolve for intra-request joiners in this request. They get\n // a fork from the same SharedCacheEntry.\n resolvableSharedCacheResult.resolve(sharedCacheResult)\n break\n } else {\n // prerender-dynamic — same root param check before hanging\n const updatedRootParamNames = knownRootParamsByFunctionId.get(id)\n if (updatedRootParamNames && rootParams) {\n const newCacheHandlerKey =\n cacheHandlerKeyBase +\n computeRootParamsCacheKeySuffix(\n rootParams,\n updatedRootParamNames\n )\n\n if (newCacheHandlerKey !== cacheHandlerKey) {\n debug?.(\n logPrefix,\n 'cross-request root param mismatch, retrying',\n cacheHandlerKey,\n '→',\n newCacheHandlerKey\n )\n cacheSignal?.endRead()\n cacheHandlerKey = newCacheHandlerKey\n continue\n }\n }\n\n debug?.(\n logPrefix,\n 'cross-request invocation is prerender-dynamic',\n cacheHandlerKey\n )\n if (resumeDataCache?.mutable) {\n resumeDataCache.cache.set(\n serializedCacheKey,\n sharedCacheResult.reason\n )\n }\n cacheSignal?.endRead()\n resolvableSharedCacheResult.resolve(sharedCacheResult)\n return sharedCacheResult.hangingPromise\n }\n }\n\n // No pending cross-request invocation — become the leader.\n if (!skipCrossRequestDedupe) {\n debug?.(\n logPrefix,\n 'registering as cross-request invocation leader',\n cacheHandlerKey\n )\n resolvableSharedCacheResult.registerIn(\n crossRequestPendingCacheInvocations,\n cacheHandlerKey\n )\n }\n\n const cacheSignal = getCacheSignal(workUnitStore)\n if (cacheSignal) {\n // Either the cache handler or the generation can be using I/O at this\n // point. We need to track when they start and when they complete.\n cacheSignal.beginRead()\n }\n\n const lazyRefreshTags = workStore.refreshTagsByCacheKind.get(kind)\n\n if (lazyRefreshTags && !isResolvedLazyResult(lazyRefreshTags)) {\n await lazyRefreshTags\n }\n\n let entry: CacheEntry | undefined\n let observedRevalidation: Promise | undefined\n\n // We ignore existing cache entries when force revalidating.\n if (cacheHandler && !shouldForceRevalidate(workStore, workUnitStore)) {\n // Record an existing revalidation before `get()` so a stale result\n // does not start another revalidation. The existing revalidation may\n // finish and remove its map entry before the lookup returns.\n observedRevalidation = backgroundRevalidations.get(cacheHandlerKey)\n entry = await cacheHandler.get(cacheHandlerKey, implicitTags)\n\n // Check if this is a redirect entry (coarse key → specific key).\n // Redirect entries have private tags encoding the root param names\n // (one tag per param name, prefixed with _N_RP_).\n if (entry && rootParams) {\n const paramNames = new Set()\n for (const tag of entry.tags) {\n if (tag.startsWith(NEXT_CACHE_ROOT_PARAM_TAG_ID)) {\n paramNames.add(tag.slice(NEXT_CACHE_ROOT_PARAM_TAG_ID.length))\n }\n }\n if (paramNames.size > 0) {\n addKnownRootParamNames(id, paramNames)\n cacheHandlerKey =\n cacheHandlerKeyBase +\n computeRootParamsCacheKeySuffix(rootParams, paramNames)\n observedRevalidation =\n backgroundRevalidations.get(cacheHandlerKey)\n entry = await cacheHandler.get(cacheHandlerKey, implicitTags)\n }\n }\n }\n\n if (entry) {\n let implicitTagsExpiration = 0\n\n if (workUnitStore.implicitTags) {\n const lazyExpiration =\n workUnitStore.implicitTags.expirationsByCacheKind.get(kind)\n\n if (lazyExpiration) {\n const expiration = isResolvedLazyResult(lazyExpiration)\n ? lazyExpiration.value\n : await lazyExpiration\n\n // If a cache handler returns an expiration time of Infinity, it\n // signals to Next.js that it handles checking cache entries for\n // staleness based on the expiration of the implicit tags passed\n // into the `get` method. In this case, we keep the default of 0,\n // which means that the implicit tags are not considered expired.\n if (expiration < Infinity) {\n implicitTagsExpiration = expiration\n }\n }\n }\n\n if (\n shouldDiscardCacheEntry(\n entry,\n workStore,\n workUnitStore,\n implicitTags,\n implicitTagsExpiration,\n logPrefix\n )\n ) {\n debug?.(logPrefix, 'discarding expired entry', cacheHandlerKey)\n entry = undefined\n }\n }\n\n const currentTime = performance.timeOrigin + performance.now()\n if (\n entry !== undefined &&\n (entry.revalidate === 0 || entry.expire < MIN_PRERENDERABLE_EXPIRE)\n ) {\n switch (workUnitStore.type) {\n case 'prerender':\n // In a Dynamic I/O prerender, if the cache entry has revalidate:\n // 0 or if the expire time is under 5 minutes, then we consider\n // this cache entry dynamic as it's not worth generating static\n // pages for such data. It's better to leave a dynamic hole that\n // can be filled in during the resume with a potentially cached\n // entry.\n if (entry.revalidate === 0) {\n debug?.(\n logPrefix,\n 'omitting entry',\n cacheHandlerKey,\n 'from static shell due to revalidate: 0'\n )\n } else {\n debug?.(\n logPrefix,\n 'omitting entry',\n cacheHandlerKey,\n 'from static shell due to short expire value:',\n entry.expire\n )\n }\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n\n // The entry is only excluded from *static* prerenders. A runtime\n // shell or prefetch would include this content.\n // TODO(app-shells): Does this handle the MIN_SHELL_STALE case below correctly?\n const hangingPromise = makeSessionDataHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n 'dynamic \"use cache\"',\n workUnitStore\n )\n debug?.(\n logPrefix,\n 'leader resolved as prerender-dynamic',\n cacheHandlerKey\n )\n resolvableSharedCacheResult.resolve({\n type: 'prerender-dynamic',\n reason: SESSION_DATA,\n hangingPromise,\n })\n return hangingPromise\n case 'request': {\n if (isValidationRender(workUnitStore)) {\n // A short-lived entry is a dynamic hole, excluded from the\n // static shell, so we end the cache signal read here (the\n // prerender case does the same) to avoid this cache hit being\n // considered a cache miss when checking for pending cache reads\n // at staged rendering task boundaries. The value is deferred to\n // the runtime stage.\n if (cacheSignal && !cacheSignalReadEnded) {\n cacheSignal.endRead()\n cacheSignalReadEnded = true\n }\n const stage = RENDER_STAGES_BY_DATA_KIND.sessionData\n debug?.(\n logPrefix,\n 'delaying entry',\n serializedCacheKey,\n `until after the ${RenderStage[stage]} stage due to short expire value:`,\n entry.expire\n )\n await makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n }\n break\n }\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (entry !== undefined && entry.stale < MIN_SHELL_STALE) {\n const isPrefetchable = entry.stale >= MIN_PREFETCHABLE_STALE\n switch (workUnitStore.type) {\n case 'request': {\n // Same as the resume data cache read path: the entry's stale\n // time is short enough that it's excluded from shells, or, if\n // it's below `MIN_PREFETCHABLE_STALE`, from prerenders\n // entirely.\n if (isValidationRender(workUnitStore)) {\n // End the cache signal read (once, in case the expire block\n // above already did) so the delayed value isn't counted as a\n // pending read at a staged rendering boundary.\n if (cacheSignal && !cacheSignalReadEnded) {\n cacheSignal.endRead()\n cacheSignalReadEnded = true\n }\n let stage: AdvanceableRenderStage\n if (!isPrefetchable) {\n // An unprefetchable entry is excluded from prerenders, so it\n // resolves in the dynamic stage.\n stage = RenderStage.Dynamic\n } else {\n // If the entry would be be excluded from the shell, treat it as\n // if it were static URL data.\n // (Note that this is still correct without PPF or in static shell validation,\n // where we don't use runtime shells and include static URL data)\n trackIncompatibleShellContent(\n workUnitStore,\n '\"use cache\" excluded from app shells due to a short staletime'\n )\n stage =\n RENDER_STAGES_BY_DATA_KIND.staticUrlData[\n workUnitStore.needsRuntimeShell ? 'runtime' : 'static'\n ]\n }\n debug?.(\n logPrefix,\n 'delaying entry',\n serializedCacheKey,\n `until after the ${RenderStage[stage]} stage due to short stale value:`,\n entry.stale\n )\n await makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n stage\n )\n }\n break\n }\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n // A handler read in a prerender context is a cache-filling read.\n // The stale exclusions for those are applied when the RDC is\n // read in the final prerender, so there's nothing to do here.\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (\n entry === undefined ||\n // In dev, the built-in default handler retains a short-`expire` entry\n // for at least `MIN_PRERENDERABLE_EXPIRE`, both when used directly\n // and when fronting a custom cache handler. Apply that same minimum\n // here so the retained entry is served and re-warmed in the\n // background (below), rather than blocking to regenerate it on every\n // read. The entry's real `expire` is untouched, so staging still\n // treats it as dynamic.\n currentTime >\n entry.timestamp +\n (process.env.__NEXT_DEV_SERVER\n ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)\n : entry.expire) *\n 1000 ||\n (willConsumerServerCache(workUnitStore) &&\n currentTime > entry.timestamp + entry.revalidate * 1000)\n ) {\n // Miss. Generate a new result.\n\n // If the cache entry is stale and its consumer will persist the\n // result in a server cache, don't persist the stale entry into a new\n // cache. We're not time constrained here, so regenerate it now.\n\n // We need to run this inside a clean AsyncLocalStorage snapshot so\n // that the cache generation cannot read anything from the context\n // we're currently executing which might include request specific\n // things like cookies() inside a React.cache().\n // Note: It is important that we await at least once before this\n // because it lets us pop out of any stack specific contexts as well -\n // aka \"Sync\" Local Storage.\n\n if (entry) {\n if (currentTime > entry.timestamp + entry.expire * 1000) {\n debug?.(logPrefix, 'entry is expired', cacheHandlerKey)\n }\n\n if (\n willConsumerServerCache(workUnitStore) &&\n currentTime > entry.timestamp + entry.revalidate * 1000\n ) {\n debug?.(\n logPrefix,\n 'foreground revalidation, entry is stale',\n cacheHandlerKey\n )\n }\n }\n\n if (cacheSignal && cacheSignalReadEnded) {\n // A short-lived deferral above (a `revalidate` of zero or a short\n // expire, or a short stale time) already ended this read. We're now\n // regenerating the entry rather than serving it, and the generation\n // ends the read again once its entry is collected. Re-begin the\n // read here so the trailing `endRead` stays balanced instead of\n // over-decrementing the cache signal.\n cacheSignal.beginRead()\n cacheSignalReadEnded = false\n }\n\n const result = await generateCacheEntry(\n workStore,\n cacheContext,\n clientReferenceManifest,\n encodedCacheKeyParts,\n fn,\n timeoutError,\n deadlockError\n )\n\n if (result.type === 'prerender-dynamic') {\n debug?.(\n logPrefix,\n 'leader resolved as prerender-dynamic (generation)',\n cacheHandlerKey\n )\n if (resumeDataCache?.mutable) {\n resumeDataCache.cache.set(serializedCacheKey, result.reason)\n }\n resolvableSharedCacheResult.resolve(result)\n return result.hangingPromise\n }\n\n const { stream: newStream, pendingCacheResult } = result\n\n let pendingWrite: Promise | undefined\n\n // When draft mode is enabled, we must not save the cache entry.\n if (!workStore.isDraftMode) {\n const savedCacheResult = saveToResumeDataCache(\n resumeDataCache,\n serializedCacheKey,\n pendingCacheResult,\n logPrefix\n )\n\n if (cacheHandler) {\n pendingWrite = saveToCacheHandler(\n cacheHandler,\n id,\n cacheHandlerKeyBase,\n savedCacheResult,\n rootParams\n )\n workStore.pendingRevalidateWrites ??= []\n workStore.pendingRevalidateWrites.push(pendingWrite)\n }\n }\n\n debug?.(\n logPrefix,\n 'leader resolved with generated entry',\n cacheHandlerKey\n )\n\n const pendingMetadata: Promise =\n pendingCacheResult.then((collected) => ({\n tags: collected.entry.tags,\n revalidate: collected.entry.revalidate,\n expire: collected.entry.expire,\n stale: collected.entry.stale,\n timestamp: collected.entry.timestamp,\n hasExplicitRevalidate: collected.hasExplicitRevalidate,\n hasExplicitExpire: collected.hasExplicitExpire,\n readRootParamNames: collected.readRootParamNames,\n dynamicNestedCacheError: collected.dynamicNestedCacheError,\n }))\n\n const sharedCacheEntry = new SharedCacheEntry(\n newStream,\n pendingMetadata,\n pendingWrite\n )\n stream = sharedCacheEntry.fork()\n resolvableSharedCacheResult.resolve({\n type: 'cached',\n entry: sharedCacheEntry,\n })\n } else {\n const entryMetadata: CacheResultMetadata = {\n tags: entry.tags,\n revalidate: entry.revalidate,\n expire: entry.expire,\n stale: entry.stale,\n timestamp: entry.timestamp,\n readRootParamNames: knownRootParamsByFunctionId.get(id),\n // For pre-existing entries from cache handlers we don't know\n // whether they had explicit cache life values or not. But we only\n // need this information during prerendering when we produce new\n // entries, where the cache life of an inner cache may be propagated\n // to the outer one. In that case we use the RDC. So it's safe to\n // set this to undefined here.\n hasExplicitRevalidate: undefined,\n hasExplicitExpire: undefined,\n // The same applies to the dynamic nested cache error.\n dynamicNestedCacheError: undefined,\n }\n\n maybePropagateCacheEntryMetadata(cacheContext, entryMetadata)\n\n // We want to return this stream, even if it's stale.\n stream = entry.value\n\n // If we have a mutable resume data cache, we need to clone the entry\n // and add it to the resume data cache.\n if (resumeDataCache?.mutable) {\n const [entryLeft, entryRight] = cloneCacheEntry(entry)\n if (cacheSignal && !cacheSignalReadEnded) {\n stream = createTrackedReadableStream(entryLeft.value, cacheSignal)\n } else {\n // The read was already ended for a short-lived deferral (or there\n // is no cacheSignal), so serve a plain stream.\n stream = entryLeft.value\n }\n\n // The RDC is per-page and root params are fixed within a page, so\n // we always use the coarse key (without root param suffix).\n resumeDataCache.cache.set(\n serializedCacheKey,\n Promise.resolve({\n entry: entryRight,\n hasExplicitRevalidate: entryMetadata.hasExplicitRevalidate,\n hasExplicitExpire: entryMetadata.hasExplicitExpire,\n readRootParamNames: entryMetadata.readRootParamNames,\n dynamicNestedCacheError: entryMetadata.dynamicNestedCacheError,\n })\n )\n } else if (!cacheSignalReadEnded) {\n // If we're not regenerating we need to signal that we've finished\n // putting the entry into the cache scope at this point. Otherwise\n // we do that inside generateCacheEntry. (Skipped when the read was\n // already ended for a short-lived deferral.)\n cacheSignal?.endRead()\n }\n\n debug?.(\n logPrefix,\n 'leader resolved with cache handler hit',\n cacheHandlerKey\n )\n\n const sharedCacheEntry = new SharedCacheEntry(\n stream,\n Promise.resolve(entryMetadata),\n undefined\n )\n stream = sharedCacheEntry.fork()\n resolvableSharedCacheResult.resolve({\n type: 'cached',\n entry: sharedCacheEntry,\n })\n\n // Trigger a background revalidation when the entry is stale (past its\n // `revalidate`), so the next read gets a fresh value without blocking\n // this one. Development additionally re-warms on every dynamic\n // request render in two cases where the dev in-memory entry would\n // otherwise read back as fresh, so a subsequent reload still shows a\n // fresh value. The first is with the in-memory cache disabled\n // (`cacheMaxMemorySize: 0`), where built-in entries keep their\n // resolved (potentially non-dynamic) cache life. The second is a\n // short-`expire` entry (an explicit dynamic or client-only cache,\n // e.g. `cacheLife({ expire: 0 })`), which is retained for at least\n // `MIN_PRERENDERABLE_EXPIRE` so it is served from the cache; this\n // also covers custom handlers, re-executing and writing through to\n // the backing.\n let shouldTriggerBackgroundRevalidation =\n currentTime > entry.timestamp + entry.revalidate * 1000\n if (\n !shouldTriggerBackgroundRevalidation &&\n process.env.__NEXT_DEV_SERVER &&\n (entry.expire < MIN_PRERENDERABLE_EXPIRE ||\n (isMemoryCacheDisabled() && !isCustomCacheHandler(kind)))\n ) {\n switch (workUnitStore.type) {\n case 'request':\n shouldTriggerBackgroundRevalidation = true\n break\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (\n shouldTriggerBackgroundRevalidation &&\n // The revalidation observed before the lookup may have finished.\n observedRevalidation === undefined &&\n // A new revalidation may have started since the lookup began.\n !backgroundRevalidations.has(cacheHandlerKey)\n ) {\n const revalidateCacheHandlerKey = cacheHandlerKey\n // Defer the call so synchronous setup errors reject the background\n // task instead of failing the stale response. This also lets us\n // register the task before generation starts.\n const revalidatePromise = Promise.resolve()\n .then(() =>\n generateCacheEntry(\n workStore,\n // The background revalidation preserves the outer store for\n // reading (e.g. implicitTags) but skips propagation of cache\n // life and tags back to the outer scope.\n { ...cacheContext, skipPropagation: true },\n clientReferenceManifest,\n encodedCacheKeyParts,\n fn,\n timeoutError,\n deadlockError\n )\n )\n .then(async (result) => {\n if (result.type === 'cached') {\n const { stream: ignoredStream, pendingCacheResult } = result\n\n const savedCacheResult = saveToResumeDataCache(\n resumeDataCache,\n serializedCacheKey,\n pendingCacheResult,\n logPrefix\n )\n\n const pendingWrite = cacheHandler\n ? saveToCacheHandler(\n cacheHandler,\n id,\n cacheHandlerKeyBase,\n savedCacheResult,\n rootParams\n )\n : savedCacheResult.then(() => {})\n\n for (const completion of await Promise.allSettled([\n ignoredStream.cancel(),\n pendingWrite,\n ])) {\n if (completion.status === 'rejected') {\n throw completion.reason\n }\n }\n }\n })\n .finally(() => {\n if (\n backgroundRevalidations.get(revalidateCacheHandlerKey) ===\n revalidatePromise\n ) {\n backgroundRevalidations.delete(revalidateCacheHandlerKey)\n }\n })\n backgroundRevalidations.set(\n revalidateCacheHandlerKey,\n revalidatePromise\n )\n revalidatePromise.catch((error) => {\n debug?.(\n logPrefix,\n 'background cache revalidation failed for',\n revalidateCacheHandlerKey,\n error\n )\n })\n workStore.pendingRevalidateWrites ??= []\n workStore.pendingRevalidateWrites.push(revalidatePromise)\n }\n }\n }\n } catch (error) {\n resolvableSharedCacheResult.reject(error)\n throw error\n }\n }\n\n // Logs are replayed even if it's a hit - to ensure we see them on the client eventually.\n // If we didn't then the client wouldn't see the logs if it was seeded from a prewarm that\n // never made it to the client. However, this also means that you see logs even when the\n // cached function isn't actually re-executed. We should instead ensure prewarms always\n // make it to the client. Another issue is that this will cause double logging in the\n // server terminal. Once while generating the cache entry and once when replaying it on\n // the server, which is required to pick it up for replaying again on the client.\n const replayConsoleLogs = true\n\n const serverConsumerManifest = {\n // moduleLoading must be null because we don't want to trigger preloads of ClientReferences\n // to be added to the consumer. Instead, we'll wait for any ClientReference to be emitted\n // which themselves will handle the preloading.\n moduleLoading: null,\n moduleMap: getRscModuleMappingForUseCache(),\n serverModuleMap: getServerModuleMap(),\n }\n\n return createFromReadableStream(stream, {\n findSourceMapURL,\n serverConsumerManifest,\n temporaryReferences,\n replayConsoleLogs,\n environmentName: 'Cache',\n })\n}\n\n/**\n * This returns cache key parts that cover everything that can affect the result of the cached\n * function (apart from the arguments). The implementation part is used by both the RDC and cache\n * handler, while the runtime env var state hash is only used by the cache handler. The RDC is\n * per-page and must reuse entries across rendering phases even if an env var changes between them.\n *\n * The parts cover:\n * - codeHash: the code itself that generates the return value\n * - Notably, this excludes the following modules. Those are included via the Next.js version anyway:\n * - react, react-dom, private-next-rsc-server-reference, private-next-rsc-cache-wrapper\n * - runtimeEnvVarsRead: the keys and values of runtime environment variables that the code reads\n * - runtimeEnvVarExistence: the unset/falsy/truthy state of runtime environment variables used in boolean contexts\n * - the version of Next.js (to account for RSC wire format changes, or use-cache-wrapper.ts changes)\n *\n * In case that granular information isn't available, fall back to\n * buildId/deploymentId/hmrRefreshHash, which is a correct hash but over-invalidates way too often.\n */\nasync function computeCacheKeyImplementationPart(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore,\n id: string\n): Promise<{\n implementationPart: unknown\n runtimeEnvVarStateHash: string | undefined\n}> {\n let durability = workStore.durableUseCacheEntries\n ? getServerActionsManifest().node[id].workers?.[\n normalizeWorkerPageName(workStore.page)\n ]?.durability\n : undefined\n if (durability) {\n // use cache is only supported in Node.js runtime. So we can use the Node.js crypto module here.\n const crypto = require('crypto') as typeof import('crypto')\n let runtimeEnvVarStateHash = crypto\n // Hash the env var values, to not leak secrets into the cache key.\n .createHash('sha256')\n .update(\n [\n ...durability.runtimeEnvVarsRead.map((k) => {\n // Make sure not to stringify `undefined` and `\"undefined\"` to the same value.\n return process.env[k] != null ? `${k}==${process.env[k]}` : k\n }),\n ...durability.runtimeEnvVarsExistence.map((k) => {\n const value = process.env[k]\n const state = value == null ? 'unset' : value ? 'truthy' : 'falsy'\n return `${k}~=${state}`\n }),\n ].join('\\0') ?? ''\n )\n .digest('hex')\n\n // The env var state is added to the cache handler key separately so it\n // doesn't affect RDC lookups between rendering phases.\n return {\n implementationPart: [durability.codeHash, nextVersion],\n runtimeEnvVarStateHash,\n }\n } else {\n // Because the Action ID is not yet unique per implementation of that Action we can't\n // safely reuse the results across builds yet. In the meantime we add the buildId to the\n // arguments as a seed to ensure they're not reused. Remove this once Action IDs hash\n // the implementation.\n const buildId = workStore.deploymentId || workStore.buildId\n\n // In dev mode, when the HMR refresh hash is set, we include it in the\n // cache key. This ensures that cache entries are not reused when server\n // components have been edited. This is a very coarse approach. But it's\n // also only a temporary solution until Action IDs are unique per\n // implementation. Remove this once Action IDs hash the implementation.\n const hmrRefreshHash = getHmrRefreshHash(workUnitStore)\n\n // otherwise fall back to buildId and/or the HMR hash.\n return {\n implementationPart: hmrRefreshHash\n ? [buildId, hmrRefreshHash]\n : [buildId],\n runtimeEnvVarStateHash: undefined,\n }\n }\n}\n\n/**\n * A request store in `next start` never delays caches.\n * We only apply delays when the render will be used for\n * validation purposes.\n */\nfunction isValidationRender(requestStore: RequestStore): boolean {\n return !!(\n process.env.__NEXT_CACHE_COMPONENTS &&\n // In dev we're always running validation.\n (process.env.__NEXT_DEV_SERVER ||\n // Build-time instant validation also uses a 'request' store.\n requestStore.validationSamples)\n )\n}\n\n/**\n * Returns `true` if the `'use cache'` function is the page component itself,\n * or `generateMetadata`/`generateViewport` in a page file.\n */\nfunction isPageSegmentFunction(\n args: any[]\n): args is [UseCachePageProps, ...unknown[]] {\n const [maybeProps] = args\n\n return (\n maybeProps !== null &&\n typeof maybeProps === 'object' &&\n (maybeProps as UseCachePageProps).$$isPage === true\n )\n}\n\n/**\n * Returns `true` if the `'use cache'` function is the layout component itself,\n * or `generateMetadata`/`generateViewport` in a layout file.\n */\nfunction isLayoutSegmentFunction(\n args: any[]\n): args is [UseCacheLayoutProps, ...unknown[]] {\n const [maybeProps] = args\n\n return (\n maybeProps !== null &&\n typeof maybeProps === 'object' &&\n (maybeProps as UseCacheLayoutProps).$$isLayout === true\n )\n}\n\nfunction shouldForceRevalidate(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): boolean {\n if (workStore.isOnDemandRevalidate || workStore.isDraftMode) {\n return true\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'request':\n return workUnitStore.headers.get('cache-control') === 'no-cache'\n case 'cache':\n case 'private-cache':\n return workUnitStore.forceRevalidate\n case 'prerender-runtime':\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nfunction shouldDiscardCacheEntry(\n entry: Pick,\n workStore: WorkStore,\n workUnitStore: WorkUnitStore,\n implicitTags: string[],\n implicitTagsExpiration: number,\n logPrefix: string\n): boolean {\n // If the cache entry was created before any of the implicit tags were\n // revalidated last, we need to discard it.\n if (entry.timestamp <= implicitTagsExpiration) {\n debug?.(\n logPrefix,\n 'entry was created at',\n entry.timestamp,\n 'before implicit tags were revalidated at',\n implicitTagsExpiration\n )\n\n return true\n }\n\n // During prerendering, we ignore recently revalidated tags. In dev mode, we\n // can assume that the dynamic dev rendering will have discarded and recreated\n // the affected cache entries, and we don't want to discard those again during\n // the prerender validation. During build-time prerendering, there will never\n // be any pending revalidated tags.\n switch (workUnitStore.type) {\n case 'prerender':\n return false\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n\n // If the cache entry contains revalidated tags that the cache handler might\n // not know about yet, we need to discard it.\n if (\n entry.tags.some((tag) =>\n isRevalidatedAfter(tag, entry.timestamp, workStore, logPrefix)\n )\n ) {\n return true\n }\n\n // Finally, if any of the implicit tags have been revalidated recently, we\n // also need to discard the cache entry.\n if (\n implicitTags.some((tag) =>\n isRevalidatedAfter(tag, entry.timestamp, workStore, logPrefix)\n )\n ) {\n return true\n }\n\n return false\n}\n\n/**\n * Whether `tag` was revalidated after an entry created at `entryTimestamp`,\n * which makes that entry stale. An entry produced after the revalidation\n * already reflects it and is still usable.\n */\nfunction isRevalidatedAfter(\n tag: string,\n entryTimestamp: number,\n workStore: WorkStore,\n logPrefix: string\n): boolean {\n const {\n previouslyRevalidatedTags,\n pendingRevalidatedTags,\n requestStartTime,\n } = workStore\n\n // Was the tag previously revalidated (e.g. by a redirecting server action)?\n // That happened in an earlier request and carries no timestamp of its own, so\n // it counts as having happened when this request started.\n if (\n entryTimestamp <= requestStartTime &&\n previouslyRevalidatedTags.includes(tag)\n ) {\n debug?.(logPrefix, 'tag', tag, 'was previously revalidated')\n\n return true\n }\n\n // It could also have been revalidated by the currently running server action.\n // In this case the revalidation might not have been fully propagated by a\n // remote cache handler yet, so we read it from the pending tags in the work\n // store.\n if (\n pendingRevalidatedTags?.some(\n (item) => item.tag === tag && item.revalidatedAt > entryTimestamp\n )\n ) {\n debug?.(logPrefix, 'tag', tag, 'was just revalidated')\n\n return true\n }\n\n return false\n}\n"],"names":["cache","nextVersion","process","env","__NEXT_VERSION","SharedCacheEntry","constructor","stream","pendingMetadata","pendingWrite","pendingCompletion","undefined","then","fork","forked","remaining","tee","ignoreReject","ResolvableSharedCacheResult","registerIn","map","key","retentionMap","set","deferred","promise","registrations","push","resolve","result","type","entry","cleanupAndRetain","cleanup","reject","error","catch","delete","createPromiseWithResolvers","crossRequestPendingCacheInvocations","Map","backgroundRevalidations","debug","NEXT_PRIVATE_DEBUG_CACHE","console","bind","filterStackFrame","NODE_ENV","require","filterStackFrameDEV","findSourceMapURL","findSourceMapURLDEV","knownRootParamsByFunctionId","addKnownRootParamNames","id","names","existing","get","name","add","created","Set","computeRootParamsCacheKeySuffix","rootParams","paramNames","size","JSON","stringify","sort","paramName","COOKIES_EXCLUDED_FROM_PRIVATE_CACHE_KEY","NEXT_INSTANT_TEST_COOKIE","HEADERS_EXCLUDED_FROM_PRIVATE_CACHE_KEY","computePrivateCacheKeyRequestSuffix","cookies","headers","relevantCookies","getAll","filter","cookie","has","value","nameA","nameB","relevantHeaders","entries","length","saveToResumeDataCache","resumeDataCache","serializedCacheKey","pendingCacheResult","logPrefix","mutable","split","clonePendingCacheResult","savedCacheResult","getNthCacheResult","rdcResult","saveSharedCacheEntryToResumeDataCache","sharedCacheEntry","existingEntry","FALLBACK_PARAMS","RUNTIME_DATA","SESSION_DATA","metadata","tags","revalidate","expire","stale","timestamp","readRootParamNames","hasExplicitRevalidate","hasExplicitExpire","dynamicNestedCacheError","serveJoinedCacheEntry","cacheContext","cacheSignal","maybePropagateCacheEntryMetadata","finally","endRead","saveToCacheHandler","cacheHandler","cacheHandlerKeyBase","collectedResult","fullEntry","rootParamNames","setPromises","coarseEntry","specificKey","Promise","rootParamTags","NEXT_CACHE_ROOT_PARAM_TAG_ID","ReadableStream","start","controller","enqueue","Uint8Array","close","allSettled","status","reason","generateCacheEntry","workStore","clientReferenceManifest","encodedArguments","fn","timeoutError","deadlockError","runInCleanSnapshot","generateCacheEntryWithRestoredWorkStore","workAsyncStorage","run","generateCacheEntryWithCacheContext","createUseCacheStore","defaultCacheLife","kind","outerWorkUnitStore","phase","consumerWillServerCache","implicitTags","explicitRevalidate","explicitExpire","explicitStale","hmrRefreshHash","getHmrRefreshHash","isHmrRefresh","serverComponentsHmrCache","getServerComponentsHmrCache","forceRevalidate","shouldForceRevalidate","draftMode","getDraftModeProviderForCacheScope","HeadersAdapter","fresh","RequestCookiesAdapter","outerOwnerStack","useCacheOrRequestStore","fallbackRootParamsPrerender","fallbackRouteParams","Object","keys","some","captureOuterOwnerStack","workUnitStore","getClientReact","getServerReact","capturedOwnerStack","captureOwnerStack","parentOuterOwnerStack","getUseCacheFillTimeoutMs","workUnitStoreType","useCacheTimeout","staticPageGenerationTimeout","effectiveTimeout","Math","min","cacheLifeProfiles","default","cacheStore","workUnitAsyncStorage","dynamicAccessAsyncStorage","abortController","AbortController","generateCacheEntryImpl","propagateCacheLifeAndTagsToRevalidateStore","revalidateStore","outerTags","tag","includes","propagateCacheStaleTimeToRequestStore","requestStore","propagateCacheEntryMetadata","MIN_PRERENDERABLE_EXPIRE","varyParamsAccumulator","getVaryParamsAccumulator","accumulateVaryParam","isValidationRender","collectResult","savedStream","innerCacheStore","startTime","errors","buffer","reader","getReader","read","done","idx","bufferStream","pull","invalidDynamicUsageError","collectedTags","isPrivateCacheInDev","Boolean","__NEXT_DEV_SERVER","forceDynamicCacheLifeInDev","collectedRevalidate","collectedExpire","collectedStale","collected","skipPropagation","getCacheSignal","temporaryReferences","createServerTemporaryReferenceSet","args","decodeReply","getServerModuleMap","decodeReplyFromAsyncIterable","Symbol","asyncIterator","renderSignal","aborted","addEventListener","once","performance","timeOrigin","now","resultPromise","createLazyResult","handleError","createReactServerErrorHandler","isBuildTimePrerendering","reactServerErrorsByDigest","Log","devTimeoutAbortController","prerenderStore","renderToReadableStream","clientModules","environmentName","onError","timeoutAbortController","timer","setTimeout","abort","dynamicAccessStore","getStore","dynamicAccessAbortSignal","signal","abortSignal","AbortSignal","any","prelude","prerender","clearTimeout","didTimeout","makeHangingPromise","makeFallbackParamsHangingPromise","makeURLDataHangingPromise","functionId","hangingPromise","trackPromiseUsed","route","trackFallbackParamsAccessed","trackURLDataAccessed","consumer","abortOnDynamicAccess","stagedRendering","stageAtReadStart","currentStage","RenderStage","Dynamic","devRenderAbortController","fillTimeoutMs","fillDeadlineAt","devRenderTimeoutTimer","Error","digest","stringHash","message","stack","toString","setupProbeScheduler","outerRequestStore","onProbeCompleted","InvariantError","returnStream","cloneCacheResult","entryA","entryB","cloneCacheEntry","i","encodeFormData","formData","stringValue","arrayBuffer","byteLength","String","fromCodePoint","Uint16Array","createTrackedReadableStream","boundArgsLength","originalFn","isPrivate","makeUntrackedHangingPromise","useCacheProbeMode","getPrivateCacheHandler","handler","getCacheHandler","isCustomCacheHandler","tieredCacheHandler","getDevTieredCacheHandler","UseCacheTimeoutError","captureStackTrace","applyOwnerStack","UseCacheDeadlockError","wrapAsInvalidDynamicUsageError","expression","makeUnknownRuntimeDataHangingPromise","throwToInterruptStaticGeneration","createUseCachePrivateInsideUnstableCacheError","createUseCachePrivateInsidePublicUseCacheError","handlerKind","createUseCachePrivateOutsideRequestContextError","functionName","NestedDynamicUseCacheError","getClientReferenceManifest","hangingInputAbortSignal","createHangingInputAbortSignal","waitForStage","RENDER_STAGES_BY_DATA_KIND","sessionData","makeDevtoolsIOAwarePromise","isPageOrLayoutSegmentFunction","isPageSegmentFunction","params","outerParams","searchParams","outerSearchParams","otherOuterArgs","props","_","otherInnerArgs","apply","makeErroringSearchParamsForUseCache","isLayoutSegmentFunction","$$isLayout","outerSlots","_innerParams","innerSlots","encryptedBoundArgs","shift","boundArgs","decryptActionBoundArgs","Array","isArray","unshift","createClientTemporaryReferenceSet","implementationPart","runtimeEnvVarStateHash","computeCacheKeyImplementationPart","cacheKeyParts","encodeCacheKeyParts","encodeReply","encodedCacheKeyParts","probeTimeoutMs","timeoutMs","cancel","probeTimeoutTimer","race","knownRootParamNames","cacheHandlerKey","cacheSignalReadEnded","getResumeDataCache","rdcEntry","makeSessionDataHangingPromise","beginRead","isRevalidatedAfter","shouldReportNestedCacheError","createNestedCacheZeroRevalidateError","createNestedCacheShortExpireError","MIN_SHELL_STALE","isPrefetchable","MIN_PREFETCHABLE_STALE","makeDynamicHangingPromise","prefetchStage","staticUrlData","static","runtimeUrlData","finalStage","makePrefetchHangingPromise","stage","trackIncompatibleShellContent","needsRuntimeShell","streamA","streamB","warn","UnexpectedCacheMissError","pendingInvocation","pendingCacheInvocations","completedInvocation","completedCacheInvocations","joinedInvocation","sharedCacheResult","shouldDiscardCacheEntry","resolvableSharedCacheResult","intraRequestPendingCacheInvocations","isBuiltInCacheHandler","skipCrossRequestDedupe","isDraftMode","crossRequestPendingCacheInvocation","updatedRootParamNames","newCacheHandlerKey","lazyRefreshTags","refreshTagsByCacheKind","isResolvedLazyResult","observedRevalidation","startsWith","slice","implicitTagsExpiration","lazyExpiration","expirationsByCacheKind","expiration","Infinity","currentTime","max","willConsumerServerCache","newStream","pendingRevalidateWrites","entryMetadata","entryLeft","entryRight","shouldTriggerBackgroundRevalidation","isMemoryCacheDisabled","revalidateCacheHandlerKey","revalidatePromise","ignoredStream","completion","replayConsoleLogs","serverConsumerManifest","moduleLoading","moduleMap","getRscModuleMappingForUseCache","serverModuleMap","createFromReadableStream","getServerActionsManifest","durability","durableUseCacheEntries","node","workers","normalizeWorkerPageName","page","crypto","createHash","update","runtimeEnvVarsRead","k","runtimeEnvVarsExistence","state","join","codeHash","buildId","deploymentId","__NEXT_CACHE_COMPONENTS","validationSamples","maybeProps","$$isPage","isOnDemandRevalidate","entryTimestamp","previouslyRevalidatedTags","pendingRevalidatedTags","requestStartTime","item","revalidatedAt"],"mappings":";;;;+BA00DsBA;;;eAAAA;;;wBAn0Df;wBAKA;wBACmB;0CAGO;8CAsB1B;4BAC6B;uCAiB7B;oCAUA;4BAGgC;gCACR;oCAIxB;mEACgB;2BAKhB;4BACsC;0BAQtC;iCAEyB;kCACS;gCAIlC;yBAIA;gCAMA;kCAOA;kCAIA;8BAIA;4BAOA;4BACgD;mDAKhD;iCAKA;6DACc;uCAC0B;sCACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0C3C,MAAMC,cAAcC,QAAQC,GAAG,CAACC,cAAc;AA6C9C;;;;CAIC,GACD,MAAMC;IAeJC,YACEC,MAAkC,EAClCC,eAA6C,EAC7CC,YAAuC,CACvC;QACA,IAAI,CAACF,MAAM,GAAGA;QACd,IAAI,CAACC,eAAe,GAAGA;QACvB,IAAI,CAACE,iBAAiB,GACpBD,iBAAiBE,YACbH,kBACAC,aAAaG,IAAI,CACf,IAAMJ,iBACN,IAAMA;IAEhB;IAEA;;;;GAIC,GACDK,OAAmC;QACjC,MAAM,CAACC,QAAQC,UAAU,GAAG,IAAI,CAACR,MAAM,CAACS,GAAG;QAC3C,IAAI,CAACT,MAAM,GAAGQ;QACd,OAAOD;IACT;AACF;AAgBA,SAASG,gBAAgB;AAEzB;;;;;;;CAOC,GACD,MAAMC;IAgBJC,WACEC,GAA4C,EAC5CC,GAAW,EACXC,Y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,KAAK;QACL,KAAK;QACL,KAAK;YACH;QACF;YACEyJ;IACJ;IAEA,4EAA4E;IAC5E,6CAA6C;IAC7C,IACExJ,MAAM0E,IAAI,CAAC4E,IAAI,CAAC,CAAC0B,MACfuM,mBAAmBvM,KAAKhL,MAAM8E,SAAS,EAAEiC,WAAWnD,aAEtD;QACA,OAAO;IACT;IAEA,0EAA0E;IAC1E,wCAAwC;IACxC,IACEoE,aAAasB,IAAI,CAAC,CAAC0B,MACjBuM,mBAAmBvM,KAAKhL,MAAM8E,SAAS,EAAEiC,WAAWnD,aAEtD;QACA,OAAO;IACT;IAEA,OAAO;AACT;AAEA;;;;CAIC,GACD,SAAS2T,mBACPvM,GAAW,EACXkS,cAAsB,EACtBnW,SAAoB,EACpBnD,SAAiB;IAEjB,MAAM,EACJuZ,yBAAyB,EACzBC,sBAAsB,EACtBC,gBAAgB,EACjB,GAAGtW;IAEJ,4EAA4E;IAC5E,8EAA8E;IAC9E,0DAA0D;IAC1D,IACEmW,kBAAkBG,oBAClBF,0BAA0BlS,QAAQ,CAACD,MACnC;QACArK,yBAAAA,MAAQiD,WAAW,OAAOoH,KAAK;QAE/B,OAAO;IACT;IAEA,8EAA8E;IAC9E,0EAA0E;IAC1E,4EAA4E;IAC5E,SAAS;IACT,IACEoS,0CAAAA,uBAAwB9T,IAAI,CAC1B,CAACgU,OAASA,KAAKtS,GAAG,KAAKA,OAAOsS,KAAKC,aAAa,GAAGL,iBAErD;QACAvc,yBAAAA,MAAQiD,WAAW,OAAOoH,KAAK;QAE/B,OAAO;IACT;IAEA,OAAO;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/utils.d.ts b/e-commerce/node_modules/next/dist/server/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..39e3358941d853ba0be50735fbb0f809caf3acb3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/utils.d.ts @@ -0,0 +1,4 @@ +export declare function isBlockedPage(page: string): boolean; +type AnyFunc = (this: T, ...args: any) => any; +export declare function debounce>(fn: F, ms: number, maxWait?: number): (this: T, ...passedArgs: Parameters) => void; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/utils.js b/e-commerce/node_modules/next/dist/server/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..de37d200b0713227dbeba9db1c4ab17028d2b67d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/utils.js @@ -0,0 +1,73 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + debounce: null, + isBlockedPage: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + debounce: function() { + return debounce; + }, + isBlockedPage: function() { + return isBlockedPage; + } +}); +const _constants = require("../shared/lib/constants"); +function isBlockedPage(page) { + return _constants.BLOCKED_PAGES.includes(page); +} +function debounce(fn, ms, maxWait = Infinity) { + let timeoutId; + // The time the debouncing function was first called during this debounce queue. + let startTime = 0; + // The time the debouncing function was last called. + let lastCall = 0; + // The arguments and this context of the last call to the debouncing function. + let args, context; + // A helper used to that either invokes the debounced function, or + // reschedules the timer if a more recent call was made. + function run() { + const now = Date.now(); + const diff = lastCall + ms - now; + // If the diff is non-positive, then we've waited at least `ms` + // milliseconds since the last call. Or if we've waited for longer than the + // max wait time, we must call the debounced function. + if (diff <= 0 || startTime + maxWait >= now) { + // It's important to clear the timeout id before invoking the debounced + // function, in case the function calls the debouncing function again. + timeoutId = undefined; + fn.apply(context, args); + } else { + // Else, a new call was made after the original timer was scheduled. We + // didn't clear the timeout (doing so is very slow), so now we need to + // reschedule the timer for the time difference. + timeoutId = setTimeout(run, diff); + } + } + return function(...passedArgs) { + // The arguments and this context of the most recent call are saved so the + // debounced function can be invoked with them later. + args = passedArgs; + context = this; + // Instead of constantly clearing and scheduling a timer, we record the + // time of the last call. If a second call comes in before the timer fires, + // then we'll reschedule in the run function. Doing this is considerably + // faster. + lastCall = Date.now(); + // Only schedule a new timer if we're not currently waiting. + if (timeoutId === undefined) { + startTime = lastCall; + timeoutId = setTimeout(run, ms); + } + }; +} + +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/utils.js.map b/e-commerce/node_modules/next/dist/server/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..72177c3080235366b57d3b9d9a21902537eb38ff --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../src/server/utils.ts"],"sourcesContent":["import { BLOCKED_PAGES } from '../shared/lib/constants'\n\nexport function isBlockedPage(page: string): boolean {\n return BLOCKED_PAGES.includes(page)\n}\n\ntype AnyFunc = (this: T, ...args: any) => any\nexport function debounce>(\n fn: F,\n ms: number,\n maxWait = Infinity\n) {\n let timeoutId: undefined | NodeJS.Timeout\n\n // The time the debouncing function was first called during this debounce queue.\n let startTime = 0\n // The time the debouncing function was last called.\n let lastCall = 0\n\n // The arguments and this context of the last call to the debouncing function.\n let args: Parameters, context: T\n\n // A helper used to that either invokes the debounced function, or\n // reschedules the timer if a more recent call was made.\n function run() {\n const now = Date.now()\n const diff = lastCall + ms - now\n\n // If the diff is non-positive, then we've waited at least `ms`\n // milliseconds since the last call. Or if we've waited for longer than the\n // max wait time, we must call the debounced function.\n if (diff <= 0 || startTime + maxWait >= now) {\n // It's important to clear the timeout id before invoking the debounced\n // function, in case the function calls the debouncing function again.\n timeoutId = undefined\n fn.apply(context, args)\n } else {\n // Else, a new call was made after the original timer was scheduled. We\n // didn't clear the timeout (doing so is very slow), so now we need to\n // reschedule the timer for the time difference.\n timeoutId = setTimeout(run, diff)\n }\n }\n\n return function (this: T, ...passedArgs: Parameters) {\n // The arguments and this context of the most recent call are saved so the\n // debounced function can be invoked with them later.\n args = passedArgs\n context = this\n\n // Instead of constantly clearing and scheduling a timer, we record the\n // time of the last call. If a second call comes in before the timer fires,\n // then we'll reschedule in the run function. Doing this is considerably\n // faster.\n lastCall = Date.now()\n\n // Only schedule a new timer if we're not currently waiting.\n if (timeoutId === undefined) {\n startTime = lastCall\n timeoutId = setTimeout(run, ms)\n }\n }\n}\n"],"names":["debounce","isBlockedPage","page","BLOCKED_PAGES","includes","fn","ms","maxWait","Infinity","timeoutId","startTime","lastCall","args","context","run","now","Date","diff","undefined","apply","setTimeout","passedArgs"],"mappings":";;;;;;;;;;;;;;;IAOgBA,QAAQ;eAARA;;IALAC,aAAa;eAAbA;;;2BAFc;AAEvB,SAASA,cAAcC,IAAY;IACxC,OAAOC,wBAAa,CAACC,QAAQ,CAACF;AAChC;AAGO,SAASF,SACdK,EAAK,EACLC,EAAU,EACVC,UAAUC,QAAQ;IAElB,IAAIC;IAEJ,gFAAgF;IAChF,IAAIC,YAAY;IAChB,oDAAoD;IACpD,IAAIC,WAAW;IAEf,8EAA8E;IAC9E,IAAIC,MAAqBC;IAEzB,kEAAkE;IAClE,wDAAwD;IACxD,SAASC;QACP,MAAMC,MAAMC,KAAKD,GAAG;QACpB,MAAME,OAAON,WAAWL,KAAKS;QAE7B,+DAA+D;QAC/D,2EAA2E;QAC3E,sDAAsD;QACtD,IAAIE,QAAQ,KAAKP,YAAYH,WAAWQ,KAAK;YAC3C,uEAAuE;YACvE,sEAAsE;YACtEN,YAAYS;YACZb,GAAGc,KAAK,CAACN,SAASD;QACpB,OAAO;YACL,uEAAuE;YACvE,sEAAsE;YACtE,gDAAgD;YAChDH,YAAYW,WAAWN,KAAKG;QAC9B;IACF;IAEA,OAAO,SAAmB,GAAGI,UAAyB;QACpD,0EAA0E;QAC1E,qDAAqD;QACrDT,OAAOS;QACPR,UAAU,IAAI;QAEd,uEAAuE;QACvE,2EAA2E;QAC3E,wEAAwE;QACxE,UAAU;QACVF,WAAWK,KAAKD,GAAG;QAEnB,4DAA4D;QAC5D,IAAIN,cAAcS,WAAW;YAC3BR,YAAYC;YACZF,YAAYW,WAAWN,KAAKR;QAC9B;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/adapter.d.ts b/e-commerce/node_modules/next/dist/server/web/adapter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd0b3cca204cacd911db1bd7b89dba28d77e9b7c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/adapter.d.ts @@ -0,0 +1,28 @@ +import type { RequestData, FetchEventResult } from './types'; +import type { RequestInit } from './spec-extension/request'; +import { NextFetchEvent } from './spec-extension/fetch-event'; +import { NextRequest } from './spec-extension/request'; +export declare class NextRequestHint extends NextRequest { + sourcePage: string; + fetchMetrics: FetchEventResult['fetchMetrics'] | undefined; + constructor(params: { + init: RequestInit; + input: Request | string; + page: string; + }); + get request(): void; + respondWith(): void; + waitUntil(): void; +} +export type AdapterOptions = { + handler: (req: NextRequestHint, event: NextFetchEvent) => Promise; + page: string; + request: RequestData; + IncrementalCache?: typeof import('../lib/incremental-cache').IncrementalCache; + incrementalCacheHandler?: typeof import('../lib/incremental-cache').CacheHandler; + bypassNextUrl?: boolean; +}; +export type EdgeHandler = (opts: { + request: AdapterOptions['request']; +}) => Promise; +export declare function adapter(params: AdapterOptions): Promise; diff --git a/e-commerce/node_modules/next/dist/server/web/adapter.js b/e-commerce/node_modules/next/dist/server/web/adapter.js new file mode 100644 index 0000000000000000000000000000000000000000..05269dfcc44ede8580d7527141306295c140579c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/adapter.js @@ -0,0 +1,407 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + NextRequestHint: null, + adapter: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + NextRequestHint: function() { + return NextRequestHint; + }, + adapter: function() { + return adapter; + } +}); +const _error = require("./error"); +const _utils = require("./utils"); +const _fetchevent = require("./spec-extension/fetch-event"); +const _request = require("./spec-extension/request"); +const _response = require("./spec-extension/response"); +const _relativizeurl = require("../../shared/lib/router/utils/relativize-url"); +const _nexturl = require("./next-url"); +const _internalutils = require("../internal-utils"); +const _apppaths = require("../../shared/lib/router/utils/app-paths"); +const _approuterheaders = require("../../client/components/app-router-headers"); +const _globals = require("./globals"); +const _requeststore = require("../async-storage/request-store"); +const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external"); +const _workstore = require("../async-storage/work-store"); +const _workasyncstorageexternal = require("../app-render/work-async-storage.external"); +const _invarianterror = require("../../shared/lib/invariant-error"); +const _tracer = require("../lib/trace/tracer"); +const _constants = require("../lib/trace/constants"); +const _webonclose = require("./web-on-close"); +const _getedgepreviewprops = require("./get-edge-preview-props"); +const _builtinrequestcontext = require("../after/builtin-request-context"); +const _implicittags = require("../lib/implicit-tags"); +const _isrscrequest = require("../lib/is-rsc-request"); +const _requestmeta = require("../request-meta"); +// The proxy (middleware) does not support `'use cache'`, so this work store +// never reaches the code that reads `cacheLife` (and `'use cache'` is +// disallowed on the edge runtime anyway). This sentinel satisfies the +// non-optional type while throwing if `default` is ever read, matching the +// "never read" sentinels used for the proxy's other unused renderOpts fields +// (`staticPageGenerationTimeout: 0`, `useCacheTimeout: 0`). It surfaces loudly +// rather than silently serving a misleading profile. +const proxyCacheLifeProfiles = { + get default () { + throw new _invarianterror.InvariantError('Proxy does not support `use cache`, so reading its `default` cacheLife profile is unexpected.'); + } +}; +class NextRequestHint extends _request.NextRequest { + constructor(params){ + super(params.input, params.init); + this.sourcePage = params.page; + } + get request() { + throw new _error.PageSignatureError({ + page: this.sourcePage + }); + } + respondWith() { + throw new _error.PageSignatureError({ + page: this.sourcePage + }); + } + waitUntil() { + throw new _error.PageSignatureError({ + page: this.sourcePage + }); + } +} +const headersGetter = { + keys: (headers)=>Array.from(headers.keys()), + get: (headers, key)=>headers.get(key) ?? undefined +}; +let propagator = (request, fn)=>{ + const tracer = (0, _tracer.getTracer)(); + return tracer.withPropagatedContext(request.headers, fn, headersGetter); +}; +let testApisIntercepted = false; +function ensureTestApisIntercepted() { + if (!testApisIntercepted) { + testApisIntercepted = true; + if (process.env.NEXT_PRIVATE_TEST_PROXY === 'true') { + const { interceptTestApis, wrapRequestHandler } = // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm + require('next/dist/experimental/testmode/server-edge'); + interceptTestApis(); + propagator = wrapRequestHandler(propagator); + } + } +} +async function adapter(params) { + var _getBuiltinRequestContext; + ensureTestApisIntercepted(); + await (0, _globals.ensureInstrumentationRegistered)(); + // TODO-APP: use explicit marker for this + const isEdgeRendering = typeof globalThis.__BUILD_MANIFEST !== 'undefined'; + params.request.url = (0, _apppaths.normalizeRscURL)(params.request.url); + const requestURL = params.bypassNextUrl ? new URL(params.request.url) : new _nexturl.NextURL(params.request.url, { + headers: params.request.headers, + nextConfig: params.request.nextConfig + }); + // Iterator uses an index to keep track of the current iteration. Because of deleting and appending below we can't just use the iterator. + // Instead we use the keys before iteration. + const keys = [ + ...requestURL.searchParams.keys() + ]; + for (const key of keys){ + const value = requestURL.searchParams.getAll(key); + const normalizedKey = (0, _utils.normalizeNextQueryParam)(key); + if (normalizedKey) { + requestURL.searchParams.delete(normalizedKey); + for (const val of value){ + requestURL.searchParams.append(normalizedKey, val); + } + requestURL.searchParams.delete(key); + } + } + // Ensure users only see page requests, never data requests. + let buildId = process.env.__NEXT_BUILD_ID || ''; + if ('buildId' in requestURL) { + buildId = requestURL.buildId || ''; + requestURL.buildId = ''; + } + let deploymentId = process.env.NEXT_DEPLOYMENT_ID; + const requestHeaders = (0, _utils.fromNodeOutgoingHttpHeaders)(params.request.headers); + const isNextDataRequest = requestHeaders.has('x-nextjs-data'); + const isRSCRequest = (0, _isrscrequest.isRSCRequestHeader)(requestHeaders.get(_approuterheaders.RSC_HEADER)); + if (isNextDataRequest && requestURL.pathname === '/index') { + requestURL.pathname = '/'; + } + const flightHeaders = new Map(); + // Headers should only be stripped for middleware + if (!isEdgeRendering && !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) { + for (const header of _approuterheaders.FLIGHT_HEADERS){ + const value = requestHeaders.get(header); + if (value !== null) { + flightHeaders.set(header, value); + requestHeaders.delete(header); + } + } + } + const normalizeURL = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? new URL(params.request.url) : requestURL; + const rscHash = normalizeURL.searchParams.get(_approuterheaders.NEXT_RSC_UNION_QUERY); + const request = new NextRequestHint({ + page: params.page, + // Strip internal query parameters off the request. + input: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? normalizeURL.toString() : (0, _internalutils.stripInternalSearchParams)(normalizeURL).toString(), + init: { + body: params.request.body, + headers: requestHeaders, + method: params.request.method, + nextConfig: params.request.nextConfig, + signal: params.request.signal + } + }); + if (params.request.requestMeta) { + (0, _requestmeta.setRequestMeta)(request, params.request.requestMeta); + } + /** + * This allows to identify the request as a data request. The user doesn't + * need to know about this property neither use it. We add it for testing + * purposes. + */ if (isNextDataRequest) { + Object.defineProperty(request, '__isData', { + enumerable: false, + value: true + }); + } + if (// If we are inside of the next start sandbox + // leverage the shared instance if not we need + // to create a fresh cache instance each time + !globalThis.__incrementalCacheShared && params.IncrementalCache) { + ; + globalThis.__incrementalCache = new params.IncrementalCache({ + CurCacheHandler: params.incrementalCacheHandler, + minimalMode: process.env.NODE_ENV !== 'development', + fetchCacheKeyPrefix: process.env.__NEXT_FETCH_CACHE_KEY_PREFIX, + dev: process.env.NODE_ENV === 'development', + requestHeaders: params.request.headers, + previewProps: (0, _getedgepreviewprops.getEdgePreviewProps)(), + prerenderManifest: { + version: -1, + routes: {}, + dynamicRoutes: {}, + notFoundRoutes: [], + preview: (0, _getedgepreviewprops.getEdgePreviewProps)() + } + }); + } + // if we're in an edge runtime sandbox, we should use the waitUntil + // that we receive from the enclosing NextServer + const outerWaitUntil = params.request.waitUntil ?? ((_getBuiltinRequestContext = (0, _builtinrequestcontext.getBuiltinRequestContext)()) == null ? void 0 : _getBuiltinRequestContext.waitUntil); + const event = new _fetchevent.NextFetchEvent({ + request, + page: params.page, + context: outerWaitUntil ? { + waitUntil: outerWaitUntil + } : undefined + }); + let response; + let cookiesFromResponse; + response = await propagator(request, ()=>{ + // we only care to make async storage available for middleware + const isMiddleware = params.page === '/middleware' || params.page === '/src/middleware' || params.page === '/proxy' || params.page === '/src/proxy'; + if (isMiddleware) { + // if we're in an edge function, we only get a subset of `nextConfig` (no `experimental`), + // so we have to inject it via DefinePlugin. + // in `next start` this will be passed normally (see `NextNodeServer.runMiddleware`). + const waitUntil = event.waitUntil.bind(event); + const closeController = new _webonclose.CloseController(); + return (0, _tracer.getTracer)().trace(_constants.MiddlewareSpan.execute, { + spanName: `middleware ${request.method}`, + attributes: { + 'http.target': request.nextUrl.pathname, + 'http.method': request.method + } + }, async ()=>{ + try { + var _params_request_nextConfig_experimental, _params_request_nextConfig; + const onUpdateCookies = (cookies)=>{ + cookiesFromResponse = cookies; + }; + const previewProps = (0, _getedgepreviewprops.getEdgePreviewProps)(); + const page = '/' // Fake Work + ; + const fallbackRouteParams = null; + const implicitTags = await (0, _implicittags.getImplicitTags)(page, request.nextUrl.pathname, fallbackRouteParams); + const requestStore = (0, _requeststore.createRequestStoreForAPI)(request, request.nextUrl, implicitTags, onUpdateCookies, previewProps, // Edge route handlers can't use `"use cache"`, so there's no HMR + // refresh hash to thread through here. + undefined); + const workStore = (0, _workstore.createWorkStore)({ + page, + renderOpts: { + cacheLifeProfiles: proxyCacheLifeProfiles, + // Proxy doesn't do static generation, so this value does not + // apply here. 0 is a sentinel: if something ever reads it, + // it'll surface loudly instead of silently using a misleading + // default. + staticPageGenerationTimeout: 0, + cacheComponents: false, + // Proxy doesn't run instant validation; the level value is + // irrelevant here. + // TODO: remove validationLevel and other global config from renderOpts + validationLevel: 'warning', + experimental: { + isRoutePPREnabled: false, + authInterrupts: !!((_params_request_nextConfig = params.request.nextConfig) == null ? void 0 : (_params_request_nextConfig_experimental = _params_request_nextConfig.experimental) == null ? void 0 : _params_request_nextConfig_experimental.authInterrupts), + // Proxy doesn't fill Cache Components entries, so this value + // is never read. 0 is a sentinel: if something ever reads it, + // the cache fill will time out immediately and surface the + // bug. + useCacheTimeout: 0, + durableUseCacheEntries: false + }, + waitUntil, + onClose: closeController.onClose.bind(closeController), + onAfterTaskError: undefined + }, + isPrefetchRequest: request.headers.get(_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER) === '1', + buildId: buildId ?? '', + deploymentId: deploymentId ?? '', + previouslyRevalidatedTags: [] + }); + return await _workasyncstorageexternal.workAsyncStorage.run(workStore, ()=>_workunitasyncstorageexternal.workUnitAsyncStorage.run(requestStore, params.handler, request, event)); + } finally{ + // middleware cannot stream, so we can consider the response closed + // as soon as the handler returns. + // we can delay running it until a bit later -- + // if it's needed, we'll have a `waitUntil` lock anyway. + setTimeout(()=>{ + closeController.dispatchClose(); + }, 0); + } + }); + } + return params.handler(request, event); + }); + // check if response is a Response object + if (response && !(response instanceof Response)) { + throw new TypeError('Expected an instance of Response to be returned'); + } + if (response && cookiesFromResponse) { + response.headers.set('set-cookie', cookiesFromResponse); + } + /** + * For rewrites we must always include the locale in the final pathname + * so we re-create the NextURL forcing it to include it when the it is + * an internal rewrite. Also we make sure the outgoing rewrite URL is + * a data URL if the request was a data request. + */ const rewrite = response == null ? void 0 : response.headers.get('x-middleware-rewrite'); + if (response && rewrite && (isRSCRequest || !isEdgeRendering)) { + var _params_request_nextConfig_experimental_clientParamParsingOrigins, _params_request_nextConfig_experimental, _params_request_nextConfig; + const destination = new _nexturl.NextURL(rewrite, { + forceLocale: true, + headers: params.request.headers, + nextConfig: params.request.nextConfig + }); + if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE && !isEdgeRendering) { + if (destination.host === request.nextUrl.host) { + destination.buildId = buildId || destination.buildId; + response.headers.set('x-middleware-rewrite', String(destination)); + } + } + /** + * When the request is a data request we must show if there was a rewrite + * with an internal header so the client knows which component to load + * from the data request. + */ const { url: relativeDestination, isRelative } = (0, _relativizeurl.parseRelativeURL)(destination.toString(), requestURL.toString()); + if (!isEdgeRendering && isNextDataRequest && // if the rewrite is external and external rewrite + // resolving config is enabled don't add this header + // so the upstream app can set it instead + !(process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE && relativeDestination.match(/http(s)?:\/\//))) { + response.headers.set('x-nextjs-rewrite', relativeDestination); + } + // Check to see if this is a non-relative rewrite. If it is, we need + // to check to see if it's an allowed origin to receive the rewritten + // headers. + const isAllowedOrigin = !isRelative ? (_params_request_nextConfig = params.request.nextConfig) == null ? void 0 : (_params_request_nextConfig_experimental = _params_request_nextConfig.experimental) == null ? void 0 : (_params_request_nextConfig_experimental_clientParamParsingOrigins = _params_request_nextConfig_experimental.clientParamParsingOrigins) == null ? void 0 : _params_request_nextConfig_experimental_clientParamParsingOrigins.some((origin)=>new RegExp(origin).test(destination.origin)) : false; + // If this is an RSC request, and the pathname or search has changed, and + // this isn't an external rewrite, we need to set the rewritten pathname and + // query headers. + if (isRSCRequest && (isRelative || isAllowedOrigin)) { + if (requestURL.pathname !== destination.pathname) { + response.headers.set(_approuterheaders.NEXT_REWRITTEN_PATH_HEADER, destination.pathname); + } + if (requestURL.search !== destination.search) { + response.headers.set(_approuterheaders.NEXT_REWRITTEN_QUERY_HEADER, // remove the leading ? from the search string + destination.search.slice(1)); + } + } + } + /** + * Always forward the `_rsc` search parameter to the rewritten URL for RSC requests, + * unless it's already present. This is necessary to ensure that RSC hash validation + * works correctly after a rewrite. For internal rewrites, the server can validate the + * RSC hash using the original URL, so forwarding the `_rsc` parameter is less critical. + * However, for external rewrites (where the request is proxied to another Next.js server), + * the external server does not have access to the original URL or its search parameters. + * In these cases, forwarding the `_rsc` parameter is essential so that the external server + * can perform the correct RSC hash validation. + */ if (response && rewrite && isRSCRequest && rscHash) { + const rewriteURL = new URL(rewrite); + if (!rewriteURL.searchParams.has(_approuterheaders.NEXT_RSC_UNION_QUERY)) { + rewriteURL.searchParams.set(_approuterheaders.NEXT_RSC_UNION_QUERY, rscHash); + response.headers.set('x-middleware-rewrite', rewriteURL.toString()); + } + } + /** + * For redirects we will not include the locale in case when it is the + * default and we must also make sure the outgoing URL is a data one if + * the incoming request was a data request. + */ const redirect = response == null ? void 0 : response.headers.get('Location'); + if (response && redirect && !isEdgeRendering) { + const redirectURL = new _nexturl.NextURL(redirect, { + forceLocale: false, + headers: params.request.headers, + nextConfig: params.request.nextConfig + }); + /** + * Responses created from redirects have immutable headers so we have + * to clone the response to be able to modify it. + */ response = new Response(response.body, response); + if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) { + if (redirectURL.host === requestURL.host) { + redirectURL.buildId = buildId || redirectURL.buildId; + response.headers.set('Location', (0, _relativizeurl.getRelativeURL)(redirectURL, requestURL)); + } + } + /** + * When the request is a data request we can't use the location header as + * it may end up with CORS error. Instead we map to an internal header so + * the client knows the destination. + */ if (isNextDataRequest) { + response.headers.delete('Location'); + response.headers.set('x-nextjs-redirect', (0, _relativizeurl.getRelativeURL)(redirectURL.toString(), requestURL.toString())); + } + } + const finalResponse = response ? response : _response.NextResponse.next(); + // Flight headers are not overridable / removable so they are applied at the end. + const middlewareOverrideHeaders = finalResponse.headers.get('x-middleware-override-headers'); + const overwrittenHeaders = []; + if (middlewareOverrideHeaders) { + for (const [key, value] of flightHeaders){ + finalResponse.headers.set(`x-middleware-request-${key}`, value); + overwrittenHeaders.push(key); + } + if (overwrittenHeaders.length > 0) { + finalResponse.headers.set('x-middleware-override-headers', middlewareOverrideHeaders + ',' + overwrittenHeaders.join(',')); + } + } + return { + response: finalResponse, + waitUntil: (0, _fetchevent.getWaitUntilPromiseFromEvent)(event) ?? Promise.resolve(), + fetchMetrics: request.fetchMetrics + }; +} + +//# sourceMappingURL=adapter.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/adapter.js.map b/e-commerce/node_modules/next/dist/server/web/adapter.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2fdfa795d946bf5b8100c73bd9fccb79f655eaa9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/adapter.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/web/adapter.ts"],"sourcesContent":["import type { RequestData, FetchEventResult } from './types'\nimport type { RequestInit } from './spec-extension/request'\nimport { PageSignatureError } from './error'\nimport { fromNodeOutgoingHttpHeaders, normalizeNextQueryParam } from './utils'\nimport {\n NextFetchEvent,\n getWaitUntilPromiseFromEvent,\n} from './spec-extension/fetch-event'\nimport { NextRequest } from './spec-extension/request'\nimport { NextResponse } from './spec-extension/response'\nimport {\n parseRelativeURL,\n getRelativeURL,\n} from '../../shared/lib/router/utils/relativize-url'\nimport { NextURL } from './next-url'\nimport { stripInternalSearchParams } from '../internal-utils'\nimport { normalizeRscURL } from '../../shared/lib/router/utils/app-paths'\nimport {\n FLIGHT_HEADERS,\n NEXT_REWRITTEN_PATH_HEADER,\n NEXT_REWRITTEN_QUERY_HEADER,\n NEXT_RSC_UNION_QUERY,\n RSC_HEADER,\n} from '../../client/components/app-router-headers'\nimport { ensureInstrumentationRegistered } from './globals'\nimport { createRequestStoreForAPI } from '../async-storage/request-store'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createWorkStore } from '../async-storage/work-store'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { ResolvedCacheLifeProfiles } from '../config-shared'\nimport { NEXT_ROUTER_PREFETCH_HEADER } from '../../client/components/app-router-headers'\nimport { getTracer } from '../lib/trace/tracer'\nimport type { TextMapGetter } from 'next/dist/compiled/@opentelemetry/api'\nimport { MiddlewareSpan } from '../lib/trace/constants'\nimport { CloseController } from './web-on-close'\nimport { getEdgePreviewProps } from './get-edge-preview-props'\nimport { getBuiltinRequestContext } from '../after/builtin-request-context'\nimport { getImplicitTags } from '../lib/implicit-tags'\nimport { isRSCRequestHeader } from '../lib/is-rsc-request'\nimport { setRequestMeta } from '../request-meta'\n\n// The proxy (middleware) does not support `'use cache'`, so this work store\n// never reaches the code that reads `cacheLife` (and `'use cache'` is\n// disallowed on the edge runtime anyway). This sentinel satisfies the\n// non-optional type while throwing if `default` is ever read, matching the\n// \"never read\" sentinels used for the proxy's other unused renderOpts fields\n// (`staticPageGenerationTimeout: 0`, `useCacheTimeout: 0`). It surfaces loudly\n// rather than silently serving a misleading profile.\nconst proxyCacheLifeProfiles: ResolvedCacheLifeProfiles = {\n get default(): never {\n throw new InvariantError(\n 'Proxy does not support `use cache`, so reading its `default` cacheLife profile is unexpected.'\n )\n },\n}\n\nexport class NextRequestHint extends NextRequest {\n sourcePage: string\n fetchMetrics: FetchEventResult['fetchMetrics'] | undefined\n\n constructor(params: {\n init: RequestInit\n input: Request | string\n page: string\n }) {\n super(params.input, params.init)\n this.sourcePage = params.page\n }\n\n get request() {\n throw new PageSignatureError({ page: this.sourcePage })\n }\n\n respondWith() {\n throw new PageSignatureError({ page: this.sourcePage })\n }\n\n waitUntil() {\n throw new PageSignatureError({ page: this.sourcePage })\n }\n}\n\nconst headersGetter: TextMapGetter = {\n keys: (headers) => Array.from(headers.keys()),\n get: (headers, key) => headers.get(key) ?? undefined,\n}\n\nexport type AdapterOptions = {\n handler: (req: NextRequestHint, event: NextFetchEvent) => Promise\n page: string\n request: RequestData\n IncrementalCache?: typeof import('../lib/incremental-cache').IncrementalCache\n incrementalCacheHandler?: typeof import('../lib/incremental-cache').CacheHandler\n bypassNextUrl?: boolean\n}\n\n// This has to be compatible with what the Vercel builder does as well:\n// https://github.com/vercel/vercel/blob/0e0a6eb9f12216202ae2f5ee37e4ada1796361fd/packages/next/src/edge-function-source/get-edge-function.ts#L112-L136\nexport type EdgeHandler = (opts: {\n request: AdapterOptions['request']\n}) => Promise\n\nlet propagator: (request: NextRequestHint, fn: () => T) => T = (\n request,\n fn\n) => {\n const tracer = getTracer()\n return tracer.withPropagatedContext(request.headers, fn, headersGetter)\n}\n\nlet testApisIntercepted = false\n\nfunction ensureTestApisIntercepted() {\n if (!testApisIntercepted) {\n testApisIntercepted = true\n if (process.env.NEXT_PRIVATE_TEST_PROXY === 'true') {\n const { interceptTestApis, wrapRequestHandler } =\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-edge') as typeof import('../../experimental/testmode/server-edge')\n interceptTestApis()\n propagator = wrapRequestHandler(propagator)\n }\n }\n}\n\nexport async function adapter(\n params: AdapterOptions\n): Promise {\n ensureTestApisIntercepted()\n await ensureInstrumentationRegistered()\n\n // TODO-APP: use explicit marker for this\n const isEdgeRendering =\n typeof (globalThis as any).__BUILD_MANIFEST !== 'undefined'\n\n params.request.url = normalizeRscURL(params.request.url)\n\n const requestURL = params.bypassNextUrl\n ? new URL(params.request.url)\n : new NextURL(params.request.url, {\n headers: params.request.headers,\n nextConfig: params.request.nextConfig,\n })\n\n // Iterator uses an index to keep track of the current iteration. Because of deleting and appending below we can't just use the iterator.\n // Instead we use the keys before iteration.\n const keys = [...requestURL.searchParams.keys()]\n for (const key of keys) {\n const value = requestURL.searchParams.getAll(key)\n\n const normalizedKey = normalizeNextQueryParam(key)\n if (normalizedKey) {\n requestURL.searchParams.delete(normalizedKey)\n for (const val of value) {\n requestURL.searchParams.append(normalizedKey, val)\n }\n requestURL.searchParams.delete(key)\n }\n }\n\n // Ensure users only see page requests, never data requests.\n let buildId = process.env.__NEXT_BUILD_ID || ''\n if ('buildId' in requestURL) {\n buildId = (requestURL as NextURL).buildId || ''\n requestURL.buildId = ''\n }\n let deploymentId = process.env.NEXT_DEPLOYMENT_ID\n\n const requestHeaders = fromNodeOutgoingHttpHeaders(params.request.headers)\n const isNextDataRequest = requestHeaders.has('x-nextjs-data')\n const isRSCRequest = isRSCRequestHeader(requestHeaders.get(RSC_HEADER))\n\n if (isNextDataRequest && requestURL.pathname === '/index') {\n requestURL.pathname = '/'\n }\n\n const flightHeaders = new Map()\n\n // Headers should only be stripped for middleware\n if (!isEdgeRendering && !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {\n for (const header of FLIGHT_HEADERS) {\n const value = requestHeaders.get(header)\n if (value !== null) {\n flightHeaders.set(header, value)\n requestHeaders.delete(header)\n }\n }\n }\n\n const normalizeURL = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n ? new URL(params.request.url)\n : requestURL\n\n const rscHash = normalizeURL.searchParams.get(NEXT_RSC_UNION_QUERY)\n\n const request = new NextRequestHint({\n page: params.page,\n // Strip internal query parameters off the request.\n input: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n ? normalizeURL.toString()\n : stripInternalSearchParams(normalizeURL).toString(),\n init: {\n body: params.request.body,\n headers: requestHeaders,\n method: params.request.method,\n nextConfig: params.request.nextConfig,\n signal: params.request.signal,\n },\n })\n\n if (params.request.requestMeta) {\n setRequestMeta(request, params.request.requestMeta)\n }\n\n /**\n * This allows to identify the request as a data request. The user doesn't\n * need to know about this property neither use it. We add it for testing\n * purposes.\n */\n if (isNextDataRequest) {\n Object.defineProperty(request, '__isData', {\n enumerable: false,\n value: true,\n })\n }\n\n if (\n // If we are inside of the next start sandbox\n // leverage the shared instance if not we need\n // to create a fresh cache instance each time\n !(globalThis as any).__incrementalCacheShared &&\n (params as any).IncrementalCache\n ) {\n ;(globalThis as any).__incrementalCache = new (\n params as {\n IncrementalCache: typeof import('../lib/incremental-cache').IncrementalCache\n }\n ).IncrementalCache({\n CurCacheHandler: params.incrementalCacheHandler,\n minimalMode: process.env.NODE_ENV !== 'development',\n fetchCacheKeyPrefix: process.env.__NEXT_FETCH_CACHE_KEY_PREFIX,\n dev: process.env.NODE_ENV === 'development',\n requestHeaders: params.request.headers as any,\n\n previewProps: getEdgePreviewProps(),\n prerenderManifest: {\n version: -1 as any, // letting us know this doesn't conform to spec\n routes: {},\n dynamicRoutes: {},\n notFoundRoutes: [],\n preview: getEdgePreviewProps(),\n },\n })\n }\n\n // if we're in an edge runtime sandbox, we should use the waitUntil\n // that we receive from the enclosing NextServer\n const outerWaitUntil =\n params.request.waitUntil ?? getBuiltinRequestContext()?.waitUntil\n\n const event = new NextFetchEvent({\n request,\n page: params.page,\n context: outerWaitUntil ? { waitUntil: outerWaitUntil } : undefined,\n })\n let response\n let cookiesFromResponse\n\n response = await propagator(request, () => {\n // we only care to make async storage available for middleware\n const isMiddleware =\n params.page === '/middleware' ||\n params.page === '/src/middleware' ||\n params.page === '/proxy' ||\n params.page === '/src/proxy'\n\n if (isMiddleware) {\n // if we're in an edge function, we only get a subset of `nextConfig` (no `experimental`),\n // so we have to inject it via DefinePlugin.\n // in `next start` this will be passed normally (see `NextNodeServer.runMiddleware`).\n\n const waitUntil = event.waitUntil.bind(event)\n const closeController = new CloseController()\n\n return getTracer().trace(\n MiddlewareSpan.execute,\n {\n spanName: `middleware ${request.method}`,\n attributes: {\n 'http.target': request.nextUrl.pathname,\n 'http.method': request.method,\n },\n },\n async () => {\n try {\n const onUpdateCookies = (cookies: Array) => {\n cookiesFromResponse = cookies\n }\n const previewProps = getEdgePreviewProps()\n const page = '/' // Fake Work\n const fallbackRouteParams = null\n\n const implicitTags = await getImplicitTags(\n page,\n request.nextUrl.pathname,\n fallbackRouteParams\n )\n\n const requestStore = createRequestStoreForAPI(\n request,\n request.nextUrl,\n implicitTags,\n onUpdateCookies,\n previewProps,\n // Edge route handlers can't use `\"use cache\"`, so there's no HMR\n // refresh hash to thread through here.\n undefined\n )\n\n const workStore = createWorkStore({\n page,\n renderOpts: {\n cacheLifeProfiles: proxyCacheLifeProfiles,\n // Proxy doesn't do static generation, so this value does not\n // apply here. 0 is a sentinel: if something ever reads it,\n // it'll surface loudly instead of silently using a misleading\n // default.\n staticPageGenerationTimeout: 0,\n cacheComponents: false,\n // Proxy doesn't run instant validation; the level value is\n // irrelevant here.\n // TODO: remove validationLevel and other global config from renderOpts\n validationLevel: 'warning',\n experimental: {\n isRoutePPREnabled: false,\n authInterrupts:\n !!params.request.nextConfig?.experimental?.authInterrupts,\n // Proxy doesn't fill Cache Components entries, so this value\n // is never read. 0 is a sentinel: if something ever reads it,\n // the cache fill will time out immediately and surface the\n // bug.\n useCacheTimeout: 0,\n durableUseCacheEntries: false,\n },\n waitUntil,\n onClose: closeController.onClose.bind(closeController),\n onAfterTaskError: undefined,\n },\n isPrefetchRequest:\n request.headers.get(NEXT_ROUTER_PREFETCH_HEADER) === '1',\n buildId: buildId ?? '',\n deploymentId: deploymentId ?? '',\n previouslyRevalidatedTags: [],\n })\n\n return await workAsyncStorage.run(workStore, () =>\n workUnitAsyncStorage.run(\n requestStore,\n params.handler,\n request,\n event\n )\n )\n } finally {\n // middleware cannot stream, so we can consider the response closed\n // as soon as the handler returns.\n // we can delay running it until a bit later --\n // if it's needed, we'll have a `waitUntil` lock anyway.\n setTimeout(() => {\n closeController.dispatchClose()\n }, 0)\n }\n }\n )\n }\n return params.handler(request, event)\n })\n\n // check if response is a Response object\n if (response && !(response instanceof Response)) {\n throw new TypeError('Expected an instance of Response to be returned')\n }\n\n if (response && cookiesFromResponse) {\n response.headers.set('set-cookie', cookiesFromResponse)\n }\n\n /**\n * For rewrites we must always include the locale in the final pathname\n * so we re-create the NextURL forcing it to include it when the it is\n * an internal rewrite. Also we make sure the outgoing rewrite URL is\n * a data URL if the request was a data request.\n */\n const rewrite = response?.headers.get('x-middleware-rewrite')\n if (response && rewrite && (isRSCRequest || !isEdgeRendering)) {\n const destination = new NextURL(rewrite, {\n forceLocale: true,\n headers: params.request.headers,\n nextConfig: params.request.nextConfig,\n })\n\n if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE && !isEdgeRendering) {\n if (destination.host === request.nextUrl.host) {\n destination.buildId = buildId || destination.buildId\n response.headers.set('x-middleware-rewrite', String(destination))\n }\n }\n\n /**\n * When the request is a data request we must show if there was a rewrite\n * with an internal header so the client knows which component to load\n * from the data request.\n */\n const { url: relativeDestination, isRelative } = parseRelativeURL(\n destination.toString(),\n requestURL.toString()\n )\n\n if (\n !isEdgeRendering &&\n isNextDataRequest &&\n // if the rewrite is external and external rewrite\n // resolving config is enabled don't add this header\n // so the upstream app can set it instead\n !(\n process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE &&\n relativeDestination.match(/http(s)?:\\/\\//)\n )\n ) {\n response.headers.set('x-nextjs-rewrite', relativeDestination)\n }\n\n // Check to see if this is a non-relative rewrite. If it is, we need\n // to check to see if it's an allowed origin to receive the rewritten\n // headers.\n const isAllowedOrigin = !isRelative\n ? params.request.nextConfig?.experimental?.clientParamParsingOrigins?.some(\n (origin) => new RegExp(origin).test(destination.origin)\n )\n : false\n\n // If this is an RSC request, and the pathname or search has changed, and\n // this isn't an external rewrite, we need to set the rewritten pathname and\n // query headers.\n if (isRSCRequest && (isRelative || isAllowedOrigin)) {\n if (requestURL.pathname !== destination.pathname) {\n response.headers.set(NEXT_REWRITTEN_PATH_HEADER, destination.pathname)\n }\n if (requestURL.search !== destination.search) {\n response.headers.set(\n NEXT_REWRITTEN_QUERY_HEADER,\n // remove the leading ? from the search string\n destination.search.slice(1)\n )\n }\n }\n }\n\n /**\n * Always forward the `_rsc` search parameter to the rewritten URL for RSC requests,\n * unless it's already present. This is necessary to ensure that RSC hash validation\n * works correctly after a rewrite. For internal rewrites, the server can validate the\n * RSC hash using the original URL, so forwarding the `_rsc` parameter is less critical.\n * However, for external rewrites (where the request is proxied to another Next.js server),\n * the external server does not have access to the original URL or its search parameters.\n * In these cases, forwarding the `_rsc` parameter is essential so that the external server\n * can perform the correct RSC hash validation.\n */\n if (response && rewrite && isRSCRequest && rscHash) {\n const rewriteURL = new URL(rewrite)\n if (!rewriteURL.searchParams.has(NEXT_RSC_UNION_QUERY)) {\n rewriteURL.searchParams.set(NEXT_RSC_UNION_QUERY, rscHash)\n response.headers.set('x-middleware-rewrite', rewriteURL.toString())\n }\n }\n\n /**\n * For redirects we will not include the locale in case when it is the\n * default and we must also make sure the outgoing URL is a data one if\n * the incoming request was a data request.\n */\n const redirect = response?.headers.get('Location')\n if (response && redirect && !isEdgeRendering) {\n const redirectURL = new NextURL(redirect, {\n forceLocale: false,\n headers: params.request.headers,\n nextConfig: params.request.nextConfig,\n })\n\n /**\n * Responses created from redirects have immutable headers so we have\n * to clone the response to be able to modify it.\n */\n response = new Response(response.body, response)\n\n if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {\n if (redirectURL.host === requestURL.host) {\n redirectURL.buildId = buildId || redirectURL.buildId\n response.headers.set(\n 'Location',\n getRelativeURL(redirectURL, requestURL)\n )\n }\n }\n\n /**\n * When the request is a data request we can't use the location header as\n * it may end up with CORS error. Instead we map to an internal header so\n * the client knows the destination.\n */\n if (isNextDataRequest) {\n response.headers.delete('Location')\n response.headers.set(\n 'x-nextjs-redirect',\n getRelativeURL(redirectURL.toString(), requestURL.toString())\n )\n }\n }\n\n const finalResponse = response ? response : NextResponse.next()\n\n // Flight headers are not overridable / removable so they are applied at the end.\n const middlewareOverrideHeaders = finalResponse.headers.get(\n 'x-middleware-override-headers'\n )\n const overwrittenHeaders: string[] = []\n if (middlewareOverrideHeaders) {\n for (const [key, value] of flightHeaders) {\n finalResponse.headers.set(`x-middleware-request-${key}`, value)\n overwrittenHeaders.push(key)\n }\n\n if (overwrittenHeaders.length > 0) {\n finalResponse.headers.set(\n 'x-middleware-override-headers',\n middlewareOverrideHeaders + ',' + overwrittenHeaders.join(',')\n )\n }\n }\n\n return {\n response: finalResponse,\n waitUntil: getWaitUntilPromiseFromEvent(event) ?? Promise.resolve(),\n fetchMetrics: request.fetchMetrics,\n }\n}\n"],"names":["NextRequestHint","adapter","proxyCacheLifeProfiles","default","InvariantError","NextRequest","constructor","params","input","init","sourcePage","page","request","PageSignatureError","respondWith","waitUntil","headersGetter","keys","headers","Array","from","get","key","undefined","propagator","fn","tracer","getTracer","withPropagatedContext","testApisIntercepted","ensureTestApisIntercepted","process","env","NEXT_PRIVATE_TEST_PROXY","interceptTestApis","wrapRequestHandler","require","getBuiltinRequestContext","ensureInstrumentationRegistered","isEdgeRendering","globalThis","__BUILD_MANIFEST","url","normalizeRscURL","requestURL","bypassNextUrl","URL","NextURL","nextConfig","searchParams","value","getAll","normalizedKey","normalizeNextQueryParam","delete","val","append","buildId","__NEXT_BUILD_ID","deploymentId","NEXT_DEPLOYMENT_ID","requestHeaders","fromNodeOutgoingHttpHeaders","isNextDataRequest","has","isRSCRequest","isRSCRequestHeader","RSC_HEADER","pathname","flightHeaders","Map","__NEXT_NO_MIDDLEWARE_URL_NORMALIZE","header","FLIGHT_HEADERS","set","normalizeURL","rscHash","NEXT_RSC_UNION_QUERY","toString","stripInternalSearchParams","body","method","signal","requestMeta","setRequestMeta","Object","defineProperty","enumerable","__incrementalCacheShared","IncrementalCache","__incrementalCache","CurCacheHandler","incrementalCacheHandler","minimalMode","NODE_ENV","fetchCacheKeyPrefix","__NEXT_FETCH_CACHE_KEY_PREFIX","dev","previewProps","getEdgePreviewProps","prerenderManifest","version","routes","dynamicRoutes","notFoundRoutes","preview","outerWaitUntil","event","NextFetchEvent","context","response","cookiesFromResponse","isMiddleware","bind","closeController","CloseController","trace","MiddlewareSpan","execute","spanName","attributes","nextUrl","onUpdateCookies","cookies","fallbackRouteParams","implicitTags","getImplicitTags","requestStore","createRequestStoreForAPI","workStore","createWorkStore","renderOpts","cacheLifeProfiles","staticPageGenerationTimeout","cacheComponents","validationLevel","experimental","isRoutePPREnabled","authInterrupts","useCacheTimeout","durableUseCacheEntries","onClose","onAfterTaskError","isPrefetchRequest","NEXT_ROUTER_PREFETCH_HEADER","previouslyRevalidatedTags","workAsyncStorage","run","workUnitAsyncStorage","handler","setTimeout","dispatchClose","Response","TypeError","rewrite","destination","forceLocale","host","String","relativeDestination","isRelative","parseRelativeURL","__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE","match","isAllowedOrigin","clientParamParsingOrigins","some","origin","RegExp","test","NEXT_REWRITTEN_PATH_HEADER","search","NEXT_REWRITTEN_QUERY_HEADER","slice","rewriteURL","redirect","redirectURL","getRelativeURL","finalResponse","NextResponse","next","middlewareOverrideHeaders","overwrittenHeaders","push","length","join","getWaitU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Ac,EAACD,YAAYlG,QAAQ,IAAIlC,WAAWkC,QAAQ;QAE9D;IACF;IAEA,MAAMoG,gBAAgBpE,WAAWA,WAAWqE,sBAAY,CAACC,IAAI;IAE7D,iFAAiF;IACjF,MAAMC,4BAA4BH,cAAchK,OAAO,CAACG,GAAG,CACzD;IAEF,MAAMiK,qBAA+B,EAAE;IACvC,IAAID,2BAA2B;QAC7B,KAAK,MAAM,CAAC/J,KAAK4B,MAAM,IAAImB,cAAe;YACxC6G,cAAchK,OAAO,CAACwD,GAAG,CAAC,CAAC,qBAAqB,EAAEpD,KAAK,EAAE4B;YACzDoI,mBAAmBC,IAAI,CAACjK;QAC1B;QAEA,IAAIgK,mBAAmBE,MAAM,GAAG,GAAG;YACjCN,cAAchK,OAAO,CAACwD,GAAG,CACvB,iCACA2G,4BAA4B,MAAMC,mBAAmBG,IAAI,CAAC;QAE9D;IACF;IAEA,OAAO;QACL3E,UAAUoE;QACVnK,WAAW2K,IAAAA,wCAA4B,EAAC/E,UAAUgF,QAAQC,OAAO;QACjEC,cAAcjL,QAAQiL,YAAY;IACpC;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/edge-route-module-wrapper.d.ts b/e-commerce/node_modules/next/dist/server/web/edge-route-module-wrapper.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..45e5a6282a619ddcdac63325717c3b9c9fb30f22 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/edge-route-module-wrapper.d.ts @@ -0,0 +1,38 @@ +import type { AppRouteRouteModule } from '../route-modules/app-route/module'; +import './globals'; +import { type EdgeHandler } from './adapter'; +import { type CacheHandler as IncrementalCacheHandler } from '../lib/incremental-cache'; +import type { CacheHandler } from '../lib/cache-handlers/types'; +export interface WrapOptions { + page: string; + cacheHandlers?: Record; + incrementalCacheHandler?: typeof IncrementalCacheHandler; +} +/** + * EdgeRouteModuleWrapper is a wrapper around a route module. + * + * Note that this class should only be used in the edge runtime. + */ +export declare class EdgeRouteModuleWrapper { + private readonly routeModule; + private readonly cacheHandlers; + private readonly pageIsDynamic; + /** + * The constructor is wrapped with private to ensure that it can only be + * constructed by the static wrap method. + * + * @param routeModule the route module to wrap + */ + private constructor(); + /** + * This will wrap a module with the EdgeModuleWrapper and return a function + * that can be used as a handler for the edge runtime. + * + * @param module the module to wrap + * @param options any options that should be passed to the adapter and + * override the ones passed from the runtime + * @returns a function that can be used as a handler for the edge runtime + */ + static wrap(routeModule: AppRouteRouteModule, options: WrapOptions): EdgeHandler; + private handler; +} diff --git a/e-commerce/node_modules/next/dist/server/web/edge-route-module-wrapper.js b/e-commerce/node_modules/next/dist/server/web/edge-route-module-wrapper.js new file mode 100644 index 0000000000000000000000000000000000000000..b8fc8a2d9fe3fb5ea421cb9311350722594c73f6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/edge-route-module-wrapper.js @@ -0,0 +1,135 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "EdgeRouteModuleWrapper", { + enumerable: true, + get: function() { + return EdgeRouteModuleWrapper; + } +}); +require("./globals"); +const _adapter = require("./adapter"); +const _incrementalcache = require("../lib/incremental-cache"); +const _handlers = require("../use-cache/handlers"); +const _internaledgewaituntil = require("./internal-edge-wait-until"); +const _serverutils = require("../server-utils"); +const _querystring = require("../../shared/lib/router/utils/querystring"); +const _webonclose = require("./web-on-close"); +const _getedgepreviewprops = require("./get-edge-preview-props"); +const _web = require("../../server/base-http/web"); +const _utils = require("../../shared/lib/router/utils"); +class EdgeRouteModuleWrapper { + /** + * The constructor is wrapped with private to ensure that it can only be + * constructed by the static wrap method. + * + * @param routeModule the route module to wrap + */ constructor(routeModule, cacheHandlers){ + this.routeModule = routeModule; + this.cacheHandlers = cacheHandlers; + this.pageIsDynamic = (0, _utils.isDynamicRoute)(routeModule.definition.pathname); + } + /** + * This will wrap a module with the EdgeModuleWrapper and return a function + * that can be used as a handler for the edge runtime. + * + * @param module the module to wrap + * @param options any options that should be passed to the adapter and + * override the ones passed from the runtime + * @returns a function that can be used as a handler for the edge runtime + */ static wrap(routeModule, options) { + // Create the module wrapper. + const wrapper = new EdgeRouteModuleWrapper(routeModule, options.cacheHandlers ?? {}); + // Return the wrapping function. + return (opts)=>{ + return (0, _adapter.adapter)({ + ...opts, + IncrementalCache: _incrementalcache.IncrementalCache, + incrementalCacheHandler: options.incrementalCacheHandler, + // Bind the handler method to the wrapper so it still has context. + handler: wrapper.handler.bind(wrapper), + page: options.page + }); + }; + } + async handler(request, evt) { + const utils = (0, _serverutils.getServerUtils)({ + pageIsDynamic: this.pageIsDynamic, + page: this.routeModule.definition.pathname, + basePath: request.nextUrl.basePath, + // We don't need the `handleRewrite` util, so can just pass an empty object + rewrites: {}, + // only used for rewrites, so setting an arbitrary default value here + caseSensitive: false + }); + const { nextConfig } = this.routeModule.getNextConfigEdge(new _web.WebNextRequest(request)); + (0, _handlers.initializeCacheHandlers)(nextConfig.cacheMaxMemorySize); + for (const [kind, cacheHandler] of Object.entries(this.cacheHandlers)){ + (0, _handlers.setCacheHandler)(kind, cacheHandler); + } + const { params } = utils.normalizeDynamicRouteParams((0, _querystring.searchParamsToUrlQuery)(request.nextUrl.searchParams), false); + const waitUntil = evt.waitUntil.bind(evt); + const closeController = new _webonclose.CloseController(); + const previewProps = (0, _getedgepreviewprops.getEdgePreviewProps)(); + // Create the context for the handler. This contains the params from the + // match (if any). + const context = { + params, + previewProps, + renderOpts: { + waitUntil, + onClose: closeController.onClose.bind(closeController), + onAfterTaskError: undefined, + cacheComponents: !!process.env.__NEXT_CACHE_COMPONENTS, + // Edge runtime doesn't run instant validation; the level value is + // irrelevant here. + // TODO: Remove validationLevel and other global config from renderOpts + validationLevel: 'warning', + experimental: { + authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS, + // Edge runtime doesn't support Cache Components, so this value is + // never read. 0 is a sentinel: if something ever reads it, the cache + // fill will time out immediately and surface the bug. + useCacheTimeout: 0, + durableUseCacheEntries: false + }, + cacheLifeProfiles: nextConfig.cacheLife, + // Edge runtime doesn't do static generation, so this value does not + // apply here. 0 is a sentinel: if something ever reads it, it'll + // surface loudly instead of silently using a misleading default. + staticPageGenerationTimeout: 0 + }, + sharedContext: { + buildId: '', + deploymentId: '' + } + }; + // Get the response from the handler. + let res = await this.routeModule.handle(request, context); + const waitUntilPromises = [ + (0, _internaledgewaituntil.internal_getCurrentFunctionWaitUntil)() + ]; + if (context.renderOpts.pendingWaitUntil) { + waitUntilPromises.push(context.renderOpts.pendingWaitUntil); + } + evt.waitUntil(Promise.all(waitUntilPromises)); + if (!res.body) { + // we can delay running it until a bit later -- + // if it's needed, we'll have a `waitUntil` lock anyway. + setTimeout(()=>closeController.dispatchClose(), 0); + } else { + // NOTE: if this is a streaming response, onClose may be called later, + // so we can't rely on `closeController.listeners` -- it might be 0 at this point. + const trackedBody = (0, _webonclose.trackStreamConsumed)(res.body, ()=>closeController.dispatchClose()); + res = new Response(trackedBody, { + status: res.status, + statusText: res.statusText, + headers: res.headers + }); + } + return res; + } +} + +//# sourceMappingURL=edge-route-module-wrapper.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/edge-route-module-wrapper.js.map b/e-commerce/node_modules/next/dist/server/web/edge-route-module-wrapper.js.map new file mode 100644 index 0000000000000000000000000000000000000000..280c015825e74adc484ddea050017cdd1360b1d6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/edge-route-module-wrapper.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/web/edge-route-module-wrapper.ts"],"sourcesContent":["import type {\n AppRouteRouteHandlerContext,\n AppRouteRouteModule,\n} from '../route-modules/app-route/module'\n\nimport './globals'\n\nimport { adapter, type NextRequestHint, type EdgeHandler } from './adapter'\nimport {\n IncrementalCache,\n type CacheHandler as IncrementalCacheHandler,\n} from '../lib/incremental-cache'\nimport type { CacheHandler } from '../lib/cache-handlers/types'\nimport { initializeCacheHandlers, setCacheHandler } from '../use-cache/handlers'\nimport type { NextFetchEvent } from './spec-extension/fetch-event'\nimport { internal_getCurrentFunctionWaitUntil } from './internal-edge-wait-until'\nimport { getServerUtils } from '../server-utils'\nimport { searchParamsToUrlQuery } from '../../shared/lib/router/utils/querystring'\nimport { CloseController, trackStreamConsumed } from './web-on-close'\nimport { getEdgePreviewProps } from './get-edge-preview-props'\nimport { WebNextRequest } from '../../server/base-http/web'\nimport { isDynamicRoute } from '../../shared/lib/router/utils'\n\nexport interface WrapOptions {\n page: string\n cacheHandlers?: Record\n incrementalCacheHandler?: typeof IncrementalCacheHandler\n}\n\n/**\n * EdgeRouteModuleWrapper is a wrapper around a route module.\n *\n * Note that this class should only be used in the edge runtime.\n */\nexport class EdgeRouteModuleWrapper {\n private readonly pageIsDynamic: boolean\n\n /**\n * The constructor is wrapped with private to ensure that it can only be\n * constructed by the static wrap method.\n *\n * @param routeModule the route module to wrap\n */\n private constructor(\n private readonly routeModule: AppRouteRouteModule,\n private readonly cacheHandlers: Record\n ) {\n this.pageIsDynamic = isDynamicRoute(routeModule.definition.pathname)\n }\n\n /**\n * This will wrap a module with the EdgeModuleWrapper and return a function\n * that can be used as a handler for the edge runtime.\n *\n * @param module the module to wrap\n * @param options any options that should be passed to the adapter and\n * override the ones passed from the runtime\n * @returns a function that can be used as a handler for the edge runtime\n */\n public static wrap(\n routeModule: AppRouteRouteModule,\n options: WrapOptions\n ): EdgeHandler {\n // Create the module wrapper.\n const wrapper = new EdgeRouteModuleWrapper(\n routeModule,\n options.cacheHandlers ?? {}\n )\n\n // Return the wrapping function.\n return (opts) => {\n return adapter({\n ...opts,\n IncrementalCache,\n incrementalCacheHandler: options.incrementalCacheHandler,\n // Bind the handler method to the wrapper so it still has context.\n handler: wrapper.handler.bind(wrapper),\n page: options.page,\n })\n }\n }\n\n private async handler(\n request: NextRequestHint,\n evt: NextFetchEvent\n ): Promise {\n const utils = getServerUtils({\n pageIsDynamic: this.pageIsDynamic,\n page: this.routeModule.definition.pathname,\n basePath: request.nextUrl.basePath,\n // We don't need the `handleRewrite` util, so can just pass an empty object\n rewrites: {},\n // only used for rewrites, so setting an arbitrary default value here\n caseSensitive: false,\n })\n\n const { nextConfig } = this.routeModule.getNextConfigEdge(\n new WebNextRequest(request)\n )\n initializeCacheHandlers(nextConfig.cacheMaxMemorySize)\n for (const [kind, cacheHandler] of Object.entries(this.cacheHandlers)) {\n setCacheHandler(kind, cacheHandler)\n }\n\n const { params } = utils.normalizeDynamicRouteParams(\n searchParamsToUrlQuery(request.nextUrl.searchParams),\n false\n )\n\n const waitUntil = evt.waitUntil.bind(evt)\n const closeController = new CloseController()\n\n const previewProps = getEdgePreviewProps()\n\n // Create the context for the handler. This contains the params from the\n // match (if any).\n const context: AppRouteRouteHandlerContext = {\n params,\n previewProps,\n renderOpts: {\n waitUntil,\n onClose: closeController.onClose.bind(closeController),\n onAfterTaskError: undefined,\n cacheComponents: !!process.env.__NEXT_CACHE_COMPONENTS,\n // Edge runtime doesn't run instant validation; the level value is\n // irrelevant here.\n // TODO: Remove validationLevel and other global config from renderOpts\n validationLevel: 'warning',\n experimental: {\n authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS,\n // Edge runtime doesn't support Cache Components, so this value is\n // never read. 0 is a sentinel: if something ever reads it, the cache\n // fill will time out immediately and surface the bug.\n useCacheTimeout: 0,\n durableUseCacheEntries: false,\n },\n cacheLifeProfiles: nextConfig.cacheLife,\n // Edge runtime doesn't do static generation, so this value does not\n // apply here. 0 is a sentinel: if something ever reads it, it'll\n // surface loudly instead of silently using a misleading default.\n staticPageGenerationTimeout: 0,\n },\n sharedContext: {\n buildId: '', // TODO: Populate this properly.\n deploymentId: '', // TODO: Populate this properly.\n },\n }\n\n // Get the response from the handler.\n let res = await this.routeModule.handle(request, context)\n\n const waitUntilPromises = [internal_getCurrentFunctionWaitUntil()]\n if (context.renderOpts.pendingWaitUntil) {\n waitUntilPromises.push(context.renderOpts.pendingWaitUntil)\n }\n evt.waitUntil(Promise.all(waitUntilPromises))\n\n if (!res.body) {\n // we can delay running it until a bit later --\n // if it's needed, we'll have a `waitUntil` lock anyway.\n setTimeout(() => closeController.dispatchClose(), 0)\n } else {\n // NOTE: if this is a streaming response, onClose may be called later,\n // so we can't rely on `closeController.listeners` -- it might be 0 at this point.\n const trackedBody = trackStreamConsumed(res.body, () =>\n closeController.dispatchClose()\n )\n res = new Response(trackedBody, {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n })\n }\n\n return res\n }\n}\n"],"names":["EdgeRouteModuleWrapper","routeModule","cacheHandlers","pageIsDynamic","isDynamicRoute","definition","pathname","wrap","options","wrapper","opts","adapter","IncrementalCache","incrementalCacheHandler","handler","bind","page","request","evt","utils","getServerUtils","basePath","nextUrl","rewrites","caseSensitive","nextConfig","getNextConfigEdge","WebNextRequest","initializeCacheHandlers","cacheMaxMemorySize","kind","cacheHandler","Object","entries","setCacheHandler","params","normalizeDynamicRouteParams","searchParamsToUrlQuery","searchParams","waitUntil","closeController","CloseController","previewProps","getEdgePreviewProps","context","renderOpts","onClose","onAfterTaskError","undefined","cacheComponents","process","env","__NEXT_CACHE_COMPONENTS","validationLevel","experimental","authInterrupts","__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS","useCacheTimeout","durableUseCacheEntries","cacheLifeProfiles","cacheLife","staticPageGenerationTimeout","sharedContext","buildId","deploymentId","res","handle","waitUntilPromises","internal_getCurrentFunctionWaitUntil","pendingWaitUntil","push","Promise","all","body","setTimeout","dispatchClose","trackedBody","trackStreamConsumed","Response","status","statusText","headers"],"mappings":";;;;+BAkCaA;;;eAAAA;;;QA7BN;yBAEyD;kCAIzD;0BAEkD;uCAEJ;6BACtB;6BACQ;4BACc;qCACjB;qBACL;uBACA;AAaxB,MAAMA;IAGX;;;;;GAKC,GACD,YACE,AAAiBC,WAAgC,EACjD,AAAiBC,aAA2C,CAC5D;aAFiBD,cAAAA;aACAC,gBAAAA;QAEjB,IAAI,CAACC,aAAa,GAAGC,IA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,YAAYf,IAAIe,UAAU;gBAC1BC,SAAShB,IAAIgB,OAAO;YACtB;QACF;QAEA,OAAOhB;IACT;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/error.d.ts b/e-commerce/node_modules/next/dist/server/web/error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..62eaa2d7cebac81649ab188145e5863919112f16 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/error.d.ts @@ -0,0 +1,11 @@ +export declare class PageSignatureError extends Error { + constructor({ page }: { + page: string; + }); +} +export declare class RemovedPageError extends Error { + constructor(); +} +export declare class RemovedUAError extends Error { + constructor(); +} diff --git a/e-commerce/node_modules/next/dist/server/web/error.js b/e-commerce/node_modules/next/dist/server/web/error.js new file mode 100644 index 0000000000000000000000000000000000000000..0c6e60fc256aced8f05ae6564a618b70a686fec0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/error.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + PageSignatureError: null, + RemovedPageError: null, + RemovedUAError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + PageSignatureError: function() { + return PageSignatureError; + }, + RemovedPageError: function() { + return RemovedPageError; + }, + RemovedUAError: function() { + return RemovedUAError; + } +}); +class PageSignatureError extends Error { + constructor({ page }){ + super(`The middleware "${page}" accepts an async API directly with the form: + + export function middleware(request, event) { + return NextResponse.redirect('/new-location') + } + + Read more: https://nextjs.org/docs/messages/middleware-new-signature + `); + } +} +class RemovedPageError extends Error { + constructor(){ + super(`The request.page has been deprecated in favour of \`URLPattern\`. + Read more: https://nextjs.org/docs/messages/middleware-request-page + `); + } +} +class RemovedUAError extends Error { + constructor(){ + super(`The request.ua has been removed in favour of \`userAgent\` function. + Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent + `); + } +} + +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/error.js.map b/e-commerce/node_modules/next/dist/server/web/error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..98728ce5ad96d61159376b25552a28fc0e172428 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/web/error.ts"],"sourcesContent":["export class PageSignatureError extends Error {\n constructor({ page }: { page: string }) {\n super(`The middleware \"${page}\" accepts an async API directly with the form:\n \n export function middleware(request, event) {\n return NextResponse.redirect('/new-location')\n }\n \n Read more: https://nextjs.org/docs/messages/middleware-new-signature\n `)\n }\n}\n\nexport class RemovedPageError extends Error {\n constructor() {\n super(`The request.page has been deprecated in favour of \\`URLPattern\\`.\n Read more: https://nextjs.org/docs/messages/middleware-request-page\n `)\n }\n}\n\nexport class RemovedUAError extends Error {\n constructor() {\n super(`The request.ua has been removed in favour of \\`userAgent\\` function.\n Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent\n `)\n }\n}\n"],"names":["PageSignatureError","RemovedPageError","RemovedUAError","Error","constructor","page"],"mappings":";;;;;;;;;;;;;;;;IAAaA,kBAAkB;eAAlBA;;IAaAC,gBAAgB;eAAhBA;;IAQAC,cAAc;eAAdA;;;AArBN,MAAMF,2BAA2BG;IACtCC,YAAY,EAAEC,IAAI,EAAoB,CAAE;QACtC,KAAK,CAAC,CAAC,gBAAgB,EAAEA,KAAK;;;;;;;EAOhC,CAAC;IACD;AACF;AAEO,MAAMJ,yBAAyBE;IACpCC,aAAc;QACZ,KAAK,CAAC,CAAC;;EAET,CAAC;IACD;AACF;AAEO,MAAMF,uBAAuBC;IAClCC,aAAc;QACZ,KAAK,CAAC,CAAC;;EAET,CAAC;IACD;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/exports/index.d.ts b/e-commerce/node_modules/next/dist/server/web/exports/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..33d2e8f6b646ee4994a0e06731c06a5064cb01a9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/exports/index.d.ts @@ -0,0 +1,7 @@ +export { ImageResponse } from '../spec-extension/image-response'; +export { NextRequest } from '../spec-extension/request'; +export { NextResponse } from '../spec-extension/response'; +export { userAgent, userAgentFromString } from '../spec-extension/user-agent'; +export { URLPattern } from '../spec-extension/url-pattern'; +export { after } from '../../after'; +export { connection } from '../../request/connection'; diff --git a/e-commerce/node_modules/next/dist/server/web/exports/index.js b/e-commerce/node_modules/next/dist/server/web/exports/index.js new file mode 100644 index 0000000000000000000000000000000000000000..63c68289a59b7e1ad60a31e238bf7e11caf3710d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/exports/index.js @@ -0,0 +1,56 @@ +// Alias index file of next/server for edge runtime for tree-shaking purpose +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + ImageResponse: null, + NextRequest: null, + NextResponse: null, + URLPattern: null, + after: null, + connection: null, + userAgent: null, + userAgentFromString: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + ImageResponse: function() { + return _imageresponse.ImageResponse; + }, + NextRequest: function() { + return _request.NextRequest; + }, + NextResponse: function() { + return _response.NextResponse; + }, + URLPattern: function() { + return _urlpattern.URLPattern; + }, + after: function() { + return _after.after; + }, + connection: function() { + return _connection.connection; + }, + userAgent: function() { + return _useragent.userAgent; + }, + userAgentFromString: function() { + return _useragent.userAgentFromString; + } +}); +const _imageresponse = require("../spec-extension/image-response"); +const _request = require("../spec-extension/request"); +const _response = require("../spec-extension/response"); +const _useragent = require("../spec-extension/user-agent"); +const _urlpattern = require("../spec-extension/url-pattern"); +const _after = require("../../after"); +const _connection = require("../../request/connection"); + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/exports/index.js.map b/e-commerce/node_modules/next/dist/server/web/exports/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8b7982d2dfa16ee79f3c8714b2c9aa1f3f3ba865 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/exports/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/exports/index.ts"],"sourcesContent":["// Alias index file of next/server for edge runtime for tree-shaking purpose\n\nexport { ImageResponse } from '../spec-extension/image-response'\nexport { NextRequest } from '../spec-extension/request'\nexport { NextResponse } from '../spec-extension/response'\nexport { userAgent, userAgentFromString } from '../spec-extension/user-agent'\nexport { URLPattern } from '../spec-extension/url-pattern'\nexport { after } from '../../after'\nexport { connection } from '../../request/connection'\n"],"names":["ImageResponse","NextRequest","NextResponse","URLPattern","after","connection","userAgent","userAgentFromString"],"mappings":"AAAA,4EAA4E;;;;;;;;;;;;;;;;;;;;;;IAEnEA,aAAa;eAAbA,4BAAa;;IACbC,WAAW;eAAXA,oBAAW;;IACXC,YAAY;eAAZA,sBAAY;;IAEZC,UAAU;eAAVA,sBAAU;;IACVC,KAAK;eAALA,YAAK;;IACLC,UAAU;eAAVA,sBAAU;;IAHVC,SAAS;eAATA,oBAAS;;IAAEC,mBAAmB;eAAnBA,8BAAmB;;;+BAHT;yBACF;0BACC;2BACkB;4BACpB;uBACL;4BACK","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/get-edge-preview-props.d.ts b/e-commerce/node_modules/next/dist/server/web/get-edge-preview-props.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec7aaf1187d87f417d78d1be278c0d28c227745f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/get-edge-preview-props.d.ts @@ -0,0 +1,10 @@ +/** + * In edge runtime, these props directly accessed from environment variables. + * - local: env vars will be injected through edge-runtime as runtime env vars + * - deployment: env vars will be replaced by edge build pipeline + */ +export declare function getEdgePreviewProps(): { + previewModeId: string; + previewModeSigningKey: string; + previewModeEncryptionKey: string; +}; diff --git a/e-commerce/node_modules/next/dist/server/web/get-edge-preview-props.js b/e-commerce/node_modules/next/dist/server/web/get-edge-preview-props.js new file mode 100644 index 0000000000000000000000000000000000000000..85c4148be0189675186143479b190a1efcf9dfd5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/get-edge-preview-props.js @@ -0,0 +1,23 @@ +/** + * In edge runtime, these props directly accessed from environment variables. + * - local: env vars will be injected through edge-runtime as runtime env vars + * - deployment: env vars will be replaced by edge build pipeline + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getEdgePreviewProps", { + enumerable: true, + get: function() { + return getEdgePreviewProps; + } +}); +function getEdgePreviewProps() { + return { + previewModeId: process.env.__NEXT_PREVIEW_MODE_ID || '', + previewModeSigningKey: process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY || '', + previewModeEncryptionKey: process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY || '' + }; +} + +//# sourceMappingURL=get-edge-preview-props.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/get-edge-preview-props.js.map b/e-commerce/node_modules/next/dist/server/web/get-edge-preview-props.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6e11752b621a04b09d855024764afc60e985127f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/get-edge-preview-props.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/web/get-edge-preview-props.ts"],"sourcesContent":["/**\n * In edge runtime, these props directly accessed from environment variables.\n * - local: env vars will be injected through edge-runtime as runtime env vars\n * - deployment: env vars will be replaced by edge build pipeline\n */\nexport function getEdgePreviewProps() {\n return {\n previewModeId: process.env.__NEXT_PREVIEW_MODE_ID || '',\n previewModeSigningKey: process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY || '',\n previewModeEncryptionKey:\n process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY || '',\n }\n}\n"],"names":["getEdgePreviewProps","previewModeId","process","env","__NEXT_PREVIEW_MODE_ID","previewModeSigningKey","__NEXT_PREVIEW_MODE_SIGNING_KEY","previewModeEncryptionKey","__NEXT_PREVIEW_MODE_ENCRYPTION_KEY"],"mappings":"AAAA;;;;CAIC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA;IACd,OAAO;QACLC,eAAeC,QAAQC,GAAG,CAACC,sBAAsB,IAAI;QACrDC,uBAAuBH,QAAQC,GAAG,CAACG,+BAA+B,IAAI;QACtEC,0BACEL,QAAQC,GAAG,CAACK,kCAAkC,IAAI;IACtD;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/globals.d.ts b/e-commerce/node_modules/next/dist/server/web/globals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3780518e3885e55c6f879eb3df0c97e36ca69dc3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/globals.d.ts @@ -0,0 +1,4 @@ +import type { InstrumentationModule, InstrumentationOnRequestError } from '../instrumentation/types'; +export declare function getEdgeInstrumentationModule(): Promise; +export declare function edgeInstrumentationOnRequestError(...args: Parameters): Promise; +export declare function ensureInstrumentationRegistered(): Promise; diff --git a/e-commerce/node_modules/next/dist/server/web/globals.js b/e-commerce/node_modules/next/dist/server/web/globals.js new file mode 100644 index 0000000000000000000000000000000000000000..fc70f7cb529362a642a850afcaee1998a94eff20 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/globals.js @@ -0,0 +1,116 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + edgeInstrumentationOnRequestError: null, + ensureInstrumentationRegistered: null, + getEdgeInstrumentationModule: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + edgeInstrumentationOnRequestError: function() { + return edgeInstrumentationOnRequestError; + }, + ensureInstrumentationRegistered: function() { + return ensureInstrumentationRegistered; + }, + getEdgeInstrumentationModule: function() { + return getEdgeInstrumentationModule; + } +}); +async function getEdgeInstrumentationModule() { + const instrumentation = '_ENTRIES' in globalThis && _ENTRIES.middleware_instrumentation && await _ENTRIES.middleware_instrumentation; + return instrumentation; +} +let instrumentationModulePromise = null; +async function registerInstrumentation() { + // Ensure registerInstrumentation is not called in production build + if (process.env.NEXT_PHASE === 'phase-production-build') return; + if (!instrumentationModulePromise) { + instrumentationModulePromise = getEdgeInstrumentationModule(); + } + const instrumentation = await instrumentationModulePromise; + if (instrumentation == null ? void 0 : instrumentation.register) { + try { + await instrumentation.register(); + } catch (err) { + err.message = `An error occurred while loading instrumentation hook: ${err.message}`; + throw err; + } + } +} +async function edgeInstrumentationOnRequestError(...args) { + const instrumentation = await getEdgeInstrumentationModule(); + try { + var _instrumentation_onRequestError; + await (instrumentation == null ? void 0 : (_instrumentation_onRequestError = instrumentation.onRequestError) == null ? void 0 : _instrumentation_onRequestError.call(instrumentation, ...args)); + } catch (err) { + // Log the soft error and continue, since the original error has already been thrown + console.error('Error in instrumentation.onRequestError:', err); + } +} +let registerInstrumentationPromise = null; +function ensureInstrumentationRegistered() { + if (!registerInstrumentationPromise) { + registerInstrumentationPromise = registerInstrumentation(); + } + return registerInstrumentationPromise; +} +function getUnsupportedModuleErrorMessage(module1) { + // warning: if you change these messages, you must adjust how dev-overlay's middleware detects modules not found + return `The edge runtime does not support Node.js '${module1}' module. +Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`; +} +function __import_unsupported(moduleName) { + const proxy = new Proxy(function() {}, { + get (_obj, prop) { + if (prop === 'then') { + return {}; + } + throw new Error(getUnsupportedModuleErrorMessage(moduleName)); + }, + construct () { + throw new Error(getUnsupportedModuleErrorMessage(moduleName)); + }, + apply (_target, _this, args) { + if (typeof args[0] === 'function') { + return args[0](proxy); + } + throw new Error(getUnsupportedModuleErrorMessage(moduleName)); + } + }); + return new Proxy({}, { + get: ()=>proxy + }); +} +function enhanceGlobals() { + if (process.env.NEXT_RUNTIME !== 'edge') { + return; + } + // The condition is true when the "process" module is provided + if (process !== global.process) { + // prefer local process but global.process has correct "env" + process.env = global.process.env; + global.process = process; + } + // to allow building code that import but does not use node.js modules, + // webpack will expect this function to exist in global scope + try { + Object.defineProperty(globalThis, '__import_unsupported', { + value: __import_unsupported, + enumerable: false, + configurable: false + }); + } catch {} + // Eagerly fire instrumentation hook to make the startup faster. + void ensureInstrumentationRegistered(); +} +enhanceGlobals(); + +//# sourceMappingURL=globals.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/globals.js.map b/e-commerce/node_modules/next/dist/server/web/globals.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b31ab208835424da5e348c62b92ca99d2c2fc9af --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/globals.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/web/globals.ts"],"sourcesContent":["import type {\n InstrumentationModule,\n InstrumentationOnRequestError,\n} from '../instrumentation/types'\n\ndeclare const _ENTRIES: any\n\nexport async function getEdgeInstrumentationModule(): Promise<\n InstrumentationModule | undefined\n> {\n const instrumentation =\n '_ENTRIES' in globalThis &&\n _ENTRIES.middleware_instrumentation &&\n (await _ENTRIES.middleware_instrumentation)\n\n return instrumentation\n}\n\nlet instrumentationModulePromise: Promise | null = null\nasync function registerInstrumentation() {\n // Ensure registerInstrumentation is not called in production build\n if (process.env.NEXT_PHASE === 'phase-production-build') return\n if (!instrumentationModulePromise) {\n instrumentationModulePromise = getEdgeInstrumentationModule()\n }\n const instrumentation = await instrumentationModulePromise\n if (instrumentation?.register) {\n try {\n await instrumentation.register()\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n}\n\nexport async function edgeInstrumentationOnRequestError(\n ...args: Parameters\n) {\n const instrumentation = await getEdgeInstrumentationModule()\n try {\n await instrumentation?.onRequestError?.(...args)\n } catch (err) {\n // Log the soft error and continue, since the original error has already been thrown\n console.error('Error in instrumentation.onRequestError:', err)\n }\n}\n\nlet registerInstrumentationPromise: Promise | null = null\nexport function ensureInstrumentationRegistered() {\n if (!registerInstrumentationPromise) {\n registerInstrumentationPromise = registerInstrumentation()\n }\n return registerInstrumentationPromise\n}\n\nfunction getUnsupportedModuleErrorMessage(module: string) {\n // warning: if you change these messages, you must adjust how dev-overlay's middleware detects modules not found\n return `The edge runtime does not support Node.js '${module}' module.\nLearn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`\n}\n\nfunction __import_unsupported(moduleName: string) {\n const proxy: any = new Proxy(function () {}, {\n get(_obj, prop) {\n if (prop === 'then') {\n return {}\n }\n throw new Error(getUnsupportedModuleErrorMessage(moduleName))\n },\n construct() {\n throw new Error(getUnsupportedModuleErrorMessage(moduleName))\n },\n apply(_target, _this, args) {\n if (typeof args[0] === 'function') {\n return args[0](proxy)\n }\n throw new Error(getUnsupportedModuleErrorMessage(moduleName))\n },\n })\n return new Proxy({}, { get: () => proxy })\n}\n\nfunction enhanceGlobals() {\n if (process.env.NEXT_RUNTIME !== 'edge') {\n return\n }\n\n // The condition is true when the \"process\" module is provided\n if (process !== global.process) {\n // prefer local process but global.process has correct \"env\"\n process.env = global.process.env\n global.process = process\n }\n\n // to allow building code that import but does not use node.js modules,\n // webpack will expect this function to exist in global scope\n try {\n Object.defineProperty(globalThis, '__import_unsupported', {\n value: __import_unsupported,\n enumerable: false,\n configurable: false,\n })\n } catch {}\n\n // Eagerly fire instrumentation hook to make the startup faster.\n void ensureInstrumentationRegistered()\n}\n\nenhanceGlobals()\n"],"names":["edgeInstrumentationOnRequestError","ensureInstrumentationRegistered","getEdgeInstrumentationModule","instrumentation","globalThis","_ENTRIES","middleware_instrumentation","instrumentationModulePromise","registerInstrumentation","process","env","NEXT_PHASE","register","err","message","args","onRequestError","console","error","registerInstrumentationPromise","getUnsupportedModuleErrorMessage","module","__import_unsupported","moduleName","proxy","Proxy","get","_obj","prop","Error","construct","apply","_target","_this","enhanceGlobals","NEXT_RUNTIME","global","Object","defineProperty","value","enumerable","configurable"],"mappings":";;;;;;;;;;;;;;;;IAoCsBA,iCAAiC;eAAjCA;;IAaNC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QACnD;QACAQ,OAAMC,OAAO,EAAEC,KAAK,EAAElB,IAAI;YACxB,IAAI,OAAOA,IAAI,CAAC,EAAE,KAAK,YAAY;gBACjC,OAAOA,IAAI,CAAC,EAAE,CAACS;YACjB;YACA,MAAM,IAAIK,MAAMT,iCAAiCG;QACnD;IACF;IACA,OAAO,IAAIE,MAAM,CAAC,GAAG;QAAEC,KAAK,IAAMF;IAAM;AAC1C;AAEA,SAASU;IACP,IAAIzB,QAAQC,GAAG,CAACyB,YAAY,KAAK,QAAQ;QACvC;IACF;IAEA,8DAA8D;IAC9D,IAAI1B,YAAY2B,OAAO3B,OAAO,EAAE;QAC9B,4DAA4D;QAC5DA,QAAQC,GAAG,GAAG0B,OAAO3B,OAAO,CAACC,GAAG;QAChC0B,OAAO3B,OAAO,GAAGA;IACnB;IAEA,uEAAuE;IACvE,6DAA6D;IAC7D,IAAI;QACF4B,OAAOC,cAAc,CAAClC,YAAY,wBAAwB;YACxDmC,OAAOjB;YACPkB,YAAY;YACZC,cAAc;QAChB;IACF,EAAE,OAAM,CAAC;IAET,gEAAgE;IAChE,KAAKxC;AACP;AAEAiC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/http.d.ts b/e-commerce/node_modules/next/dist/server/web/http.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c2c044688b53371c67aad7c8b7348c7e2cbb7d7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/http.d.ts @@ -0,0 +1,18 @@ +/** + * List of valid HTTP methods that can be implemented by Next.js's Custom App + * Routes. + */ +export declare const HTTP_METHODS: readonly ["GET", "HEAD", "OPTIONS", "POST", "PUT", "DELETE", "PATCH"]; +/** + * A type representing the valid HTTP methods that can be implemented by + * Next.js's Custom App Routes. + */ +export type HTTP_METHOD = (typeof HTTP_METHODS)[number]; +/** + * Checks to see if the passed string is an HTTP method. Note that this is case + * sensitive. + * + * @param maybeMethod the string that may be an HTTP method + * @returns true if the string is an HTTP method + */ +export declare function isHTTPMethod(maybeMethod: string): maybeMethod is HTTP_METHOD; diff --git a/e-commerce/node_modules/next/dist/server/web/http.js b/e-commerce/node_modules/next/dist/server/web/http.js new file mode 100644 index 0000000000000000000000000000000000000000..652972a2c6df6d6f8f557cd8143af704f6951900 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/http.js @@ -0,0 +1,39 @@ +/** + * List of valid HTTP methods that can be implemented by Next.js's Custom App + * Routes. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + HTTP_METHODS: null, + isHTTPMethod: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + HTTP_METHODS: function() { + return HTTP_METHODS; + }, + isHTTPMethod: function() { + return isHTTPMethod; + } +}); +const HTTP_METHODS = [ + 'GET', + 'HEAD', + 'OPTIONS', + 'POST', + 'PUT', + 'DELETE', + 'PATCH' +]; +function isHTTPMethod(maybeMethod) { + return HTTP_METHODS.includes(maybeMethod); +} + +//# sourceMappingURL=http.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/http.js.map b/e-commerce/node_modules/next/dist/server/web/http.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c1a4a98fe3cc1e33c3830f674b11405f399c25f3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/http.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/web/http.ts"],"sourcesContent":["/**\n * List of valid HTTP methods that can be implemented by Next.js's Custom App\n * Routes.\n */\nexport const HTTP_METHODS = [\n 'GET',\n 'HEAD',\n 'OPTIONS',\n 'POST',\n 'PUT',\n 'DELETE',\n 'PATCH',\n] as const\n\n/**\n * A type representing the valid HTTP methods that can be implemented by\n * Next.js's Custom App Routes.\n */\nexport type HTTP_METHOD = (typeof HTTP_METHODS)[number]\n\n/**\n * Checks to see if the passed string is an HTTP method. Note that this is case\n * sensitive.\n *\n * @param maybeMethod the string that may be an HTTP method\n * @returns true if the string is an HTTP method\n */\nexport function isHTTPMethod(maybeMethod: string): maybeMethod is HTTP_METHOD {\n return HTTP_METHODS.includes(maybeMethod as HTTP_METHOD)\n}\n"],"names":["HTTP_METHODS","isHTTPMethod","maybeMethod","includes"],"mappings":"AAAA;;;CAGC;;;;;;;;;;;;;;;IACYA,YAAY;eAAZA;;IAuBGC,YAAY;eAAZA;;;AAvBT,MAAMD,eAAe;IAC1B;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAeM,SAASC,aAAaC,WAAmB;IAC9C,OAAOF,aAAaG,QAAQ,CAACD;AAC/B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/internal-edge-wait-until.d.ts b/e-commerce/node_modules/next/dist/server/web/internal-edge-wait-until.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4363f35431a86bd1d5cba8c9e0279d67f95a9fe --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/internal-edge-wait-until.d.ts @@ -0,0 +1,2 @@ +export declare function internal_getCurrentFunctionWaitUntil(): Promise | null; +export declare function internal_runWithWaitUntil(fn: () => T): T; diff --git a/e-commerce/node_modules/next/dist/server/web/internal-edge-wait-until.js b/e-commerce/node_modules/next/dist/server/web/internal-edge-wait-until.js new file mode 100644 index 0000000000000000000000000000000000000000..226781e1b73107253d76d6bc30e06d83a8b7e487 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/internal-edge-wait-until.js @@ -0,0 +1,64 @@ +// An internal module to expose the "waitUntil" API to Edge SSR and Edge Route Handler functions. +// This is highly experimental and subject to change. +// We still need a global key to bypass Webpack's layering of modules. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + internal_getCurrentFunctionWaitUntil: null, + internal_runWithWaitUntil: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + internal_getCurrentFunctionWaitUntil: function() { + return internal_getCurrentFunctionWaitUntil; + }, + internal_runWithWaitUntil: function() { + return internal_runWithWaitUntil; + } +}); +const GLOBAL_KEY = Symbol.for('__next_internal_waitUntil__'); +const state = // @ts-ignore +globalThis[GLOBAL_KEY] || // @ts-ignore +(globalThis[GLOBAL_KEY] = { + waitUntilCounter: 0, + waitUntilResolve: undefined, + waitUntilPromise: null +}); +// No matter how many concurrent requests are being handled, we want to make sure +// that the final promise is only resolved once all of the waitUntil promises have +// settled. +function resolveOnePromise() { + state.waitUntilCounter--; + if (state.waitUntilCounter === 0) { + state.waitUntilResolve(); + state.waitUntilPromise = null; + } +} +function internal_getCurrentFunctionWaitUntil() { + return state.waitUntilPromise; +} +function internal_runWithWaitUntil(fn) { + const result = fn(); + if (result && typeof result === 'object' && 'then' in result && 'finally' in result && typeof result.then === 'function' && typeof result.finally === 'function') { + if (!state.waitUntilCounter) { + // Create the promise for the next batch of waitUntil calls. + state.waitUntilPromise = new Promise((resolve)=>{ + state.waitUntilResolve = resolve; + }); + } + state.waitUntilCounter++; + return result.finally(()=>{ + resolveOnePromise(); + }); + } + return result; +} + +//# sourceMappingURL=internal-edge-wait-until.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/internal-edge-wait-until.js.map b/e-commerce/node_modules/next/dist/server/web/internal-edge-wait-until.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4a76840677f83fa580097a65ace32edff1a85e94 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/internal-edge-wait-until.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/web/internal-edge-wait-until.ts"],"sourcesContent":["// An internal module to expose the \"waitUntil\" API to Edge SSR and Edge Route Handler functions.\n// This is highly experimental and subject to change.\n\n// We still need a global key to bypass Webpack's layering of modules.\nconst GLOBAL_KEY = Symbol.for('__next_internal_waitUntil__')\n\nconst state: {\n waitUntilCounter: number\n waitUntilResolve: () => void\n waitUntilPromise: Promise | null\n} =\n // @ts-ignore\n globalThis[GLOBAL_KEY] ||\n // @ts-ignore\n (globalThis[GLOBAL_KEY] = {\n waitUntilCounter: 0,\n waitUntilResolve: undefined,\n waitUntilPromise: null,\n })\n\n// No matter how many concurrent requests are being handled, we want to make sure\n// that the final promise is only resolved once all of the waitUntil promises have\n// settled.\nfunction resolveOnePromise() {\n state.waitUntilCounter--\n if (state.waitUntilCounter === 0) {\n state.waitUntilResolve()\n state.waitUntilPromise = null\n }\n}\n\nexport function internal_getCurrentFunctionWaitUntil() {\n return state.waitUntilPromise\n}\n\nexport function internal_runWithWaitUntil(fn: () => T): T {\n const result = fn()\n if (\n result &&\n typeof result === 'object' &&\n 'then' in result &&\n 'finally' in result &&\n typeof result.then === 'function' &&\n typeof result.finally === 'function'\n ) {\n if (!state.waitUntilCounter) {\n // Create the promise for the next batch of waitUntil calls.\n state.waitUntilPromise = new Promise((resolve) => {\n state.waitUntilResolve = resolve\n })\n }\n state.waitUntilCounter++\n return result.finally(() => {\n resolveOnePromise()\n })\n }\n\n return result\n}\n"],"names":["internal_getCurrentFunctionWaitUntil","internal_runWithWaitUntil","GLOBAL_KEY","Symbol","for","state","globalThis","waitUntilCounter","waitUntilResolve","undefined","waitUntilPromise","resolveOnePromise","fn","result","then","finally","Promise","resolve"],"mappings":"AAAA,iGAAiG;AACjG,qDAAqD;AAErD,sEAAsE;;;;;;;;;;;;;;;;IA4BtDA,oCAAoC;eAApCA;;IAIAC,yBAAyB;eAAzBA;;;AA/BhB,MAAMC,aAAaC,OAAOC,GAAG,CAAC;AAE9B,MAAMC,QAKJ,aAAa;AACbC,UAAU,CAACJ,WAAW,IACtB,aAAa;AACZI,CAAAA,UAAU,CAACJ,WAAW,GAAG;IACxBK,kBAAkB;IAClBC,kBAAkBC;IAClBC,kBAAkB;AACpB,CAAA;AAEF,iFAAiF;AACjF,kFAAkF;AAClF,WAAW;AACX,SAASC;IACPN,MAAME,gBAAgB;IACtB,IAAIF,MAAME,gBAAgB,KAAK,GAAG;QAChCF,MAAMG,gBAAgB;QACtBH,MAAMK,gBAAgB,GAAG;IAC3B;AACF;AAEO,SAASV;IACd,OAAOK,MAAMK,gBAAgB;AAC/B;AAEO,SAAST,0BAA6BW,EAAW;IACtD,MAAMC,SAASD;IACf,IACEC,UACA,OAAOA,WAAW,YAClB,UAAUA,UACV,aAAaA,UACb,OAAOA,OAAOC,IAAI,KAAK,cACvB,OAAOD,OAAOE,OAAO,KAAK,YAC1B;QACA,IAAI,CAACV,MAAME,gBAAgB,EAAE;YAC3B,4DAA4D;YAC5DF,MAAMK,gBAAgB,GAAG,IAAIM,QAAc,CAACC;gBAC1CZ,MAAMG,gBAAgB,GAAGS;YAC3B;QACF;QACAZ,MAAME,gBAAgB;QACtB,OAAOM,OAAOE,OAAO,CAAC;YACpBJ;QACF;IACF;IAEA,OAAOE;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/next-url.d.ts b/e-commerce/node_modules/next/dist/server/web/next-url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2038a9d8c3d97749eeb8c35f1086340490431786 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/next-url.d.ts @@ -0,0 +1,57 @@ +import type { OutgoingHttpHeaders } from 'http'; +import type { DomainLocale, I18NConfig } from '../config-shared'; +import type { I18NProvider } from '../lib/i18n-provider'; +interface Options { + base?: string | URL; + headers?: OutgoingHttpHeaders; + forceLocale?: boolean; + nextConfig?: { + basePath?: string; + i18n?: I18NConfig | null; + trailingSlash?: boolean; + }; + i18nProvider?: I18NProvider; +} +declare const Internal: unique symbol; +export declare class NextURL { + private [Internal]; + constructor(input: string | URL, base?: string | URL, opts?: Options); + constructor(input: string | URL, opts?: Options); + private analyze; + private formatPathname; + private formatSearch; + get buildId(): string | undefined; + set buildId(buildId: string | undefined); + get locale(): string; + set locale(locale: string); + get defaultLocale(): string | undefined; + get domainLocale(): DomainLocale | undefined; + get searchParams(): URLSearchParams; + get host(): string; + set host(value: string); + get hostname(): string; + set hostname(value: string); + get port(): string; + set port(value: string); + get protocol(): string; + set protocol(value: string); + get href(): string; + set href(url: string); + get origin(): string; + get pathname(): string; + set pathname(value: string); + get hash(): string; + set hash(value: string); + get search(): string; + set search(value: string); + get password(): string; + set password(value: string); + get username(): string; + set username(value: string); + get basePath(): string; + set basePath(value: string); + toString(): string; + toJSON(): string; + clone(): NextURL; +} +export {}; diff --git a/e-commerce/node_modules/next/dist/server/web/next-url.js b/e-commerce/node_modules/next/dist/server/web/next-url.js new file mode 100644 index 0000000000000000000000000000000000000000..8d68b9b32cb523e954e48521c72907729e63baa7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/next-url.js @@ -0,0 +1,195 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NextURL", { + enumerable: true, + get: function() { + return NextURL; + } +}); +const _detectdomainlocale = require("../../shared/lib/i18n/detect-domain-locale"); +const _formatnextpathnameinfo = require("../../shared/lib/router/utils/format-next-pathname-info"); +const _gethostname = require("../../shared/lib/get-hostname"); +const _getnextpathnameinfo = require("../../shared/lib/router/utils/get-next-pathname-info"); +const REGEX_LOCALHOST_HOSTNAME = /^(?:127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)$/; +function parseURL(url, base) { + const parsed = new URL(String(url), base && String(base)); + if (REGEX_LOCALHOST_HOSTNAME.test(parsed.hostname)) { + parsed.hostname = 'localhost'; + } + return parsed; +} +const Internal = Symbol('NextURLInternal'); +class NextURL { + constructor(input, baseOrOpts, opts){ + let base; + let options; + if (typeof baseOrOpts === 'object' && 'pathname' in baseOrOpts || typeof baseOrOpts === 'string') { + base = baseOrOpts; + options = opts || {}; + } else { + options = opts || baseOrOpts || {}; + } + this[Internal] = { + url: parseURL(input, base ?? options.base), + options: options, + basePath: '' + }; + this.analyze(); + } + analyze() { + var _this_Internal_options_nextConfig_i18n, _this_Internal_options_nextConfig, _this_Internal_domainLocale, _this_Internal_options_nextConfig_i18n1, _this_Internal_options_nextConfig1; + const info = (0, _getnextpathnameinfo.getNextPathnameInfo)(this[Internal].url.pathname, { + nextConfig: this[Internal].options.nextConfig, + parseData: !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE, + i18nProvider: this[Internal].options.i18nProvider + }); + const hostname = (0, _gethostname.getHostname)(this[Internal].url, this[Internal].options.headers); + this[Internal].domainLocale = this[Internal].options.i18nProvider ? this[Internal].options.i18nProvider.detectDomainLocale(hostname) : (0, _detectdomainlocale.detectDomainLocale)((_this_Internal_options_nextConfig = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n = _this_Internal_options_nextConfig.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n.domains, hostname); + const defaultLocale = ((_this_Internal_domainLocale = this[Internal].domainLocale) == null ? void 0 : _this_Internal_domainLocale.defaultLocale) || ((_this_Internal_options_nextConfig1 = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n1 = _this_Internal_options_nextConfig1.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n1.defaultLocale); + this[Internal].url.pathname = info.pathname; + this[Internal].defaultLocale = defaultLocale; + this[Internal].basePath = info.basePath ?? ''; + this[Internal].buildId = info.buildId; + this[Internal].locale = info.locale ?? defaultLocale; + this[Internal].trailingSlash = info.trailingSlash; + } + formatPathname() { + return (0, _formatnextpathnameinfo.formatNextPathnameInfo)({ + basePath: this[Internal].basePath, + buildId: this[Internal].buildId, + defaultLocale: !this[Internal].options.forceLocale ? this[Internal].defaultLocale : undefined, + locale: this[Internal].locale, + pathname: this[Internal].url.pathname, + trailingSlash: this[Internal].trailingSlash + }); + } + formatSearch() { + return this[Internal].url.search; + } + get buildId() { + return this[Internal].buildId; + } + set buildId(buildId) { + this[Internal].buildId = buildId; + } + get locale() { + return this[Internal].locale ?? ''; + } + set locale(locale) { + var _this_Internal_options_nextConfig_i18n, _this_Internal_options_nextConfig; + if (!this[Internal].locale || !((_this_Internal_options_nextConfig = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n = _this_Internal_options_nextConfig.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n.locales.includes(locale))) { + throw new TypeError(`The NextURL configuration includes no locale "${locale}"`); + } + this[Internal].locale = locale; + } + get defaultLocale() { + return this[Internal].defaultLocale; + } + get domainLocale() { + return this[Internal].domainLocale; + } + get searchParams() { + return this[Internal].url.searchParams; + } + get host() { + return this[Internal].url.host; + } + set host(value) { + this[Internal].url.host = value; + } + get hostname() { + return this[Internal].url.hostname; + } + set hostname(value) { + this[Internal].url.hostname = value; + } + get port() { + return this[Internal].url.port; + } + set port(value) { + this[Internal].url.port = value; + } + get protocol() { + return this[Internal].url.protocol; + } + set protocol(value) { + this[Internal].url.protocol = value; + } + get href() { + const pathname = this.formatPathname(); + const search = this.formatSearch(); + return `${this.protocol}//${this.host}${pathname}${search}${this.hash}`; + } + set href(url) { + this[Internal].url = parseURL(url); + this.analyze(); + } + get origin() { + return this[Internal].url.origin; + } + get pathname() { + return this[Internal].url.pathname; + } + set pathname(value) { + this[Internal].url.pathname = value; + } + get hash() { + return this[Internal].url.hash; + } + set hash(value) { + this[Internal].url.hash = value; + } + get search() { + return this[Internal].url.search; + } + set search(value) { + this[Internal].url.search = value; + } + get password() { + return this[Internal].url.password; + } + set password(value) { + this[Internal].url.password = value; + } + get username() { + return this[Internal].url.username; + } + set username(value) { + this[Internal].url.username = value; + } + get basePath() { + return this[Internal].basePath; + } + set basePath(value) { + this[Internal].basePath = value.startsWith('/') ? value : `/${value}`; + } + toString() { + return this.href; + } + toJSON() { + return this.href; + } + [Symbol.for('edge-runtime.inspect.custom')]() { + return { + href: this.href, + origin: this.origin, + protocol: this.protocol, + username: this.username, + password: this.password, + host: this.host, + hostname: this.hostname, + port: this.port, + pathname: this.pathname, + search: this.search, + searchParams: this.searchParams, + hash: this.hash + }; + } + clone() { + return new NextURL(String(this), this[Internal].options); + } +} + +//# sourceMappingURL=next-url.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/next-url.js.map b/e-commerce/node_modules/next/dist/server/web/next-url.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ec491f86dee37a6dc0b69579657f8a6d3c6bb11b --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/next-url.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/web/next-url.ts"],"sourcesContent":["import type { OutgoingHttpHeaders } from 'http'\nimport type { DomainLocale, I18NConfig } from '../config-shared'\nimport type { I18NProvider } from '../lib/i18n-provider'\n\nimport { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'\nimport { formatNextPathnameInfo } from '../../shared/lib/router/utils/format-next-pathname-info'\nimport { getHostname } from '../../shared/lib/get-hostname'\nimport { getNextPathnameInfo } from '../../shared/lib/router/utils/get-next-pathname-info'\n\ninterface Options {\n base?: string | URL\n headers?: OutgoingHttpHeaders\n forceLocale?: boolean\n nextConfig?: {\n basePath?: string\n i18n?: I18NConfig | null\n trailingSlash?: boolean\n }\n i18nProvider?: I18NProvider\n}\n\nconst REGEX_LOCALHOST_HOSTNAME =\n /^(?:127(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\\[::1\\]|localhost)$/\n\nfunction parseURL(url: string | URL, base?: string | URL) {\n const parsed = new URL(String(url), base && String(base))\n if (REGEX_LOCALHOST_HOSTNAME.test(parsed.hostname)) {\n parsed.hostname = 'localhost'\n }\n return parsed\n}\n\nconst Internal = Symbol('NextURLInternal')\n\nexport class NextURL {\n private [Internal]: {\n basePath: string\n buildId?: string\n flightSearchParameters?: Record\n defaultLocale?: string\n domainLocale?: DomainLocale\n locale?: string\n options: Options\n trailingSlash?: boolean\n url: URL\n }\n\n constructor(input: string | URL, base?: string | URL, opts?: Options)\n constructor(input: string | URL, opts?: Options)\n constructor(\n input: string | URL,\n baseOrOpts?: string | URL | Options,\n opts?: Options\n ) {\n let base: undefined | string | URL\n let options: Options\n\n if (\n (typeof baseOrOpts === 'object' && 'pathname' in baseOrOpts) ||\n typeof baseOrOpts === 'string'\n ) {\n base = baseOrOpts\n options = opts || {}\n } else {\n options = opts || baseOrOpts || {}\n }\n\n this[Internal] = {\n url: parseURL(input, base ?? options.base),\n options: options,\n basePath: '',\n }\n\n this.analyze()\n }\n\n private analyze() {\n const info = getNextPathnameInfo(this[Internal].url.pathname, {\n nextConfig: this[Internal].options.nextConfig,\n parseData: !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE,\n i18nProvider: this[Internal].options.i18nProvider,\n })\n\n const hostname = getHostname(\n this[Internal].url,\n this[Internal].options.headers\n )\n this[Internal].domainLocale = this[Internal].options.i18nProvider\n ? this[Internal].options.i18nProvider.detectDomainLocale(hostname)\n : detectDomainLocale(\n this[Internal].options.nextConfig?.i18n?.domains,\n hostname\n )\n\n const defaultLocale =\n this[Internal].domainLocale?.defaultLocale ||\n this[Internal].options.nextConfig?.i18n?.defaultLocale\n\n this[Internal].url.pathname = info.pathname\n this[Internal].defaultLocale = defaultLocale\n this[Internal].basePath = info.basePath ?? ''\n this[Internal].buildId = info.buildId\n this[Internal].locale = info.locale ?? defaultLocale\n this[Internal].trailingSlash = info.trailingSlash\n }\n\n private formatPathname() {\n return formatNextPathnameInfo({\n basePath: this[Internal].basePath,\n buildId: this[Internal].buildId,\n defaultLocale: !this[Internal].options.forceLocale\n ? this[Internal].defaultLocale\n : undefined,\n locale: this[Internal].locale,\n pathname: this[Internal].url.pathname,\n trailingSlash: this[Internal].trailingSlash,\n })\n }\n\n private formatSearch() {\n return this[Internal].url.search\n }\n\n public get buildId() {\n return this[Internal].buildId\n }\n\n public set buildId(buildId: string | undefined) {\n this[Internal].buildId = buildId\n }\n\n public get locale() {\n return this[Internal].locale ?? ''\n }\n\n public set locale(locale: string) {\n if (\n !this[Internal].locale ||\n !this[Internal].options.nextConfig?.i18n?.locales.includes(locale)\n ) {\n throw new TypeError(\n `The NextURL configuration includes no locale \"${locale}\"`\n )\n }\n\n this[Internal].locale = locale\n }\n\n get defaultLocale() {\n return this[Internal].defaultLocale\n }\n\n get domainLocale() {\n return this[Internal].domainLocale\n }\n\n get searchParams() {\n return this[Internal].url.searchParams\n }\n\n get host() {\n return this[Internal].url.host\n }\n\n set host(value: string) {\n this[Internal].url.host = value\n }\n\n get hostname() {\n return this[Internal].url.hostname\n }\n\n set hostname(value: string) {\n this[Internal].url.hostname = value\n }\n\n get port() {\n return this[Internal].url.port\n }\n\n set port(value: string) {\n this[Internal].url.port = value\n }\n\n get protocol() {\n return this[Internal].url.protocol\n }\n\n set protocol(value: string) {\n this[Internal].url.protocol = value\n }\n\n get href() {\n const pathname = this.formatPathname()\n const search = this.formatSearch()\n return `${this.protocol}//${this.host}${pathname}${search}${this.hash}`\n }\n\n set href(url: string) {\n this[Internal].url = parseURL(url)\n this.analyze()\n }\n\n get origin() {\n return this[Internal].url.origin\n }\n\n get pathname() {\n return this[Internal].url.pathname\n }\n\n set pathname(value: string) {\n this[Internal].url.pathname = value\n }\n\n get hash() {\n return this[Internal].url.hash\n }\n\n set hash(value: string) {\n this[Internal].url.hash = value\n }\n\n get search() {\n return this[Internal].url.search\n }\n\n set search(value: string) {\n this[Internal].url.search = value\n }\n\n get password() {\n return this[Internal].url.password\n }\n\n set password(value: string) {\n this[Internal].url.password = value\n }\n\n get username() {\n return this[Internal].url.username\n }\n\n set username(value: string) {\n this[Internal].url.username = value\n }\n\n get basePath() {\n return this[Internal].basePath\n }\n\n set basePath(value: string) {\n this[Internal].basePath = value.startsWith('/') ? value : `/${value}`\n }\n\n toString() {\n return this.href\n }\n\n toJSON() {\n return this.href\n }\n\n [Symbol.for('edge-runtime.inspect.custom')]() {\n return {\n href: this.href,\n origin: this.origin,\n protocol: this.protocol,\n username: this.username,\n password: this.password,\n host: this.host,\n hostname: this.hostname,\n port: this.port,\n pathname: this.pathname,\n search: this.search,\n searchParams: this.searchParams,\n hash: this.hash,\n }\n }\n\n clone() {\n return new NextURL(String(this), this[Internal].options)\n }\n}\n"],"names":["NextURL","REGEX_LOCALHOST_HOSTNAME","parseURL","url","base","parsed","URL","String","test","hostname","Internal","Symbol","constructor","input","baseOrOpts","opts","options","basePath","analyze","info","getNextPathnameInfo","pathname","nextConfig","parseData","process","env","__NEXT_NO_MIDDLEWARE_URL_NORMALIZE","i18nProvider","getHostname","headers","domainLocale","detectDomainLocale","i18n","domains","defaultLocale","buildId","locale","trailingSlash","formatPathname","formatNextPathnameInfo","forceLocale","undefined","formatSearch","search","locales","includes","TypeError","searchParams","host","value","port","protocol","href","hash","origin","password","username","startsWith","toString","toJSON","for","clone"],"mappings":";;;;+BAkCaA;;;eAAAA;;;oCA9BsB;wCACI;6BACX;qCACQ;AAcpC,MAAMC,2BACJ;AAEF,SAASC,SAASC,GAAiB,EAAEC,IAAmB;IACtD,MAAMC,SAAS,IAAIC,IAAIC,OAAOJ,MAAMC,QAAQG,OAAOH;IACnD,IAAIH,yBAAyBO,IAAI,CAACH,OAAOI,QAAQ,GAAG;QAClDJ,OAAOI,QAAQ,GAAG;IACpB;IACA,OAAOJ;AACT;AAEA,MAAMK,WAAWC,OAAO;AAEjB,MAAMX;IAeXY,YACEC,KAAmB,EACnBC,UAAmC,EACnCC,IAAc,CACd;QACA,IAAIX;QACJ,IAAIY;QAEJ,IACE,AAAC,OAAOF,eAAe,YAAY,cAAcA,cACjD,OAAOA,eAAe,UACtB;YACAV,OAAOU;YACPE,UAAUD,QAAQ,CAAC;QACrB,OAAO;YACLC,UAAUD,QAAQD,cAAc,CAAC;QACnC;QAEA,IAAI,CAACJ,SAAS,GAAG;YACfP,KAAKD,SAASW,OAAOT,QAAQY,QAAQZ,IAAI;YACzCY,SAASA;YACTC,UAAU;QACZ;QAEA,IAAI,CAACC,OAAO;IACd;IAEQA,UAAU;YAcV,wCAAA,mCAKJ,6BACA,yCAAA;QAnBF,MAAMC,OAAOC,IAAAA,wCAAmB,EAAC,IAAI,CAACV,SAAS,CAACP,GAAG,CAACkB,QAAQ,E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G;QAC5C,OAAO;YACLR,MAAM,IAAI,CAACA,IAAI;YACfE,QAAQ,IAAI,CAACA,MAAM;YACnBH,UAAU,IAAI,CAACA,QAAQ;YACvBK,UAAU,IAAI,CAACA,QAAQ;YACvBD,UAAU,IAAI,CAACA,QAAQ;YACvBP,MAAM,IAAI,CAACA,IAAI;YACfvC,UAAU,IAAI,CAACA,QAAQ;YACvByC,MAAM,IAAI,CAACA,IAAI;YACf7B,UAAU,IAAI,CAACA,QAAQ;YACvBsB,QAAQ,IAAI,CAACA,MAAM;YACnBI,cAAc,IAAI,CAACA,YAAY;YAC/BM,MAAM,IAAI,CAACA,IAAI;QACjB;IACF;IAEAQ,QAAQ;QACN,OAAO,IAAI7D,QAAQO,OAAO,IAAI,GAAG,IAAI,CAACG,SAAS,CAACM,OAAO;IACzD;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/context.d.ts b/e-commerce/node_modules/next/dist/server/web/sandbox/context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c5c2748c05d8d23bb9666de7341555bd9c98149 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/context.d.ts @@ -0,0 +1,41 @@ +import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'; +import { AsyncLocalStorage } from 'async_hooks'; +import { EdgeRuntime } from 'next/dist/compiled/edge-runtime'; +/** + * Same as clearModuleContext but for all module contexts. + */ +export declare function clearAllModuleContexts(): Promise; +/** + * For a given path a context, this function checks if there is any module + * context that contains the path with an older content and, if that's the + * case, removes the context from the cache. + * + * This function also clears all intervals and timeouts created by the + * module context. + */ +export declare function clearModuleContext(path: string): Promise; +export declare const requestStore: AsyncLocalStorage<{ + headers: Headers; +}>; +export declare const edgeSandboxNextRequestContext: import("../../after/builtin-request-context").RunnableBuiltinRequestContext; +interface ModuleContextOptions { + moduleName: string; + onError: (err: unknown) => void; + onWarning: (warn: Error) => void; + useCache: boolean; + distDir: string; + edgeFunctionEntry: Pick; +} +/** + * For a given module name this function will get a cached module + * context or create it. It will return the module context along + * with a function that allows to run some code from a given + * filepath within the context. + */ +export declare function getModuleContext(options: ModuleContextOptions): Promise<{ + evaluateInContext: (filepath: string) => void; + runtime: EdgeRuntime; + paths: Map; + warnedEvals: Set; +}>; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/context.js b/e-commerce/node_modules/next/dist/server/web/sandbox/context.js new file mode 100644 index 0000000000000000000000000000000000000000..e0995e68ef22cea0cabff3dbffcd653c92bbd455 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/context.js @@ -0,0 +1,444 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + clearAllModuleContexts: null, + clearModuleContext: null, + edgeSandboxNextRequestContext: null, + getModuleContext: null, + requestStore: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + clearAllModuleContexts: function() { + return clearAllModuleContexts; + }, + clearModuleContext: function() { + return clearModuleContext; + }, + edgeSandboxNextRequestContext: function() { + return edgeSandboxNextRequestContext; + }, + getModuleContext: function() { + return getModuleContext; + }, + requestStore: function() { + return requestStore; + } +}); +const _async_hooks = require("async_hooks"); +const _constants = require("../../../shared/lib/constants"); +const _edgeruntime = require("next/dist/compiled/edge-runtime"); +const _fs = require("fs"); +const _utils = require("../utils"); +const _pick = require("../../../lib/pick"); +const _fetchinlineassets = require("./fetch-inline-assets"); +const _vm = require("vm"); +const _nodebuffer = /*#__PURE__*/ _interop_require_default(require("node:buffer")); +const _nodeevents = /*#__PURE__*/ _interop_require_default(require("node:events")); +const _nodeassert = /*#__PURE__*/ _interop_require_default(require("node:assert")); +const _nodeutil = /*#__PURE__*/ _interop_require_default(require("node:util")); +const _nodeasync_hooks = /*#__PURE__*/ _interop_require_default(require("node:async_hooks")); +const _resourcemanagers = require("./resource-managers"); +const _builtinrequestcontext = require("../../after/builtin-request-context"); +const _patcherrorinspect = require("../../patch-error-inspect"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +let getServerError; +let decorateServerError; +if (process.env.NODE_ENV === 'development') { + getServerError = require('../../dev/node-stack-frames').getServerError; + decorateServerError = require('../../../shared/lib/error-source').decorateServerError; +} else { + getServerError = (error)=>error; + decorateServerError = ()=>{}; +} +/** + * A Map of cached module contexts indexed by the module name. It allows + * to have a different cache scoped per module name or depending on the + * provided module key on creation. + */ const moduleContexts = new Map(); +const pendingModuleCaches = new Map(); +async function clearAllModuleContexts() { + _resourcemanagers.intervalsManager.removeAll(); + _resourcemanagers.timeoutsManager.removeAll(); + moduleContexts.clear(); + pendingModuleCaches.clear(); +} +async function clearModuleContext(path) { + _resourcemanagers.intervalsManager.removeAll(); + _resourcemanagers.timeoutsManager.removeAll(); + const handleContext = (key, cache, context)=>{ + if (cache == null ? void 0 : cache.paths.has(path)) { + context.delete(key); + } + }; + for (const [key, cache] of moduleContexts){ + handleContext(key, cache, moduleContexts); + } + for (const [key, cache] of pendingModuleCaches){ + handleContext(key, await cache, pendingModuleCaches); + } +} +async function loadWasm(wasm) { + const modules = {}; + await Promise.all(wasm.map(async (binding)=>{ + const module1 = await WebAssembly.compile(// @ts-expect-error - Argument of type 'Buffer' is not assignable to parameter of type 'BufferSource'. + await _fs.promises.readFile(binding.filePath)); + modules[binding.name] = module1; + })); + return modules; +} +function buildEnvironmentVariablesFrom(injectedEnvironments) { + let env = Object.fromEntries([ + ...Object.entries(process.env), + ...Object.entries(injectedEnvironments), + [ + 'NEXT_RUNTIME', + 'edge' + ] + ]); + return env; +} +function throwUnsupportedAPIError(name) { + const error = new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime. +Learn more: https://nextjs.org/docs/api-reference/edge-runtime`); + decorateServerError(error, _constants.COMPILER_NAMES.edgeServer); + throw error; +} +function createProcessPolyfill(env) { + const processPolyfill = { + env: buildEnvironmentVariablesFrom(env) + }; + const overriddenValue = {}; + for (const key of Object.keys(process)){ + if (key === 'env') continue; + Object.defineProperty(processPolyfill, key, { + get () { + if (overriddenValue[key] !== undefined) { + return overriddenValue[key]; + } + if (typeof process[key] === 'function') { + return ()=>throwUnsupportedAPIError(`process.${key}`); + } + return undefined; + }, + set (value) { + overriddenValue[key] = value; + }, + enumerable: false + }); + } + return processPolyfill; +} +function addStub(context, name) { + Object.defineProperty(context, name, { + get () { + return function() { + throwUnsupportedAPIError(name); + }; + }, + enumerable: false + }); +} +function getDecorateUnhandledError(runtime) { + const EdgeRuntimeError = runtime.evaluate(`Error`); + return (error)=>{ + if (error instanceof EdgeRuntimeError) { + decorateServerError(error, _constants.COMPILER_NAMES.edgeServer); + } + }; +} +function getDecorateUnhandledRejection(runtime) { + const EdgeRuntimeError = runtime.evaluate(`Error`); + return (rejected)=>{ + if (rejected.reason instanceof EdgeRuntimeError) { + decorateServerError(rejected.reason, _constants.COMPILER_NAMES.edgeServer); + } + }; +} +const NativeModuleMap = (()=>{ + const mods = { + 'node:buffer': (0, _pick.pick)(_nodebuffer.default, [ + 'constants', + 'kMaxLength', + 'kStringMaxLength', + 'Buffer', + 'SlowBuffer' + ]), + 'node:events': (0, _pick.pick)(_nodeevents.default, [ + 'EventEmitter', + 'captureRejectionSymbol', + 'defaultMaxListeners', + 'errorMonitor', + 'listenerCount', + 'on', + 'once' + ]), + 'node:async_hooks': (0, _pick.pick)(_nodeasync_hooks.default, [ + 'AsyncLocalStorage', + 'AsyncResource' + ]), + 'node:assert': (0, _pick.pick)(_nodeassert.default, [ + 'AssertionError', + 'deepEqual', + 'deepStrictEqual', + 'doesNotMatch', + 'doesNotReject', + 'doesNotThrow', + 'equal', + 'fail', + 'ifError', + 'match', + 'notDeepEqual', + 'notDeepStrictEqual', + 'notEqual', + 'notStrictEqual', + 'ok', + 'rejects', + 'strict', + 'strictEqual', + 'throws' + ]), + 'node:util': (0, _pick.pick)(_nodeutil.default, [ + '_extend', + 'callbackify', + 'format', + 'inherits', + 'promisify', + 'types' + ]) + }; + return new Map(Object.entries(mods)); +})(); +const requestStore = new _async_hooks.AsyncLocalStorage(); +const edgeSandboxNextRequestContext = (0, _builtinrequestcontext.createLocalRequestContext)(); +/** + * Create a module cache specific for the provided parameters. It includes + * a runtime context, require cache and paths cache. + */ async function createModuleContext(options) { + const warnedEvals = new Set(); + const warnedWasmCodegens = new Set(); + const { edgeFunctionEntry } = options; + const wasm = await loadWasm(edgeFunctionEntry.wasm ?? []); + const runtime = new _edgeruntime.EdgeRuntime({ + codeGeneration: process.env.NODE_ENV !== 'production' ? { + strings: true, + wasm: true + } : undefined, + extend: (context)=>{ + context.process = createProcessPolyfill(edgeFunctionEntry.env); + Object.defineProperty(context, 'require', { + enumerable: false, + value: (id)=>{ + const value = NativeModuleMap.get(id); + if (!value) { + throw TypeError('Native module not found: ' + id); + } + return value; + } + }); + if (process.env.NODE_ENV !== 'production') { + context.__next_log_error__ = function(err) { + options.onError(err); + }; + } + context.__next_eval__ = function __next_eval__(fn) { + const key = fn.toString(); + if (!warnedEvals.has(key)) { + const warning = getServerError(new Error(`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime +Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), _constants.COMPILER_NAMES.edgeServer); + warning.name = 'DynamicCodeEvaluationWarning'; + Error.captureStackTrace(warning, __next_eval__); + warnedEvals.add(key); + options.onWarning(warning); + } + return fn(); + }; + context.__next_webassembly_compile__ = function __next_webassembly_compile__(fn) { + const key = fn.toString(); + if (!warnedWasmCodegens.has(key)) { + const warning = getServerError(new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime. +Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), _constants.COMPILER_NAMES.edgeServer); + warning.name = 'DynamicWasmCodeGenerationWarning'; + Error.captureStackTrace(warning, __next_webassembly_compile__); + warnedWasmCodegens.add(key); + options.onWarning(warning); + } + return fn(); + }; + context.__next_webassembly_instantiate__ = async function __next_webassembly_instantiate__(fn) { + const result = await fn(); + // If a buffer is given, WebAssembly.instantiate returns an object + // containing both a module and an instance while it returns only an + // instance if a WASM module is given. Utilize the fact to determine + // if the WASM code generation happens. + // + // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code + const instantiatedFromBuffer = result.hasOwnProperty('module'); + const key = fn.toString(); + if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) { + const warning = getServerError(new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime. +Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), _constants.COMPILER_NAMES.edgeServer); + warning.name = 'DynamicWasmCodeGenerationWarning'; + Error.captureStackTrace(warning, __next_webassembly_instantiate__); + warnedWasmCodegens.add(key); + options.onWarning(warning); + } + return result; + }; + const __fetch = context.fetch; + context.fetch = async (input, init = {})=>{ + const callingError = new Error('[internal]'); + const assetResponse = await (0, _fetchinlineassets.fetchInlineAsset)({ + input, + assets: options.edgeFunctionEntry.assets, + distDir: options.distDir, + context + }); + if (assetResponse) { + return assetResponse; + } + init.headers = new Headers(init.headers ?? {}); + if (!init.headers.has('user-agent')) { + init.headers.set(`user-agent`, `Next.js Middleware`); + } + const response = typeof input === 'object' && 'url' in input ? __fetch(input.url, { + ...(0, _pick.pick)(input, [ + 'method', + 'body', + 'cache', + 'credentials', + 'integrity', + 'keepalive', + 'mode', + 'redirect', + 'referrer', + 'referrerPolicy', + 'signal' + ]), + ...init, + headers: { + ...Object.fromEntries(input.headers), + ...Object.fromEntries(init.headers) + } + }) : __fetch(String(input), init); + return await response.catch((err)=>{ + callingError.message = err.message; + err.stack = callingError.stack; + throw err; + }); + }; + const __Request = context.Request; + context.Request = class extends __Request { + constructor(input, init){ + const url = typeof input !== 'string' && 'url' in input ? input.url : String(input); + if (typeof input === 'string') { + (0, _utils.validateURL)(url); + super(input, init); + } else { + super(input, init); + (0, _utils.validateURL)(url); + } + this.next = init == null ? void 0 : init.next; + } + }; + const __redirect = context.Response.redirect.bind(context.Response); + context.Response.redirect = (...args)=>{ + (0, _utils.validateURL)(args[0]); + return __redirect(...args); + }; + for (const name of _constants.EDGE_UNSUPPORTED_NODE_APIS){ + addStub(context, name); + } + Object.assign(context, wasm); + context.performance = performance; + context.AsyncLocalStorage = _async_hooks.AsyncLocalStorage; + // @ts-ignore the timeouts have weird types in the edge runtime + context.setInterval = (...args)=>_resourcemanagers.intervalsManager.add([ + context, + ...args + ]); + // @ts-ignore the timeouts have weird types in the edge runtime + context.clearInterval = (interval)=>_resourcemanagers.intervalsManager.remove(interval); + // @ts-ignore the timeouts have weird types in the edge runtime + context.setTimeout = (...args)=>_resourcemanagers.timeoutsManager.add([ + context, + ...args + ]); + // @ts-ignore the timeouts have weird types in the edge runtime + context.clearTimeout = (timeout)=>_resourcemanagers.timeoutsManager.remove(timeout); + // Duplicated from packages/next/src/server/after/builtin-request-context.ts + // because we need to use the sandboxed `Symbol.for`, not the one from the outside + const NEXT_REQUEST_CONTEXT_SYMBOL = context.Symbol.for('@next/request-context'); + Object.defineProperty(context, NEXT_REQUEST_CONTEXT_SYMBOL, { + enumerable: false, + value: edgeSandboxNextRequestContext + }); + return context; + } + }); + const decorateUnhandledError = getDecorateUnhandledError(runtime); + runtime.context.addEventListener('error', decorateUnhandledError); + const decorateUnhandledRejection = getDecorateUnhandledRejection(runtime); + runtime.context.addEventListener('unhandledrejection', decorateUnhandledRejection); + (0, _patcherrorinspect.patchErrorInspectEdgeLite)(runtime.context.Error); + // An Error from within the Edge Runtime could also bubble up into the Node.js process. + // For example, uncaught errors are handled in the Node.js runtime. + (0, _patcherrorinspect.patchErrorInspectNodeJS)(runtime.context.Error); + return { + runtime, + paths: new Map(), + warnedEvals: new Set() + }; +} +function getModuleContextShared(options) { + let deferredModuleContext = pendingModuleCaches.get(options.moduleName); + if (!deferredModuleContext) { + deferredModuleContext = createModuleContext(options); + pendingModuleCaches.set(options.moduleName, deferredModuleContext); + } + return deferredModuleContext; +} +async function getModuleContext(options) { + let lazyModuleContext; + if (options.useCache) { + lazyModuleContext = moduleContexts.get(options.moduleName) || await getModuleContextShared(options); + } + if (!lazyModuleContext) { + lazyModuleContext = await createModuleContext(options); + moduleContexts.set(options.moduleName, lazyModuleContext); + } + const moduleContext = lazyModuleContext; + const evaluateInContext = (filepath)=>{ + if (!moduleContext.paths.has(filepath)) { + const content = (0, _fs.readFileSync)(filepath, 'utf-8'); + try { + (0, _vm.runInContext)(content, moduleContext.runtime.context, { + filename: filepath + }); + moduleContext.paths.set(filepath, content); + } catch (error) { + if (options.useCache) { + moduleContext == null ? void 0 : moduleContext.paths.delete(filepath); + } + throw error; + } + } + }; + return { + ...moduleContext, + evaluateInContext + }; +} + +//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/context.js.map b/e-commerce/node_modules/next/dist/server/web/sandbox/context.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e2f4540f14680fca8b2926b1e10a559345f9335a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/context.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/sandbox/context.ts"],"sourcesContent":["import type { AssetBinding } from '../../../build/webpack/loaders/get-module-build-info'\nimport type {\n EdgeFunctionDefinition,\n SUPPORTED_NATIVE_MODULES,\n} from '../../../build/webpack/plugins/middleware-plugin'\nimport type { UnwrapPromise } from '../../../lib/coalesced-function'\nimport { AsyncLocalStorage } from 'async_hooks'\nimport {\n COMPILER_NAMES,\n EDGE_UNSUPPORTED_NODE_APIS,\n} from '../../../shared/lib/constants'\nimport { EdgeRuntime } from 'next/dist/compiled/edge-runtime'\nimport { readFileSync, promises as fs } from 'fs'\nimport { validateURL } from '../utils'\nimport { pick } from '../../../lib/pick'\nimport { fetchInlineAsset } from './fetch-inline-assets'\nimport { runInContext } from 'vm'\nimport BufferImplementation from 'node:buffer'\nimport EventsImplementation from 'node:events'\nimport AssertImplementation from 'node:assert'\nimport UtilImplementation from 'node:util'\nimport AsyncHooksImplementation from 'node:async_hooks'\nimport { intervalsManager, timeoutsManager } from './resource-managers'\nimport { createLocalRequestContext } from '../../after/builtin-request-context'\nimport {\n patchErrorInspectEdgeLite,\n patchErrorInspectNodeJS,\n} from '../../patch-error-inspect'\n\ninterface ModuleContext {\n runtime: EdgeRuntime\n paths: Map\n warnedEvals: Set\n}\n\nlet getServerError: typeof import('../../dev/node-stack-frames').getServerError\nlet decorateServerError: typeof import('../../../shared/lib/error-source').decorateServerError\n\nif (process.env.NODE_ENV === 'development') {\n getServerError = (\n require('../../dev/node-stack-frames') as typeof import('../../dev/node-stack-frames') as typeof import('../../dev/node-stack-frames')\n ).getServerError\n decorateServerError = (\n require('../../../shared/lib/error-source') as typeof import('../../../shared/lib/error-source')\n ).decorateServerError\n} else {\n getServerError = (error) => error\n decorateServerError = () => {}\n}\n\n/**\n * A Map of cached module contexts indexed by the module name. It allows\n * to have a different cache scoped per module name or depending on the\n * provided module key on creation.\n */\nconst moduleContexts = new Map()\n\nconst pendingModuleCaches = new Map>()\n\n/**\n * Same as clearModuleContext but for all module contexts.\n */\nexport async function clearAllModuleContexts() {\n intervalsManager.removeAll()\n timeoutsManager.removeAll()\n moduleContexts.clear()\n pendingModuleCaches.clear()\n}\n\n/**\n * For a given path a context, this function checks if there is any module\n * context that contains the path with an older content and, if that's the\n * case, removes the context from the cache.\n *\n * This function also clears all intervals and timeouts created by the\n * module context.\n */\nexport async function clearModuleContext(path: string) {\n intervalsManager.removeAll()\n timeoutsManager.removeAll()\n\n const handleContext = (\n key: string,\n cache: ReturnType<(typeof moduleContexts)['get']>,\n context: typeof moduleContexts | typeof pendingModuleCaches\n ) => {\n if (cache?.paths.has(path)) {\n context.delete(key)\n }\n }\n\n for (const [key, cache] of moduleContexts) {\n handleContext(key, cache, moduleContexts)\n }\n for (const [key, cache] of pendingModuleCaches) {\n handleContext(key, await cache, pendingModuleCaches)\n }\n}\n\nasync function loadWasm(\n wasm: AssetBinding[]\n): Promise> {\n const modules: Record = {}\n\n await Promise.all(\n wasm.map(async (binding) => {\n const module = await WebAssembly.compile(\n // @ts-expect-error - Argument of type 'Buffer' is not assignable to parameter of type 'BufferSource'.\n await fs.readFile(binding.filePath)\n )\n modules[binding.name] = module\n })\n )\n\n return modules\n}\n\nfunction buildEnvironmentVariablesFrom(\n injectedEnvironments: Record\n): Record {\n let env = Object.fromEntries([\n ...Object.entries(process.env),\n ...Object.entries(injectedEnvironments),\n ['NEXT_RUNTIME', 'edge'],\n ])\n return env\n}\n\nfunction throwUnsupportedAPIError(name: string) {\n const error =\n new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime.\nLearn more: https://nextjs.org/docs/api-reference/edge-runtime`)\n decorateServerError(error, COMPILER_NAMES.edgeServer)\n throw error\n}\n\nfunction createProcessPolyfill(env: Record) {\n const processPolyfill = { env: buildEnvironmentVariablesFrom(env) }\n const overriddenValue: Record = {}\n\n for (const key of Object.keys(process)) {\n if (key === 'env') continue\n Object.defineProperty(processPolyfill, key, {\n get() {\n if (overriddenValue[key] !== undefined) {\n return overriddenValue[key]\n }\n if (typeof (process as any)[key] === 'function') {\n return () => throwUnsupportedAPIError(`process.${key}`)\n }\n return undefined\n },\n set(value) {\n overriddenValue[key] = value\n },\n enumerable: false,\n })\n }\n return processPolyfill\n}\n\nfunction addStub(context: EdgeRuntime['context'], name: string) {\n Object.defineProperty(context, name, {\n get() {\n return function () {\n throwUnsupportedAPIError(name)\n }\n },\n enumerable: false,\n })\n}\n\nfunction getDecorateUnhandledError(runtime: EdgeRuntime) {\n const EdgeRuntimeError = runtime.evaluate(`Error`)\n return (error: any) => {\n if (error instanceof EdgeRuntimeError) {\n decorateServerError(error, COMPILER_NAMES.edgeServer)\n }\n }\n}\n\nfunction getDecorateUnhandledRejection(runtime: EdgeRuntime) {\n const EdgeRuntimeError = runtime.evaluate(`Error`)\n return (rejected: { reason: typeof EdgeRuntimeError }) => {\n if (rejected.reason instanceof EdgeRuntimeError) {\n decorateServerError(rejected.reason, COMPILER_NAMES.edgeServer)\n }\n }\n}\n\nconst NativeModuleMap = (() => {\n const mods: Record<\n `node:${(typeof SUPPORTED_NATIVE_MODULES)[number]}`,\n unknown\n > = {\n 'node:buffer': pick(BufferImplementation, [\n 'constants',\n 'kMaxLength',\n 'kStringMaxLength',\n 'Buffer',\n 'SlowBuffer',\n ]),\n 'node:events': pick(EventsImplementation, [\n 'EventEmitter',\n 'captureRejectionSymbol',\n 'defaultMaxListeners',\n 'errorMonitor',\n 'listenerCount',\n 'on',\n 'once',\n ]),\n 'node:async_hooks': pick(AsyncHooksImplementation, [\n 'AsyncLocalStorage',\n 'AsyncResource',\n ]),\n 'node:assert': pick(AssertImplementation, [\n 'AssertionError',\n 'deepEqual',\n 'deepStrictEqual',\n 'doesNotMatch',\n 'doesNotReject',\n 'doesNotThrow',\n 'equal',\n 'fail',\n 'ifError',\n 'match',\n 'notDeepEqual',\n 'notDeepStrictEqual',\n 'notEqual',\n 'notStrictEqual',\n 'ok',\n 'rejects',\n 'strict',\n 'strictEqual',\n 'throws',\n ]),\n 'node:util': pick(UtilImplementation, [\n '_extend' as any,\n 'callbackify',\n 'format',\n 'inherits',\n 'promisify',\n 'types',\n ]),\n }\n return new Map(Object.entries(mods))\n})()\n\nexport const requestStore = new AsyncLocalStorage<{\n headers: Headers\n}>()\n\nexport const edgeSandboxNextRequestContext = createLocalRequestContext()\n\n/**\n * Create a module cache specific for the provided parameters. It includes\n * a runtime context, require cache and paths cache.\n */\nasync function createModuleContext(options: ModuleContextOptions) {\n const warnedEvals = new Set()\n const warnedWasmCodegens = new Set()\n const { edgeFunctionEntry } = options\n const wasm = await loadWasm(edgeFunctionEntry.wasm ?? [])\n const runtime = new EdgeRuntime({\n codeGeneration:\n process.env.NODE_ENV !== 'production'\n ? { strings: true, wasm: true }\n : undefined,\n extend: (context) => {\n context.process = createProcessPolyfill(edgeFunctionEntry.env)\n\n Object.defineProperty(context, 'require', {\n enumerable: false,\n value: (id: string) => {\n const value = NativeModuleMap.get(id)\n if (!value) {\n throw TypeError('Native module not found: ' + id)\n }\n return value\n },\n })\n\n if (process.env.NODE_ENV !== 'production') {\n context.__next_log_error__ = function (err: unknown) {\n options.onError(err)\n }\n }\n\n context.__next_eval__ = function __next_eval__(fn: Function) {\n const key = fn.toString()\n if (!warnedEvals.has(key)) {\n const warning = getServerError(\n new Error(\n `Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime\nLearn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`\n ),\n COMPILER_NAMES.edgeServer\n )\n warning.name = 'DynamicCodeEvaluationWarning'\n Error.captureStackTrace(warning, __next_eval__)\n warnedEvals.add(key)\n options.onWarning(warning)\n }\n return fn()\n }\n\n context.__next_webassembly_compile__ =\n function __next_webassembly_compile__(fn: Function) {\n const key = fn.toString()\n if (!warnedWasmCodegens.has(key)) {\n const warning = getServerError(\n new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.\nLearn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`),\n COMPILER_NAMES.edgeServer\n )\n warning.name = 'DynamicWasmCodeGenerationWarning'\n Error.captureStackTrace(warning, __next_webassembly_compile__)\n warnedWasmCodegens.add(key)\n options.onWarning(warning)\n }\n return fn()\n }\n\n context.__next_webassembly_instantiate__ =\n async function __next_webassembly_instantiate__(fn: Function) {\n const result = await fn()\n\n // If a buffer is given, WebAssembly.instantiate returns an object\n // containing both a module and an instance while it returns only an\n // instance if a WASM module is given. Utilize the fact to determine\n // if the WASM code generation happens.\n //\n // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code\n const instantiatedFromBuffer = result.hasOwnProperty('module')\n\n const key = fn.toString()\n if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) {\n const warning = getServerError(\n new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.\nLearn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`),\n COMPILER_NAMES.edgeServer\n )\n warning.name = 'DynamicWasmCodeGenerationWarning'\n Error.captureStackTrace(warning, __next_webassembly_instantiate__)\n warnedWasmCodegens.add(key)\n options.onWarning(warning)\n }\n return result\n }\n\n const __fetch = context.fetch\n context.fetch = async (input, init = {}) => {\n const callingError = new Error('[internal]')\n const assetResponse = await fetchInlineAsset({\n input,\n assets: options.edgeFunctionEntry.assets,\n distDir: options.distDir,\n context,\n })\n if (assetResponse) {\n return assetResponse\n }\n\n init.headers = new Headers(init.headers ?? {})\n\n if (!init.headers.has('user-agent')) {\n init.headers.set(`user-agent`, `Next.js Middleware`)\n }\n\n const response =\n typeof input === 'object' && 'url' in input\n ? __fetch(input.url, {\n ...pick(input, [\n 'method',\n 'body',\n 'cache',\n 'credentials',\n 'integrity',\n 'keepalive',\n 'mode',\n 'redirect',\n 'referrer',\n 'referrerPolicy',\n 'signal',\n ]),\n ...init,\n headers: {\n ...Object.fromEntries(input.headers),\n ...Object.fromEntries(init.headers),\n },\n })\n : __fetch(String(input), init)\n\n return await response.catch((err) => {\n callingError.message = err.message\n err.stack = callingError.stack\n throw err\n })\n }\n\n const __Request = context.Request\n context.Request = class extends __Request {\n next?: NextFetchRequestConfig | undefined\n constructor(input: URL | RequestInfo, init?: RequestInit | undefined) {\n const url =\n typeof input !== 'string' && 'url' in input\n ? input.url\n : String(input)\n\n if (typeof input === 'string') {\n validateURL(url)\n super(input, init)\n } else {\n super(input, init)\n validateURL(url)\n }\n this.next = init?.next\n }\n }\n\n const __redirect = context.Response.redirect.bind(context.Response)\n context.Response.redirect = (...args) => {\n validateURL(args[0])\n return __redirect(...args)\n }\n\n for (const name of EDGE_UNSUPPORTED_NODE_APIS) {\n addStub(context, name)\n }\n\n Object.assign(context, wasm)\n\n context.performance = performance\n\n context.AsyncLocalStorage = AsyncLocalStorage\n\n // @ts-ignore the timeouts have weird types in the edge runtime\n context.setInterval = (...args: Parameters) =>\n intervalsManager.add([context, ...args])\n\n // @ts-ignore the timeouts have weird types in the edge runtime\n context.clearInterval = (interval: number) =>\n intervalsManager.remove(interval)\n\n // @ts-ignore the timeouts have weird types in the edge runtime\n context.setTimeout = (...args: Parameters) =>\n timeoutsManager.add([context, ...args])\n\n // @ts-ignore the timeouts have weird types in the edge runtime\n context.clearTimeout = (timeout: number) =>\n timeoutsManager.remove(timeout)\n\n // Duplicated from packages/next/src/server/after/builtin-request-context.ts\n // because we need to use the sandboxed `Symbol.for`, not the one from the outside\n const NEXT_REQUEST_CONTEXT_SYMBOL = context.Symbol.for(\n '@next/request-context'\n )\n Object.defineProperty(context, NEXT_REQUEST_CONTEXT_SYMBOL, {\n enumerable: false,\n value: edgeSandboxNextRequestContext,\n })\n\n return context\n },\n })\n\n const decorateUnhandledError = getDecorateUnhandledError(runtime)\n runtime.context.addEventListener('error', decorateUnhandledError)\n const decorateUnhandledRejection = getDecorateUnhandledRejection(runtime)\n runtime.context.addEventListener(\n 'unhandledrejection',\n decorateUnhandledRejection\n )\n\n patchErrorInspectEdgeLite(runtime.context.Error)\n // An Error from within the Edge Runtime could also bubble up into the Node.js process.\n // For example, uncaught errors are handled in the Node.js runtime.\n patchErrorInspectNodeJS(runtime.context.Error)\n\n return {\n runtime,\n paths: new Map(),\n warnedEvals: new Set(),\n }\n}\n\ninterface ModuleContextOptions {\n moduleName: string\n onError: (err: unknown) => void\n onWarning: (warn: Error) => void\n useCache: boolean\n distDir: string\n edgeFunctionEntry: Pick\n}\n\nfunction getModuleContextShared(options: ModuleContextOptions) {\n let deferredModuleContext = pendingModuleCaches.get(options.moduleName)\n if (!deferredModuleContext) {\n deferredModuleContext = createModuleContext(options)\n pendingModuleCaches.set(options.moduleName, deferredModuleContext)\n }\n return deferredModuleContext\n}\n\n/**\n * For a given module name this function will get a cached module\n * context or create it. It will return the module context along\n * with a function that allows to run some code from a given\n * filepath within the context.\n */\nexport async function getModuleContext(options: ModuleContextOptions): Promise<{\n evaluateInContext: (filepath: string) => void\n runtime: EdgeRuntime\n paths: Map\n warnedEvals: Set\n}> {\n let lazyModuleContext:\n | UnwrapPromise>\n | undefined\n\n if (options.useCache) {\n lazyModuleContext =\n moduleContexts.get(options.moduleName) ||\n (await getModuleContextShared(options))\n }\n\n if (!lazyModuleContext) {\n lazyModuleContext = await createModuleContext(options)\n moduleContexts.set(options.moduleName, lazyModuleContext)\n }\n\n const moduleContext = lazyModuleContext\n\n const evaluateInContext = (filepath: string) => {\n if (!moduleContext.paths.has(filepath)) {\n const content = readFileSync(filepath, 'utf-8')\n try {\n runInContext(content, moduleContext.runtime.context, {\n filename: filepath,\n })\n moduleContext.paths.set(filepath, content)\n } catch (error) {\n if (options.useCache) {\n moduleContext?.paths.delete(filepath)\n }\n throw error\n }\n }\n }\n\n return { ...moduleContext, evaluateInContext }\n}\n"],"names":["clearAllModuleContexts","clearModuleContext","edgeSandboxNextRequestContext","getModuleContext","requestStore","getServerError","decorateServerError","process","env","NODE_ENV","require","error","moduleContexts","Map","pendingModuleCaches","intervalsManager","removeAll","timeoutsManager","clear","path","handleContext","key","cache","context","paths","has","delete","loadWasm","wasm","modules","Promise","all","map","binding","module","WebAssembly","compile","fs","readFile","filePath","name","buildEnvironmentVariablesFrom","injectedEnvironments","Object","fromEntries","entries","throwUnsupportedAPIError","Error","COMPILER_NAMES","edgeServer","createProcessPolyfill","processPolyfill","overriddenValue","keys","defineProperty","get","undefined","set","value","enumerable","addStub","getDecorateUnhandledError","runtime","EdgeRuntimeError","evaluate","getDecorateUnhandledRejection","rejected","reason","NativeModuleMap","mods","pick","BufferImplementation","EventsImplementation","AsyncHooksImplementation","AssertImplementation","UtilImplementation","AsyncLocalStorage","createLocalRequestContext","createModuleContext","options","warnedEvals","Set","warnedWasmCodegens","edgeFunctionEntry","EdgeRuntime","codeGeneration","strings","extend","id","TypeError","__next_log_error__","err","onError","__next_eval__","fn","toString","warning","captureStackTrace","add","onWarning","__next_webassembly_compile__","__next_webassembly_instantiate__","result","instantiatedFromBuffer","hasOwnProperty","__fetch","fetch","input","init","callingError","assetResponse","fetchInlineAsset","assets","distDir","headers","Headers","response","url","String","catch","message","stack","__Request","Request","constructor","validateURL","next","__redirect","Response","redirect","bind","args","EDGE_UNSUPPORTED_NODE_APIS","assign","performance","setInterval","clearInterval","interval","remove","setTimeout","clearTimeout","timeout","NEXT_REQUEST_CONTEXT_SYMBOL","Symbol","for","decorateUnhandledError","addEventListener","decorateUnhandledRejection","patchErrorInspectEdgeLite","patchErrorInspectNodeJS","getModuleContextShared","deferredModuleContext","moduleName","lazyModuleContext","useCache","moduleContext","evaluateInContext","filepath","content","readFileSync","runInContext","filename"],"mappings":";;;;;;;;;;;;;;;;;;IA8DsBA,sBAAsB;eAAtBA;;IAeAC,kBAAkB;eAAlBA;;IA+KTC,6BAA6B;eAA7BA;;IAkQSC,gBAAgB;eAAhBA;;IAtQTC,YAAY;eAAZA;;;6BAlPqB;2BAI3B;6BACqB;oBACiB;uBACjB;sBACP;mCACY;oBACJ;mEACI;mEACA;mEACA;iEACF;wEACM;kCACa;uCACR;mCAInC;;;;;;AAQP,IAAIC;AACJ,IAAIC;AAEJ,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;IAC1CJ,iBAAiB,AACfK,QAAQ,+BACRL,cAAc;IAChBC,sBAAsB,AACpBI,QAAQ,oCACRJ,mBAAmB;AACvB,OAAO;IACLD,iBAAiB,CAACM,QAAUA;IAC5BL,sBAAsB,KAAO;AAC/B;AAEA;;;;CAIC,GACD,MAAMM,iBAAiB,IAAIC;AAE3B,MAAMC,sBAAsB,IAAID;AAKzB,eAAeb;IACpBe,kCAAgB,CAACC,SAAS;IAC1BC,iCAAe,CAACD,SAAS;IACzBJ,eAAeM,KAAK;IACpBJ,oBAAoBI,KAAK;AAC3B;AAUO,eAAejB,mBAAmBkB,IAAY;IACnDJ,kCA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c7F,OAAO,CAACvC,OAAO,EAAE;oBACnD0I,UAAUJ;gBACZ;gBACAF,cAAcnI,KAAK,CAACiC,GAAG,CAACoG,UAAUC;YACpC,EAAE,OAAOnJ,OAAO;gBACd,IAAIoE,QAAQ2E,QAAQ,EAAE;oBACpBC,iCAAAA,cAAenI,KAAK,CAACE,MAAM,CAACmI;gBAC9B;gBACA,MAAMlJ;YACR;QACF;IACF;IAEA,OAAO;QAAE,GAAGgJ,aAAa;QAAEC;IAAkB;AAC/C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/fetch-inline-assets.d.ts b/e-commerce/node_modules/next/dist/server/web/sandbox/fetch-inline-assets.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fd7488ca56555c5f07b584efdc4a8c014005f60 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/fetch-inline-assets.d.ts @@ -0,0 +1,15 @@ +import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'; +/** + * Short-circuits the `fetch` function + * to return a stream for a given asset, if a user used `new URL("file", import.meta.url)`. + * This allows to embed assets in Edge Runtime. + */ +export declare function fetchInlineAsset(options: { + input: RequestInfo | URL; + distDir: string; + assets: EdgeFunctionDefinition['assets']; + context: { + Response: typeof Response; + ReadableStream: typeof ReadableStream; + }; +}): Promise; diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/fetch-inline-assets.js b/e-commerce/node_modules/next/dist/server/web/sandbox/fetch-inline-assets.js new file mode 100644 index 0000000000000000000000000000000000000000..1bcacd01d47f4f8c22adfec57e6b7312d08be2dd --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/fetch-inline-assets.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "fetchInlineAsset", { + enumerable: true, + get: function() { + return fetchInlineAsset; + } +}); +const _fs = require("fs"); +const _bodystreams = require("../../body-streams"); +const _path = require("path"); +async function fetchInlineAsset(options) { + const inputString = String(options.input); + if (!inputString.startsWith('blob:')) { + return; + } + const name = inputString.replace('blob:', ''); + const asset = options.assets ? options.assets.find((x)=>x.name === name) : { + name, + filePath: name + }; + if (!asset) { + return; + } + const filePath = (0, _path.resolve)(options.distDir, asset.filePath); + const fileIsReadable = await _fs.promises.access(filePath).then(()=>true, ()=>false); + if (fileIsReadable) { + const readStream = (0, _fs.createReadStream)(filePath); + return new options.context.Response((0, _bodystreams.requestToBodyStream)(options.context, Uint8Array, readStream)); + } +} + +//# sourceMappingURL=fetch-inline-assets.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/fetch-inline-assets.js.map b/e-commerce/node_modules/next/dist/server/web/sandbox/fetch-inline-assets.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ef7fdf83a1021b6e4955281e364c95a8ea7f1767 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/fetch-inline-assets.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/sandbox/fetch-inline-assets.ts"],"sourcesContent":["import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'\nimport { createReadStream, promises as fs } from 'fs'\nimport { requestToBodyStream } from '../../body-streams'\nimport { resolve } from 'path'\n\n/**\n * Short-circuits the `fetch` function\n * to return a stream for a given asset, if a user used `new URL(\"file\", import.meta.url)`.\n * This allows to embed assets in Edge Runtime.\n */\nexport async function fetchInlineAsset(options: {\n input: RequestInfo | URL\n distDir: string\n assets: EdgeFunctionDefinition['assets']\n context: { Response: typeof Response; ReadableStream: typeof ReadableStream }\n}): Promise {\n const inputString = String(options.input)\n if (!inputString.startsWith('blob:')) {\n return\n }\n\n const name = inputString.replace('blob:', '')\n const asset = options.assets\n ? options.assets.find((x) => x.name === name)\n : {\n name,\n filePath: name,\n }\n if (!asset) {\n return\n }\n\n const filePath = resolve(options.distDir, asset.filePath)\n const fileIsReadable = await fs.access(filePath).then(\n () => true,\n () => false\n )\n\n if (fileIsReadable) {\n const readStream = createReadStream(filePath)\n return new options.context.Response(\n requestToBodyStream(options.context, Uint8Array, readStream)\n )\n }\n}\n"],"names":["fetchInlineAsset","options","inputString","String","input","startsWith","name","replace","asset","assets","find","x","filePath","resolve","distDir","fileIsReadable","fs","access","then","readStream","createReadStream","context","Response","requestToBodyStream","Uint8Array"],"mappings":";;;;+BAUsBA;;;eAAAA;;;oBAT2B;6BACb;sBACZ;AAOjB,eAAeA,iBAAiBC,OAKtC;IACC,MAAMC,cAAcC,OAAOF,QAAQG,KAAK;IACxC,IAAI,CAACF,YAAYG,UAAU,CAAC,UAAU;QACpC;IACF;IAEA,MAAMC,OAAOJ,YAAYK,OAAO,CAAC,SAAS;IAC1C,MAAMC,QAAQP,QAAQQ,MAAM,GACxBR,QAAQQ,MAAM,CAACC,IAAI,CAAC,CAACC,IAAMA,EAAEL,IAAI,KAAKA,QACtC;QACEA;QACAM,UAAUN;IACZ;IACJ,IAAI,CAACE,OAAO;QACV;IACF;IAEA,MAAMI,WAAWC,IAAAA,aAAO,EAACZ,QAAQa,OAAO,EAAEN,MAAMI,QAAQ;IACxD,MAAMG,iBAAiB,MAAMC,YAAE,CAACC,MAAM,CAACL,UAAUM,IAAI,CACnD,IAAM,MACN,IAAM;IAGR,IAAIH,gBAAgB;QAClB,MAAMI,aAAaC,IAAAA,oBAAgB,EAACR;QACpC,OAAO,IAAIX,QAAQoB,OAAO,CAACC,QAAQ,CACjCC,IAAAA,gCAAmB,EAACtB,QAAQoB,OAAO,EAAEG,YAAYL;IAErD;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/index.d.ts b/e-commerce/node_modules/next/dist/server/web/sandbox/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d46a6da6b073751f45c208fbe19d1fefa6115598 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/index.d.ts @@ -0,0 +1,2 @@ +export * from './sandbox'; +export { clearModuleContext } from './context'; diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/index.js b/e-commerce/node_modules/next/dist/server/web/sandbox/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7d8aaca87270aeda976b7dbaeffb83897ae46dfe --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/index.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "clearModuleContext", { + enumerable: true, + get: function() { + return _context.clearModuleContext; + } +}); +0 && __export(require("./sandbox")); +_export_star(require("./sandbox"), exports); +const _context = require("./context"); +function _export_star(from, to) { + Object.keys(from).forEach(function(k) { + if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { + Object.defineProperty(to, k, { + enumerable: true, + get: function() { + return from[k]; + } + }); + } + }); + return from; +} + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/index.js.map b/e-commerce/node_modules/next/dist/server/web/sandbox/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f07b237aba812a4344788b51dcbc0069e5eaf90d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/sandbox/index.ts"],"sourcesContent":["export * from './sandbox'\nexport { clearModuleContext } from './context'\n"],"names":["clearModuleContext"],"mappings":";;;;+BACSA;;;eAAAA,2BAAkB;;;;qBADb;yBACqB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/resource-managers.d.ts b/e-commerce/node_modules/next/dist/server/web/sandbox/resource-managers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4fb94359ba278e5ebdc5c94abc9b2fa70d63dae6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/resource-managers.d.ts @@ -0,0 +1,30 @@ +declare abstract class ResourceManager { + private resources; + abstract create(resourceArgs: Args): T; + abstract destroy(resource: T): void; + add(resourceArgs: Args): T; + 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; +} +export declare class IntervalsManager extends ResourceManager> { + create(args: Parameters): number; + destroy(interval: number): void; +} +export declare class TimeoutsManager extends ResourceManager> { + create(args: Parameters): number; + destroy(timeout: number): void; +} +export type GlobalObject = import('edge-runtime').EdgeRuntime['context']; +declare function webSetIntervalPolyfill(globalObject: GlobalObject, callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): number; +declare function webSetTimeoutPolyfill(globalObject: GlobalObject, callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): number; +export declare const intervalsManager: IntervalsManager; +export declare const timeoutsManager: TimeoutsManager; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/resource-managers.js b/e-commerce/node_modules/next/dist/server/web/sandbox/resource-managers.js new file mode 100644 index 0000000000000000000000000000000000000000..04fcd2fce1b9f8e7124ff009df5977807c524aad --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/resource-managers.js @@ -0,0 +1,123 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + IntervalsManager: null, + TimeoutsManager: null, + intervalsManager: null, + timeoutsManager: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + IntervalsManager: function() { + return IntervalsManager; + }, + TimeoutsManager: function() { + return TimeoutsManager; + }, + intervalsManager: function() { + return intervalsManager; + }, + timeoutsManager: function() { + return timeoutsManager; + } +}); +class ResourceManager { + add(resourceArgs) { + const resource = this.create(resourceArgs); + this.resources.add(resource); + return resource; + } + remove(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() { + 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 = new Set(); + } +} +class IntervalsManager extends ResourceManager { + create(args) { + // TODO: use the edge runtime provided `setInterval` instead + return webSetIntervalPolyfill(...args); + } + destroy(interval) { + clearInterval(interval); + } +} +class TimeoutsManager extends ResourceManager { + create(args) { + // TODO: use the edge runtime provided `setTimeout` instead + 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; + } + destroy(timeout) { + clearTimeout(timeout); + } +} +function webSetIntervalPolyfill(globalObject, callback, ms, ...args) { + return setInterval(()=>{ + // node's `setInterval` sets `this` to the `Timeout` instance it returned, + // but web `setInterval` always sets `this` to `window` + // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval#the_this_problem + return callback.apply(globalObject, args); + }, ms)[Symbol.toPrimitive](); +} +function webSetTimeoutPolyfill(globalObject, callback, ms, ...args) { + const wrappedCallback = ()=>{ + try { + // node's `setTimeout` sets `this` to the `Timeout` instance it returned, + // but web `setTimeout` always sets `this` to `window` + // see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#the_this_problem + return callback.apply(globalObject, args); + } finally{ + // On certain older node versions (<20.16.0, <22.4.0), + // a `setTimeout` whose Timeout was converted to a primitive will leak. + // See: https://github.com/nodejs/node/issues/53335 + // We can work around this by explicitly calling `clearTimeout` after the callback runs. + clearTimeout(timeout); + } + }; + const timeout = setTimeout(wrappedCallback, ms); + return timeout[Symbol.toPrimitive](); +} +const intervalsManager = new IntervalsManager(); +const timeoutsManager = new TimeoutsManager(); + +//# sourceMappingURL=resource-managers.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/resource-managers.js.map b/e-commerce/node_modules/next/dist/server/web/sandbox/resource-managers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8307ea4b376f873132d7f8ccdc907fd7f7156eba --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/resource-managers.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/sandbox/resource-managers.ts"],"sourcesContent":["abstract class ResourceManager {\n private resources = new Set()\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\n> {\n create(args: Parameters) {\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\n> {\n create(args: Parameters) {\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(\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(\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,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;AAEO,MAAMjB,yBAAyBI;IAIpCI,OAAOU,IAA+C,EAAE;QACtD,4DAA4D;QAC5D,OAAOC,0BAA0BD;IACnC;IAEAN,QAAQQ,QAAgB,EAAE;QACxBC,cAAcD;IAChB;AACF;AAEO,MAAMnB,wBAAwBG;IAInCI,OAAOU,IAA8C,EAAE;QACrD,2DAA2D;QAC3D,MAAM,CAACI,cAAcC,UAAUC,IAAI,GAAGC,KAAK,GAAGP;QAE9C,yEAAyE;QACzE,qEAAqE;QACrE,qEAAqE;QACrE,iEAAiE;QACjE,sDAAsD;QACtD,IAAIQ;QACJ,MAAMC,sBAAsB,CAAC,GAAGC;YAC9B,IAAI;gBACF,OAAOL,SAASM,KAAK,CAACP,cAAcM;YACtC,SAAU;gBACR,IAAI,CAACjB,OAAO,CAACe;YACf;QACF;QAEAA,YAAYI,sBACVR,cACAK,qBACAH,OACGC;QAEL,OAAOC;IACT;IAEAd,QAAQmB,OAAe,EAAE;QACvBC,aAAaD;IACf;AACF;AAIA,SAASZ,uBACPG,YAA0B,EAC1BC,QAAkC,EAClCC,EAAW,EACX,GAAGN,IAAW;IAEd,OAAOe,YAAY;QACjB,0EAA0E;QAC1E,uDAAuD;QACvD,4FAA4F;QAC5F,OAAOV,SAASM,KAAK,CAACP,cAAcJ;IACtC,GAAGM,GAAG,CAACU,OAAOC,WAAW,CAAC;AAC5B;AAEA,SAASL,sBACPR,YAA0B,EAC1BC,QAAkC,EAClCC,EAAW,EACX,GAAGN,IAAW;IAEd,MAAMkB,kBAAkB;QACtB,IAAI;YACF,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]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/sandbox.d.ts b/e-commerce/node_modules/next/dist/server/web/sandbox/sandbox.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0326a7b7ff3a3dffe85f732d61a62ae3273bfb65 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/sandbox.d.ts @@ -0,0 +1,22 @@ +import type { NodejsRequestData, FetchEventResult } from '../types'; +import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'; +import type { EdgeRuntime } from 'next/dist/compiled/edge-runtime'; +import type { ServerComponentsHmrCache } from '../../response-cache'; +export declare const ErrorSource: unique symbol; +interface RunnerFnParams { + name: string; + onError?: (err: unknown) => void; + onWarning?: (warn: Error) => void; + paths: string[]; + request: NodejsRequestData; + useCache: boolean; + edgeFunctionEntry: Pick; + distDir: string; + incrementalCache?: any; + serverComponentsHmrCache?: ServerComponentsHmrCache; + clientAssetToken: string; +} +type RunnerFn = (params: RunnerFnParams) => Promise; +export declare function getRuntimeContext(params: Omit): Promise>; +export declare const run: RunnerFn; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/sandbox.js b/e-commerce/node_modules/next/dist/server/web/sandbox/sandbox.js new file mode 100644 index 0000000000000000000000000000000000000000..6b81d451b3f3eacce1acd7964da19f3368574caa --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/sandbox.js @@ -0,0 +1,133 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + ErrorSource: null, + getRuntimeContext: null, + run: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + ErrorSource: function() { + return ErrorSource; + }, + getRuntimeContext: function() { + return getRuntimeContext; + }, + run: function() { + return run; + } +}); +const _context = require("./context"); +const _bodystreams = require("../../body-streams"); +const _builtinrequestcontext = require("../../after/builtin-request-context"); +const _routerservercontext = require("../../lib/router-utils/router-server-context"); +const ErrorSource = Symbol('SandboxError'); +const FORBIDDEN_HEADERS = [ + 'content-length', + 'content-encoding', + 'transfer-encoding' +]; +/** + * Decorates the runner function making sure all errors it can produce are + * tagged with `edge-server` so they can properly be rendered in dev. + */ function withTaggedErrors(fn) { + if (process.env.NODE_ENV === 'development') { + const { getServerError } = require('../../dev/node-stack-frames'); + return (params)=>fn(params).then((result)=>{ + var _result_waitUntil; + return { + ...result, + waitUntil: result == null ? void 0 : (_result_waitUntil = result.waitUntil) == null ? void 0 : _result_waitUntil.catch((error)=>{ + // TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size. + throw getServerError(error, 'edge-server'); + }) + }; + }).catch((error)=>{ + // TODO: used COMPILER_NAMES.edgeServer instead + throw getServerError(error, 'edge-server'); + }); + } + return fn; +} +async function getRuntimeContext(params) { + const { runtime, evaluateInContext } = await (0, _context.getModuleContext)({ + moduleName: params.name, + onWarning: params.onWarning ?? (()=>{}), + onError: params.onError ?? (()=>{}), + useCache: params.useCache !== false, + edgeFunctionEntry: params.edgeFunctionEntry, + distDir: params.distDir + }); + if (params.incrementalCache) { + runtime.context.globalThis.__incrementalCacheShared = true; + runtime.context.globalThis.__incrementalCache = params.incrementalCache; + } + // expose router server context for access to dev handlers like + // logErrorWithOriginalStack + ; + runtime.context.globalThis[_routerservercontext.RouterServerContextSymbol] = _routerservercontext.routerServerGlobal[_routerservercontext.RouterServerContextSymbol]; + if (params.serverComponentsHmrCache) { + runtime.context.globalThis.__serverComponentsHmrCache = params.serverComponentsHmrCache; + } + if (params.clientAssetToken) { + runtime.context.globalThis.NEXT_CLIENT_ASSET_SUFFIX = params.clientAssetToken ? `?dpl=${params.clientAssetToken}` : ''; + } + for (const paramPath of params.paths){ + evaluateInContext(paramPath); + } + return runtime; +} +const run = withTaggedErrors(async function runWithTaggedErrors(params) { + var _params_request_body; + const runtime = await getRuntimeContext(params); + const edgeFunction = (await runtime.context._ENTRIES[`middleware_${params.name}`]).default; + const cloned = ![ + 'HEAD', + 'GET' + ].includes(params.request.method) ? (_params_request_body = params.request.body) == null ? void 0 : _params_request_body.cloneBodyStream() : undefined; + const KUint8Array = runtime.evaluate('Uint8Array'); + const urlInstance = new URL(params.request.url); + params.request.url = urlInstance.toString(); + const headers = new Headers(); + for (const [key, value] of Object.entries(params.request.headers)){ + headers.set(key, (value == null ? void 0 : value.toString()) ?? ''); + } + try { + let result = undefined; + const builtinRequestCtx = { + ...(0, _builtinrequestcontext.getBuiltinRequestContext)(), + // FIXME(after): + // arguably, this is an abuse of "@next/request-context" -- + // it'd make more sense to simply forward its existing value into the sandbox (in `createModuleContext`) + // but here we're using it to just pass in `waitUntil` regardless if we were running in this context or not. + waitUntil: params.request.waitUntil + }; + await _context.edgeSandboxNextRequestContext.run(builtinRequestCtx, ()=>_context.requestStore.run({ + headers + }, async ()=>{ + result = await edgeFunction({ + request: { + ...params.request, + body: cloned && (0, _bodystreams.requestToBodyStream)(runtime.context, KUint8Array, cloned) + } + }); + for (const headerName of FORBIDDEN_HEADERS){ + result.response.headers.delete(headerName); + } + })); + if (!result) throw new Error('Edge function did not return a response'); + return result; + } finally{ + var _params_request_body1; + await ((_params_request_body1 = params.request.body) == null ? void 0 : _params_request_body1.finalize()); + } +}); + +//# sourceMappingURL=sandbox.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/sandbox/sandbox.js.map b/e-commerce/node_modules/next/dist/server/web/sandbox/sandbox.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b6264433f38e92f0c5bd217682e8b6913ef9a711 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/sandbox/sandbox.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/sandbox/sandbox.ts"],"sourcesContent":["import type { NodejsRequestData, FetchEventResult } from '../types'\nimport type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'\nimport type { EdgeRuntime } from 'next/dist/compiled/edge-runtime'\nimport {\n getModuleContext,\n requestStore,\n edgeSandboxNextRequestContext,\n} from './context'\nimport { requestToBodyStream } from '../../body-streams'\nimport type { ServerComponentsHmrCache } from '../../response-cache'\nimport {\n getBuiltinRequestContext,\n type BuiltinRequestContextValue,\n} from '../../after/builtin-request-context'\nimport {\n RouterServerContextSymbol,\n routerServerGlobal,\n} from '../../lib/router-utils/router-server-context'\nimport type { EdgeHandler } from '../adapter'\n\nexport const ErrorSource = Symbol('SandboxError')\n\nconst FORBIDDEN_HEADERS = [\n 'content-length',\n 'content-encoding',\n 'transfer-encoding',\n]\n\ninterface RunnerFnParams {\n name: string\n onError?: (err: unknown) => void\n onWarning?: (warn: Error) => void\n paths: string[]\n request: NodejsRequestData\n useCache: boolean\n edgeFunctionEntry: Pick\n distDir: string\n incrementalCache?: any\n serverComponentsHmrCache?: ServerComponentsHmrCache\n clientAssetToken: string\n}\n\ntype RunnerFn = (params: RunnerFnParams) => Promise\n\n/**\n * Decorates the runner function making sure all errors it can produce are\n * tagged with `edge-server` so they can properly be rendered in dev.\n */\nfunction withTaggedErrors(fn: RunnerFn): RunnerFn {\n if (process.env.NODE_ENV === 'development') {\n const { getServerError } =\n require('../../dev/node-stack-frames') as typeof import('../../dev/node-stack-frames')\n\n return (params) =>\n fn(params)\n .then((result) => ({\n ...result,\n waitUntil: result?.waitUntil?.catch((error) => {\n // TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size.\n throw getServerError(error, 'edge-server')\n }),\n }))\n .catch((error) => {\n // TODO: used COMPILER_NAMES.edgeServer instead\n throw getServerError(error, 'edge-server')\n })\n }\n\n return fn\n}\n\nexport async function getRuntimeContext(\n params: Omit\n): Promise> {\n const { runtime, evaluateInContext } = await getModuleContext({\n moduleName: params.name,\n onWarning: params.onWarning ?? (() => {}),\n onError: params.onError ?? (() => {}),\n useCache: params.useCache !== false,\n edgeFunctionEntry: params.edgeFunctionEntry,\n distDir: params.distDir,\n })\n\n if (params.incrementalCache) {\n runtime.context.globalThis.__incrementalCacheShared = true\n runtime.context.globalThis.__incrementalCache = params.incrementalCache\n }\n\n // expose router server context for access to dev handlers like\n // logErrorWithOriginalStack\n ;(runtime.context.globalThis as any as typeof routerServerGlobal)[\n RouterServerContextSymbol\n ] = routerServerGlobal[RouterServerContextSymbol]\n\n if (params.serverComponentsHmrCache) {\n runtime.context.globalThis.__serverComponentsHmrCache =\n params.serverComponentsHmrCache\n }\n\n if (params.clientAssetToken) {\n runtime.context.globalThis.NEXT_CLIENT_ASSET_SUFFIX =\n params.clientAssetToken ? `?dpl=${params.clientAssetToken}` : ''\n }\n\n for (const paramPath of params.paths) {\n evaluateInContext(paramPath)\n }\n return runtime\n}\n\nexport const run = withTaggedErrors(async function runWithTaggedErrors(params) {\n const runtime = await getRuntimeContext(params)\n\n const edgeFunction: EdgeHandler = (\n await runtime.context._ENTRIES[`middleware_${params.name}`]\n ).default\n\n const cloned = !['HEAD', 'GET'].includes(params.request.method)\n ? params.request.body?.cloneBodyStream()\n : undefined\n\n const KUint8Array = runtime.evaluate('Uint8Array')\n const urlInstance = new URL(params.request.url)\n\n params.request.url = urlInstance.toString()\n\n const headers = new Headers()\n for (const [key, value] of Object.entries(params.request.headers)) {\n headers.set(key, value?.toString() ?? '')\n }\n\n try {\n let result: FetchEventResult | undefined = undefined\n const builtinRequestCtx: BuiltinRequestContextValue = {\n ...getBuiltinRequestContext(),\n // FIXME(after):\n // arguably, this is an abuse of \"@next/request-context\" --\n // it'd make more sense to simply forward its existing value into the sandbox (in `createModuleContext`)\n // but here we're using it to just pass in `waitUntil` regardless if we were running in this context or not.\n waitUntil: params.request.waitUntil,\n }\n await edgeSandboxNextRequestContext.run(builtinRequestCtx, () =>\n requestStore.run({ headers }, async () => {\n result = await edgeFunction({\n request: {\n ...params.request,\n body:\n cloned &&\n requestToBodyStream(runtime.context, KUint8Array, cloned),\n },\n })\n for (const headerName of FORBIDDEN_HEADERS) {\n result.response.headers.delete(headerName)\n }\n })\n )\n\n if (!result) throw new Error('Edge function did not return a response')\n return result\n } finally {\n await params.request.body?.finalize()\n }\n})\n"],"names":["ErrorSource","getRuntimeContext","run","Symbol","FORBIDDEN_HEADERS","withTaggedErrors","fn","process","env","NODE_ENV","getServerError","require","params","then","result","waitUntil","catch","error","runtime","evaluateInContext","getModuleContext","moduleName","name","onWarning","onError","useCache","edgeFunctionEntry","distDir","incrementalCache","context","globalThis","__incrementalCacheShared","__incrementalCache","RouterServerContextSymbol","routerServerGlobal","serverComponentsHmrCache","__serverComponentsHmrCache","clientAssetToken","NEXT_CLIENT_ASSET_SUFFIX","paramPath","paths","runWithTaggedErrors","edgeFunction","_ENTRIES","default","cloned","includes","request","method","body","cloneBodyStream","undefined","KUint8Array","evaluate","urlInstance","URL","url","toString","headers","Headers","key","value","Object","entries","set","builtinRequestCtx","getBuiltinRequestContext","edgeSandboxNextRequestContext","requestStore","requestToBodyStream","headerName","response","delete","Error","finalize"],"mappings":";;;;;;;;;;;;;;;;IAoBaA,WAAW;eAAXA;;IAmDSC,iBAAiB;eAAjBA;;IAuCTC,GAAG;eAAHA;;;yBAvGN;6BAC6B;uCAK7B;qCAIA;AAGA,MAAMF,cAAcG,OAAO;AAElC,MAAMC,oBAAoB;IACxB;IACA;IACA;CACD;AAkBD;;;CAGC,GACD,SAASC,iBAAiBC,EAAY;IACpC,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QAC1C,MAAM,EAAEC,cAAc,EAAE,GACtBC,QAAQ;QAEV,OAAO,CAACC,SACNN,GAAGM,QACAC,IAAI,CAAC,CAACC;oBAEMA;uBAFM;oBACjB,GAAGA,MAAM;oBACTC,SAAS,EAAED,2BAAAA,oBAAAA,OAAQC,SAAS,qBAAjBD,kBAAmBE,KAAK,CAAC,CAACC;wBACnC,mGAAmG;wBACnG,MAAMP,eAAeO,OAAO;oBAC9B;gBACF;eACCD,KAAK,CAAC,CAACC;gBACN,+CAA+C;gBAC/C,MAAMP,eAAeO,OAAO;YAC9B;IACN;IAEA,OAAOX;AACT;AAEO,eAAeL,kBACpBW,MAAuC;IAEvC,MAAM,EAAEM,OAAO,EAAEC,iBAAiB,EAAE,GAAG,MAAMC,IAAAA,yBAAgB,EAAC;QAC5DC,YAAYT,OAAOU,IAAI;QACvBC,WAAWX,OAAOW,SAAS,IAAK,CAAA,KAAO,CAAA;QACvCC,SAASZ,OAAOY,OAAO,IAAK,CAAA,KAAO,CAAA;QACnCC,UAAUb,OAAOa,QAAQ,KAAK;QAC9BC,m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,OAAOmC,OAAO,CAACS,GAAG;IAE9C5C,OAAOmC,OAAO,CAACS,GAAG,GAAGF,YAAYG,QAAQ;IAEzC,MAAMC,UAAU,IAAIC;IACpB,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACnD,OAAOmC,OAAO,CAACW,OAAO,EAAG;QACjEA,QAAQM,GAAG,CAACJ,KAAKC,CAAAA,yBAAAA,MAAOJ,QAAQ,OAAM;IACxC;IAEA,IAAI;QACF,IAAI3C,SAAuCqC;QAC3C,MAAMc,oBAAgD;YACpD,GAAGC,IAAAA,+CAAwB,GAAE;YAC7B,gBAAgB;YAChB,2DAA2D;YAC3D,wGAAwG;YACxG,4GAA4G;YAC5GnD,WAAWH,OAAOmC,OAAO,CAAChC,SAAS;QACrC;QACA,MAAMoD,sCAA6B,CAACjE,GAAG,CAAC+D,mBAAmB,IACzDG,qBAAY,CAAClE,GAAG,CAAC;gBAAEwD;YAAQ,GAAG;gBAC5B5C,SAAS,MAAM4B,aAAa;oBAC1BK,SAAS;wBACP,GAAGnC,OAAOmC,OAAO;wBACjBE,MACEJ,UACAwB,IAAAA,gCAAmB,EAACnD,QAAQW,OAAO,EAAEuB,aAAaP;oBACtD;gBACF;gBACA,KAAK,MAAMyB,cAAclE,kBAAmB;oBAC1CU,OAAOyD,QAAQ,CAACb,OAAO,CAACc,MAAM,CAACF;gBACjC;YACF;QAGF,IAAI,CAACxD,QAAQ,MAAM,IAAI2D,MAAM;QAC7B,OAAO3D;IACT,SAAU;YACFF;QAAN,QAAMA,wBAAAA,OAAOmC,OAAO,CAACE,IAAI,qBAAnBrC,sBAAqB8D,QAAQ;IACrC;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/headers.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/headers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4fa8c96f0b8af361331f7b711fb86e6b4c1e041f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/headers.d.ts @@ -0,0 +1,56 @@ +import type { IncomingHttpHeaders } from 'http'; +export type ReadonlyHeaders = Headers & { + /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */ + append(...args: any[]): void; + /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */ + set(...args: any[]): void; + /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */ + delete(...args: any[]): void; +}; +export declare class HeadersAdapter extends Headers { + private readonly headers; + constructor(headers: IncomingHttpHeaders); + /** + * Seals a Headers instance to prevent modification by throwing an error when + * any mutating method is called. + * + * The sealed view stays live. Later writes to `headers` remain visible + * through it. + * + * `hidden` omits the given header names from every read operation (`get`, + * `has`, `getSetCookie`, `forEach`, and iteration). The names must be + * lowercase. The underlying headers are neither copied nor mutated, so hidden + * headers remain available to the framework. + */ + static seal(headers: Headers, hidden?: ReadonlySet): ReadonlyHeaders; + /** + * @param headers + * @returns A fresh object identity backed by the original value + */ + static fresh(headers: ReadonlyHeaders): ReadonlyHeaders; + /** + * Merges a header value into a string. This stores multiple values as an + * array, so we need to merge them into a string. + * + * @param value a header value + * @returns a merged header value (a string) + */ + private merge; + /** + * Creates a Headers instance from a plain object or a Headers instance. + * + * @param headers a plain object or a Headers instance + * @returns a headers instance + */ + static from(headers: IncomingHttpHeaders | Headers): Headers; + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; + forEach(callbackfn: (value: string, name: string, parent: Headers) => void, thisArg?: any): void; + entries(): HeadersIterator<[string, string]>; + keys(): HeadersIterator; + values(): HeadersIterator; + [Symbol.iterator](): HeadersIterator<[string, string]>; +} diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/headers.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/headers.js new file mode 100644 index 0000000000000000000000000000000000000000..e754dfbd42d6d7df3741a23f275fb6c84e08e842 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/headers.js @@ -0,0 +1,288 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + HeadersAdapter: null, + ReadonlyHeadersError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + HeadersAdapter: function() { + return HeadersAdapter; + }, + ReadonlyHeadersError: function() { + return ReadonlyHeadersError; + } +}); +const _reflect = require("./reflect"); +class ReadonlyHeadersError extends Error { + constructor(){ + super('Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers'); + } + static callable() { + throw new ReadonlyHeadersError(); + } +} +/** + * Builds the read methods for a sealed view that exposes all of `target`. + */ function createPassThroughMethods(target, sealed) { + return { + get: target.get.bind(target), + has: target.has.bind(target), + getSetCookie: target.getSetCookie.bind(target), + keys: target.keys.bind(target), + values: target.values.bind(target), + entries: target.entries.bind(target), + [Symbol.iterator]: target[Symbol.iterator].bind(target), + // The native method passes the unsealed target as the callback's `parent` + // argument. That is a mutable handle on the underlying headers. Pass the + // sealed view instead. + forEach (callbackfn, thisArg) { + for (const [name, value] of target.entries()){ + callbackfn.call(thisArg, value, name, sealed); + } + } + }; +} +/** + * Builds the read methods for a sealed view that omits the header names matched + * by `isHidden`. + */ function createHidingMethods(target, sealed, isHidden) { + function* entries() { + for (const entry of target.entries()){ + if (!isHidden(entry[0])) { + yield entry; + } + } + } + return { + entries, + [Symbol.iterator]: entries, + get: (name)=>isHidden(name) ? null : target.get(name), + has: (name)=>isHidden(name) ? false : target.has(name), + getSetCookie: ()=>isHidden('set-cookie') ? [] : target.getSetCookie(), + *keys () { + for (const name of target.keys()){ + if (!isHidden(name)) { + yield name; + } + } + }, + *values () { + for (const [, value] of entries()){ + yield value; + } + }, + // The native method passes the unsealed target as the callback's `parent` + // argument. That is a mutable handle on the underlying headers. Pass the + // sealed view instead. + forEach (callbackfn, thisArg) { + for (const [name, value] of entries()){ + callbackfn.call(thisArg, value, name, sealed); + } + } + }; +} +class HeadersAdapter extends Headers { + constructor(headers){ + // We've already overridden the methods that would be called, so we're just + // calling the super constructor to ensure that the instanceof check works. + super(); + this.headers = new Proxy(headers, { + get (target, prop, receiver) { + // Because this is just an object, we expect that all "get" operations + // are for properties. If it's a "get" for a symbol, we'll just return + // the symbol. + if (typeof prop === 'symbol') { + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + const lowercased = prop.toLowerCase(); + // Let's find the original casing of the key. This assumes that there is + // no mixed case keys (e.g. "Content-Type" and "content-type") in the + // headers object. + const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased); + // If the original casing doesn't exist, return undefined. + if (typeof original === 'undefined') return; + // If the original casing exists, return the value. + return _reflect.ReflectAdapter.get(target, original, receiver); + }, + set (target, prop, value, receiver) { + if (typeof prop === 'symbol') { + return _reflect.ReflectAdapter.set(target, prop, value, receiver); + } + const lowercased = prop.toLowerCase(); + // Let's find the original casing of the key. This assumes that there is + // no mixed case keys (e.g. "Content-Type" and "content-type") in the + // headers object. + const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased); + // If the original casing doesn't exist, use the prop as the key. + return _reflect.ReflectAdapter.set(target, original ?? prop, value, receiver); + }, + has (target, prop) { + if (typeof prop === 'symbol') return _reflect.ReflectAdapter.has(target, prop); + const lowercased = prop.toLowerCase(); + // Let's find the original casing of the key. This assumes that there is + // no mixed case keys (e.g. "Content-Type" and "content-type") in the + // headers object. + const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased); + // If the original casing doesn't exist, return false. + if (typeof original === 'undefined') return false; + // If the original casing exists, return true. + return _reflect.ReflectAdapter.has(target, original); + }, + deleteProperty (target, prop) { + if (typeof prop === 'symbol') return _reflect.ReflectAdapter.deleteProperty(target, prop); + const lowercased = prop.toLowerCase(); + // Let's find the original casing of the key. This assumes that there is + // no mixed case keys (e.g. "Content-Type" and "content-type") in the + // headers object. + const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased); + // If the original casing doesn't exist, return true. + if (typeof original === 'undefined') return true; + // If the original casing exists, delete the property. + return _reflect.ReflectAdapter.deleteProperty(target, original); + } + }); + } + /** + * Seals a Headers instance to prevent modification by throwing an error when + * any mutating method is called. + * + * The sealed view stays live. Later writes to `headers` remain visible + * through it. + * + * `hidden` omits the given header names from every read operation (`get`, + * `has`, `getSetCookie`, `forEach`, and iteration). The names must be + * lowercase. The underlying headers are neither copied nor mutated, so hidden + * headers remain available to the framework. + */ static seal(headers, hidden) { + const isHidden = hidden && hidden.size > 0 ? (name)=>hidden.has(name.toLowerCase()) : null; + // The methods are built once per sealed view and reused, so repeated access + // returns the same function instead of a fresh closure. They are assigned + // after the proxy exists because `forEach` hands the proxy to its callback. + // Creating the proxy runs no trap, so nothing can read them before then. + let methods; + const sealed = new Proxy(headers, { + get (target, prop, receiver) { + switch(prop){ + case 'append': + case 'delete': + case 'set': + return ReadonlyHeadersError.callable; + case Symbol.iterator: + return methods[Symbol.iterator]; + case 'get': + case 'has': + case 'getSetCookie': + case 'keys': + case 'values': + case 'entries': + case 'forEach': + return methods[prop]; + default: + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + } + }); + methods = isHidden ? createHidingMethods(headers, sealed, isHidden) : createPassThroughMethods(headers, sealed); + return sealed; + } + /** + * @param headers + * @returns A fresh object identity backed by the original value + */ static fresh(headers) { + return new Proxy(headers, { + get (target, prop, receiver) { + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + }); + } + /** + * Merges a header value into a string. This stores multiple values as an + * array, so we need to merge them into a string. + * + * @param value a header value + * @returns a merged header value (a string) + */ merge(value) { + if (Array.isArray(value)) return value.join(', '); + return value; + } + /** + * Creates a Headers instance from a plain object or a Headers instance. + * + * @param headers a plain object or a Headers instance + * @returns a headers instance + */ static from(headers) { + if (headers instanceof Headers) return headers; + return new HeadersAdapter(headers); + } + append(name, value) { + const existing = this.headers[name]; + if (typeof existing === 'string') { + this.headers[name] = [ + existing, + value + ]; + } else if (Array.isArray(existing)) { + existing.push(value); + } else { + this.headers[name] = value; + } + } + delete(name) { + delete this.headers[name]; + } + get(name) { + const value = this.headers[name]; + if (typeof value !== 'undefined') return this.merge(value); + return null; + } + has(name) { + return typeof this.headers[name] !== 'undefined'; + } + set(name, value) { + this.headers[name] = value; + } + forEach(callbackfn, thisArg) { + for (const [name, value] of this.entries()){ + callbackfn.call(thisArg, value, name, this); + } + } + *entries() { + for (const key of Object.keys(this.headers)){ + const name = key.toLowerCase(); + // We assert here that this is a string because we got it from the + // Object.keys() call above. + const value = this.get(name); + yield [ + name, + value + ]; + } + } + *keys() { + for (const key of Object.keys(this.headers)){ + const name = key.toLowerCase(); + yield name; + } + } + *values() { + for (const key of Object.keys(this.headers)){ + // We assert here that this is a string because we got it from the + // Object.keys() call above. + const value = this.get(key); + yield value; + } + } + [Symbol.iterator]() { + return this.entries(); + } +} + +//# sourceMappingURL=headers.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/headers.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/headers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..faa082d138c303975513a2594b6d6dcf8628c74d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/headers.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/web/spec-extension/adapters/headers.ts"],"sourcesContent":["import type { IncomingHttpHeaders } from 'http'\n\nimport { ReflectAdapter } from './reflect'\n\n/**\n * @internal\n */\nexport class ReadonlyHeadersError extends Error {\n constructor() {\n super(\n 'Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers'\n )\n }\n\n public static callable() {\n throw new ReadonlyHeadersError()\n }\n}\n\nexport type ReadonlyHeaders = Headers & {\n /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */\n append(...args: any[]): void\n /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */\n set(...args: any[]): void\n /** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/app/api-reference/functions/headers */\n delete(...args: any[]): void\n}\n\n/**\n * The read methods that a sealed view provides itself instead of forwarding to\n * the underlying `Headers`. Deriving the type from `Headers` keeps the\n * implementations in step with the platform signatures.\n */\ntype SealedHeaderMethods = Pick<\n Headers,\n | 'get'\n | 'has'\n | 'getSetCookie'\n | 'keys'\n | 'values'\n | 'entries'\n | 'forEach'\n | typeof Symbol.iterator\n>\n\n/**\n * Builds the read methods for a sealed view that exposes all of `target`.\n */\nfunction createPassThroughMethods(\n target: Headers,\n sealed: ReadonlyHeaders\n): SealedHeaderMethods {\n return {\n get: target.get.bind(target),\n has: target.has.bind(target),\n getSetCookie: target.getSetCookie.bind(target),\n keys: target.keys.bind(target),\n values: target.values.bind(target),\n entries: target.entries.bind(target),\n [Symbol.iterator]: target[Symbol.iterator].bind(target),\n // The native method passes the unsealed target as the callback's `parent`\n // argument. That is a mutable handle on the underlying headers. Pass the\n // sealed view instead.\n forEach(callbackfn, thisArg) {\n for (const [name, value] of target.entries()) {\n callbackfn.call(thisArg, value, name, sealed)\n }\n },\n }\n}\n\n/**\n * Builds the read methods for a sealed view that omits the header names matched\n * by `isHidden`.\n */\nfunction createHidingMethods(\n target: Headers,\n sealed: ReadonlyHeaders,\n isHidden: (name: string) => boolean\n): SealedHeaderMethods {\n function* entries(): HeadersIterator<[string, string]> {\n for (const entry of target.entries()) {\n if (!isHidden(entry[0])) {\n yield entry\n }\n }\n }\n\n return {\n entries,\n [Symbol.iterator]: entries,\n get: (name) => (isHidden(name) ? null : target.get(name)),\n has: (name) => (isHidden(name) ? false : target.has(name)),\n getSetCookie: () => (isHidden('set-cookie') ? [] : target.getSetCookie()),\n *keys(): HeadersIterator {\n for (const name of target.keys()) {\n if (!isHidden(name)) {\n yield name\n }\n }\n },\n *values(): HeadersIterator {\n for (const [, value] of entries()) {\n yield value\n }\n },\n // The native method passes the unsealed target as the callback's `parent`\n // argument. That is a mutable handle on the underlying headers. Pass the\n // sealed view instead.\n forEach(callbackfn, thisArg) {\n for (const [name, value] of entries()) {\n callbackfn.call(thisArg, value, name, sealed)\n }\n },\n }\n}\n\nexport class HeadersAdapter extends Headers {\n private readonly headers: IncomingHttpHeaders\n\n constructor(headers: IncomingHttpHeaders) {\n // We've already overridden the methods that would be called, so we're just\n // calling the super constructor to ensure that the instanceof check works.\n super()\n\n this.headers = new Proxy(headers, {\n get(target, prop, receiver) {\n // Because this is just an object, we expect that all \"get\" operations\n // are for properties. If it's a \"get\" for a symbol, we'll just return\n // the symbol.\n if (typeof prop === 'symbol') {\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n const lowercased = prop.toLowerCase()\n\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find(\n (o) => o.toLowerCase() === lowercased\n )\n\n // If the original casing doesn't exist, return undefined.\n if (typeof original === 'undefined') return\n\n // If the original casing exists, return the value.\n return ReflectAdapter.get(target, original, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'symbol') {\n return ReflectAdapter.set(target, prop, value, receiver)\n }\n\n const lowercased = prop.toLowerCase()\n\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find(\n (o) => o.toLowerCase() === lowercased\n )\n\n // If the original casing doesn't exist, use the prop as the key.\n return ReflectAdapter.set(target, original ?? prop, value, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'symbol') return ReflectAdapter.has(target, prop)\n\n const lowercased = prop.toLowerCase()\n\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find(\n (o) => o.toLowerCase() === lowercased\n )\n\n // If the original casing doesn't exist, return false.\n if (typeof original === 'undefined') return false\n\n // If the original casing exists, return true.\n return ReflectAdapter.has(target, original)\n },\n deleteProperty(target, prop) {\n if (typeof prop === 'symbol')\n return ReflectAdapter.deleteProperty(target, prop)\n\n const lowercased = prop.toLowerCase()\n\n // Let's find the original casing of the key. This assumes that there is\n // no mixed case keys (e.g. \"Content-Type\" and \"content-type\") in the\n // headers object.\n const original = Object.keys(headers).find(\n (o) => o.toLowerCase() === lowercased\n )\n\n // If the original casing doesn't exist, return true.\n if (typeof original === 'undefined') return true\n\n // If the original casing exists, delete the property.\n return ReflectAdapter.deleteProperty(target, original)\n },\n })\n }\n\n /**\n * Seals a Headers instance to prevent modification by throwing an error when\n * any mutating method is called.\n *\n * The sealed view stays live. Later writes to `headers` remain visible\n * through it.\n *\n * `hidden` omits the given header names from every read operation (`get`,\n * `has`, `getSetCookie`, `forEach`, and iteration). The names must be\n * lowercase. The underlying headers are neither copied nor mutated, so hidden\n * headers remain available to the framework.\n */\n public static seal(\n headers: Headers,\n hidden?: ReadonlySet\n ): ReadonlyHeaders {\n const isHidden =\n hidden && hidden.size > 0\n ? (name: string): boolean => hidden.has(name.toLowerCase())\n : null\n\n // The methods are built once per sealed view and reused, so repeated access\n // returns the same function instead of a fresh closure. They are assigned\n // after the proxy exists because `forEach` hands the proxy to its callback.\n // Creating the proxy runs no trap, so nothing can read them before then.\n let methods: SealedHeaderMethods\n\n const sealed: ReadonlyHeaders = new Proxy(headers, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'append':\n case 'delete':\n case 'set':\n return ReadonlyHeadersError.callable\n case Symbol.iterator:\n return methods[Symbol.iterator]\n case 'get':\n case 'has':\n case 'getSetCookie':\n case 'keys':\n case 'values':\n case 'entries':\n case 'forEach':\n return methods[prop]\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n })\n\n methods = isHidden\n ? createHidingMethods(headers, sealed, isHidden)\n : createPassThroughMethods(headers, sealed)\n\n return sealed\n }\n\n /**\n * @param headers\n * @returns A fresh object identity backed by the original value\n */\n public static fresh(headers: ReadonlyHeaders): ReadonlyHeaders {\n return new Proxy(headers, {\n get(target, prop, receiver) {\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n }\n\n /**\n * Merges a header value into a string. This stores multiple values as an\n * array, so we need to merge them into a string.\n *\n * @param value a header value\n * @returns a merged header value (a string)\n */\n private merge(value: string | string[]): string {\n if (Array.isArray(value)) return value.join(', ')\n\n return value\n }\n\n /**\n * Creates a Headers instance from a plain object or a Headers instance.\n *\n * @param headers a plain object or a Headers instance\n * @returns a headers instance\n */\n public static from(headers: IncomingHttpHeaders | Headers): Headers {\n if (headers instanceof Headers) return headers\n\n return new HeadersAdapter(headers)\n }\n\n public append(name: string, value: string): void {\n const existing = this.headers[name]\n if (typeof existing === 'string') {\n this.headers[name] = [existing, value]\n } else if (Array.isArray(existing)) {\n existing.push(value)\n } else {\n this.headers[name] = value\n }\n }\n\n public delete(name: string): void {\n delete this.headers[name]\n }\n\n public get(name: string): string | null {\n const value = this.headers[name]\n if (typeof value !== 'undefined') return this.merge(value)\n\n return null\n }\n\n public has(name: string): boolean {\n return typeof this.headers[name] !== 'undefined'\n }\n\n public set(name: string, value: string): void {\n this.headers[name] = value\n }\n\n public forEach(\n callbackfn: (value: string, name: string, parent: Headers) => void,\n thisArg?: any\n ): void {\n for (const [name, value] of this.entries()) {\n callbackfn.call(thisArg, value, name, this)\n }\n }\n\n public *entries(): HeadersIterator<[string, string]> {\n for (const key of Object.keys(this.headers)) {\n const name = key.toLowerCase()\n // We assert here that this is a string because we got it from the\n // Object.keys() call above.\n const value = this.get(name) as string\n\n yield [name, value] as [string, string]\n }\n }\n\n public *keys(): HeadersIterator {\n for (const key of Object.keys(this.headers)) {\n const name = key.toLowerCase()\n yield name\n }\n }\n\n public *values(): HeadersIterator {\n for (const key of Object.keys(this.headers)) {\n // We assert here that this is a string because we got it from the\n // Object.keys() call above.\n const value = this.get(key) as string\n\n yield value\n }\n }\n\n public [Symbol.iterator](): HeadersIterator<[string, string]> {\n return this.entries()\n }\n}\n"],"names":["HeadersAdapter","ReadonlyHeadersError","Error","constructor","callable","createPassThroughMethods","target","sealed","get","bind","has","getSetCookie","keys","values","entries","Symbol","iterator","forEach","callbackfn","thisArg","name","value","call","createHidingMethods","isHidden","entry","Headers","headers","Proxy","prop","receiver","ReflectAdapter","lowercased","toLowerCase","original","Object","find","o","set","deleteProperty","seal","hidden","size","methods","fresh","merge","Array","isArray","join","from","append","existing","push","delete","key"],"mappings":";;;;;;;;;;;;;;;IAqHaA,cAAc;eAAdA;;IA9GAC,oBAAoB;eAApBA;;;yBALkB;AAKxB,MAAMA,6BAA6BC;IACxCC,aAAc;QACZ,KAAK,CACH;IAEJ;IAEA,OAAcC,WAAW;QACvB,MAAM,IAAIH;IACZ;AACF;AA4BA;;CAEC,GACD,SAASI,yBACPC,MAAe,EACfC,MAAuB;IAEvB,OAAO;QACLC,KAAKF,OAAOE,GAAG,CAACC,IAAI,CAACH;QACrBI,KAAKJ,OAAOI,GAAG,CAACD,IAAI,CAACH;QACrBK,cAAcL,OAAOK,YAAY,CAACF,IAAI,CAACH;QACvCM,MAAMN,OAAOM,IAAI,CAACH,IAAI,CAACH;QACvBO,QAAQP,OAAOO,MAAM,CAACJ,IAAI,CAACH;QAC3BQ,SAASR,OAAOQ,OAAO,CAACL,IAAI,CAACH;QAC7B,CAACS,OAAOC,QAAQ,CAAC,EAAEV,MAAM,CAACS,OAAOC,QAAQ,CAAC,CAACP,IAAI,CAACH;QAChD,0EAA0E;QAC1E,yEAAyE;QACzE,uBAAuB;QACvBW,SAAQC,UAAU,EAAEC,OAAO;YACzB,KAAK,MAAM,CAACC,MAAMC,MAAM,IAAIf,OAAOQ,OAAO,GAAI;gBAC5CI,WAAWI,IAAI,CAACH,SAASE,OAAOD,MAAMb;YACxC;QACF;IACF;AACF;AAEA;;;CAGC,GACD,SAASgB,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WI,IAAI,CAACH,SAASE,OAAOD,MAAM,IAAI;QAC5C;IACF;IAEA,CAAQN,UAA6C;QACnD,KAAK,MAAMwC,OAAOnB,OAAOvB,IAAI,CAAC,IAAI,CAACe,OAAO,EAAG;YAC3C,MAAMP,OAAOkC,IAAIrB,WAAW;YAC5B,kEAAkE;YAClE,4BAA4B;YAC5B,MAAMZ,QAAQ,IAAI,CAACb,GAAG,CAACY;YAEvB,MAAM;gBAACA;gBAAMC;aAAM;QACrB;IACF;IAEA,CAAQT,OAAgC;QACtC,KAAK,MAAM0C,OAAOnB,OAAOvB,IAAI,CAAC,IAAI,CAACe,OAAO,EAAG;YAC3C,MAAMP,OAAOkC,IAAIrB,WAAW;YAC5B,MAAMb;QACR;IACF;IAEA,CAAQP,SAAkC;QACxC,KAAK,MAAMyC,OAAOnB,OAAOvB,IAAI,CAAC,IAAI,CAACe,OAAO,EAAG;YAC3C,kEAAkE;YAClE,4BAA4B;YAC5B,MAAMN,QAAQ,IAAI,CAACb,GAAG,CAAC8C;YAEvB,MAAMjC;QACR;IACF;IAEO,CAACN,OAAOC,QAAQ,CAAC,GAAsC;QAC5D,OAAO,IAAI,CAACF,OAAO;IACrB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/next-request.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/next-request.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d05f8072016a0f5e8e48caf14cbcf35bc9ef60f --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/next-request.d.ts @@ -0,0 +1,31 @@ +import type { BaseNextRequest } from '../../../base-http'; +import type { NodeNextRequest } from '../../../base-http/node'; +import type { WebNextRequest } from '../../../base-http/web'; +import type { Writable } from 'node:stream'; +import { NextRequest } from '../request'; +export declare const ResponseAbortedName = "ResponseAborted"; +export declare class ResponseAborted extends Error { + readonly name = "ResponseAborted"; +} +/** + * Creates an AbortController tied to the closing of a ServerResponse (or other + * appropriate Writable). + * + * If the `close` event is fired before the `finish` event, then we'll send the + * `abort` signal. + */ +export declare function createAbortController(response: Writable): AbortController; +/** + * Creates an AbortSignal tied to the closing of a ServerResponse (or other + * appropriate Writable). + * + * This cannot be done with the request (IncomingMessage or Readable) because + * the `abort` event will not fire if to data has been fully read (because that + * will "close" the readable stream and nothing fires after that). + */ +export declare function signalFromNodeResponse(response: Writable): AbortSignal; +export declare class NextRequestAdapter { + static fromBaseNextRequest(request: BaseNextRequest, signal: AbortSignal): NextRequest; + static fromNodeNextRequest(request: NodeNextRequest, signal: AbortSignal): NextRequest; + static fromWebNextRequest(request: WebNextRequest): NextRequest; +} diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js new file mode 100644 index 0000000000000000000000000000000000000000..91a783894ec07a3c748d03930817b4b5412a1e45 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js @@ -0,0 +1,138 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + NextRequestAdapter: null, + ResponseAborted: null, + ResponseAbortedName: null, + createAbortController: null, + signalFromNodeResponse: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + NextRequestAdapter: function() { + return NextRequestAdapter; + }, + ResponseAborted: function() { + return ResponseAborted; + }, + ResponseAbortedName: function() { + return ResponseAbortedName; + }, + createAbortController: function() { + return createAbortController; + }, + signalFromNodeResponse: function() { + return signalFromNodeResponse; + } +}); +const _requestmeta = require("../../../request-meta"); +const _utils = require("../../utils"); +const _request = require("../request"); +const _helpers = require("../../../base-http/helpers"); +const ResponseAbortedName = 'ResponseAborted'; +class ResponseAborted extends Error { + constructor(...args){ + super(...args), this.name = ResponseAbortedName; + } +} +function createAbortController(response) { + const controller = new AbortController(); + // If `finish` fires first, then `res.end()` has been called and the close is + // just us finishing the stream on our side. If `close` fires first, then we + // know the client disconnected before we finished. + response.once('close', ()=>{ + if (response.writableFinished) return; + controller.abort(new ResponseAborted()); + }); + return controller; +} +function signalFromNodeResponse(response) { + const { errored, destroyed } = response; + if (errored || destroyed) { + return AbortSignal.abort(errored ?? new ResponseAborted()); + } + const { signal } = createAbortController(response); + return signal; +} +class NextRequestAdapter { + static fromBaseNextRequest(request, signal) { + if (// The type check here ensures that `req` is correctly typed, and the + // environment variable check provides dead code elimination. + process.env.NEXT_RUNTIME === 'edge' && (0, _helpers.isWebNextRequest)(request)) { + return NextRequestAdapter.fromWebNextRequest(request); + } else if (// The type check here ensures that `req` is correctly typed, and the + // environment variable check provides dead code elimination. + process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextRequest)(request)) { + return NextRequestAdapter.fromNodeNextRequest(request, signal); + } else { + throw new Error('Invariant: Unsupported NextRequest type'); + } + } + static fromNodeNextRequest(request, signal) { + // HEAD and GET requests can not have a body. + let body = null; + if (request.method !== 'GET' && request.method !== 'HEAD' && request.body) { + // @ts-expect-error - this is handled by undici, when streams/web land use it instead + body = request.body; + } + let url; + if (request.url.startsWith('http')) { + url = new URL(request.url); + } else { + // Grab the full URL from the request metadata. + const base = (0, _requestmeta.getRequestMeta)(request, 'initURL'); + if (!base || !base.startsWith('http')) { + // Because the URL construction relies on the fact that the URL provided + // is absolute, we need to provide a base URL. We can't use the request + // URL because it's relative, so we use a dummy URL instead. + url = new URL(request.url, 'http://n'); + } else { + url = new URL(request.url, base); + } + } + return new _request.NextRequest(url, { + method: request.method, + headers: (0, _utils.fromNodeOutgoingHttpHeaders)(request.headers), + duplex: 'half', + signal, + // geo + // ip + // nextConfig + // body can not be passed if request was aborted + // or we get a Request body was disturbed error + ...signal.aborted ? {} : { + body + } + }); + } + static fromWebNextRequest(request) { + // HEAD and GET requests can not have a body. + let body = null; + if (request.method !== 'GET' && request.method !== 'HEAD') { + body = request.body; + } + return new _request.NextRequest(request.url, { + method: request.method, + headers: (0, _utils.fromNodeOutgoingHttpHeaders)(request.headers), + duplex: 'half', + signal: request.request.signal, + // geo + // ip + // nextConfig + // body can not be passed if request was aborted + // or we get a Request body was disturbed error + ...request.request.signal.aborted ? {} : { + body + } + }); + } +} + +//# sourceMappingURL=next-request.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js.map new file mode 100644 index 0000000000000000000000000000000000000000..fcdbd164f1c2bff335e227bad0618af7953a15f6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/next-request.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/web/spec-extension/adapters/next-request.ts"],"sourcesContent":["import type { BaseNextRequest } from '../../../base-http'\nimport type { NodeNextRequest } from '../../../base-http/node'\nimport type { WebNextRequest } from '../../../base-http/web'\nimport type { Writable } from 'node:stream'\n\nimport { getRequestMeta } from '../../../request-meta'\nimport { fromNodeOutgoingHttpHeaders } from '../../utils'\nimport { NextRequest } from '../request'\nimport { isNodeNextRequest, isWebNextRequest } from '../../../base-http/helpers'\n\nexport const ResponseAbortedName = 'ResponseAborted'\nexport class ResponseAborted extends Error {\n public readonly name = ResponseAbortedName\n}\n\n/**\n * Creates an AbortController tied to the closing of a ServerResponse (or other\n * appropriate Writable).\n *\n * If the `close` event is fired before the `finish` event, then we'll send the\n * `abort` signal.\n */\nexport function createAbortController(response: Writable): AbortController {\n const controller = new AbortController()\n\n // If `finish` fires first, then `res.end()` has been called and the close is\n // just us finishing the stream on our side. If `close` fires first, then we\n // know the client disconnected before we finished.\n response.once('close', () => {\n if (response.writableFinished) return\n\n controller.abort(new ResponseAborted())\n })\n\n return controller\n}\n\n/**\n * Creates an AbortSignal tied to the closing of a ServerResponse (or other\n * appropriate Writable).\n *\n * This cannot be done with the request (IncomingMessage or Readable) because\n * the `abort` event will not fire if to data has been fully read (because that\n * will \"close\" the readable stream and nothing fires after that).\n */\nexport function signalFromNodeResponse(response: Writable): AbortSignal {\n const { errored, destroyed } = response\n if (errored || destroyed) {\n return AbortSignal.abort(errored ?? new ResponseAborted())\n }\n\n const { signal } = createAbortController(response)\n return signal\n}\n\nexport class NextRequestAdapter {\n public static fromBaseNextRequest(\n request: BaseNextRequest,\n signal: AbortSignal\n ): NextRequest {\n if (\n // The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME === 'edge' &&\n isWebNextRequest(request)\n ) {\n return NextRequestAdapter.fromWebNextRequest(request)\n } else if (\n // The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' &&\n isNodeNextRequest(request)\n ) {\n return NextRequestAdapter.fromNodeNextRequest(request, signal)\n } else {\n throw new Error('Invariant: Unsupported NextRequest type')\n }\n }\n\n public static fromNodeNextRequest(\n request: NodeNextRequest,\n signal: AbortSignal\n ): NextRequest {\n // HEAD and GET requests can not have a body.\n let body: BodyInit | null = null\n if (request.method !== 'GET' && request.method !== 'HEAD' && request.body) {\n // @ts-expect-error - this is handled by undici, when streams/web land use it instead\n body = request.body\n }\n\n let url: URL\n if (request.url.startsWith('http')) {\n url = new URL(request.url)\n } else {\n // Grab the full URL from the request metadata.\n const base = getRequestMeta(request, 'initURL')\n if (!base || !base.startsWith('http')) {\n // Because the URL construction relies on the fact that the URL provided\n // is absolute, we need to provide a base URL. We can't use the request\n // URL because it's relative, so we use a dummy URL instead.\n url = new URL(request.url, 'http://n')\n } else {\n url = new URL(request.url, base)\n }\n }\n\n return new NextRequest(url, {\n method: request.method,\n headers: fromNodeOutgoingHttpHeaders(request.headers),\n duplex: 'half',\n signal,\n // geo\n // ip\n // nextConfig\n\n // body can not be passed if request was aborted\n // or we get a Request body was disturbed error\n ...(signal.aborted\n ? {}\n : {\n body,\n }),\n })\n }\n\n public static fromWebNextRequest(request: WebNextRequest): NextRequest {\n // HEAD and GET requests can not have a body.\n let body: ReadableStream | null = null\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n body = request.body\n }\n\n return new NextRequest(request.url, {\n method: request.method,\n headers: fromNodeOutgoingHttpHeaders(request.headers),\n duplex: 'half',\n signal: request.request.signal,\n // geo\n // ip\n // nextConfig\n\n // body can not be passed if request was aborted\n // or we get a Request body was disturbed error\n ...(request.request.signal.aborted\n ? {}\n : {\n body,\n }),\n })\n }\n}\n"],"names":["NextRequestAdapter","ResponseAborted","ResponseAbortedName","createAbortController","signalFromNodeResponse","Error","name","response","controller","AbortController","once","writableFinished","abort","errored","destroyed","AbortSignal","signal","fromBaseNextRequest","request","process","env","NEXT_RUNTIME","isWebNextRequest","fromWebNextRequest","isNodeNextRequest","fromNodeNextRequest","body","method","url","startsWith","URL","base","getRequestMeta","NextRequest","headers","fromNodeOutgoingHttpHeaders","duplex","aborted"],"mappings":";;;;;;;;;;;;;;;;;;IAuDaA,kBAAkB;eAAlBA;;IA5CAC,eAAe;eAAfA;;IADAC,mBAAmB;eAAnBA;;IAYGC,qBAAqB;eAArBA;;IAuBAC,sBAAsB;eAAtBA;;;6BAxCe;uBACa;yBAChB;yBACwB;AAE7C,MAAMF,sBAAsB;AAC5B,MAAMD,wBAAwBI;;QAA9B,qBACWC,OAAOJ;;AACzB;AASO,SAASC,sBAAsBI,QAAkB;IACtD,MAAMC,aAAa,IAAIC;IAEvB,6EAA6E;IAC7E,4EAA4E;IAC5E,mDAAmD;IACnDF,SAASG,IAAI,CAAC,SAAS;QACrB,IAAIH,SAASI,gBAAgB,EAAE;QAE/BH,WAAWI,KAAK,CAAC,IAAIX;IACvB;IAEA,OAAOO;AACT;AAUO,SAASJ,uBAAuBG,QAAkB;IACvD,MAAM,EAAEM,OAAO,EAAEC,SAAS,EAAE,GAAGP;IAC/B,IAAIM,WAAWC,WAAW;QACxB,OAAOC,YAAYH,KAAK,CAACC,WAAW,IAAIZ;IAC1C;IAEA,MAAM,EAAEe,MAAM,EA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YACN,KAAK;YACL,aAAa;YAEb,gDAAgD;YAChD,+CAA+C;YAC/C,GAAIA,OAAOqB,OAAO,GACd,CAAC,IACD;gBACEX;YACF,CAAC;QACP;IACF;IAEA,OAAcH,mBAAmBL,OAAuB,EAAe;QACrE,6CAA6C;QAC7C,IAAIQ,OAA8B;QAClC,IAAIR,QAAQS,MAAM,KAAK,SAAST,QAAQS,MAAM,KAAK,QAAQ;YACzDD,OAAOR,QAAQQ,IAAI;QACrB;QAEA,OAAO,IAAIO,oBAAW,CAACf,QAAQU,GAAG,EAAE;YAClCD,QAAQT,QAAQS,MAAM;YACtBO,SAASC,IAAAA,kCAA2B,EAACjB,QAAQgB,OAAO;YACpDE,QAAQ;YACRpB,QAAQE,QAAQA,OAAO,CAACF,MAAM;YAC9B,MAAM;YACN,KAAK;YACL,aAAa;YAEb,gDAAgD;YAChD,+CAA+C;YAC/C,GAAIE,QAAQA,OAAO,CAACF,MAAM,CAACqB,OAAO,GAC9B,CAAC,IACD;gBACEX;YACF,CAAC;QACP;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/reflect.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/reflect.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9deb12104e611e3625be9d514dfa086ff84eae99 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/reflect.d.ts @@ -0,0 +1,6 @@ +export declare class ReflectAdapter { + static get(target: T, prop: string | symbol, receiver: unknown): any; + static set(target: T, prop: string | symbol, value: any, receiver: any): boolean; + static has(target: T, prop: string | symbol): boolean; + static deleteProperty(target: T, prop: string | symbol): boolean; +} diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/reflect.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/reflect.js new file mode 100644 index 0000000000000000000000000000000000000000..146f06314c9cf6ab22433a625dbda93d6ca27b23 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/reflect.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ReflectAdapter", { + enumerable: true, + get: function() { + return ReflectAdapter; + } +}); +class ReflectAdapter { + static get(target, prop, receiver) { + const value = Reflect.get(target, prop, receiver); + if (typeof value === 'function') { + return value.bind(target); + } + return value; + } + static set(target, prop, value, receiver) { + return Reflect.set(target, prop, value, receiver); + } + static has(target, prop) { + return Reflect.has(target, prop); + } + static deleteProperty(target, prop) { + return Reflect.deleteProperty(target, prop); + } +} + +//# sourceMappingURL=reflect.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/reflect.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/reflect.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bc34fb2dcba0d80d9b8dc0754dedbedbe4a4e0d1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/reflect.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/web/spec-extension/adapters/reflect.ts"],"sourcesContent":["export class ReflectAdapter {\n static get(\n target: T,\n prop: string | symbol,\n receiver: unknown\n ): any {\n const value = Reflect.get(target, prop, receiver)\n if (typeof value === 'function') {\n return value.bind(target)\n }\n\n return value\n }\n\n static set(\n target: T,\n prop: string | symbol,\n value: any,\n receiver: any\n ): boolean {\n return Reflect.set(target, prop, value, receiver)\n }\n\n static has(target: T, prop: string | symbol): boolean {\n return Reflect.has(target, prop)\n }\n\n static deleteProperty(\n target: T,\n prop: string | symbol\n ): boolean {\n return Reflect.deleteProperty(target, prop)\n }\n}\n"],"names":["ReflectAdapter","get","target","prop","receiver","value","Reflect","bind","set","has","deleteProperty"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA;IACX,OAAOC,IACLC,MAAS,EACTC,IAAqB,EACrBC,QAAiB,EACZ;QACL,MAAMC,QAAQC,QAAQL,GAAG,CAACC,QAAQC,MAAMC;QACxC,IAAI,OAAOC,UAAU,YAAY;YAC/B,OAAOA,MAAME,IAAI,CAACL;QACpB;QAEA,OAAOG;IACT;IAEA,OAAOG,IACLN,MAAS,EACTC,IAAqB,EACrBE,KAAU,EACVD,QAAa,EACJ;QACT,OAAOE,QAAQE,GAAG,CAACN,QAAQC,MAAME,OAAOD;IAC1C;IAEA,OAAOK,IAAsBP,MAAS,EAAEC,IAAqB,EAAW;QACtE,OAAOG,QAAQG,GAAG,CAACP,QAAQC;IAC7B;IAEA,OAAOO,eACLR,MAAS,EACTC,IAAqB,EACZ;QACT,OAAOG,QAAQI,cAAc,CAACR,QAAQC;IACxC;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ae2342b1a55dacf57bef932206d94e1878d5231 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.d.ts @@ -0,0 +1,22 @@ +import { RequestCookies } from '../cookies'; +import { ResponseCookies } from '../cookies'; +import type { RequestStore } from '../../../app-render/work-unit-async-storage.external'; +export type { ResponseCookies }; +export type ReadonlyRequestCookies = Omit & Pick; +export declare class RequestCookiesAdapter { + static seal(cookies: RequestCookies): ReadonlyRequestCookies; + /** + * @param cookies + * @returns A fresh object identity backed by the original value + */ + static fresh(cookies: ReadonlyRequestCookies): ReadonlyRequestCookies; +} +export declare function getModifiedCookieValues(cookies: ResponseCookies): ResponseCookie[]; +export declare function appendMutableCookies(headers: Headers, mutableCookies: ResponseCookies): boolean; +type ResponseCookie = NonNullable['get']>>; +export declare class MutableRequestCookiesAdapter { + static wrap(cookies: RequestCookies, onUpdateCookies?: (cookies: string[]) => void): ResponseCookies; +} +export declare function createCookiesWithMutableAccessCheck(requestStore: RequestStore): ResponseCookies; +export declare function areCookiesMutableInCurrentPhase(requestStore: RequestStore): boolean; +export declare function responseCookiesToRequestCookies(responseCookies: ResponseCookies): RequestCookies; diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.js new file mode 100644 index 0000000000000000000000000000000000000000..d9b94113cb58bdf3047e4bd0af987a39ffb29858 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.js @@ -0,0 +1,221 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + MutableRequestCookiesAdapter: null, + ReadonlyRequestCookiesError: null, + RequestCookiesAdapter: null, + appendMutableCookies: null, + areCookiesMutableInCurrentPhase: null, + createCookiesWithMutableAccessCheck: null, + getModifiedCookieValues: null, + responseCookiesToRequestCookies: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + MutableRequestCookiesAdapter: function() { + return MutableRequestCookiesAdapter; + }, + ReadonlyRequestCookiesError: function() { + return ReadonlyRequestCookiesError; + }, + RequestCookiesAdapter: function() { + return RequestCookiesAdapter; + }, + appendMutableCookies: function() { + return appendMutableCookies; + }, + areCookiesMutableInCurrentPhase: function() { + return areCookiesMutableInCurrentPhase; + }, + createCookiesWithMutableAccessCheck: function() { + return createCookiesWithMutableAccessCheck; + }, + getModifiedCookieValues: function() { + return getModifiedCookieValues; + }, + responseCookiesToRequestCookies: function() { + return responseCookiesToRequestCookies; + } +}); +const _cookies = require("../cookies"); +const _reflect = require("./reflect"); +const _workasyncstorageexternal = require("../../../app-render/work-async-storage.external"); +const _actionrevalidationkind = require("../../../../shared/lib/action-revalidation-kind"); +class ReadonlyRequestCookiesError extends Error { + constructor(){ + super('Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options'); + } + static callable() { + throw new ReadonlyRequestCookiesError(); + } +} +class RequestCookiesAdapter { + static seal(cookies) { + return new Proxy(cookies, { + get (target, prop, receiver) { + switch(prop){ + case 'clear': + case 'delete': + case 'set': + return ReadonlyRequestCookiesError.callable; + default: + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + } + }); + } + /** + * @param cookies + * @returns A fresh object identity backed by the original value + */ static fresh(cookies) { + return new Proxy(cookies, { + get (target, prop, receiver) { + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + }); + } +} +const SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for('next.mutated.cookies'); +function getModifiedCookieValues(cookies) { + const modified = cookies[SYMBOL_MODIFY_COOKIE_VALUES]; + if (!modified || !Array.isArray(modified) || modified.length === 0) { + return []; + } + return modified; +} +function appendMutableCookies(headers, mutableCookies) { + const modifiedCookieValues = getModifiedCookieValues(mutableCookies); + if (modifiedCookieValues.length === 0) { + return false; + } + // Return a new response that extends the response with + // the modified cookies as fallbacks. `res` cookies + // will still take precedence. + const resCookies = new _cookies.ResponseCookies(headers); + const returnedCookies = resCookies.getAll(); + // Set the modified cookies as fallbacks. + for (const cookie of modifiedCookieValues){ + resCookies.set(cookie); + } + // Set the original cookies as the final values. + for (const cookie of returnedCookies){ + resCookies.set(cookie); + } + return true; +} +class MutableRequestCookiesAdapter { + static wrap(cookies, onUpdateCookies) { + const responseCookies = new _cookies.ResponseCookies(new Headers()); + for (const cookie of cookies.getAll()){ + responseCookies.set(cookie); + } + let modifiedValues = []; + const modifiedCookies = new Set(); + const updateResponseCookies = ()=>{ + // TODO-APP: change method of getting workStore + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (workStore) { + workStore.pathWasRevalidated = _actionrevalidationkind.ActionDidRevalidateStaticAndDynamic; + } + const allCookies = responseCookies.getAll(); + modifiedValues = allCookies.filter((c)=>modifiedCookies.has(c.name)); + if (onUpdateCookies) { + const serializedCookies = []; + for (const cookie of modifiedValues){ + const tempCookies = new _cookies.ResponseCookies(new Headers()); + tempCookies.set(cookie); + serializedCookies.push(tempCookies.toString()); + } + onUpdateCookies(serializedCookies); + } + }; + const wrappedCookies = new Proxy(responseCookies, { + get (target, prop, receiver) { + switch(prop){ + // A special symbol to get the modified cookie values + case SYMBOL_MODIFY_COOKIE_VALUES: + return modifiedValues; + // TODO: Throw error if trying to set a cookie after the response + // headers have been set. + case 'delete': + return function(...args) { + modifiedCookies.add(typeof args[0] === 'string' ? args[0] : args[0].name); + try { + target.delete(...args); + return wrappedCookies; + } finally{ + updateResponseCookies(); + } + }; + case 'set': + return function(...args) { + modifiedCookies.add(typeof args[0] === 'string' ? args[0] : args[0].name); + try { + target.set(...args); + return wrappedCookies; + } finally{ + updateResponseCookies(); + } + }; + default: + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + } + }); + return wrappedCookies; + } +} +function createCookiesWithMutableAccessCheck(requestStore) { + const wrappedCookies = new Proxy(requestStore.mutableCookies, { + get (target, prop, receiver) { + switch(prop){ + case 'delete': + return function(...args) { + ensureCookiesAreStillMutable(requestStore, 'cookies().delete'); + target.delete(...args); + return wrappedCookies; + }; + case 'set': + return function(...args) { + ensureCookiesAreStillMutable(requestStore, 'cookies().set'); + target.set(...args); + return wrappedCookies; + }; + default: + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + } + }); + return wrappedCookies; +} +function areCookiesMutableInCurrentPhase(requestStore) { + return requestStore.phase === 'action'; +} +/** Ensure that cookies() starts throwing on mutation + * if we changed phases and can no longer mutate. + * + * This can happen when going: + * 'render' -> 'after' + * 'action' -> 'render' + * */ function ensureCookiesAreStillMutable(requestStore, _callingExpression) { + if (!areCookiesMutableInCurrentPhase(requestStore)) { + // TODO: maybe we can give a more precise error message based on callingExpression? + throw new ReadonlyRequestCookiesError(); + } +} +function responseCookiesToRequestCookies(responseCookies) { + const requestCookies = new _cookies.RequestCookies(new Headers()); + for (const cookie of responseCookies.getAll()){ + requestCookies.set(cookie); + } + return requestCookies; +} + +//# sourceMappingURL=request-cookies.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.js.map new file mode 100644 index 0000000000000000000000000000000000000000..febb76ab51d25924215260fece944bf41c9fdfc3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/server/web/spec-extension/adapters/request-cookies.ts"],"sourcesContent":["import { RequestCookies } from '../cookies'\n\nimport { ResponseCookies } from '../cookies'\nimport { ReflectAdapter } from './reflect'\nimport { workAsyncStorage } from '../../../app-render/work-async-storage.external'\nimport type { RequestStore } from '../../../app-render/work-unit-async-storage.external'\nimport { ActionDidRevalidateStaticAndDynamic } from '../../../../shared/lib/action-revalidation-kind'\n\n/**\n * @internal\n */\nexport class ReadonlyRequestCookiesError extends Error {\n constructor() {\n super(\n 'Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options'\n )\n }\n\n public static callable() {\n throw new ReadonlyRequestCookiesError()\n }\n}\n\n// We use this to type some APIs but we don't construct instances directly\nexport type { ResponseCookies }\n\n// The `cookies()` API is a mix of request and response cookies. For `.get()` methods,\n// we want to return the request cookie if it exists. For mutative methods like `.set()`,\n// we want to return the response cookie.\nexport type ReadonlyRequestCookies = Omit<\n RequestCookies,\n 'set' | 'clear' | 'delete'\n> &\n Pick\n\nexport class RequestCookiesAdapter {\n public static seal(cookies: RequestCookies): ReadonlyRequestCookies {\n return new Proxy(cookies as any, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'clear':\n case 'delete':\n case 'set':\n return ReadonlyRequestCookiesError.callable\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n })\n }\n\n /**\n * @param cookies\n * @returns A fresh object identity backed by the original value\n */\n public static fresh(cookies: ReadonlyRequestCookies): ReadonlyRequestCookies {\n return new Proxy(cookies, {\n get(target, prop, receiver) {\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n }\n}\n\nconst SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for('next.mutated.cookies')\n\nexport function getModifiedCookieValues(\n cookies: ResponseCookies\n): ResponseCookie[] {\n const modified: ResponseCookie[] | undefined = (cookies as unknown as any)[\n SYMBOL_MODIFY_COOKIE_VALUES\n ]\n if (!modified || !Array.isArray(modified) || modified.length === 0) {\n return []\n }\n\n return modified\n}\n\ntype SetCookieArgs =\n | [key: string, value: string, cookie?: Partial]\n | [options: ResponseCookie]\n\nexport function appendMutableCookies(\n headers: Headers,\n mutableCookies: ResponseCookies\n): boolean {\n const modifiedCookieValues = getModifiedCookieValues(mutableCookies)\n if (modifiedCookieValues.length === 0) {\n return false\n }\n\n // Return a new response that extends the response with\n // the modified cookies as fallbacks. `res` cookies\n // will still take precedence.\n const resCookies = new ResponseCookies(headers)\n const returnedCookies = resCookies.getAll()\n\n // Set the modified cookies as fallbacks.\n for (const cookie of modifiedCookieValues) {\n resCookies.set(cookie)\n }\n\n // Set the original cookies as the final values.\n for (const cookie of returnedCookies) {\n resCookies.set(cookie)\n }\n\n return true\n}\n\ntype ResponseCookie = NonNullable<\n ReturnType['get']>\n>\n\nexport class MutableRequestCookiesAdapter {\n public static wrap(\n cookies: RequestCookies,\n onUpdateCookies?: (cookies: string[]) => void\n ): ResponseCookies {\n const responseCookies = new ResponseCookies(new Headers())\n for (const cookie of cookies.getAll()) {\n responseCookies.set(cookie)\n }\n\n let modifiedValues: ResponseCookie[] = []\n const modifiedCookies = new Set()\n const updateResponseCookies = () => {\n // TODO-APP: change method of getting workStore\n const workStore = workAsyncStorage.getStore()\n if (workStore) {\n workStore.pathWasRevalidated = ActionDidRevalidateStaticAndDynamic\n }\n\n const allCookies = responseCookies.getAll()\n modifiedValues = allCookies.filter((c) => modifiedCookies.has(c.name))\n if (onUpdateCookies) {\n const serializedCookies: string[] = []\n for (const cookie of modifiedValues) {\n const tempCookies = new ResponseCookies(new Headers())\n tempCookies.set(cookie)\n serializedCookies.push(tempCookies.toString())\n }\n\n onUpdateCookies(serializedCookies)\n }\n }\n\n const wrappedCookies = new Proxy(responseCookies, {\n get(target, prop, receiver) {\n switch (prop) {\n // A special symbol to get the modified cookie values\n case SYMBOL_MODIFY_COOKIE_VALUES:\n return modifiedValues\n\n // TODO: Throw error if trying to set a cookie after the response\n // headers have been set.\n case 'delete':\n return function (...args: [string] | [ResponseCookie]) {\n modifiedCookies.add(\n typeof args[0] === 'string' ? args[0] : args[0].name\n )\n try {\n target.delete(...args)\n return wrappedCookies\n } finally {\n updateResponseCookies()\n }\n }\n case 'set':\n return function (...args: SetCookieArgs) {\n modifiedCookies.add(\n typeof args[0] === 'string' ? args[0] : args[0].name\n )\n try {\n target.set(...args)\n return wrappedCookies\n } finally {\n updateResponseCookies()\n }\n }\n\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n })\n\n return wrappedCookies\n }\n}\n\nexport function createCookiesWithMutableAccessCheck(\n requestStore: RequestStore\n): ResponseCookies {\n const wrappedCookies = new Proxy(requestStore.mutableCookies, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'delete':\n return function (...args: [string] | [ResponseCookie]) {\n ensureCookiesAreStillMutable(requestStore, 'cookies().delete')\n target.delete(...args)\n return wrappedCookies\n }\n case 'set':\n return function (...args: SetCookieArgs) {\n ensureCookiesAreStillMutable(requestStore, 'cookies().set')\n target.set(...args)\n return wrappedCookies\n }\n\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n })\n return wrappedCookies\n}\n\nexport function areCookiesMutableInCurrentPhase(requestStore: RequestStore) {\n return requestStore.phase === 'action'\n}\n\n/** Ensure that cookies() starts throwing on mutation\n * if we changed phases and can no longer mutate.\n *\n * This can happen when going:\n * 'render' -> 'after'\n * 'action' -> 'render'\n * */\nfunction ensureCookiesAreStillMutable(\n requestStore: RequestStore,\n _callingExpression: string\n) {\n if (!areCookiesMutableInCurrentPhase(requestStore)) {\n // TODO: maybe we can give a more precise error message based on callingExpression?\n throw new ReadonlyRequestCookiesError()\n }\n}\n\nexport function responseCookiesToRequestCookies(\n responseCookies: ResponseCookies\n): RequestCookies {\n const requestCookies = new RequestCookies(new Headers())\n for (const cookie of responseCookies.getAll()) {\n requestCookies.set(cookie)\n }\n return requestCookies\n}\n"],"names":["MutableRequestCookiesAdapter","ReadonlyRequestCookiesError","RequestCookiesAdapter","appendMutableCookies","areCookiesMutableInCurrentPhase","createCookiesWithMutableAccessCheck","getModifiedCookieValues","responseCookiesToRequestCookies","Error","constructor","callable","seal","cookies","Proxy","get","target","prop","receiver","ReflectAdapter","fresh","SYMBOL_MODIFY_COOKIE_VALUES","Symbol","for","modified","Array","isArray","length","headers","mutableCookies","modifiedCookieValues","resCookies","ResponseCookies","returnedCookies","getAll","cookie","set","wrap","onUpdateCookies","responseCookies","Headers","modifiedValues","modifiedCookies","Set","updateResponseCookies","workStore","workAsyncStorage","getStore","pathWasRevalidated","ActionDidRevalidateStaticAndDynamic","allCookies","filter","c","has","name","serializedCookies","tempCookies","push","toString","wrappedCookies","args","add","delete","requestStore","ensureCookiesAreStillMutable","phase","_callingExpression","requestCookies","RequestCookies"],"mappings":";;;;;;;;;;;;;;;;;;;;;IAmHaA,4BAA4B;eAA5BA;;IAxGAC,2BAA2B;eAA3BA;;IAwBAC,qBAAqB;eAArBA;;IAgDGC,oBAAoB;eAApBA;;IAwIAC,+BAA+B;eAA/BA;;IA3BAC,mCAAmC;eAAnCA;;IA9HAC,uBAAuB;eAAvBA;;IA8KAC,+BAA+B;eAA/BA;;;yBAhPe;yBAGA;0CACE;wCAEmB;AAK7C,MAAMN,oCAAoCO;IAC/CC,aAAc;QACZ,KAAK,CACH;IAEJ;IAEA,OAAcC,WAAW;QACvB,MAAM,IAAIT;IACZ;AACF;AAcO,MAAMC;IACX,OAAcS,KAAKC,OAAuB,EAA0B;QAClE,OAAO,IAAIC,MAAMD,SAAgB;YAC/BE,KAAIC,MAAM,EAAEC,IAAI,EAAEC,QAAQ;gBACxB,O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OoB,GAAG,IAAIwB;gCACd,OAAOD;4BACT,SAAU;gCACRf;4BACF;wBACF;oBAEF;wBACE,OAAOzB,uBAAc,CAACJ,GAAG,CAACC,QAAQC,MAAMC;gBAC5C;YACF;QACF;QAEA,OAAOyC;IACT;AACF;AAEO,SAASrD,oCACdyD,YAA0B;IAE1B,MAAMJ,iBAAiB,IAAI7C,MAAMiD,aAAalC,cAAc,EAAE;QAC5Dd,KAAIC,MAAM,EAAEC,IAAI,EAAEC,QAAQ;YACxB,OAAQD;gBACN,KAAK;oBACH,OAAO,SAAU,GAAG2C,IAAiC;wBACnDI,6BAA6BD,cAAc;wBAC3C/C,OAAO8C,MAAM,IAAIF;wBACjB,OAAOD;oBACT;gBACF,KAAK;oBACH,OAAO,SAAU,GAAGC,IAAmB;wBACrCI,6BAA6BD,cAAc;wBAC3C/C,OAAOoB,GAAG,IAAIwB;wBACd,OAAOD;oBACT;gBAEF;oBACE,OAAOxC,uBAAc,CAACJ,GAAG,CAACC,QAAQC,MAAMC;YAC5C;QACF;IACF;IACA,OAAOyC;AACT;AAEO,SAAStD,gCAAgC0D,YAA0B;IACxE,OAAOA,aAAaE,KAAK,KAAK;AAChC;AAEA;;;;;;GAMG,GACH,SAASD,6BACPD,YAA0B,EAC1BG,kBAA0B;IAE1B,IAAI,CAAC7D,gCAAgC0D,eAAe;QAClD,mFAAmF;QACnF,MAAM,IAAI7D;IACZ;AACF;AAEO,SAASM,gCACd+B,eAAgC;IAEhC,MAAM4B,iBAAiB,IAAIC,uBAAc,CAAC,IAAI5B;IAC9C,KAAK,MAAML,UAAUI,gBAAgBL,MAAM,GAAI;QAC7CiC,eAAe/B,GAAG,CAACD;IACrB;IACA,OAAOgC;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/cookies.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/cookies.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e233b0201acc7302ea6e025e5ad56f1a92981057 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/cookies.d.ts @@ -0,0 +1 @@ +export { RequestCookies, ResponseCookies, stringifyCookie, } from 'next/dist/compiled/@edge-runtime/cookies'; diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/cookies.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/cookies.js new file mode 100644 index 0000000000000000000000000000000000000000..5c3122230fe8a70111e2e4f7a327613411454aad --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/cookies.js @@ -0,0 +1,29 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + RequestCookies: null, + ResponseCookies: null, + stringifyCookie: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + RequestCookies: function() { + return _cookies.RequestCookies; + }, + ResponseCookies: function() { + return _cookies.ResponseCookies; + }, + stringifyCookie: function() { + return _cookies.stringifyCookie; + } +}); +const _cookies = require("next/dist/compiled/@edge-runtime/cookies"); + +//# sourceMappingURL=cookies.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/cookies.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/cookies.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bdcf18d3648a855dbc4c674fab95f15b029a1eb4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/cookies.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/spec-extension/cookies.ts"],"sourcesContent":["export {\n RequestCookies,\n ResponseCookies,\n stringifyCookie,\n} from 'next/dist/compiled/@edge-runtime/cookies'\n"],"names":["RequestCookies","ResponseCookies","stringifyCookie"],"mappings":";;;;;;;;;;;;;;;;IACEA,cAAc;eAAdA,uBAAc;;IACdC,eAAe;eAAfA,wBAAe;;IACfC,eAAe;eAAfA,wBAAe;;;yBACV","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/fetch-event.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/fetch-event.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4fd407c50e84a4e8187707e5d792ab64a545e4c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/fetch-event.d.ts @@ -0,0 +1,44 @@ +import type { WaitUntil } from '../../after/builtin-request-context'; +import type { NextRequest } from './request'; +declare const responseSymbol: unique symbol; +declare const passThroughSymbol: unique symbol; +declare const waitUntilSymbol: unique symbol; +declare class FetchEvent { + readonly [waitUntilSymbol]: { + kind: 'internal'; + promises: Promise[]; + } | { + kind: 'external'; + function: WaitUntil; + }; + [responseSymbol]?: Promise; + [passThroughSymbol]: boolean; + constructor(_request: Request, waitUntil?: WaitUntil); + respondWith(response: Response | Promise): void; + passThroughOnException(): void; + waitUntil(promise: Promise): void; +} +export declare function getWaitUntilPromiseFromEvent(event: FetchEvent): Promise | undefined; +export declare class NextFetchEvent extends FetchEvent { + sourcePage: string; + constructor(params: { + request: NextRequest; + page: string; + context: { + waitUntil: WaitUntil; + } | undefined; + }); + /** + * @deprecated The `request` is now the first parameter and the API is now async. + * + * Read more: https://nextjs.org/docs/messages/middleware-new-signature + */ + get request(): void; + /** + * @deprecated Using `respondWith` is no longer needed. + * + * Read more: https://nextjs.org/docs/messages/middleware-new-signature + */ + respondWith(): void; +} +export {}; diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/fetch-event.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/fetch-event.js new file mode 100644 index 0000000000000000000000000000000000000000..7c4f60f76603c2413791132bbafe77debbf833e5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/fetch-event.js @@ -0,0 +1,90 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + NextFetchEvent: null, + getWaitUntilPromiseFromEvent: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + NextFetchEvent: function() { + return NextFetchEvent; + }, + getWaitUntilPromiseFromEvent: function() { + return getWaitUntilPromiseFromEvent; + } +}); +const _error = require("../error"); +const responseSymbol = Symbol('response'); +const passThroughSymbol = Symbol('passThrough'); +const waitUntilSymbol = Symbol('waitUntil'); +class FetchEvent { + constructor(_request, waitUntil){ + this[passThroughSymbol] = false; + this[waitUntilSymbol] = waitUntil ? { + kind: 'external', + function: waitUntil + } : { + kind: 'internal', + promises: [] + }; + } + // TODO: is this dead code? NextFetchEvent never lets this get called + respondWith(response) { + if (!this[responseSymbol]) { + this[responseSymbol] = Promise.resolve(response); + } + } + // TODO: is this dead code? passThroughSymbol is unused + passThroughOnException() { + this[passThroughSymbol] = true; + } + waitUntil(promise) { + if (this[waitUntilSymbol].kind === 'external') { + // if we received an external waitUntil, we delegate to it + // TODO(after): this will make us not go through `getServerError(error, 'edge-server')` in `sandbox` + const waitUntil = this[waitUntilSymbol].function; + return waitUntil(promise); + } else { + // if we didn't receive an external waitUntil, we make it work on our own + // (and expect the caller to do something with the promises) + this[waitUntilSymbol].promises.push(promise); + } + } +} +function getWaitUntilPromiseFromEvent(event) { + return event[waitUntilSymbol].kind === 'internal' ? Promise.all(event[waitUntilSymbol].promises).then(()=>{}) : undefined; +} +class NextFetchEvent extends FetchEvent { + constructor(params){ + var _params_context; + super(params.request, (_params_context = params.context) == null ? void 0 : _params_context.waitUntil); + this.sourcePage = params.page; + } + /** + * @deprecated The `request` is now the first parameter and the API is now async. + * + * Read more: https://nextjs.org/docs/messages/middleware-new-signature + */ get request() { + throw new _error.PageSignatureError({ + page: this.sourcePage + }); + } + /** + * @deprecated Using `respondWith` is no longer needed. + * + * Read more: https://nextjs.org/docs/messages/middleware-new-signature + */ respondWith() { + throw new _error.PageSignatureError({ + page: this.sourcePage + }); + } +} + +//# sourceMappingURL=fetch-event.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/fetch-event.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/fetch-event.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9b6c9ff653276ec1a04dd83eb9a234fe41082d92 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/fetch-event.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/spec-extension/fetch-event.ts"],"sourcesContent":["import type { WaitUntil } from '../../after/builtin-request-context'\nimport { PageSignatureError } from '../error'\nimport type { NextRequest } from './request'\n\nconst responseSymbol = Symbol('response')\nconst passThroughSymbol = Symbol('passThrough')\nconst waitUntilSymbol = Symbol('waitUntil')\n\nclass FetchEvent {\n // TODO(after): get rid of the 'internal' variant and always use an external waitUntil\n // (this means removing `FetchEventResult.waitUntil` which also requires a builder change)\n readonly [waitUntilSymbol]:\n | { kind: 'internal'; promises: Promise[] }\n | { kind: 'external'; function: WaitUntil };\n\n [responseSymbol]?: Promise;\n [passThroughSymbol] = false\n\n constructor(_request: Request, waitUntil?: WaitUntil) {\n this[waitUntilSymbol] = waitUntil\n ? { kind: 'external', function: waitUntil }\n : { kind: 'internal', promises: [] }\n }\n\n // TODO: is this dead code? NextFetchEvent never lets this get called\n respondWith(response: Response | Promise): void {\n if (!this[responseSymbol]) {\n this[responseSymbol] = Promise.resolve(response)\n }\n }\n\n // TODO: is this dead code? passThroughSymbol is unused\n passThroughOnException(): void {\n this[passThroughSymbol] = true\n }\n\n waitUntil(promise: Promise): void {\n if (this[waitUntilSymbol].kind === 'external') {\n // if we received an external waitUntil, we delegate to it\n // TODO(after): this will make us not go through `getServerError(error, 'edge-server')` in `sandbox`\n const waitUntil = this[waitUntilSymbol].function\n return waitUntil(promise)\n } else {\n // if we didn't receive an external waitUntil, we make it work on our own\n // (and expect the caller to do something with the promises)\n this[waitUntilSymbol].promises.push(promise)\n }\n }\n}\n\nexport function getWaitUntilPromiseFromEvent(\n event: FetchEvent\n): Promise | undefined {\n return event[waitUntilSymbol].kind === 'internal'\n ? Promise.all(event[waitUntilSymbol].promises).then(() => {})\n : undefined\n}\n\nexport class NextFetchEvent extends FetchEvent {\n sourcePage: string\n\n constructor(params: {\n request: NextRequest\n page: string\n context: { waitUntil: WaitUntil } | undefined\n }) {\n super(params.request, params.context?.waitUntil)\n this.sourcePage = params.page\n }\n\n /**\n * @deprecated The `request` is now the first parameter and the API is now async.\n *\n * Read more: https://nextjs.org/docs/messages/middleware-new-signature\n */\n get request() {\n throw new PageSignatureError({\n page: this.sourcePage,\n })\n }\n\n /**\n * @deprecated Using `respondWith` is no longer needed.\n *\n * Read more: https://nextjs.org/docs/messages/middleware-new-signature\n */\n respondWith() {\n throw new PageSignatureError({\n page: this.sourcePage,\n })\n }\n}\n"],"names":["NextFetchEvent","getWaitUntilPromiseFromEvent","responseSymbol","Symbol","passThroughSymbol","waitUntilSymbol","FetchEvent","constructor","_request","waitUntil","kind","function","promises","respondWith","response","Promise","resolve","passThroughOnException","promise","push","event","all","then","undefined","params","request","context","sourcePage","page","PageSignatureError"],"mappings":";;;;;;;;;;;;;;;IA0DaA,cAAc;eAAdA;;IARGC,4BAA4B;eAA5BA;;;uBAjDmB;AAGnC,MAAMC,iBAAiBC,OAAO;AAC9B,MAAMC,oBAAoBD,OAAO;AACjC,MAAME,kBAAkBF,OAAO;AAE/B,MAAMG;IAUJC,YAAYC,QAAiB,EAAEC,SAAqB,CAAE;YAFtD,CAACL,kBAAkB,GAAG;QAGpB,IAAI,CAACC,gBAAgB,GAAGI,YACpB;YAAEC,MAAM;YAAYC,UAAUF;QAAU,IACxC;YAAEC,MAAM;YAAYE,UAAU,EAAE;QAAC;IACvC;IAEA,qEAAqE;IACrEC,YAAYC,QAAsC,EAAQ;QACxD,IAAI,CAAC,IAAI,CAACZ,eAAe,EAAE;YACzB,IAAI,CAACA,eAAe,GAAGa,QAAQC,OAAO,CAACF;QACzC;IACF;IAEA,uDAAuD;IACvDG,yBAA+B;QAC7B,IAAI,CAACb,kBAAkB,GAAG;IAC5B;IAEAK,UAAUS,OAAqB,EAAQ;QACrC,IAAI,IAAI,CAACb,gBAAgB,CAACK,IAAI,KAAK,YAAY;YAC7C,0DAA0D;YAC1D,oGAAoG;YACpG,MAAMD,YAAY,IAAI,CAACJ,gBAAgB,CAACM,QAAQ;YAChD,OAAOF,UAAUS;QACnB,OAAO;YACL,yEAAyE;YACzE,4DAA4D;YAC5D,IAAI,CAACb,gBAAgB,CAACO,QAAQ,CAACO,IAAI,CAACD;QACtC;IACF;AACF;AAEO,SAASjB,6BACdmB,KAAiB;IAEjB,OAAOA,KAAK,CAACf,gBAAgB,CAACK,IAAI,KAAK,aACnCK,QAAQM,GAAG,CAACD,KAAK,CAACf,gBAAgB,CAACO,QAAQ,EAAEU,IAAI,CAAC,KAAO,KACzDC;AACN;AAEO,MAAMvB,uBAAuBM;IAGlCC,YAAYiB,MAIX,CAAE;YACqBA;QAAtB,KAAK,CAACA,OAAOC,OAAO,GAAED,kBAAAA,OAAOE,OAAO,qBAAdF,gBAAgBf,SAAS;QAC/C,IAAI,CAACkB,UAAU,GAAGH,OAAOI,IAAI;IAC/B;IAEA;;;;GAIC,GACD,IAAIH,UAAU;QACZ,MAAM,IAAII,yBAAkB,CAAC;YAC3BD,MAAM,IAAI,CAACD,UAAU;QACvB;IACF;IAEA;;;;GAIC,GACDd,cAAc;QACZ,MAAM,IAAIgB,yBAAkB,CAAC;YAC3BD,MAAM,IAAI,CAACD,UAAU;QACvB;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/image-response.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/image-response.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..994d2baad37b068648e44c510d0936faf3fcc1b9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/image-response.d.ts @@ -0,0 +1,5 @@ +/** + * @deprecated ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead. + * Migration with codemods: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#next-og-import + */ +export declare function ImageResponse(): never; diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/image-response.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/image-response.js new file mode 100644 index 0000000000000000000000000000000000000000..545c61f3ffbb2524e8c7b91c2289f57c17c9f167 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/image-response.js @@ -0,0 +1,18 @@ +/** + * @deprecated ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead. + * Migration with codemods: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#next-og-import + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ImageResponse", { + enumerable: true, + get: function() { + return ImageResponse; + } +}); +function ImageResponse() { + throw new Error('ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead'); +} + +//# sourceMappingURL=image-response.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/image-response.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/image-response.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cb9f59a79986167a3849805719ca0c6516e2137d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/image-response.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/spec-extension/image-response.ts"],"sourcesContent":["/**\n * @deprecated ImageResponse moved from \"next/server\" to \"next/og\" since Next.js 14, please import from \"next/og\" instead.\n * Migration with codemods: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#next-og-import\n */\nexport function ImageResponse(): never {\n throw new Error(\n 'ImageResponse moved from \"next/server\" to \"next/og\" since Next.js 14, please import from \"next/og\" instead'\n )\n}\n"],"names":["ImageResponse","Error"],"mappings":"AAAA;;;CAGC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA;IACd,MAAM,IAAIC,MACR;AAEJ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/request.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/request.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..53ed456da879344ade22781fda41fae19ef9fb83 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/request.d.ts @@ -0,0 +1,36 @@ +import type { I18NConfig } from '../../config-shared'; +import { NextURL } from '../next-url'; +import { RequestCookies } from './cookies'; +export declare const INTERNALS: unique symbol; +/** + * This class extends the [Web `Request` API](https://developer.mozilla.org/docs/Web/API/Request) with additional convenience methods. + * + * Read more: [Next.js Docs: `NextRequest`](https://nextjs.org/docs/app/api-reference/functions/next-request) + */ +export declare class NextRequest extends Request { + constructor(input: URL | RequestInfo, init?: RequestInit); + get cookies(): RequestCookies; + get nextUrl(): NextURL; + /** + * @deprecated + * `page` has been deprecated in favour of `URLPattern`. + * Read more: https://nextjs.org/docs/messages/middleware-request-page + */ + get page(): void; + /** + * @deprecated + * `ua` has been removed in favour of \`userAgent\` function. + * Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent + */ + get ua(): void; + get url(): string; +} +export interface RequestInit extends globalThis.RequestInit { + nextConfig?: { + basePath?: string; + i18n?: I18NConfig | null; + trailingSlash?: boolean; + }; + signal?: AbortSignal; + duplex?: 'half'; +} diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/request.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/request.js new file mode 100644 index 0000000000000000000000000000000000000000..3dc1ce5791e9f23a8f1dedacc3287af3e3c6ce7c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/request.js @@ -0,0 +1,99 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + INTERNALS: null, + NextRequest: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + INTERNALS: function() { + return INTERNALS; + }, + NextRequest: function() { + return NextRequest; + } +}); +const _nexturl = require("../next-url"); +const _utils = require("../utils"); +const _error = require("../error"); +const _cookies = require("./cookies"); +const INTERNALS = Symbol('internal request'); +class NextRequest extends Request { + constructor(input, init = {}){ + const url = typeof input !== 'string' && 'url' in input ? input.url : String(input); + (0, _utils.validateURL)(url); + // node Request instance requires duplex option when a body + // is present or it errors, we don't handle this for + // Request being passed in since it would have already + // errored if this wasn't configured + if (process.env.NEXT_RUNTIME !== 'edge') { + if (init.body && init.duplex !== 'half') { + init.duplex = 'half'; + } + } + if (input instanceof Request) super(input, init); + else super(url, init); + const nextUrl = new _nexturl.NextURL(url, { + headers: (0, _utils.toNodeOutgoingHttpHeaders)(this.headers), + nextConfig: init.nextConfig + }); + this[INTERNALS] = { + cookies: new _cookies.RequestCookies(this.headers), + nextUrl, + url: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? url : nextUrl.toString() + }; + } + [Symbol.for('edge-runtime.inspect.custom')]() { + return { + cookies: this.cookies, + nextUrl: this.nextUrl, + url: this.url, + // rest of props come from Request + bodyUsed: this.bodyUsed, + cache: this.cache, + credentials: this.credentials, + destination: this.destination, + headers: Object.fromEntries(this.headers), + integrity: this.integrity, + keepalive: this.keepalive, + method: this.method, + mode: this.mode, + redirect: this.redirect, + referrer: this.referrer, + referrerPolicy: this.referrerPolicy, + signal: this.signal + }; + } + get cookies() { + return this[INTERNALS].cookies; + } + get nextUrl() { + return this[INTERNALS].nextUrl; + } + /** + * @deprecated + * `page` has been deprecated in favour of `URLPattern`. + * Read more: https://nextjs.org/docs/messages/middleware-request-page + */ get page() { + throw new _error.RemovedPageError(); + } + /** + * @deprecated + * `ua` has been removed in favour of \`userAgent\` function. + * Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent + */ get ua() { + throw new _error.RemovedUAError(); + } + get url() { + return this[INTERNALS].url; + } +} + +//# sourceMappingURL=request.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/request.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/request.js.map new file mode 100644 index 0000000000000000000000000000000000000000..91e5a6d1e1a29c17185a4dbeed8e1d6a9de8b796 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/request.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/spec-extension/request.ts"],"sourcesContent":["import type { I18NConfig } from '../../config-shared'\nimport { NextURL } from '../next-url'\nimport { toNodeOutgoingHttpHeaders, validateURL } from '../utils'\nimport { RemovedUAError, RemovedPageError } from '../error'\nimport { RequestCookies } from './cookies'\n\nexport const INTERNALS = Symbol('internal request')\n\n/**\n * This class extends the [Web `Request` API](https://developer.mozilla.org/docs/Web/API/Request) with additional convenience methods.\n *\n * Read more: [Next.js Docs: `NextRequest`](https://nextjs.org/docs/app/api-reference/functions/next-request)\n */\nexport class NextRequest extends Request {\n /** @internal */\n [INTERNALS]: {\n cookies: RequestCookies\n url: string\n nextUrl: NextURL\n }\n\n constructor(input: URL | RequestInfo, init: RequestInit = {}) {\n const url =\n typeof input !== 'string' && 'url' in input ? input.url : String(input)\n\n validateURL(url)\n\n // node Request instance requires duplex option when a body\n // is present or it errors, we don't handle this for\n // Request being passed in since it would have already\n // errored if this wasn't configured\n if (process.env.NEXT_RUNTIME !== 'edge') {\n if (init.body && init.duplex !== 'half') {\n init.duplex = 'half'\n }\n }\n\n if (input instanceof Request) super(input, init)\n else super(url, init)\n\n const nextUrl = new NextURL(url, {\n headers: toNodeOutgoingHttpHeaders(this.headers),\n nextConfig: init.nextConfig,\n })\n this[INTERNALS] = {\n cookies: new RequestCookies(this.headers),\n nextUrl,\n url: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n ? url\n : nextUrl.toString(),\n }\n }\n\n [Symbol.for('edge-runtime.inspect.custom')]() {\n return {\n cookies: this.cookies,\n nextUrl: this.nextUrl,\n url: this.url,\n // rest of props come from Request\n bodyUsed: this.bodyUsed,\n cache: this.cache,\n credentials: this.credentials,\n destination: this.destination,\n headers: Object.fromEntries(this.headers),\n integrity: this.integrity,\n keepalive: this.keepalive,\n method: this.method,\n mode: this.mode,\n redirect: this.redirect,\n referrer: this.referrer,\n referrerPolicy: this.referrerPolicy,\n signal: this.signal,\n }\n }\n\n public get cookies() {\n return this[INTERNALS].cookies\n }\n\n public get nextUrl() {\n return this[INTERNALS].nextUrl\n }\n\n /**\n * @deprecated\n * `page` has been deprecated in favour of `URLPattern`.\n * Read more: https://nextjs.org/docs/messages/middleware-request-page\n */\n public get page() {\n throw new RemovedPageError()\n }\n\n /**\n * @deprecated\n * `ua` has been removed in favour of \\`userAgent\\` function.\n * Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent\n */\n public get ua() {\n throw new RemovedUAError()\n }\n\n public get url() {\n return this[INTERNALS].url\n }\n}\n\nexport interface RequestInit extends globalThis.RequestInit {\n nextConfig?: {\n basePath?: string\n i18n?: I18NConfig | null\n trailingSlash?: boolean\n }\n signal?: AbortSignal\n // see https://github.com/whatwg/fetch/pull/1457\n duplex?: 'half'\n}\n"],"names":["INTERNALS","NextRequest","Symbol","Request","constructor","input","init","url","String","validateURL","process","env","NEXT_RUNTIME","body","duplex","nextUrl","NextURL","headers","toNodeOutgoingHttpHeaders","nextConfig","cookies","RequestCookies","__NEXT_NO_MIDDLEWARE_URL_NORMALIZE","toString","for","bodyUsed","cache","credentials","destination","Object","fromEntries","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","page","RemovedPageError","ua","RemovedUAError"],"mappings":";;;;;;;;;;;;;;;IAMaA,SAAS;eAATA;;IAOAC,WAAW;eAAXA;;;yBAZW;uBAC+B;uBACN;yBAClB;AAExB,MAAMD,YAAYE,OAAO;AAOzB,MAAMD,oBAAoBE;IAQ/BC,YAAYC,KAAwB,EAAEC,OAAoB,CAAC,CAAC,CAAE;QAC5D,MAAMC,MACJ,OAAOF,UAAU,YAAY,SAASA,QAAQA,MAAME,GAAG,GAAGC,OAAOH;QAEnEI,IAAAA,kBAAW,EAACF;QAEZ,2DAA2D;QA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AI,CAACpB,UAAU,CAACoB,OAAO;IAChC;IAEA,IAAWL,UAAU;QACnB,OAAO,IAAI,CAACf,UAAU,CAACe,OAAO;IAChC;IAEA;;;;GAIC,GACD,IAAWwB,OAAO;QAChB,MAAM,IAAIC,uBAAgB;IAC5B;IAEA;;;;GAIC,GACD,IAAWC,KAAK;QACd,MAAM,IAAIC,qBAAc;IAC1B;IAEA,IAAWnC,MAAM;QACf,OAAO,IAAI,CAACP,UAAU,CAACO,GAAG;IAC5B;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/response.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/response.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f1a70fd67a043bd8d4c87236d2415f35e38e7f69 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/response.d.ts @@ -0,0 +1,43 @@ +import type { I18NConfig } from '../../config-shared'; +import { NextURL } from '../next-url'; +import { ResponseCookies } from './cookies'; +declare const INTERNALS: unique symbol; +/** + * This class extends the [Web `Response` API](https://developer.mozilla.org/docs/Web/API/Response) with additional convenience methods. + * + * Read more: [Next.js Docs: `NextResponse`](https://nextjs.org/docs/app/api-reference/functions/next-response) + */ +export declare class NextResponse extends Response { + [INTERNALS]: { + cookies: ResponseCookies; + url?: NextURL; + body?: Body; + }; + constructor(body?: BodyInit | null, init?: ResponseInit); + get cookies(): ResponseCookies; + static json(body: JsonBody, init?: ResponseInit): NextResponse; + static redirect(url: string | NextURL | URL, init?: number | ResponseInit): NextResponse; + static rewrite(destination: string | NextURL | URL, init?: MiddlewareResponseInit): NextResponse; + static next(init?: MiddlewareResponseInit): NextResponse; +} +interface ResponseInit extends globalThis.ResponseInit { + nextConfig?: { + basePath?: string; + i18n?: I18NConfig; + trailingSlash?: boolean; + }; + url?: string; +} +interface ModifiedRequest { + /** + * If this is set, the request headers will be overridden with this value. + */ + headers?: Headers; +} +interface MiddlewareResponseInit extends globalThis.ResponseInit { + /** + * These fields will override the request from clients. + */ + request?: ModifiedRequest; +} +export {}; diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/response.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/response.js new file mode 100644 index 0000000000000000000000000000000000000000..6be86495668d8584aedb4510f994081f988f74c2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/response.js @@ -0,0 +1,128 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NextResponse", { + enumerable: true, + get: function() { + return NextResponse; + } +}); +const _cookies = require("../../web/spec-extension/cookies"); +const _nexturl = require("../next-url"); +const _utils = require("../utils"); +const _reflect = require("./adapters/reflect"); +const _cookies1 = require("./cookies"); +const INTERNALS = Symbol('internal response'); +const REDIRECTS = new Set([ + 301, + 302, + 303, + 307, + 308 +]); +function handleMiddlewareField(init, headers) { + var _init_request; + if (init == null ? void 0 : (_init_request = init.request) == null ? void 0 : _init_request.headers) { + if (!(init.request.headers instanceof Headers)) { + throw new Error('request.headers must be an instance of Headers'); + } + const keys = []; + for (const [key, value] of init.request.headers){ + headers.set('x-middleware-request-' + key, value); + keys.push(key); + } + headers.set('x-middleware-override-headers', keys.join(',')); + } +} +class NextResponse extends Response { + constructor(body, init = {}){ + super(body, init); + const headers = this.headers; + const cookies = new _cookies1.ResponseCookies(headers); + const cookiesProxy = new Proxy(cookies, { + get (target, prop, receiver) { + switch(prop){ + case 'delete': + case 'set': + { + return (...args)=>{ + const result = Reflect.apply(target[prop], target, args); + const newHeaders = new Headers(headers); + if (result instanceof _cookies1.ResponseCookies) { + headers.set('x-middleware-set-cookie', result.getAll().map((cookie)=>(0, _cookies.stringifyCookie)(cookie)).join(',')); + } + handleMiddlewareField(init, newHeaders); + return result; + }; + } + default: + return _reflect.ReflectAdapter.get(target, prop, receiver); + } + } + }); + this[INTERNALS] = { + cookies: cookiesProxy, + url: init.url ? new _nexturl.NextURL(init.url, { + headers: (0, _utils.toNodeOutgoingHttpHeaders)(headers), + nextConfig: init.nextConfig + }) : undefined + }; + } + [Symbol.for('edge-runtime.inspect.custom')]() { + return { + cookies: this.cookies, + url: this.url, + // rest of props come from Response + body: this.body, + bodyUsed: this.bodyUsed, + headers: Object.fromEntries(this.headers), + ok: this.ok, + redirected: this.redirected, + status: this.status, + statusText: this.statusText, + type: this.type + }; + } + get cookies() { + return this[INTERNALS].cookies; + } + static json(body, init) { + const response = Response.json(body, init); + return new NextResponse(response.body, response); + } + static redirect(url, init) { + const status = typeof init === 'number' ? init : (init == null ? void 0 : init.status) ?? 307; + if (!REDIRECTS.has(status)) { + throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); + } + const initObj = typeof init === 'object' ? init : {}; + const headers = new Headers(initObj == null ? void 0 : initObj.headers); + headers.set('Location', (0, _utils.validateURL)(url)); + return new NextResponse(null, { + ...initObj, + headers, + status + }); + } + static rewrite(destination, init) { + const headers = new Headers(init == null ? void 0 : init.headers); + headers.set('x-middleware-rewrite', (0, _utils.validateURL)(destination)); + handleMiddlewareField(init, headers); + return new NextResponse(null, { + ...init, + headers + }); + } + static next(init) { + const headers = new Headers(init == null ? void 0 : init.headers); + headers.set('x-middleware-next', '1'); + handleMiddlewareField(init, headers); + return new NextResponse(null, { + ...init, + headers + }); + } +} + +//# sourceMappingURL=response.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/response.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/response.js.map new file mode 100644 index 0000000000000000000000000000000000000000..66fe16ea0e5a0f86c802deb58d73a6d04daa7aeb --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/response.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/spec-extension/response.ts"],"sourcesContent":["import { stringifyCookie } from '../../web/spec-extension/cookies'\nimport type { I18NConfig } from '../../config-shared'\nimport { NextURL } from '../next-url'\nimport { toNodeOutgoingHttpHeaders, validateURL } from '../utils'\nimport { ReflectAdapter } from './adapters/reflect'\n\nimport { ResponseCookies } from './cookies'\n\nconst INTERNALS = Symbol('internal response')\nconst REDIRECTS = new Set([301, 302, 303, 307, 308])\n\nfunction handleMiddlewareField(\n init: MiddlewareResponseInit | undefined,\n headers: Headers\n) {\n if (init?.request?.headers) {\n if (!(init.request.headers instanceof Headers)) {\n throw new Error('request.headers must be an instance of Headers')\n }\n\n const keys = []\n for (const [key, value] of init.request.headers) {\n headers.set('x-middleware-request-' + key, value)\n keys.push(key)\n }\n\n headers.set('x-middleware-override-headers', keys.join(','))\n }\n}\n\n/**\n * This class extends the [Web `Response` API](https://developer.mozilla.org/docs/Web/API/Response) with additional convenience methods.\n *\n * Read more: [Next.js Docs: `NextResponse`](https://nextjs.org/docs/app/api-reference/functions/next-response)\n */\nexport class NextResponse extends Response {\n [INTERNALS]: {\n cookies: ResponseCookies\n url?: NextURL\n body?: Body\n }\n\n constructor(body?: BodyInit | null, init: ResponseInit = {}) {\n super(body, init)\n\n const headers = this.headers\n const cookies = new ResponseCookies(headers)\n\n const cookiesProxy = new Proxy(cookies, {\n get(target, prop, receiver) {\n switch (prop) {\n case 'delete':\n case 'set': {\n return (...args: [string, string]) => {\n const result = Reflect.apply(target[prop], target, args)\n const newHeaders = new Headers(headers)\n\n if (result instanceof ResponseCookies) {\n headers.set(\n 'x-middleware-set-cookie',\n result\n .getAll()\n .map((cookie) => stringifyCookie(cookie))\n .join(',')\n )\n }\n\n handleMiddlewareField(init, newHeaders)\n return result\n }\n }\n default:\n return ReflectAdapter.get(target, prop, receiver)\n }\n },\n })\n\n this[INTERNALS] = {\n cookies: cookiesProxy,\n url: init.url\n ? new NextURL(init.url, {\n headers: toNodeOutgoingHttpHeaders(headers),\n nextConfig: init.nextConfig,\n })\n : undefined,\n }\n }\n\n [Symbol.for('edge-runtime.inspect.custom')]() {\n return {\n cookies: this.cookies,\n url: this.url,\n // rest of props come from Response\n body: this.body,\n bodyUsed: this.bodyUsed,\n headers: Object.fromEntries(this.headers),\n ok: this.ok,\n redirected: this.redirected,\n status: this.status,\n statusText: this.statusText,\n type: this.type,\n }\n }\n\n public get cookies() {\n return this[INTERNALS].cookies\n }\n\n static json(\n body: JsonBody,\n init?: ResponseInit\n ): NextResponse {\n const response: Response = Response.json(body, init)\n return new NextResponse(response.body, response)\n }\n\n static redirect(url: string | NextURL | URL, init?: number | ResponseInit) {\n const status = typeof init === 'number' ? init : (init?.status ?? 307)\n if (!REDIRECTS.has(status)) {\n throw new RangeError(\n 'Failed to execute \"redirect\" on \"response\": Invalid status code'\n )\n }\n const initObj = typeof init === 'object' ? init : {}\n const headers = new Headers(initObj?.headers)\n headers.set('Location', validateURL(url))\n\n return new NextResponse(null, {\n ...initObj,\n headers,\n status,\n })\n }\n\n static rewrite(\n destination: string | NextURL | URL,\n init?: MiddlewareResponseInit\n ) {\n const headers = new Headers(init?.headers)\n headers.set('x-middleware-rewrite', validateURL(destination))\n\n handleMiddlewareField(init, headers)\n return new NextResponse(null, { ...init, headers })\n }\n\n static next(init?: MiddlewareResponseInit) {\n const headers = new Headers(init?.headers)\n headers.set('x-middleware-next', '1')\n\n handleMiddlewareField(init, headers)\n return new NextResponse(null, { ...init, headers })\n }\n}\n\ninterface ResponseInit extends globalThis.ResponseInit {\n nextConfig?: {\n basePath?: string\n i18n?: I18NConfig\n trailingSlash?: boolean\n }\n url?: string\n}\n\ninterface ModifiedRequest {\n /**\n * If this is set, the request headers will be overridden with this value.\n */\n headers?: Headers\n}\n\ninterface MiddlewareResponseInit extends globalThis.ResponseInit {\n /**\n * These fields will override the request from clients.\n */\n request?: ModifiedRequest\n}\n"],"names":["NextResponse","INTERNALS","Symbol","REDIRECTS","Set","handleMiddlewareField","init","headers","request","Headers","Error","keys","key","value","set","push","join","Response","constructor","body","cookies","ResponseCookies","cookiesProxy","Proxy","get","target","prop","receiver","args","result","Reflect","apply","newHeaders","getAll","map","cookie","stringifyCookie","ReflectAdapter","url","NextURL","toNodeOutgoingHttpHeaders","nextConfig","undefined","for","bodyUsed","Object","fromEntries","ok","redirected","status","statusText","type","json","response","redirect","has","RangeError","initObj","validateURL","rewrite","destination","next"],"mappings":";;;;+BAmCaA;;;eAAAA;;;yBAnCmB;yBAER;uBAC+B;yBACxB;0BAEC;AAEhC,MAAMC,YAAYC,OAAO;AACzB,MAAMC,YAAY,IAAIC,IAAI;IAAC;IAAK;IAAK;IAAK;IAAK;CAAI;AAEnD,SAASC,sBACPC,IAAwC,EACxCC,OAAgB;QAEZD;IAAJ,IAAIA,yBAAAA,gBAAAA,KAAME,OAAO,qBAAbF,cAAeC,OAAO,EAAE;QAC1B,IAAI,CAAED,CAAAA,KAAKE,OAAO,CAACD,OAAO,YAAYE,OAAM,GAAI;YAC9C,MAAM,IAAIC,MAAM;QAClB;QAEA,MAAMC,OAAO,EAAE;QACf,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIP,KAAKE,OAAO,CAACD,OAAO,CAAE;YAC/CA,QAAQO,GAAG,CAAC,0BAA0BF,KAAKC;YAC3CF,KAAKI,IAAI,CAACH;QACZ;QAEAL,QAAQO,GAAG,CAAC,iCAAiCH,KAAKK,IAAI,CAAC;IACzD;AACF;AAOO,MAAMhB,qBAAqCiB;IAOhDC,YAAYC,IAAsB,EAAEb,OAAqB,CAAC,CAAC,CAAE;QAC3D,KAAK,CAACa,MAAMb;QAEZ,MAAMC,UAAU,IAAI,CAACA,OAAO;QAC5B,MAAMa,UAAU,IAAIC,yBAAe,CAACd;QAEpC,MAAMe,eAAe,IAAIC,MAAMH,SAAS;YACtCI,KAAIC,MAAM,EAAEC,IAAI,EAAEC,QAAQ;gBACxB,OAAQD;oBACN,KAAK;oBACL,KAAK;wBAAO;4BACV,OAAO,CAAC,GAAGE;gCACT,MAAMC,SAASC,QAAQC,KAAK,CAACN,MAAM,CAACC,KAAK,EAAED,QAAQG;gCACnD,MAAMI,aAAa,IAAIvB,QAAQF;gCAE/B,IAAIsB,kBAAkBR,yBAAe,EAAE;oCACrCd,QAAQO,GAAG,CACT,2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KAAI;QAClE,IAAI,CAAC9C,UAAUoD,GAAG,CAACN,SAAS;YAC1B,MAAM,IAAIO,WACR;QAEJ;QACA,MAAMC,UAAU,OAAOnD,SAAS,WAAWA,OAAO,CAAC;QACnD,MAAMC,UAAU,IAAIE,QAAQgD,2BAAAA,QAASlD,OAAO;QAC5CA,QAAQO,GAAG,CAAC,YAAY4C,IAAAA,kBAAW,EAACpB;QAEpC,OAAO,IAAItC,aAAa,MAAM;YAC5B,GAAGyD,OAAO;YACVlD;YACA0C;QACF;IACF;IAEA,OAAOU,QACLC,WAAmC,EACnCtD,IAA6B,EAC7B;QACA,MAAMC,UAAU,IAAIE,QAAQH,wBAAAA,KAAMC,OAAO;QACzCA,QAAQO,GAAG,CAAC,wBAAwB4C,IAAAA,kBAAW,EAACE;QAEhDvD,sBAAsBC,MAAMC;QAC5B,OAAO,IAAIP,aAAa,MAAM;YAAE,GAAGM,IAAI;YAAEC;QAAQ;IACnD;IAEA,OAAOsD,KAAKvD,IAA6B,EAAE;QACzC,MAAMC,UAAU,IAAIE,QAAQH,wBAAAA,KAAMC,OAAO;QACzCA,QAAQO,GAAG,CAAC,qBAAqB;QAEjCT,sBAAsBC,MAAMC;QAC5B,OAAO,IAAIP,aAAa,MAAM;YAAE,GAAGM,IAAI;YAAEC;QAAQ;IACnD;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/revalidate.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/revalidate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..455043afff22f59df94be528bf56f420b3996c7c --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/revalidate.d.ts @@ -0,0 +1,33 @@ +type CacheLifeConfig = { + expire?: number; +}; +/** + * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag. + * + * The second argument specifies a [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife#reference) profile + * (e.g. `"max"`), or a `{ expire }` object. For immediate expiration in Server Actions, use + * [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag) instead. + * + * Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag) + */ +export declare function revalidateTag(tag: string, profile: string | CacheLifeConfig): undefined; +/** + * This function allows you to update [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag. + * This can only be called from within a Server Action to enable read-your-own-writes semantics. + * + * Read more: [Next.js Docs: `updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag) + */ +export declare function updateTag(tag: string): undefined; +/** + * This function allows you to refresh client cache from server actions. + * It's useful as dynamic data can be cached on the client which won't + * be refreshed by updateTag + */ +export declare function refresh(): void; +/** + * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path. + * + * Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath) + */ +export declare function revalidatePath(originalPath: string, type?: 'layout' | 'page'): undefined; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/revalidate.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/revalidate.js new file mode 100644 index 0000000000000000000000000000000000000000..0366a43e7f4b37767c1f57abfb0160ec41f55dee --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/revalidate.js @@ -0,0 +1,188 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + refresh: null, + revalidatePath: null, + revalidateTag: null, + updateTag: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + refresh: function() { + return refresh; + }, + revalidatePath: function() { + return revalidatePath; + }, + revalidateTag: function() { + return revalidateTag; + }, + updateTag: function() { + return updateTag; + } +}); +const _dynamicrendering = require("../../app-render/dynamic-rendering"); +const _utils = require("../../../shared/lib/router/utils"); +const _constants = require("../../../lib/constants"); +const _workasyncstorageexternal = require("../../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external"); +const _hooksservercontext = require("../../../client/components/hooks-server-context"); +const _invarianterror = require("../../../shared/lib/invariant-error"); +const _actionrevalidationkind = require("../../../shared/lib/action-revalidation-kind"); +const _removetrailingslash = require("../../../shared/lib/router/utils/remove-trailing-slash"); +const _encodeheadersafe = require("../../lib/encode-header-safe"); +const _usecachemessages = require("../../use-cache/use-cache-messages"); +const _cachelifeprofile = require("../../use-cache/cache-life-profile"); +function revalidateTag(tag, profile) { + if (!profile) { + console.warn('"revalidateTag" without the second argument is now deprecated, add second argument of "max" or use "updateTag". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'); + } else if (typeof profile === 'object') { + profile = (0, _cachelifeprofile.validateAndNormalizeCacheLifeProfile)(profile, { + kind: 'inline' + }); + } + return revalidate([ + (0, _encodeheadersafe.encodeHeaderSafe)(tag) + ], `revalidateTag(${JSON.stringify(tag)})`, profile); +} +function updateTag(tag) { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + // TODO: change this after investigating why phase: 'action' is + // set for route handlers + if (!workStore || workStore.page.endsWith('/route')) { + throw new Error('updateTag can only be called from within a Server Action. ' + 'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' + 'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'); + } + // updateTag uses immediate expiration (no profile) without deprecation warning + return revalidate([ + (0, _encodeheadersafe.encodeHeaderSafe)(tag) + ], `updateTag(${JSON.stringify(tag)})`, undefined); +} +function refresh() { + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (!workStore || workStore.page.endsWith('/route') || (workUnitStore == null ? void 0 : workUnitStore.phase) !== 'action') { + throw new Error('refresh can only be called from within a Server Action. ' + 'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'); + } + if (workStore) { + // The Server Action version of refresh() only revalidates the dynamic data + // on the client. It doesn't affect cached data. + workStore.pathWasRevalidated = _actionrevalidationkind.ActionDidRevalidateDynamicOnly; + } +} +function revalidatePath(originalPath, type) { + if (originalPath.length > _constants.NEXT_CACHE_SOFT_TAG_MAX_LENGTH) { + console.warn(`Warning: revalidatePath received "${originalPath}" which exceeded max length of ${_constants.NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`); + return; + } + let normalizedPath = `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${(0, _encodeheadersafe.encodeHeaderSafe)((0, _removetrailingslash.removeTrailingSlash)(originalPath))}`; + if (type) { + normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`; + } else if ((0, _utils.isDynamicRoute)(originalPath)) { + console.warn(`Warning: a dynamic page path "${originalPath}" was passed to "revalidatePath", but the "type" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`); + } + const tags = [ + normalizedPath + ]; + if (normalizedPath === `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}/`) { + tags.push(`${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}/index`); + } else if (normalizedPath === `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}/index`) { + tags.push(`${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}/`); + } + return revalidate(tags, `revalidatePath(${JSON.stringify(originalPath)})`); +} +function revalidate(tags, expression, profile) { + const store = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (!store || !store.incrementalCache) { + throw new Error(`Invariant: static generation store missing in ${expression}`); + } + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (workUnitStore) { + // Prefer the more specific contexts over the general render-phase error. + switch(workUnitStore.type){ + case 'build-time-generator': + throw (0, _usecachemessages.createRevalidateInBuildTimeGeneratorError)(store.route, expression, workUnitStore.functionName); + case 'cache': + case 'private-cache': + case 'unstable-cache': + throw (0, _usecachemessages.createRevalidateInCachedFunctionError)(store.route, expression); + case 'prerender': + case 'prerender-runtime': + case 'prerender-client': + case 'validation-client': + case 'prerender-legacy': + case 'request': + break; + default: + workUnitStore; + } + if (workUnitStore.phase === 'render') { + throw (0, _usecachemessages.createRevalidateDuringRenderError)(store.route, expression); + } + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-runtime': + // cacheComponents Prerender + const error = new Error(`Route ${store.route} used ${expression} without first calling \`await connection()\`.`); + return (0, _dynamicrendering.abortAndThrowOnSynchronousRequestDataAccess)(store.route, expression, error, workUnitStore); + case 'prerender-client': + case 'validation-client': + throw new _invarianterror.InvariantError(`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`); + case 'prerender-legacy': + workUnitStore.revalidate = 0; + const err = new _hooksservercontext.DynamicServerError(`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`); + store.dynamicUsageDescription = expression; + store.dynamicUsageStack = err.stack; + throw err; + case 'request': + break; + default: + workUnitStore; + } + } + if (!store.pendingRevalidatedTags) { + store.pendingRevalidatedTags = []; + } + const revalidatedAt = performance.timeOrigin + performance.now(); + for (const tag of tags){ + const existingIndex = store.pendingRevalidatedTags.findIndex((item)=>{ + if (item.tag !== tag) return false; + // Compare profiles: both strings, both objects, or both undefined + if (typeof item.profile === 'string' && typeof profile === 'string') { + return item.profile === profile; + } + if (typeof item.profile === 'object' && typeof profile === 'object') { + return JSON.stringify(item.profile) === JSON.stringify(profile); + } + return item.profile === profile; + }); + if (existingIndex === -1) { + store.pendingRevalidatedTags.push({ + tag, + profile, + revalidatedAt + }); + } else { + // Revalidating a tag again invalidates everything produced up to now, so + // the latest revalidation is the one that decides which entries are + // stale. + store.pendingRevalidatedTags[existingIndex].revalidatedAt = revalidatedAt; + } + } + // if profile is provided and this is a stale-while-revalidate + // update we do not mark the path as revalidated so that server + // actions don't pull their own writes + const cacheLife = profile && typeof profile === 'object' ? profile : profile && typeof profile === 'string' && (store == null ? void 0 : store.cacheLifeProfiles[profile]) ? store.cacheLifeProfiles[profile] : undefined; + if (!profile || (cacheLife == null ? void 0 : cacheLife.expire) === 0) { + // TODO: only revalidate if the path matches + store.pathWasRevalidated = _actionrevalidationkind.ActionDidRevalidateStaticAndDynamic; + } +} + +//# sourceMappingURL=revalidate.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/revalidate.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/revalidate.js.map new file mode 100644 index 0000000000000000000000000000000000000000..78097dd26720e4b6f4f7240b1f052effe72750cd --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/revalidate.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/spec-extension/revalidate.ts"],"sourcesContent":["import { abortAndThrowOnSynchronousRequestDataAccess } from '../../app-render/dynamic-rendering'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport {\n NEXT_CACHE_IMPLICIT_TAG_ID,\n NEXT_CACHE_SOFT_TAG_MAX_LENGTH,\n} from '../../../lib/constants'\nimport { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { DynamicServerError } from '../../../client/components/hooks-server-context'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport {\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,\n} from '../../../shared/lib/action-revalidation-kind'\nimport { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport {\n createRevalidateDuringRenderError,\n createRevalidateInBuildTimeGeneratorError,\n createRevalidateInCachedFunctionError,\n} from '../../use-cache/use-cache-messages'\nimport { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'\n\ntype CacheLifeConfig = {\n expire?: number\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n *\n * The second argument specifies a [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife#reference) profile\n * (e.g. `\"max\"`), or a `{ expire }` object. For immediate expiration in Server Actions, use\n * [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag) instead.\n *\n * Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)\n */\nexport function revalidateTag(tag: string, profile: string | CacheLifeConfig) {\n if (!profile) {\n console.warn(\n '\"revalidateTag\" without the second argument is now deprecated, add second argument of \"max\" or use \"updateTag\". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'\n )\n } else if (typeof profile === 'object') {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n return revalidate(\n [encodeHeaderSafe(tag)],\n `revalidateTag(${JSON.stringify(tag)})`,\n profile\n )\n}\n\n/**\n * This function allows you to update [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n * This can only be called from within a Server Action to enable read-your-own-writes semantics.\n *\n * Read more: [Next.js Docs: `updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag)\n */\nexport function updateTag(tag: string) {\n const workStore = workAsyncStorage.getStore()\n\n // TODO: change this after investigating why phase: 'action' is\n // set for route handlers\n if (!workStore || workStore.page.endsWith('/route')) {\n throw new Error(\n 'updateTag can only be called from within a Server Action. ' +\n 'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'\n )\n }\n // updateTag uses immediate expiration (no profile) without deprecation warning\n return revalidate(\n [encodeHeaderSafe(tag)],\n `updateTag(${JSON.stringify(tag)})`,\n undefined\n )\n}\n\n/**\n * This function allows you to refresh client cache from server actions.\n * It's useful as dynamic data can be cached on the client which won't\n * be refreshed by updateTag\n */\nexport function refresh() {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (\n !workStore ||\n workStore.page.endsWith('/route') ||\n workUnitStore?.phase !== 'action'\n ) {\n throw new Error(\n 'refresh can only be called from within a Server Action. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'\n )\n }\n\n if (workStore) {\n // The Server Action version of refresh() only revalidates the dynamic data\n // on the client. It doesn't affect cached data.\n workStore.pathWasRevalidated = ActionDidRevalidateDynamicOnly\n }\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.\n *\n * Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath)\n */\nexport function revalidatePath(originalPath: string, type?: 'layout' | 'page') {\n if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {\n console.warn(\n `Warning: revalidatePath received \"${originalPath}\" which exceeded max length of ${NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n return\n }\n\n let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeHeaderSafe(removeTrailingSlash(originalPath))}`\n\n if (type) {\n normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`\n } else if (isDynamicRoute(originalPath)) {\n console.warn(\n `Warning: a dynamic page path \"${originalPath}\" was passed to \"revalidatePath\", but the \"type\" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n }\n\n const tags = [normalizedPath]\n if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n } else if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/index`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n return revalidate(tags, `revalidatePath(${JSON.stringify(originalPath)})`)\n}\n\nfunction revalidate(\n tags: string[],\n expression: string,\n profile?: string | CacheLifeConfig\n) {\n const store = workAsyncStorage.getStore()\n if (!store || !store.incrementalCache) {\n throw new Error(\n `Invariant: static generation store missing in ${expression}`\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n // Prefer the more specific contexts over the general render-phase error.\n switch (workUnitStore.type) {\n case 'build-time-generator':\n throw createRevalidateInBuildTimeGeneratorError(\n store.route,\n expression,\n workUnitStore.functionName\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw createRevalidateInCachedFunctionError(store.route, expression)\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n\n if (workUnitStore.phase === 'render') {\n throw createRevalidateDuringRenderError(store.route, expression)\n }\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n // cacheComponents Prerender\n const error = new Error(\n `Route ${store.route} used ${expression} without first calling \\`await connection()\\`.`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n store.route,\n expression,\n error,\n workUnitStore\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n // TODO(restart-on-cache-miss): we should do a sync IO error here in dev\n // to match prerender behavior\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (!store.pendingRevalidatedTags) {\n store.pendingRevalidatedTags = []\n }\n\n const revalidatedAt = performance.timeOrigin + performance.now()\n\n for (const tag of tags) {\n const existingIndex = store.pendingRevalidatedTags.findIndex((item) => {\n if (item.tag !== tag) return false\n // Compare profiles: both strings, both objects, or both undefined\n if (typeof item.profile === 'string' && typeof profile === 'string') {\n return item.profile === profile\n }\n if (typeof item.profile === 'object' && typeof profile === 'object') {\n return JSON.stringify(item.profile) === JSON.stringify(profile)\n }\n return item.profile === profile\n })\n if (existingIndex === -1) {\n store.pendingRevalidatedTags.push({\n tag,\n profile,\n revalidatedAt,\n })\n } else {\n // Revalidating a tag again invalidates everything produced up to now, so\n // the latest revalidation is the one that decides which entries are\n // stale.\n store.pendingRevalidatedTags[existingIndex].revalidatedAt = revalidatedAt\n }\n }\n\n // if profile is provided and this is a stale-while-revalidate\n // update we do not mark the path as revalidated so that server\n // actions don't pull their own writes\n const cacheLife =\n profile && typeof profile === 'object'\n ? profile\n : profile &&\n typeof profile === 'string' &&\n store?.cacheLifeProfiles[profile]\n ? store.cacheLifeProfiles[profile]\n : undefined\n\n if (!profile || cacheLife?.expire === 0) {\n // TODO: only revalidate if the path matches\n store.pathWasRevalidated = ActionDidRevalidate\n }\n}\n"],"names":["refresh","revalidatePath","revalidateTag","updateTag","tag","profile","console","warn","validateAndNormalizeCacheLifeProfile","kind","revalidate","encodeHeaderSafe","JSON","stringify","workStore","workAsyncStorage","getStore","page","endsWith","Error","undefined","workUnitStore","workUnitAsyncStorage","phase","pathWasRevalidated","ActionDidRevalidateDynamicOnly","originalPath","type","length","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","normalizedPath","NEXT_CACHE_IMPLICIT_TAG_ID","removeTrailingSlash","isDynamicRoute","tags","push","expression","store","incrementalCache","createRevalidateInBuildTimeGeneratorError","route","functionName","createRevalidateInCachedFunctionError","createRevalidateDuringRenderError","error","abortAndThrowOnSynchronousRequestDataAccess","InvariantError","err","DynamicServerError","dynamicUsageDescription","dynamicUsageStack","stack","pendingRevalidatedTags","revalidatedAt","performance","timeOrigin","now","existingIndex","findIndex","item","cacheLife","cacheLifeProfiles","expire","ActionDidRevalidate"],"mappings":";;;;;;;;;;;;;;;;;IAkFgBA,OAAO;e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,KAAKA,KAAK,OAAO;YAC7B,kEAAkE;YAClE,IAAI,OAAOuD,KAAKtD,OAAO,KAAK,YAAY,OAAOA,YAAY,UAAU;gBACnE,OAAOsD,KAAKtD,OAAO,KAAKA;YAC1B;YACA,IAAI,OAAOsD,KAAKtD,OAAO,KAAK,YAAY,OAAOA,YAAY,UAAU;gBACnE,OAAOO,KAAKC,SAAS,CAAC8C,KAAKtD,OAAO,MAAMO,KAAKC,SAAS,CAACR;YACzD;YACA,OAAOsD,KAAKtD,OAAO,KAAKA;QAC1B;QACA,IAAIoD,kBAAkB,CAAC,GAAG;YACxBpB,MAAMe,sBAAsB,CAACjB,IAAI,CAAC;gBAChC/B;gBACAC;gBACAgD;YACF;QACF,OAAO;YACL,yEAAyE;YACzE,oEAAoE;YACpE,SAAS;YACThB,MAAMe,sBAAsB,CAACK,cAAc,CAACJ,aAAa,GAAGA;QAC9D;IACF;IAEA,8DAA8D;IAC9D,+DAA+D;IAC/D,sCAAsC;IACtC,MAAMO,YACJvD,WAAW,OAAOA,YAAY,WAC1BA,UACAA,WACE,OAAOA,YAAY,aACnBgC,yBAAAA,MAAOwB,iBAAiB,CAACxD,QAAQ,IACjCgC,MAAMwB,iBAAiB,CAACxD,QAAQ,GAChCe;IAER,IAAI,CAACf,WAAWuD,CAAAA,6BAAAA,UAAWE,MAAM,MAAK,GAAG;QACvC,4CAA4C;QAC5CzB,MAAMb,kBAAkB,GAAGuC,2DAAmB;IAChD;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-cache.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-cache.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ad2c4a7e721482375c5640c70378bed90a4a815 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-cache.d.ts @@ -0,0 +1,14 @@ +type Callback = (...args: any[]) => Promise; +/** + * This function allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests. + * + * Read more: [Next.js Docs: `unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache) + */ +export declare function unstable_cache(cb: T, keyParts?: string[], options?: { + /** + * The revalidation interval in seconds. + */ + revalidate?: number | false; + tags?: string[]; +}): T; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-cache.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-cache.js new file mode 100644 index 0000000000000000000000000000000000000000..9aa57b8091fc225397a3b9509c228bc75f7cd8ef --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-cache.js @@ -0,0 +1,299 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "unstable_cache", { + enumerable: true, + get: function() { + return unstable_cache; + } +}); +const _constants = require("../../../lib/constants"); +const _patchfetch = require("../../lib/patch-fetch"); +const _encodeheadersafe = require("../../lib/encode-header-safe"); +const _workasyncstorageexternal = require("../../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external"); +const _responsecache = require("../../response-cache"); +let noStoreFetchIdx = 0; +async function cacheNewResult(result, incrementalCache, cacheKey, tags, revalidate, fetchIdx, fetchUrl) { + await incrementalCache.set(cacheKey, { + kind: _responsecache.CachedRouteKind.FETCH, + data: { + headers: {}, + // TODO: handle non-JSON values? + body: JSON.stringify(result), + status: 200, + url: '' + }, + revalidate: typeof revalidate !== 'number' ? _constants.CACHE_ONE_YEAR_SECONDS : revalidate + }, { + fetchCache: true, + tags, + fetchIdx, + fetchUrl + }); + return; +} +function unstable_cache(cb, keyParts, options = {}) { + if (options.revalidate === 0) { + throw new Error(`Invariant revalidate: 0 can not be passed to unstable_cache(), must be "false" or "> 0" ${cb.toString()}`); + } + // Validate the tags provided are valid + const tags = options.tags ? (0, _patchfetch.validateTags)(options.tags, `unstable_cache ${cb.toString()}`) : []; + // Validate the revalidate option, and adopt the normalized value, which + // maps `false` and `Infinity` to INFINITE_CACHE so that the stored value + // survives JSON serialization. + const revalidate = (0, _patchfetch.validateRevalidate)(options.revalidate, `unstable_cache ${cb.name || cb.toString()}`); + // Stash the fixed part of the key at construction time. The invocation key will combine + // the fixed key with the arguments when actually called + // @TODO if cb.toString() is long we should hash it + // @TODO come up with a collision-free way to combine keyParts + // @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees + // and the error produced by accidentally using something that cannot be safely coerced is likely + // hard to debug + const fixedKey = `${cb.toString()}-${Array.isArray(keyParts) && keyParts.join(',')}`; + const cachedCb = async (...args)=>{ + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + // We must be able to find the incremental cache otherwise we throw + const maybeIncrementalCache = (workStore == null ? void 0 : workStore.incrementalCache) || globalThis.__incrementalCache; + if (!maybeIncrementalCache) { + throw new Error(`Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`); + } + const incrementalCache = maybeIncrementalCache; + const cacheSignal = workUnitStore ? (0, _workunitasyncstorageexternal.getCacheSignal)(workUnitStore) : null; + if (cacheSignal) { + cacheSignal.beginRead(); + } + try { + // If there's no request store, we aren't in a request (or we're not in + // app router) and if there's no static generation store, we aren't in app + // router. Default to an empty pathname and search params when there's no + // request store or static generation store available. + const fetchUrlPrefix = workStore && workUnitStore ? getFetchUrlPrefix(workStore, workUnitStore) : ''; + // Construct the complete cache key for this function invocation + // @TODO stringify is likely not safe here. We will coerce undefined to null which will make + // the keyspace smaller than the execution space + const invocationKey = `${fixedKey}-${JSON.stringify(args)}`; + const cacheKey = await incrementalCache.generateSimpleCacheKey(invocationKey); + // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse + // + // A cache implementation may serialize this name into an HTTP request + // header, so it is encoded here. Both parts can carry a character above + // U+00FF: the search parameters are decoded, and a JavaScript identifier + // may hold one. The character class leaves the separating spaces and the + // URL punctuation untouched, so the shape above is preserved. + // + // `toWellFormed` replaces lone surrogates, which `cb.name` can hold and + // which `encodeURIComponent` rejects. The name identifies the call for + // debug metrics, so a replacement character is an acceptable trade for + // not failing the render. + const fetchUrl = (0, _encodeheadersafe.encodeHeaderSafe)(`unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`.toWellFormed()); + const fetchIdx = (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1; + const implicitTags = workUnitStore == null ? void 0 : workUnitStore.implicitTags; + const innerCacheStore = { + type: 'unstable-cache', + phase: 'render', + consumerWillServerCache: true, + implicitTags, + draftMode: workUnitStore && workStore && (0, _workunitasyncstorageexternal.getDraftModeProviderForCacheScope)(workStore, workUnitStore), + rootParams: undefined + }; + if (workStore) { + workStore.nextFetchId = fetchIdx + 1; + // We are in an App Router context. We try to return the cached entry if it exists and is valid + // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in + // the background. If the entry is missing or invalid we generate a new entry and return it. + let isNestedUnstableCache = false; + if (workUnitStore) { + switch(workUnitStore.type){ + case 'cache': + case 'private-cache': + case 'prerender': + case 'prerender-runtime': + case 'prerender-legacy': + // We update the store's revalidate property if the revalidate option is a higher precedence + // revalidate === undefined doesn't affect timing. + // revalidate === INFINITE_CACHE (from `false` or `Infinity`) doesn't shrink timing. it stays at the maximum. + if (typeof revalidate === 'number') { + if (workUnitStore.revalidate < revalidate) { + // The store is already revalidating on a shorter time interval, leave it alone + } else { + workUnitStore.revalidate = revalidate; + } + } + // We need to accumulate the tags for this invocation within the store + const collectedTags = workUnitStore.tags; + if (collectedTags === null) { + workUnitStore.tags = tags.slice(); + } else { + for (const tag of tags){ + // @TODO refactor tags to be a set to avoid this O(n) lookup + if (!collectedTags.includes(tag)) { + collectedTags.push(tag); + } + } + } + break; + case 'unstable-cache': + isNestedUnstableCache = true; + break; + case 'prerender-client': + case 'validation-client': + case 'request': + case 'build-time-generator': + break; + default: + workUnitStore; + } + } + if (// when we are nested inside of other unstable_cache's + // we should bypass cache similar to fetches + !isNestedUnstableCache && workStore.fetchCache !== 'force-no-store' && !workStore.isOnDemandRevalidate && !incrementalCache.isOnDemandRevalidate && !workStore.isDraftMode) { + // We attempt to get the current cache entry from the incremental cache. + const cacheEntry = await incrementalCache.get(cacheKey, { + kind: _responsecache.IncrementalCacheKind.FETCH, + revalidate, + tags, + softTags: implicitTags == null ? void 0 : implicitTags.tags, + fetchIdx, + fetchUrl + }); + if (cacheEntry && cacheEntry.value) { + // The entry exists and has a value + if (cacheEntry.value.kind !== _responsecache.CachedRouteKind.FETCH) { + // The entry is invalid and we need a special warning + // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced + // so bugs can be reported + // @TODO the invocation key can have sensitive data in it. we should not log this entire object + console.error(`Invariant invalid cacheEntry returned for ${invocationKey}`); + // will fall through to generating a new cache entry below + } else { + // We have a valid cache entry so we will be returning it. We also check to see if we need + // to background revalidate it by checking if it is stale. + const cachedResponse = cacheEntry.value.data.body !== undefined ? JSON.parse(cacheEntry.value.data.body) : undefined; + if (cacheEntry.isStale) { + if (!workStore.pendingRevalidates) { + workStore.pendingRevalidates = {}; + } + // Check if there's already a pending revalidation to avoid duplicate work + if (!workStore.pendingRevalidates[invocationKey]) { + // Create the revalidation promise + const revalidationPromise = _workunitasyncstorageexternal.workUnitAsyncStorage.run(innerCacheStore, cb, ...args).then(async (result)=>{ + await cacheNewResult(result, incrementalCache, cacheKey, tags, revalidate, fetchIdx, fetchUrl); + return result; + }).catch((err)=>{ + // @TODO This error handling seems wrong. We swallow the error? + console.error(`revalidating cache with key: ${invocationKey}`, err); + // Return the stale value on error for foreground revalidation + return cachedResponse; + }); + // Attach the empty catch here so we don't get a "unhandled promise + // rejection" warning. (Behavior is matched with patch-fetch) + if ((0, _workunitasyncstorageexternal.willConsumerServerCache)(workUnitStore)) { + revalidationPromise.catch(()=>{}); + } + workStore.pendingRevalidates[invocationKey] = revalidationPromise; + } + // Check if we need to do foreground revalidation + if ((0, _workunitasyncstorageexternal.willConsumerServerCache)(workUnitStore)) { + // When the consumer will persist this result in a server + // cache, wait for fresh data so it doesn't persist a stale + // value. The `await` here also keeps `cacheSignal.endRead` (in + // the outer `finally`) suspended until the recompute + + // cacheNewResult actually complete, so a prospective + // prerender's `cacheSignal` doesn't resolve `cacheReady` + // prematurely. + return await workStore.pendingRevalidates[invocationKey]; + } + // Otherwise, we're doing background revalidation - return stale immediately + } + // We had a valid cache entry so we return it here + return cachedResponse; + } + } + } + // If we got this far then we had an invalid cache entry and need to generate a new one + const result = await _workunitasyncstorageexternal.workUnitAsyncStorage.run(innerCacheStore, cb, ...args); + if (!workStore.isDraftMode) { + if (!workStore.pendingRevalidates) { + workStore.pendingRevalidates = {}; + } + // We need to push the cache result promise to pending + // revalidates otherwise it won't be awaited and is just + // dangling + workStore.pendingRevalidates[invocationKey] = cacheNewResult(result, incrementalCache, cacheKey, tags, revalidate, fetchIdx, fetchUrl); + } + return result; + } else { + noStoreFetchIdx += 1; + // We are in Pages Router or were called outside of a render. We don't have a store + // so we just call the callback directly when it needs to run. + // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in + // the background. If the entry is missing or invalid we generate a new entry and return it. + if (!incrementalCache.isOnDemandRevalidate) { + // We aren't doing an on demand revalidation so we check use the cache if valid + const cacheEntry = await incrementalCache.get(cacheKey, { + kind: _responsecache.IncrementalCacheKind.FETCH, + revalidate, + tags, + fetchIdx, + fetchUrl, + softTags: implicitTags == null ? void 0 : implicitTags.tags + }); + if (cacheEntry && cacheEntry.value) { + // The entry exists and has a value + if (cacheEntry.value.kind !== _responsecache.CachedRouteKind.FETCH) { + // The entry is invalid and we need a special warning + // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced + // so bugs can be reported + console.error(`Invariant invalid cacheEntry returned for ${invocationKey}`); + // will fall through to generating a new cache entry below + } else if (!cacheEntry.isStale) { + // We have a valid cache entry and it is fresh so we return it + return cacheEntry.value.data.body !== undefined ? JSON.parse(cacheEntry.value.data.body) : undefined; + } + } + } + // If we got this far then we had an invalid cache entry and need to generate a new one + const result = await _workunitasyncstorageexternal.workUnitAsyncStorage.run(innerCacheStore, cb, ...args); + // we need to wait setting the new cache result here as + // we don't have pending revalidates on workStore to + // push to and we can't have a dangling promise + await cacheNewResult(result, incrementalCache, cacheKey, tags, revalidate, fetchIdx, fetchUrl); + return result; + } + } finally{ + if (cacheSignal) { + cacheSignal.endRead(); + } + } + }; + // TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary + return cachedCb; +} +function getFetchUrlPrefix(workStore, workUnitStore) { + switch(workUnitStore.type){ + case 'request': + const pathname = workUnitStore.url.pathname; + const searchParams = new URLSearchParams(workUnitStore.url.search); + const sortedSearch = [ + ...searchParams.keys() + ].sort((a, b)=>a.localeCompare(b)).map((key)=>`${key}=${searchParams.get(key)}`).join('&'); + return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`; + case 'prerender': + case 'prerender-client': + case 'validation-client': + case 'prerender-runtime': + case 'prerender-legacy': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + return workStore.route; + default: + return workUnitStore; + } +} + +//# sourceMappingURL=unstable-cache.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-cache.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-cache.js.map new file mode 100644 index 0000000000000000000000000000000000000000..25ff3fe672c8119fdb4fd3e30d259c9ee83a97c7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-cache.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/spec-extension/unstable-cache.ts"],"sourcesContent":["import type { IncrementalCache } from '../../lib/incremental-cache'\n\nimport { CACHE_ONE_YEAR_SECONDS } from '../../../lib/constants'\nimport { validateRevalidate, validateTags } from '../../lib/patch-fetch'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../../app-render/work-async-storage.external'\nimport {\n getCacheSignal,\n getDraftModeProviderForCacheScope,\n willConsumerServerCache,\n workUnitAsyncStorage,\n} from '../../app-render/work-unit-async-storage.external'\nimport {\n CachedRouteKind,\n IncrementalCacheKind,\n type CachedFetchData,\n} from '../../response-cache'\nimport type {\n UnstableCacheStore,\n WorkUnitStore,\n} from '../../app-render/work-unit-async-storage.external'\n\ntype Callback = (...args: any[]) => Promise\n\nlet noStoreFetchIdx = 0\n\nasync function cacheNewResult(\n result: T,\n incrementalCache: IncrementalCache,\n cacheKey: string,\n tags: string[],\n revalidate: number | false | undefined,\n fetchIdx: number,\n fetchUrl: string\n): Promise {\n await incrementalCache.set(\n cacheKey,\n {\n kind: CachedRouteKind.FETCH,\n data: {\n headers: {},\n // TODO: handle non-JSON values?\n body: JSON.stringify(result),\n status: 200,\n url: '',\n } satisfies CachedFetchData,\n revalidate:\n typeof revalidate !== 'number' ? CACHE_ONE_YEAR_SECONDS : revalidate,\n },\n { fetchCache: true, tags, fetchIdx, fetchUrl }\n )\n return\n}\n\n/**\n * This function allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.\n *\n * Read more: [Next.js Docs: `unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache)\n */\nexport function unstable_cache(\n cb: T,\n keyParts?: string[],\n options: {\n /**\n * The revalidation interval in seconds.\n */\n revalidate?: number | false\n tags?: string[]\n } = {}\n): T {\n if (options.revalidate === 0) {\n throw new Error(\n `Invariant revalidate: 0 can not be passed to unstable_cache(), must be \"false\" or \"> 0\" ${cb.toString()}`\n )\n }\n\n // Validate the tags provided are valid\n const tags = options.tags\n ? validateTags(options.tags, `unstable_cache ${cb.toString()}`)\n : []\n\n // Validate the revalidate option, and adopt the normalized value, which\n // maps `false` and `Infinity` to INFINITE_CACHE so that the stored value\n // survives JSON serialization.\n const revalidate = validateRevalidate(\n options.revalidate,\n `unstable_cache ${cb.name || cb.toString()}`\n )\n\n // Stash the fixed part of the key at construction time. The invocation key will combine\n // the fixed key with the arguments when actually called\n // @TODO if cb.toString() is long we should hash it\n // @TODO come up with a collision-free way to combine keyParts\n // @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees\n // and the error produced by accidentally using something that cannot be safely coerced is likely\n // hard to debug\n const fixedKey = `${cb.toString()}-${\n Array.isArray(keyParts) && keyParts.join(',')\n }`\n\n const cachedCb = async (...args: any[]) => {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // We must be able to find the incremental cache otherwise we throw\n const maybeIncrementalCache:\n | import('../../lib/incremental-cache').IncrementalCache\n | undefined =\n workStore?.incrementalCache || (globalThis as any).__incrementalCache\n\n if (!maybeIncrementalCache) {\n throw new Error(\n `Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`\n )\n }\n const incrementalCache = maybeIncrementalCache\n\n const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null\n if (cacheSignal) {\n cacheSignal.beginRead()\n }\n try {\n // If there's no request store, we aren't in a request (or we're not in\n // app router) and if there's no static generation store, we aren't in app\n // router. Default to an empty pathname and search params when there's no\n // request store or static generation store available.\n const fetchUrlPrefix =\n workStore && workUnitStore\n ? getFetchUrlPrefix(workStore, workUnitStore)\n : ''\n\n // Construct the complete cache key for this function invocation\n // @TODO stringify is likely not safe here. We will coerce undefined to null which will make\n // the keyspace smaller than the execution space\n const invocationKey = `${fixedKey}-${JSON.stringify(args)}`\n const cacheKey =\n await incrementalCache.generateSimpleCacheKey(invocationKey)\n // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse\n //\n // A cache implementation may serialize this name into an HTTP request\n // header, so it is encoded here. Both parts can carry a character above\n // U+00FF: the search parameters are decoded, and a JavaScript identifier\n // may hold one. The character class leaves the separating spaces and the\n // URL punctuation untouched, so the shape above is preserved.\n //\n // `toWellFormed` replaces lone surrogates, which `cb.name` can hold and\n // which `encodeURIComponent` rejects. The name identifies the call for\n // debug metrics, so a replacement character is an acceptable trade for\n // not failing the render.\n const fetchUrl = encodeHeaderSafe(\n `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`.toWellFormed()\n )\n const fetchIdx =\n (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1\n\n const implicitTags = workUnitStore?.implicitTags\n\n const innerCacheStore: UnstableCacheStore = {\n type: 'unstable-cache',\n phase: 'render',\n consumerWillServerCache: true,\n implicitTags,\n draftMode:\n workUnitStore &&\n workStore &&\n getDraftModeProviderForCacheScope(workStore, workUnitStore),\n rootParams: undefined,\n }\n\n if (workStore) {\n workStore.nextFetchId = fetchIdx + 1\n\n // We are in an App Router context. We try to return the cached entry if it exists and is valid\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n let isNestedUnstableCache = false\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-legacy':\n // We update the store's revalidate property if the revalidate option is a higher precedence\n // revalidate === undefined doesn't affect timing.\n // revalidate === INFINITE_CACHE (from `false` or `Infinity`) doesn't shrink timing. it stays at the maximum.\n if (typeof revalidate === 'number') {\n if (workUnitStore.revalidate < revalidate) {\n // The store is already revalidating on a shorter time interval, leave it alone\n } else {\n workUnitStore.revalidate = revalidate\n }\n }\n\n // We need to accumulate the tags for this invocation within the store\n const collectedTags = workUnitStore.tags\n if (collectedTags === null) {\n workUnitStore.tags = tags.slice()\n } else {\n for (const tag of tags) {\n // @TODO refactor tags to be a set to avoid this O(n) lookup\n if (!collectedTags.includes(tag)) {\n collectedTags.push(tag)\n }\n }\n }\n break\n case 'unstable-cache':\n isNestedUnstableCache = true\n break\n case 'prerender-client':\n case 'validation-client':\n case 'request':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (\n // when we are nested inside of other unstable_cache's\n // we should bypass cache similar to fetches\n !isNestedUnstableCache &&\n workStore.fetchCache !== 'force-no-store' &&\n !workStore.isOnDemandRevalidate &&\n !incrementalCache.isOnDemandRevalidate &&\n !workStore.isDraftMode\n ) {\n // We attempt to get the current cache entry from the incremental cache.\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n softTags: implicitTags?.tags,\n fetchIdx,\n fetchUrl,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n // @TODO the invocation key can have sensitive data in it. we should not log this entire object\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else {\n // We have a valid cache entry so we will be returning it. We also check to see if we need\n // to background revalidate it by checking if it is stale.\n const cachedResponse =\n cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n\n if (cacheEntry.isStale) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // Check if there's already a pending revalidation to avoid duplicate work\n if (!workStore.pendingRevalidates[invocationKey]) {\n // Create the revalidation promise\n const revalidationPromise = workUnitAsyncStorage\n .run(innerCacheStore, cb, ...args)\n .then(async (result) => {\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n })\n .catch((err) => {\n // @TODO This error handling seems wrong. We swallow the error?\n console.error(\n `revalidating cache with key: ${invocationKey}`,\n err\n )\n // Return the stale value on error for foreground revalidation\n return cachedResponse\n })\n\n // Attach the empty catch here so we don't get a \"unhandled promise\n // rejection\" warning. (Behavior is matched with patch-fetch)\n if (willConsumerServerCache(workUnitStore)) {\n revalidationPromise.catch(() => {})\n }\n\n workStore.pendingRevalidates[invocationKey] =\n revalidationPromise\n }\n\n // Check if we need to do foreground revalidation\n if (willConsumerServerCache(workUnitStore)) {\n // When the consumer will persist this result in a server\n // cache, wait for fresh data so it doesn't persist a stale\n // value. The `await` here also keeps `cacheSignal.endRead` (in\n // the outer `finally`) suspended until the recompute +\n // cacheNewResult actually complete, so a prospective\n // prerender's `cacheSignal` doesn't resolve `cacheReady`\n // prematurely.\n return await workStore.pendingRevalidates[invocationKey]\n }\n // Otherwise, we're doing background revalidation - return stale immediately\n }\n\n // We had a valid cache entry so we return it here\n return cachedResponse\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n if (!workStore.isDraftMode) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // We need to push the cache result promise to pending\n // revalidates otherwise it won't be awaited and is just\n // dangling\n workStore.pendingRevalidates[invocationKey] = cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n }\n\n return result\n } else {\n noStoreFetchIdx += 1\n // We are in Pages Router or were called outside of a render. We don't have a store\n // so we just call the callback directly when it needs to run.\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n if (!incrementalCache.isOnDemandRevalidate) {\n // We aren't doing an on demand revalidation so we check use the cache if valid\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n fetchIdx,\n fetchUrl,\n softTags: implicitTags?.tags,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else if (!cacheEntry.isStale) {\n // We have a valid cache entry and it is fresh so we return it\n return cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n // we need to wait setting the new cache result here as\n // we don't have pending revalidates on workStore to\n // push to and we can't have a dangling promise\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n }\n } finally {\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n }\n }\n // TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary\n return cachedCb as unknown as T\n}\n\nfunction getFetchUrlPrefix(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): string {\n switch (workUnitStore.type) {\n case 'request':\n const pathname = workUnitStore.url.pathname\n const searchParams = new URLSearchParams(workUnitStore.url.search)\n\n const sortedSearch = [...searchParams.keys()]\n .sort((a, b) => a.localeCompare(b))\n .map((key) => `${key}=${searchParams.get(key)}`)\n .join('&')\n\n return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n return workStore.route\n default:\n return workUnitStore satisfies never\n }\n}\n"],"names":["unstable_cache","noStoreFetchIdx","cacheNewResult","result","incrementalCache","cacheKey","tags","revalidate","fetchIdx","fetchUrl","set","kind","CachedRouteKind","FETCH","data","headers","body","JSON","stringify","status","url","CACHE_ONE_YEAR_SECONDS","fetchCache","cb","keyParts","options","Error","toString","validateTags","validateRevalidate","name","fixedKey","Array","isArray","join","cachedCb","args","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","maybeIncrementalCache","globalThis","__incrementalCache","cacheSignal","getCacheSignal","beginRead","fetchUrlPrefix","getFetchUrlPrefix","invocationKey","generateSimpleCacheKey","encodeHeaderSafe","toWellFormed","nextFetchId","implicitTags","innerCacheStore","type","phase","consumerWillServerCache","draftMode","getDraftModeProviderForCacheScope","rootParams","undefined","isNestedUnstableCache","collectedTags","slice","tag","includes","push","isOnDemandRevalidate","isDraftMode","cacheEntry","get","IncrementalCacheKind","softTags","value","console","error","cachedResponse","parse","isStale","pendingRevalidates","revalidationPromise","run","then","catch","err","willConsumerServerCache","endRead","pathname","searchParams","URLSearchParams","search","sortedSearch","keys","sort","a","b","localeCompare","map","key","length","route"],"mappings":";;;;+BA8DgBA;;;eAAAA;;;2BA5DuB;4BACU;kCAChB;0CAI1B;8CAMA;+BAKA;AAQP,IAAIC,kBAAkB;AAEtB,eAAeC,eACbC,MAAS,EACTC,gBAAkC,EAClCC,QAAgB,EAChBC,IAAc,EACdC,UAAsC,EACtCC,QAAgB,EAChBC,QAAgB;IAEhB,MAAML,iBAAiBM,GAAG,CACxBL,UACA;QACEM,MAAMC,8BAAe,CAACC,KAAK;QAC3BC,MAAM;YACJC,SAAS,CAAC;YACV,gCAAgC;YAChCC,MAAMC,KAAKC,SAAS,CAACf;YACrBgB,QAAQ;YACRC,KAAK;QACP;QACAb,YACE,OAAOA,eAAe,WAAWc,iCAAsB,GAAGd;IAC9D,GACA;QAAEe,YAAY;QAAMhB;QAAME;QAAUC;IAAS;IAE/C;AACF;AAOO,SAAST,eACduB,EAAK,EACLC,QAAmB,EACnBC,UAMI,CAAC,CAAC;IAEN,IAAIA,QAAQlB,UAAU,KAAK,GAAG;QAC5B,MAAM,IAAImB,MACR,CAAC,wFAAwF,EAAEH,GAAGI,QAAQ,IAAI;IAE9G;IAEA,uCAAuC;IACvC,MAAMrB,OAAOmB,QAAQnB,IAAI,GACrBsB,IAAAA,wBAAY,EAACH,QAAQnB,IAAI,EAAE,CAAC,eAAe,EAAEiB,GAAGI,QAAQ,IAAI,IAC5D,EAAE;IAEN,wEAAwE;IACxE,yEAAyE;IACzE,+BAA+B;IAC/B,MAAMpB,aAAasB,IAAAA,8BAAkB,EACnCJ,QAAQlB,UAAU,EAClB,CAAC,eAAe,EAA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AAEE,aAAa,CAACD,IAC/BE,GAAG,CAAC,CAACC,MAAQ,GAAGA,IAAI,CAAC,EAAEV,aAAalB,GAAG,CAAC4B,MAAM,EAC9CnE,IAAI,CAAC;YAER,OAAO,GAAGwD,WAAWI,aAAaQ,MAAM,GAAG,MAAM,KAAKR,cAAc;QACtE,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOzD,UAAUkE,KAAK;QACxB;YACE,OAAO/D;IACX;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-no-store.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-no-store.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e62ce3ce21178317761514c8ee7bb717c93438a8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-no-store.d.ts @@ -0,0 +1,16 @@ +/** + * This function can be used to declaratively opt out of static rendering and indicate a particular component should not be cached. + * + * It marks the current scope as dynamic. + * + * - In [non-PPR](https://nextjs.org/docs/app/api-reference/next-config-js/partial-prerendering) cases this will make a static render + * halt and mark the page as dynamic. + * - In PPR cases this will postpone the render at this location. + * + * If we are inside a cache scope then this function does nothing. + * + * @note It expects to be called within App Router and will error otherwise. + * + * Read more: [Next.js Docs: `unstable_noStore`](https://nextjs.org/docs/app/api-reference/functions/unstable_noStore) + */ +export declare function unstable_noStore(): void; diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-no-store.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-no-store.js new file mode 100644 index 0000000000000000000000000000000000000000..89e806182abee029d0575a86519d129909de97d4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-no-store.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "unstable_noStore", { + enumerable: true, + get: function() { + return unstable_noStore; + } +}); +const _workasyncstorageexternal = require("../../app-render/work-async-storage.external"); +const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external"); +const _dynamicrendering = require("../../app-render/dynamic-rendering"); +function unstable_noStore() { + const callingExpression = 'unstable_noStore()'; + const store = _workasyncstorageexternal.workAsyncStorage.getStore(); + const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); + if (!store) { + // This generally implies we are being called in Pages router. We should probably not support + // unstable_noStore in contexts outside of `react-server` condition but since we historically + // have not errored here previously, we maintain that behavior for now. + return; + } else if (store.forceStatic) { + return; + } else { + store.isUnstableNoStore = true; + if (workUnitStore) { + switch(workUnitStore.type){ + case 'prerender': + case 'prerender-client': + case 'validation-client': + case 'prerender-runtime': + // unstable_noStore() is a noop in Dynamic I/O. + return; + case 'prerender-legacy': + case 'request': + case 'cache': + case 'private-cache': + case 'unstable-cache': + case 'build-time-generator': + break; + default: + workUnitStore; + } + } + (0, _dynamicrendering.markCurrentScopeAsDynamic)(store, workUnitStore, callingExpression); + } +} + +//# sourceMappingURL=unstable-no-store.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-no-store.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-no-store.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ebaaaf2534d82bd8b42a8ca9d7ee0b9d1583fc78 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/unstable-no-store.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/spec-extension/unstable-no-store.ts"],"sourcesContent":["import { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'\n\n/**\n * This function can be used to declaratively opt out of static rendering and indicate a particular component should not be cached.\n *\n * It marks the current scope as dynamic.\n *\n * - In [non-PPR](https://nextjs.org/docs/app/api-reference/next-config-js/partial-prerendering) cases this will make a static render\n * halt and mark the page as dynamic.\n * - In PPR cases this will postpone the render at this location.\n *\n * If we are inside a cache scope then this function does nothing.\n *\n * @note It expects to be called within App Router and will error otherwise.\n *\n * Read more: [Next.js Docs: `unstable_noStore`](https://nextjs.org/docs/app/api-reference/functions/unstable_noStore)\n */\nexport function unstable_noStore() {\n const callingExpression = 'unstable_noStore()'\n const store = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!store) {\n // This generally implies we are being called in Pages router. We should probably not support\n // unstable_noStore in contexts outside of `react-server` condition but since we historically\n // have not errored here previously, we maintain that behavior for now.\n return\n } else if (store.forceStatic) {\n return\n } else {\n store.isUnstableNoStore = true\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n // unstable_noStore() is a noop in Dynamic I/O.\n return\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'build-time-generator':\n break\n default:\n workUnitStore satisfies never\n }\n }\n markCurrentScopeAsDynamic(store, workUnitStore, callingExpression)\n }\n}\n"],"names":["unstable_noStore","callingExpression","store","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","forceStatic","isUnstableNoStore","type","markCurrentScopeAsDynamic"],"mappings":";;;;+BAmBgBA;;;eAAAA;;;0CAnBiB;8CACI;kCACK;AAiBnC,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,QAAQC,0CAAgB,CAACC,QAAQ;IACvC,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IACnD,IAAI,CAACF,OAAO;QACV,6FAA6F;QAC7F,6FAA6F;QAC7F,uEAAuE;QACvE;IACF,OAAO,IAAIA,MAAMK,WAAW,EAAE;QAC5B;IACF,OAAO;QACLL,MAAMM,iBAAiB,GAAG;QAC1B,IAAIH,eAAe;YACjB,OAAQA,cAAcI,IAAI;gBACxB,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBACH,+CAA+C;oBAC/C;gBACF,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;gBACL,KAAK;oBACH;gBACF;oBACEJ;YACJ;QACF;QACAK,IAAAA,2CAAyB,EAACR,OAAOG,eAAeJ;IAClD;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/url-pattern.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/url-pattern.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..098f7a2e427d80d5cbcb553983816d6a33c65405 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/url-pattern.d.ts @@ -0,0 +1,6 @@ +declare const GlobalURLPattern: { + new (input: URLPatternInput, baseURL: string | URL, options?: URLPatternOptions): URLPattern; + new (input?: URLPatternInput, options?: URLPatternOptions): URLPattern; + prototype: URLPattern; +} | undefined; +export { GlobalURLPattern as URLPattern }; diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/url-pattern.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/url-pattern.js new file mode 100644 index 0000000000000000000000000000000000000000..905a707095b386bf83ac45b5a57f54522d22cec7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/url-pattern.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "URLPattern", { + enumerable: true, + get: function() { + return GlobalURLPattern; + } +}); +const GlobalURLPattern = typeof URLPattern === 'undefined' ? undefined : URLPattern; + +//# sourceMappingURL=url-pattern.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/url-pattern.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/url-pattern.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b07328f6eceaca4ad2b61aae9af6471e24f42aac --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/url-pattern.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/spec-extension/url-pattern.ts"],"sourcesContent":["const GlobalURLPattern =\n typeof URLPattern === 'undefined' ? undefined : URLPattern\n\nexport { GlobalURLPattern as URLPattern }\n"],"names":["URLPattern","GlobalURLPattern","undefined"],"mappings":";;;;+BAG6BA;;;eAApBC;;;AAHT,MAAMA,mBACJ,OAAOD,eAAe,cAAcE,YAAYF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/user-agent.d.ts b/e-commerce/node_modules/next/dist/server/web/spec-extension/user-agent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eee028acde759aed7f1ea7f2d28609a4b3eea863 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/user-agent.d.ts @@ -0,0 +1,31 @@ +interface UserAgent { + isBot: boolean; + ua: string; + browser: { + name?: string; + version?: string; + major?: string; + }; + device: { + model?: string; + type?: string; + vendor?: string; + }; + engine: { + name?: string; + version?: string; + }; + os: { + name?: string; + version?: string; + }; + cpu: { + architecture?: string; + }; +} +export declare function isBot(input: string): boolean; +export declare function userAgentFromString(input: string | undefined): UserAgent; +export declare function userAgent({ headers }: { + headers: Headers; +}): UserAgent; +export {}; diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/user-agent.js b/e-commerce/node_modules/next/dist/server/web/spec-extension/user-agent.js new file mode 100644 index 0000000000000000000000000000000000000000..673179da3ba0be2e9a8885d3e078fdfd8142e949 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/user-agent.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + isBot: null, + userAgent: null, + userAgentFromString: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + isBot: function() { + return isBot; + }, + userAgent: function() { + return userAgent; + }, + userAgentFromString: function() { + return userAgentFromString; + } +}); +const _uaparserjs = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/ua-parser-js")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function isBot(input) { + return /Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Google-InspectionTool|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver|GPTBot/i.test(input); +} +function userAgentFromString(input) { + return { + ...(0, _uaparserjs.default)(input), + isBot: input === undefined ? false : isBot(input) + }; +} +function userAgent({ headers }) { + return userAgentFromString(headers.get('user-agent') || undefined); +} + +//# sourceMappingURL=user-agent.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/spec-extension/user-agent.js.map b/e-commerce/node_modules/next/dist/server/web/spec-extension/user-agent.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d08411fd93622cecfb41967f8e40b6369d6d9aee --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/spec-extension/user-agent.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/server/web/spec-extension/user-agent.ts"],"sourcesContent":["import parseua from 'next/dist/compiled/ua-parser-js'\n\ninterface UserAgent {\n isBot: boolean\n ua: string\n browser: {\n name?: string\n version?: string\n major?: string\n }\n device: {\n model?: string\n type?: string\n vendor?: string\n }\n engine: {\n name?: string\n version?: string\n }\n os: {\n name?: string\n version?: string\n }\n cpu: {\n architecture?: string\n }\n}\n\nexport function isBot(input: string): boolean {\n return /Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Google-InspectionTool|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver|GPTBot/i.test(\n input\n )\n}\n\nexport function userAgentFromString(input: string | undefined): UserAgent {\n return {\n ...parseua(input),\n isBot: input === undefined ? false : isBot(input),\n }\n}\n\nexport function userAgent({ headers }: { headers: Headers }): UserAgent {\n return userAgentFromString(headers.get('user-agent') || undefined)\n}\n"],"names":["isBot","userAgent","userAgentFromString","input","test","parseua","undefined","headers","get"],"mappings":";;;;;;;;;;;;;;;;IA4BgBA,KAAK;eAALA;;IAaAC,SAAS;eAATA;;IAPAC,mBAAmB;eAAnBA;;;mEAlCI;;;;;;AA4Bb,SAASF,MAAMG,KAAa;IACjC,OAAO,iXAAiXC,IAAI,CAC1XD;AAEJ;AAEO,SAASD,oBAAoBC,KAAyB;IAC3D,OAAO;QACL,GAAGE,IAAAA,mBAAO,EAACF,MAAM;QACjBH,OAAOG,UAAUG,YAAY,QAAQN,MAAMG;IAC7C;AACF;AAEO,SAASF,UAAU,EAAEM,OAAO,EAAwB;IACzD,OAAOL,oBAAoBK,QAAQC,GAAG,CAAC,iBAAiBF;AAC1D","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/types.d.ts b/e-commerce/node_modules/next/dist/server/web/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d49a7869b0181155c0244afa260fe17b950f173d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/types.d.ts @@ -0,0 +1,63 @@ +import type { ExperimentalConfig, I18NConfig } from '../config-shared'; +import type { NextRequest } from './spec-extension/request'; +import type { NextFetchEvent } from './spec-extension/fetch-event'; +import type { NextResponse } from './spec-extension/response'; +import type { CloneableBody } from '../body-streams'; +import type { OutgoingHttpHeaders } from 'http'; +import type { FetchMetrics } from '../base-http'; +import type { RequestMeta } from '../request-meta'; +/** + * @deprecated Use `ProxyConfig` instead. Middleware has been renamed to Proxy. + */ +export type { MiddlewareConfigInput as MiddlewareConfig } from '../../build/segment-config/middleware/middleware-config'; +export type { MiddlewareConfigInput as ProxyConfig } from '../../build/segment-config/middleware/middleware-config'; +export interface RequestData { + headers: OutgoingHttpHeaders; + method: string; + nextConfig?: { + basePath?: string; + i18n?: I18NConfig | null; + trailingSlash?: boolean; + experimental?: Pick; + }; + page?: { + name?: string; + params?: { + [key: string]: string | string[] | undefined; + }; + }; + url: string; + body?: ReadableStream; + signal: AbortSignal; + requestMeta?: RequestMeta; + /** passed in when running in edge runtime sandbox */ + waitUntil?: (promise: Promise) => void; +} +export type NodejsRequestData = Omit & { + body?: CloneableBody; +}; +export interface FetchEventResult { + response: Response; + waitUntil: Promise; + fetchMetrics?: FetchMetrics; +} +export type NextMiddlewareResult = NextResponse | Response | null | undefined | void; +/** + * Middleware allows you to run code before a request is completed. + * Then, based on the incoming request, you can modify the response + * by rewriting, redirecting, modifying the request or response headers, + * or responding directly. + * + * @deprecated Use `NextProxy` instead. Middleware has been renamed to Proxy. + * Read more: [Next.js Docs: Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware) + */ +export type NextMiddleware = (request: NextRequest, event: NextFetchEvent) => NextMiddlewareResult | Promise; +/** + * Proxy allows you to run code before a request is completed. + * Then, based on the incoming request, you can modify the response + * by rewriting, redirecting, modifying the request or response headers, + * or responding directly. + * + * Read more: [Next.js Docs: Proxy](https://nextjs.org/docs/app/building-your-application/routing/middleware) + */ +export type NextProxy = NextMiddleware; diff --git a/e-commerce/node_modules/next/dist/server/web/types.js b/e-commerce/node_modules/next/dist/server/web/types.js new file mode 100644 index 0000000000000000000000000000000000000000..f89b9ccce54e89b62b432c4802c4612600a703d4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/types.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/types.js.map b/e-commerce/node_modules/next/dist/server/web/types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/types.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/utils.d.ts b/e-commerce/node_modules/next/dist/server/web/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b51f0068a4cd98d8ae251bb1626c1012f8f645d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/utils.d.ts @@ -0,0 +1,29 @@ +import type { OutgoingHttpHeaders } from 'http'; +/** + * Converts a Node.js IncomingHttpHeaders object to a Headers object. Any + * headers with multiple values will be joined with a comma and space. Any + * headers that have an undefined value will be ignored and others will be + * coerced to strings. + * + * @param nodeHeaders the headers object to convert + * @returns the converted headers object + */ +export declare function fromNodeOutgoingHttpHeaders(nodeHeaders: OutgoingHttpHeaders): Headers; +export declare function splitCookiesString(cookiesString: string): string[]; +/** + * Converts a Headers object to a Node.js OutgoingHttpHeaders object. This is + * required to support the set-cookie header, which may have multiple values. + * + * @param headers the headers object to convert + * @returns the converted headers object + */ +export declare function toNodeOutgoingHttpHeaders(headers: Headers): OutgoingHttpHeaders; +/** + * Validate the correctness of a user-provided URL. + */ +export declare function validateURL(url: string | URL): string; +/** + * Normalizes `nxtP` and `nxtI` query param values to remove the prefix. + * This function does not mutate the input key. + */ +export declare function normalizeNextQueryParam(key: string): null | string; diff --git a/e-commerce/node_modules/next/dist/server/web/utils.js b/e-commerce/node_modules/next/dist/server/web/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..2faf9ce2a159b0205bc1da25e6f3132542e2aa75 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/utils.js @@ -0,0 +1,147 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + fromNodeOutgoingHttpHeaders: null, + normalizeNextQueryParam: null, + splitCookiesString: null, + toNodeOutgoingHttpHeaders: null, + validateURL: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + fromNodeOutgoingHttpHeaders: function() { + return fromNodeOutgoingHttpHeaders; + }, + normalizeNextQueryParam: function() { + return normalizeNextQueryParam; + }, + splitCookiesString: function() { + return splitCookiesString; + }, + toNodeOutgoingHttpHeaders: function() { + return toNodeOutgoingHttpHeaders; + }, + validateURL: function() { + return validateURL; + } +}); +const _constants = require("../../lib/constants"); +function fromNodeOutgoingHttpHeaders(nodeHeaders) { + const headers = new Headers(); + for (let [key, value] of Object.entries(nodeHeaders)){ + const values = Array.isArray(value) ? value : [ + value + ]; + for (let v of values){ + if (typeof v === 'undefined') continue; + if (typeof v === 'number') { + v = v.toString(); + } + headers.append(key, v); + } + } + return headers; +} +function splitCookiesString(cookiesString) { + var cookiesStrings = []; + var pos = 0; + var start; + var ch; + var lastComma; + var nextStart; + var cookiesSeparatorFound; + function skipWhitespace() { + while(pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))){ + pos += 1; + } + return pos < cookiesString.length; + } + function notSpecialChar() { + ch = cookiesString.charAt(pos); + return ch !== '=' && ch !== ';' && ch !== ','; + } + while(pos < cookiesString.length){ + start = pos; + cookiesSeparatorFound = false; + while(skipWhitespace()){ + ch = cookiesString.charAt(pos); + if (ch === ',') { + // ',' is a cookie separator if we have later first '=', not ';' or ',' + lastComma = pos; + pos += 1; + skipWhitespace(); + nextStart = pos; + while(pos < cookiesString.length && notSpecialChar()){ + pos += 1; + } + // currently special character + if (pos < cookiesString.length && cookiesString.charAt(pos) === '=') { + // we found cookies separator + cookiesSeparatorFound = true; + // pos is inside the next cookie, so back up and return it. + pos = nextStart; + cookiesStrings.push(cookiesString.substring(start, lastComma)); + start = pos; + } else { + // in param ',' or param separator ';', + // we continue from that comma + pos = lastComma + 1; + } + } else { + pos += 1; + } + } + if (!cookiesSeparatorFound || pos >= cookiesString.length) { + cookiesStrings.push(cookiesString.substring(start, cookiesString.length)); + } + } + return cookiesStrings; +} +function toNodeOutgoingHttpHeaders(headers) { + const nodeHeaders = {}; + const cookies = []; + if (headers) { + for (const [key, value] of headers.entries()){ + if (key.toLowerCase() === 'set-cookie') { + // We may have gotten a comma joined string of cookies, or multiple + // set-cookie headers. We need to merge them into one header array + // to represent all the cookies. + cookies.push(...splitCookiesString(value)); + nodeHeaders[key] = cookies.length === 1 ? cookies[0] : cookies; + } else { + nodeHeaders[key] = value; + } + } + } + return nodeHeaders; +} +function validateURL(url) { + try { + return String(new URL(String(url))); + } catch (error) { + throw new Error(`URL is malformed "${String(url)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`, { + cause: error + }); + } +} +function normalizeNextQueryParam(key) { + const prefixes = [ + _constants.NEXT_QUERY_PARAM_PREFIX, + _constants.NEXT_INTERCEPTION_MARKER_PREFIX + ]; + for (const prefix of prefixes){ + if (key !== prefix && key.startsWith(prefix)) { + return key.substring(prefix.length); + } + } + return null; +} + +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/utils.js.map b/e-commerce/node_modules/next/dist/server/web/utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bbcb484a8abafa564794b0529fd4c2a5f3e2a4b0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/web/utils.ts"],"sourcesContent":["import type { OutgoingHttpHeaders } from 'http'\nimport {\n NEXT_INTERCEPTION_MARKER_PREFIX,\n NEXT_QUERY_PARAM_PREFIX,\n} from '../../lib/constants'\n\n/**\n * Converts a Node.js IncomingHttpHeaders object to a Headers object. Any\n * headers with multiple values will be joined with a comma and space. Any\n * headers that have an undefined value will be ignored and others will be\n * coerced to strings.\n *\n * @param nodeHeaders the headers object to convert\n * @returns the converted headers object\n */\nexport function fromNodeOutgoingHttpHeaders(\n nodeHeaders: OutgoingHttpHeaders\n): Headers {\n const headers = new Headers()\n for (let [key, value] of Object.entries(nodeHeaders)) {\n const values = Array.isArray(value) ? value : [value]\n for (let v of values) {\n if (typeof v === 'undefined') continue\n if (typeof v === 'number') {\n v = v.toString()\n }\n\n headers.append(key, v)\n }\n }\n return headers\n}\n\n/*\n Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas\n that are within a single set-cookie field-value, such as in the Expires portion.\n This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2\n Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128\n React Native's fetch does this for *every* header, including set-cookie.\n \n Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25\n Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation\n*/\nexport function splitCookiesString(cookiesString: string) {\n var cookiesStrings = []\n var pos = 0\n var start\n var ch\n var lastComma\n var nextStart\n var cookiesSeparatorFound\n\n function skipWhitespace() {\n while (pos < cookiesString.length && /\\s/.test(cookiesString.charAt(pos))) {\n pos += 1\n }\n return pos < cookiesString.length\n }\n\n function notSpecialChar() {\n ch = cookiesString.charAt(pos)\n\n return ch !== '=' && ch !== ';' && ch !== ','\n }\n\n while (pos < cookiesString.length) {\n start = pos\n cookiesSeparatorFound = false\n\n while (skipWhitespace()) {\n ch = cookiesString.charAt(pos)\n if (ch === ',') {\n // ',' is a cookie separator if we have later first '=', not ';' or ','\n lastComma = pos\n pos += 1\n\n skipWhitespace()\n nextStart = pos\n\n while (pos < cookiesString.length && notSpecialChar()) {\n pos += 1\n }\n\n // currently special character\n if (pos < cookiesString.length && cookiesString.charAt(pos) === '=') {\n // we found cookies separator\n cookiesSeparatorFound = true\n // pos is inside the next cookie, so back up and return it.\n pos = nextStart\n cookiesStrings.push(cookiesString.substring(start, lastComma))\n start = pos\n } else {\n // in param ',' or param separator ';',\n // we continue from that comma\n pos = lastComma + 1\n }\n } else {\n pos += 1\n }\n }\n\n if (!cookiesSeparatorFound || pos >= cookiesString.length) {\n cookiesStrings.push(cookiesString.substring(start, cookiesString.length))\n }\n }\n\n return cookiesStrings\n}\n\n/**\n * Converts a Headers object to a Node.js OutgoingHttpHeaders object. This is\n * required to support the set-cookie header, which may have multiple values.\n *\n * @param headers the headers object to convert\n * @returns the converted headers object\n */\nexport function toNodeOutgoingHttpHeaders(\n headers: Headers\n): OutgoingHttpHeaders {\n const nodeHeaders: OutgoingHttpHeaders = {}\n const cookies: string[] = []\n if (headers) {\n for (const [key, value] of headers.entries()) {\n if (key.toLowerCase() === 'set-cookie') {\n // We may have gotten a comma joined string of cookies, or multiple\n // set-cookie headers. We need to merge them into one header array\n // to represent all the cookies.\n cookies.push(...splitCookiesString(value))\n nodeHeaders[key] = cookies.length === 1 ? cookies[0] : cookies\n } else {\n nodeHeaders[key] = value\n }\n }\n }\n return nodeHeaders\n}\n\n/**\n * Validate the correctness of a user-provided URL.\n */\nexport function validateURL(url: string | URL): string {\n try {\n return String(new URL(String(url)))\n } catch (error: any) {\n throw new Error(\n `URL is malformed \"${String(\n url\n )}\". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`,\n { cause: error }\n )\n }\n}\n\n/**\n * Normalizes `nxtP` and `nxtI` query param values to remove the prefix.\n * This function does not mutate the input key.\n */\nexport function normalizeNextQueryParam(key: string): null | string {\n const prefixes = [NEXT_QUERY_PARAM_PREFIX, NEXT_INTERCEPTION_MARKER_PREFIX]\n for (const prefix of prefixes) {\n if (key !== prefix && key.startsWith(prefix)) {\n return key.substring(prefix.length)\n }\n }\n return null\n}\n"],"names":["fromNodeOutgoingHttpHeaders","normalizeNextQueryParam","splitCookiesString","toNodeOutgoingHttpHeaders","validateURL","nodeHeaders","headers","Headers","key","value","Object","entries","values","Array","isArray","v","toString","append","cookiesString","cookiesStrings","pos","start","ch","lastComma","nextStart","cookiesSeparatorFound","skipWhitespace","length","test","charAt","notSpecialChar","push","substring","cookies","toLowerCase","url","String","URL","error","Error","cause","prefixes","NEXT_QUERY_PARAM_PREFIX","NEXT_INTERCEPTION_MARKER_PREFIX","prefix","startsWith"],"mappings":";;;;;;;;;;;;;;;;;;IAegBA,2BAA2B;eAA3BA;;IA8IAC,uBAAuB;eAAvBA;;IAlHAC,kBAAkB;eAAlBA;;IAyEAC,yBAAyB;eAAzBA;;IAwBAC,WAAW;eAAXA;;;2BAxIT;AAWA,SAASJ,4BACdK,WAAgC;IAEhC,MAAMC,UAAU,IAAIC;IACpB,KAAK,IAAI,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACN,aAAc;QACpD,MAAMO,SAASC,MAAMC,OAAO,CAACL,SAASA,QAAQ;YAACA;SAAM;QACrD,KAAK,IAAIM,KAAKH,OAAQ;YACpB,IAAI,OAAOG,MAAM,aAAa;YAC9B,IAAI,OAAOA,MAAM,UAAU;gBACzBA,IAAIA,EAAEC,QAAQ;YAChB;YAEAV,QAAQW,MAAM,CAACT,KAAKO;QACtB;IACF;IACA,OAAOT;AACT;AAYO,SAASJ,mBAAmBgB,aAAqB;IACtD,IAAIC,iBAAiB,EAAE;IACvB,IAAIC,MAAM;IACV,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAEJ,SAASC;QACP,MAAON,MAAMF,cAAcS,MAAM,IAAI,KAAKC,IAAI,CAACV,cAAcW,MAAM,CAACT,MAAO;YACzEA,OAAO;QACT;QACA,OAAOA,MAAMF,cAAcS,MAAM;IACnC;IAEA,SAASG;QACPR,KAAKJ,cAAcW,MAAM,CAACT;QAE1B,OAAOE,OAAO,OAAOA,OAAO,OAAOA,OAAO;IAC5C;IAEA,MAAOF,MAAMF,cAAcS,MAAM,CAAE;QACjCN,QAAQD;QACRK,wBAAwB;QAExB,MAAOC,iBAAkB;YACvBJ,KAAKJ,cAAcW,MAAM,CAACT;YAC1B,IAAIE,OAAO,KAAK;gBACd,uEAAuE;gB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A4F,CAAC,EAC/F;YAAEK,OAAOF;QAAM;IAEnB;AACF;AAMO,SAASrC,wBAAwBO,GAAW;IACjD,MAAMiC,WAAW;QAACC,kCAAuB;QAAEC,0CAA+B;KAAC;IAC3E,KAAK,MAAMC,UAAUH,SAAU;QAC7B,IAAIjC,QAAQoC,UAAUpC,IAAIqC,UAAU,CAACD,SAAS;YAC5C,OAAOpC,IAAIwB,SAAS,CAACY,OAAOjB,MAAM;QACpC;IACF;IACA,OAAO;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/web-on-close.d.ts b/e-commerce/node_modules/next/dist/server/web/web-on-close.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ab58b30580bcdf2a26662cd515dea5ba7d0701a --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/web-on-close.d.ts @@ -0,0 +1,12 @@ +/** Monitor when the consumer finishes reading the response body. +that's as close as we can get to `res.on('close')` using web APIs. +*/ +export declare function trackBodyConsumed(body: string | ReadableStream, onEnd: () => void): BodyInit; +export declare function trackStreamConsumed(stream: ReadableStream, onEnd: () => void): ReadableStream; +export declare class CloseController { + private target; + listeners: number; + isClosed: boolean; + onClose(callback: () => void): void; + dispatchClose(): void; +} diff --git a/e-commerce/node_modules/next/dist/server/web/web-on-close.js b/e-commerce/node_modules/next/dist/server/web/web-on-close.js new file mode 100644 index 0000000000000000000000000000000000000000..7726dc02c5e3f8587fc9b6c7c80d71e90c2c892d --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/web-on-close.js @@ -0,0 +1,79 @@ +/** Monitor when the consumer finishes reading the response body. +that's as close as we can get to `res.on('close')` using web APIs. +*/ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + CloseController: null, + trackBodyConsumed: null, + trackStreamConsumed: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + CloseController: function() { + return CloseController; + }, + trackBodyConsumed: function() { + return trackBodyConsumed; + }, + trackStreamConsumed: function() { + return trackStreamConsumed; + } +}); +function trackBodyConsumed(body, onEnd) { + if (typeof body === 'string') { + const generator = async function* generate() { + const encoder = new TextEncoder(); + yield encoder.encode(body); + onEnd(); + }; + // @ts-expect-error BodyInit typings doesn't seem to include AsyncIterables even though it's supported in practice + return generator(); + } else { + return trackStreamConsumed(body, onEnd); + } +} +function trackStreamConsumed(stream, onEnd) { + // NOTE: This function must handle `stream` being aborted or cancelled, + // so it can't just be this: + // + // return stream.pipeThrough(new TransformStream({ flush() { onEnd() } })) + // + // because that doesn't handle cancellations. + // (and cancellation handling via `Transformer.cancel` is only available in node >20) + const dest = new TransformStream(); + const runOnEnd = ()=>onEnd(); + stream.pipeTo(dest.writable).then(runOnEnd, runOnEnd); + return dest.readable; +} +class CloseController { + onClose(callback) { + if (this.isClosed) { + throw new Error('Cannot subscribe to a closed CloseController'); + } + this.target.addEventListener('close', callback); + this.listeners++; + } + dispatchClose() { + if (this.isClosed) { + throw new Error('Cannot close a CloseController multiple times'); + } + if (this.listeners > 0) { + this.target.dispatchEvent(new Event('close')); + } + this.isClosed = true; + } + constructor(){ + this.target = new EventTarget(); + this.listeners = 0; + this.isClosed = false; + } +} + +//# sourceMappingURL=web-on-close.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/server/web/web-on-close.js.map b/e-commerce/node_modules/next/dist/server/web/web-on-close.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9e86049ff882c1a40511940306382a2ff1ef6aa2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/server/web/web-on-close.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/server/web/web-on-close.ts"],"sourcesContent":["/** Monitor when the consumer finishes reading the response body.\nthat's as close as we can get to `res.on('close')` using web APIs.\n*/\nexport function trackBodyConsumed(\n body: string | ReadableStream,\n onEnd: () => void\n): BodyInit {\n if (typeof body === 'string') {\n const generator = async function* generate() {\n const encoder = new TextEncoder()\n yield encoder.encode(body)\n onEnd()\n }\n // @ts-expect-error BodyInit typings doesn't seem to include AsyncIterables even though it's supported in practice\n return generator()\n } else {\n return trackStreamConsumed(body, onEnd)\n }\n}\n\nexport function trackStreamConsumed(\n stream: ReadableStream,\n onEnd: () => void\n): ReadableStream {\n // NOTE: This function must handle `stream` being aborted or cancelled,\n // so it can't just be this:\n //\n // return stream.pipeThrough(new TransformStream({ flush() { onEnd() } }))\n //\n // because that doesn't handle cancellations.\n // (and cancellation handling via `Transformer.cancel` is only available in node >20)\n const dest = new TransformStream()\n const runOnEnd = () => onEnd()\n stream.pipeTo(dest.writable).then(runOnEnd, runOnEnd)\n return dest.readable\n}\n\nexport class CloseController {\n private target = new EventTarget()\n listeners = 0\n isClosed = false\n\n onClose(callback: () => void) {\n if (this.isClosed) {\n throw new Error('Cannot subscribe to a closed CloseController')\n }\n\n this.target.addEventListener('close', callback)\n this.listeners++\n }\n\n dispatchClose() {\n if (this.isClosed) {\n throw new Error('Cannot close a CloseController multiple times')\n }\n if (this.listeners > 0) {\n this.target.dispatchEvent(new Event('close'))\n }\n this.isClosed = true\n }\n}\n"],"names":["CloseController","trackBodyConsumed","trackStreamConsumed","body","onEnd","generator","generate","encoder","TextEncoder","encode","stream","dest","TransformStream","runOnEnd","pipeTo","writable","then","readable","onClose","callback","isClosed","Error","target","addEventListener","listeners","dispatchClose","dispatchEvent","Event","EventTarget"],"mappings":"AAAA;;AAEA;;;;;;;;;;;;;;;;IAmCaA,eAAe;eAAfA;;IAlCGC,iBAAiB;eAAjBA;;IAiBAC,mBAAmB;eAAnBA;;;AAjBT,SAASD,kBACdE,IAA6B,EAC7BC,KAAiB;IAEjB,IAAI,OAAOD,SAAS,UAAU;QAC5B,MAAME,YAAY,gBAAgBC;YAChC,MAAMC,UAAU,IAAIC;YACpB,MAAMD,QAAQE,MAAM,CAACN;YACrBC;QACF;QACA,kHAAkH;QAClH,OAAOC;IACT,OAAO;QACL,OAAOH,oBAAoBC,MAAMC;IACnC;AACF;AAEO,SAASF,oBACdQ,MAA8B,EAC9BN,KAAiB;IAEjB,uEAAuE;IACvE,4BAA4B;IAC5B,EAAE;IACF,4EAA4E;IAC5E,EAAE;IACF,6CAA6C;IAC7C,qFAAqF;IACrF,MAAMO,OAAO,IAAIC;IACjB,MAAMC,WAAW,IAAMT;IACvBM,OAAOI,MAAM,CAACH,KAAKI,QAAQ,EAAEC,IAAI,CAACH,UAAUA;IAC5C,OAAOF,KAAKM,QAAQ;AACtB;AAEO,MAAMjB;IAKXkB,QAAQC,QAAoB,EAAE;QAC5B,IAAI,IAAI,CAACC,QAAQ,EAAE;YACjB,MAAM,IAAIC,MAAM;QAClB;QAEA,IAAI,CAACC,MAAM,CAACC,gBAAgB,CAAC,SAASJ;QACtC,IAAI,CAACK,SAAS;IAChB;IAEAC,gBAAgB;QACd,IAAI,IAAI,CAACL,QAAQ,EAAE;YACjB,MAAM,IAAIC,MAAM;QAClB;QACA,IAAI,IAAI,CAACG,SAAS,GAAG,GAAG;YACtB,IAAI,CAACF,MAAM,CAACI,aAAa,CAAC,IAAIC,MAAM;QACtC;QACA,IAAI,CAACP,QAAQ,GAAG;IAClB;;aArBQE,SAAS,IAAIM;aACrBJ,YAAY;aACZJ,WAAW;;AAoBb","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/action-revalidation-kind.d.ts b/e-commerce/node_modules/next/dist/shared/lib/action-revalidation-kind.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..88132d8dd03dad602a6cd56f83c769b49beae319 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/action-revalidation-kind.d.ts @@ -0,0 +1,4 @@ +export type ActionRevalidationKind = 0 | 1 | 2; +export declare const ActionDidNotRevalidate = 0; +export declare const ActionDidRevalidateStaticAndDynamic = 1; +export declare const ActionDidRevalidateDynamicOnly = 2; diff --git a/e-commerce/node_modules/next/dist/shared/lib/action-revalidation-kind.js b/e-commerce/node_modules/next/dist/shared/lib/action-revalidation-kind.js new file mode 100644 index 0000000000000000000000000000000000000000..c6b5715bffe7130ecfa9ffd6d4dee363d6812758 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/action-revalidation-kind.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + ActionDidNotRevalidate: null, + ActionDidRevalidateDynamicOnly: null, + ActionDidRevalidateStaticAndDynamic: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + ActionDidNotRevalidate: function() { + return ActionDidNotRevalidate; + }, + ActionDidRevalidateDynamicOnly: function() { + return ActionDidRevalidateDynamicOnly; + }, + ActionDidRevalidateStaticAndDynamic: function() { + return ActionDidRevalidateStaticAndDynamic; + } +}); +const ActionDidNotRevalidate = 0; +const ActionDidRevalidateStaticAndDynamic = 1; +const ActionDidRevalidateDynamicOnly = 2; + +//# sourceMappingURL=action-revalidation-kind.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/action-revalidation-kind.js.map b/e-commerce/node_modules/next/dist/shared/lib/action-revalidation-kind.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1d9df94e1fed2c7a72343d210e0c84f61c0153f1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/action-revalidation-kind.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/action-revalidation-kind.ts"],"sourcesContent":["export type ActionRevalidationKind = 0 | 1 | 2\n\nexport const ActionDidNotRevalidate = 0\nexport const ActionDidRevalidateStaticAndDynamic = 1\nexport const ActionDidRevalidateDynamicOnly = 2\n"],"names":["ActionDidNotRevalidate","ActionDidRevalidateDynamicOnly","ActionDidRevalidateStaticAndDynamic"],"mappings":";;;;;;;;;;;;;;;;IAEaA,sBAAsB;eAAtBA;;IAEAC,8BAA8B;eAA9BA;;IADAC,mCAAmC;eAAnCA;;;AADN,MAAMF,yBAAyB;AAC/B,MAAME,sCAAsC;AAC5C,MAAMD,iCAAiC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/app-dynamic.d.ts b/e-commerce/node_modules/next/dist/shared/lib/app-dynamic.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..033e97c33780e1a5d03189067c797b6a299e9ca2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/app-dynamic.d.ts @@ -0,0 +1,15 @@ +import type React from 'react'; +import type { JSX } from 'react'; +import type { LoadableGeneratedOptions, DynamicOptionsLoadingProps, Loader, LoaderComponent } from './lazy-dynamic/types'; +export { type LoadableGeneratedOptions, type DynamicOptionsLoadingProps, type Loader, type LoaderComponent, }; +export type DynamicOptions

= LoadableGeneratedOptions & { + loading?: () => JSX.Element | null; + loader?: Loader

; + loadableGenerated?: LoadableGeneratedOptions; + modules?: string[]; + ssr?: boolean; +}; +export type LoadableOptions

= DynamicOptions

; +export type LoadableFn

= (opts: LoadableOptions

) => React.ComponentType

; +export type LoadableComponent

= React.ComponentType

; +export default function dynamic

(dynamicOptions: DynamicOptions

| Loader

, options?: DynamicOptions

): React.ComponentType

; diff --git a/e-commerce/node_modules/next/dist/shared/lib/app-dynamic.js b/e-commerce/node_modules/next/dist/shared/lib/app-dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..68be534c349cf57fe9b44f549445c2148da7c39c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/app-dynamic.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return dynamic; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _loadable = /*#__PURE__*/ _interop_require_default._(require("./lazy-dynamic/loadable")); +function dynamic(dynamicOptions, options) { + const loadableOptions = {}; + if (typeof dynamicOptions === 'function') { + loadableOptions.loader = dynamicOptions; + } + const mergedOptions = { + ...loadableOptions, + ...options + }; + return (0, _loadable.default)({ + ...mergedOptions, + modules: mergedOptions.loadableGenerated?.modules + }); +} + +if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') { + Object.defineProperty(exports.default, '__esModule', { value: true }); + Object.assign(exports.default, exports); + module.exports = exports.default; +} + +//# sourceMappingURL=app-dynamic.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/app-dynamic.js.map b/e-commerce/node_modules/next/dist/shared/lib/app-dynamic.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9358c51a1c9a60d4231613f0e66662e739a51155 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/app-dynamic.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/app-dynamic.tsx"],"sourcesContent":["import type React from 'react'\nimport type { JSX } from 'react'\nimport Loadable from './lazy-dynamic/loadable'\n\nimport type {\n LoadableGeneratedOptions,\n DynamicOptionsLoadingProps,\n Loader,\n LoaderComponent,\n} from './lazy-dynamic/types'\n\nexport {\n type LoadableGeneratedOptions,\n type DynamicOptionsLoadingProps,\n type Loader,\n type LoaderComponent,\n}\n\nexport type DynamicOptions

= LoadableGeneratedOptions & {\n loading?: () => JSX.Element | null\n loader?: Loader

\n loadableGenerated?: LoadableGeneratedOptions\n modules?: string[]\n ssr?: boolean\n}\n\nexport type LoadableOptions

= DynamicOptions

\n\nexport type LoadableFn

= (\n opts: LoadableOptions

\n) => React.ComponentType

\n\nexport type LoadableComponent

= React.ComponentType

\n\nexport default function dynamic

(\n dynamicOptions: DynamicOptions

| Loader

,\n options?: DynamicOptions

\n): React.ComponentType

{\n const loadableOptions: LoadableOptions

= {}\n\n if (typeof dynamicOptions === 'function') {\n loadableOptions.loader = dynamicOptions\n }\n\n const mergedOptions = {\n ...loadableOptions,\n ...options,\n }\n\n return Loadable({\n ...mergedOptions,\n modules: mergedOptions.loadableGenerated?.modules,\n })\n}\n"],"names":["dynamic","dynamicOptions","options","loadableOptions","loader","mergedOptions","Loadable","modules","loadableGenerated"],"mappings":";;;;+BAkCA;;;eAAwBA;;;;mEAhCH;AAgCN,SAASA,QACtBC,cAA6C,EAC7CC,OAA2B;IAE3B,MAAMC,kBAAsC,CAAC;IAE7C,IAAI,OAAOF,mBAAmB,YAAY;QACxCE,gBAAgBC,MAAM,GAAGH;IAC3B;IAEA,MAAMI,gBAAgB;QACpB,GAAGF,eAAe;QAClB,GAAGD,OAAO;IACZ;IAEA,OAAOI,IAAAA,iBAAQ,EAAC;QACd,GAAGD,aAAa;QAChBE,SAASF,cAAcG,iBAAiB,EAAED;IAC5C;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/app-router-context.shared-runtime.d.ts b/e-commerce/node_modules/next/dist/shared/lib/app-router-context.shared-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f2c784faf06d2c60a20e9eafcbc80a19873f65d1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/app-router-context.shared-runtime.d.ts @@ -0,0 +1,92 @@ +import type { RouteTree } from '../../client/components/segment-cache/cache'; +import type { ScrollHandlerRef, PrefetchKind } from '../../client/components/router-reducer/router-reducer-types'; +import type { Params } from '../../server/request/params'; +import type { FlightRouterState, FlightSegmentPath, CacheNode, LoadingModuleData } from './app-router-types'; +import React from 'react'; +export interface NavigateOptions { + scroll?: boolean; + /** + * Transition types to apply when navigating. These types are passed to + * [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType) + * inside the navigation transition, enabling + * [``](https://react.dev/reference/react/ViewTransition) components + * to apply different animations based on the type of navigation. + */ + transitionTypes?: string[]; +} +export interface PrefetchOptions { + kind: PrefetchKind; + onInvalidate?: () => void; +} +export interface AppRouterInstance { + /** + * Navigate to the previous history entry. + */ + back(): void; + /** + * Navigate to the next history entry. + */ + forward(): void; + /** + * Refresh the current page. + */ + refresh(): void; + /** + * Navigate to the provided href. + * Pushes a new history entry. + */ + push(href: string, options?: NavigateOptions): void; + /** + * Navigate to the provided href. + * Replaces the current history entry. + */ + replace(href: string, options?: NavigateOptions): void; + /** + * Prefetch the provided href. + */ + prefetch(href: string, options?: PrefetchOptions): void; + /** + * Perform a gesture navigation using prefetched data. + * Only available when experimental.gestureTransition is enabled. + * @experimental + */ + experimental_gesturePush?(href: string, options?: NavigateOptions): void; + /** + * An opaque string identifier scoped to the current route segment. + * + * Changes when the surrounding segment is freshly created by a push or + * replace navigation. Stays the same for back/forward navigations, + * `router.refresh()`, and search-param/hash-only changes. + * + * Intended to be passed to a React `key` to opt out of state preservation + * on fresh navigations: + * + * ```tsx + *

+ * ``` + * + * In most cases, prefer resetting state explicitly in an event handler, or + * deriving a key from your data (e.g. a draft id from the server). Use + * `bfcacheId` only when those patterns aren't a fit. + */ + bfcacheId: string; +} +export declare const AppRouterContext: React.Context; +export declare const LayoutRouterContext: React.Context<{ + parentTree: FlightRouterState; + parentRenderTree: RouteTree; + parentSegmentPath: FlightSegmentPath | null; + parentParams: Params; + parentLoadingData: LoadingModuleData | null; + debugNameContext: string; + url: string; + isActive: boolean; +} | null>; +export declare const GlobalLayoutRouterContext: React.Context<{ + tree: FlightRouterState; + scrollRef: ScrollHandlerRef; + nextUrl: string | null; + previousNextUrl: string | null; +}>; +export declare const TemplateContext: React.Context; +export declare const MissingSlotContext: React.Context>; diff --git a/e-commerce/node_modules/next/dist/shared/lib/app-router-context.shared-runtime.js b/e-commerce/node_modules/next/dist/shared/lib/app-router-context.shared-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..b9fa390e862472f0a2f6e46e44d3ef68f6597490 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/app-router-context.shared-runtime.js @@ -0,0 +1,50 @@ +'use client'; +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + AppRouterContext: null, + GlobalLayoutRouterContext: null, + LayoutRouterContext: null, + MissingSlotContext: null, + TemplateContext: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + AppRouterContext: function() { + return AppRouterContext; + }, + GlobalLayoutRouterContext: function() { + return GlobalLayoutRouterContext; + }, + LayoutRouterContext: function() { + return LayoutRouterContext; + }, + MissingSlotContext: function() { + return MissingSlotContext; + }, + TemplateContext: function() { + return TemplateContext; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _react = /*#__PURE__*/ _interop_require_default._(require("react")); +const AppRouterContext = _react.default.createContext(null); +const LayoutRouterContext = _react.default.createContext(null); +const GlobalLayoutRouterContext = _react.default.createContext(null); +const TemplateContext = _react.default.createContext(null); +if (process.env.NODE_ENV !== 'production') { + AppRouterContext.displayName = 'AppRouterContext'; + LayoutRouterContext.displayName = 'LayoutRouterContext'; + GlobalLayoutRouterContext.displayName = 'GlobalLayoutRouterContext'; + TemplateContext.displayName = 'TemplateContext'; +} +const MissingSlotContext = _react.default.createContext(new Set()); + +//# sourceMappingURL=app-router-context.shared-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/app-router-context.shared-runtime.js.map b/e-commerce/node_modules/next/dist/shared/lib/app-router-context.shared-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..28815577986d8f17fe7b7d8ec6ee783d9ed9be38 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/app-router-context.shared-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/app-router-context.shared-runtime.ts"],"sourcesContent":["'use client'\n\nimport type { RouteTree } from '../../client/components/segment-cache/cache'\n\nimport type {\n ScrollHandlerRef,\n PrefetchKind,\n} from '../../client/components/router-reducer/router-reducer-types'\nimport type { Params } from '../../server/request/params'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n CacheNode,\n LoadingModuleData,\n} from './app-router-types'\nimport React from 'react'\n\nexport interface NavigateOptions {\n scroll?: boolean\n /**\n * Transition types to apply when navigating. These types are passed to\n * [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType)\n * inside the navigation transition, enabling\n * [``](https://react.dev/reference/react/ViewTransition) components\n * to apply different animations based on the type of navigation.\n */\n transitionTypes?: string[]\n}\n\nexport interface PrefetchOptions {\n kind: PrefetchKind\n onInvalidate?: () => void\n}\n\nexport interface AppRouterInstance {\n /**\n * Navigate to the previous history entry.\n */\n back(): void\n /**\n * Navigate to the next history entry.\n */\n forward(): void\n /**\n * Refresh the current page.\n */\n refresh(): void\n /**\n * Refresh the current page. Use in development only.\n * @internal\n */\n hmrRefresh(): void\n /**\n * Navigate to the provided href.\n * Pushes a new history entry.\n */\n push(href: string, options?: NavigateOptions): void\n /**\n * Navigate to the provided href.\n * Replaces the current history entry.\n */\n replace(href: string, options?: NavigateOptions): void\n /**\n * Prefetch the provided href.\n */\n prefetch(href: string, options?: PrefetchOptions): void\n /**\n * Perform a gesture navigation using prefetched data.\n * Only available when experimental.gestureTransition is enabled.\n * @experimental\n */\n experimental_gesturePush?(href: string, options?: NavigateOptions): void\n /**\n * An opaque string identifier scoped to the current route segment.\n *\n * Changes when the surrounding segment is freshly created by a push or\n * replace navigation. Stays the same for back/forward navigations,\n * `router.refresh()`, and search-param/hash-only changes.\n *\n * Intended to be passed to a React `key` to opt out of state preservation\n * on fresh navigations:\n *\n * ```tsx\n * \n * ```\n *\n * In most cases, prefer resetting state explicitly in an event handler, or\n * deriving a key from your data (e.g. a draft id from the server). Use\n * `bfcacheId` only when those patterns aren't a fit.\n */\n bfcacheId: string\n}\n\nexport const AppRouterContext = React.createContext(\n null\n)\nexport const LayoutRouterContext = React.createContext<{\n parentTree: FlightRouterState\n parentRenderTree: RouteTree\n parentSegmentPath: FlightSegmentPath | null\n parentParams: Params\n parentLoadingData: LoadingModuleData | null\n debugNameContext: string\n url: string\n isActive: boolean\n} | null>(null)\n\nexport const GlobalLayoutRouterContext = React.createContext<{\n tree: FlightRouterState\n scrollRef: ScrollHandlerRef\n nextUrl: string | null\n previousNextUrl: string | null\n}>(null as any)\n\nexport const TemplateContext = React.createContext(null as any)\n\nif (process.env.NODE_ENV !== 'production') {\n AppRouterContext.displayName = 'AppRouterContext'\n LayoutRouterContext.displayName = 'LayoutRouterContext'\n GlobalLayoutRouterContext.displayName = 'GlobalLayoutRouterContext'\n TemplateContext.displayName = 'TemplateContext'\n}\n\nexport const MissingSlotContext = React.createContext>(new Set())\n"],"names":["AppRouterContext","GlobalLayoutRouterContext","LayoutRouterContext","MissingSlotContext","TemplateContext","React","createContext","process","env","NODE_ENV","displayName","Set"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;IA6FaA,gBAAgB;eAAhBA;;IAcAC,yBAAyB;eAAzBA;;IAXAC,mBAAmB;eAAnBA;;IA2BAC,kBAAkB;eAAlBA;;IATAC,eAAe;eAAfA;;;;gEAnGK;AA8EX,MAAMJ,mBAAmBK,cAAK,CAACC,aAAa,CACjD;AAEK,MAAMJ,sBAAsBG,cAAK,CAACC,aAAa,CAS5C;AAEH,MAAML,4BAA4BI,cAAK,CAACC,aAAa,CAKzD;AAEI,MAAMF,kBAAkBC,cAAK,CAACC,aAAa,CAAkB;AAEpE,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCT,iBAAiBU,WAAW,GAAG;IAC/BR,oBAAoBQ,WAAW,GAAG;IAClCT,0BAA0BS,WAAW,GAAG;IACxCN,gBAAgBM,WAAW,GAAG;AAChC;AAEO,MAAMP,qBAAqBE,cAAK,CAACC,aAAa,CAAc,IAAIK","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/app-router-types.d.ts b/e-commerce/node_modules/next/dist/shared/lib/app-router-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c043e3e6ecedcb1371e11c027d8880623512928d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/app-router-types.d.ts @@ -0,0 +1,524 @@ +/** + * App Router types - Client-safe types for the Next.js App Router + * + * This file contains type definitions that can be safely imported + * by both client-side and server-side code without circular dependencies. + */ +import type React from 'react'; +export type LoadingModuleData = [React.JSX.Element, React.ReactNode, React.ReactNode] | null; +import type { VaryParams, VaryParamsIterable } from './segment-cache/vary-params-decoding'; +import type { FullTransportData, PartialTransportData } from './rsc-transport'; +/** viewport metadata node */ +export type HeadData = React.ReactNode; +/** + * Render state for a segment. Reuse this object while its data is unchanged; + * create a new one when a navigation replaces the segment's data. + */ +export type CacheNode = { + /** + * When rsc is not null, it represents the RSC data for the + * corresponding segment. + * + * `null` is a valid React Node but because segment data is always a + * component, we can use `null` to represent empty. When it is + * null, it represents missing data, and rendering should suspend. + */ + rsc: React.ReactNode; + /** + * Represents a static version of the segment that can be shown immediately, + * and may or may not contain dynamic holes. It's prefetched before a + * navigation occurs. + * + * During rendering, we will choose whether to render `rsc` or `prefetchRsc` + * with `useDeferredValue`. As with the `rsc` field, a value of `null` means + * no value was provided. In this case, the LayoutRouter will go straight to + * rendering the `rsc` value; if that one is also missing, it will suspend and + * trigger a lazy fetch. + */ + prefetchRsc: React.ReactNode; + /** + * The source of the params `rsc` depends on, from the response that + * produced it. Null when unknown: the data came from the segment cache, or + * from a render that didn't track params, or `rsc` is still pending — it + * is set alongside `rsc` when the response arrives. A navigation that only + * changes params this output did not depend on can keep rendering it. + */ + varyParams: VaryParams | null; + /** + * A shared mutable ref that tracks whether this segment should be scrolled + * to. All new segments created during a single navigation share the same + * ref. When any segment's scroll handler fires, it sets `current` to + * `false` so no other segment scrolls for the same navigation. + * + * `null` means this segment is not a scroll target (e.g., a reused shared + * layout segment). + */ + scrollRef: ScrollRef | null; + /** + * Globally-unique identifier minted from a monotonic counter when the + * CacheNode is freshly created. Surfaced to user code as a string via + * `useRouter().bfcacheId` and intended to be used as a React `key` to + * opt out of Activity-based state preservation on fresh navigations. + * + * Preserved when the CacheNode is reused (shared layouts, refresh, + * search/hash-only navigations) or restored from the BFCache during a + * back/forward navigation. + */ + bfcacheId: number; +}; +/** + * A mutable ref shared across all new segments created during a single + * navigation. Used to ensure that only one segment scrolls per navigation. + */ +export type ScrollRef = { + current: boolean; +}; +export type DynamicParamTypes = 'catchall' | 'catchall-intercepted-(..)(..)' | 'catchall-intercepted-(.)' | 'catchall-intercepted-(..)' | 'catchall-intercepted-(...)' | 'optional-catchall' | 'dynamic' | 'dynamic-intercepted-(..)(..)' | 'dynamic-intercepted-(.)' | 'dynamic-intercepted-(..)' | 'dynamic-intercepted-(...)'; +export type DynamicParamTypesShort = 'c' | 'ci(..)(..)' | 'ci(.)' | 'ci(..)' | 'ci(...)' | 'oc' | 'd' | 'di(..)(..)' | 'di(.)' | 'di(..)' | 'di(...)'; +export type DynamicSegmentTuple = [ + paramName: string, + paramCacheKey: string, + dynamicParamType: DynamicParamTypesShort, + staticSiblings: readonly string[] | null +]; +export type Segment = string | DynamicSegmentTuple; +/** + * Router state + */ +export type FlightRouterState = [ + segment: Segment, + parallelRoutes: { + [parallelRouterKey: string]: FlightRouterState; + }, + refreshState?: CompressedRefreshState | null, + /** + * - "refetch" is used during a request to inform the server where rendering + * should start from. + * + * - "inside-shared-layout" is used during a prefetch request to inform the + * server that even if the segment matches, it should be treated as if it's + * within the "new" part of a navigation — inside the shared layout. If + * the segment doesn't match, then it has no effect, since it would be + * treated as new regardless. If it does match, though, the server does not + * need to render it, because the client already has it. + * + * - "metadata-only" instructs the server to skip rendering the segments and + * only send the head data. + * + * A bit confusing, but that's because it has only one extremely narrow use + * case — during a non-PPR prefetch, the server uses it to find the first + * loading boundary beneath a shared layout. + * + * TODO: We should rethink the protocol for dynamic requests. It might not + * make sense for the client to send a FlightRouterState, since this type is + * overloaded with concerns. + */ + refresh?: 'refetch' | 'inside-shared-layout' | 'metadata-only' | null, + /** + * Bitmask of PrefetchHint flags. Encodes route structure metadata: + * root layout, loading boundaries, instant configs, and prefetch strategy + * hints. Only set when non-zero. JSON encodes an omitted slot as null when + * a later slot is present. + */ + prefetchHints?: number | null, + /** + * The rendered search params of a page segment. An empty string means there + * are none. Only set on page nodes, and left out of request headers. + * TODO: Revisit this as part of the larger FlightRouterState refactor. + */ + renderedSearch?: string +]; +/** + * When rendering a parallel route, some of the parallel paths may not match + * the current URL. In that case, the Next client has to render something, + * so it will render whichever was the last route to match that slot. We use + * this type to track when this has happened. It's a tuple of the original + * URL that was used to fetch the segment, and the (possibly rewritten) search + * query that was rendered by the server. The URL is needed when performing + * a refresh of the segment, and the search query is needed for looking up + * matching entries in the segment cache. + */ +export type CompressedRefreshState = [url: string, renderedSearch: string]; +export declare const enum PrefetchHint { + SubtreeHasPartialPrefetching = 2, + SegmentHasLoadingBoundary = 4, + SubtreeHasLoadingBoundary = 8, + IsRootLayoutOrAbove = 16, + ParentInlinedIntoSelf = 32, + InlinedIntoChild = 64, + HeadInlinedIntoSelf = 128, + HeadOutlined = 256, + InliningHintsStale = 512, + PrefetchDisabled = 1024, + SubtreeHasInstantFalse = 8192, + ShouldAttemptStaticShell = 16384, + ShouldAttemptStaticPrefetch = 32768, + IsClosedParam = 65536, + SubtreeHasClosedParams = 131072 +} +/** + * Bitmask for checking whether a segment's static prefetch is skipped — i.e. + * the server emits no static data for it (its node in a segment response + * carries identity only, and it participates in a bundle only as a + * pass-through) and the client never issues a static request for it. + * + * Static prefetching is disabled ONLY by `prefetch: 'force-disabled'` + * (PrefetchDisabled). Notably, Partial Prefetching segments DO have static + * data even though they can use runtime requests: the server emits it + * unconditionally — it can't be gated on the ShouldAttemptStatic{Shell,Prefetch} + * hints, because which segments carry static data must be deterministic + * from build-time config. A runtime request may still be needed for the + * segment, but the scheduler may attempt a static prefetch first (per the + * ShouldAttemptStatic{Shell,Prefetch} hints) and skip the runtime request if the + * static response proves sufficient. + * + * Usage: `(hints & StaticPrefetchDisabled) !== 0` + */ +export declare const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled; +export declare const StaticAttemptHints: number; +/** + * The subset of PrefetchHint bits that propagate upward from a child segment to + * its ancestors (as opposed to segment-local bits like SegmentHasLoadingBoundary + * or IsRootLayoutOrAbove). Used to clear stale propagated bits before re-deriving them + * from a node's children. + */ +export declare const SubtreePrefetchHints: number; +/** + * Folds a child segment's prefetch hints into its parent's, propagating the + * "subtree" flags. A child's segment-local flag (e.g. it has a loading + * boundary) becomes the corresponding "subtree" flag on the parent, so the + * root segment ends up reflecting the entire subtree. + * + * Used wherever a route tree is assembled bottom-up: on the server when building + * a transport tree (createTransportTreeFromLoaderTree) and on the client when + * overlaying a navigation response onto the existing tree + * (createNavigationSeed). Keep these in sync by routing both through + * this helper. + */ +export declare function propagateSubtreeBits(parentHints: number, childHints: number): number; +/** + * A path through the segment tree: a repeating sequence of segment and + * parallel route key. Used by the client to address positions in the + * render tree (see layout-router). + */ +export type FlightSegmentPath = any[] | [ + segment: Segment, + parallelRouterKey: string, + segment: Segment, + parallelRouterKey: string, + segment: Segment, + parallelRouterKey: string +]; +/** + * Per-route prefetch hints computed at build time. Mirrors the shape of the + * loader tree so hints can be traversed in parallel during router state + * creation. Each node stores a bitmask of PrefetchHint flags + * (ParentInlinedIntoSelf, InlinedIntoChild) computed by the segment size + * measurement pass. + * + * Persisted to prefetch-hints.json as Record (keyed + * by route pattern) and loaded at server startup. + */ +export type PrefetchHints = { + /** Bitmask of PrefetchHint flags for this segment. */ + hints: number; + /** Child hint nodes, keyed by parallel route key. */ + slots: Record | null; +}; +export type ActionResult = Promise; +export type InitialRSCPayload = { + /** buildId, can be empty if the x-nextjs-build-id header is set */ + b?: string; + /** initialCanonicalUrlParts */ + c: string[]; + /** initialRenderedSearch */ + q: string; + /** couldBeIntercepted */ + i: boolean; + /** initial transport data — the tree + head for hydration */ + t: FullTransportData; + /** missingSlots */ + m: Set | undefined; + /** GlobalError */ + G: [React.ComponentType, React.ReactNode | undefined]; + /** supportsPerSegmentPrefetching */ + S: boolean; + /** + * rootVaryParams - the root params accessed anywhere in the response, emitted + * once. The client unions these into the head and every segment's vary + * params, rather than the server folding them into each set. + */ + r?: VaryParamsIterable; + /** staleTime in seconds - Only present when Cache Components is enabled. */ + s?: AsyncIterable; + /** + * runtimeDataAccessed — whether the render has accessed a data source that + * hangs during a static prerender but would resolve during a runtime + * prerender (cookies, headers, fallback params, searchParams, ...). The + * flag is monotonic (false → true, at most once), so it's encoded as a + * promise: resolved `true` at the moment of first access — the fulfillment + * row's position in the stream records the stage the access happened in — + * or resolved `false` when the prerender completes without one, a row that + * lands past every stage boundary. A truncated (shell) decode therefore + * reads the answer as of the shell stage: fulfilled `true` iff the access + * happened during a stage it includes, pending (⇒ no access) otherwise. + * Unlike an async iterable, a pending promise costs Flight no abort + * listener on the render. Used when generating per-segment prefetch + * responses (forwarded as each response's own `u`). + * The build-time constant `PrefetchHint.ShouldAttemptStatic{Shell,Prefetch}` + * hint is tracked separately. + * Only present for static prerenders when Cache Components is enabled. + */ + u?: Promise; + /** staticStageByteLength - Resolves when the static stage ends. */ + l?: Promise; + /** + * shellByteLength - Resolves when the shell stage ends. + * If it resolves to null, then the shell is the same as the main response. + * */ + a?: Promise; + /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */ + p?: ReadableStream; + /** + * dynamicStaleTime — Per-page BFCache stale time in seconds, from + * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls + * how long the client router cache retains dynamic navigation data. This is + * distinct from the `s` field, which controls segment cache (prefetch) + * staleness. + */ + d?: number; + /** + * revealAfter (dev only). Resolves once the server has flushed the + * shell-stage content to the stream (static shell, or runtime-prefetchable + * shell for runtime-prefetch routes), or earlier on a cache miss. The client + * decodes this from the payload and defers resolving the response's deferred + * RSCs on it, so a boundary's children aren't revealed before their row has + * been decoded (which would flush a premature Suspense fallback). Its + * resolution row follows the children's row in the payload, so the children + * are decoded by the time the client unblocks. The HTML render gates on the + * same signal server-side instead of reading this field. + */ + _revealAfter?: Promise; +}; +/** + * The fields shared by every navigation/prefetch response kind. Not used + * directly — see NavigationFlightResponse (the general form) and the + * per-context aliases DynamicNavigationFlightResponse and + * PrefetchFlightResponse below. Fields that only apply to some response + * kinds are optional. + */ +type NavigationFlightResponseBase = { + /** buildId, can be empty if the x-nextjs-build-id header is set */ + b?: string; + /** + * transport data — present iff the response carries a SPA payload. + * Absent when the response renders nothing (see `n` for MPA navigations). + * + * In a per-segment prefetch response the tree is root-anchored with `d` + * present on exactly the segments whose data is bundled into the response + * (the requested segment and any ancestors inlined into it, per the + * build-time prefetch hints); the remaining nodes — the spine above the + * bundle, and segments with static prefetching disabled — carry identity + * but no data. Every node carries the same hints the `/_tree` response + * emits for it, so the tree decodes like any other transport tree. Data + * nodes use the staged encodings: `p` is a promise and `s` is present + * (see TransportSegmentData). The head (`h`) is present iff it's bundled + * into the response: the standalone head response (whose tree is a bare + * root identity), or a page response whose bundle accepted the head + * (PrefetchHint.HeadInlinedIntoSelf). + */ + t?: PartialTransportData; + /** + * MPA navigation URL — present iff the client should hard-navigate to + * this URL instead of applying a SPA payload. Reserved: no server path + * emits it today (hard navigations are signaled by non-RSC content types + * or a build-id mismatch), but the client honors it. + */ + n?: string; + /** staleTime - Only present in live-render responses. + * Per-segment prefetch responses carry staleTime per node instead (see + * TransportSegmentData). */ + s?: AsyncIterable; + /** staticStageByteLength - Resolves when the static stage ends. */ + l?: Promise; + /** + * shellByteLength - Resolves when the shell stage ends. + * If it resolves to null, then the shell is the same as the main response. + * + * In a per-segment prefetch response this is the shell byte boundary the + * client uses for the shell double-decode: re-decoding the buffered + * response truncated at the offset yields the shell variant of every + * segment (param-dependent content reduced to still-pending references). + * `0` means no shell exists (the page wasn't produced by staged + * rendering) — never a valid offset, so it doubles as the "none" + * sentinel. The resolution row flushes past the boundary, so a truncated + * shell decode reads it as pending, which is harmless. The client's + * buffered read leans on the same fact from the other side: 0 read from + * an unfulfilled `a` implies a bug — see the shell-extraction comment in + * fetchAndWritePerSegmentPrefetchResponse (segment-cache/cache.ts). + */ + a?: Promise; + /** + * needsRuntimeRequest — presence means the response carries a stage-scoped + * runtime-data verdict. Per-segment prefetch responses always emit one, + * and so does any prerendered page payload, which embeds the prerender's + * runtime-data probe — that covers navigation responses served from + * prerender output and the truncated initial payload alike. Live renders + * emit none. Only per-segment responses additionally promise-encode the + * head's partiality (see TransportSegmentData). The value is the page's + * runtime-data-access flag (the page payload's own `u`; per-segment + * responses forward it from the staged decode of the page data). + * Fulfilled `true` means a runtime prefetch would return more + * than this static response; pending or fulfilled `false` means it + * wouldn't. Promise-encoded so the answer rewinds with a truncated + * decode: the fulfillment row lands on the same side of the shell byte + * boundary (`a`) as the access it records. Tracking is page-global, so it + * lives on the response, not on each segment; per-segment granularity + * comes from combining it with each segment's partiality: + * needsRuntimeRequest(segment) = (settled true) && (isPartial pending). + * The derived value must never falsely claim that no runtime request is + * needed, so every fallback is conservative: pages that carry no `u` + * (legacy render paths) forward an already-resolved `true`. Unlike the + * build-constant prefetch hints, this is computed per render and may + * change between responses for the same build — it reflects THIS + * response. + */ + u?: Promise; + /** + * shellUsedSessionData — present only in runtime-shell prefetch + * responses: true if resolving session data unblocked new content in the + * shell. Only meaningful where there's a proper session shell. + * Promise-encoded so the answer rewinds with a truncated decode. + * Currently has no client consumer; emitted for forward compatibility. + */ + w?: Promise; + /** + * isUpgradeableISRFallback — present (true) iff this is a per-segment + * prefetch response generated from a fallback shell render (i.e. the page + * had not yet been prerendered with concrete params, so it was rendered + * with `fallbackRouteParams`). The client uses this to schedule a retry, + * since a more complete version may become available once the server's + * background regeneration finishes. + * + * Note: this is distinct from per-segment partiality. A fully-prerendered + * PPR page can have partial segments (dynamic holes filled by runtime + * requests); those should not be retried. This flag specifically means a + * more complete *static* version may become available. + */ + f?: boolean; + /** + * rootVaryParams - the root params accessed anywhere in the response, emitted + * once. The client unions these into the head and every segment's vary + * params. + */ + r?: VaryParamsIterable; + /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */ + p?: ReadableStream; + /** + * dynamicStaleTime — Per-page BFCache stale time in seconds, from + * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls + * how long the client router cache retains dynamic navigation data. This is + * distinct from the `s` field, which controls segment cache (prefetch) + * staleness. + */ + d?: number; + /** + * revealAfter (dev only). Resolves once the server has flushed the + * shell-stage content to the stream (static shell, or runtime-prefetchable + * shell for runtime-prefetch routes), or earlier on a cache miss. The client + * decodes this from the payload and defers resolving the response's deferred + * RSCs on it, so a boundary's children aren't revealed before their row has + * been decoded (which would flush a premature Suspense fallback). Its + * resolution row follows the children's row in the payload, so the children + * are decoded by the time the client unblocks. The HTML render gates on the + * same signal server-side instead of reading this field. + */ + _revealAfter?: Promise; +}; +/** + * A live-render response: navigations, refreshes, runtime prefetches, and + * dynamic route tree prefetches. Live renders always emit `S`, `q`, and `i`, + * so they're required here — used at the sites that produce these responses + * (app-render) and the decode sites that only ever receive them, so a + * malformed response fails the type rather than being masked by a fallback. + */ +export type DynamicNavigationFlightResponse = NavigationFlightResponseBase & { + /** + * supportsPerSegmentPrefetching — whether per-segment prefetch responses + * can be served for this route. + */ + S: boolean; + /** renderedSearch */ + q: string; + /** couldBeIntercepted */ + i: boolean; +}; +/** + * A per-segment prefetch response served from static storage: the `/_tree` + * route tree prefetch and the per-segment responses generated by + * collect-segment-data. Never carries `S` (implied by the response's + * existence), `q` (search-agnostic; the client writes these responses into + * the cache using the rendered search already recorded on the route tree + * entry), or `i` (the client reads the Vary header instead). Structurally + * the shared base — the alias marks the response kind at the sites that + * produce and decode it. + */ +export type PrefetchFlightResponse = NavigationFlightResponseBase; +/** + * The general form: a response that may be either kind, for the flows that + * handle both (the `/_tree` fetch, which receives a live render when + * per-segment prefetching is unsupported, and the shared cache-write path). + * Both aliases above are assignable to it. + */ +export type NavigationFlightResponse = NavigationFlightResponseBase & { + /** + * supportsPerSegmentPrefetching — present in live-render responses; + * absent in per-segment prefetch responses served from static storage + * (where it's implied by the response's existence). + */ + S?: boolean; + /** + * renderedSearch — present in live-render responses; absent in + * per-segment prefetch responses, which are search-agnostic (the client + * writes them into the cache using the rendered search already recorded + * on the route tree entry). + */ + q?: string; + /** + * couldBeIntercepted — present in live-render responses; absent in + * per-segment prefetch responses (the client reads the Vary header + * instead). + */ + i?: boolean; +}; +export type ActionFlightResponse = { + /** actionResult */ + a: ActionResult; + /** buildId, can be empty if the x-nextjs-build-id header is set */ + b?: string; + /** + * transport data — present iff the action response re-rendered the page. + * Absent when the action rendered nothing (see `n` for MPA navigations). + */ + t?: PartialTransportData; + /** + * MPA navigation URL — present iff the client should hard-navigate to + * this URL instead of applying a SPA payload. Reserved: no server path + * emits it today, but the client honors it. + */ + n?: string; + /** renderedSearch */ + q: string; + /** couldBeIntercepted */ + i: boolean; +}; +export type RSCPayload = InitialRSCPayload | NavigationFlightResponse | ActionFlightResponse; +export type InstantCookie = [captured: 0, id: string] | [captured: 1, id: string, state: null] | [ + captured: 1, + id: string, + state: { + from: FlightRouterState; + to: FlightRouterState | null; + } +]; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/app-router-types.js b/e-commerce/node_modules/next/dist/shared/lib/app-router-types.js new file mode 100644 index 0000000000000000000000000000000000000000..503b909f11ca4ee303a6dcf78e1ebf35f0b799a9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/app-router-types.js @@ -0,0 +1,169 @@ +/** + * App Router types - Client-safe types for the Next.js App Router + * + * This file contains type definitions that can be safely imported + * by both client-side and server-side code without circular dependencies. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + PrefetchHint: null, + StaticAttemptHints: null, + StaticPrefetchDisabled: null, + SubtreePrefetchHints: null, + propagateSubtreeBits: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + PrefetchHint: function() { + return PrefetchHint; + }, + StaticAttemptHints: function() { + return StaticAttemptHints; + }, + StaticPrefetchDisabled: function() { + return StaticPrefetchDisabled; + }, + SubtreePrefetchHints: function() { + return SubtreePrefetchHints; + }, + propagateSubtreeBits: function() { + return propagateSubtreeBits; + } +}); +var PrefetchHint = /*#__PURE__*/ function(PrefetchHint) { + // NOTE: The 0b00001 bit was previously HasRuntimePrefetch (prefetch: + // 'allow-runtime'). Partial Prefetching allows using runtime requests + // for every segment, so the bit was removed. Do not reuse it without + // considering caches populated by older builds. + // This segment or one of its descendants opts into Partial Prefetching, i.e. + // uses the two-phase (Shell then Speculative) prefetch flow. Set when + // `prefetch` is 'partial' (including the default implied by the global + // `partialPrefetching` config). Propagates upward so the root segment + // reflects the entire subtree. + // + // Partial Prefetching routes may use runtime requests for both shells + // and prefetches. They *may* be optimized to a use a static request + // if no runtime data was accessed during the prerender. + // However, If the route has `ensureStatic` configured to "shell", "prefetch", + // or "navigation", we *must* use static requests for the shell (and possibly the + // prefetch). + // Both of these cases are signalled to the scheduler via the + // `ShouldAttemptStatic{Shell,Prefetch}` hints and the `needsRuntimeRequest` + // promise. + PrefetchHint[PrefetchHint["SubtreeHasPartialPrefetching"] = 2] = "SubtreeHasPartialPrefetching"; + // This segment itself has a loading.tsx boundary. + PrefetchHint[PrefetchHint["SegmentHasLoadingBoundary"] = 4] = "SegmentHasLoadingBoundary"; + // A descendant segment (but not this one) has a loading.tsx boundary. + // Propagates upward so the root reflects the entire subtree. + PrefetchHint[PrefetchHint["SubtreeHasLoadingBoundary"] = 8] = "SubtreeHasLoadingBoundary"; + // This segment is at or above the application's root layout — the root layout + // segment itself and all of its ancestors. A dynamic param in one of these + // segments is a "root param". + PrefetchHint[PrefetchHint["IsRootLayoutOrAbove"] = 16] = "IsRootLayoutOrAbove"; + // This segment's response includes its parent's data inlined into it. + // Set at build time by the segment size measurement pass. + PrefetchHint[PrefetchHint["ParentInlinedIntoSelf"] = 32] = "ParentInlinedIntoSelf"; + // This segment's data is inlined into one of its children — don't fetch + // it separately. Set at build time by the segment size measurement pass. + PrefetchHint[PrefetchHint["InlinedIntoChild"] = 64] = "InlinedIntoChild"; + // On a __PAGE__: this page's response includes the head (metadata/viewport) + // in its transport data (PartialTransportData's `h`). + PrefetchHint[PrefetchHint["HeadInlinedIntoSelf"] = 128] = "HeadInlinedIntoSelf"; + // On the root hint node: the head was NOT inlined into any page — fetch + // it separately. Absence of this bit means the head is bundled into a page. + PrefetchHint[PrefetchHint["HeadOutlined"] = 256] = "HeadOutlined"; + // The inlining hints in this tree may be stale because the tree was + // generated before collectPrefetchHints ran (e.g. the initial RSC payload + // for a fully static page at build time). When writing this tree into the + // cache, the route entry should be immediately expired so it gets + // re-fetched with correct hints. Only set during build-time prerendering, + // never at runtime. + PrefetchHint[PrefetchHint["InliningHintsStale"] = 512] = "InliningHintsStale"; + // This segment has prefetch = 'force-disabled'. The opt-out is passive + // and applies to this segment only: it never INITIATES a prefetch — no + // static data is emitted or fetched, and it's never the reason a runtime + // prefetch spawns — but it may ride along in a runtime response issued on + // another segment's behalf. Descendants prefetch normally. + // + // TODO: Also set as an internal fallback when the prefetch hints manifest + // is unavailable (see #91407 mitigations), which only means "no static + // prefetch data exists" — not a user opt-out. Split the fallback into its + // own bit so the two intents can diverge. + PrefetchHint[PrefetchHint["PrefetchDisabled"] = 1024] = "PrefetchDisabled"; + // NOTE: The 0b100000000000 bit was previously SubtreeHasRuntimePrefetch. + // Partial Prefetching now implies runtime completeness for every segment + // (see SubtreeHasPartialPrefetching), so the bit was removed. Do not reuse + // it without considering caches populated by older builds. + // NOTE: The 0b1000000000000 bit was previously SubtreeHasEagerPrefetch + // (prefetch: 'unstable_eager', plus every segment that did not opt into + // Partial Prefetching). After `unstable_eager` was removed, it's no longer needed. + // This segment or one of its descendants exports `instant = false`, + // explicitly opting out of Partial Prefetching. Propagates upward so the root + // reflects the entire subtree. Used only to suppress the dev-time + // `` warning — unlike PrefetchDisabled, it has no effect + // on the actual prefetch behavior. + PrefetchHint[PrefetchHint["SubtreeHasInstantFalse"] = 8192] = "SubtreeHasInstantFalse"; + // The client should attempt a static prefetch for this route: the + // build-time prerender did not access any runtime data (cookies, headers, + // searchParams, ...), so a static prefetch is expected to be as complete + // as a runtime one. A fallback-param access only unsets the bit when the + // route can never be upgraded from a fallback to a concrete prerender — + // on an upgradeable route, ISR later produces the concrete prerender a + // static attempt would hit (until then, the static responses' own + // signal reports the insufficiency per response). Purely advisory, and + // both error directions are safe: if set when a runtime request is + // actually needed, that same response-level signal (the load-bearing + // `needsRuntimeRequest` promise combined with each segment's `isPartial`) + // directs the client to follow up — the cost is a wasted static attempt. + // If unset when static would have sufficed, the client goes straight to a + // runtime prefetch, which is a superset of the static response — the cost + // is only reduced cacheability. Like the other bits, this one is computed + // once per build and stays constant for the build's lifetime; it rides + // the prefetch-hints manifest into every response that carries hints — + // `/_tree` prefetch responses and the FlightRouterState of dynamic + // navigations alike. (Routes missing from the manifest — see the #91407 + // fallbacks — simply never carry it.) Set on every node of the tree, but + // does not propagate. + PrefetchHint[PrefetchHint["ShouldAttemptStaticShell"] = 16384] = "ShouldAttemptStaticShell"; + PrefetchHint[PrefetchHint["ShouldAttemptStaticPrefetch"] = 32768] = "ShouldAttemptStaticPrefetch"; + // This dynamic segment only accepts build-time parameter values. Kept on + // the affected node, without propagating or copying it to other segments. + // Until the client knows the allowed values, any such node prevents route + // prediction, even when the route's components never read the parameter. + PrefetchHint[PrefetchHint["IsClosedParam"] = 65536] = "IsClosedParam"; + // A descendant segment (but not this one) has a closed parameter. Propagates + // upward so route prediction can check the root instead of walking the tree. + PrefetchHint[PrefetchHint["SubtreeHasClosedParams"] = 131072] = "SubtreeHasClosedParams"; + return PrefetchHint; +}({}); +const StaticPrefetchDisabled = 1024; +const StaticAttemptHints = 16384 | 32768; +const SubtreePrefetchHints = 2 | 8 | 8192 | 131072; +function propagateSubtreeBits(parentHints, childHints) { + if (childHints & 2) { + parentHints |= 2; + } + // A child with a loading boundary (directly, or anywhere in its subtree) makes + // this a SubtreeHasLoadingBoundary on the parent. + if (childHints & (4 | 8)) { + parentHints |= 8; + } + // And for `instant = false`. The bit is set directly on each opted-out + // segment, so there's no separate segment-local flag — propagate it as-is. + if (childHints & 8192) { + parentHints |= 8192; + } + if (childHints & (65536 | 131072)) { + parentHints |= 131072; + } + return parentHints; +} + +//# sourceMappingURL=app-router-types.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/app-router-types.js.map b/e-commerce/node_modules/next/dist/shared/lib/app-router-types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..49b6cefa26e1be635f8533285791fa081daf29ba --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/app-router-types.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/app-router-types.ts"],"sourcesContent":["/**\n * App Router types - Client-safe types for the Next.js App Router\n *\n * This file contains type definitions that can be safely imported\n * by both client-side and server-side code without circular dependencies.\n */\n\nimport type React from 'react'\n\nexport type LoadingModuleData =\n | [React.JSX.Element, React.ReactNode, React.ReactNode]\n | null\n\nimport type {\n VaryParams,\n VaryParamsIterable,\n} from './segment-cache/vary-params-decoding'\nimport type { FullTransportData, PartialTransportData } from './rsc-transport'\n\n/** viewport metadata node */\nexport type HeadData = React.ReactNode\n\n/**\n * Render state for a segment. Reuse this object while its data is unchanged;\n * create a new one when a navigation replaces the segment's data.\n */\nexport type CacheNode = {\n /**\n * When rsc is not null, it represents the RSC data for the\n * corresponding segment.\n *\n * `null` is a valid React Node but because segment data is always a\n * component, we can use `null` to represent empty. When it is\n * null, it represents missing data, and rendering should suspend.\n */\n rsc: React.ReactNode\n\n /**\n * Represents a static version of the segment that can be shown immediately,\n * and may or may not contain dynamic holes. It's prefetched before a\n * navigation occurs.\n *\n * During rendering, we will choose whether to render `rsc` or `prefetchRsc`\n * with `useDeferredValue`. As with the `rsc` field, a value of `null` means\n * no value was provided. In this case, the LayoutRouter will go straight to\n * rendering the `rsc` value; if that one is also missing, it will suspend and\n * trigger a lazy fetch.\n */\n prefetchRsc: React.ReactNode\n\n /**\n * The source of the params `rsc` depends on, from the response that\n * produced it. Null when unknown: the data came from the segment cache, or\n * from a render that didn't track params, or `rsc` is still pending — it\n * is set alongside `rsc` when the response arrives. A navigation that only\n * changes params this output did not depend on can keep rendering it.\n */\n varyParams: VaryParams | null\n\n /**\n * A shared mutable ref that tracks whether this segment should be scrolled\n * to. All new segments created during a single navigation share the same\n * ref. When any segment's scroll handler fires, it sets `current` to\n * `false` so no other segment scrolls for the same navigation.\n *\n * `null` means this segment is not a scroll target (e.g., a reused shared\n * layout segment).\n */\n scrollRef: ScrollRef | null\n\n /**\n * Globally-unique identifier minted from a monotonic counter when the\n * CacheNode is freshly created. Surfaced to user code as a string via\n * `useRouter().bfcacheId` and intended to be used as a React `key` to\n * opt out of Activity-based state preservation on fresh navigations.\n *\n * Preserved when the CacheNode is reused (shared layouts, refresh,\n * search/hash-only navigations) or restored from the BFCache during a\n * back/forward navigation.\n */\n bfcacheId: number\n}\n\n/**\n * A mutable ref shared across all new segments created during a single\n * navigation. Used to ensure that only one segment scrolls per navigation.\n */\nexport type ScrollRef = { current: boolean }\n\nexport type DynamicParamTypes =\n | 'catchall'\n | 'catchall-intercepted-(..)(..)'\n | 'catchall-intercepted-(.)'\n | 'catchall-intercepted-(..)'\n | 'catchall-intercepted-(...)'\n | 'optional-catchall'\n | 'dynamic'\n | 'dynamic-intercepted-(..)(..)'\n | 'dynamic-intercepted-(.)'\n | 'dynamic-intercepted-(..)'\n | 'dynamic-intercepted-(...)'\n\nexport type DynamicParamTypesShort =\n | 'c'\n | 'ci(..)(..)'\n | 'ci(.)'\n | 'ci(..)'\n | 'ci(...)'\n | 'oc'\n | 'd'\n | 'di(..)(..)'\n | 'di(.)'\n | 'di(..)'\n | 'di(...)'\n\n// The tuple form of a segment, used for dynamic route params\nexport type DynamicSegmentTuple = [\n // Param name\n paramName: string,\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n paramCacheKey: string,\n // Dynamic param type\n dynamicParamType: DynamicParamTypesShort,\n // Static sibling segments at the same URL level. Used by the client\n // router to determine if a prefetch can be reused when navigating to\n // a static sibling of a dynamic route. For example, if the route is\n // /products/[id] and there's also /products/sale, then staticSiblings\n // would be ['sale']. null means the siblings are unknown (e.g. in\n // webpack dev mode).\n staticSiblings: readonly string[] | null,\n]\n\nexport type Segment = string | DynamicSegmentTuple\n\n/**\n * Router state\n */\nexport type FlightRouterState = [\n segment: Segment,\n parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },\n refreshState?: CompressedRefreshState | null,\n /**\n * - \"refetch\" is used during a request to inform the server where rendering\n * should start from.\n *\n * - \"inside-shared-layout\" is used during a prefetch request to inform the\n * server that even if the segment matches, it should be treated as if it's\n * within the \"new\" part of a navigation — inside the shared layout. If\n * the segment doesn't match, then it has no effect, since it would be\n * treated as new regardless. If it does match, though, the server does not\n * need to render it, because the client already has it.\n *\n * - \"metadata-only\" instructs the server to skip rendering the segments and\n * only send the head data.\n *\n * A bit confusing, but that's because it has only one extremely narrow use\n * case — during a non-PPR prefetch, the server uses it to find the first\n * loading boundary beneath a shared layout.\n *\n * TODO: We should rethink the protocol for dynamic requests. It might not\n * make sense for the client to send a FlightRouterState, since this type is\n * overloaded with concerns.\n */\n refresh?: 'refetch' | 'inside-shared-layout' | 'metadata-only' | null,\n /**\n * Bitmask of PrefetchHint flags. Encodes route structure metadata:\n * root layout, loading boundaries, instant configs, and prefetch strategy\n * hints. Only set when non-zero. JSON encodes an omitted slot as null when\n * a later slot is present.\n */\n prefetchHints?: number | null,\n /**\n * The rendered search params of a page segment. An empty string means there\n * are none. Only set on page nodes, and left out of request headers.\n * TODO: Revisit this as part of the larger FlightRouterState refactor.\n */\n renderedSearch?: string,\n]\n\n/**\n * When rendering a parallel route, some of the parallel paths may not match\n * the current URL. In that case, the Next client has to render something,\n * so it will render whichever was the last route to match that slot. We use\n * this type to track when this has happened. It's a tuple of the original\n * URL that was used to fetch the segment, and the (possibly rewritten) search\n * query that was rendered by the server. The URL is needed when performing\n * a refresh of the segment, and the search query is needed for looking up\n * matching entries in the segment cache.\n */\nexport type CompressedRefreshState = [url: string, renderedSearch: string]\n\nexport const enum PrefetchHint {\n // NOTE: The 0b00001 bit was previously HasRuntimePrefetch (prefetch:\n // 'allow-runtime'). Partial Prefetching allows using runtime requests\n // for every segment, so the bit was removed. Do not reuse it without\n // considering caches populated by older builds.\n\n // This segment or one of its descendants opts into Partial Prefetching, i.e.\n // uses the two-phase (Shell then Speculative) prefetch flow. Set when\n // `prefetch` is 'partial' (including the default implied by the global\n // `partialPrefetching` config). Propagates upward so the root segment\n // reflects the entire subtree.\n //\n // Partial Prefetching routes may use runtime requests for both shells\n // and prefetches. They *may* be optimized to a use a static request\n // if no runtime data was accessed during the prerender.\n // However, If the route has `ensureStatic` configured to \"shell\", \"prefetch\",\n // or \"navigation\", we *must* use static requests for the shell (and possibly the\n // prefetch).\n // Both of these cases are signalled to the scheduler via the\n // `ShouldAttemptStatic{Shell,Prefetch}` hints and the `needsRuntimeRequest`\n // promise.\n SubtreeHasPartialPrefetching = 0b00010,\n // This segment itself has a loading.tsx boundary.\n SegmentHasLoadingBoundary = 0b00100,\n // A descendant segment (but not this one) has a loading.tsx boundary.\n // Propagates upward so the root reflects the entire subtree.\n SubtreeHasLoadingBoundary = 0b01000,\n // This segment is at or above the application's root layout — the root layout\n // segment itself and all of its ancestors. A dynamic param in one of these\n // segments is a \"root param\".\n IsRootLayoutOrAbove = 0b10000,\n // This segment's response includes its parent's data inlined into it.\n // Set at build time by the segment size measurement pass.\n ParentInlinedIntoSelf = 0b100000,\n // This segment's data is inlined into one of its children — don't fetch\n // it separately. Set at build time by the segment size measurement pass.\n InlinedIntoChild = 0b1000000,\n // On a __PAGE__: this page's response includes the head (metadata/viewport)\n // in its transport data (PartialTransportData's `h`).\n HeadInlinedIntoSelf = 0b10000000,\n // On the root hint node: the head was NOT inlined into any page — fetch\n // it separately. Absence of this bit means the head is bundled into a page.\n HeadOutlined = 0b100000000,\n // The inlining hints in this tree may be stale because the tree was\n // generated before collectPrefetchHints ran (e.g. the initial RSC payload\n // for a fully static page at build time). When writing this tree into the\n // cache, the route entry should be immediately expired so it gets\n // re-fetched with correct hints. Only set during build-time prerendering,\n // never at runtime.\n InliningHintsStale = 0b1000000000,\n // This segment has prefetch = 'force-disabled'. The opt-out is passive\n // and applies to this segment only: it never INITIATES a prefetch — no\n // static data is emitted or fetched, and it's never the reason a runtime\n // prefetch spawns — but it may ride along in a runtime response issued on\n // another segment's behalf. Descendants prefetch normally.\n //\n // TODO: Also set as an internal fallback when the prefetch hints manifest\n // is unavailable (see #91407 mitigations), which only means \"no static\n // prefetch data exists\" — not a user opt-out. Split the fallback into its\n // own bit so the two intents can diverge.\n PrefetchDisabled = 0b10000000000,\n // NOTE: The 0b100000000000 bit was previously SubtreeHasRuntimePrefetch.\n // Partial Prefetching now implies runtime completeness for every segment\n // (see SubtreeHasPartialPrefetching), so the bit was removed. Do not reuse\n // it without considering caches populated by older builds.\n\n // NOTE: The 0b1000000000000 bit was previously SubtreeHasEagerPrefetch\n // (prefetch: 'unstable_eager', plus every segment that did not opt into\n // Partial Prefetching). After `unstable_eager` was removed, it's no longer needed.\n\n // This segment or one of its descendants exports `instant = false`,\n // explicitly opting out of Partial Prefetching. Propagates upward so the root\n // reflects the entire subtree. Used only to suppress the dev-time\n // `` warning — unlike PrefetchDisabled, it has no effect\n // on the actual prefetch behavior.\n SubtreeHasInstantFalse = 0b10000000000000,\n // The client should attempt a static prefetch for this route: the\n // build-time prerender did not access any runtime data (cookies, headers,\n // searchParams, ...), so a static prefetch is expected to be as complete\n // as a runtime one. A fallback-param access only unsets the bit when the\n // route can never be upgraded from a fallback to a concrete prerender —\n // on an upgradeable route, ISR later produces the concrete prerender a\n // static attempt would hit (until then, the static responses' own\n // signal reports the insufficiency per response). Purely advisory, and\n // both error directions are safe: if set when a runtime request is\n // actually needed, that same response-level signal (the load-bearing\n // `needsRuntimeRequest` promise combined with each segment's `isPartial`)\n // directs the client to follow up — the cost is a wasted static attempt.\n // If unset when static would have sufficed, the client goes straight to a\n // runtime prefetch, which is a superset of the static response — the cost\n // is only reduced cacheability. Like the other bits, this one is computed\n // once per build and stays constant for the build's lifetime; it rides\n // the prefetch-hints manifest into every response that carries hints —\n // `/_tree` prefetch responses and the FlightRouterState of dynamic\n // navigations alike. (Routes missing from the manifest — see the #91407\n // fallbacks — simply never carry it.) Set on every node of the tree, but\n // does not propagate.\n ShouldAttemptStaticShell = 0b100000000000000,\n ShouldAttemptStaticPrefetch = 0b1000000000000000,\n // This dynamic segment only accepts build-time parameter values. Kept on\n // the affected node, without propagating or copying it to other segments.\n // Until the client knows the allowed values, any such node prevents route\n // prediction, even when the route's components never read the parameter.\n IsClosedParam = 0b10000000000000000,\n // A descendant segment (but not this one) has a closed parameter. Propagates\n // upward so route prediction can check the root instead of walking the tree.\n SubtreeHasClosedParams = 0b100000000000000000,\n}\n\n/**\n * Bitmask for checking whether a segment's static prefetch is skipped — i.e.\n * the server emits no static data for it (its node in a segment response\n * carries identity only, and it participates in a bundle only as a\n * pass-through) and the client never issues a static request for it.\n *\n * Static prefetching is disabled ONLY by `prefetch: 'force-disabled'`\n * (PrefetchDisabled). Notably, Partial Prefetching segments DO have static\n * data even though they can use runtime requests: the server emits it\n * unconditionally — it can't be gated on the ShouldAttemptStatic{Shell,Prefetch}\n * hints, because which segments carry static data must be deterministic\n * from build-time config. A runtime request may still be needed for the\n * segment, but the scheduler may attempt a static prefetch first (per the\n * ShouldAttemptStatic{Shell,Prefetch} hints) and skip the runtime request if the\n * static response proves sufficient.\n *\n * Usage: `(hints & StaticPrefetchDisabled) !== 0`\n */\nexport const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled\n\nexport const StaticAttemptHints =\n PrefetchHint.ShouldAttemptStaticShell |\n PrefetchHint.ShouldAttemptStaticPrefetch\n\n/**\n * The subset of PrefetchHint bits that propagate upward from a child segment to\n * its ancestors (as opposed to segment-local bits like SegmentHasLoadingBoundary\n * or IsRootLayoutOrAbove). Used to clear stale propagated bits before re-deriving them\n * from a node's children.\n */\nexport const SubtreePrefetchHints =\n PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasLoadingBoundary |\n PrefetchHint.SubtreeHasInstantFalse |\n PrefetchHint.SubtreeHasClosedParams\n\n/**\n * Folds a child segment's prefetch hints into its parent's, propagating the\n * \"subtree\" flags. A child's segment-local flag (e.g. it has a loading\n * boundary) becomes the corresponding \"subtree\" flag on the parent, so the\n * root segment ends up reflecting the entire subtree.\n *\n * Used wherever a route tree is assembled bottom-up: on the server when building\n * a transport tree (createTransportTreeFromLoaderTree) and on the client when\n * overlaying a navigation response onto the existing tree\n * (createNavigationSeed). Keep these in sync by routing both through\n * this helper.\n */\nexport function propagateSubtreeBits(\n parentHints: number,\n childHints: number\n): number {\n if (childHints & PrefetchHint.SubtreeHasPartialPrefetching) {\n parentHints |= PrefetchHint.SubtreeHasPartialPrefetching\n }\n // A child with a loading boundary (directly, or anywhere in its subtree) makes\n // this a SubtreeHasLoadingBoundary on the parent.\n if (\n childHints &\n (PrefetchHint.SegmentHasLoadingBoundary |\n PrefetchHint.SubtreeHasLoadingBoundary)\n ) {\n parentHints |= PrefetchHint.SubtreeHasLoadingBoundary\n }\n // And for `instant = false`. The bit is set directly on each opted-out\n // segment, so there's no separate segment-local flag — propagate it as-is.\n if (childHints & PrefetchHint.SubtreeHasInstantFalse) {\n parentHints |= PrefetchHint.SubtreeHasInstantFalse\n }\n if (\n childHints &\n (PrefetchHint.IsClosedParam | PrefetchHint.SubtreeHasClosedParams)\n ) {\n parentHints |= PrefetchHint.SubtreeHasClosedParams\n }\n return parentHints\n}\n\n/**\n * A path through the segment tree: a repeating sequence of segment and\n * parallel route key. Used by the client to address positions in the\n * render tree (see layout-router).\n */\nexport type FlightSegmentPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n ]\n\n/**\n * Per-route prefetch hints computed at build time. Mirrors the shape of the\n * loader tree so hints can be traversed in parallel during router state\n * creation. Each node stores a bitmask of PrefetchHint flags\n * (ParentInlinedIntoSelf, InlinedIntoChild) computed by the segment size\n * measurement pass.\n *\n * Persisted to prefetch-hints.json as Record (keyed\n * by route pattern) and loaded at server startup.\n */\nexport type PrefetchHints = {\n /** Bitmask of PrefetchHint flags for this segment. */\n hints: number\n /** Child hint nodes, keyed by parallel route key. */\n slots: Record | null\n}\n\nexport type ActionResult = Promise\n\nexport type InitialRSCPayload = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** initialCanonicalUrlParts */\n c: string[]\n /** initialRenderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** initial transport data — the tree + head for hydration */\n t: FullTransportData\n /** missingSlots */\n m: Set | undefined\n /** GlobalError */\n G: [React.ComponentType, React.ReactNode | undefined]\n /** supportsPerSegmentPrefetching */\n S: boolean\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params, rather than the server folding them into each set.\n */\n r?: VaryParamsIterable\n /** staleTime in seconds - Only present when Cache Components is enabled. */\n s?: AsyncIterable\n /**\n * runtimeDataAccessed — whether the render has accessed a data source that\n * hangs during a static prerender but would resolve during a runtime\n * prerender (cookies, headers, fallback params, searchParams, ...). The\n * flag is monotonic (false → true, at most once), so it's encoded as a\n * promise: resolved `true` at the moment of first access — the fulfillment\n * row's position in the stream records the stage the access happened in —\n * or resolved `false` when the prerender completes without one, a row that\n * lands past every stage boundary. A truncated (shell) decode therefore\n * reads the answer as of the shell stage: fulfilled `true` iff the access\n * happened during a stage it includes, pending (⇒ no access) otherwise.\n * Unlike an async iterable, a pending promise costs Flight no abort\n * listener on the render. Used when generating per-segment prefetch\n * responses (forwarded as each response's own `u`).\n * The build-time constant `PrefetchHint.ShouldAttemptStatic{Shell,Prefetch}`\n * hint is tracked separately.\n * Only present for static prerenders when Cache Components is enabled.\n */\n u?: Promise\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n * */\n a?: Promise\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise\n}\n\n/**\n * The fields shared by every navigation/prefetch response kind. Not used\n * directly — see NavigationFlightResponse (the general form) and the\n * per-context aliases DynamicNavigationFlightResponse and\n * PrefetchFlightResponse below. Fields that only apply to some response\n * kinds are optional.\n */\ntype NavigationFlightResponseBase = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /**\n * transport data — present iff the response carries a SPA payload.\n * Absent when the response renders nothing (see `n` for MPA navigations).\n *\n * In a per-segment prefetch response the tree is root-anchored with `d`\n * present on exactly the segments whose data is bundled into the response\n * (the requested segment and any ancestors inlined into it, per the\n * build-time prefetch hints); the remaining nodes — the spine above the\n * bundle, and segments with static prefetching disabled — carry identity\n * but no data. Every node carries the same hints the `/_tree` response\n * emits for it, so the tree decodes like any other transport tree. Data\n * nodes use the staged encodings: `p` is a promise and `s` is present\n * (see TransportSegmentData). The head (`h`) is present iff it's bundled\n * into the response: the standalone head response (whose tree is a bare\n * root identity), or a page response whose bundle accepted the head\n * (PrefetchHint.HeadInlinedIntoSelf).\n */\n t?: PartialTransportData\n /**\n * MPA navigation URL — present iff the client should hard-navigate to\n * this URL instead of applying a SPA payload. Reserved: no server path\n * emits it today (hard navigations are signaled by non-RSC content types\n * or a build-id mismatch), but the client honors it.\n */\n n?: string\n /** staleTime - Only present in live-render responses.\n * Per-segment prefetch responses carry staleTime per node instead (see\n * TransportSegmentData). */\n s?: AsyncIterable\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n *\n * In a per-segment prefetch response this is the shell byte boundary the\n * client uses for the shell double-decode: re-decoding the buffered\n * response truncated at the offset yields the shell variant of every\n * segment (param-dependent content reduced to still-pending references).\n * `0` means no shell exists (the page wasn't produced by staged\n * rendering) — never a valid offset, so it doubles as the \"none\"\n * sentinel. The resolution row flushes past the boundary, so a truncated\n * shell decode reads it as pending, which is harmless. The client's\n * buffered read leans on the same fact from the other side: 0 read from\n * an unfulfilled `a` implies a bug — see the shell-extraction comment in\n * fetchAndWritePerSegmentPrefetchResponse (segment-cache/cache.ts).\n */\n a?: Promise\n /**\n * needsRuntimeRequest — presence means the response carries a stage-scoped\n * runtime-data verdict. Per-segment prefetch responses always emit one,\n * and so does any prerendered page payload, which embeds the prerender's\n * runtime-data probe — that covers navigation responses served from\n * prerender output and the truncated initial payload alike. Live renders\n * emit none. Only per-segment responses additionally promise-encode the\n * head's partiality (see TransportSegmentData). The value is the page's\n * runtime-data-access flag (the page payload's own `u`; per-segment\n * responses forward it from the staged decode of the page data).\n * Fulfilled `true` means a runtime prefetch would return more\n * than this static response; pending or fulfilled `false` means it\n * wouldn't. Promise-encoded so the answer rewinds with a truncated\n * decode: the fulfillment row lands on the same side of the shell byte\n * boundary (`a`) as the access it records. Tracking is page-global, so it\n * lives on the response, not on each segment; per-segment granularity\n * comes from combining it with each segment's partiality:\n * needsRuntimeRequest(segment) = (settled true) && (isPartial pending).\n * The derived value must never falsely claim that no runtime request is\n * needed, so every fallback is conservative: pages that carry no `u`\n * (legacy render paths) forward an already-resolved `true`. Unlike the\n * build-constant prefetch hints, this is computed per render and may\n * change between responses for the same build — it reflects THIS\n * response.\n */\n u?: Promise\n /**\n * shellUsedSessionData — present only in runtime-shell prefetch\n * responses: true if resolving session data unblocked new content in the\n * shell. Only meaningful where there's a proper session shell.\n * Promise-encoded so the answer rewinds with a truncated decode.\n * Currently has no client consumer; emitted for forward compatibility.\n */\n w?: Promise\n /**\n * isUpgradeableISRFallback — present (true) iff this is a per-segment\n * prefetch response generated from a fallback shell render (i.e. the page\n * had not yet been prerendered with concrete params, so it was rendered\n * with `fallbackRouteParams`). The client uses this to schedule a retry,\n * since a more complete version may become available once the server's\n * background regeneration finishes.\n *\n * Note: this is distinct from per-segment partiality. A fully-prerendered\n * PPR page can have partial segments (dynamic holes filled by runtime\n * requests); those should not be retried. This flag specifically means a\n * more complete *static* version may become available.\n */\n f?: boolean\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params.\n */\n r?: VaryParamsIterable\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise\n}\n\n/**\n * A live-render response: navigations, refreshes, runtime prefetches, and\n * dynamic route tree prefetches. Live renders always emit `S`, `q`, and `i`,\n * so they're required here — used at the sites that produce these responses\n * (app-render) and the decode sites that only ever receive them, so a\n * malformed response fails the type rather than being masked by a fallback.\n */\nexport type DynamicNavigationFlightResponse = NavigationFlightResponseBase & {\n /**\n * supportsPerSegmentPrefetching — whether per-segment prefetch responses\n * can be served for this route.\n */\n S: boolean\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n}\n\n/**\n * A per-segment prefetch response served from static storage: the `/_tree`\n * route tree prefetch and the per-segment responses generated by\n * collect-segment-data. Never carries `S` (implied by the response's\n * existence), `q` (search-agnostic; the client writes these responses into\n * the cache using the rendered search already recorded on the route tree\n * entry), or `i` (the client reads the Vary header instead). Structurally\n * the shared base — the alias marks the response kind at the sites that\n * produce and decode it.\n */\nexport type PrefetchFlightResponse = NavigationFlightResponseBase\n\n/**\n * The general form: a response that may be either kind, for the flows that\n * handle both (the `/_tree` fetch, which receives a live render when\n * per-segment prefetching is unsupported, and the shared cache-write path).\n * Both aliases above are assignable to it.\n */\nexport type NavigationFlightResponse = NavigationFlightResponseBase & {\n /**\n * supportsPerSegmentPrefetching — present in live-render responses;\n * absent in per-segment prefetch responses served from static storage\n * (where it's implied by the response's existence).\n */\n S?: boolean\n /**\n * renderedSearch — present in live-render responses; absent in\n * per-segment prefetch responses, which are search-agnostic (the client\n * writes them into the cache using the rendered search already recorded\n * on the route tree entry).\n */\n q?: string\n /**\n * couldBeIntercepted — present in live-render responses; absent in\n * per-segment prefetch responses (the client reads the Vary header\n * instead).\n */\n i?: boolean\n}\n\n// Response from `createFromFetch` for server actions.\nexport type ActionFlightResponse = {\n /** actionResult */\n a: ActionResult\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /**\n * transport data — present iff the action response re-rendered the page.\n * Absent when the action rendered nothing (see `n` for MPA navigations).\n */\n t?: PartialTransportData\n /**\n * MPA navigation URL — present iff the client should hard-navigate to\n * this URL instead of applying a SPA payload. Reserved: no server path\n * emits it today, but the client honors it.\n */\n n?: string\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n}\n\nexport type RSCPayload =\n | InitialRSCPayload\n | NavigationFlightResponse\n | ActionFlightResponse\n\nexport type InstantCookie =\n // pending (waiting to capture)\n | [captured: 0, id: string]\n // captured MPA page load\n | [captured: 1, id: string, state: null]\n // captured SPA navigation (from/to route trees)\n | [\n captured: 1,\n id: string,\n state: { from: FlightRouterState; to: FlightRouterState | null },\n ]\n"],"names":["PrefetchHint","StaticAttemptHints","StaticPrefetchDisabled","SubtreePrefetchHints","propagateSubtreeBits","parentHints","childHints"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;;;;;;;;IA+LiBA,YAAY;eAAZA;;IAiILC,kBAAkB;eAAlBA;;IAFAC,sBAAsB;eAAtBA;;IAYAC,oBAAoB;eAApBA;;IAkBGC,oBAAoB;eAApBA;;;AA7JT,IAAA,AAAWJ,sCAAAA;IAChB,qEAAqE;IACrE,sEAAsE;IACtE,qEAAqE;IACrE,gDAAgD;IAEhD,6EAA6E;IAC7E,sEAAsE;IACtE,uEAAuE;IACvE,sEAAsE;IACtE,+BAA+B;IAC/B,EAAE;IACF,sEAAsE;IACtE,oEAAoE;IACpE,wDAAwD;IACxD,8EAA8E;IAC9E,iFAAiF;IACjF,aAAa;IACb,6DAA6D;IAC7D,4EAA4E;IAC5E,WAAW;;IAEX,kDAAkD;;IAElD,sEAAsE;IACtE,6DAA6D;;IAE7D,8EAA8E;IAC9E,2EAA2E;IAC3E,8BAA8B;;IAE9B,sEAAsE;IACtE,0DAA0D;;IAE1D,wEAAwE;IACxE,yEAAyE;;IAEzE,4EAA4E;IAC5E,sDAAsD;;IAEtD,wEAAwE;IACxE,4EAA4E;;IAE5E,oEAAoE;IACpE,0EAA0E;IAC1E,0EAA0E;IAC1E,kEAAkE;IAClE,0EAA0E;IAC1E,oBAAoB;;IAEpB,uEAAuE;IACvE,uEAAuE;IACvE,yEAAyE;IACzE,0EAA0E;IAC1E,2DAA2D;IAC3D,EAAE;IACF,0EAA0E;IAC1E,uEAAuE;IACvE,0EAA0E;IAC1E,0CAA0C;;IAE1C,yEAAyE;IACzE,yEAAyE;IACzE,2EAA2E;IAC3E,2DAA2D;IAE3D,uEAAuE;IACvE,wEAAwE;IACxE,mFAAmF;IAEnF,oEAAoE;IACpE,8EAA8E;IAC9E,kEAAkE;IAClE,+EAA+E;IAC/E,mCAAmC;;IAEnC,kEAAkE;IAClE,0EAA0E;IAC1E,yEAAyE;IACzE,yEAAyE;IACzE,wEAAwE;IACxE,uEAAuE;IACvE,kEAAkE;IAClE,uEAAuE;IACvE,mEAAmE;IACnE,qEAAqE;IACrE,0EAA0E;IAC1E,yEAAyE;IACzE,0EAA0E;IAC1E,0EAA0E;IAC1E,0EAA0E;IAC1E,uEAAuE;IACvE,uEAAuE;IACvE,mEAAmE;IACnE,wEAAwE;IACxE,yEAAyE;IACzE,sBAAsB;;;IAGtB,yEAAyE;IACzE,0EAA0E;IAC1E,0EAA0E;IAC1E,yEAAyE;;IAEzE,6EAA6E;IAC7E,6EAA6E;;WAzG7DA;;AA+HX,MAAME;AAEN,MAAMD,qBACXD;AASK,MAAMG,uBACXH;AAiBK,SAASI,qBACdC,WAAmB,EACnBC,UAAkB;IAElB,IAAIA,gBAAwD;QAC1DD;IACF;IACA,+EAA+E;IAC/E,kDAAkD;IAClD,IACEC,aACCN,CAAAA,KACsC,GACvC;QACAK;IACF;IACA,uEAAuE;IACvE,2EAA2E;IAC3E,IAAIC,mBAAkD;QACpDD;IACF;IACA,IACEC,aACCN,CAAAA,cAA+D,GAChE;QACAK;IACF;IACA,OAAOA;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/bloom-filter.d.ts b/e-commerce/node_modules/next/dist/shared/lib/bloom-filter.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b0091ed8504972f335b529b78662693cb1a4c6a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/bloom-filter.d.ts @@ -0,0 +1,20 @@ +export declare class BloomFilter { + numItems: number; + errorRate: number; + numBits: number; + numHashes: number; + bitArray: number[]; + constructor(numItems: number, errorRate?: number); + static from(items: string[], errorRate?: number): BloomFilter; + export(): { + numItems: number; + errorRate: number; + numBits: number; + numHashes: number; + bitArray: number[]; + }; + import(data: ReturnType<(typeof this)['export']>): void; + add(item: string): void; + contains(item: string): boolean; + getHashValues(item: string): number[]; +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/bloom-filter.js b/e-commerce/node_modules/next/dist/shared/lib/bloom-filter.js new file mode 100644 index 0000000000000000000000000000000000000000..d0241253111eda3a027f0fe881476724861debf4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/bloom-filter.js @@ -0,0 +1,85 @@ +// minimal implementation MurmurHash2 hash function +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "BloomFilter", { + enumerable: true, + get: function() { + return BloomFilter; + } +}); +function murmurhash2(str) { + let h = 0; + for(let i = 0; i < str.length; i++){ + const c = str.charCodeAt(i); + h = Math.imul(h ^ c, 0x5bd1e995); + h ^= h >>> 13; + h = Math.imul(h, 0x5bd1e995); + } + return h >>> 0; +} +// default to 0.01% error rate as the filter compresses very well +const DEFAULT_ERROR_RATE = 0.0001; +class BloomFilter { + constructor(numItems, errorRate = DEFAULT_ERROR_RATE){ + this.numItems = numItems; + this.errorRate = errorRate; + this.numBits = Math.ceil(-(numItems * Math.log(errorRate)) / (Math.log(2) * Math.log(2))); + this.numHashes = Math.ceil(this.numBits / numItems * Math.log(2)); + this.bitArray = new Array(this.numBits).fill(0); + } + static from(items, errorRate = DEFAULT_ERROR_RATE) { + const filter = new BloomFilter(items.length, errorRate); + for (const item of items){ + filter.add(item); + } + return filter; + } + export() { + const data = { + numItems: this.numItems, + errorRate: this.errorRate, + numBits: this.numBits, + numHashes: this.numHashes, + bitArray: this.bitArray + }; + if (process.env.NEXT_RUNTIME === 'nodejs') { + if (this.errorRate < DEFAULT_ERROR_RATE) { + const filterData = JSON.stringify(data); + const gzipSize = require('next/dist/compiled/gzip-size').sync(filterData); + if (gzipSize > 1024) { + console.warn(`Creating filter with error rate less than 0.1% (0.001) can increase the size dramatically proceed with caution. Received error rate ${this.errorRate} resulted in size ${filterData.length} bytes, ${gzipSize} bytes (gzip)`); + } + } + } + return data; + } + import(data) { + this.numItems = data.numItems; + this.errorRate = data.errorRate; + this.numBits = data.numBits; + this.numHashes = data.numHashes; + this.bitArray = data.bitArray; + } + add(item) { + const hashValues = this.getHashValues(item); + hashValues.forEach((hash)=>{ + this.bitArray[hash] = 1; + }); + } + contains(item) { + const hashValues = this.getHashValues(item); + return hashValues.every((hash)=>this.bitArray[hash]); + } + getHashValues(item) { + const hashValues = []; + for(let i = 1; i <= this.numHashes; i++){ + const hash = murmurhash2(`${item}${i}`) % this.numBits; + hashValues.push(hash); + } + return hashValues; + } +} + +//# sourceMappingURL=bloom-filter.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/bloom-filter.js.map b/e-commerce/node_modules/next/dist/shared/lib/bloom-filter.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3a7486fda41df3f9b9efa70ebac501308b0e260c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/bloom-filter.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/bloom-filter.ts"],"sourcesContent":["// minimal implementation MurmurHash2 hash function\nfunction murmurhash2(str: string) {\n let h = 0\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i)\n h = Math.imul(h ^ c, 0x5bd1e995)\n h ^= h >>> 13\n h = Math.imul(h, 0x5bd1e995)\n }\n return h >>> 0\n}\n\n// default to 0.01% error rate as the filter compresses very well\nconst DEFAULT_ERROR_RATE = 0.0001\n\nexport class BloomFilter {\n numItems: number\n errorRate: number\n numBits: number\n numHashes: number\n bitArray: number[]\n\n constructor(numItems: number, errorRate: number = DEFAULT_ERROR_RATE) {\n this.numItems = numItems\n this.errorRate = errorRate\n this.numBits = Math.ceil(\n -(numItems * Math.log(errorRate)) / (Math.log(2) * Math.log(2))\n )\n this.numHashes = Math.ceil((this.numBits / numItems) * Math.log(2))\n this.bitArray = new Array(this.numBits).fill(0)\n }\n\n static from(items: string[], errorRate = DEFAULT_ERROR_RATE) {\n const filter = new BloomFilter(items.length, errorRate)\n\n for (const item of items) {\n filter.add(item)\n }\n return filter\n }\n\n export() {\n const data = {\n numItems: this.numItems,\n errorRate: this.errorRate,\n numBits: this.numBits,\n numHashes: this.numHashes,\n bitArray: this.bitArray,\n }\n\n if (process.env.NEXT_RUNTIME === 'nodejs') {\n if (this.errorRate < DEFAULT_ERROR_RATE) {\n const filterData = JSON.stringify(data)\n const gzipSize = (\n require('next/dist/compiled/gzip-size') as typeof import('next/dist/compiled/gzip-size')\n ).sync(filterData)\n\n if (gzipSize > 1024) {\n console.warn(\n `Creating filter with error rate less than 0.1% (0.001) can increase the size dramatically proceed with caution. Received error rate ${this.errorRate} resulted in size ${filterData.length} bytes, ${gzipSize} bytes (gzip)`\n )\n }\n }\n }\n\n return data\n }\n\n import(data: ReturnType<(typeof this)['export']>) {\n this.numItems = data.numItems\n this.errorRate = data.errorRate\n this.numBits = data.numBits\n this.numHashes = data.numHashes\n this.bitArray = data.bitArray\n }\n\n add(item: string) {\n const hashValues = this.getHashValues(item)\n hashValues.forEach((hash) => {\n this.bitArray[hash] = 1\n })\n }\n\n contains(item: string) {\n const hashValues = this.getHashValues(item)\n return hashValues.every((hash) => this.bitArray[hash])\n }\n\n getHashValues(item: string) {\n const hashValues = []\n for (let i = 1; i <= this.numHashes; i++) {\n const hash = murmurhash2(`${item}${i}`) % this.numBits\n hashValues.push(hash)\n }\n return hashValues\n }\n}\n"],"names":["BloomFilter","murmurhash2","str","h","i","length","c","charCodeAt","Math","imul","DEFAULT_ERROR_RATE","constructor","numItems","errorRate","numBits","ceil","log","numHashes","bitArray","Array","fill","from","items","filter","item","add","export","data","process","env","NEXT_RUNTIME","filterData","JSON","stringify","gzipSize","require","sync","console","warn","import","hashValues","getHash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;YACtD0B,WAAWM,IAAI,CAACH;QAClB;QACA,OAAOH;IACT;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/constants.d.ts b/e-commerce/node_modules/next/dist/shared/lib/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..86200c929c01eee4e392bfa51088e5eebb519c5e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/constants.d.ts @@ -0,0 +1,123 @@ +import MODERN_BROWSERSLIST_TARGET from './modern-browserslist-target'; +export { MODERN_BROWSERSLIST_TARGET }; +export type ValueOf = Required[keyof T]; +export declare const COMPILER_NAMES: { + readonly client: "client"; + readonly server: "server"; + readonly edgeServer: "edge-server"; +}; +export type CompilerNameValues = ValueOf; +export declare const COMPILER_INDEXES: { + [compilerKey in CompilerNameValues]: number; +}; +export { UNDERSCORE_NOT_FOUND_ROUTE, UNDERSCORE_NOT_FOUND_ROUTE_ENTRY, UNDERSCORE_GLOBAL_ERROR_ROUTE, UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY, } from './entry-constants'; +export declare enum AdapterOutputType { + /** + * `PAGES` represents all the React pages that are under `pages/`. + */ + PAGES = "PAGES", + /** + * `PAGES_API` represents all the API routes under `pages/api/`. + */ + PAGES_API = "PAGES_API", + /** + * `APP_PAGE` represents all the React pages that are under `app/` with the + * filename of `page.{j,t}s{,x}`. + */ + APP_PAGE = "APP_PAGE", + /** + * `APP_ROUTE` represents all the API routes and metadata routes that are under `app/` with the + * filename of `route.{j,t}s{,x}`. + */ + APP_ROUTE = "APP_ROUTE", + /** + * `PRERENDER` represents an ISR enabled route that might + * have a seeded cache entry or fallback generated during build + */ + PRERENDER = "PRERENDER", + /** + * `STATIC_FILE` represents a static file (ie /_next/static) + */ + STATIC_FILE = "STATIC_FILE", + /** + * `MIDDLEWARE` represents the middleware output if present + */ + MIDDLEWARE = "MIDDLEWARE" +} +export declare const PHASE_EXPORT = "phase-export"; +export declare const PHASE_ANALYZE = "phase-analyze"; +export declare const PHASE_PRODUCTION_BUILD = "phase-production-build"; +export declare const PHASE_PRODUCTION_SERVER = "phase-production-server"; +export declare const PHASE_DEVELOPMENT_SERVER = "phase-development-server"; +export declare const PHASE_TEST = "phase-test"; +export declare const PHASE_INFO = "phase-info"; +export type PHASE_TYPE = typeof PHASE_INFO | typeof PHASE_TEST | typeof PHASE_EXPORT | typeof PHASE_ANALYZE | typeof PHASE_PRODUCTION_BUILD | typeof PHASE_PRODUCTION_SERVER | typeof PHASE_DEVELOPMENT_SERVER; +export declare const PAGES_MANIFEST = "pages-manifest.json"; +export declare const APP_PATHS_MANIFEST = "app-paths-manifest.json"; +export declare const APP_PATH_ROUTES_MANIFEST = "app-path-routes-manifest.json"; +export declare const BUILD_MANIFEST = "build-manifest.json"; +export declare const FUNCTIONS_CONFIG_MANIFEST = "functions-config-manifest.json"; +export declare const SUBRESOURCE_INTEGRITY_MANIFEST = "subresource-integrity-manifest"; +export declare const NEXT_FONT_MANIFEST = "next-font-manifest"; +export declare const EXPORT_MARKER = "export-marker.json"; +export declare const EXPORT_DETAIL = "export-detail.json"; +export declare const PRERENDER_MANIFEST = "prerender-manifest.json"; +export declare const PREFETCH_HINTS = "prefetch-hints.json"; +export declare const PREVIEW_PROPS_MANIFEST = "preview-props.json"; +export declare const ROUTES_MANIFEST = "routes-manifest.json"; +export declare const IMAGES_MANIFEST = "images-manifest.json"; +export declare const SERVER_FILES_MANIFEST = "required-server-files"; +export declare const DEV_CLIENT_PAGES_MANIFEST = "_devPagesManifest.json"; +export declare const REQUEST_INSIGHTS_DEV_ENDPOINT = "/_next/development/request-insights"; +export declare const MIDDLEWARE_MANIFEST = "middleware-manifest.json"; +export declare const TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST = "_clientMiddlewareManifest.js"; +export declare const TURBOPACK_CLIENT_BUILD_MANIFEST = "client-build-manifest.json"; +export declare const DEV_CLIENT_MIDDLEWARE_MANIFEST = "_devMiddlewareManifest.json"; +export declare const REACT_LOADABLE_MANIFEST = "react-loadable-manifest.json"; +export declare const SERVER_DIRECTORY = "server"; +export declare const CONFIG_FILES: string[]; +export declare const BUILD_ID_FILE = "BUILD_ID"; +export declare const BLOCKED_PAGES: string[]; +export declare const CLIENT_PUBLIC_FILES_PATH = "public"; +export declare const CLIENT_STATIC_FILES_PATH = "static"; +export declare const STRING_LITERAL_DROP_BUNDLE = "__NEXT_DROP_CLIENT_FILE__"; +export declare const NEXT_BUILTIN_DOCUMENT = "__NEXT_BUILTIN_DOCUMENT__"; +export declare const BARREL_OPTIMIZATION_PREFIX = "__barrel_optimize__"; +export declare const CLIENT_REFERENCE_MANIFEST = "client-reference-manifest"; +export declare const SERVER_REFERENCE_MANIFEST = "server-reference-manifest"; +export declare const MIDDLEWARE_BUILD_MANIFEST = "middleware-build-manifest"; +export declare const MIDDLEWARE_REACT_LOADABLE_MANIFEST = "middleware-react-loadable-manifest"; +export declare const INTERCEPTION_ROUTE_REWRITE_MANIFEST = "interception-route-rewrite-manifest"; +export declare const DYNAMIC_CSS_MANIFEST = "dynamic-css-manifest"; +export declare const CLIENT_STATIC_FILES_RUNTIME_MAIN = "main"; +export declare const CLIENT_STATIC_FILES_RUNTIME_MAIN_APP = "main-app"; +export declare const APP_CLIENT_INTERNALS = "app-pages-internals"; +export declare const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = "react-refresh"; +export declare const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = "webpack"; +export declare const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS = "polyfills"; +export declare const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL: unique symbol; +export declare const DEFAULT_RUNTIME_WEBPACK = "webpack-runtime"; +export declare const EDGE_RUNTIME_WEBPACK = "edge-runtime-webpack"; +export declare const STATIC_PROPS_ID = "__N_SSG"; +export declare const SERVER_PROPS_ID = "__N_SSP"; +export declare const DEFAULT_SERIF_FONT: { + name: string; + xAvgCharWidth: number; + azAvgWidth: number; + unitsPerEm: number; +}; +export declare const DEFAULT_SANS_SERIF_FONT: { + name: string; + xAvgCharWidth: number; + azAvgWidth: number; + unitsPerEm: number; +}; +export declare const STATIC_STATUS_PAGES: string[]; +export declare const TRACE_OUTPUT_VERSION = 1; +export declare const TURBO_TRACE_DEFAULT_MEMORY_LIMIT = 6000; +export declare const RSC_MODULE_TYPES: { + readonly client: "client"; + readonly server: "server"; +}; +export declare const EDGE_UNSUPPORTED_NODE_APIS: string[]; +export declare const SYSTEM_ENTRYPOINTS: Set; diff --git a/e-commerce/node_modules/next/dist/shared/lib/constants.js b/e-commerce/node_modules/next/dist/shared/lib/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..bff67cba3037769f752cb2b54b6243ee5a540c1c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/constants.js @@ -0,0 +1,458 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + APP_CLIENT_INTERNALS: null, + APP_PATHS_MANIFEST: null, + APP_PATH_ROUTES_MANIFEST: null, + AdapterOutputType: null, + BARREL_OPTIMIZATION_PREFIX: null, + BLOCKED_PAGES: null, + BUILD_ID_FILE: null, + BUILD_MANIFEST: null, + CLIENT_PUBLIC_FILES_PATH: null, + CLIENT_REFERENCE_MANIFEST: null, + CLIENT_STATIC_FILES_PATH: null, + CLIENT_STATIC_FILES_RUNTIME_MAIN: null, + CLIENT_STATIC_FILES_RUNTIME_MAIN_APP: null, + CLIENT_STATIC_FILES_RUNTIME_POLYFILLS: null, + CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL: null, + CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH: null, + CLIENT_STATIC_FILES_RUNTIME_WEBPACK: null, + COMPILER_INDEXES: null, + COMPILER_NAMES: null, + CONFIG_FILES: null, + DEFAULT_RUNTIME_WEBPACK: null, + DEFAULT_SANS_SERIF_FONT: null, + DEFAULT_SERIF_FONT: null, + DEV_CLIENT_MIDDLEWARE_MANIFEST: null, + DEV_CLIENT_PAGES_MANIFEST: null, + DYNAMIC_CSS_MANIFEST: null, + EDGE_RUNTIME_WEBPACK: null, + EDGE_UNSUPPORTED_NODE_APIS: null, + EXPORT_DETAIL: null, + EXPORT_MARKER: null, + FUNCTIONS_CONFIG_MANIFEST: null, + IMAGES_MANIFEST: null, + INTERCEPTION_ROUTE_REWRITE_MANIFEST: null, + MIDDLEWARE_BUILD_MANIFEST: null, + MIDDLEWARE_MANIFEST: null, + MIDDLEWARE_REACT_LOADABLE_MANIFEST: null, + MODERN_BROWSERSLIST_TARGET: null, + NEXT_BUILTIN_DOCUMENT: null, + NEXT_FONT_MANIFEST: null, + PAGES_MANIFEST: null, + PHASE_ANALYZE: null, + PHASE_DEVELOPMENT_SERVER: null, + PHASE_EXPORT: null, + PHASE_INFO: null, + PHASE_PRODUCTION_BUILD: null, + PHASE_PRODUCTION_SERVER: null, + PHASE_TEST: null, + PREFETCH_HINTS: null, + PRERENDER_MANIFEST: null, + PREVIEW_PROPS_MANIFEST: null, + REACT_LOADABLE_MANIFEST: null, + REQUEST_INSIGHTS_DEV_ENDPOINT: null, + ROUTES_MANIFEST: null, + RSC_MODULE_TYPES: null, + SERVER_DIRECTORY: null, + SERVER_FILES_MANIFEST: null, + SERVER_PROPS_ID: null, + SERVER_REFERENCE_MANIFEST: null, + STATIC_PROPS_ID: null, + STATIC_STATUS_PAGES: null, + STRING_LITERAL_DROP_BUNDLE: null, + SUBRESOURCE_INTEGRITY_MANIFEST: null, + SYSTEM_ENTRYPOINTS: null, + TRACE_OUTPUT_VERSION: null, + TURBOPACK_CLIENT_BUILD_MANIFEST: null, + TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST: null, + TURBO_TRACE_DEFAULT_MEMORY_LIMIT: null, + UNDERSCORE_GLOBAL_ERROR_ROUTE: null, + UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY: null, + UNDERSCORE_NOT_FOUND_ROUTE: null, + UNDERSCORE_NOT_FOUND_ROUTE_ENTRY: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + APP_CLIENT_INTERNALS: function() { + return APP_CLIENT_INTERNALS; + }, + APP_PATHS_MANIFEST: function() { + return APP_PATHS_MANIFEST; + }, + APP_PATH_ROUTES_MANIFEST: function() { + return APP_PATH_ROUTES_MANIFEST; + }, + AdapterOutputType: function() { + return AdapterOutputType; + }, + BARREL_OPTIMIZATION_PREFIX: function() { + return BARREL_OPTIMIZATION_PREFIX; + }, + BLOCKED_PAGES: function() { + return BLOCKED_PAGES; + }, + BUILD_ID_FILE: function() { + return BUILD_ID_FILE; + }, + BUILD_MANIFEST: function() { + return BUILD_MANIFEST; + }, + CLIENT_PUBLIC_FILES_PATH: function() { + return CLIENT_PUBLIC_FILES_PATH; + }, + CLIENT_REFERENCE_MANIFEST: function() { + return CLIENT_REFERENCE_MANIFEST; + }, + CLIENT_STATIC_FILES_PATH: function() { + return CLIENT_STATIC_FILES_PATH; + }, + CLIENT_STATIC_FILES_RUNTIME_MAIN: function() { + return CLIENT_STATIC_FILES_RUNTIME_MAIN; + }, + CLIENT_STATIC_FILES_RUNTIME_MAIN_APP: function() { + return CLIENT_STATIC_FILES_RUNTIME_MAIN_APP; + }, + CLIENT_STATIC_FILES_RUNTIME_POLYFILLS: function() { + return CLIENT_STATIC_FILES_RUNTIME_POLYFILLS; + }, + CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL: function() { + return CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL; + }, + CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH: function() { + return CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH; + }, + CLIENT_STATIC_FILES_RUNTIME_WEBPACK: function() { + return CLIENT_STATIC_FILES_RUNTIME_WEBPACK; + }, + COMPILER_INDEXES: function() { + return COMPILER_INDEXES; + }, + COMPILER_NAMES: function() { + return COMPILER_NAMES; + }, + CONFIG_FILES: function() { + return CONFIG_FILES; + }, + DEFAULT_RUNTIME_WEBPACK: function() { + return DEFAULT_RUNTIME_WEBPACK; + }, + DEFAULT_SANS_SERIF_FONT: function() { + return DEFAULT_SANS_SERIF_FONT; + }, + DEFAULT_SERIF_FONT: function() { + return DEFAULT_SERIF_FONT; + }, + DEV_CLIENT_MIDDLEWARE_MANIFEST: function() { + return DEV_CLIENT_MIDDLEWARE_MANIFEST; + }, + DEV_CLIENT_PAGES_MANIFEST: function() { + return DEV_CLIENT_PAGES_MANIFEST; + }, + DYNAMIC_CSS_MANIFEST: function() { + return DYNAMIC_CSS_MANIFEST; + }, + EDGE_RUNTIME_WEBPACK: function() { + return EDGE_RUNTIME_WEBPACK; + }, + EDGE_UNSUPPORTED_NODE_APIS: function() { + return EDGE_UNSUPPORTED_NODE_APIS; + }, + EXPORT_DETAIL: function() { + return EXPORT_DETAIL; + }, + EXPORT_MARKER: function() { + return EXPORT_MARKER; + }, + FUNCTIONS_CONFIG_MANIFEST: function() { + return FUNCTIONS_CONFIG_MANIFEST; + }, + IMAGES_MANIFEST: function() { + return IMAGES_MANIFEST; + }, + INTERCEPTION_ROUTE_REWRITE_MANIFEST: function() { + return INTERCEPTION_ROUTE_REWRITE_MANIFEST; + }, + MIDDLEWARE_BUILD_MANIFEST: function() { + return MIDDLEWARE_BUILD_MANIFEST; + }, + MIDDLEWARE_MANIFEST: function() { + return MIDDLEWARE_MANIFEST; + }, + MIDDLEWARE_REACT_LOADABLE_MANIFEST: function() { + return MIDDLEWARE_REACT_LOADABLE_MANIFEST; + }, + MODERN_BROWSERSLIST_TARGET: function() { + return _modernbrowserslisttarget.default; + }, + NEXT_BUILTIN_DOCUMENT: function() { + return NEXT_BUILTIN_DOCUMENT; + }, + NEXT_FONT_MANIFEST: function() { + return NEXT_FONT_MANIFEST; + }, + PAGES_MANIFEST: function() { + return PAGES_MANIFEST; + }, + PHASE_ANALYZE: function() { + return PHASE_ANALYZE; + }, + PHASE_DEVELOPMENT_SERVER: function() { + return PHASE_DEVELOPMENT_SERVER; + }, + PHASE_EXPORT: function() { + return PHASE_EXPORT; + }, + PHASE_INFO: function() { + return PHASE_INFO; + }, + PHASE_PRODUCTION_BUILD: function() { + return PHASE_PRODUCTION_BUILD; + }, + PHASE_PRODUCTION_SERVER: function() { + return PHASE_PRODUCTION_SERVER; + }, + PHASE_TEST: function() { + return PHASE_TEST; + }, + PREFETCH_HINTS: function() { + return PREFETCH_HINTS; + }, + PRERENDER_MANIFEST: function() { + return PRERENDER_MANIFEST; + }, + PREVIEW_PROPS_MANIFEST: function() { + return PREVIEW_PROPS_MANIFEST; + }, + REACT_LOADABLE_MANIFEST: function() { + return REACT_LOADABLE_MANIFEST; + }, + REQUEST_INSIGHTS_DEV_ENDPOINT: function() { + return REQUEST_INSIGHTS_DEV_ENDPOINT; + }, + ROUTES_MANIFEST: function() { + return ROUTES_MANIFEST; + }, + RSC_MODULE_TYPES: function() { + return RSC_MODULE_TYPES; + }, + SERVER_DIRECTORY: function() { + return SERVER_DIRECTORY; + }, + SERVER_FILES_MANIFEST: function() { + return SERVER_FILES_MANIFEST; + }, + SERVER_PROPS_ID: function() { + return SERVER_PROPS_ID; + }, + SERVER_REFERENCE_MANIFEST: function() { + return SERVER_REFERENCE_MANIFEST; + }, + STATIC_PROPS_ID: function() { + return STATIC_PROPS_ID; + }, + STATIC_STATUS_PAGES: function() { + return STATIC_STATUS_PAGES; + }, + STRING_LITERAL_DROP_BUNDLE: function() { + return STRING_LITERAL_DROP_BUNDLE; + }, + SUBRESOURCE_INTEGRITY_MANIFEST: function() { + return SUBRESOURCE_INTEGRITY_MANIFEST; + }, + SYSTEM_ENTRYPOINTS: function() { + return SYSTEM_ENTRYPOINTS; + }, + TRACE_OUTPUT_VERSION: function() { + return TRACE_OUTPUT_VERSION; + }, + TURBOPACK_CLIENT_BUILD_MANIFEST: function() { + return TURBOPACK_CLIENT_BUILD_MANIFEST; + }, + TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST: function() { + return TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST; + }, + TURBO_TRACE_DEFAULT_MEMORY_LIMIT: function() { + return TURBO_TRACE_DEFAULT_MEMORY_LIMIT; + }, + UNDERSCORE_GLOBAL_ERROR_ROUTE: function() { + return _entryconstants.UNDERSCORE_GLOBAL_ERROR_ROUTE; + }, + UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY: function() { + return _entryconstants.UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY; + }, + UNDERSCORE_NOT_FOUND_ROUTE: function() { + return _entryconstants.UNDERSCORE_NOT_FOUND_ROUTE; + }, + UNDERSCORE_NOT_FOUND_ROUTE_ENTRY: function() { + return _entryconstants.UNDERSCORE_NOT_FOUND_ROUTE_ENTRY; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _modernbrowserslisttarget = /*#__PURE__*/ _interop_require_default._(require("./modern-browserslist-target")); +const _entryconstants = require("./entry-constants"); +const COMPILER_NAMES = { + client: 'client', + server: 'server', + edgeServer: 'edge-server' +}; +const COMPILER_INDEXES = { + [COMPILER_NAMES.client]: 0, + [COMPILER_NAMES.server]: 1, + [COMPILER_NAMES.edgeServer]: 2 +}; +var AdapterOutputType = /*#__PURE__*/ function(AdapterOutputType) { + /** + * `PAGES` represents all the React pages that are under `pages/`. + */ AdapterOutputType["PAGES"] = "PAGES"; + /** + * `PAGES_API` represents all the API routes under `pages/api/`. + */ AdapterOutputType["PAGES_API"] = "PAGES_API"; + /** + * `APP_PAGE` represents all the React pages that are under `app/` with the + * filename of `page.{j,t}s{,x}`. + */ AdapterOutputType["APP_PAGE"] = "APP_PAGE"; + /** + * `APP_ROUTE` represents all the API routes and metadata routes that are under `app/` with the + * filename of `route.{j,t}s{,x}`. + */ AdapterOutputType["APP_ROUTE"] = "APP_ROUTE"; + /** + * `PRERENDER` represents an ISR enabled route that might + * have a seeded cache entry or fallback generated during build + */ AdapterOutputType["PRERENDER"] = "PRERENDER"; + /** + * `STATIC_FILE` represents a static file (ie /_next/static) + */ AdapterOutputType["STATIC_FILE"] = "STATIC_FILE"; + /** + * `MIDDLEWARE` represents the middleware output if present + */ AdapterOutputType["MIDDLEWARE"] = "MIDDLEWARE"; + return AdapterOutputType; +}({}); +const PHASE_EXPORT = 'phase-export'; +const PHASE_ANALYZE = 'phase-analyze'; +const PHASE_PRODUCTION_BUILD = 'phase-production-build'; +const PHASE_PRODUCTION_SERVER = 'phase-production-server'; +const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'; +const PHASE_TEST = 'phase-test'; +const PHASE_INFO = 'phase-info'; +const PAGES_MANIFEST = 'pages-manifest.json'; +const APP_PATHS_MANIFEST = 'app-paths-manifest.json'; +const APP_PATH_ROUTES_MANIFEST = 'app-path-routes-manifest.json'; +const BUILD_MANIFEST = 'build-manifest.json'; +const FUNCTIONS_CONFIG_MANIFEST = 'functions-config-manifest.json'; +const SUBRESOURCE_INTEGRITY_MANIFEST = 'subresource-integrity-manifest'; +const NEXT_FONT_MANIFEST = 'next-font-manifest'; +const EXPORT_MARKER = 'export-marker.json'; +const EXPORT_DETAIL = 'export-detail.json'; +const PRERENDER_MANIFEST = 'prerender-manifest.json'; +const PREFETCH_HINTS = 'prefetch-hints.json'; +const PREVIEW_PROPS_MANIFEST = 'preview-props.json'; +const ROUTES_MANIFEST = 'routes-manifest.json'; +const IMAGES_MANIFEST = 'images-manifest.json'; +const SERVER_FILES_MANIFEST = 'required-server-files'; +const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json'; +const REQUEST_INSIGHTS_DEV_ENDPOINT = '/_next/development/request-insights'; +const MIDDLEWARE_MANIFEST = 'middleware-manifest.json'; +const TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST = '_clientMiddlewareManifest.js'; +const TURBOPACK_CLIENT_BUILD_MANIFEST = 'client-build-manifest.json'; +const DEV_CLIENT_MIDDLEWARE_MANIFEST = '_devMiddlewareManifest.json'; +const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json'; +const SERVER_DIRECTORY = 'server'; +const CONFIG_FILES = [ + 'next.config.js', + 'next.config.mjs', + 'next.config.ts', + // process.features can be undefined on Edge runtime + // TODO: Remove `as any` once we bump @types/node to v22.10.0+ + ...process?.features?.typescript ? [ + 'next.config.mts' + ] : [] +]; +const BUILD_ID_FILE = 'BUILD_ID'; +const BLOCKED_PAGES = [ + '/_document', + '/_app', + '/_error' +]; +const CLIENT_PUBLIC_FILES_PATH = 'public'; +const CLIENT_STATIC_FILES_PATH = 'static'; +const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__'; +const NEXT_BUILTIN_DOCUMENT = '__NEXT_BUILTIN_DOCUMENT__'; +const BARREL_OPTIMIZATION_PREFIX = '__barrel_optimize__'; +const CLIENT_REFERENCE_MANIFEST = 'client-reference-manifest'; +const SERVER_REFERENCE_MANIFEST = 'server-reference-manifest'; +const MIDDLEWARE_BUILD_MANIFEST = 'middleware-build-manifest'; +const MIDDLEWARE_REACT_LOADABLE_MANIFEST = 'middleware-react-loadable-manifest'; +const INTERCEPTION_ROUTE_REWRITE_MANIFEST = 'interception-route-rewrite-manifest'; +const DYNAMIC_CSS_MANIFEST = 'dynamic-css-manifest'; +const CLIENT_STATIC_FILES_RUNTIME_MAIN = `main`; +const CLIENT_STATIC_FILES_RUNTIME_MAIN_APP = `${CLIENT_STATIC_FILES_RUNTIME_MAIN}-app`; +const APP_CLIENT_INTERNALS = 'app-pages-internals'; +const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `react-refresh`; +const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack`; +const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS = 'polyfills'; +const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(CLIENT_STATIC_FILES_RUNTIME_POLYFILLS); +const DEFAULT_RUNTIME_WEBPACK = 'webpack-runtime'; +const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack'; +const STATIC_PROPS_ID = '__N_SSG'; +const SERVER_PROPS_ID = '__N_SSP'; +const DEFAULT_SERIF_FONT = { + name: 'Times New Roman', + xAvgCharWidth: 821, + azAvgWidth: 854.3953488372093, + unitsPerEm: 2048 +}; +const DEFAULT_SANS_SERIF_FONT = { + name: 'Arial', + xAvgCharWidth: 904, + azAvgWidth: 934.5116279069767, + unitsPerEm: 2048 +}; +const STATIC_STATUS_PAGES = [ + '/500' +]; +const TRACE_OUTPUT_VERSION = 1; +const TURBO_TRACE_DEFAULT_MEMORY_LIMIT = 6000; +const RSC_MODULE_TYPES = { + client: 'client', + server: 'server' +}; +const EDGE_UNSUPPORTED_NODE_APIS = [ + 'clearImmediate', + 'setImmediate', + 'BroadcastChannel', + 'ByteLengthQueuingStrategy', + 'CompressionStream', + 'CountQueuingStrategy', + 'DecompressionStream', + 'DomException', + 'MessageChannel', + 'MessageEvent', + 'MessagePort', + 'ReadableByteStreamController', + 'ReadableStreamBYOBRequest', + 'ReadableStreamDefaultController', + 'TransformStreamDefaultController', + 'WritableStreamDefaultController' +]; +const SYSTEM_ENTRYPOINTS = new Set([ + CLIENT_STATIC_FILES_RUNTIME_MAIN, + CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, + CLIENT_STATIC_FILES_RUNTIME_MAIN_APP +]); + +if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') { + Object.defineProperty(exports.default, '__esModule', { value: true }); + Object.assign(exports.default, exports); + module.exports = exports.default; +} + +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/constants.js.map b/e-commerce/node_modules/next/dist/shared/lib/constants.js.map new file mode 100644 index 0000000000000000000000000000000000000000..228ca56da65d67ad17d8a949ff13f0b137a3a6ff --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/constants.ts"],"sourcesContent":["import MODERN_BROWSERSLIST_TARGET from './modern-browserslist-target'\n\nexport { MODERN_BROWSERSLIST_TARGET }\n\nexport type ValueOf = Required[keyof T]\n\nexport const COMPILER_NAMES = {\n client: 'client',\n server: 'server',\n edgeServer: 'edge-server',\n} as const\n\nexport type CompilerNameValues = ValueOf\n\nexport const COMPILER_INDEXES: {\n [compilerKey in CompilerNameValues]: number\n} = {\n [COMPILER_NAMES.client]: 0,\n [COMPILER_NAMES.server]: 1,\n [COMPILER_NAMES.edgeServer]: 2,\n} as const\n\n// Re-export entry constants for backward compatibility\nexport {\n UNDERSCORE_NOT_FOUND_ROUTE,\n UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,\n UNDERSCORE_GLOBAL_ERROR_ROUTE,\n UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY,\n} from './entry-constants'\n\nexport enum AdapterOutputType {\n /**\n * `PAGES` represents all the React pages that are under `pages/`.\n */\n PAGES = 'PAGES',\n\n /**\n * `PAGES_API` represents all the API routes under `pages/api/`.\n */\n PAGES_API = 'PAGES_API',\n /**\n * `APP_PAGE` represents all the React pages that are under `app/` with the\n * filename of `page.{j,t}s{,x}`.\n */\n APP_PAGE = 'APP_PAGE',\n\n /**\n * `APP_ROUTE` represents all the API routes and metadata routes that are under `app/` with the\n * filename of `route.{j,t}s{,x}`.\n */\n APP_ROUTE = 'APP_ROUTE',\n\n /**\n * `PRERENDER` represents an ISR enabled route that might\n * have a seeded cache entry or fallback generated during build\n */\n PRERENDER = 'PRERENDER',\n\n /**\n * `STATIC_FILE` represents a static file (ie /_next/static)\n */\n STATIC_FILE = 'STATIC_FILE',\n\n /**\n * `MIDDLEWARE` represents the middleware output if present\n */\n MIDDLEWARE = 'MIDDLEWARE',\n}\n\nexport const PHASE_EXPORT = 'phase-export'\nexport const PHASE_ANALYZE = 'phase-analyze'\nexport const PHASE_PRODUCTION_BUILD = 'phase-production-build'\nexport const PHASE_PRODUCTION_SERVER = 'phase-production-server'\nexport const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'\nexport const PHASE_TEST = 'phase-test'\nexport const PHASE_INFO = 'phase-info'\n\nexport type PHASE_TYPE =\n | typeof PHASE_INFO\n | typeof PHASE_TEST\n | typeof PHASE_EXPORT\n | typeof PHASE_ANALYZE\n | typeof PHASE_PRODUCTION_BUILD\n | typeof PHASE_PRODUCTION_SERVER\n | typeof PHASE_DEVELOPMENT_SERVER\n\nexport const PAGES_MANIFEST = 'pages-manifest.json'\nexport const APP_PATHS_MANIFEST = 'app-paths-manifest.json'\nexport const APP_PATH_ROUTES_MANIFEST = 'app-path-routes-manifest.json'\nexport const BUILD_MANIFEST = 'build-manifest.json'\nexport const FUNCTIONS_CONFIG_MANIFEST = 'functions-config-manifest.json'\nexport const SUBRESOURCE_INTEGRITY_MANIFEST = 'subresource-integrity-manifest'\nexport const NEXT_FONT_MANIFEST = 'next-font-manifest'\nexport const EXPORT_MARKER = 'export-marker.json'\nexport const EXPORT_DETAIL = 'export-detail.json'\nexport const PRERENDER_MANIFEST = 'prerender-manifest.json'\nexport const PREFETCH_HINTS = 'prefetch-hints.json'\nexport const PREVIEW_PROPS_MANIFEST = 'preview-props.json'\nexport const ROUTES_MANIFEST = 'routes-manifest.json'\nexport const IMAGES_MANIFEST = 'images-manifest.json'\nexport const SERVER_FILES_MANIFEST = 'required-server-files'\nexport const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json'\nexport const REQUEST_INSIGHTS_DEV_ENDPOINT =\n '/_next/development/request-insights'\nexport const MIDDLEWARE_MANIFEST = 'middleware-manifest.json'\nexport const TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST =\n '_clientMiddlewareManifest.js'\nexport const TURBOPACK_CLIENT_BUILD_MANIFEST = 'client-build-manifest.json'\nexport const DEV_CLIENT_MIDDLEWARE_MANIFEST = '_devMiddlewareManifest.json'\nexport const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json'\nexport const SERVER_DIRECTORY = 'server'\nexport const CONFIG_FILES = [\n 'next.config.js',\n 'next.config.mjs',\n 'next.config.ts',\n // process.features can be undefined on Edge runtime\n // TODO: Remove `as any` once we bump @types/node to v22.10.0+\n ...((process?.features as any)?.typescript ? ['next.config.mts'] : []),\n]\nexport const BUILD_ID_FILE = 'BUILD_ID'\nexport const BLOCKED_PAGES = ['/_document', '/_app', '/_error']\nexport const CLIENT_PUBLIC_FILES_PATH = 'public'\nexport const CLIENT_STATIC_FILES_PATH = 'static'\nexport const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__'\nexport const NEXT_BUILTIN_DOCUMENT = '__NEXT_BUILTIN_DOCUMENT__'\nexport const BARREL_OPTIMIZATION_PREFIX = '__barrel_optimize__'\n\n// server/[entry]/page_client-reference-manifest.js\nexport const CLIENT_REFERENCE_MANIFEST = 'client-reference-manifest'\n// server/server-reference-manifest\nexport const SERVER_REFERENCE_MANIFEST = 'server-reference-manifest'\n// server/middleware-build-manifest.js\nexport const MIDDLEWARE_BUILD_MANIFEST = 'middleware-build-manifest'\n// server/middleware-react-loadable-manifest.js\nexport const MIDDLEWARE_REACT_LOADABLE_MANIFEST =\n 'middleware-react-loadable-manifest'\n// server/interception-route-rewrite-manifest.js\nexport const INTERCEPTION_ROUTE_REWRITE_MANIFEST =\n 'interception-route-rewrite-manifest'\n// server/dynamic-css-manifest.js\nexport const DYNAMIC_CSS_MANIFEST = 'dynamic-css-manifest'\n\n// static/runtime/main.js\nexport const CLIENT_STATIC_FILES_RUNTIME_MAIN = `main`\nexport const CLIENT_STATIC_FILES_RUNTIME_MAIN_APP = `${CLIENT_STATIC_FILES_RUNTIME_MAIN}-app`\n// next internal client components chunk for layouts\nexport const APP_CLIENT_INTERNALS = 'app-pages-internals'\n// static/runtime/react-refresh.js\nexport const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `react-refresh`\n// static/runtime/webpack.js\nexport const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack`\n// static/runtime/polyfills.js\nexport const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS = 'polyfills'\nexport const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(\n CLIENT_STATIC_FILES_RUNTIME_POLYFILLS\n)\nexport const DEFAULT_RUNTIME_WEBPACK = 'webpack-runtime'\nexport const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack'\nexport const STATIC_PROPS_ID = '__N_SSG'\nexport const SERVER_PROPS_ID = '__N_SSP'\nexport const DEFAULT_SERIF_FONT = {\n name: 'Times New Roman',\n xAvgCharWidth: 821,\n azAvgWidth: 854.3953488372093,\n unitsPerEm: 2048,\n}\nexport const DEFAULT_SANS_SERIF_FONT = {\n name: 'Arial',\n xAvgCharWidth: 904,\n azAvgWidth: 934.5116279069767,\n unitsPerEm: 2048,\n}\nexport const STATIC_STATUS_PAGES = ['/500']\nexport const TRACE_OUTPUT_VERSION = 1\n// in `MB`\nexport const TURBO_TRACE_DEFAULT_MEMORY_LIMIT = 6000\n\nexport const RSC_MODULE_TYPES = {\n client: 'client',\n server: 'server',\n} as const\n\n// comparing\n// https://nextjs.org/docs/api-reference/edge-runtime\n// with\n// https://nodejs.org/docs/latest/api/globals.html\nexport const EDGE_UNSUPPORTED_NODE_APIS = [\n 'clearImmediate',\n 'setImmediate',\n 'BroadcastChannel',\n 'ByteLengthQueuingStrategy',\n 'CompressionStream',\n 'CountQueuingStrategy',\n 'DecompressionStream',\n 'DomException',\n 'MessageChannel',\n 'MessageEvent',\n 'MessagePort',\n 'ReadableByteStreamController',\n 'ReadableStreamBYOBRequest',\n 'ReadableStreamDefaultController',\n 'TransformStreamDefaultController',\n 'WritableStreamDefaultController',\n]\n\nexport const SYSTEM_ENTRYPOINTS = new Set([\n CLIENT_STATIC_FILES_RUNTIME_MAIN,\n CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,\n CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,\n])\n"],"names":["APP_CLIENT_INTERNALS","APP_PATHS_MANIFEST","APP_PATH_ROUTES_MANIFEST","AdapterOutputType","BARREL_OPTIMIZATION_PREFIX","BLOCKED_PAGES","BUILD_ID_FILE","BUILD_MANIFEST","CLIENT_PUBLIC_FILES_PATH","CLIENT_REFERENCE_MANIFEST","CLIENT_STATIC_FILES_PATH","CLIENT_STATIC_FILES_RUNTIME_MAIN","CLIENT_STATIC_FILES_RUNTIME_MAIN_APP","CLIENT_STATIC_FILES_RUNTIME_POLYFILLS","CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL","CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH","CLIENT_STATIC_FILES_RUNTIME_WEBPACK","COMPILER_INDEXES","COMPILER_NAMES","CONFIG_FILES","DEFAULT_RUNTIME_WEBPACK","DEFAULT_SANS_SERIF_FONT","DEFAULT_SERIF_FONT","DEV_CLIENT_MIDDLEWARE_MANIFEST","DEV_CLIENT_PAGES_MANIFEST","DYNAMIC_CSS_MANIFEST","EDGE_RUNTIME_WEBPACK","EDGE_UNSUPPORTED_NODE_APIS","EXPORT_DETAIL","EXPORT_MARKER","FUNCTIONS_CONFIG_MANIFEST","IMAGES_MANIFEST","INTERCEPTION_ROUTE_REWRITE_MANIFEST","MIDDLEWARE_BUILD_MANIFEST","MIDDLEWARE_MANIFEST","MIDDLEWARE_REACT_LOADABLE_MANIFEST","MODERN_BROWSERSLIST_TARGET","NEXT_BUILTIN_DOCUMENT","NEXT_FONT_MANIFEST","PAGES_MANIFEST","PHASE_ANALYZE","PHASE_DEVELOPMENT_SERVER","PHASE_EXPORT","PHASE_INFO","PHASE_PRODUCTION_BUILD","PHASE_PRODUCTION_SERVER","PHASE_TEST","PREFETCH_HINTS","PRERENDER_MANIFEST","PREVIEW_PROPS_MANIFEST","REACT_LOADABLE_MANIFEST","REQUEST_INSIGHTS_DEV_ENDPOINT","ROUTES_MANIFEST","RSC_MODULE_TYPES","SERVER_DIRECTORY","SERVER_FILES_MANIFEST","SERVER_PROPS_ID","SERVER_REFERENCE_MANIFEST","STATIC_PROPS_ID","STATIC_STATUS_PAGES","STRING_LITERAL_DROP_BUNDLE","SUBRESOURCE_INTEGRITY_MANIFEST","SYSTEM_ENTRYPOINTS","TRACE_OUTPUT_VERSION","TURBOPACK_CLIENT_BUILD_MANIFEST","TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST","TURBO_TRACE_DEFAULT_MEMORY_LIMIT","UNDERSCORE_GLOBAL_ERROR_ROUTE","UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY","UNDERSCORE_NOT_FOUND_ROUTE","UNDERSCORE_NOT_FOUND_ROUTE_ENTRY","client","server","edgeServer","process","features","typescript","Symbol","name","xAvgCharWidth","azAvgWidth","unitsPerEm","Set"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAkJaA,oBAAoB;eAApBA;;IA3DAC,kBAAkB;eAAlBA;;IACAC,wBAAwB;eAAxBA;;IA1DDC,iBAAiB;eAAjBA;;IA+FCC,0BAA0B;eAA1BA;;IALAC,aAAa;eAAbA;;IADAC,aAAa;eAAbA;;IA9BAC,cAAc;eAAdA;;IAgCAC,wBAAwB;eAAxBA;;IAOAC,yBAAyB;eAAzBA;;IANAC,wBAAwB;eAAxBA;;IAqBAC,gCAAgC;eAAhCA;;IACAC,oCAAoC;eAApCA;;IAQAC,qCAAqC;eAArCA;;IACAC,4CAA4C;eAA5CA;;IALAC,yCAAyC;eAAzCA;;IAEAC,mCAAmC;eAAnCA;;IAxIAC,gBAAgB;eAAhBA;;IARAC,cAAc;eAAdA;;IAyGAC,YAAY;eAAZA;;IA6CAC,uBAAuB;eAAvBA;;IAUAC,uBAAuB;eAAvBA;;IANAC,kBAAkB;eAAlBA;;IApDAC,8BAA8B;eAA9BA;;IAPAC,yBAAyB;eAAzBA;;IAuCAC,oBAAoB;eAApBA;;IAiBAC,oBAAoB;eAApBA;;IA6BAC,0BAA0B;eAA1BA;;IA5FAC,aAAa;e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4BAA4B;AAElC,MAAMxB,4BAA4B;AAElC,MAAME,qCACX;AAEK,MAAMH,sCACX;AAEK,MAAMP,uBAAuB;AAG7B,MAAMd,mCAAmC,CAAC,IAAI,CAAC;AAC/C,MAAMC,uCAAuC,GAAGD,iCAAiC,IAAI,CAAC;AAEtF,MAAMX,uBAAuB;AAE7B,MAAMe,4CAA4C,CAAC,aAAa,CAAC;AAEjE,MAAMC,sCAAsC,CAAC,OAAO,CAAC;AAErD,MAAMH,wCAAwC;AAC9C,MAAMC,+CAA+C+D,OAC1DhE;AAEK,MAAMO,0BAA0B;AAChC,MAAMM,uBAAuB;AAC7B,MAAMgC,kBAAkB;AACxB,MAAMF,kBAAkB;AACxB,MAAMlC,qBAAqB;IAChCwD,MAAM;IACNC,eAAe;IACfC,YAAY;IACZC,YAAY;AACd;AACO,MAAM5D,0BAA0B;IACrCyD,MAAM;IACNC,eAAe;IACfC,YAAY;IACZC,YAAY;AACd;AACO,MAAMtB,sBAAsB;IAAC;CAAO;AACpC,MAAMI,uBAAuB;AAE7B,MAAMG,mCAAmC;AAEzC,MAAMb,mBAAmB;IAC9BkB,QAAQ;IACRC,QAAQ;AACV;AAMO,MAAM7C,6BAA6B;IACxC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAEM,MAAMmC,qBAAqB,IAAIoB,IAAY;IAChDvE;IACAI;IACAH;CACD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/deep-freeze.d.ts b/e-commerce/node_modules/next/dist/shared/lib/deep-freeze.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0a4d5e13e5ef3948e2e2e87b644ede74c8204f4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/deep-freeze.d.ts @@ -0,0 +1,10 @@ +import type { DeepReadonly } from './deep-readonly'; +/** + * Recursively freezes an object and all of its properties. This prevents the + * object from being modified at runtime. When the JS runtime is running in + * strict mode, any attempts to modify a frozen object will throw an error. + * + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze + * @param obj The object to freeze. + */ +export declare function deepFreeze(obj: T): DeepReadonly; diff --git a/e-commerce/node_modules/next/dist/shared/lib/deep-freeze.js b/e-commerce/node_modules/next/dist/shared/lib/deep-freeze.js new file mode 100644 index 0000000000000000000000000000000000000000..27022afc62a6b4cc65467d43760261afc5e4ada8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/deep-freeze.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "deepFreeze", { + enumerable: true, + get: function() { + return deepFreeze; + } +}); +function deepFreeze(obj) { + // If the object is already frozen, there's no need to freeze it again. + if (Object.isFrozen(obj)) return obj; + // An array is an object, but we also want to freeze each element in the array + // as well. + if (Array.isArray(obj)) { + for (const item of obj){ + if (!item || typeof item !== 'object') continue; + deepFreeze(item); + } + return Object.freeze(obj); + } + for (const value of Object.values(obj)){ + if (!value || typeof value !== 'object') continue; + deepFreeze(value); + } + return Object.freeze(obj); +} + +//# sourceMappingURL=deep-freeze.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/deep-freeze.js.map b/e-commerce/node_modules/next/dist/shared/lib/deep-freeze.js.map new file mode 100644 index 0000000000000000000000000000000000000000..42c22a5c67d9dec2e87ffef92c3b181ad414513e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/deep-freeze.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/deep-freeze.ts"],"sourcesContent":["import type { DeepReadonly } from './deep-readonly'\n\n/**\n * Recursively freezes an object and all of its properties. This prevents the\n * object from being modified at runtime. When the JS runtime is running in\n * strict mode, any attempts to modify a frozen object will throw an error.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\n * @param obj The object to freeze.\n */\nexport function deepFreeze(obj: T): DeepReadonly {\n // If the object is already frozen, there's no need to freeze it again.\n if (Object.isFrozen(obj)) return obj as DeepReadonly\n\n // An array is an object, but we also want to freeze each element in the array\n // as well.\n if (Array.isArray(obj)) {\n for (const item of obj) {\n if (!item || typeof item !== 'object') continue\n deepFreeze(item)\n }\n\n return Object.freeze(obj) as DeepReadonly\n }\n\n for (const value of Object.values(obj)) {\n if (!value || typeof value !== 'object') continue\n deepFreeze(value)\n }\n\n return Object.freeze(obj) as DeepReadonly\n}\n"],"names":["deepFreeze","obj","Object","isFrozen","Array","isArray","item","freeze","value","values"],"mappings":";;;;+BAUgBA;;;eAAAA;;;AAAT,SAASA,WAA6BC,GAAM;IACjD,uEAAuE;IACvE,IAAIC,OAAOC,QAAQ,CAACF,MAAM,OAAOA;IAEjC,8EAA8E;IAC9E,WAAW;IACX,IAAIG,MAAMC,OAAO,CAACJ,MAAM;QACtB,KAAK,MAAMK,QAAQL,IAAK;YACtB,IAAI,CAACK,QAAQ,OAAOA,SAAS,UAAU;YACvCN,WAAWM;QACb;QAEA,OAAOJ,OAAOK,MAAM,CAACN;IACvB;IAEA,KAAK,MAAMO,SAASN,OAAOO,MAAM,CAACR,KAAM;QACtC,IAAI,CAACO,SAAS,OAAOA,UAAU,UAAU;QACzCR,WAAWQ;IACb;IAEA,OAAON,OAAOK,MAAM,CAACN;AACvB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/deep-readonly.d.ts b/e-commerce/node_modules/next/dist/shared/lib/deep-readonly.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..842726cd9105d68ce20c8a98fa70c73e9a42e415 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/deep-readonly.d.ts @@ -0,0 +1,8 @@ +/** + * A type that represents a deeply readonly object. This is similar to + * TypeScript's `Readonly` type, but it recursively applies the `readonly` + * modifier to all properties of an object and all elements of arrays. + */ +export type DeepReadonly = T extends (infer R)[] ? ReadonlyArray> : T extends object ? { + readonly [K in keyof T]: DeepReadonly; +} : T; diff --git a/e-commerce/node_modules/next/dist/shared/lib/deep-readonly.js b/e-commerce/node_modules/next/dist/shared/lib/deep-readonly.js new file mode 100644 index 0000000000000000000000000000000000000000..a836d80de4daaedeadfbc5ff2fbf632f144bacb0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/deep-readonly.js @@ -0,0 +1,10 @@ +/** + * A type that represents a deeply readonly object. This is similar to + * TypeScript's `Readonly` type, but it recursively applies the `readonly` + * modifier to all properties of an object and all elements of arrays. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=deep-readonly.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/deep-readonly.js.map b/e-commerce/node_modules/next/dist/shared/lib/deep-readonly.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f8b66705368e8fc665f40af355ab9ae63fa81eef --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/deep-readonly.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/deep-readonly.ts"],"sourcesContent":["/**\n * A type that represents a deeply readonly object. This is similar to\n * TypeScript's `Readonly` type, but it recursively applies the `readonly`\n * modifier to all properties of an object and all elements of arrays.\n */\nexport type DeepReadonly = T extends (infer R)[]\n ? ReadonlyArray>\n : T extends object\n ? {\n readonly [K in keyof T]: DeepReadonly\n }\n : T\n"],"names":[],"mappings":"AAAA;;;;CAIC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/deployment-id.d.ts b/e-commerce/node_modules/next/dist/shared/lib/deployment-id.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..03ca66b25ccd26a708820b7c1b8545b71f903df5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/deployment-id.d.ts @@ -0,0 +1,4 @@ +export declare function getDeploymentId(): string | undefined; +export declare function getDeploymentIdQuery(ampersand?: boolean): string; +export declare function getAssetToken(): string | undefined; +export declare function getAssetTokenQuery(ampersand?: boolean): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/deployment-id.js b/e-commerce/node_modules/next/dist/shared/lib/deployment-id.js new file mode 100644 index 0000000000000000000000000000000000000000..c683540f9c26de8aaeca649a3e773edea16063a7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/deployment-id.js @@ -0,0 +1,63 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getAssetToken: null, + getAssetTokenQuery: null, + getDeploymentId: null, + getDeploymentIdQuery: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getAssetToken: function() { + return getAssetToken; + }, + getAssetTokenQuery: function() { + return getAssetTokenQuery; + }, + getDeploymentId: function() { + return getDeploymentId; + }, + getDeploymentIdQuery: function() { + return getDeploymentIdQuery; + } +}); +let deploymentId; +if (typeof window !== 'undefined') { + deploymentId = document.documentElement.dataset.dplId; + // Immediately remove the attribute to prevent hydration errors (the dplId was inserted into the + // HTML only), React isn't aware of it at all. + document.documentElement.removeAttribute('data-dpl-id'); +} else { + // Client side: replaced with globalThis.NEXT_DEPLOYMENT_ID + // Server side: left as is or replaced with a string or replaced with false + deploymentId = process.env.NEXT_DEPLOYMENT_ID || undefined; +} +function getDeploymentId() { + return deploymentId; +} +function getDeploymentIdQuery(ampersand = false) { + let id = getDeploymentId(); + if (id) { + return `${ampersand ? '&' : '?'}dpl=${id}`; + } + return ''; +} +function getAssetToken() { + return process.env.NEXT_SUPPORTS_IMMUTABLE_ASSETS ? undefined : process.env.NEXT_DEPLOYMENT_ID; +} +function getAssetTokenQuery(ampersand = false) { + let id = getAssetToken(); + if (id) { + return `${ampersand ? '&' : '?'}dpl=${id}`; + } + return ''; +} + +//# sourceMappingURL=deployment-id.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/deployment-id.js.map b/e-commerce/node_modules/next/dist/shared/lib/deployment-id.js.map new file mode 100644 index 0000000000000000000000000000000000000000..80851d41ee71228baa02271d0e1e633e24a09be6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/deployment-id.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/deployment-id.ts"],"sourcesContent":["let deploymentId: string | undefined\n\nif (typeof window !== 'undefined') {\n deploymentId = document.documentElement.dataset.dplId\n // Immediately remove the attribute to prevent hydration errors (the dplId was inserted into the\n // HTML only), React isn't aware of it at all.\n document.documentElement.removeAttribute('data-dpl-id')\n} else {\n // Client side: replaced with globalThis.NEXT_DEPLOYMENT_ID\n // Server side: left as is or replaced with a string or replaced with false\n deploymentId = process.env.NEXT_DEPLOYMENT_ID || undefined\n}\n\nexport function getDeploymentId(): string | undefined {\n return deploymentId\n}\n\nexport function getDeploymentIdQuery(ampersand = false): string {\n let id = getDeploymentId()\n if (id) {\n return `${ampersand ? '&' : '?'}dpl=${id}`\n }\n return ''\n}\n\nexport function getAssetToken(): string | undefined {\n return process.env.NEXT_SUPPORTS_IMMUTABLE_ASSETS\n ? undefined\n : process.env.NEXT_DEPLOYMENT_ID\n}\n\nexport function getAssetTokenQuery(ampersand = false): string {\n let id = getAssetToken()\n if (id) {\n return `${ampersand ? '&' : '?'}dpl=${id}`\n }\n return ''\n}\n"],"names":["getAssetToken","getAssetTokenQuery","getDeploymentId","getDeploymentIdQuery","deploymentId","window","document","documentElement","dataset","dplId","removeAttribute","process","env","NEXT_DEPLOYMENT_ID","undefined","ampersand","id","NEXT_SUPPORTS_IMMUTABLE_ASSETS"],"mappings":";;;;;;;;;;;;;;;;;IAyBgBA,aAAa;eAAbA;;IAMAC,kBAAkB;eAAlBA;;IAlBAC,eAAe;eAAfA;;IAIAC,oBAAoB;eAApBA;;;AAjBhB,IAAIC;AAEJ,IAAI,OAAOC,WAAW,aAAa;IACjCD,eAAeE,SAASC,eAAe,CAACC,OAAO,CAACC,KAAK;IACrD,gGAAgG;IAChG,8CAA8C;IAC9CH,SAASC,eAAe,CAACG,eAAe,CAAC;AAC3C,OAAO;IACL,2DAA2D;IAC3D,2EAA2E;IAC3EN,eAAeO,QAAQC,GAAG,CAACC,kBAAkB,IAAIC;AACnD;AAEO,SAASZ;IACd,OAAOE;AACT;AAEO,SAASD,qBAAqBY,YAAY,KAAK;IACpD,IAAIC,KAAKd;IACT,IAAIc,IAAI;QACN,OAAO,GAAGD,YAAY,MAAM,IAAI,IAAI,EAAEC,IAAI;IAC5C;IACA,OAAO;AACT;AAEO,SAAShB;IACd,OAAOW,QAAQC,GAAG,CAACK,8BAA8B,GAC7CH,YACAH,QAAQC,GAAG,CAACC,kBAAkB;AACpC;AAEO,SAASZ,mBAAmBc,YAAY,KAAK;IAClD,IAAIC,KAAKhB;IACT,IAAIgB,IAAI;QACN,OAAO,GAAGD,YAAY,MAAM,IAAI,IAAI,EAAEC,IAAI;IAC5C;IACA,OAAO;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/dset.d.ts b/e-commerce/node_modules/next/dist/shared/lib/dset.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7883ed0fcc10d6a5cbe1196d9c83c05a17fd9c5a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/dset.d.ts @@ -0,0 +1,5 @@ +export function dset( + obj: T, + keys: string | ArrayLike, + value: V +): void diff --git a/e-commerce/node_modules/next/dist/shared/lib/dset.js b/e-commerce/node_modules/next/dist/shared/lib/dset.js new file mode 100644 index 0000000000000000000000000000000000000000..dc0e7816ac6b57817a34d2a5300150bdc7fd7510 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/dset.js @@ -0,0 +1,34 @@ +/* +The MIT License (MIT) + +Copyright (c) Luke Edwards (lukeed.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ // This file is based on https://github.com/lukeed/dset/blob/v3.1.3/src/index.js +// It's been edited for the needs of this script +// See the LICENSE at the top of the file +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "dset", { + enumerable: true, + get: function() { + return dset; + } +}); +function dset(obj, keys, val) { + keys.split && (keys = keys.split('.')); + var i = 0, l = keys.length, t = obj, x, k; + while(i < l){ + k = keys[i++]; + if (k === '__proto__' || k === 'constructor' || k === 'prototype') break; + t = t[k] = i === l ? val : typeof (x = t[k]) === typeof keys ? x : keys[i] * 0 !== 0 || !!~('' + keys[i]).indexOf('.') ? {} : []; + } +} + +//# sourceMappingURL=dset.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/dset.js.map b/e-commerce/node_modules/next/dist/shared/lib/dset.js.map new file mode 100644 index 0000000000000000000000000000000000000000..762a32e90fc7b13c5d96d5d542aa44887e09c486 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/dset.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/dset.js"],"sourcesContent":["/*\nThe MIT License (MIT)\n\nCopyright (c) Luke Edwards (lukeed.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n// This file is based on https://github.com/lukeed/dset/blob/v3.1.3/src/index.js\n// It's been edited for the needs of this script\n// See the LICENSE at the top of the file\n\nexport function dset(obj, keys, val) {\n keys.split && (keys = keys.split('.'))\n var i = 0,\n l = keys.length,\n t = obj,\n x,\n k\n while (i < l) {\n k = keys[i++]\n if (k === '__proto__' || k === 'constructor' || k === 'prototype') break\n t = t[k] =\n i === l\n ? val\n : typeof (x = t[k]) === typeof keys\n ? x\n : keys[i] * 0 !== 0 || !!~('' + keys[i]).indexOf('.')\n ? {}\n : []\n }\n}\n"],"names":["dset","obj","keys","val","split","i","l","length","t","x","k","indexOf"],"mappings":"AAAA;;;;;;;;;;AAUA,GAEA,gFAAgF;AAChF,gDAAgD;AAChD,yCAAyC;;;;;+BAEzBA;;;eAAAA;;;AAAT,SAASA,KAAKC,GAAG,EAAEC,IAAI,EAAEC,GAAG;IACjCD,KAAKE,KAAK,IAAKF,CAAAA,OAAOA,KAAKE,KAAK,CAAC,IAAG;IACpC,IAAIC,IAAI,GACNC,IAAIJ,KAAKK,MAAM,EACfC,IAAIP,KACJQ,GACAC;IACF,MAAOL,IAAIC,EAAG;QACZI,IAAIR,IAAI,CAACG,IAAI;QACb,IAAIK,MAAM,eAAeA,MAAM,iBAAiBA,MAAM,aAAa;QACnEF,IAAIA,CAAC,CAACE,EAAE,GACNL,MAAMC,IACFH,MACA,OAAQM,CAAAA,IAAID,CAAC,CAACE,EAAE,AAAD,MAAO,OAAOR,OAC3BO,IACAP,IAAI,CAACG,EAAE,GAAG,MAAM,KAAK,CAAC,CAAC,CAAC,AAAC,CAAA,KAAKH,IAAI,CAACG,EAAE,AAAD,EAAGM,OAAO,CAAC,OAC7C,CAAC,IACD,EAAE;IACd;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/dynamic.d.ts b/e-commerce/node_modules/next/dist/shared/lib/dynamic.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f756d86661e32d607d6b7a972c31038df3af8ce0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/dynamic.d.ts @@ -0,0 +1,38 @@ +import React from 'react'; +type ComponentModule

= { + default: React.ComponentType

; +}; +export declare type LoaderComponent

= Promise | ComponentModule

>; +export declare type Loader

= (() => LoaderComponent

) | LoaderComponent

; +export type LoaderMap = { + [module: string]: () => Loader; +}; +export type LoadableGeneratedOptions = { + webpack?(): any; + modules?(): LoaderMap; +}; +export type DynamicOptionsLoadingProps = { + error?: Error | null; + isLoading?: boolean; + pastDelay?: boolean; + retry?: () => void; + timedOut?: boolean; +}; +export type DynamicOptions

= LoadableGeneratedOptions & { + loading?: (loadingProps: DynamicOptionsLoadingProps) => React.ReactNode; + loader?: Loader

| LoaderMap; + loadableGenerated?: LoadableGeneratedOptions; + ssr?: boolean; +}; +export type LoadableOptions

= DynamicOptions

; +export type LoadableFn

= (opts: LoadableOptions

) => React.ComponentType

; +export type LoadableComponent

= React.ComponentType

; +export declare function noSSR

(LoadableInitializer: LoadableFn

, loadableOptions: DynamicOptions

): React.ComponentType

; +/** + * This function lets you dynamically import a component. + * It uses [React.lazy()](https://react.dev/reference/react/lazy) with [Suspense](https://react.dev/reference/react/Suspense) under the hood. + * + * Read more: [Next.js Docs: `next/dynamic`](https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic) + */ +export default function dynamic

(dynamicOptions: DynamicOptions

| Loader

, options?: DynamicOptions

): React.ComponentType

; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/dynamic.js b/e-commerce/node_modules/next/dist/shared/lib/dynamic.js new file mode 100644 index 0000000000000000000000000000000000000000..7780c50f66a4df2ebcc46f33681e93812c820c0a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/dynamic.js @@ -0,0 +1,130 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + default: null, + noSSR: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + /** + * This function lets you dynamically import a component. + * It uses [React.lazy()](https://react.dev/reference/react/lazy) with [Suspense](https://react.dev/reference/react/Suspense) under the hood. + * + * Read more: [Next.js Docs: `next/dynamic`](https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic) + */ default: function() { + return dynamic; + }, + noSSR: function() { + return noSSR; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _jsxruntime = require("react/jsx-runtime"); +const _react = /*#__PURE__*/ _interop_require_default._(require("react")); +const _loadablesharedruntime = /*#__PURE__*/ _interop_require_default._(require("./loadable.shared-runtime")); +const isServerSide = typeof window === 'undefined'; +// Normalize loader to return the module as form { default: Component } for `React.lazy`. +// Also for backward compatible since next/dynamic allows to resolve a component directly with loader +// Client component reference proxy need to be converted to a module. +function convertModule(mod) { + return { + default: mod?.default || mod + }; +} +function noSSR(LoadableInitializer, loadableOptions) { + // Removing webpack and modules means react-loadable won't try preloading + delete loadableOptions.webpack; + delete loadableOptions.modules; + // This check is necessary to prevent react-loadable from initializing on the server + if (!isServerSide) { + return LoadableInitializer(loadableOptions); + } + const Loading = loadableOptions.loading; + // This will only be rendered on the server side + return ()=>/*#__PURE__*/ (0, _jsxruntime.jsx)(Loading, { + error: null, + isLoading: true, + pastDelay: false, + timedOut: false + }); +} +function dynamic(dynamicOptions, options) { + let loadableFn = _loadablesharedruntime.default; + let loadableOptions = { + // A loading component is not required, so we default it + loading: ({ error, isLoading, pastDelay })=>{ + if (!pastDelay) return null; + if (process.env.NODE_ENV !== 'production') { + if (isLoading) { + return null; + } + if (error) { + return /*#__PURE__*/ (0, _jsxruntime.jsxs)("p", { + children: [ + error.message, + /*#__PURE__*/ (0, _jsxruntime.jsx)("br", {}), + error.stack + ] + }); + } + } + return null; + } + }; + // Support for direct import(), eg: dynamic(import('../hello-world')) + // Note that this is only kept for the edge case where someone is passing in a promise as first argument + // The react-loadable babel plugin will turn dynamic(import('../hello-world')) into dynamic(() => import('../hello-world')) + // To make sure we don't execute the import without rendering first + if (dynamicOptions instanceof Promise) { + loadableOptions.loader = ()=>dynamicOptions; + // Support for having import as a function, eg: dynamic(() => import('../hello-world')) + } else if (typeof dynamicOptions === 'function') { + loadableOptions.loader = dynamicOptions; + // Support for having first argument being options, eg: dynamic({loader: import('../hello-world')}) + } else if (typeof dynamicOptions === 'object') { + loadableOptions = { + ...loadableOptions, + ...dynamicOptions + }; + } + // Support for passing options, eg: dynamic(import('../hello-world'), {loading: () =>

Loading something

}) + loadableOptions = { + ...loadableOptions, + ...options + }; + const loaderFn = loadableOptions.loader; + const loader = ()=>loaderFn != null ? loaderFn().then(convertModule) : Promise.resolve(convertModule(()=>null)); + // coming from build/babel/plugins/react-loadable-plugin.js + if (loadableOptions.loadableGenerated) { + loadableOptions = { + ...loadableOptions, + ...loadableOptions.loadableGenerated + }; + delete loadableOptions.loadableGenerated; + } + // support for disabling server side rendering, eg: dynamic(() => import('../hello-world'), {ssr: false}). + if (typeof loadableOptions.ssr === 'boolean' && !loadableOptions.ssr) { + delete loadableOptions.webpack; + delete loadableOptions.modules; + return noSSR(loadableFn, loadableOptions); + } + return loadableFn({ + ...loadableOptions, + loader: loader + }); +} + +if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') { + Object.defineProperty(exports.default, '__esModule', { value: true }); + Object.assign(exports.default, exports); + module.exports = exports.default; +} + +//# sourceMappingURL=dynamic.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/dynamic.js.map b/e-commerce/node_modules/next/dist/shared/lib/dynamic.js.map new file mode 100644 index 0000000000000000000000000000000000000000..16d3c3a2ffb23f405f61f5ab62b84c60a4758f48 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/dynamic.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/dynamic.tsx"],"sourcesContent":["import React from 'react'\nimport Loadable from './loadable.shared-runtime'\n\nconst isServerSide = typeof window === 'undefined'\n\ntype ComponentModule

= { default: React.ComponentType

}\n\nexport declare type LoaderComponent

= Promise<\n React.ComponentType

| ComponentModule

\n>\n\nexport declare type Loader

=\n | (() => LoaderComponent

)\n | LoaderComponent

\n\nexport type LoaderMap = { [module: string]: () => Loader }\n\nexport type LoadableGeneratedOptions = {\n webpack?(): any\n modules?(): LoaderMap\n}\n\nexport type DynamicOptionsLoadingProps = {\n error?: Error | null\n isLoading?: boolean\n pastDelay?: boolean\n retry?: () => void\n timedOut?: boolean\n}\n\n// Normalize loader to return the module as form { default: Component } for `React.lazy`.\n// Also for backward compatible since next/dynamic allows to resolve a component directly with loader\n// Client component reference proxy need to be converted to a module.\nfunction convertModule

(mod: React.ComponentType

| ComponentModule

) {\n return { default: (mod as ComponentModule

)?.default || mod }\n}\n\nexport type DynamicOptions

= LoadableGeneratedOptions & {\n loading?: (loadingProps: DynamicOptionsLoadingProps) => React.ReactNode\n loader?: Loader

| LoaderMap\n loadableGenerated?: LoadableGeneratedOptions\n ssr?: boolean\n}\n\nexport type LoadableOptions

= DynamicOptions

\n\nexport type LoadableFn

= (\n opts: LoadableOptions

\n) => React.ComponentType

\n\nexport type LoadableComponent

= React.ComponentType

\n\nexport function noSSR

(\n LoadableInitializer: LoadableFn

,\n loadableOptions: DynamicOptions

\n): React.ComponentType

{\n // Removing webpack and modules means react-loadable won't try preloading\n delete loadableOptions.webpack\n delete loadableOptions.modules\n\n // This check is necessary to prevent react-loadable from initializing on the server\n if (!isServerSide) {\n return LoadableInitializer(loadableOptions)\n }\n\n const Loading = loadableOptions.loading!\n // This will only be rendered on the server side\n return () => (\n \n )\n}\n\n/**\n * This function lets you dynamically import a component.\n * It uses [React.lazy()](https://react.dev/reference/react/lazy) with [Suspense](https://react.dev/reference/react/Suspense) under the hood.\n *\n * Read more: [Next.js Docs: `next/dynamic`](https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic)\n */\nexport default function dynamic

(\n dynamicOptions: DynamicOptions

| Loader

,\n options?: DynamicOptions

\n): React.ComponentType

{\n let loadableFn = Loadable as LoadableFn

\n\n let loadableOptions: LoadableOptions

= {\n // A loading component is not required, so we default it\n loading: ({ error, isLoading, pastDelay }) => {\n if (!pastDelay) return null\n if (process.env.NODE_ENV !== 'production') {\n if (isLoading) {\n return null\n }\n if (error) {\n return (\n

\n {error.message}\n
\n {error.stack}\n

\n )\n }\n }\n return null\n },\n }\n\n // Support for direct import(), eg: dynamic(import('../hello-world'))\n // Note that this is only kept for the edge case where someone is passing in a promise as first argument\n // The react-loadable babel plugin will turn dynamic(import('../hello-world')) into dynamic(() => import('../hello-world'))\n // To make sure we don't execute the import without rendering first\n if (dynamicOptions instanceof Promise) {\n loadableOptions.loader = () => dynamicOptions\n // Support for having import as a function, eg: dynamic(() => import('../hello-world'))\n } else if (typeof dynamicOptions === 'function') {\n loadableOptions.loader = dynamicOptions\n // Support for having first argument being options, eg: dynamic({loader: import('../hello-world')})\n } else if (typeof dynamicOptions === 'object') {\n loadableOptions = { ...loadableOptions, ...dynamicOptions }\n }\n\n // Support for passing options, eg: dynamic(import('../hello-world'), {loading: () =>

Loading something

})\n loadableOptions = { ...loadableOptions, ...options }\n\n const loaderFn = loadableOptions.loader as () => LoaderComponent

\n const loader = () =>\n loaderFn != null\n ? loaderFn().then(convertModule)\n : Promise.resolve(convertModule(() => null))\n\n // coming from build/babel/plugins/react-loadable-plugin.js\n if (loadableOptions.loadableGenerated) {\n loadableOptions = {\n ...loadableOptions,\n ...loadableOptions.loadableGenerated,\n }\n delete loadableOptions.loadableGenerated\n }\n\n // support for disabling server side rendering, eg: dynamic(() => import('../hello-world'), {ssr: false}).\n if (typeof loadableOptions.ssr === 'boolean' && !loadableOptions.ssr) {\n delete loadableOptions.webpack\n delete loadableOptions.modules\n\n return noSSR(loadableFn, loadableOptions)\n }\n\n return loadableFn({ ...loadableOptions, loader: loader as Loader

})\n}\n"],"names":["dynamic","noSSR","isServerSide","window","convertModule","mod","default","LoadableInitializer","loadableOptions","webpack","modules","Loading","loading","error","isLoading","pastDelay","timedOut","dynamicOptions","options","loadableFn","Loadable","process","env","NODE_ENV","p","message","br","stack","Promise","loader","loaderFn","then","resolve","loadableGenerated","ssr"],"mappings":";;;;;;;;;;;;;;;IAwEA;;;;;CAKC,GACD,OAqEC;eArEuBA;;IA1BRC,KAAK;eAALA;;;;;gEApDE;gFACG;AAErB,MAAMC,eAAe,OAAOC,WAAW;AA2BvC,yFAAyF;AACzF,qGAAqG;AACrG,qEAAqE;AACrE,SAASC,cAAiBC,GAAgD;IACxE,OAAO;QAAEC,SAAS,AAACD,KAA4BC,WAAWD;IAAI;AAChE;AAiBO,SAASJ,MACdM,mBAAkC,EAClCC,eAAkC;IAElC,yEAAyE;IACzE,OAAOA,gBAAgBC,OAAO;IAC9B,OAAOD,gBAAgBE,OAAO;IAE9B,oFAAoF;IACpF,IAAI,CAACR,cAAc;QACjB,OAAOK,oBAAoBC;IAC7B;IAEA,MAAMG,UAAUH,gBAAgBI,OAAO;IACvC,gDAAgD;IAChD,OAAO,kBACL,qBAACD;YAAQE,OAAO;YAAMC,SAAS;YAACC,WAAW;Y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,CAAC1B,gBAAgB0B,GAAG,EAAE;QACpE,OAAO1B,gBAAgBC,OAAO;QAC9B,OAAOD,gBAAgBE,OAAO;QAE9B,OAAOT,MAAMkB,YAAYX;IAC3B;IAEA,OAAOW,WAAW;QAAE,GAAGX,eAAe;QAAEqB,QAAQA;IAAoB;AACtE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/encode-uri-path.d.ts b/e-commerce/node_modules/next/dist/shared/lib/encode-uri-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9b54b032cacbbff1b7acc52187edfc2303b5afe --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/encode-uri-path.d.ts @@ -0,0 +1 @@ +export declare function encodeURIPath(file: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/encode-uri-path.js b/e-commerce/node_modules/next/dist/shared/lib/encode-uri-path.js new file mode 100644 index 0000000000000000000000000000000000000000..d42d28203a087ce51899b7e4525c7cc35d99e55f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/encode-uri-path.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "encodeURIPath", { + enumerable: true, + get: function() { + return encodeURIPath; + } +}); +function encodeURIPath(file) { + return file.split('/').map((p)=>encodeURIComponent(p)).join('/'); +} + +//# sourceMappingURL=encode-uri-path.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/encode-uri-path.js.map b/e-commerce/node_modules/next/dist/shared/lib/encode-uri-path.js.map new file mode 100644 index 0000000000000000000000000000000000000000..929993cd2857e3fa89e030a859bea1faacf9cfff --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/encode-uri-path.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/encode-uri-path.ts"],"sourcesContent":["export function encodeURIPath(file: string) {\n return file\n .split('/')\n .map((p) => encodeURIComponent(p))\n .join('/')\n}\n"],"names":["encodeURIPath","file","split","map","p","encodeURIComponent","join"],"mappings":";;;;+BAAgBA;;;eAAAA;;;AAAT,SAASA,cAAcC,IAAY;IACxC,OAAOA,KACJC,KAAK,CAAC,KACNC,GAAG,CAAC,CAACC,IAAMC,mBAAmBD,IAC9BE,IAAI,CAAC;AACV","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/entry-constants.d.ts b/e-commerce/node_modules/next/dist/shared/lib/entry-constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b003d06b38cf0998aef8e473360a6348f8a6a4e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/entry-constants.d.ts @@ -0,0 +1,4 @@ +export declare const UNDERSCORE_NOT_FOUND_ROUTE = "/_not-found"; +export declare const UNDERSCORE_NOT_FOUND_ROUTE_ENTRY = "/_not-found/page"; +export declare const UNDERSCORE_GLOBAL_ERROR_ROUTE = "/_global-error"; +export declare const UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY = "/_global-error/page"; diff --git a/e-commerce/node_modules/next/dist/shared/lib/entry-constants.js b/e-commerce/node_modules/next/dist/shared/lib/entry-constants.js new file mode 100644 index 0000000000000000000000000000000000000000..b6d461a8b53c4512f72c1a876769e1528083e03b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/entry-constants.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + UNDERSCORE_GLOBAL_ERROR_ROUTE: null, + UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY: null, + UNDERSCORE_NOT_FOUND_ROUTE: null, + UNDERSCORE_NOT_FOUND_ROUTE_ENTRY: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + UNDERSCORE_GLOBAL_ERROR_ROUTE: function() { + return UNDERSCORE_GLOBAL_ERROR_ROUTE; + }, + UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY: function() { + return UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY; + }, + UNDERSCORE_NOT_FOUND_ROUTE: function() { + return UNDERSCORE_NOT_FOUND_ROUTE; + }, + UNDERSCORE_NOT_FOUND_ROUTE_ENTRY: function() { + return UNDERSCORE_NOT_FOUND_ROUTE_ENTRY; + } +}); +const UNDERSCORE_NOT_FOUND_ROUTE = '/_not-found'; +const UNDERSCORE_NOT_FOUND_ROUTE_ENTRY = `${UNDERSCORE_NOT_FOUND_ROUTE}/page`; +const UNDERSCORE_GLOBAL_ERROR_ROUTE = '/_global-error'; +const UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY = `${UNDERSCORE_GLOBAL_ERROR_ROUTE}/page`; + +//# sourceMappingURL=entry-constants.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/entry-constants.js.map b/e-commerce/node_modules/next/dist/shared/lib/entry-constants.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d7b2764c0582f9934d5604b13988adf4562a2e96 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/entry-constants.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/entry-constants.ts"],"sourcesContent":["export const UNDERSCORE_NOT_FOUND_ROUTE = '/_not-found'\nexport const UNDERSCORE_NOT_FOUND_ROUTE_ENTRY = `${UNDERSCORE_NOT_FOUND_ROUTE}/page`\nexport const UNDERSCORE_GLOBAL_ERROR_ROUTE = '/_global-error'\nexport const UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY = `${UNDERSCORE_GLOBAL_ERROR_ROUTE}/page`\n"],"names":["UNDERSCORE_GLOBAL_ERROR_ROUTE","UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY","UNDERSCORE_NOT_FOUND_ROUTE","UNDERSCORE_NOT_FOUND_ROUTE_ENTRY"],"mappings":";;;;;;;;;;;;;;;;;IAEaA,6BAA6B;eAA7BA;;IACAC,mCAAmC;eAAnCA;;IAHAC,0BAA0B;eAA1BA;;IACAC,gCAAgC;eAAhCA;;;AADN,MAAMD,6BAA6B;AACnC,MAAMC,mCAAmC,GAAGD,2BAA2B,KAAK,CAAC;AAC7E,MAAMF,gCAAgC;AACtC,MAAMC,sCAAsC,GAAGD,8BAA8B,KAAK,CAAC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/error-source.d.ts b/e-commerce/node_modules/next/dist/shared/lib/error-source.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..56647b17e23e70881c9754fb00dabab1a2d8a98f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/error-source.d.ts @@ -0,0 +1,3 @@ +export declare function getErrorSource(error: Error): 'server' | 'edge-server' | null; +export type ErrorSourceType = 'edge-server' | 'server'; +export declare function decorateServerError(error: Error, type: ErrorSourceType): void; diff --git a/e-commerce/node_modules/next/dist/shared/lib/error-source.js b/e-commerce/node_modules/next/dist/shared/lib/error-source.js new file mode 100644 index 0000000000000000000000000000000000000000..4aa059c11337786cdfaeb50ca5e7aa844b3d2483 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/error-source.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + decorateServerError: null, + getErrorSource: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + decorateServerError: function() { + return decorateServerError; + }, + getErrorSource: function() { + return getErrorSource; + } +}); +const symbolError = Symbol.for('NextjsError'); +function getErrorSource(error) { + return error[symbolError] || null; +} +function decorateServerError(error, type) { + Object.defineProperty(error, symbolError, { + writable: false, + enumerable: false, + configurable: false, + value: type + }); +} + +//# sourceMappingURL=error-source.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/error-source.js.map b/e-commerce/node_modules/next/dist/shared/lib/error-source.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4bb4d53069783f5e3a8568f02a7fe3ab89e0f321 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/error-source.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/error-source.ts"],"sourcesContent":["const symbolError = Symbol.for('NextjsError')\n\nexport function getErrorSource(error: Error): 'server' | 'edge-server' | null {\n return (error as any)[symbolError] || null\n}\n\nexport type ErrorSourceType = 'edge-server' | 'server'\n\nexport function decorateServerError(error: Error, type: ErrorSourceType) {\n Object.defineProperty(error, symbolError, {\n writable: false,\n enumerable: false,\n configurable: false,\n value: type,\n })\n}\n"],"names":["decorateServerError","getErrorSource","symbolError","Symbol","for","error","type","Object","defineProperty","writable","enumerable","configurable","value"],"mappings":";;;;;;;;;;;;;;;IAQgBA,mBAAmB;eAAnBA;;IANAC,cAAc;eAAdA;;;AAFhB,MAAMC,cAAcC,OAAOC,GAAG,CAAC;AAExB,SAASH,eAAeI,KAAY;IACzC,OAAO,AAACA,KAAa,CAACH,YAAY,IAAI;AACxC;AAIO,SAASF,oBAAoBK,KAAY,EAAEC,IAAqB;IACrEC,OAAOC,cAAc,CAACH,OAAOH,aAAa;QACxCO,UAAU;QACVC,YAAY;QACZC,cAAc;QACdC,OAAON;IACT;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/canary-only-config-error.d.ts b/e-commerce/node_modules/next/dist/shared/lib/errors/canary-only-config-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2fd2c8040d767d6372a9c8a71f381cedfd61d632 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/canary-only-config-error.d.ts @@ -0,0 +1,6 @@ +export declare function isStableBuild(): boolean; +export declare class CanaryOnlyConfigError extends Error { + constructor(arg: { + feature: string; + } | string); +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/canary-only-config-error.js b/e-commerce/node_modules/next/dist/shared/lib/errors/canary-only-config-error.js new file mode 100644 index 0000000000000000000000000000000000000000..6201200d2e093aa145630f5e9095fcd013126d98 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/canary-only-config-error.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + CanaryOnlyConfigError: null, + isStableBuild: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + CanaryOnlyConfigError: function() { + return CanaryOnlyConfigError; + }, + isStableBuild: function() { + return isStableBuild; + } +}); +function isStableBuild() { + const nextVersion = "16.4.0"; + return !nextVersion?.includes('canary') && // Commit preview tarballs (e.g. `16.4.0-preview-84cee7e6-20260917`, see + // scripts/set-preview-version.js) are built from arbitrary canary commits, + // so they are not stable. Numbered preview releases published to npm + // (e.g. `16.3.0-preview.10`) are stable. + !nextVersion?.includes('-preview-') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; +} +class CanaryOnlyConfigError extends Error { + constructor(arg){ + if (typeof arg === 'object' && 'feature' in arg) { + super(`The experimental feature "${arg.feature}" can only be enabled when using the latest canary version of Next.js.`); + } else { + super(arg); + } + // This error is meant to interrupt the server start/build process + // but the stack trace isn't meaningful, as it points to internal code. + this.stack = undefined; + } +} + +//# sourceMappingURL=canary-only-config-error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/canary-only-config-error.js.map b/e-commerce/node_modules/next/dist/shared/lib/errors/canary-only-config-error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8a40ffbdc6d4ee131c2f0c40b02b869f45a10c93 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/canary-only-config-error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/errors/canary-only-config-error.ts"],"sourcesContent":["export function isStableBuild() {\n const nextVersion = process.env.__NEXT_VERSION\n return (\n !nextVersion?.includes('canary') &&\n // Commit preview tarballs (e.g. `16.4.0-preview-84cee7e6-20260917`, see\n // scripts/set-preview-version.js) are built from arbitrary canary commits,\n // so they are not stable. Numbered preview releases published to npm\n // (e.g. `16.3.0-preview.10`) are stable.\n !nextVersion?.includes('-preview-') &&\n !process.env.__NEXT_TEST_MODE &&\n !process.env.NEXT_PRIVATE_LOCAL_DEV\n )\n}\n\nexport class CanaryOnlyConfigError extends Error {\n constructor(arg: { feature: string } | string) {\n if (typeof arg === 'object' && 'feature' in arg) {\n super(\n `The experimental feature \"${arg.feature}\" can only be enabled when using the latest canary version of Next.js.`\n )\n } else {\n super(arg)\n }\n\n // This error is meant to interrupt the server start/build process\n // but the stack trace isn't meaningful, as it points to internal code.\n this.stack = undefined\n }\n}\n"],"names":["CanaryOnlyConfigError","isStableBuild","nextVersion","process","env","__NEXT_VERSION","includes","__NEXT_TEST_MODE","NEXT_PRIVATE_LOCAL_DEV","Error","constructor","arg","feature","stack","undefined"],"mappings":";;;;;;;;;;;;;;;IAcaA,qBAAqB;eAArBA;;IAdGC,aAAa;eAAbA;;;AAAT,SAASA;IACd,MAAMC,cAAcC,QAAQC,GAAG,CAACC,cAAc;IAC9C,OACE,CAACH,aAAaI,SAAS,aACvB,wEAAwE;IACxE,2EAA2E;IAC3E,qEAAqE;IACrE,yCAAyC;IACzC,CAACJ,aAAaI,SAAS,gBACvB,CAACH,QAAQC,GAAG,CAACG,gBAAgB,IAC7B,CAACJ,QAAQC,GAAG,CAACI,sBAAsB;AAEvC;AAEO,MAAMR,8BAA8BS;IACzCC,YAAYC,GAAiC,CAAE;QAC7C,IAAI,OAAOA,QAAQ,YAAY,aAAaA,KAAK;YAC/C,KAAK,CACH,CAAC,0BAA0B,EAAEA,IAAIC,OAAO,CAAC,sEAAsE,CAAC;QAEpH,OAAO;YACL,KAAK,CAACD;QACR;QAEA,kEAAkE;QAClE,uEAAuE;QACvE,IAAI,CAACE,KAAK,GAAGC;IACf;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/code-frame.d.ts b/e-commerce/node_modules/next/dist/shared/lib/errors/code-frame.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4ae1e032580807655c3210b110a47b5f27950b0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/code-frame.d.ts @@ -0,0 +1,7 @@ +import type { NapiCodeFrameLocation, NapiCodeFrameOptions } from '../../../build/swc/generated-native'; +/** + * Renders a code frame showing the location of an error in source code. + * Requires native bindings to be installed — throws otherwise. + */ +export declare function codeFrameColumns(file: string, location: NapiCodeFrameLocation, options?: NapiCodeFrameOptions): string | undefined; +export type { NapiCodeFrameLocation, NapiCodeFrameOptions }; diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/code-frame.js b/e-commerce/node_modules/next/dist/shared/lib/errors/code-frame.js new file mode 100644 index 0000000000000000000000000000000000000000..71c04de1e3022ad31e418c5187c02154b19539e6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/code-frame.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "codeFrameColumns", { + enumerable: true, + get: function() { + return codeFrameColumns; + } +}); +const _swc = require("../../../build/swc"); +function codeFrameColumns(file, location, options = {}) { + // Default to the terminal width. The CLI passes it on when it pipes this + // process's output for the upgrade menu. + if (options.maxWidth === undefined) { + options.maxWidth = process.stdout.columns ?? (Number(process.env.NEXT_PRIVATE_TERMINAL_COLUMNS) || undefined); + } + return (0, _swc.getBindingsSync)().codeFrameColumns(file, location, options); +} + +//# sourceMappingURL=code-frame.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/code-frame.js.map b/e-commerce/node_modules/next/dist/shared/lib/errors/code-frame.js.map new file mode 100644 index 0000000000000000000000000000000000000000..17545626b6fa6a595976211e38e08ec571411afb --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/code-frame.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/errors/code-frame.ts"],"sourcesContent":["import { getBindingsSync } from '../../../build/swc'\nimport type {\n NapiCodeFrameLocation,\n NapiCodeFrameOptions,\n} from '../../../build/swc/generated-native'\n\n/**\n * Renders a code frame showing the location of an error in source code.\n * Requires native bindings to be installed — throws otherwise.\n */\nexport function codeFrameColumns(\n file: string,\n location: NapiCodeFrameLocation,\n options: NapiCodeFrameOptions = {}\n): string | undefined {\n // Default to the terminal width. The CLI passes it on when it pipes this\n // process's output for the upgrade menu.\n if (options.maxWidth === undefined) {\n options.maxWidth =\n process.stdout.columns ??\n (Number(process.env.NEXT_PRIVATE_TERMINAL_COLUMNS) || undefined)\n }\n return getBindingsSync().codeFrameColumns(file, location, options)\n}\n\nexport type { NapiCodeFrameLocation, NapiCodeFrameOptions }\n"],"names":["codeFrameColumns","file","location","options","maxWidth","undefined","process","stdout","columns","Number","env","NEXT_PRIVATE_TERMINAL_COLUMNS","getBindingsSync"],"mappings":";;;;+BAUgBA;;;eAAAA;;;qBAVgB;AAUzB,SAASA,iBACdC,IAAY,EACZC,QAA+B,EAC/BC,UAAgC,CAAC,CAAC;IAElC,yEAAyE;IACzE,yCAAyC;IACzC,IAAIA,QAAQC,QAAQ,KAAKC,WAAW;QAClCF,QAAQC,QAAQ,GACdE,QAAQC,MAAM,CAACC,OAAO,IACrBC,CAAAA,OAAOH,QAAQI,GAAG,CAACC,6BAA6B,KAAKN,SAAQ;IAClE;IACA,OAAOO,IAAAA,oBAAe,IAAGZ,gBAAgB,CAACC,MAAMC,UAAUC;AAC5D","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/constants.d.ts b/e-commerce/node_modules/next/dist/shared/lib/errors/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..529df718c3b0e558fc88134ddf8f7a3b165e928d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/constants.d.ts @@ -0,0 +1 @@ +export declare const MISSING_ROOT_TAGS_ERROR = "NEXT_MISSING_ROOT_TAGS"; diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/constants.js b/e-commerce/node_modules/next/dist/shared/lib/errors/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..e13ef7f50ece443615bbee496de06adb08c6ab0a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/constants.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "MISSING_ROOT_TAGS_ERROR", { + enumerable: true, + get: function() { + return MISSING_ROOT_TAGS_ERROR; + } +}); +const MISSING_ROOT_TAGS_ERROR = 'NEXT_MISSING_ROOT_TAGS'; + +if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') { + Object.defineProperty(exports.default, '__esModule', { value: true }); + Object.assign(exports.default, exports); + module.exports = exports.default; +} + +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/constants.js.map b/e-commerce/node_modules/next/dist/shared/lib/errors/constants.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5cbe91643705b00bc25b6f8fe7590d9160c9cd20 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/constants.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/errors/constants.ts"],"sourcesContent":["export const MISSING_ROOT_TAGS_ERROR = 'NEXT_MISSING_ROOT_TAGS'\n"],"names":["MISSING_ROOT_TAGS_ERROR"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA,0BAA0B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/empty-generate-static-params-error.d.ts b/e-commerce/node_modules/next/dist/shared/lib/errors/empty-generate-static-params-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7639ec7814b88a36ce30a7536f299f980c8ae83a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/empty-generate-static-params-error.d.ts @@ -0,0 +1 @@ +export declare function throwEmptyGenerateStaticParamsError(createError: (() => Error) | undefined): never; diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/empty-generate-static-params-error.js b/e-commerce/node_modules/next/dist/shared/lib/errors/empty-generate-static-params-error.js new file mode 100644 index 0000000000000000000000000000000000000000..e84f974c58b3038e1ec89b3ed7e4b1cfc1e1f106 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/empty-generate-static-params-error.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "throwEmptyGenerateStaticParamsError", { + enumerable: true, + get: function() { + return throwEmptyGenerateStaticParamsError; + } +}); +function throwEmptyGenerateStaticParamsError(// Compiler-injected factory whose error stack is anchored at the user's +// `generateStaticParams`. The transform injects it for every app page that +// exports `generateStaticParams` by a statically-visible name, but a few +// forms can't be detected from the page module alone (e.g. `export *` +// re-exports), so it may be absent. +createError) { + if (createError) { + throw createError(); + } + // Fallback for the rare case the compiler couldn't inject an anchored factory + // (e.g. a wildcard re-export). The stack points at framework internals, but + // we keep it: those frames are ignore-listed in the output and stay available + // for debugging. + throw new Error('When using Cache Components, all `generateStaticParams` functions must return at least one result. ' + 'This is to ensure that we can perform build-time validation that there is no other dynamic accesses that would cause a runtime error.\n\n' + 'Learn more: https://nextjs.org/docs/messages/empty-generate-static-params'); +} + +//# sourceMappingURL=empty-generate-static-params-error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/empty-generate-static-params-error.js.map b/e-commerce/node_modules/next/dist/shared/lib/errors/empty-generate-static-params-error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0a94ddfb2eb05ca34276867cac62c1b48c35f6c5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/empty-generate-static-params-error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/errors/empty-generate-static-params-error.ts"],"sourcesContent":["export function throwEmptyGenerateStaticParamsError(\n // Compiler-injected factory whose error stack is anchored at the user's\n // `generateStaticParams`. The transform injects it for every app page that\n // exports `generateStaticParams` by a statically-visible name, but a few\n // forms can't be detected from the page module alone (e.g. `export *`\n // re-exports), so it may be absent.\n createError: (() => Error) | undefined\n): never {\n if (createError) {\n throw createError()\n }\n\n // Fallback for the rare case the compiler couldn't inject an anchored factory\n // (e.g. a wildcard re-export). The stack points at framework internals, but\n // we keep it: those frames are ignore-listed in the output and stay available\n // for debugging.\n throw new Error(\n 'When using Cache Components, all `generateStaticParams` functions must return at least one result. ' +\n 'This is to ensure that we can perform build-time validation that there is no other dynamic accesses that would cause a runtime error.\\n\\n' +\n 'Learn more: https://nextjs.org/docs/messages/empty-generate-static-params'\n )\n}\n"],"names":["throwEmptyGenerateStaticParamsError","createError","Error"],"mappings":";;;;+BAAgBA;;;eAAAA;;;AAAT,SAASA,oCACd,wEAAwE;AACxE,2EAA2E;AAC3E,yEAAyE;AACzE,sEAAsE;AACtE,oCAAoC;AACpCC,WAAsC;IAEtC,IAAIA,aAAa;QACf,MAAMA;IACR;IAEA,8EAA8E;IAC9E,4EAA4E;IAC5E,8EAA8E;IAC9E,iBAAiB;IACjB,MAAM,IAAIC,MACR,wGACE,8IACA;AAEN","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/ensure-static-gsp-errors.d.ts b/e-commerce/node_modules/next/dist/shared/lib/errors/ensure-static-gsp-errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5fd9fc8d1441b70c724f20679ebef319c1efda81 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/ensure-static-gsp-errors.d.ts @@ -0,0 +1,2 @@ +export declare function throwMissingGspErrorInStaticRoute(page: string): void; +export declare function throwIncompleteStaticParamsErrorInStaticRoute(page: string, missingParamNames: string[]): void; diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/ensure-static-gsp-errors.js b/e-commerce/node_modules/next/dist/shared/lib/errors/ensure-static-gsp-errors.js new file mode 100644 index 0000000000000000000000000000000000000000..e799cbd4d145139d595746b61fd71ae1a765d96b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/ensure-static-gsp-errors.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + throwIncompleteStaticParamsErrorInStaticRoute: null, + throwMissingGspErrorInStaticRoute: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + throwIncompleteStaticParamsErrorInStaticRoute: function() { + return throwIncompleteStaticParamsErrorInStaticRoute; + }, + throwMissingGspErrorInStaticRoute: function() { + return throwMissingGspErrorInStaticRoute; + } +}); +function throwMissingGspErrorInStaticRoute(page) { + throw new Error(`Page "${page}": \`ensureStatic = "navigation"\` requires an exported \`generateStaticParams()\` function.\nLearn more: https://nextjs.org/docs/messages/generate-static-params#with-ensurestatic`); +} +function throwIncompleteStaticParamsErrorInStaticRoute(page, missingParamNames) { + throw new Error(`Page "${page}": \`generateStaticParams()\` returned incomplete params. Routes using \`ensureStatic = "navigation"\` must return every dynamic route parameter. Missing: ${missingParamNames.map((name)=>`"${name}"`).join(', ')}.\nLearn more: https://nextjs.org/docs/messages/generate-static-params#with-ensurestatic`); +} + +//# sourceMappingURL=ensure-static-gsp-errors.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/ensure-static-gsp-errors.js.map b/e-commerce/node_modules/next/dist/shared/lib/errors/ensure-static-gsp-errors.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6888d8d20e4400b24d25c05e117228afbc712f21 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/ensure-static-gsp-errors.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/errors/ensure-static-gsp-errors.ts"],"sourcesContent":["export function throwMissingGspErrorInStaticRoute(page: string) {\n throw new Error(\n `Page \"${page}\": \\`ensureStatic = \"navigation\"\\` requires an exported \\`generateStaticParams()\\` function.\\nLearn more: https://nextjs.org/docs/messages/generate-static-params#with-ensurestatic`\n )\n}\n\nexport function throwIncompleteStaticParamsErrorInStaticRoute(\n page: string,\n missingParamNames: string[]\n) {\n throw new Error(\n `Page \"${page}\": \\`generateStaticParams()\\` returned incomplete params. Routes using \\`ensureStatic = \"navigation\"\\` must return every dynamic route parameter. Missing: ${missingParamNames.map((name) => `\"${name}\"`).join(', ')}.\\nLearn more: https://nextjs.org/docs/messages/generate-static-params#with-ensurestatic`\n )\n}\n"],"names":["throwIncompleteStaticParamsErrorInStaticRoute","throwMissingGspErrorInStaticRoute","page","Error","missingParamNames","map","name","join"],"mappings":";;;;;;;;;;;;;;;IAMgBA,6CAA6C;eAA7CA;;IANAC,iCAAiC;eAAjCA;;;AAAT,SAASA,kCAAkCC,IAAY;IAC5D,MAAM,IAAIC,MACR,CAAC,MAAM,EAAED,KAAK,mLAAmL,CAAC;AAEtM;AAEO,SAASF,8CACdE,IAAY,EACZE,iBAA2B;IAE3B,MAAM,IAAID,MACR,CAAC,MAAM,EAAED,KAAK,2JAA2J,EAAEE,kBAAkBC,GAAG,CAAC,CAACC,OAAS,CAAC,CAAC,EAAEA,KAAK,CAAC,CAAC,EAAEC,IAAI,CAAC,MAAM,wFAAwF,CAAC;AAEhU","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/hard-deprecated-config-error.d.ts b/e-commerce/node_modules/next/dist/shared/lib/errors/hard-deprecated-config-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a4331f3d20386c6d7a4e3813382f9d1031af7be --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/hard-deprecated-config-error.d.ts @@ -0,0 +1,3 @@ +export declare class HardDeprecatedConfigError extends Error { + constructor(message: string); +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/hard-deprecated-config-error.js b/e-commerce/node_modules/next/dist/shared/lib/errors/hard-deprecated-config-error.js new file mode 100644 index 0000000000000000000000000000000000000000..a4a7f1227bd168cbf22335323265ffdde01da430 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/hard-deprecated-config-error.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "HardDeprecatedConfigError", { + enumerable: true, + get: function() { + return HardDeprecatedConfigError; + } +}); +class HardDeprecatedConfigError extends Error { + constructor(message){ + super(message); + // This error is meant to interrupt the server start/build process + // but the stack trace isn't meaningful, as it points to internal code. + this.stack = undefined; + } +} + +//# sourceMappingURL=hard-deprecated-config-error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/hard-deprecated-config-error.js.map b/e-commerce/node_modules/next/dist/shared/lib/errors/hard-deprecated-config-error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8bf630474039750266f2605982373ff065c0dd3b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/hard-deprecated-config-error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/errors/hard-deprecated-config-error.ts"],"sourcesContent":["export class HardDeprecatedConfigError extends Error {\n constructor(message: string) {\n super(message)\n\n // This error is meant to interrupt the server start/build process\n // but the stack trace isn't meaningful, as it points to internal code.\n this.stack = undefined\n }\n}\n"],"names":["HardDeprecatedConfigError","Error","constructor","message","stack","undefined"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA,kCAAkCC;IAC7CC,YAAYC,OAAe,CAAE;QAC3B,KAAK,CAACA;QAEN,kEAAkE;QAClE,uEAAuE;QACvE,IAAI,CAACC,KAAK,GAAGC;IACf;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/incompatible-parallel-route-slots-error.d.ts b/e-commerce/node_modules/next/dist/shared/lib/errors/incompatible-parallel-route-slots-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d281cc84c2b4e74cdb296318e76d34e75fc2b3d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/incompatible-parallel-route-slots-error.d.ts @@ -0,0 +1,8 @@ +export type IncompatibleParallelRouteSlots = { + layoutFile: string; + route: string; + missingSlots: readonly string[]; +}; +export declare class IncompatibleParallelRouteSlotsError extends Error { + constructor(routes: readonly IncompatibleParallelRouteSlots[]); +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/incompatible-parallel-route-slots-error.js b/e-commerce/node_modules/next/dist/shared/lib/errors/incompatible-parallel-route-slots-error.js new file mode 100644 index 0000000000000000000000000000000000000000..d5aa70bbec034fc6dc730ea1f0e8a59e3007a4f1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/incompatible-parallel-route-slots-error.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "IncompatibleParallelRouteSlotsError", { + enumerable: true, + get: function() { + return IncompatibleParallelRouteSlotsError; + } +}); +class IncompatibleParallelRouteSlotsError extends Error { + constructor(routes){ + const routesByLayout = new Map(); + for (const route of routes){ + const layoutRoutes = routesByLayout.get(route.layoutFile); + if (layoutRoutes) { + layoutRoutes.push(route); + } else { + routesByLayout.set(route.layoutFile, [ + route + ]); + } + } + const formattedLayouts = [ + ...routesByLayout + ].sort(([a], [b])=>a.localeCompare(b)).map(([layoutFile, layoutRoutes])=>{ + const formattedRoutes = layoutRoutes.sort((a, b)=>a.route.localeCompare(b.route)).map(({ route, missingSlots })=>`- ${route} is missing a matching page or default.tsx in ${missingSlots.join(', ')}`).join('\n'); + return `${layoutFile}\n${formattedRoutes}`; + }).join('\n\n'); + super(`The following layouts have parallel route slots that cannot render the same URLs:\n${formattedLayouts}\n\nEvery URL matched by one slot must have a matching page or default.tsx in every sibling slot.`); + this.name = 'IncompatibleParallelRouteSlotsError'; + this.stack = undefined; + } +} + +//# sourceMappingURL=incompatible-parallel-route-slots-error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/incompatible-parallel-route-slots-error.js.map b/e-commerce/node_modules/next/dist/shared/lib/errors/incompatible-parallel-route-slots-error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8938a183173fd02c9a44377a81afac1a7d264f3f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/incompatible-parallel-route-slots-error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/errors/incompatible-parallel-route-slots-error.ts"],"sourcesContent":["export type IncompatibleParallelRouteSlots = {\n layoutFile: string\n route: string\n missingSlots: readonly string[]\n}\n\nexport class IncompatibleParallelRouteSlotsError extends Error {\n constructor(routes: readonly IncompatibleParallelRouteSlots[]) {\n const routesByLayout = new Map()\n\n for (const route of routes) {\n const layoutRoutes = routesByLayout.get(route.layoutFile)\n if (layoutRoutes) {\n layoutRoutes.push(route)\n } else {\n routesByLayout.set(route.layoutFile, [route])\n }\n }\n\n const formattedLayouts = [...routesByLayout]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([layoutFile, layoutRoutes]) => {\n const formattedRoutes = layoutRoutes\n .sort((a, b) => a.route.localeCompare(b.route))\n .map(\n ({ route, missingSlots }) =>\n `- ${route} is missing a matching page or default.tsx in ${missingSlots.join(', ')}`\n )\n .join('\\n')\n return `${layoutFile}\\n${formattedRoutes}`\n })\n .join('\\n\\n')\n\n super(\n `The following layouts have parallel route slots that cannot render the same URLs:\\n${formattedLayouts}\\n\\nEvery URL matched by one slot must have a matching page or default.tsx in every sibling slot.`\n )\n\n this.name = 'IncompatibleParallelRouteSlotsError'\n this.stack = undefined\n }\n}\n"],"names":["IncompatibleParallelRouteSlotsError","Error","constructor","routes","routesByLayout","Map","route","layoutRoutes","get","layoutFile","push","set","formattedLayouts","sort","a","b","localeCompare","map","formattedRoutes","missingSlots","join","name","stack","undefined"],"mappings":";;;;+BAMaA;;;eAAAA;;;AAAN,MAAMA,4CAA4CC;IACvDC,YAAYC,MAAiD,CAAE;QAC7D,MAAMC,iBAAiB,IAAIC;QAE3B,KAAK,MAAMC,SAASH,OAAQ;YAC1B,MAAMI,eAAeH,eAAeI,GAAG,CAACF,MAAMG,UAAU;YACxD,IAAIF,cAAc;gBAChBA,aAAaG,IAAI,CAACJ;YACpB,OAAO;gBACLF,eAAeO,GAAG,CAACL,MAAMG,UAAU,EAAE;oBAACH;iBAAM;YAC9C;QACF;QAEA,MAAMM,mBAAmB;eAAIR;SAAe,CACzCS,IAAI,CAAC,CAAC,CAACC,EAAE,EAAE,CAACC,EAAE,GAAKD,EAAEE,aAAa,CAACD,IACnCE,GAAG,CAAC,CAAC,CAACR,YAAYF,aAAa;YAC9B,MAAMW,kBAAkBX,aACrBM,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAER,KAAK,CAACU,aAAa,CAACD,EAAET,KAAK,GAC5CW,GAAG,CACF,CAAC,EAAEX,KAAK,EAAEa,YAAY,EAAE,GACtB,CAAC,EAAE,EAAEb,MAAM,8CAA8C,EAAEa,aAAaC,IAAI,CAAC,OAAO,EAEvFA,IAAI,CAAC;YACR,OAAO,GAAGX,WAAW,EAAE,EAAES,iBAAiB;QAC5C,GACCE,IAAI,CAAC;QAER,KAAK,CACH,CAAC,mFAAmF,EAAER,iBAAiB,iGAAiG,CAAC;QAG3M,IAAI,CAACS,IAAI,GAAG;QACZ,IAAI,CAACC,KAAK,GAAGC;IACf;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/missing-canonical-interception-routes-error.d.ts b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-canonical-interception-routes-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..59a9ab3147ba3c51fc75667bfed0b08bcc7fa168 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-canonical-interception-routes-error.d.ts @@ -0,0 +1,4 @@ +import type { MissingCanonicalInterceptionRoute } from '../router/utils/interception-routes'; +export declare class MissingCanonicalInterceptionRoutesError extends Error { + constructor(routes: readonly MissingCanonicalInterceptionRoute[]); +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/missing-canonical-interception-routes-error.js b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-canonical-interception-routes-error.js new file mode 100644 index 0000000000000000000000000000000000000000..bf1b634e87915b61b7e1cfd2ab6571fb0daf688e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-canonical-interception-routes-error.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "MissingCanonicalInterceptionRoutesError", { + enumerable: true, + get: function() { + return MissingCanonicalInterceptionRoutesError; + } +}); +class MissingCanonicalInterceptionRoutesError extends Error { + constructor(routes){ + const formattedRoutes = routes.map(({ interceptionRoute, canonicalRoute })=>`- ${interceptionRoute} (expected ${canonicalRoute})`).join('\n'); + super(`The following interception routes do not have a canonical route:\n${formattedRoutes}\n\nEvery interception route must have a matching non-interception route so the URL can be loaded directly or refreshed.`); + this.name = 'MissingCanonicalInterceptionRoutesError'; + this.stack = undefined; + } +} + +//# sourceMappingURL=missing-canonical-interception-routes-error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/missing-canonical-interception-routes-error.js.map b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-canonical-interception-routes-error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..330a966b0adfea46c77408ecf1c5f417847a2a90 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-canonical-interception-routes-error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/errors/missing-canonical-interception-routes-error.ts"],"sourcesContent":["import type { MissingCanonicalInterceptionRoute } from '../router/utils/interception-routes'\n\nexport class MissingCanonicalInterceptionRoutesError extends Error {\n constructor(routes: readonly MissingCanonicalInterceptionRoute[]) {\n const formattedRoutes = routes\n .map(\n ({ interceptionRoute, canonicalRoute }) =>\n `- ${interceptionRoute} (expected ${canonicalRoute})`\n )\n .join('\\n')\n super(\n `The following interception routes do not have a canonical route:\\n${formattedRoutes}\\n\\nEvery interception route must have a matching non-interception route so the URL can be loaded directly or refreshed.`\n )\n\n this.name = 'MissingCanonicalInterceptionRoutesError'\n this.stack = undefined\n }\n}\n"],"names":["MissingCanonicalInterceptionRoutesError","Error","constructor","routes","formattedRoutes","map","interceptionRoute","canonicalRoute","join","name","stack","undefined"],"mappings":";;;;+BAEaA;;;eAAAA;;;AAAN,MAAMA,gDAAgDC;IAC3DC,YAAYC,MAAoD,CAAE;QAChE,MAAMC,kBAAkBD,OACrBE,GAAG,CACF,CAAC,EAAEC,iBAAiB,EAAEC,cAAc,EAAE,GACpC,CAAC,EAAE,EAAED,kBAAkB,WAAW,EAAEC,eAAe,CAAC,CAAC,EAExDC,IAAI,CAAC;QACR,KAAK,CACH,CAAC,kEAAkE,EAAEJ,gBAAgB,wHAAwH,CAAC;QAGhN,IAAI,CAACK,IAAI,GAAG;QACZ,IAAI,CAACC,KAAK,GAAGC;IACf;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/missing-default-parallel-route-error.d.ts b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-default-parallel-route-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0fb2d364a7146ac479f5cb3182bfd5b3d65011a0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-default-parallel-route-error.d.ts @@ -0,0 +1,4 @@ +import { UsageError } from './usage-error'; +export declare class MissingDefaultParallelRouteError extends UsageError { + constructor(fullSegmentPath: string, slotName: string); +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/missing-default-parallel-route-error.js b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-default-parallel-route-error.js new file mode 100644 index 0000000000000000000000000000000000000000..5ebafd4b7d04ee7f5a265f65172be6f64ea4f5e9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-default-parallel-route-error.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "MissingDefaultParallelRouteError", { + enumerable: true, + get: function() { + return MissingDefaultParallelRouteError; + } +}); +const _usageerror = require("./usage-error"); +class MissingDefaultParallelRouteError extends _usageerror.UsageError { + constructor(fullSegmentPath, slotName){ + super(`Missing required default.js file for parallel route at ${fullSegmentPath}\n` + `The parallel route slot "${slotName}" is missing a default.js file. When using parallel routes, each slot must have a default.js file to serve as a fallback.\n\n` + `Create a default.js file at: ${fullSegmentPath}/default.js`, 'https://nextjs.org/docs/messages/slot-missing-default'); + this.name = 'MissingDefaultParallelRouteError'; + } +} + +//# sourceMappingURL=missing-default-parallel-route-error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/missing-default-parallel-route-error.js.map b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-default-parallel-route-error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3e0729c995516f3ab3ded5ff50cc2765509be409 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/missing-default-parallel-route-error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/errors/missing-default-parallel-route-error.ts"],"sourcesContent":["import { UsageError } from './usage-error'\n\nexport class MissingDefaultParallelRouteError extends UsageError {\n constructor(fullSegmentPath: string, slotName: string) {\n super(\n `Missing required default.js file for parallel route at ${fullSegmentPath}\\n` +\n `The parallel route slot \"${slotName}\" is missing a default.js file. When using parallel routes, each slot must have a default.js file to serve as a fallback.\\n\\n` +\n `Create a default.js file at: ${fullSegmentPath}/default.js`,\n 'https://nextjs.org/docs/messages/slot-missing-default'\n )\n\n this.name = 'MissingDefaultParallelRouteError'\n }\n}\n"],"names":["MissingDefaultParallelRouteError","UsageError","constructor","fullSegmentPath","slotName","name"],"mappings":";;;;+BAEaA;;;eAAAA;;;4BAFc;AAEpB,MAAMA,yCAAyCC,sBAAU;IAC9DC,YAAYC,eAAuB,EAAEC,QAAgB,CAAE;QACrD,KAAK,CACH,CAAC,uDAAuD,EAAED,gBAAgB,EAAE,CAAC,GAC3E,CAAC,yBAAyB,EAAEC,SAAS,6HAA6H,CAAC,GACnK,CAAC,6BAA6B,EAAED,gBAAgB,WAAW,CAAC,EAC9D;QAGF,IAAI,CAACE,IAAI,GAAG;IACd;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/unmatched-app-pages-error.d.ts b/e-commerce/node_modules/next/dist/shared/lib/errors/unmatched-app-pages-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4052c10969426592d0682c38deb11ae3a5a1b52d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/unmatched-app-pages-error.d.ts @@ -0,0 +1,3 @@ +export declare class UnmatchedAppPagesError extends Error { + constructor(pagePaths: readonly string[]); +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/unmatched-app-pages-error.js b/e-commerce/node_modules/next/dist/shared/lib/errors/unmatched-app-pages-error.js new file mode 100644 index 0000000000000000000000000000000000000000..ac97a0ff5bae0650041fe92d199791a1cc461cb1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/unmatched-app-pages-error.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "UnmatchedAppPagesError", { + enumerable: true, + get: function() { + return UnmatchedAppPagesError; + } +}); +class UnmatchedAppPagesError extends Error { + constructor(pagePaths){ + const formattedPagePaths = pagePaths.map((pagePath)=>`- ${pagePath}`).join('\n'); + super(`The following page files do not match any complete route:\n${formattedPagePaths}\n\nEvery page must be part of at least one complete route. Add matching pages or default files for the sibling parallel route slots, or remove the unreachable pages.`); + this.name = 'UnmatchedAppPagesError'; + this.stack = undefined; + } +} + +//# sourceMappingURL=unmatched-app-pages-error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/unmatched-app-pages-error.js.map b/e-commerce/node_modules/next/dist/shared/lib/errors/unmatched-app-pages-error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b6d7f6c015b5f1638b296c35305ca9d6d8ef5ac6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/unmatched-app-pages-error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/errors/unmatched-app-pages-error.ts"],"sourcesContent":["export class UnmatchedAppPagesError extends Error {\n constructor(pagePaths: readonly string[]) {\n const formattedPagePaths = pagePaths\n .map((pagePath) => `- ${pagePath}`)\n .join('\\n')\n super(\n `The following page files do not match any complete route:\\n${formattedPagePaths}\\n\\nEvery page must be part of at least one complete route. Add matching pages or default files for the sibling parallel route slots, or remove the unreachable pages.`\n )\n\n this.name = 'UnmatchedAppPagesError'\n this.stack = undefined\n }\n}\n"],"names":["UnmatchedAppPagesError","Error","constructor","pagePaths","formattedPagePaths","map","pagePath","join","name","stack","undefined"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA,+BAA+BC;IAC1CC,YAAYC,SAA4B,CAAE;QACxC,MAAMC,qBAAqBD,UACxBE,GAAG,CAAC,CAACC,WAAa,CAAC,EAAE,EAAEA,UAAU,EACjCC,IAAI,CAAC;QACR,KAAK,CACH,CAAC,2DAA2D,EAAEH,mBAAmB,sKAAsK,CAAC;QAG1P,IAAI,CAACI,IAAI,GAAG;QACZ,IAAI,CAACC,KAAK,GAAGC;IACf;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/usage-error.d.ts b/e-commerce/node_modules/next/dist/shared/lib/errors/usage-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..91a97e02e43ab6795b6d5e0c4364622f69f63516 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/usage-error.d.ts @@ -0,0 +1,3 @@ +export declare class UsageError extends Error { + constructor(message: string, docUrl: string); +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/usage-error.js b/e-commerce/node_modules/next/dist/shared/lib/errors/usage-error.js new file mode 100644 index 0000000000000000000000000000000000000000..2f6b6db8db7ca35203f9dcc924d5aedec724f4b3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/usage-error.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "UsageError", { + enumerable: true, + get: function() { + return UsageError; + } +}); +class UsageError extends Error { + constructor(message, docUrl){ + super(`${message}\n\nLearn more: ${docUrl}`); + this.name = 'UsageError'; + // This error is meant to interrupt the server start/build process + // but the stack trace isn't meaningful, as it points to internal code. + this.stack = undefined; + } +} + +//# sourceMappingURL=usage-error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/errors/usage-error.js.map b/e-commerce/node_modules/next/dist/shared/lib/errors/usage-error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..62f057c4d63ef705256ef7c01aca58ea7c77b80f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/errors/usage-error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/errors/usage-error.ts"],"sourcesContent":["export class UsageError extends Error {\n constructor(message: string, docUrl: string) {\n super(`${message}\\n\\nLearn more: ${docUrl}`)\n this.name = 'UsageError'\n\n // This error is meant to interrupt the server start/build process\n // but the stack trace isn't meaningful, as it points to internal code.\n this.stack = undefined\n }\n}\n"],"names":["UsageError","Error","constructor","message","docUrl","name","stack","undefined"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA,mBAAmBC;IAC9BC,YAAYC,OAAe,EAAEC,MAAc,CAAE;QAC3C,KAAK,CAAC,GAAGD,QAAQ,gBAAgB,EAAEC,QAAQ;QAC3C,IAAI,CAACC,IAAI,GAAG;QAEZ,kEAAkE;QAClE,uEAAuE;QACvE,IAAI,CAACC,KAAK,GAAGC;IACf;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/escape-regexp.d.ts b/e-commerce/node_modules/next/dist/shared/lib/escape-regexp.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b69f1869a60442527675b5d2c8be44a5ae941570 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/escape-regexp.d.ts @@ -0,0 +1 @@ +export declare function escapeStringRegexp(str: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/escape-regexp.js b/e-commerce/node_modules/next/dist/shared/lib/escape-regexp.js new file mode 100644 index 0000000000000000000000000000000000000000..e208e2a982a6795eec1774d4b95b87180bbef9a6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/escape-regexp.js @@ -0,0 +1,22 @@ +// regexp is based on https://github.com/sindresorhus/escape-string-regexp +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "escapeStringRegexp", { + enumerable: true, + get: function() { + return escapeStringRegexp; + } +}); +const reHasRegExp = /[|\\{}()[\]^$+*?.-]/; +const reReplaceRegExp = /[|\\{}()[\]^$+*?.-]/g; +function escapeStringRegexp(str) { + // see also: https://github.com/lodash/lodash/blob/2da024c3b4f9947a48517639de7560457cd4ec6c/escapeRegExp.js#L23 + if (reHasRegExp.test(str)) { + return str.replace(reReplaceRegExp, '\\$&'); + } + return str; +} + +//# sourceMappingURL=escape-regexp.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/escape-regexp.js.map b/e-commerce/node_modules/next/dist/shared/lib/escape-regexp.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0600bf2606de8d54d76d88f128dc0714d77b3cdf --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/escape-regexp.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/escape-regexp.ts"],"sourcesContent":["// regexp is based on https://github.com/sindresorhus/escape-string-regexp\nconst reHasRegExp = /[|\\\\{}()[\\]^$+*?.-]/\nconst reReplaceRegExp = /[|\\\\{}()[\\]^$+*?.-]/g\n\nexport function escapeStringRegexp(str: string) {\n // see also: https://github.com/lodash/lodash/blob/2da024c3b4f9947a48517639de7560457cd4ec6c/escapeRegExp.js#L23\n if (reHasRegExp.test(str)) {\n return str.replace(reReplaceRegExp, '\\\\$&')\n }\n return str\n}\n"],"names":["escapeStringRegexp","reHasRegExp","reReplaceRegExp","str","test","replace"],"mappings":"AAAA,0EAA0E;;;;;+BAI1DA;;;eAAAA;;;AAHhB,MAAMC,cAAc;AACpB,MAAMC,kBAAkB;AAEjB,SAASF,mBAAmBG,GAAW;IAC5C,+GAA+G;IAC/G,IAAIF,YAAYG,IAAI,CAACD,MAAM;QACzB,OAAOA,IAAIE,OAAO,CAACH,iBAAiB;IACtC;IACA,OAAOC;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/find-closest-quality.d.ts b/e-commerce/node_modules/next/dist/shared/lib/find-closest-quality.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0ba843f8a94e4328a94bf7f330175292bf1d07a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/find-closest-quality.d.ts @@ -0,0 +1,8 @@ +import type { NextConfig } from '../../server/config-shared'; +/** + * Find the closest matching `quality` in the list of `config.qualities` + * @param quality the quality prop passed to the image component + * @param config the "images" configuration from next.config.js + * @returns the closest matching quality value + */ +export declare function findClosestQuality(quality: number | undefined, config: NextConfig['images'] | undefined): number; diff --git a/e-commerce/node_modules/next/dist/shared/lib/find-closest-quality.js b/e-commerce/node_modules/next/dist/shared/lib/find-closest-quality.js new file mode 100644 index 0000000000000000000000000000000000000000..5f9b59c5913c174b07ec301119d8dd95b39884cb --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/find-closest-quality.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "findClosestQuality", { + enumerable: true, + get: function() { + return findClosestQuality; + } +}); +function findClosestQuality(quality, config) { + const q = quality || 75; + if (!config?.qualities?.length) { + return q; + } + return config.qualities.reduce((prev, cur)=>Math.abs(cur - q) < Math.abs(prev - q) ? cur : prev, config.qualities[0]); +} + +//# sourceMappingURL=find-closest-quality.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/find-closest-quality.js.map b/e-commerce/node_modules/next/dist/shared/lib/find-closest-quality.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a1718160b2c4f4575d08b83a79a78c6388609866 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/find-closest-quality.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/find-closest-quality.ts"],"sourcesContent":["import type { NextConfig } from '../../server/config-shared'\n\n/**\n * Find the closest matching `quality` in the list of `config.qualities`\n * @param quality the quality prop passed to the image component\n * @param config the \"images\" configuration from next.config.js\n * @returns the closest matching quality value\n */\nexport function findClosestQuality(\n quality: number | undefined,\n config: NextConfig['images'] | undefined\n): number {\n const q = quality || 75\n if (!config?.qualities?.length) {\n return q\n }\n return config.qualities.reduce(\n (prev, cur) => (Math.abs(cur - q) < Math.abs(prev - q) ? cur : prev),\n config.qualities[0]\n )\n}\n"],"names":["findClosestQuality","quality","config","q","qualities","length","reduce","prev","cur","Math","abs"],"mappings":";;;;+BAQgBA;;;eAAAA;;;AAAT,SAASA,mBACdC,OAA2B,EAC3BC,MAAwC;IAExC,MAAMC,IAAIF,WAAW;IACrB,IAAI,CAACC,QAAQE,WAAWC,QAAQ;QAC9B,OAAOF;IACT;IACA,OAAOD,OAAOE,SAAS,CAACE,MAAM,CAC5B,CAACC,MAAMC,MAASC,KAAKC,GAAG,CAACF,MAAML,KAAKM,KAAKC,GAAG,CAACH,OAAOJ,KAAKK,MAAMD,MAC/DL,OAAOE,SAAS,CAAC,EAAE;AAEvB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/fnv1a.d.ts b/e-commerce/node_modules/next/dist/shared/lib/fnv1a.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3dd3371805acd97689f6c27c5db96820022e203b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/fnv1a.d.ts @@ -0,0 +1,13 @@ +declare const FNV_PRIMES: { + readonly 32: bigint; + readonly 64: bigint; + readonly 128: bigint; + readonly 256: bigint; + readonly 512: bigint; + readonly 1024: bigint; +}; +export default function fnv1a(inputString: string, { size, seed, }?: { + size?: keyof typeof FNV_PRIMES; + seed?: number; +}): bigint; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/fnv1a.js b/e-commerce/node_modules/next/dist/shared/lib/fnv1a.js new file mode 100644 index 0000000000000000000000000000000000000000..68f1d63668b85f9dbd9b68c3dfc2aa4f33760b1e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/fnv1a.js @@ -0,0 +1,52 @@ +// source: https://github.com/sindresorhus/fnv1a +// FNV_PRIMES and FNV_OFFSETS from +// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return fnv1a; + } +}); +const FNV_PRIMES = { + 32: BigInt(16777619), + 64: BigInt(1099511628211), + 128: BigInt(309485009821345068724781371), + 256: BigInt(374144419156711147060143317175368453031918731002211), + 512: BigInt(35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759), + 1024: BigInt(5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573) +}; +const FNV_OFFSETS = { + 32: BigInt(2166136261), + 64: BigInt(14695981039346656037), + 128: BigInt(144066263297769815596495629667062367629), + 256: BigInt(100029257958052580907070968620625704837092796014241193945225284501741471925557), + 512: BigInt(9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785), + 1024: BigInt(14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915) +}; +function fnv1a(inputString, { size = 32, seed = 0 } = {}) { + if (!FNV_PRIMES[size]) { + throw new Error('The `size` option must be one of 32, 64, 128, 256, 512, or 1024'); + } + let hash = FNV_OFFSETS[size] ^ BigInt(seed); + const fnvPrime = FNV_PRIMES[size]; + // Handle Unicode code points > 0x7f + let isUnicoded = false; + for(let index = 0; index < inputString.length; index++){ + let characterCode = inputString.charCodeAt(index); + // Non-ASCII characters trigger the Unicode escape logic + if (characterCode > 0x7f && !isUnicoded) { + inputString = unescape(encodeURIComponent(inputString)); + characterCode = inputString.charCodeAt(index); + isUnicoded = true; + } + hash ^= BigInt(characterCode); + hash = BigInt.asUintN(size, hash * fnvPrime); + } + return hash; +} + +//# sourceMappingURL=fnv1a.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/fnv1a.js.map b/e-commerce/node_modules/next/dist/shared/lib/fnv1a.js.map new file mode 100644 index 0000000000000000000000000000000000000000..74a0c0cfad9d52e5ad612179a074e1d5318a452b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/fnv1a.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/fnv1a.ts"],"sourcesContent":["// source: https://github.com/sindresorhus/fnv1a\n// FNV_PRIMES and FNV_OFFSETS from\n// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param\n\nconst FNV_PRIMES = {\n 32: BigInt(16_777_619),\n 64: BigInt(1_099_511_628_211),\n 128: BigInt(309_485_009_821_345_068_724_781_371),\n 256: BigInt(\n 374_144_419_156_711_147_060_143_317_175_368_453_031_918_731_002_211\n ),\n 512: BigInt(\n 35_835_915_874_844_867_368_919_076_489_095_108_449_946_327_955_754_392_558_399_825_615_420_669_938_882_575_126_094_039_892_345_713_852_759\n ),\n 1024: BigInt(\n 5_016_456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_720_260_389_217_684_476_157_468_082_573\n ),\n} as const\n\nconst FNV_OFFSETS = {\n 32: BigInt(2_166_136_261),\n 64: BigInt(14_695_981_039_346_656_037),\n 128: BigInt(144_066_263_297_769_815_596_495_629_667_062_367_629),\n 256: BigInt(\n 100_029_257_958_052_580_907_070_968_620_625_704_837_092_796_014_241_193_945_225_284_501_741_471_925_557\n ),\n 512: BigInt(\n 9_659_303_129_496_669_498_009_435_400_716_310_466_090_418_745_672_637_896_108_374_329_434_462_657_994_582_932_197_716_438_449_813_051_892_206_539_805_784_495_328_239_340_083_876_191_928_701_583_869_517_785\n ),\n 1024: BigInt(\n 14_197_795_064_947_621_068_722_070_641_403_218_320_880_622_795_441_933_960_878_474_914_617_582_723_252_296_732_303_717_722_150_864_096_521_202_355_549_365_628_174_669_108_571_814_760_471_015_076_148_029_755_969_804_077_320_157_692_458_563_003_215_304_957_150_157_403_644_460_363_550_505_412_711_285_966_361_610_267_868_082_893_823_963_790_439_336_411_086_884_584_107_735_010_676_915\n ),\n} as const\n\nexport default function fnv1a(\n inputString: string,\n {\n size = 32,\n seed = 0,\n }: {\n size?: keyof typeof FNV_PRIMES\n seed?: number\n } = {}\n) {\n if (!FNV_PRIMES[size]) {\n throw new Error(\n 'The `size` option must be one of 32, 64, 128, 256, 512, or 1024'\n )\n }\n\n let hash: bigint = FNV_OFFSETS[size] ^ BigInt(seed)\n const fnvPrime = FNV_PRIMES[size]\n\n // Handle Unicode code points > 0x7f\n let isUnicoded = false\n\n for (let index = 0; index < inputString.length; index++) {\n let characterCode = inputString.charCodeAt(index)\n\n // Non-ASCII characters trigger the Unicode escape logic\n if (characterCode > 0x7f && !isUnicoded) {\n inputString = unescape(encodeURIComponent(inputString))\n characterCode = inputString.charCodeAt(index)\n isUnicoded = true\n }\n\n hash ^= BigInt(characterCode)\n hash = BigInt.asUintN(size, hash * fnvPrime)\n }\n\n return hash\n}\n"],"names":["fnv1a","FNV_PRIMES","BigInt","FNV_OFFSETS","inputString","size","seed","Error","hash","fnvPrime","isUnicoded","index","length","characterCode","charCodeAt","unescape","encodeURIComponent","asUintN"],"mappings":"AAAA,gDAAgD;AAChD,kCAAkC;AAClC,iEAAiE;;;;;+BAgCjE;;;eAAwBA;;;AA9BxB,MAAMC,aAAa;IACjB,IAAIC,OAAO;IACX,IAAIA,OAAO;IACX,KAAKA,OAAO;IACZ,KAAKA,OACH;IAEF,KAAKA,OACH;IAEF,MAAMA,OACJ;AAEJ;AAEA,MAAMC,cAAc;IAClB,IAAID,OAAO;IACX,IAAIA,OAAO;IACX,KAAKA,OAAO;IACZ,KAAKA,OACH;IAEF,KAAKA,OACH;IAEF,MAAMA,OACJ;AAEJ;AAEe,SAASF,MACtBI,WAAmB,EACnB,EACEC,OAAO,EAAE,EACTC,OAAO,CAAC,EAIT,GAAG,CAAC,CAAC;IAEN,IAAI,CAACL,UAAU,CAACI,KAAK,EAAE;QACrB,MAAM,IAAIE,MACR;IAEJ;IAEA,IAAIC,OAAeL,WAAW,CAACE,KAAK,GAAGH,OAAOI;IAC9C,MAAMG,WAAWR,UAAU,CAACI,KAAK;IAEjC,oCAAoC;IACpC,IAAIK,aAAa;IAEjB,IAAK,IAAIC,QAAQ,GAAGA,QAAQP,YAAYQ,MAAM,EAAED,QAAS;QACvD,IAAIE,gBAAgBT,YAAYU,UAAU,CAACH;QAE3C,wDAAwD;QACxD,IAAIE,gBAAgB,QAAQ,CAACH,YAAY;YACvCN,cAAcW,SAASC,mBAAmBZ;YAC1CS,gBAAgBT,YAAYU,UAAU,CAACH;YACvCD,aAAa;QACf;QAEAF,QAAQN,OAAOW;QACfL,OAAON,OAAOe,OAAO,CAACZ,MAAMG,OAAOC;IACrC;IAEA,OAAOD;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/format-webpack-messages.d.ts b/e-commerce/node_modules/next/dist/shared/lib/format-webpack-messages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9865f98526f0e56e827d3cb10ef61c353069658e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/format-webpack-messages.d.ts @@ -0,0 +1 @@ +export default function formatWebpackMessages(json: any, verbose?: boolean): any; diff --git a/e-commerce/node_modules/next/dist/shared/lib/format-webpack-messages.js b/e-commerce/node_modules/next/dist/shared/lib/format-webpack-messages.js new file mode 100644 index 0000000000000000000000000000000000000000..617cc6b235c488efc6c104132c0eda43e67b0eb2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/format-webpack-messages.js @@ -0,0 +1,184 @@ +/** +MIT License + +Copyright (c) 2015-present, Facebook, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return formatWebpackMessages; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _stripansi = /*#__PURE__*/ _interop_require_default._(require("next/dist/compiled/strip-ansi")); +// This file is based on https://github.com/facebook/create-react-app/blob/7b1a32be6ec9f99a6c9a3c66813f3ac09c4736b9/packages/react-dev-utils/formatWebpackMessages.js +// It's been edited to remove chalk and CRA-specific logic +const friendlySyntaxErrorLabel = 'Syntax error:'; +const WEBPACK_BREAKING_CHANGE_POLYFILLS = '\n\nBREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.'; +function isLikelyASyntaxError(message) { + return (0, _stripansi.default)(message).includes(friendlySyntaxErrorLabel); +} +let hadMissingSassError = false; +// Cleans up webpack error messages. +function formatMessage(message, verbose, importTraceNote) { + // TODO: Replace this once webpack 5 is stable + if (typeof message === 'object' && message.message) { + let filteredModuleTrace = message.moduleTrace && message.moduleTrace.filter((trace)=>!/next-(middleware|client-pages|route|edge-function)-loader\.js/.test(trace.originName)); + let body = message.message; + const breakingChangeIndex = body.indexOf(WEBPACK_BREAKING_CHANGE_POLYFILLS); + if (breakingChangeIndex >= 0) { + body = body.slice(0, breakingChangeIndex); + } + // TODO: Rspack currently doesn't populate moduleName correctly in some cases, + // fall back to moduleIdentifier as a workaround + if (process.env.NEXT_RSPACK && !message.moduleName && !message.file && message.moduleIdentifier) { + const parts = message.moduleIdentifier.split('!'); + message.moduleName = parts[parts.length - 1]; + } + message = (message.moduleName ? (0, _stripansi.default)(message.moduleName) + '\n' : '') + (message.file ? (0, _stripansi.default)(message.file) + '\n' : '') + body + (message.details && verbose ? '\n' + message.details : '') + (filteredModuleTrace && filteredModuleTrace.length ? (importTraceNote || '\n\nImport trace for requested module:') + filteredModuleTrace.map((trace)=>`\n${trace.moduleName}`).join('') : '') + (message.stack && verbose ? '\n' + message.stack : ''); + } + let lines = message.split('\n'); + // Extract loader paths from Webpack-added headers and move them to end. + // Original format: "Module build failed (from ./loaders/foo-loader.js):" + // The header line is removed and the path is appended at the end as: + // " (from ./loaders/foo-loader.js)" + // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js + const loaderPaths = []; + lines = lines.filter((line)=>{ + const match = /Module [A-z ]+\(from (.+)\):?\s*$/.exec(line); + if (match) { + loaderPaths.push(match[1]); + return false; + } + return true; + }); + // Transform parsing error into syntax error + // TODO: move this to our ESLint formatter? + lines = lines.map((line)=>{ + const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(line); + if (!parsingError) { + return line; + } + const [, errorLine, errorColumn, errorMessage] = parsingError; + return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`; + }); + message = lines.join('\n'); + // Smoosh syntax errors (commonly found in CSS) + message = message.replace(/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g, `${friendlySyntaxErrorLabel} $3 ($1:$2)\n`); + // Clean up export errors + message = message.replace(/^.*export '(.+?)' was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$2'.`); + message = message.replace(/^.*export 'default' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$2' does not contain a default export (imported as '$1').`); + message = message.replace(/^.*export '(.+?)' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$3' (imported as '$2').`); + lines = message.split('\n'); + // Remove leading newline + if (lines.length > 2 && lines[1].trim() === '') { + lines.splice(1, 1); + } + // Cleans up verbose "module not found" messages for files and packages. + if (lines[1] && lines[1].startsWith('Module not found: ')) { + lines = [ + lines[0], + lines[1].replace('Error: ', '').replace('Module not found: Cannot find file:', 'Cannot find file:'), + ...lines.slice(2) + ]; + } + // Add helpful message for users trying to use Sass for the first time + if (lines[1] && lines[1].match(/Cannot find module.+sass/)) { + // ./file.module.scss (<>) => ./file.module.scss + const firstLine = lines[0].split('!'); + lines[0] = firstLine[firstLine.length - 1]; + lines[1] = "To use Next.js' built-in Sass support, you first need to install `sass`.\n"; + lines[1] += 'Run `npm i sass` or `yarn add sass` inside your workspace.\n'; + lines[1] += '\nLearn more: https://nextjs.org/docs/messages/install-sass'; + // dispose of unhelpful stack trace + lines = lines.slice(0, 2); + hadMissingSassError = true; + } else if (hadMissingSassError && message.match(/(sass-loader|resolve-url-loader: CSS error)/)) { + // dispose of unhelpful stack trace following missing sass module + lines = []; + } + if (!verbose) { + message = lines.join('\n'); + // Internal stacks are generally useless so we strip them... with the + // exception of stacks containing `webpack:` because they're normally + // from user code generated by Webpack. For more information see + // https://github.com/facebook/create-react-app/pull/1050 + message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, '') // at ... ...:x:y + ; + message = message.replace(/^\s*at\s(\n|$)/gm, '') // at + ; + message = message.replace(/File was processed with these loaders:\n(.+[\\/](next[\\/]dist[\\/].+|@next[\\/]react-refresh-utils[\\/]loader)\.js\n)*You may need an additional loader to handle the result of these loaders.\n/g, ''); + lines = message.split('\n'); + } + // Append loader paths at the end (before any remaining stack trace) + if (loaderPaths.length > 0) { + for (const loaderPath of loaderPaths){ + // Don't show internal Next.js loader paths — they're noise for users + if (!/[/\\]next[/\\]dist[/\\]/.test(loaderPath)) { + lines.push(` (from ${loaderPath})`); + } + } + } + // Remove duplicated newlines + lines = lines.filter((line, index, arr)=>index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim()); + // Reassemble the message + message = lines.join('\n'); + return message.trim(); +} +function formatWebpackMessages(json, verbose) { + const formattedErrors = json.errors.map((message)=>{ + const isUnknownNextFontError = message.message.includes('An error occurred in `next/font`.'); + return formatMessage(message, isUnknownNextFontError || verbose); + }); + const formattedWarnings = json.warnings.map((message)=>{ + return formatMessage(message, verbose); + }); + // Reorder errors to put the most relevant ones first. + let reactServerComponentsError = -1; + for(let i = 0; i < formattedErrors.length; i++){ + const error = formattedErrors[i]; + if (error.includes('ReactServerComponentsError')) { + reactServerComponentsError = i; + break; + } + } + // Move the reactServerComponentsError to the top if it exists + if (reactServerComponentsError !== -1) { + const error = formattedErrors.splice(reactServerComponentsError, 1); + formattedErrors.unshift(error[0]); + } + const result = { + ...json, + errors: formattedErrors, + warnings: formattedWarnings + }; + if (!verbose && result.errors.some(isLikelyASyntaxError)) { + // If there are any syntax errors, show just them. + result.errors = result.errors.filter(isLikelyASyntaxError); + result.warnings = []; + } + return result; +} + +//# sourceMappingURL=format-webpack-messages.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/format-webpack-messages.js.map b/e-commerce/node_modules/next/dist/shared/lib/format-webpack-messages.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ce8a4f919bc07eb9c107f47356abdd26b1396e02 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/format-webpack-messages.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/format-webpack-messages.ts"],"sourcesContent":["/**\nMIT License\n\nCopyright (c) 2015-present, Facebook, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\nimport stripAnsi from 'next/dist/compiled/strip-ansi'\n// This file is based on https://github.com/facebook/create-react-app/blob/7b1a32be6ec9f99a6c9a3c66813f3ac09c4736b9/packages/react-dev-utils/formatWebpackMessages.js\n// It's been edited to remove chalk and CRA-specific logic\n\nconst friendlySyntaxErrorLabel = 'Syntax error:'\n\nconst WEBPACK_BREAKING_CHANGE_POLYFILLS =\n '\\n\\nBREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.'\n\nfunction isLikelyASyntaxError(message: string) {\n return stripAnsi(message).includes(friendlySyntaxErrorLabel)\n}\n\nlet hadMissingSassError = false\n\n// Cleans up webpack error messages.\nfunction formatMessage(\n message: any,\n verbose?: boolean,\n importTraceNote?: boolean\n) {\n // TODO: Replace this once webpack 5 is stable\n if (typeof message === 'object' && message.message) {\n let filteredModuleTrace =\n message.moduleTrace &&\n message.moduleTrace.filter(\n (trace: any) =>\n !/next-(middleware|client-pages|route|edge-function)-loader\\.js/.test(\n trace.originName\n )\n )\n\n let body = message.message\n const breakingChangeIndex = body.indexOf(WEBPACK_BREAKING_CHANGE_POLYFILLS)\n if (breakingChangeIndex >= 0) {\n body = body.slice(0, breakingChangeIndex)\n }\n\n // TODO: Rspack currently doesn't populate moduleName correctly in some cases,\n // fall back to moduleIdentifier as a workaround\n if (\n process.env.NEXT_RSPACK &&\n !message.moduleName &&\n !message.file &&\n message.moduleIdentifier\n ) {\n const parts = message.moduleIdentifier.split('!')\n message.moduleName = parts[parts.length - 1]\n }\n\n message =\n (message.moduleName ? stripAnsi(message.moduleName) + '\\n' : '') +\n (message.file ? stripAnsi(message.file) + '\\n' : '') +\n body +\n (message.details && verbose ? '\\n' + message.details : '') +\n (filteredModuleTrace && filteredModuleTrace.length\n ? (importTraceNote || '\\n\\nImport trace for requested module:') +\n filteredModuleTrace\n .map((trace: any) => `\\n${trace.moduleName}`)\n .join('')\n : '') +\n (message.stack && verbose ? '\\n' + message.stack : '')\n }\n let lines = message.split('\\n')\n\n // Extract loader paths from Webpack-added headers and move them to end.\n // Original format: \"Module build failed (from ./loaders/foo-loader.js):\"\n // The header line is removed and the path is appended at the end as:\n // \" (from ./loaders/foo-loader.js)\"\n // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js\n const loaderPaths: string[] = []\n lines = lines.filter((line: string) => {\n const match = /Module [A-z ]+\\(from (.+)\\):?\\s*$/.exec(line)\n if (match) {\n loaderPaths.push(match[1])\n return false\n }\n return true\n })\n\n // Transform parsing error into syntax error\n // TODO: move this to our ESLint formatter?\n lines = lines.map((line: string) => {\n const parsingError = /Line (\\d+):(?:(\\d+):)?\\s*Parsing error: (.+)$/.exec(\n line\n )\n if (!parsingError) {\n return line\n }\n const [, errorLine, errorColumn, errorMessage] = parsingError\n return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`\n })\n\n message = lines.join('\\n')\n // Smoosh syntax errors (commonly found in CSS)\n message = message.replace(\n /SyntaxError\\s+\\((\\d+):(\\d+)\\)\\s*(.+?)\\n/g,\n `${friendlySyntaxErrorLabel} $3 ($1:$2)\\n`\n )\n // Clean up export errors\n message = message.replace(\n /^.*export '(.+?)' was not found in '(.+?)'.*$/gm,\n `Attempted import error: '$1' is not exported from '$2'.`\n )\n message = message.replace(\n /^.*export 'default' \\(imported as '(.+?)'\\) was not found in '(.+?)'.*$/gm,\n `Attempted import error: '$2' does not contain a default export (imported as '$1').`\n )\n message = message.replace(\n /^.*export '(.+?)' \\(imported as '(.+?)'\\) was not found in '(.+?)'.*$/gm,\n `Attempted import error: '$1' is not exported from '$3' (imported as '$2').`\n )\n lines = message.split('\\n')\n\n // Remove leading newline\n if (lines.length > 2 && lines[1].trim() === '') {\n lines.splice(1, 1)\n }\n\n // Cleans up verbose \"module not found\" messages for files and packages.\n if (lines[1] && lines[1].startsWith('Module not found: ')) {\n lines = [\n lines[0],\n lines[1]\n .replace('Error: ', '')\n .replace('Module not found: Cannot find file:', 'Cannot find file:'),\n ...lines.slice(2),\n ]\n }\n\n // Add helpful message for users trying to use Sass for the first time\n if (lines[1] && lines[1].match(/Cannot find module.+sass/)) {\n // ./file.module.scss (<>) => ./file.module.scss\n const firstLine = lines[0].split('!')\n lines[0] = firstLine[firstLine.length - 1]\n\n lines[1] =\n \"To use Next.js' built-in Sass support, you first need to install `sass`.\\n\"\n lines[1] += 'Run `npm i sass` or `yarn add sass` inside your workspace.\\n'\n lines[1] += '\\nLearn more: https://nextjs.org/docs/messages/install-sass'\n\n // dispose of unhelpful stack trace\n lines = lines.slice(0, 2)\n hadMissingSassError = true\n } else if (\n hadMissingSassError &&\n message.match(/(sass-loader|resolve-url-loader: CSS error)/)\n ) {\n // dispose of unhelpful stack trace following missing sass module\n lines = []\n }\n\n if (!verbose) {\n message = lines.join('\\n')\n // Internal stacks are generally useless so we strip them... with the\n // exception of stacks containing `webpack:` because they're normally\n // from user code generated by Webpack. For more information see\n // https://github.com/facebook/create-react-app/pull/1050\n message = message.replace(\n /^\\s*at\\s((?!webpack:).)*:\\d+:\\d+[\\s)]*(\\n|$)/gm,\n ''\n ) // at ... ...:x:y\n message = message.replace(/^\\s*at\\s(\\n|$)/gm, '') // at \n\n message = message.replace(\n /File was processed with these loaders:\\n(.+[\\\\/](next[\\\\/]dist[\\\\/].+|@next[\\\\/]react-refresh-utils[\\\\/]loader)\\.js\\n)*You may need an additional loader to handle the result of these loaders.\\n/g,\n ''\n )\n\n lines = message.split('\\n')\n }\n\n // Append loader paths at the end (before any remaining stack trace)\n if (loaderPaths.length > 0) {\n for (const loaderPath of loaderPaths) {\n // Don't show internal Next.js loader paths — they're noise for users\n if (!/[/\\\\]next[/\\\\]dist[/\\\\]/.test(loaderPath)) {\n lines.push(` (from ${loaderPath})`)\n }\n }\n }\n\n // Remove duplicated newlines\n lines = (lines as string[]).filter(\n (line, index, arr) =>\n index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim()\n )\n\n // Reassemble the message\n message = lines.join('\\n')\n return message.trim()\n}\n\nexport default function formatWebpackMessages(json: any, verbose?: boolean) {\n const formattedErrors = json.errors.map((message: any) => {\n const isUnknownNextFontError = message.message.includes(\n 'An error occurred in `next/font`.'\n )\n return formatMessage(message, isUnknownNextFontError || verbose)\n })\n const formattedWarnings = json.warnings.map((message: any) => {\n return formatMessage(message, verbose)\n })\n\n // Reorder errors to put the most relevant ones first.\n let reactServerComponentsError = -1\n\n for (let i = 0; i < formattedErrors.length; i++) {\n const error = formattedErrors[i]\n if (error.includes('ReactServerComponentsError')) {\n reactServerComponentsError = i\n break\n }\n }\n\n // Move the reactServerComponentsError to the top if it exists\n if (reactServerComponentsError !== -1) {\n const error = formattedErrors.splice(reactServerComponentsError, 1)\n formattedErrors.unshift(error[0])\n }\n\n const result = {\n ...json,\n errors: formattedErrors,\n warnings: formattedWarnings,\n }\n if (!verbose && result.errors.some(isLikelyASyntaxError)) {\n // If there are any syntax errors, show just them.\n result.errors = result.errors.filter(isLikelyASyntaxError)\n result.warnings = []\n }\n return result\n}\n"],"names":["formatWebpackMessages","friendlySyntaxErrorLabel","WEBPACK_BREAKING_CHANGE_POLYFILLS","isLikelyASyntaxError","message","stripAnsi","includes","hadMissingSassError","formatMessage","verbose","importTraceNote","filteredModuleTrace","moduleTrace","filter","trace","test","originName","body","breakingChangeIndex","indexOf","slice","process","env","NEXT_RSPACK","moduleName","file","moduleIdentifier","parts","split","length","details","map","join","stack","lines","loaderPaths","line","match","exec","push","parsingError","errorLine","errorColumn","errorMessage","replace","trim","splice","startsWith","firstLine","loaderPath","index","arr","json","formattedErrors","errors","isUnknownNextFontError","formattedWarnings","warnings","reactServerComponentsError","i","error","unshift","result","some"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;AAsBA;;;;+BAkMA;;;eAAwBA;;;;oEAjMF;AACtB,qKAAqK;AACrK,0DAA0D;AAE1D,MAAMC,2BAA2B;AAEjC,MAAMC,oCACJ;AAEF,SAASC,qBAAqBC,OAAe;IAC3C,OAAOC,IAAAA,kBAAS,EAACD,SAASE,QAAQ,CAACL;AACrC;AAEA,IAAIM,sBAAsB;AAE1B,oCA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","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-hostname.d.ts b/e-commerce/node_modules/next/dist/shared/lib/get-hostname.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..188883b1dbf45150572ef95c1b93c8b8ffa56e25 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-hostname.d.ts @@ -0,0 +1,10 @@ +import type { OutgoingHttpHeaders } from 'http'; +/** + * Takes an object with a hostname property (like a parsed URL) and some + * headers that may contain Host and returns the preferred hostname. + * @param parsed An object containing a hostname property. + * @param headers A dictionary with headers containing a `host`. + */ +export declare function getHostname(parsed: { + hostname?: string | null; +}, headers?: OutgoingHttpHeaders): string | undefined; diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-hostname.js b/e-commerce/node_modules/next/dist/shared/lib/get-hostname.js new file mode 100644 index 0000000000000000000000000000000000000000..9511b828eb82db77ccd1ac2abfbb306106c77ea3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-hostname.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getHostname", { + enumerable: true, + get: function() { + return getHostname; + } +}); +function getHostname(parsed, headers) { + // Get the hostname from the headers if it exists, otherwise use the parsed + // hostname. + let hostname; + if (headers?.host && !Array.isArray(headers.host)) { + hostname = headers.host.toString().split(':', 1)[0]; + } else if (parsed.hostname) { + hostname = parsed.hostname; + } else return; + return hostname.toLowerCase(); +} + +//# sourceMappingURL=get-hostname.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-hostname.js.map b/e-commerce/node_modules/next/dist/shared/lib/get-hostname.js.map new file mode 100644 index 0000000000000000000000000000000000000000..034b7049bbe65e44e600a4d504c389236c656156 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-hostname.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/get-hostname.ts"],"sourcesContent":["import type { OutgoingHttpHeaders } from 'http'\n\n/**\n * Takes an object with a hostname property (like a parsed URL) and some\n * headers that may contain Host and returns the preferred hostname.\n * @param parsed An object containing a hostname property.\n * @param headers A dictionary with headers containing a `host`.\n */\nexport function getHostname(\n parsed: { hostname?: string | null },\n headers?: OutgoingHttpHeaders\n): string | undefined {\n // Get the hostname from the headers if it exists, otherwise use the parsed\n // hostname.\n let hostname: string\n if (headers?.host && !Array.isArray(headers.host)) {\n hostname = headers.host.toString().split(':', 1)[0]\n } else if (parsed.hostname) {\n hostname = parsed.hostname\n } else return\n\n return hostname.toLowerCase()\n}\n"],"names":["getHostname","parsed","headers","hostname","host","Array","isArray","toString","split","toLowerCase"],"mappings":";;;;+BAQgBA;;;eAAAA;;;AAAT,SAASA,YACdC,MAAoC,EACpCC,OAA6B;IAE7B,2EAA2E;IAC3E,YAAY;IACZ,IAAIC;IACJ,IAAID,SAASE,QAAQ,CAACC,MAAMC,OAAO,CAACJ,QAAQE,IAAI,GAAG;QACjDD,WAAWD,QAAQE,IAAI,CAACG,QAAQ,GAAGC,KAAK,CAAC,KAAK,EAAE,CAAC,EAAE;IACrD,OAAO,IAAIP,OAAOE,QAAQ,EAAE;QAC1BA,WAAWF,OAAOE,QAAQ;IAC5B,OAAO;IAEP,OAAOA,SAASM,WAAW;AAC7B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-img-props.d.ts b/e-commerce/node_modules/next/dist/shared/lib/get-img-props.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff4d4371fb917faa04496ae2e1b87db5f3d09fc9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-img-props.d.ts @@ -0,0 +1,96 @@ +import type { ImageLoaderProps, ImageLoaderPropsWithConfig, PreparedImageConfig } from './image-config'; +import type { CSSProperties, JSX } from 'react'; +export interface StaticImageData { + src: string; + height: number; + width: number; + blurDataURL?: string; + blurWidth?: number; + blurHeight?: number; +} +export interface StaticRequire { + default: StaticImageData; +} +export type StaticImport = StaticRequire | StaticImageData; +export type ImageProps = Omit & { + src: string | StaticImport; + alt: string; + width?: number | `${number}`; + height?: number | `${number}`; + fill?: boolean; + loader?: ImageLoader; + quality?: number | `${number}`; + preload?: boolean; + /** + * @deprecated Use `preload` prop instead. + * See https://nextjs.org/docs/app/api-reference/components/image#preload + */ + priority?: boolean; + loading?: LoadingValue; + placeholder?: PlaceholderValue; + blurDataURL?: string; + unoptimized?: boolean; + overrideSrc?: string; + /** + * @deprecated Use `onLoad` instead. + * @see https://nextjs.org/docs/app/api-reference/components/image#onload + */ + onLoadingComplete?: OnLoadingComplete; + /** + * @deprecated Use `fill` prop instead of `layout="fill"` or change import to `next/legacy/image`. + * @see https://nextjs.org/docs/api-reference/next/legacy/image + */ + layout?: string; + /** + * @deprecated Use `style` prop instead. + */ + objectFit?: string; + /** + * @deprecated Use `style` prop instead. + */ + objectPosition?: string; + /** + * @deprecated This prop does not do anything. + */ + lazyBoundary?: string; + /** + * @deprecated This prop does not do anything. + */ + lazyRoot?: string; +}; +export type ImgProps = Omit & { + loading: LoadingValue; + width: number | undefined; + height: number | undefined; + style: NonNullable; + sizes: string | undefined; + srcSet: string | undefined; + src: string; +}; +declare const VALID_LOADING_VALUES: readonly ["lazy", "eager", undefined]; +type LoadingValue = (typeof VALID_LOADING_VALUES)[number]; +type ImageConfig = PreparedImageConfig; +export type ImageLoader = (p: ImageLoaderProps) => string; +type ImageLoaderWithConfig = (p: ImageLoaderPropsWithConfig) => string; +export type PlaceholderValue = 'blur' | 'empty' | `data:image/${string}`; +export type OnLoad = React.ReactEventHandler | undefined; +export type OnLoadingComplete = (img: HTMLImageElement) => void; +export type PlaceholderStyle = Partial>; +/** + * A shared function, used on both client and server, to generate the props for . + */ +export declare function getImgProps({ src, sizes, unoptimized, priority, preload, loading, className, quality, width, height, fill, style, overrideSrc, onLoad, onLoadingComplete, placeholder, blurDataURL, fetchPriority, decoding, layout, objectFit, objectPosition, lazyBoundary, lazyRoot, ...rest }: ImageProps, _state: { + defaultLoader: ImageLoaderWithConfig; + imgConf: ImageConfig; + showAltText?: boolean; + blurComplete?: boolean; +}): { + props: ImgProps; + meta: { + unoptimized: boolean; + preload: boolean; + placeholder: NonNullable; + fill: boolean; + }; +}; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-img-props.js b/e-commerce/node_modules/next/dist/shared/lib/get-img-props.js new file mode 100644 index 0000000000000000000000000000000000000000..1c92e4f6f5f1d07d8eef7f07a1d6012afb954ecc --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-img-props.js @@ -0,0 +1,490 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getImgProps", { + enumerable: true, + get: function() { + return getImgProps; + } +}); +const _deploymentid = require("./deployment-id"); +const _imageblursvg = require("./image-blur-svg"); +const VALID_LOADING_VALUES = [ + 'lazy', + 'eager', + undefined +]; +// Object-fit values that are not valid background-size values +const INVALID_BACKGROUND_SIZE_VALUES = [ + '-moz-initial', + 'fill', + 'none', + 'scale-down', + undefined +]; +function isStaticRequire(src) { + return src.default !== undefined; +} +function isStaticImageData(src) { + return src.src !== undefined; +} +function isStaticImport(src) { + return !!src && typeof src === 'object' && (isStaticRequire(src) || isStaticImageData(src)); +} +const allImgs = new Map(); +let perfObserver; +function getInt(x) { + if (typeof x === 'undefined') { + return x; + } + if (typeof x === 'number') { + return Number.isFinite(x) ? x : NaN; + } + if (typeof x === 'string' && /^[0-9]+$/.test(x)) { + return parseInt(x, 10); + } + return NaN; +} +function getWidths({ deviceSizes, allSizes }, width, sizes) { + if (sizes) { + // Find all the "vw" percent sizes used in the sizes prop + const viewportWidthRe = /(^|\s)(1?\d?\d)vw/g; + const percentSizes = []; + for(let match; match = viewportWidthRe.exec(sizes); match){ + percentSizes.push(parseInt(match[2])); + } + if (percentSizes.length) { + const smallestRatio = Math.min(...percentSizes) * 0.01; + return { + widths: allSizes.filter((s)=>s >= deviceSizes[0] * smallestRatio), + kind: 'w' + }; + } + return { + widths: allSizes, + kind: 'w' + }; + } + if (typeof width !== 'number') { + return { + widths: deviceSizes, + kind: 'w' + }; + } + const widths = [ + ...new Set(// > This means that most OLED screens that say they are 3x resolution, + // > are actually 3x in the green color, but only 1.5x in the red and + // > blue colors. Showing a 3x resolution image in the app vs a 2x + // > resolution image will be visually the same, though the 3x image + // > takes significantly more data. Even true 3x resolution screens are + // > wasteful as the human eye cannot see that level of detail without + // > something like a magnifying glass. + // https://blog.twitter.com/engineering/en_us/topics/infrastructure/2019/capping-image-fidelity-on-ultra-high-resolution-devices.html + [ + width, + width * 2 /*, width * 3*/ + ].map((w)=>allSizes.find((p)=>p >= w) || allSizes[allSizes.length - 1])) + ]; + return { + widths, + kind: 'x' + }; +} +function generateImgAttrs({ config, src, unoptimized, width, quality, sizes, loader }) { + if (unoptimized) { + if (src.startsWith('/') && !src.startsWith('//')) { + let deploymentId = (0, _deploymentid.getDeploymentId)(); + if (src.includes('/_next/static/immutable') && !(0, _deploymentid.getAssetToken)()) { + // immutable static asset and supported by platform, don't add `?dpl=` + deploymentId = undefined; + } else if (deploymentId) { + // We unfortunately can't easily use `new URL()` here, because it normalizes the URL which causes + // double-encoding with the `encodeURIComponent(src)` below + const qIndex = src.indexOf('?'); + if (qIndex !== -1) { + const params = new URLSearchParams(src.slice(qIndex + 1)); + const srcDpl = params.get('dpl'); + if (!srcDpl) { + // src is missing the dpl parameter, but we have a deploymentId, so add it to the src URL + params.append('dpl', deploymentId); + src = src.slice(0, qIndex) + '?' + params.toString(); + } + } else { + // src is missing the dpl parameter, but we have a deploymentId, so add it to the src URL + src = src + `?dpl=${deploymentId}`; + } + } + } + return { + src, + srcSet: undefined, + sizes: undefined + }; + } + const { widths, kind } = getWidths(config, width, sizes); + const last = widths.length - 1; + return { + sizes: !sizes && kind === 'w' ? '100vw' : sizes, + srcSet: widths.map((w, i)=>`${loader({ + config, + src, + quality, + width: w + })} ${kind === 'w' ? w : i + 1}${kind}`).join(', '), + // It's intended to keep `src` the last attribute because React updates + // attributes in order. If we keep `src` the first one, Safari will + // immediately start to fetch `src`, before `sizes` and `srcSet` are even + // updated by React. That causes multiple unnecessary requests if `srcSet` + // and `sizes` are defined. + // This bug cannot be reproduced in Chrome or Firefox. + src: loader({ + config, + src, + quality, + width: widths[last] + }) + }; +} +function getImgProps({ src, sizes, unoptimized = false, priority = false, preload = false, loading, className, quality, width, height, fill = false, style, overrideSrc, onLoad, onLoadingComplete, placeholder = 'empty', blurDataURL, fetchPriority, decoding = 'async', layout, objectFit, objectPosition, lazyBoundary, lazyRoot, ...rest }, _state) { + const { imgConf: config, showAltText, blurComplete, defaultLoader } = _state; + if (typeof defaultLoader === 'undefined') { + throw new Error('images.loaderFile detected but the file is missing default export.\nRead more: https://nextjs.org/docs/messages/invalid-images-config'); + } + let loader = rest.loader || defaultLoader; + // Remove property so it's not spread on element + delete rest.loader; + delete rest.srcSet; + // This special value indicates that the user + // didn't define a "loader" prop or "loader" config. + const isDefaultLoader = '__next_img_default' in loader; + if (isDefaultLoader) { + if (config.loader === 'custom') { + throw new Error(`Image with src "${src}" is missing "loader" prop.` + `\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader`); + } + } else { + // The user defined a "loader" prop or config. + // Since the config object is internal only, we + // must not pass it to the user-defined "loader". + const customImageLoader = loader; + loader = (obj)=>{ + const { config: _, ...opts } = obj; + return customImageLoader(opts); + }; + } + if (layout) { + if (layout === 'fill') { + fill = true; + } + const layoutToStyle = { + intrinsic: { + maxWidth: '100%', + height: 'auto' + }, + responsive: { + width: '100%', + height: 'auto' + } + }; + const layoutToSizes = { + responsive: '100vw', + fill: '100vw' + }; + const layoutStyle = layoutToStyle[layout]; + if (layoutStyle) { + style = { + ...style, + ...layoutStyle + }; + } + const layoutSizes = layoutToSizes[layout]; + if (layoutSizes && !sizes) { + sizes = layoutSizes; + } + } + let staticSrc = ''; + let widthInt = getInt(width); + let heightInt = getInt(height); + let blurWidth; + let blurHeight; + if (isStaticImport(src)) { + const staticImageData = isStaticRequire(src) ? src.default : src; + if (!staticImageData.src) { + throw new Error(`An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received ${JSON.stringify(staticImageData)}`); + } + if (!staticImageData.height || !staticImageData.width) { + throw new Error(`An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ${JSON.stringify(staticImageData)}`); + } + blurWidth = staticImageData.blurWidth; + blurHeight = staticImageData.blurHeight; + blurDataURL = blurDataURL || staticImageData.blurDataURL; + staticSrc = staticImageData.src; + if (!fill) { + if (!widthInt && !heightInt) { + widthInt = staticImageData.width; + heightInt = staticImageData.height; + } else if (widthInt && !heightInt) { + const ratio = widthInt / staticImageData.width; + heightInt = Math.round(staticImageData.height * ratio); + } else if (!widthInt && heightInt) { + const ratio = heightInt / staticImageData.height; + widthInt = Math.round(staticImageData.width * ratio); + } + } + } + src = typeof src === 'string' ? src : staticSrc; + let isLazy = !priority && !preload && (loading === 'lazy' || typeof loading === 'undefined'); + if (!src || src.startsWith('data:') || src.startsWith('blob:')) { + // https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URIs + unoptimized = true; + isLazy = false; + } + if (config.unoptimized) { + unoptimized = true; + } + if (isDefaultLoader && !config.dangerouslyAllowSVG && src.split('?', 1)[0].endsWith('.svg')) { + // Special case to make svg serve as-is to avoid proxying + // through the built-in Image Optimization API. + unoptimized = true; + } + const qualityInt = getInt(quality); + if (process.env.NODE_ENV !== 'production') { + const { warnOnce } = require('./utils/warn-once'); + if (config.output === 'export' && isDefaultLoader && !unoptimized) { + throw new Error(`Image Optimization using the default loader is not compatible with \`{ output: 'export' }\`. + Possible solutions: + - Remove \`{ output: 'export' }\` and run "next start" to run server mode including the Image Optimization API. + - Configure \`{ images: { unoptimized: true } }\` in \`next.config.js\` to disable the Image Optimization API. + Read more: https://nextjs.org/docs/messages/export-image-api`); + } + if (!src) { + // React doesn't show the stack trace and there's + // no `src` to help identify which image, so we + // instead console.error(ref) during mount. + unoptimized = true; + } else { + if (fill) { + if (width) { + throw new Error(`Image with src "${src}" has both "width" and "fill" properties. Only one should be used.`); + } + if (height) { + throw new Error(`Image with src "${src}" has both "height" and "fill" properties. Only one should be used.`); + } + if (style?.position && style.position !== 'absolute') { + throw new Error(`Image with src "${src}" has both "fill" and "style.position" properties. Images with "fill" always use position absolute - it cannot be modified.`); + } + if (style?.width && style.width !== '100%') { + throw new Error(`Image with src "${src}" has both "fill" and "style.width" properties. Images with "fill" always use width 100% - it cannot be modified.`); + } + if (style?.height && style.height !== '100%') { + throw new Error(`Image with src "${src}" has both "fill" and "style.height" properties. Images with "fill" always use height 100% - it cannot be modified.`); + } + } else { + if (typeof widthInt === 'undefined') { + throw new Error(`Image with src "${src}" is missing required "width" property.`); + } else if (isNaN(widthInt)) { + throw new Error(`Image with src "${src}" has invalid "width" property. Expected a numeric value in pixels but received "${width}".`); + } + if (typeof heightInt === 'undefined') { + throw new Error(`Image with src "${src}" is missing required "height" property.`); + } else if (isNaN(heightInt)) { + throw new Error(`Image with src "${src}" has invalid "height" property. Expected a numeric value in pixels but received "${height}".`); + } + // eslint-disable-next-line no-control-regex + if (/^[\x00-\x20]/.test(src)) { + throw new Error(`Image with src "${src}" cannot start with a space or control character. Use src.trimStart() to remove it or encodeURIComponent(src) to keep it.`); + } + // eslint-disable-next-line no-control-regex + if (/[\x00-\x20]$/.test(src)) { + throw new Error(`Image with src "${src}" cannot end with a space or control character. Use src.trimEnd() to remove it or encodeURIComponent(src) to keep it.`); + } + } + } + if (!VALID_LOADING_VALUES.includes(loading)) { + throw new Error(`Image with src "${src}" has invalid "loading" property. Provided "${loading}" should be one of ${VALID_LOADING_VALUES.map(String).join(',')}.`); + } + if (priority && loading === 'lazy') { + throw new Error(`Image with src "${src}" has both "priority" and "loading='lazy'" properties. Only one should be used.`); + } + if (preload && loading === 'lazy') { + throw new Error(`Image with src "${src}" has both "preload" and "loading='lazy'" properties. Only one should be used.`); + } + if (preload && priority) { + throw new Error(`Image with src "${src}" has both "preload" and "priority" properties. Only "preload" should be used.`); + } + if (placeholder !== 'empty' && placeholder !== 'blur' && !placeholder.startsWith('data:image/')) { + throw new Error(`Image with src "${src}" has invalid "placeholder" property "${placeholder}".`); + } + if (placeholder !== 'empty') { + if (widthInt && heightInt && widthInt * heightInt < 1600) { + warnOnce(`Image with src "${src}" is smaller than 40x40. Consider removing the "placeholder" property to improve performance.`); + } + } + if (qualityInt && config.qualities && !config.qualities.includes(qualityInt)) { + warnOnce(`Image with src "${src}" is using quality "${qualityInt}" which is not configured in images.qualities [${config.qualities.join(', ')}]. Please update your config to [${[ + ...config.qualities, + qualityInt + ].sort().join(', ')}].` + `\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-qualities`); + } + if (placeholder === 'blur' && !blurDataURL) { + const VALID_BLUR_EXT = [ + 'jpeg', + 'png', + 'webp', + 'avif' + ] // should match next-image-loader + ; + throw new Error(`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property. + Possible solutions: + - Add a "blurDataURL" property, the contents should be a small Data URL to represent the image + - Change the "src" property to a static import with one of the supported file types: ${VALID_BLUR_EXT.join(',')} (animated images not supported) + - Remove the "placeholder" property, effectively no blur effect + Read more: https://nextjs.org/docs/messages/placeholder-blur-data-url`); + } + if ('ref' in rest) { + warnOnce(`Image with src "${src}" is using unsupported "ref" property. Consider using the "onLoad" property instead.`); + } + if (!unoptimized && !isDefaultLoader) { + const urlStr = loader({ + config, + src, + width: widthInt || 400, + quality: qualityInt || 75 + }); + let url; + try { + url = new URL(urlStr); + } catch (err) {} + if (urlStr === src || url && url.pathname === src && !url.search) { + warnOnce(`Image with src "${src}" has a "loader" property that does not implement width. Please implement it or use the "unoptimized" property instead.` + `\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader-width`); + } + } + if (onLoadingComplete) { + warnOnce(`Image with src "${src}" is using deprecated "onLoadingComplete" property. Please use the "onLoad" property instead.`); + } + for (const [legacyKey, legacyValue] of Object.entries({ + layout, + objectFit, + objectPosition, + lazyBoundary, + lazyRoot + })){ + if (legacyValue) { + warnOnce(`Image with src "${src}" has legacy prop "${legacyKey}". Did you forget to run the codemod?` + `\nRead more: https://nextjs.org/docs/messages/next-image-upgrade-to-13`); + } + } + if (typeof window !== 'undefined' && !perfObserver && window.PerformanceObserver) { + perfObserver = new PerformanceObserver((entryList)=>{ + for (const entry of entryList.getEntries()){ + // @ts-ignore - missing "LargestContentfulPaint" class with "element" prop + const imgSrc = entry?.element?.src || ''; + const lcpImage = allImgs.get(imgSrc); + if (lcpImage && lcpImage.loading === 'lazy' && lcpImage.placeholder === 'empty' && !lcpImage.src.startsWith('data:') && !lcpImage.src.startsWith('blob:')) { + // https://web.dev/lcp/#measure-lcp-in-javascript + warnOnce(`Image with src "${lcpImage.src}" was detected as the Largest Contentful Paint (LCP). Please add the \`loading="eager"\` property if this image is above the fold.` + `\nRead more: https://nextjs.org/docs/app/api-reference/components/image#loading`); + } + } + }); + try { + perfObserver.observe({ + type: 'largest-contentful-paint', + buffered: true + }); + } catch (err) { + // Log error but don't crash the app + console.error(err); + } + } + } + const imgStyle = Object.assign(fill ? { + position: 'absolute', + height: '100%', + width: '100%', + left: 0, + top: 0, + right: 0, + bottom: 0, + objectFit, + objectPosition + } : {}, showAltText ? {} : { + color: 'transparent' + }, style); + const backgroundImage = !blurComplete && placeholder !== 'empty' ? placeholder === 'blur' ? `url("data:image/svg+xml;charset=utf-8,${(0, _imageblursvg.getImageBlurSvg)({ + widthInt, + heightInt, + blurWidth, + blurHeight, + blurDataURL: blurDataURL || '', + objectFit: imgStyle.objectFit + })}")` : `url("${placeholder}")` // assume `data:image/` + : null; + const backgroundSize = !INVALID_BACKGROUND_SIZE_VALUES.includes(imgStyle.objectFit) ? imgStyle.objectFit : imgStyle.objectFit === 'fill' ? '100% 100%' // the background-size equivalent of `fill` + : 'cover'; + let placeholderStyle = backgroundImage ? { + backgroundSize, + backgroundPosition: imgStyle.objectPosition || '50% 50%', + backgroundRepeat: 'no-repeat', + backgroundImage + } : {}; + if (process.env.NODE_ENV === 'development') { + if (placeholderStyle.backgroundImage && placeholder === 'blur' && blurDataURL?.startsWith('/')) { + // During `next dev`, we don't want to generate blur placeholders with webpack + // because it can delay starting the dev server. Instead, `next-image-loader.js` + // will inline a special url to lazily generate the blur placeholder at request time. + placeholderStyle.backgroundImage = `url("${blurDataURL}")`; + } + } + const imgAttributes = generateImgAttrs({ + config, + src, + unoptimized, + width: widthInt, + quality: qualityInt, + sizes, + loader + }); + const loadingFinal = isLazy ? 'lazy' : loading; + if (process.env.NODE_ENV !== 'production') { + if (typeof window !== 'undefined') { + let fullUrl; + try { + fullUrl = new URL(imgAttributes.src); + } catch (e) { + fullUrl = new URL(imgAttributes.src, window.location.href); + } + allImgs.set(fullUrl.href, { + src, + loading: loadingFinal, + placeholder + }); + } + } + const props = { + ...rest, + loading: loadingFinal, + fetchPriority, + width: widthInt, + height: heightInt, + decoding, + className, + style: { + ...imgStyle, + ...placeholderStyle + }, + sizes: imgAttributes.sizes, + srcSet: imgAttributes.srcSet, + src: overrideSrc || imgAttributes.src + }; + const meta = { + unoptimized, + preload: preload || priority, + placeholder, + fill + }; + return { + props, + meta + }; +} + +//# sourceMappingURL=get-img-props.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-img-props.js.map b/e-commerce/node_modules/next/dist/shared/lib/get-img-props.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1556b02e6c4f8456391f3213283958e4a4f1fd19 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-img-props.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/get-img-props.ts"],"sourcesContent":["import { getAssetToken, getDeploymentId } from './deployment-id'\nimport { getImageBlurSvg } from './image-blur-svg'\nimport type {\n ImageLoaderProps,\n ImageLoaderPropsWithConfig,\n PreparedImageConfig,\n} from './image-config'\n\nimport type { CSSProperties, JSX } from 'react'\n\nexport interface StaticImageData {\n src: string\n height: number\n width: number\n blurDataURL?: string\n blurWidth?: number\n blurHeight?: number\n}\n\nexport interface StaticRequire {\n default: StaticImageData\n}\n\nexport type StaticImport = StaticRequire | StaticImageData\n\nexport type ImageProps = Omit<\n JSX.IntrinsicElements['img'],\n 'src' | 'srcSet' | 'ref' | 'alt' | 'width' | 'height' | 'loading'\n> & {\n src: string | StaticImport\n alt: string\n width?: number | `${number}`\n height?: number | `${number}`\n fill?: boolean\n loader?: ImageLoader\n quality?: number | `${number}`\n preload?: boolean\n /**\n * @deprecated Use `preload` prop instead.\n * See https://nextjs.org/docs/app/api-reference/components/image#preload\n */\n priority?: boolean\n loading?: LoadingValue\n placeholder?: PlaceholderValue\n blurDataURL?: string\n unoptimized?: boolean\n overrideSrc?: string\n /**\n * @deprecated Use `onLoad` instead.\n * @see https://nextjs.org/docs/app/api-reference/components/image#onload\n */\n onLoadingComplete?: OnLoadingComplete\n /**\n * @deprecated Use `fill` prop instead of `layout=\"fill\"` or change import to `next/legacy/image`.\n * @see https://nextjs.org/docs/api-reference/next/legacy/image\n */\n layout?: string\n /**\n * @deprecated Use `style` prop instead.\n */\n objectFit?: string\n /**\n * @deprecated Use `style` prop instead.\n */\n objectPosition?: string\n /**\n * @deprecated This prop does not do anything.\n */\n lazyBoundary?: string\n /**\n * @deprecated This prop does not do anything.\n */\n lazyRoot?: string\n}\n\nexport type ImgProps = Omit & {\n loading: LoadingValue\n width: number | undefined\n height: number | undefined\n style: NonNullable\n sizes: string | undefined\n srcSet: string | undefined\n src: string\n}\n\nconst VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const\n\n// Object-fit values that are not valid background-size values\nconst INVALID_BACKGROUND_SIZE_VALUES = [\n '-moz-initial',\n 'fill',\n 'none',\n 'scale-down',\n undefined,\n]\ntype LoadingValue = (typeof VALID_LOADING_VALUES)[number]\ntype ImageConfig = PreparedImageConfig\n\nexport type ImageLoader = (p: ImageLoaderProps) => string\n\n// Do not export - this is an internal type only\n// because `next.config.js` is only meant for the\n// built-in loaders, not for a custom loader() prop.\ntype ImageLoaderWithConfig = (p: ImageLoaderPropsWithConfig) => string\n\nexport type PlaceholderValue = 'blur' | 'empty' | `data:image/${string}`\nexport type OnLoad = React.ReactEventHandler | undefined\nexport type OnLoadingComplete = (img: HTMLImageElement) => void\n\nexport type PlaceholderStyle = Partial<\n Pick<\n CSSProperties,\n | 'backgroundSize'\n | 'backgroundPosition'\n | 'backgroundRepeat'\n | 'backgroundImage'\n >\n>\n\nfunction isStaticRequire(\n src: StaticRequire | StaticImageData\n): src is StaticRequire {\n return (src as StaticRequire).default !== undefined\n}\n\nfunction isStaticImageData(\n src: StaticRequire | StaticImageData\n): src is StaticImageData {\n return (src as StaticImageData).src !== undefined\n}\n\nfunction isStaticImport(src: string | StaticImport): src is StaticImport {\n return (\n !!src &&\n typeof src === 'object' &&\n (isStaticRequire(src as StaticImport) ||\n isStaticImageData(src as StaticImport))\n )\n}\n\nconst allImgs = new Map<\n string,\n { src: string; loading: LoadingValue; placeholder: PlaceholderValue }\n>()\nlet perfObserver: PerformanceObserver | undefined\n\nfunction getInt(x: unknown): number | undefined {\n if (typeof x === 'undefined') {\n return x\n }\n if (typeof x === 'number') {\n return Number.isFinite(x) ? x : NaN\n }\n if (typeof x === 'string' && /^[0-9]+$/.test(x)) {\n return parseInt(x, 10)\n }\n return NaN\n}\n\nfunction getWidths(\n { deviceSizes, allSizes }: ImageConfig,\n width: number | undefined,\n sizes: string | undefined\n): { widths: number[]; kind: 'w' | 'x' } {\n if (sizes) {\n // Find all the \"vw\" percent sizes used in the sizes prop\n const viewportWidthRe = /(^|\\s)(1?\\d?\\d)vw/g\n const percentSizes = []\n for (let match; (match = viewportWidthRe.exec(sizes)); match) {\n percentSizes.push(parseInt(match[2]))\n }\n if (percentSizes.length) {\n const smallestRatio = Math.min(...percentSizes) * 0.01\n return {\n widths: allSizes.filter((s) => s >= deviceSizes[0] * smallestRatio),\n kind: 'w',\n }\n }\n return { widths: allSizes, kind: 'w' }\n }\n if (typeof width !== 'number') {\n return { widths: deviceSizes, kind: 'w' }\n }\n\n const widths = [\n ...new Set(\n // > This means that most OLED screens that say they are 3x resolution,\n // > are actually 3x in the green color, but only 1.5x in the red and\n // > blue colors. Showing a 3x resolution image in the app vs a 2x\n // > resolution image will be visually the same, though the 3x image\n // > takes significantly more data. Even true 3x resolution screens are\n // > wasteful as the human eye cannot see that level of detail without\n // > something like a magnifying glass.\n // https://blog.twitter.com/engineering/en_us/topics/infrastructure/2019/capping-image-fidelity-on-ultra-high-resolution-devices.html\n [width, width * 2 /*, width * 3*/].map(\n (w) => allSizes.find((p) => p >= w) || allSizes[allSizes.length - 1]\n )\n ),\n ]\n return { widths, kind: 'x' }\n}\n\ntype GenImgAttrsData = {\n config: ImageConfig\n src: string\n unoptimized: boolean\n loader: ImageLoaderWithConfig\n width?: number\n quality?: number\n sizes?: string\n}\n\ntype GenImgAttrsResult = {\n src: string\n srcSet: string | undefined\n sizes: string | undefined\n}\n\nfunction generateImgAttrs({\n config,\n src,\n unoptimized,\n width,\n quality,\n sizes,\n loader,\n}: GenImgAttrsData): GenImgAttrsResult {\n if (unoptimized) {\n if (src.startsWith('/') && !src.startsWith('//')) {\n let deploymentId = getDeploymentId()\n if (src.includes('/_next/static/immutable') && !getAssetToken()) {\n // immutable static asset and supported by platform, don't add `?dpl=`\n deploymentId = undefined\n } else if (deploymentId) {\n // We unfortunately can't easily use `new URL()` here, because it normalizes the URL which causes\n // double-encoding with the `encodeURIComponent(src)` below\n const qIndex = src.indexOf('?')\n if (qIndex !== -1) {\n const params = new URLSearchParams(src.slice(qIndex + 1))\n const srcDpl = params.get('dpl')\n if (!srcDpl) {\n // src is missing the dpl parameter, but we have a deploymentId, so add it to the src URL\n params.append('dpl', deploymentId)\n src = src.slice(0, qIndex) + '?' + params.toString()\n }\n } else {\n // src is missing the dpl parameter, but we have a deploymentId, so add it to the src URL\n src = src + `?dpl=${deploymentId}`\n }\n }\n }\n return { src, srcSet: undefined, sizes: undefined }\n }\n\n const { widths, kind } = getWidths(config, width, sizes)\n const last = widths.length - 1\n\n return {\n sizes: !sizes && kind === 'w' ? '100vw' : sizes,\n srcSet: widths\n .map(\n (w, i) =>\n `${loader({ config, src, quality, width: w })} ${\n kind === 'w' ? w : i + 1\n }${kind}`\n )\n .join(', '),\n\n // It's intended to keep `src` the last attribute because React updates\n // attributes in order. If we keep `src` the first one, Safari will\n // immediately start to fetch `src`, before `sizes` and `srcSet` are even\n // updated by React. That causes multiple unnecessary requests if `srcSet`\n // and `sizes` are defined.\n // This bug cannot be reproduced in Chrome or Firefox.\n src: loader({ config, src, quality, width: widths[last] }),\n }\n}\n\n/**\n * A shared function, used on both client and server, to generate the props for .\n */\nexport function getImgProps(\n {\n src,\n sizes,\n unoptimized = false,\n priority = false,\n preload = false,\n loading,\n className,\n quality,\n width,\n height,\n fill = false,\n style,\n overrideSrc,\n onLoad,\n onLoadingComplete,\n placeholder = 'empty',\n blurDataURL,\n fetchPriority,\n decoding = 'async',\n layout,\n objectFit,\n objectPosition,\n lazyBoundary,\n lazyRoot,\n ...rest\n }: ImageProps,\n _state: {\n defaultLoader: ImageLoaderWithConfig\n imgConf: ImageConfig\n showAltText?: boolean\n blurComplete?: boolean\n }\n): {\n props: ImgProps\n meta: {\n unoptimized: boolean\n preload: boolean\n placeholder: NonNullable\n fill: boolean\n }\n} {\n const { imgConf: config, showAltText, blurComplete, defaultLoader } = _state\n\n if (typeof defaultLoader === 'undefined') {\n throw new Error(\n 'images.loaderFile detected but the file is missing default export.\\nRead more: https://nextjs.org/docs/messages/invalid-images-config'\n )\n }\n let loader: ImageLoaderWithConfig = rest.loader || defaultLoader\n\n // Remove property so it's not spread on element\n delete rest.loader\n delete (rest as any).srcSet\n\n // This special value indicates that the user\n // didn't define a \"loader\" prop or \"loader\" config.\n const isDefaultLoader = '__next_img_default' in loader\n\n if (isDefaultLoader) {\n if (config.loader === 'custom') {\n throw new Error(\n `Image with src \"${src}\" is missing \"loader\" prop.` +\n `\\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader`\n )\n }\n } else {\n // The user defined a \"loader\" prop or config.\n // Since the config object is internal only, we\n // must not pass it to the user-defined \"loader\".\n const customImageLoader = loader as ImageLoader\n loader = (obj) => {\n const { config: _, ...opts } = obj\n return customImageLoader(opts)\n }\n }\n\n if (layout) {\n if (layout === 'fill') {\n fill = true\n }\n const layoutToStyle: Record | undefined> = {\n intrinsic: { maxWidth: '100%', height: 'auto' },\n responsive: { width: '100%', height: 'auto' },\n }\n const layoutToSizes: Record = {\n responsive: '100vw',\n fill: '100vw',\n }\n const layoutStyle = layoutToStyle[layout]\n if (layoutStyle) {\n style = { ...style, ...layoutStyle }\n }\n const layoutSizes = layoutToSizes[layout]\n if (layoutSizes && !sizes) {\n sizes = layoutSizes\n }\n }\n\n let staticSrc = ''\n let widthInt = getInt(width)\n let heightInt = getInt(height)\n let blurWidth: number | undefined\n let blurHeight: number | undefined\n if (isStaticImport(src)) {\n const staticImageData = isStaticRequire(src) ? src.default : src\n\n if (!staticImageData.src) {\n throw new Error(\n `An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received ${JSON.stringify(\n staticImageData\n )}`\n )\n }\n if (!staticImageData.height || !staticImageData.width) {\n throw new Error(\n `An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ${JSON.stringify(\n staticImageData\n )}`\n )\n }\n\n blurWidth = staticImageData.blurWidth\n blurHeight = staticImageData.blurHeight\n blurDataURL = blurDataURL || staticImageData.blurDataURL\n staticSrc = staticImageData.src\n\n if (!fill) {\n if (!widthInt && !heightInt) {\n widthInt = staticImageData.width\n heightInt = staticImageData.height\n } else if (widthInt && !heightInt) {\n const ratio = widthInt / staticImageData.width\n heightInt = Math.round(staticImageData.height * ratio)\n } else if (!widthInt && heightInt) {\n const ratio = heightInt / staticImageData.height\n widthInt = Math.round(staticImageData.width * ratio)\n }\n }\n }\n src = typeof src === 'string' ? src : staticSrc\n\n let isLazy =\n !priority &&\n !preload &&\n (loading === 'lazy' || typeof loading === 'undefined')\n if (!src || src.startsWith('data:') || src.startsWith('blob:')) {\n // https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URIs\n unoptimized = true\n isLazy = false\n }\n if (config.unoptimized) {\n unoptimized = true\n }\n if (\n isDefaultLoader &&\n !config.dangerouslyAllowSVG &&\n src.split('?', 1)[0].endsWith('.svg')\n ) {\n // Special case to make svg serve as-is to avoid proxying\n // through the built-in Image Optimization API.\n unoptimized = true\n }\n\n const qualityInt = getInt(quality)\n\n if (process.env.NODE_ENV !== 'production') {\n const { warnOnce } =\n require('./utils/warn-once') as typeof import('./utils/warn-once')\n if (config.output === 'export' && isDefaultLoader && !unoptimized) {\n throw new Error(\n `Image Optimization using the default loader is not compatible with \\`{ output: 'export' }\\`.\n Possible solutions:\n - Remove \\`{ output: 'export' }\\` and run \"next start\" to run server mode including the Image Optimization API.\n - Configure \\`{ images: { unoptimized: true } }\\` in \\`next.config.js\\` to disable the Image Optimization API.\n Read more: https://nextjs.org/docs/messages/export-image-api`\n )\n }\n if (!src) {\n // React doesn't show the stack trace and there's\n // no `src` to help identify which image, so we\n // instead console.error(ref) during mount.\n unoptimized = true\n } else {\n if (fill) {\n if (width) {\n throw new Error(\n `Image with src \"${src}\" has both \"width\" and \"fill\" properties. Only one should be used.`\n )\n }\n if (height) {\n throw new Error(\n `Image with src \"${src}\" has both \"height\" and \"fill\" properties. Only one should be used.`\n )\n }\n if (style?.position && style.position !== 'absolute') {\n throw new Error(\n `Image with src \"${src}\" has both \"fill\" and \"style.position\" properties. Images with \"fill\" always use position absolute - it cannot be modified.`\n )\n }\n if (style?.width && style.width !== '100%') {\n throw new Error(\n `Image with src \"${src}\" has both \"fill\" and \"style.width\" properties. Images with \"fill\" always use width 100% - it cannot be modified.`\n )\n }\n if (style?.height && style.height !== '100%') {\n throw new Error(\n `Image with src \"${src}\" has both \"fill\" and \"style.height\" properties. Images with \"fill\" always use height 100% - it cannot be modified.`\n )\n }\n } else {\n if (typeof widthInt === 'undefined') {\n throw new Error(\n `Image with src \"${src}\" is missing required \"width\" property.`\n )\n } else if (isNaN(widthInt)) {\n throw new Error(\n `Image with src \"${src}\" has invalid \"width\" property. Expected a numeric value in pixels but received \"${width}\".`\n )\n }\n if (typeof heightInt === 'undefined') {\n throw new Error(\n `Image with src \"${src}\" is missing required \"height\" property.`\n )\n } else if (isNaN(heightInt)) {\n throw new Error(\n `Image with src \"${src}\" has invalid \"height\" property. Expected a numeric value in pixels but received \"${height}\".`\n )\n }\n // eslint-disable-next-line no-control-regex\n if (/^[\\x00-\\x20]/.test(src)) {\n throw new Error(\n `Image with src \"${src}\" cannot start with a space or control character. Use src.trimStart() to remove it or encodeURIComponent(src) to keep it.`\n )\n }\n // eslint-disable-next-line no-control-regex\n if (/[\\x00-\\x20]$/.test(src)) {\n throw new Error(\n `Image with src \"${src}\" cannot end with a space or control character. Use src.trimEnd() to remove it or encodeURIComponent(src) to keep it.`\n )\n }\n }\n }\n if (!VALID_LOADING_VALUES.includes(loading)) {\n throw new Error(\n `Image with src \"${src}\" has invalid \"loading\" property. Provided \"${loading}\" should be one of ${VALID_LOADING_VALUES.map(\n String\n ).join(',')}.`\n )\n }\n if (priority && loading === 'lazy') {\n throw new Error(\n `Image with src \"${src}\" has both \"priority\" and \"loading='lazy'\" properties. Only one should be used.`\n )\n }\n if (preload && loading === 'lazy') {\n throw new Error(\n `Image with src \"${src}\" has both \"preload\" and \"loading='lazy'\" properties. Only one should be used.`\n )\n }\n if (preload && priority) {\n throw new Error(\n `Image with src \"${src}\" has both \"preload\" and \"priority\" properties. Only \"preload\" should be used.`\n )\n }\n if (\n placeholder !== 'empty' &&\n placeholder !== 'blur' &&\n !placeholder.startsWith('data:image/')\n ) {\n throw new Error(\n `Image with src \"${src}\" has invalid \"placeholder\" property \"${placeholder}\".`\n )\n }\n if (placeholder !== 'empty') {\n if (widthInt && heightInt && widthInt * heightInt < 1600) {\n warnOnce(\n `Image with src \"${src}\" is smaller than 40x40. Consider removing the \"placeholder\" property to improve performance.`\n )\n }\n }\n if (\n qualityInt &&\n config.qualities &&\n !config.qualities.includes(qualityInt)\n ) {\n warnOnce(\n `Image with src \"${src}\" is using quality \"${qualityInt}\" which is not configured in images.qualities [${config.qualities.join(', ')}]. Please update your config to [${[...config.qualities, qualityInt].sort().join(', ')}].` +\n `\\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-qualities`\n )\n }\n if (placeholder === 'blur' && !blurDataURL) {\n const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader\n\n throw new Error(\n `Image with src \"${src}\" has \"placeholder='blur'\" property but is missing the \"blurDataURL\" property.\n Possible solutions:\n - Add a \"blurDataURL\" property, the contents should be a small Data URL to represent the image\n - Change the \"src\" property to a static import with one of the supported file types: ${VALID_BLUR_EXT.join(\n ','\n )} (animated images not supported)\n - Remove the \"placeholder\" property, effectively no blur effect\n Read more: https://nextjs.org/docs/messages/placeholder-blur-data-url`\n )\n }\n if ('ref' in rest) {\n warnOnce(\n `Image with src \"${src}\" is using unsupported \"ref\" property. Consider using the \"onLoad\" property instead.`\n )\n }\n\n if (!unoptimized && !isDefaultLoader) {\n const urlStr = loader({\n config,\n src,\n width: widthInt || 400,\n quality: qualityInt || 75,\n })\n let url: URL | undefined\n try {\n url = new URL(urlStr)\n } catch (err) {}\n if (urlStr === src || (url && url.pathname === src && !url.search)) {\n warnOnce(\n `Image with src \"${src}\" has a \"loader\" property that does not implement width. Please implement it or use the \"unoptimized\" property instead.` +\n `\\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader-width`\n )\n }\n }\n\n if (onLoadingComplete) {\n warnOnce(\n `Image with src \"${src}\" is using deprecated \"onLoadingComplete\" property. Please use the \"onLoad\" property instead.`\n )\n }\n\n for (const [legacyKey, legacyValue] of Object.entries({\n layout,\n objectFit,\n objectPosition,\n lazyBoundary,\n lazyRoot,\n })) {\n if (legacyValue) {\n warnOnce(\n `Image with src \"${src}\" has legacy prop \"${legacyKey}\". Did you forget to run the codemod?` +\n `\\nRead more: https://nextjs.org/docs/messages/next-image-upgrade-to-13`\n )\n }\n }\n\n if (\n typeof window !== 'undefined' &&\n !perfObserver &&\n window.PerformanceObserver\n ) {\n perfObserver = new PerformanceObserver((entryList) => {\n for (const entry of entryList.getEntries()) {\n // @ts-ignore - missing \"LargestContentfulPaint\" class with \"element\" prop\n const imgSrc = entry?.element?.src || ''\n const lcpImage = allImgs.get(imgSrc)\n if (\n lcpImage &&\n lcpImage.loading === 'lazy' &&\n lcpImage.placeholder === 'empty' &&\n !lcpImage.src.startsWith('data:') &&\n !lcpImage.src.startsWith('blob:')\n ) {\n // https://web.dev/lcp/#measure-lcp-in-javascript\n warnOnce(\n `Image with src \"${lcpImage.src}\" was detected as the Largest Contentful Paint (LCP). Please add the \\`loading=\"eager\"\\` property if this image is above the fold.` +\n `\\nRead more: https://nextjs.org/docs/app/api-reference/components/image#loading`\n )\n }\n }\n })\n try {\n perfObserver.observe({\n type: 'largest-contentful-paint',\n buffered: true,\n })\n } catch (err) {\n // Log error but don't crash the app\n console.error(err)\n }\n }\n }\n const imgStyle = Object.assign(\n fill\n ? {\n position: 'absolute',\n height: '100%',\n width: '100%',\n left: 0,\n top: 0,\n right: 0,\n bottom: 0,\n objectFit,\n objectPosition,\n }\n : {},\n showAltText ? {} : { color: 'transparent' },\n style\n )\n\n const backgroundImage =\n !blurComplete && placeholder !== 'empty'\n ? placeholder === 'blur'\n ? `url(\"data:image/svg+xml;charset=utf-8,${getImageBlurSvg({\n widthInt,\n heightInt,\n blurWidth,\n blurHeight,\n blurDataURL: blurDataURL || '', // assume not undefined\n objectFit: imgStyle.objectFit,\n })}\")`\n : `url(\"${placeholder}\")` // assume `data:image/`\n : null\n\n const backgroundSize = !INVALID_BACKGROUND_SIZE_VALUES.includes(\n imgStyle.objectFit\n )\n ? imgStyle.objectFit\n : imgStyle.objectFit === 'fill'\n ? '100% 100%' // the background-size equivalent of `fill`\n : 'cover'\n\n let placeholderStyle: PlaceholderStyle = backgroundImage\n ? {\n backgroundSize,\n backgroundPosition: imgStyle.objectPosition || '50% 50%',\n backgroundRepeat: 'no-repeat',\n backgroundImage,\n }\n : {}\n\n if (process.env.NODE_ENV === 'development') {\n if (\n placeholderStyle.backgroundImage &&\n placeholder === 'blur' &&\n blurDataURL?.startsWith('/')\n ) {\n // During `next dev`, we don't want to generate blur placeholders with webpack\n // because it can delay starting the dev server. Instead, `next-image-loader.js`\n // will inline a special url to lazily generate the blur placeholder at request time.\n placeholderStyle.backgroundImage = `url(\"${blurDataURL}\")`\n }\n }\n\n const imgAttributes = generateImgAttrs({\n config,\n src,\n unoptimized,\n width: widthInt,\n quality: qualityInt,\n sizes,\n loader,\n })\n\n const loadingFinal = isLazy ? 'lazy' : loading\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof window !== 'undefined') {\n let fullUrl: URL\n try {\n fullUrl = new URL(imgAttributes.src)\n } catch (e) {\n fullUrl = new URL(imgAttributes.src, window.location.href)\n }\n allImgs.set(fullUrl.href, { src, loading: loadingFinal, placeholder })\n }\n }\n\n const props: ImgProps = {\n ...rest,\n loading: loadingFinal,\n fetchPriority,\n width: widthInt,\n height: heightInt,\n decoding,\n className,\n style: { ...imgStyle, ...placeholderStyle },\n sizes: imgAttributes.sizes,\n srcSet: imgAttributes.srcSet,\n src: overrideSrc || imgAttributes.src,\n }\n const meta = { unoptimized, preload: preload || priority, placeholder, fill }\n return { props, meta }\n}\n"],"names":["getImgProps","VALID_LOADING_VALUES","undefined","INVALID_BACKGROUND_SIZE_VALUES","isStaticRequire","src","default","isStaticImageData","isStaticImport","allImgs","Map","perfObserver","getInt","x","Number","isFinite","NaN","test","parseInt","getWidths","deviceSizes","allSizes","width","sizes","viewportWidthRe","percentSizes","match","exec","push","length","smallestRatio","Math","min","widths","filter","s","kind","Set","map","w","find","p","generateImgAttrs","config","unoptimized","quality","loader","startsWith","deploymentId","getDeploymentId","includes","getAssetToken","qIndex","indexOf","params","URLSearchParams","slice","srcDpl","get","append","toString","srcSet","last","i","join","priority","preload","loading","className","height","fill","style","overrideSrc","onLoad","onLoadingComplete","placeholder","blurDataURL","fetchPriority","decoding","layout","objectFit","objectPosition","lazyBoundary","lazyRoot","rest","_state","imgConf","showAltText","blurComplete","defaultLoader","Error","isDefaultLoader","customImageLoader","obj","_","opts","layoutToStyle","intrinsic","maxWidth","responsive","layoutToSizes","layoutStyle","layoutSizes","staticSrc","widthInt","heightInt","blurWidth","blurHeight","staticImageData","JSON","stringify","ratio","round","isLazy","dangerouslyAllowSVG","split","endsWith","qualityInt","process","env","NODE_ENV","warnOnce","require","output","position","isNaN","String","qualities","sort","VALID_BLUR_EXT","urlStr","url","URL","err","pathname","search","legacyKey","legacyValue","Object","entries","window","PerformanceObserver","entryList","entry","getEntries","imgSrc","element","lcpImage","observe","type","buffered","console","error","imgStyle","assign","left","top","right","bottom","color","backgroundImage","getImageBlurSvg","backgroundSize","placeholderStyle","backgroundPosition","backgroundRepeat","imgAttributes","loadingFinal","fullUrl","e","location","href","set","props","meta"],"mappings":";;;;+BAyRgBA;;;eAAAA;;;8BAzR+B;8BACf;AAoFhC,MAAMC,uBAAuB;IAAC;IAAQ;IAASC;CAAU;AAEzD,8DAA8D;AAC9D,MAAMC,iCAAiC;IACrC;IACA;IACA;IACA;IACAD;CACD;AAyBD,SAASE,gBACPC,GAAoC;IAEpC,OAAO,AA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F;IAEA,MAAMkG,QAAkB;QACtB,GAAGzF,IAAI;QACPjB,SAASoG;QACT1F;QACAvD,OAAOkF;QACPnC,QAAQoC;QACR3B;QACAV;QACAG,OAAO;YAAE,GAAGkF,QAAQ;YAAE,GAAGU,gBAAgB;QAAC;QAC1C5I,OAAO+I,cAAc/I,KAAK;QAC1BsC,QAAQyG,cAAczG,MAAM;QAC5BxD,KAAKmE,eAAe8F,cAAcjK,GAAG;IACvC;IACA,MAAMyK,OAAO;QAAElI;QAAasB,SAASA,WAAWD;QAAUU;QAAaL;IAAK;IAC5E,OAAO;QAAEuG;QAAOC;IAAK;AACvB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-rspack.d.ts b/e-commerce/node_modules/next/dist/shared/lib/get-rspack.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..277687a8b23d00c5c598837447af2d0445028c25 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-rspack.d.ts @@ -0,0 +1 @@ +export declare function getRspackCore(): any; diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-rspack.js b/e-commerce/node_modules/next/dist/shared/lib/get-rspack.js new file mode 100644 index 0000000000000000000000000000000000000000..01b8daba7a722985f5444eca4e0ce6ebc0a85aed --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-rspack.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getRspackCore", { + enumerable: true, + get: function() { + return getRspackCore; + } +}); +const _log = require("../../build/output/log"); +function getRspackCore() { + warnRspack(); + try { + // eslint-disable-next-line @next/internal/typechecked-require + return require('next-rspack/rspack-core'); + } catch (e) { + if (e instanceof Error && 'code' in e && e.code === 'MODULE_NOT_FOUND') { + throw new Error('@rspack/core is not available. Please make sure `next-rspack` is correctly installed.'); + } + throw e; + } +} +function warnRspack() { + if (process.env.__NEXT_TEST_MODE) { + return; + } + (0, _log.warnOnce)(`\`next-rspack\` is currently experimental. It's not an official Next.js plugin, and is supported by the Rspack team in partnership with Next.js. Help improve Next.js and Rspack by providing feedback at https://github.com/vercel/next.js/discussions/77800`); +} + +//# sourceMappingURL=get-rspack.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-rspack.js.map b/e-commerce/node_modules/next/dist/shared/lib/get-rspack.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e13e31cb5be16af1d020fd5cb63ac6d99122ce4c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-rspack.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/get-rspack.ts"],"sourcesContent":["import { warnOnce } from '../../build/output/log'\n\nexport function getRspackCore() {\n warnRspack()\n try {\n // eslint-disable-next-line @next/internal/typechecked-require\n return require('next-rspack/rspack-core')\n } catch (e) {\n if (e instanceof Error && 'code' in e && e.code === 'MODULE_NOT_FOUND') {\n throw new Error(\n '@rspack/core is not available. Please make sure `next-rspack` is correctly installed.'\n )\n }\n\n throw e\n }\n}\n\nfunction warnRspack() {\n if (process.env.__NEXT_TEST_MODE) {\n return\n }\n warnOnce(\n `\\`next-rspack\\` is currently experimental. It's not an official Next.js plugin, and is supported by the Rspack team in partnership with Next.js. Help improve Next.js and Rspack by providing feedback at https://github.com/vercel/next.js/discussions/77800`\n )\n}\n"],"names":["getRspackCore","warnRspack","require","e","Error","code","process","env","__NEXT_TEST_MODE","warnOnce"],"mappings":";;;;+BAEgBA;;;eAAAA;;;qBAFS;AAElB,SAASA;IACdC;IACA,IAAI;QACF,8DAA8D;QAC9D,OAAOC,QAAQ;IACjB,EAAE,OAAOC,GAAG;QACV,IAAIA,aAAaC,SAAS,UAAUD,KAAKA,EAAEE,IAAI,KAAK,oBAAoB;YACtE,MAAM,IAAID,MACR;QAEJ;QAEA,MAAMD;IACR;AACF;AAEA,SAASF;IACP,IAAIK,QAAQC,GAAG,CAACC,gBAAgB,EAAE;QAChC;IACF;IACAC,IAAAA,aAAQ,EACN,CAAC,6PAA6P,CAAC;AAEnQ","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-webpack-bundler.d.ts b/e-commerce/node_modules/next/dist/shared/lib/get-webpack-bundler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..525be519f4420a2189d44d906b2d76eb67623583 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-webpack-bundler.d.ts @@ -0,0 +1,8 @@ +import { webpack } from 'next/dist/compiled/webpack/webpack'; +/** + * Depending on if Rspack is active or not, returns the appropriate set of + * webpack-compatible api. + * + * @returns webpack bundler + */ +export default function getWebpackBundler(): typeof webpack; diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-webpack-bundler.js b/e-commerce/node_modules/next/dist/shared/lib/get-webpack-bundler.js new file mode 100644 index 0000000000000000000000000000000000000000..00a6bb28e0bc8f5b10463bf74b881254dbf12d96 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-webpack-bundler.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, /** + * Depending on if Rspack is active or not, returns the appropriate set of + * webpack-compatible api. + * + * @returns webpack bundler + */ "default", { + enumerable: true, + get: function() { + return getWebpackBundler; + } +}); +const _webpack = require("next/dist/compiled/webpack/webpack"); +const _getrspack = require("./get-rspack"); +function getWebpackBundler() { + return process.env.NEXT_RSPACK ? (0, _getrspack.getRspackCore)() : _webpack.webpack; +} + +//# sourceMappingURL=get-webpack-bundler.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/get-webpack-bundler.js.map b/e-commerce/node_modules/next/dist/shared/lib/get-webpack-bundler.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b89f7626a6e8c5ab21bf0723e5b3c5281842aa6e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/get-webpack-bundler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/get-webpack-bundler.ts"],"sourcesContent":["import { webpack } from 'next/dist/compiled/webpack/webpack'\nimport { getRspackCore } from './get-rspack'\n\n/**\n * Depending on if Rspack is active or not, returns the appropriate set of\n * webpack-compatible api.\n *\n * @returns webpack bundler\n */\nexport default function getWebpackBundler(): typeof webpack {\n return process.env.NEXT_RSPACK ? getRspackCore() : webpack\n}\n"],"names":["getWebpackBundler","process","env","NEXT_RSPACK","getRspackCore","webpack"],"mappings":";;;;+BAGA;;;;;CAKC,GACD;;;eAAwBA;;;yBATA;2BACM;AAQf,SAASA;IACtB,OAAOC,QAAQC,GAAG,CAACC,WAAW,GAAGC,IAAAA,wBAAa,MAAKC,gBAAO;AAC5D","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/hash.d.ts b/e-commerce/node_modules/next/dist/shared/lib/hash.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6eb07b7306206602fae481eace13b259a544b3d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/hash.d.ts @@ -0,0 +1,2 @@ +export declare function djb2Hash(str: string): number; +export declare function hexHash(str: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/hash.js b/e-commerce/node_modules/next/dist/shared/lib/hash.js new file mode 100644 index 0000000000000000000000000000000000000000..7d806fbda71789797aae56f57dfe04f3ade7362d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/hash.js @@ -0,0 +1,42 @@ +// http://www.cse.yorku.ca/~oz/hash.html +// More specifically, 32-bit hash via djbxor +// (ref: https://gist.github.com/eplawless/52813b1d8ad9af510d85?permalink_comment_id=3367765#gistcomment-3367765) +// This is due to number type differences between rust for turbopack to js number types, +// where rust does not have easy way to repreesnt js's 53-bit float number type for the matching +// overflow behavior. This is more `correct` in terms of having canonical hash across different runtime / implementation +// as can gaurantee determinstic output from 32bit hash. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + djb2Hash: null, + hexHash: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + djb2Hash: function() { + return djb2Hash; + }, + hexHash: function() { + return hexHash; + } +}); +function djb2Hash(str) { + let hash = 5381; + for(let i = 0; i < str.length; i++){ + const char = str.charCodeAt(i); + hash = (hash << 5) + hash + char & 0xffffffff; + } + return hash >>> 0; +} +function hexHash(str) { + return djb2Hash(str).toString(36).slice(0, 5); +} + +//# sourceMappingURL=hash.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/hash.js.map b/e-commerce/node_modules/next/dist/shared/lib/hash.js.map new file mode 100644 index 0000000000000000000000000000000000000000..924401d3334ca10c6698ffc8173984d2f274ebd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/hash.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/hash.ts"],"sourcesContent":["// http://www.cse.yorku.ca/~oz/hash.html\n// More specifically, 32-bit hash via djbxor\n// (ref: https://gist.github.com/eplawless/52813b1d8ad9af510d85?permalink_comment_id=3367765#gistcomment-3367765)\n// This is due to number type differences between rust for turbopack to js number types,\n// where rust does not have easy way to repreesnt js's 53-bit float number type for the matching\n// overflow behavior. This is more `correct` in terms of having canonical hash across different runtime / implementation\n// as can gaurantee determinstic output from 32bit hash.\nexport function djb2Hash(str: string) {\n let hash = 5381\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i)\n hash = ((hash << 5) + hash + char) & 0xffffffff\n }\n return hash >>> 0\n}\n\nexport function hexHash(str: string) {\n return djb2Hash(str).toString(36).slice(0, 5)\n}\n"],"names":["djb2Hash","hexHash","str","hash","i","length","char","charCodeAt","toString","slice"],"mappings":"AAAA,wCAAwC;AACxC,4CAA4C;AAC5C,iHAAiH;AACjH,wFAAwF;AACxF,gGAAgG;AAChG,wHAAwH;AACxH,wDAAwD;;;;;;;;;;;;;;;;IACxCA,QAAQ;eAARA;;IASAC,OAAO;eAAPA;;;AATT,SAASD,SAASE,GAAW;IAClC,IAAIC,OAAO;IACX,IAAK,IAAIC,IAAI,GAAGA,IAAIF,IAAIG,MAAM,EAAED,IAAK;QACnC,MAAME,OAAOJ,IAAIK,UAAU,CAACH;QAC5BD,OAAO,AAAEA,CAAAA,QAAQ,CAAA,IAAKA,OAAOG,OAAQ;IACvC;IACA,OAAOH,SAAS;AAClB;AAEO,SAASF,QAAQC,GAAW;IACjC,OAAOF,SAASE,KAAKM,QAAQ,CAAC,IAAIC,KAAK,CAAC,GAAG;AAC7C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.d.ts b/e-commerce/node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..016665a9e71246c2e97df3b9a19e4c9e301c1ccd --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.d.ts @@ -0,0 +1,10 @@ +import React from 'react'; +export declare const HeadManagerContext: React.Context<{ + updateHead?: (state: any) => void; + mountedInstances?: any; + updateScripts?: (state: any) => void; + scripts?: any; + getIsSsr?: () => boolean; + appDir?: boolean; + nonce?: string; +}>; diff --git a/e-commerce/node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.js b/e-commerce/node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..ba50b232d726d14afa351a516ef01215d10e2cbb --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "HeadManagerContext", { + enumerable: true, + get: function() { + return HeadManagerContext; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _react = /*#__PURE__*/ _interop_require_default._(require("react")); +const HeadManagerContext = _react.default.createContext({}); +if (process.env.NODE_ENV !== 'production') { + HeadManagerContext.displayName = 'HeadManagerContext'; +} + +//# sourceMappingURL=head-manager-context.shared-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.js.map b/e-commerce/node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3fc94cc0dd8f3d53b571d586192639ce19e8c67d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/head-manager-context.shared-runtime.ts"],"sourcesContent":["import React from 'react'\n\nexport const HeadManagerContext: React.Context<{\n updateHead?: (state: any) => void\n mountedInstances?: any\n updateScripts?: (state: any) => void\n scripts?: any\n getIsSsr?: () => boolean\n\n // Used in app directory, to render script tags as server components.\n appDir?: boolean\n nonce?: string\n}> = React.createContext({})\n\nif (process.env.NODE_ENV !== 'production') {\n HeadManagerContext.displayName = 'HeadManagerContext'\n}\n"],"names":["HeadManagerContext","React","createContext","process","env","NODE_ENV","displayName"],"mappings":";;;;+BAEaA;;;eAAAA;;;;gEAFK;AAEX,MAAMA,qBAURC,cAAK,CAACC,aAAa,CAAC,CAAC;AAE1B,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCL,mBAAmBM,WAAW,GAAG;AACnC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/head.d.ts b/e-commerce/node_modules/next/dist/shared/lib/head.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d5de196a5e375d150be07429c3f24e5bf4878ac0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/head.d.ts @@ -0,0 +1,10 @@ +import React, { type JSX } from 'react'; +export declare function defaultHead(): JSX.Element[]; +/** + * This component injects elements to `` of your page. + * To avoid duplicated `tags` in `` you can use the `key` property, which will make sure every tag is only rendered once. + */ +declare function Head({ children }: { + children: React.ReactNode; +}): JSX.Element; +export default Head; diff --git a/e-commerce/node_modules/next/dist/shared/lib/head.js b/e-commerce/node_modules/next/dist/shared/lib/head.js new file mode 100644 index 0000000000000000000000000000000000000000..410a433cba4a2d6c282b09768ffc9bdfa06611b1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/head.js @@ -0,0 +1,164 @@ +'use client'; +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + default: null, + defaultHead: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + default: function() { + return _default; + }, + defaultHead: function() { + return defaultHead; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"); +const _jsxruntime = require("react/jsx-runtime"); +const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react")); +const _sideeffect = /*#__PURE__*/ _interop_require_default._(require("./side-effect")); +const _headmanagercontextsharedruntime = require("./head-manager-context.shared-runtime"); +function defaultHead() { + const head = [ + /*#__PURE__*/ (0, _jsxruntime.jsx)("meta", { + charSet: "utf-8" + }, "charset"), + /*#__PURE__*/ (0, _jsxruntime.jsx)("meta", { + name: "viewport", + content: "width=device-width" + }, "viewport") + ]; + return head; +} +function onlyReactElement(list, child) { + // React children can be "string" or "number" in this case we ignore them for backwards compat + if (typeof child === 'string' || typeof child === 'number') { + return list; + } + // Adds support for React.Fragment + if (child.type === _react.default.Fragment) { + return list.concat(// @ts-expect-error @types/react does not remove fragments but this could also return ReactPortal[] + _react.default.Children.toArray(child.props.children).reduce(// @ts-expect-error @types/react does not remove fragments but this could also return ReactPortal[] + (fragmentList, fragmentChild)=>{ + if (typeof fragmentChild === 'string' || typeof fragmentChild === 'number') { + return fragmentList; + } + return fragmentList.concat(fragmentChild); + }, [])); + } + return list.concat(child); +} +const METATYPES = [ + 'name', + 'httpEquiv', + 'charSet', + 'itemProp' +]; +/* + returns a function for filtering head child elements + which shouldn't be duplicated, like + Also adds support for deduplicated `key` properties +*/ function unique() { + const keys = new Set(); + const tags = new Set(); + const metaTypes = new Set(); + const metaCategories = {}; + return (h)=>{ + let isUnique = true; + let hasKey = false; + if (h.key && typeof h.key !== 'number' && h.key.indexOf('$') > 0) { + hasKey = true; + const key = h.key.slice(h.key.indexOf('$') + 1); + if (keys.has(key)) { + isUnique = false; + } else { + keys.add(key); + } + } + switch(h.type){ + case 'title': + case 'base': + if (tags.has(h.type)) { + isUnique = false; + } else { + tags.add(h.type); + } + break; + case 'meta': + for(let i = 0, len = METATYPES.length; i < len; i++){ + const metatype = METATYPES[i]; + if (!h.props.hasOwnProperty(metatype)) continue; + if (metatype === 'charSet') { + if (metaTypes.has(metatype)) { + isUnique = false; + } else { + metaTypes.add(metatype); + } + } else { + const category = h.props[metatype]; + const categories = metaCategories[metatype] || new Set(); + if ((metatype !== 'name' || !hasKey) && categories.has(category)) { + isUnique = false; + } else { + categories.add(category); + metaCategories[metatype] = categories; + } + } + } + break; + default: + break; + } + return isUnique; + }; +} +/** + * + * @param headChildrenElements List of children of <Head> + */ function reduceComponents(headChildrenElements) { + return headChildrenElements.reduce(onlyReactElement, []).reverse().concat(defaultHead().reverse()).filter(unique()).reverse().map((c, i)=>{ + const key = c.key || i; + if (process.env.NODE_ENV === 'development') { + const { warnOnce } = require('./utils/warn-once'); + // omit JSON-LD structured data snippets from the warning + if (c.type === 'script' && c.props['type'] !== 'application/ld+json') { + const srcMessage = c.props['src'] ? `<script> tag with src="${c.props['src']}"` : `inline <script>`; + warnOnce(`Do not add <script> tags using next/head (see ${srcMessage}). Use next/script instead. \nSee more info here: https://nextjs.org/docs/messages/no-script-tags-in-head-component`); + } else if (c.type === 'link' && c.props['rel'] === 'stylesheet') { + warnOnce(`Do not add stylesheets using next/head (see <link rel="stylesheet"> tag with href="${c.props['href']}"). Use Document instead. \nSee more info here: https://nextjs.org/docs/messages/no-stylesheets-in-head-component`); + } + } + return /*#__PURE__*/ _react.default.cloneElement(c, { + key + }); + }); +} +/** + * This component injects elements to `<head>` of your page. + * To avoid duplicated `tags` in `<head>` you can use the `key` property, which will make sure every tag is only rendered once. + */ function Head({ children }) { + const headManager = (0, _react.useContext)(_headmanagercontextsharedruntime.HeadManagerContext); + return /*#__PURE__*/ (0, _jsxruntime.jsx)(_sideeffect.default, { + reduceComponentsToState: reduceComponents, + headManager: headManager, + children: children + }); +} +const _default = Head; + +if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') { + Object.defineProperty(exports.default, '__esModule', { value: true }); + Object.assign(exports.default, exports); + module.exports = exports.default; +} + +//# sourceMappingURL=head.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/head.js.map b/e-commerce/node_modules/next/dist/shared/lib/head.js.map new file mode 100644 index 0000000000000000000000000000000000000000..70d51b2575fbb571241ad4518b67dd59a44faaeb --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/head.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/head.tsx"],"sourcesContent":["'use client'\n\nimport React, { useContext, type JSX } from 'react'\nimport Effect from './side-effect'\nimport { HeadManagerContext } from './head-manager-context.shared-runtime'\n\nexport function defaultHead(): JSX.Element[] {\n const head = [\n <meta charSet=\"utf-8\" key=\"charset\" />,\n <meta name=\"viewport\" content=\"width=device-width\" key=\"viewport\" />,\n ]\n return head\n}\n\nfunction onlyReactElement(\n list: Array<React.ReactElement<any>>,\n child: React.ReactElement | number | string\n): Array<React.ReactElement<any>> {\n // React children can be \"string\" or \"number\" in this case we ignore them for backwards compat\n if (typeof child === 'string' || typeof child === 'number') {\n return list\n }\n // Adds support for React.Fragment\n if (child.type === React.Fragment) {\n return list.concat(\n // @ts-expect-error @types/react does not remove fragments but this could also return ReactPortal[]\n React.Children.toArray(child.props.children).reduce(\n // @ts-expect-error @types/react does not remove fragments but this could also return ReactPortal[]\n (\n fragmentList: Array<React.ReactElement<any>>,\n fragmentChild: React.ReactElement | number | string\n ): Array<React.ReactElement<any>> => {\n if (\n typeof fragmentChild === 'string' ||\n typeof fragmentChild === 'number'\n ) {\n return fragmentList\n }\n return fragmentList.concat(fragmentChild)\n },\n []\n )\n )\n }\n return list.concat(child)\n}\n\nconst METATYPES = ['name', 'httpEquiv', 'charSet', 'itemProp']\n\n/*\n returns a function for filtering head child elements\n which shouldn't be duplicated, like <title/>\n Also adds support for deduplicated `key` properties\n*/\nfunction unique() {\n const keys = new Set()\n const tags = new Set()\n const metaTypes = new Set()\n const metaCategories: { [metatype: string]: Set<string> } = {}\n\n return (h: React.ReactElement<any>) => {\n let isUnique = true\n let hasKey = false\n\n if (h.key && typeof h.key !== 'number' && h.key.indexOf('$') > 0) {\n hasKey = true\n const key = h.key.slice(h.key.indexOf('$') + 1)\n if (keys.has(key)) {\n isUnique = false\n } else {\n keys.add(key)\n }\n }\n\n switch (h.type) {\n case 'title':\n case 'base':\n if (tags.has(h.type)) {\n isUnique = false\n } else {\n tags.add(h.type)\n }\n break\n case 'meta':\n for (let i = 0, len = METATYPES.length; i < len; i++) {\n const metatype = METATYPES[i]\n if (!h.props.hasOwnProperty(metatype)) continue\n\n if (metatype === 'charSet') {\n if (metaTypes.has(metatype)) {\n isUnique = false\n } else {\n metaTypes.add(metatype)\n }\n } else {\n const category = h.props[metatype]\n const categories = metaCategories[metatype] || new Set()\n if ((metatype !== 'name' || !hasKey) && categories.has(category)) {\n isUnique = false\n } else {\n categories.add(category)\n metaCategories[metatype] = categories\n }\n }\n }\n break\n default:\n break\n }\n\n return isUnique\n }\n}\n\n/**\n *\n * @param headChildrenElements List of children of <Head>\n */\nfunction reduceComponents(\n headChildrenElements: Array<React.ReactElement<any>>\n) {\n return headChildrenElements\n .reduce(onlyReactElement, [])\n .reverse()\n .concat(defaultHead().reverse())\n .filter(unique())\n .reverse()\n .map((c: React.ReactElement<any>, i: number) => {\n const key = c.key || i\n if (process.env.NODE_ENV === 'development') {\n const { warnOnce } =\n require('./utils/warn-once') as typeof import('./utils/warn-once')\n // omit JSON-LD structured data snippets from the warning\n if (c.type === 'script' && c.props['type'] !== 'application/ld+json') {\n const srcMessage = c.props['src']\n ? `<script> tag with src=\"${c.props['src']}\"`\n : `inline <script>`\n warnOnce(\n `Do not add <script> tags using next/head (see ${srcMessage}). Use next/script instead. \\nSee more info here: https://nextjs.org/docs/messages/no-script-tags-in-head-component`\n )\n } else if (c.type === 'link' && c.props['rel'] === 'stylesheet') {\n warnOnce(\n `Do not add stylesheets using next/head (see <link rel=\"stylesheet\"> tag with href=\"${c.props['href']}\"). Use Document instead. \\nSee more info here: https://nextjs.org/docs/messages/no-stylesheets-in-head-component`\n )\n }\n }\n return React.cloneElement(c, { key })\n })\n}\n\n/**\n * This component injects elements to `<head>` of your page.\n * To avoid duplicated `tags` in `<head>` you can use the `key` property, which will make sure every tag is only rendered once.\n */\nfunction Head({ children }: { children: React.ReactNode }) {\n const headManager = useContext(HeadManagerContext)\n return (\n <Effect\n reduceComponentsToState={reduceComponents}\n headManager={headManager}\n >\n {children}\n </Effect>\n )\n}\n\nexport default Head\n"],"names":["defaultHead","head","meta","charSet","name","content","onlyReactElement","list","child","type","React","Fragment","concat","Children","toArray","props","children","reduce","fragmentList","fragmentChild","METATYPES","unique","keys","Set","tags","metaTypes","metaCategories","h","isUnique","hasKey","key","indexOf","slice","has","add","i","len","length","metatype","hasOwnProperty","category","categories","reduceComponents","headChildrenElements","reverse","filter","map","c","process","env","NODE_ENV","warnOnce","require","srcMessage","cloneElement","Head","headManager","useContext","HeadManagerContext","Effect","reduceComponentsToState"],"mappings":"AAAA;;;;;;;;;;;;;;;;IAsKA,OAAmB;eAAnB;;IAhKgBA,WAAW;eAAXA;;;;;;iEAJ4B;qEACzB;iDACgB;AAE5B,SAASA;IACd,MAAMC,OAAO;sBACX,qBAACC;YAAKC,SAAQ;WAAY;sBAC1B,qBAACD;YAAKE,MAAK;YAAWC,SAAQ;WAAyB;KACxD;IACD,OAAOJ;AAC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EAAEhC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,GAC3C,CAAC,eAAe,CAAC;gBACrBoC,SACE,CAAC,8CAA8C,EAAEE,WAAW,mHAAmH,CAAC;YAEpL,OAAO,IAAIN,EAAEtC,IAAI,KAAK,UAAUsC,EAAEhC,KAAK,CAAC,MAAM,KAAK,cAAc;gBAC/DoC,SACE,CAAC,mFAAmF,EAAEJ,EAAEhC,KAAK,CAAC,OAAO,CAAC,iHAAiH,CAAC;YAE5N;QACF;QACA,qBAAOL,cAAK,CAAC4C,YAAY,CAACP,GAAG;YAAEjB;QAAI;IACrC;AACJ;AAEA;;;CAGC,GACD,SAASyB,KAAK,EAAEvC,QAAQ,EAAiC;IACvD,MAAMwC,cAAcC,IAAAA,iBAAU,EAACC,mDAAkB;IACjD,qBACE,qBAACC,mBAAM;QACLC,yBAAyBlB;QACzBc,aAAaA;kBAEZxC;;AAGP;MAEA,WAAeuC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.d.ts b/e-commerce/node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab5d12c65535b3a2f3868c6e35c50deb5470bcef --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.d.ts @@ -0,0 +1,20 @@ +import type { Params } from '../../server/request/params'; +import { ReadonlyURLSearchParams } from '../../client/components/readonly-url-search-params'; +export declare const SearchParamsContext: import("react").Context<URLSearchParams | null>; +export declare const PathnameContext: import("react").Context<string | null>; +export declare const PathParamsContext: import("react").Context<Params | null>; +export type InstrumentedPromise<T> = Promise<T> & { + status: 'fulfilled'; + value: T; + displayName: string; +}; +export type NavigationPromises = { + pathname: InstrumentedPromise<string>; + searchParams: InstrumentedPromise<ReadonlyURLSearchParams>; + params: InstrumentedPromise<Params>; + selectedLayoutSegmentPromises?: Map<string, InstrumentedPromise<string | null>>; + selectedLayoutSegmentsPromises?: Map<string, InstrumentedPromise<string[]>>; +}; +export declare const NavigationPromisesContext: import("react").Context<NavigationPromises | null>; +export declare function createDevToolsInstrumentedPromise<T>(displayName: string, value: T): InstrumentedPromise<T>; +export { ReadonlyURLSearchParams }; diff --git a/e-commerce/node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.js b/e-commerce/node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..0f4990725faa7225ae24269e794bb4c17659ff5c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.js @@ -0,0 +1,60 @@ +'use client'; +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + NavigationPromisesContext: null, + PathParamsContext: null, + PathnameContext: null, + ReadonlyURLSearchParams: null, + SearchParamsContext: null, + createDevToolsInstrumentedPromise: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + NavigationPromisesContext: function() { + return NavigationPromisesContext; + }, + PathParamsContext: function() { + return PathParamsContext; + }, + PathnameContext: function() { + return PathnameContext; + }, + ReadonlyURLSearchParams: function() { + return _readonlyurlsearchparams.ReadonlyURLSearchParams; + }, + SearchParamsContext: function() { + return SearchParamsContext; + }, + createDevToolsInstrumentedPromise: function() { + return createDevToolsInstrumentedPromise; + } +}); +const _react = require("react"); +const _readonlyurlsearchparams = require("../../client/components/readonly-url-search-params"); +const SearchParamsContext = (0, _react.createContext)(null); +const PathnameContext = (0, _react.createContext)(null); +const PathParamsContext = (0, _react.createContext)(null); +const NavigationPromisesContext = (0, _react.createContext)(null); +function createDevToolsInstrumentedPromise(displayName, value) { + const promise = Promise.resolve(value); + promise.status = 'fulfilled'; + promise.value = value; + promise.displayName = `${displayName} (SSR)`; + return promise; +} +if (process.env.NODE_ENV !== 'production') { + SearchParamsContext.displayName = 'SearchParamsContext'; + PathnameContext.displayName = 'PathnameContext'; + PathParamsContext.displayName = 'PathParamsContext'; + NavigationPromisesContext.displayName = 'NavigationPromisesContext'; +} + +//# sourceMappingURL=hooks-client-context.shared-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.js.map b/e-commerce/node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4be7f7c5893d461b21ae76546c7a9bce1fa5c94d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/hooks-client-context.shared-runtime.ts"],"sourcesContent":["'use client'\n\nimport { createContext } from 'react'\nimport type { Params } from '../../server/request/params'\nimport { ReadonlyURLSearchParams } from '../../client/components/readonly-url-search-params'\n\nexport const SearchParamsContext = createContext<URLSearchParams | null>(null)\nexport const PathnameContext = createContext<string | null>(null)\nexport const PathParamsContext = createContext<Params | null>(null)\n\n// Dev-only context for Suspense DevTools instrumentation\n// These promises are used to track navigation hook usage in React DevTools\nexport type InstrumentedPromise<T> = Promise<T> & {\n status: 'fulfilled'\n value: T\n displayName: string\n}\n\nexport type NavigationPromises = {\n pathname: InstrumentedPromise<string>\n searchParams: InstrumentedPromise<ReadonlyURLSearchParams>\n params: InstrumentedPromise<Params>\n // Layout segment hooks (updated at each layout boundary)\n selectedLayoutSegmentPromises?: Map<\n string,\n InstrumentedPromise<string | null>\n >\n selectedLayoutSegmentsPromises?: Map<string, InstrumentedPromise<string[]>>\n}\n\nexport const NavigationPromisesContext =\n createContext<NavigationPromises | null>(null)\n\n// Creates an instrumented promise for Suspense DevTools\n// These promises are always fulfilled and exist purely for\n// tracking in React's Suspense DevTools.\nexport function createDevToolsInstrumentedPromise<T>(\n displayName: string,\n value: T\n): InstrumentedPromise<T> {\n const promise = Promise.resolve(value) as InstrumentedPromise<T>\n promise.status = 'fulfilled'\n promise.value = value\n promise.displayName = `${displayName} (SSR)`\n return promise\n}\n\nexport { ReadonlyURLSearchParams }\n\nif (process.env.NODE_ENV !== 'production') {\n SearchParamsContext.displayName = 'SearchParamsContext'\n PathnameContext.displayName = 'PathnameContext'\n PathParamsContext.displayName = 'PathParamsContext'\n NavigationPromisesContext.displayName = 'NavigationPromisesContext'\n}\n"],"names":["NavigationPromisesContext","PathParamsContext","PathnameContext","ReadonlyURLSearchParams","SearchParamsContext","createDevToolsInstrumentedPromise","createContext","displayName","value","promise","Promise","resolve","status","process","env","NODE_ENV"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;IA8BaA,yBAAyB;eAAzBA;;IAtBAC,iBAAiB;eAAjBA;;IADAC,eAAe;eAAfA;;IAwCJC,uBAAuB;eAAvBA,gDAAuB;;IAzCnBC,mBAAmB;eAAnBA;;IA8BGC,iCAAiC;eAAjCA;;;uBAlCc;yCAEU;AAEjC,MAAMD,sBAAsBE,IAAAA,oBAAa,EAAyB;AAClE,MAAMJ,kBAAkBI,IAAAA,oBAAa,EAAgB;AACrD,MAAML,oBAAoBK,IAAAA,oBAAa,EAAgB;AAsBvD,MAAMN,4BACXM,IAAAA,oBAAa,EAA4B;AAKpC,SAASD,kCACdE,WAAmB,EACnBC,KAAQ;IAER,MAAMC,UAAUC,QAAQC,OAAO,CAACH;IAChCC,QAAQG,MAAM,GAAG;IACjBH,QAAQD,KAAK,GAAGA;IAChBC,QAAQF,WAAW,GAAG,GAAGA,YAAY,MAAM,CAAC;IAC5C,OAAOE;AACT;AAIA,IAAII,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCX,oBAAoBG,WAAW,GAAG;IAClCL,gBAAgBK,WAAW,GAAG;IAC9BN,kBAAkBM,WAAW,GAAG;IAChCP,0BAA0BO,WAAW,GAAG;AAC1C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/html-context.shared-runtime.d.ts b/e-commerce/node_modules/next/dist/shared/lib/html-context.shared-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c324ea9366fb9a491181f4705175484dd27006f0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/html-context.shared-runtime.d.ts @@ -0,0 +1,57 @@ +import type { BuildManifest } from '../../server/get-page-files'; +import type { ServerRuntime } from '../../types'; +import type { NEXT_DATA } from './utils'; +import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'; +import type { DeepReadonly } from './deep-readonly'; +import { type JSX } from 'react'; +export type HtmlProps = { + __NEXT_DATA__: NEXT_DATA; + nonce?: string; + dangerousAsPath: string; + docComponentsRendered: { + Html?: boolean; + Main?: boolean; + Head?: boolean; + NextScript?: boolean; + }; + buildManifest: BuildManifest; + isDevelopment: boolean; + deploymentId: string | undefined; + dynamicImports: string[]; + /** + * This manifest is only needed for Pages dir, Production, Webpack + * @see https://github.com/vercel/next.js/pull/72959 + */ + dynamicCssManifest: Set<string>; + assetPrefix?: string; + headTags: any[]; + unstable_runtimeJS?: false; + unstable_JsPreload?: false; + assetQueryString: string; + mutableAssetQueryString: string; + /** + * Asset query string for CSS and font assets. + * See https://github.com/vercel/next.js/issues/92118. + */ + cssAssetQueryString: string; + scriptLoader: { + afterInteractive?: string[]; + beforeInteractive?: any[]; + worker?: any[]; + }; + locale?: string; + disableOptimizedLoading?: boolean; + styles?: React.ReactElement[] | Iterable<React.ReactNode>; + head?: Array<JSX.Element | null>; + crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined; + optimizeCss?: any; + nextConfigOutput?: 'standalone' | 'export'; + nextScriptWorkers?: boolean; + runtime?: ServerRuntime; + hasConcurrentFeatures?: boolean; + largePageDataBytes?: number; + nextFontManifest?: DeepReadonly<NextFontManifest>; + experimentalClientTraceMetadata?: string[]; +}; +export declare const HtmlContext: import("react").Context<HtmlProps | undefined>; +export declare function useHtmlContext(): HtmlProps; diff --git a/e-commerce/node_modules/next/dist/shared/lib/html-context.shared-runtime.js b/e-commerce/node_modules/next/dist/shared/lib/html-context.shared-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..5f4daab0aea771843ee3b04bf4285e6aaf2ece35 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/html-context.shared-runtime.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + HtmlContext: null, + useHtmlContext: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + HtmlContext: function() { + return HtmlContext; + }, + useHtmlContext: function() { + return useHtmlContext; + } +}); +const _react = require("react"); +const HtmlContext = (0, _react.createContext)(undefined); +if (process.env.NODE_ENV !== 'production') { + HtmlContext.displayName = 'HtmlContext'; +} +function useHtmlContext() { + const context = (0, _react.useContext)(HtmlContext); + if (!context) { + throw new Error(`<Html> should not be imported outside of pages/_document.\n` + 'Read more: https://nextjs.org/docs/messages/no-document-import-in-page'); + } + return context; +} + +//# sourceMappingURL=html-context.shared-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/html-context.shared-runtime.js.map b/e-commerce/node_modules/next/dist/shared/lib/html-context.shared-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..437d7a3d1458b153ba72b11be5ef7b15a5bbf493 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/html-context.shared-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/html-context.shared-runtime.ts"],"sourcesContent":["import type { BuildManifest } from '../../server/get-page-files'\nimport type { ServerRuntime } from '../../types'\nimport type { NEXT_DATA } from './utils'\nimport type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'\nimport type { DeepReadonly } from './deep-readonly'\n\nimport { createContext, useContext, type JSX } from 'react'\n\nexport type HtmlProps = {\n __NEXT_DATA__: NEXT_DATA\n nonce?: string\n dangerousAsPath: string\n docComponentsRendered: {\n Html?: boolean\n Main?: boolean\n Head?: boolean\n NextScript?: boolean\n }\n buildManifest: BuildManifest\n isDevelopment: boolean\n deploymentId: string | undefined\n dynamicImports: string[]\n /**\n * This manifest is only needed for Pages dir, Production, Webpack\n * @see https://github.com/vercel/next.js/pull/72959\n */\n dynamicCssManifest: Set<string>\n assetPrefix?: string\n headTags: any[]\n unstable_runtimeJS?: false\n unstable_JsPreload?: false\n assetQueryString: string\n mutableAssetQueryString: string\n /**\n * Asset query string for CSS and font assets.\n * See https://github.com/vercel/next.js/issues/92118.\n */\n cssAssetQueryString: string\n scriptLoader: {\n afterInteractive?: string[]\n beforeInteractive?: any[]\n worker?: any[]\n }\n locale?: string\n disableOptimizedLoading?: boolean\n styles?: React.ReactElement[] | Iterable<React.ReactNode>\n head?: Array<JSX.Element | null>\n crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined\n optimizeCss?: any\n nextConfigOutput?: 'standalone' | 'export'\n nextScriptWorkers?: boolean\n runtime?: ServerRuntime\n hasConcurrentFeatures?: boolean\n largePageDataBytes?: number\n nextFontManifest?: DeepReadonly<NextFontManifest>\n experimentalClientTraceMetadata?: string[]\n}\n\nexport const HtmlContext = createContext<HtmlProps | undefined>(undefined)\nif (process.env.NODE_ENV !== 'production') {\n HtmlContext.displayName = 'HtmlContext'\n}\n\nexport function useHtmlContext() {\n const context = useContext(HtmlContext)\n\n if (!context) {\n throw new Error(\n `<Html> should not be imported outside of pages/_document.\\n` +\n 'Read more: https://nextjs.org/docs/messages/no-document-import-in-page'\n )\n }\n\n return context\n}\n"],"names":["HtmlContext","useHtmlContext","createContext","undefined","process","env","NODE_ENV","displayName","context","useContext","Error"],"mappings":";;;;;;;;;;;;;;;IA0DaA,WAAW;eAAXA;;IAKGC,cAAc;eAAdA;;;uBAzDoC;AAoD7C,MAAMD,cAAcE,IAAAA,oBAAa,EAAwBC;AAChE,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCN,YAAYO,WAAW,GAAG;AAC5B;AAEO,SAASN;IACd,MAAMO,UAAUC,IAAAA,iBAAU,EAACT;IAE3B,IAAI,CAACQ,SAAS;QACZ,MAAM,IAAIE,MACR,CAAC,2DAA2D,CAAC,GAC3D;IAEN;IAEA,OAAOF;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/htmlescape.d.ts b/e-commerce/node_modules/next/dist/shared/lib/htmlescape.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..32122bd2f3202cfc70de34777125ea6e0c0618d4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/htmlescape.d.ts @@ -0,0 +1,3 @@ +export declare const ESCAPE_REGEX: RegExp; +export declare function htmlEscapeJsonString(str: string): string; +export declare function htmlEscapeAttributeString(str: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/htmlescape.js b/e-commerce/node_modules/next/dist/shared/lib/htmlescape.js new file mode 100644 index 0000000000000000000000000000000000000000..fb161c56f50a076c04f4cd5c4d7f7afdfe87c027 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/htmlescape.js @@ -0,0 +1,52 @@ +// This utility is based on https://github.com/zertosh/htmlescape +// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + ESCAPE_REGEX: null, + htmlEscapeAttributeString: null, + htmlEscapeJsonString: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + ESCAPE_REGEX: function() { + return ESCAPE_REGEX; + }, + htmlEscapeAttributeString: function() { + return htmlEscapeAttributeString; + }, + htmlEscapeJsonString: function() { + return htmlEscapeJsonString; + } +}); +const ESCAPE_LOOKUP = { + '&': '\\u0026', + '>': '\\u003e', + '<': '\\u003c', + '\u2028': '\\u2028', + '\u2029': '\\u2029' +}; +const ESCAPE_REGEX = /[&><\u2028\u2029]/g; +const ATTRIBUTE_ESCAPE_LOOKUP = { + '&': '&', + '"': '"', + "'": ''', + '<': '<', + '>': '>' +}; +const ATTRIBUTE_ESCAPE_REGEX = /[&"'<>]/g; +function htmlEscapeJsonString(str) { + return str.replace(ESCAPE_REGEX, (match)=>ESCAPE_LOOKUP[match]); +} +function htmlEscapeAttributeString(str) { + return str.replace(ATTRIBUTE_ESCAPE_REGEX, (match)=>ATTRIBUTE_ESCAPE_LOOKUP[match]); +} + +//# sourceMappingURL=htmlescape.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/htmlescape.js.map b/e-commerce/node_modules/next/dist/shared/lib/htmlescape.js.map new file mode 100644 index 0000000000000000000000000000000000000000..98baa8357b31afa4c1d33e7d1686a85d7259636d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/htmlescape.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/htmlescape.ts"],"sourcesContent":["// This utility is based on https://github.com/zertosh/htmlescape\n// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE\n\nconst ESCAPE_LOOKUP: { [match: string]: string } = {\n '&': '\\\\u0026',\n '>': '\\\\u003e',\n '<': '\\\\u003c',\n '\\u2028': '\\\\u2028',\n '\\u2029': '\\\\u2029',\n}\n\nexport const ESCAPE_REGEX = /[&><\\u2028\\u2029]/g\n\nconst ATTRIBUTE_ESCAPE_LOOKUP: { [match: string]: string } = {\n '&': '&',\n '\"': '"',\n \"'\": ''',\n '<': '<',\n '>': '>',\n}\n\nconst ATTRIBUTE_ESCAPE_REGEX = /[&\"'<>]/g\n\nexport function htmlEscapeJsonString(str: string): string {\n return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match])\n}\n\nexport function htmlEscapeAttributeString(str: string): string {\n return str.replace(\n ATTRIBUTE_ESCAPE_REGEX,\n (match) => ATTRIBUTE_ESCAPE_LOOKUP[match]\n )\n}\n"],"names":["ESCAPE_REGEX","htmlEscapeAttributeString","htmlEscapeJsonString","ESCAPE_LOOKUP","ATTRIBUTE_ESCAPE_LOOKUP","ATTRIBUTE_ESCAPE_REGEX","str","replace","match"],"mappings":"AAAA,iEAAiE;AACjE,uGAAuG;;;;;;;;;;;;;;;;;IAU1FA,YAAY;eAAZA;;IAgBGC,yBAAyB;eAAzBA;;IAJAC,oBAAoB;eAApBA;;;AApBhB,MAAMC,gBAA6C;IACjD,KAAK;IACL,KAAK;IACL,KAAK;IACL,UAAU;IACV,UAAU;AACZ;AAEO,MAAMH,eAAe;AAE5B,MAAMI,0BAAuD;IAC3D,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;AACP;AAEA,MAAMC,yBAAyB;AAExB,SAASH,qBAAqBI,GAAW;IAC9C,OAAOA,IAAIC,OAAO,CAACP,cAAc,CAACQ,QAAUL,aAAa,CAACK,MAAM;AAClE;AAEO,SAASP,0BAA0BK,GAAW;IACnD,OAAOA,IAAIC,OAAO,CAChBF,wBACA,CAACG,QAAUJ,uBAAuB,CAACI,MAAM;AAE7C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/i18n/detect-domain-locale.d.ts b/e-commerce/node_modules/next/dist/shared/lib/i18n/detect-domain-locale.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..df711f625b71e5efaa8ce907acc501111432c641 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/i18n/detect-domain-locale.d.ts @@ -0,0 +1,2 @@ +import type { DomainLocale } from '../../../server/config-shared'; +export declare function detectDomainLocale(domainItems?: readonly DomainLocale[], hostname?: string, detectedLocale?: string): DomainLocale | undefined; diff --git a/e-commerce/node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js b/e-commerce/node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js new file mode 100644 index 0000000000000000000000000000000000000000..67071ed782da400308f11b2b671f46417984f05d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "detectDomainLocale", { + enumerable: true, + get: function() { + return detectDomainLocale; + } +}); +function detectDomainLocale(domainItems, hostname, detectedLocale) { + if (!domainItems) return; + if (detectedLocale) { + detectedLocale = detectedLocale.toLowerCase(); + } + for (const item of domainItems){ + // remove port if present + const domainHostname = item.domain?.split(':', 1)[0].toLowerCase(); + if (hostname === domainHostname || detectedLocale === item.defaultLocale.toLowerCase() || item.locales?.some((locale)=>locale.toLowerCase() === detectedLocale)) { + return item; + } + } +} + +//# sourceMappingURL=detect-domain-locale.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js.map b/e-commerce/node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e966029ae3b57113cf4321cacdf4c47fd38afd71 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/i18n/detect-domain-locale.ts"],"sourcesContent":["import type { DomainLocale } from '../../../server/config-shared'\n\nexport function detectDomainLocale(\n domainItems?: readonly DomainLocale[],\n hostname?: string,\n detectedLocale?: string\n) {\n if (!domainItems) return\n\n if (detectedLocale) {\n detectedLocale = detectedLocale.toLowerCase()\n }\n\n for (const item of domainItems) {\n // remove port if present\n const domainHostname = item.domain?.split(':', 1)[0].toLowerCase()\n if (\n hostname === domainHostname ||\n detectedLocale === item.defaultLocale.toLowerCase() ||\n item.locales?.some((locale) => locale.toLowerCase() === detectedLocale)\n ) {\n return item\n }\n }\n}\n"],"names":["detectDomainLocale","domainItems","hostname","detectedLocale","toLowerCase","item","domainHostname","domain","split","defaultLocale","locales","some","locale"],"mappings":";;;;+BAEgBA;;;eAAAA;;;AAAT,SAASA,mBACdC,WAAqC,EACrCC,QAAiB,EACjBC,cAAuB;IAEvB,IAAI,CAACF,aAAa;IAElB,IAAIE,gBAAgB;QAClBA,iBAAiBA,eAAeC,WAAW;IAC7C;IAEA,KAAK,MAAMC,QAAQJ,YAAa;QAC9B,yBAAyB;QACzB,MAAMK,iBAAiBD,KAAKE,MAAM,EAAEC,MAAM,KAAK,EAAE,CAAC,EAAE,CAACJ;QACrD,IACEF,aAAaI,kBACbH,mBAAmBE,KAAKI,aAAa,CAACL,WAAW,MACjDC,KAAKK,OAAO,EAAEC,KAAK,CAACC,SAAWA,OAAOR,WAAW,OAAOD,iBACxD;YACA,OAAOE;QACT;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/i18n/get-locale-redirect.d.ts b/e-commerce/node_modules/next/dist/shared/lib/i18n/get-locale-redirect.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..22f5ab34113404e67d63b056a435b7d14cfce866 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/i18n/get-locale-redirect.d.ts @@ -0,0 +1,21 @@ +import type { DomainLocale } from '../../../server/config'; +import type { I18NConfig } from '../../../server/config-shared'; +interface Options { + defaultLocale: string; + domainLocale?: DomainLocale; + headers?: { + [key: string]: string | string[] | undefined; + }; + nextConfig: { + basePath?: string; + i18n?: I18NConfig | null; + trailingSlash?: boolean; + }; + pathLocale?: string; + urlParsed: { + hostname?: string | null; + pathname: string; + }; +} +export declare function getLocaleRedirect({ defaultLocale, domainLocale, pathLocale, headers, nextConfig, urlParsed, }: Options): string | undefined; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/i18n/get-locale-redirect.js b/e-commerce/node_modules/next/dist/shared/lib/i18n/get-locale-redirect.js new file mode 100644 index 0000000000000000000000000000000000000000..8ddd1f424e712dc706828ef50e8b8df4c9f9eeb1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/i18n/get-locale-redirect.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getLocaleRedirect", { + enumerable: true, + get: function() { + return getLocaleRedirect; + } +}); +const _acceptheader = require("../../../server/accept-header"); +const _denormalizepagepath = require("../page-path/denormalize-page-path"); +const _detectdomainlocale = require("./detect-domain-locale"); +const _formaturl = require("../router/utils/format-url"); +const _getcookieparser = require("../../../server/api-utils/get-cookie-parser"); +function getLocaleFromCookie(i18n, headers = {}) { + const nextLocale = (0, _getcookieparser.getCookieParser)(headers || {})()?.NEXT_LOCALE?.toLowerCase(); + return nextLocale ? i18n.locales.find((locale)=>nextLocale === locale.toLowerCase()) : undefined; +} +function detectLocale({ i18n, headers, domainLocale, preferredLocale, pathLocale }) { + return pathLocale || domainLocale?.defaultLocale || getLocaleFromCookie(i18n, headers) || preferredLocale || i18n.defaultLocale; +} +function getAcceptPreferredLocale(i18n, headers) { + if (headers?.['accept-language'] && !Array.isArray(headers['accept-language'])) { + try { + return (0, _acceptheader.acceptLanguage)(headers['accept-language'], i18n.locales); + } catch (err) {} + } +} +function getLocaleRedirect({ defaultLocale, domainLocale, pathLocale, headers, nextConfig, urlParsed }) { + if (nextConfig.i18n && nextConfig.i18n.localeDetection !== false && (0, _denormalizepagepath.denormalizePagePath)(urlParsed.pathname) === '/') { + const preferredLocale = getAcceptPreferredLocale(nextConfig.i18n, headers); + const detectedLocale = detectLocale({ + i18n: nextConfig.i18n, + preferredLocale, + headers, + pathLocale, + domainLocale + }); + const preferredDomain = (0, _detectdomainlocale.detectDomainLocale)(nextConfig.i18n.domains, undefined, preferredLocale); + if (domainLocale && preferredDomain) { + const isPDomain = preferredDomain.domain === domainLocale.domain; + const isPLocale = preferredDomain.defaultLocale === preferredLocale; + if (!isPDomain || !isPLocale) { + const scheme = `http${preferredDomain.http ? '' : 's'}`; + const rlocale = isPLocale ? '' : preferredLocale; + return `${scheme}://${preferredDomain.domain}/${rlocale}`; + } + } + if (detectedLocale.toLowerCase() !== defaultLocale.toLowerCase()) { + return (0, _formaturl.formatUrl)({ + ...urlParsed, + pathname: `${nextConfig.basePath || ''}/${detectedLocale}${nextConfig.trailingSlash ? '/' : ''}` + }); + } + } +} + +//# sourceMappingURL=get-locale-redirect.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/i18n/get-locale-redirect.js.map b/e-commerce/node_modules/next/dist/shared/lib/i18n/get-locale-redirect.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7d7c8e7858c0bb12fddc862e7ddbeaa775ce70c5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/i18n/get-locale-redirect.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/i18n/get-locale-redirect.ts"],"sourcesContent":["import type { DomainLocale } from '../../../server/config'\nimport type { I18NConfig } from '../../../server/config-shared'\nimport { acceptLanguage } from '../../../server/accept-header'\nimport { denormalizePagePath } from '../page-path/denormalize-page-path'\nimport { detectDomainLocale } from './detect-domain-locale'\nimport { formatUrl } from '../router/utils/format-url'\nimport { getCookieParser } from '../../../server/api-utils/get-cookie-parser'\n\ninterface Options {\n defaultLocale: string\n domainLocale?: DomainLocale\n headers?: { [key: string]: string | string[] | undefined }\n nextConfig: {\n basePath?: string\n i18n?: I18NConfig | null\n trailingSlash?: boolean\n }\n pathLocale?: string\n urlParsed: { hostname?: string | null; pathname: string }\n}\n\nfunction getLocaleFromCookie(\n i18n: I18NConfig,\n headers: { [key: string]: string | string[] | undefined } = {}\n) {\n const nextLocale = getCookieParser(\n headers || {}\n )()?.NEXT_LOCALE?.toLowerCase()\n return nextLocale\n ? i18n.locales.find((locale) => nextLocale === locale.toLowerCase())\n : undefined\n}\n\nfunction detectLocale({\n i18n,\n headers,\n domainLocale,\n preferredLocale,\n pathLocale,\n}: {\n i18n: I18NConfig\n preferredLocale?: string\n headers?: { [key: string]: string | string[] | undefined }\n domainLocale?: DomainLocale\n pathLocale?: string\n}) {\n return (\n pathLocale ||\n domainLocale?.defaultLocale ||\n getLocaleFromCookie(i18n, headers) ||\n preferredLocale ||\n i18n.defaultLocale\n )\n}\n\nfunction getAcceptPreferredLocale(\n i18n: I18NConfig,\n headers?: { [key: string]: string | string[] | undefined }\n) {\n if (\n headers?.['accept-language'] &&\n !Array.isArray(headers['accept-language'])\n ) {\n try {\n return acceptLanguage(headers['accept-language'], i18n.locales)\n } catch (err) {}\n }\n}\n\nexport function getLocaleRedirect({\n defaultLocale,\n domainLocale,\n pathLocale,\n headers,\n nextConfig,\n urlParsed,\n}: Options) {\n if (\n nextConfig.i18n &&\n nextConfig.i18n.localeDetection !== false &&\n denormalizePagePath(urlParsed.pathname) === '/'\n ) {\n const preferredLocale = getAcceptPreferredLocale(nextConfig.i18n, headers)\n const detectedLocale = detectLocale({\n i18n: nextConfig.i18n,\n preferredLocale,\n headers,\n pathLocale,\n domainLocale,\n })\n\n const preferredDomain = detectDomainLocale(\n nextConfig.i18n.domains,\n undefined,\n preferredLocale\n )\n\n if (domainLocale && preferredDomain) {\n const isPDomain = preferredDomain.domain === domainLocale.domain\n const isPLocale = preferredDomain.defaultLocale === preferredLocale\n if (!isPDomain || !isPLocale) {\n const scheme = `http${preferredDomain.http ? '' : 's'}`\n const rlocale = isPLocale ? '' : preferredLocale\n return `${scheme}://${preferredDomain.domain}/${rlocale}`\n }\n }\n\n if (detectedLocale.toLowerCase() !== defaultLocale.toLowerCase()) {\n return formatUrl({\n ...urlParsed,\n pathname: `${nextConfig.basePath || ''}/${detectedLocale}${\n nextConfig.trailingSlash ? '/' : ''\n }`,\n })\n }\n }\n}\n"],"names":["getLocaleRedirect","getLocaleFromCookie","i18n","headers","nextLocale","getCookieParser","NEXT_LOCALE","toLowerCase","locales","find","locale","undefined","detectLocale","domainLocale","preferredLocale","pathLocale","defaultLocale","getAcceptPreferredLocale","Array","isArray","acceptLanguage","err","nextConfig","urlParsed","localeDetection","denormalizePagePath","pathname","detectedLocale","preferredDomain","detectDomainLocale","domains","isPDomain","domain","isPLocale","scheme","http","rlocale","formatUrl","basePath","trailingSlash"],"mappings":";;;;+BAqEgBA;;;eAAAA;;;8BAnEe;qCACK;oC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L,gBAAgBZ,aAAa,KAAKF;YACpD,IAAI,CAACiB,aAAa,CAACE,WAAW;gBAC5B,MAAMC,SAAS,CAAC,IAAI,EAAEN,gBAAgBO,IAAI,GAAG,KAAK,KAAK;gBACvD,MAAMC,UAAUH,YAAY,KAAKnB;gBACjC,OAAO,GAAGoB,OAAO,GAAG,EAAEN,gBAAgBI,MAAM,CAAC,CAAC,EAAEI,SAAS;YAC3D;QACF;QAEA,IAAIT,eAAepB,WAAW,OAAOS,cAAcT,WAAW,IAAI;YAChE,OAAO8B,IAAAA,oBAAS,EAAC;gBACf,GAAGd,SAAS;gBACZG,UAAU,GAAGJ,WAAWgB,QAAQ,IAAI,GAAG,CAAC,EAAEX,iBACxCL,WAAWiB,aAAa,GAAG,MAAM,IACjC;YACJ;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/i18n/normalize-locale-path.d.ts b/e-commerce/node_modules/next/dist/shared/lib/i18n/normalize-locale-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc4b541289c8197e1ae121909b512935dd354ac8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/i18n/normalize-locale-path.d.ts @@ -0,0 +1,14 @@ +export interface PathLocale { + detectedLocale?: string; + pathname: string; +} +/** + * For a pathname that may include a locale from a list of locales, it + * removes the locale from the pathname returning it alongside with the + * detected locale. + * + * @param pathname A pathname that may include a locale. + * @param locales A list of locales. + * @returns The detected locale and pathname without locale + */ +export declare function normalizeLocalePath(pathname: string, locales?: readonly string[]): PathLocale; diff --git a/e-commerce/node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js b/e-commerce/node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js new file mode 100644 index 0000000000000000000000000000000000000000..2c120c56dccdfce1929d706f0c1f515b708d646c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "normalizeLocalePath", { + enumerable: true, + get: function() { + return normalizeLocalePath; + } +}); +/** + * A cache of lowercased locales for each list of locales. This is stored as a + * WeakMap so if the locales are garbage collected, the cache entry will be + * removed as well. + */ const cache = new WeakMap(); +function normalizeLocalePath(pathname, locales) { + // If locales is undefined, return the pathname as is. + if (!locales) return { + pathname + }; + // Get the cached lowercased locales or create a new cache entry. + let lowercasedLocales = cache.get(locales); + if (!lowercasedLocales) { + lowercasedLocales = locales.map((locale)=>locale.toLowerCase()); + cache.set(locales, lowercasedLocales); + } + let detectedLocale; + // The first segment will be empty, because it has a leading `/`. If + // there is no further segment, there is no locale (or it's the default). + const segments = pathname.split('/', 2); + // If there's no second segment (ie, the pathname is just `/`), there's no + // locale. + if (!segments[1]) return { + pathname + }; + // The second segment will contain the locale part if any. + const segment = segments[1].toLowerCase(); + // See if the segment matches one of the locales. If it doesn't, there is + // no locale (or it's the default). + const index = lowercasedLocales.indexOf(segment); + if (index < 0) return { + pathname + }; + // Return the case-sensitive locale. + detectedLocale = locales[index]; + // Remove the `/${locale}` part of the pathname. + pathname = pathname.slice(detectedLocale.length + 1) || '/'; + return { + pathname, + detectedLocale + }; +} + +//# sourceMappingURL=normalize-locale-path.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js.map b/e-commerce/node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5890f9b253d70b6891bc6d719c2cf97ae0477e02 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/i18n/normalize-locale-path.ts"],"sourcesContent":["export interface PathLocale {\n detectedLocale?: string\n pathname: string\n}\n\n/**\n * A cache of lowercased locales for each list of locales. This is stored as a\n * WeakMap so if the locales are garbage collected, the cache entry will be\n * removed as well.\n */\nconst cache = new WeakMap<readonly string[], readonly string[]>()\n\n/**\n * For a pathname that may include a locale from a list of locales, it\n * removes the locale from the pathname returning it alongside with the\n * detected locale.\n *\n * @param pathname A pathname that may include a locale.\n * @param locales A list of locales.\n * @returns The detected locale and pathname without locale\n */\nexport function normalizeLocalePath(\n pathname: string,\n locales?: readonly string[]\n): PathLocale {\n // If locales is undefined, return the pathname as is.\n if (!locales) return { pathname }\n\n // Get the cached lowercased locales or create a new cache entry.\n let lowercasedLocales = cache.get(locales)\n if (!lowercasedLocales) {\n lowercasedLocales = locales.map((locale) => locale.toLowerCase())\n cache.set(locales, lowercasedLocales)\n }\n\n let detectedLocale: string | undefined\n\n // The first segment will be empty, because it has a leading `/`. If\n // there is no further segment, there is no locale (or it's the default).\n const segments = pathname.split('/', 2)\n\n // If there's no second segment (ie, the pathname is just `/`), there's no\n // locale.\n if (!segments[1]) return { pathname }\n\n // The second segment will contain the locale part if any.\n const segment = segments[1].toLowerCase()\n\n // See if the segment matches one of the locales. If it doesn't, there is\n // no locale (or it's the default).\n const index = lowercasedLocales.indexOf(segment)\n if (index < 0) return { pathname }\n\n // Return the case-sensitive locale.\n detectedLocale = locales[index]\n\n // Remove the `/${locale}` part of the pathname.\n pathname = pathname.slice(detectedLocale.length + 1) || '/'\n\n return { pathname, detectedLocale }\n}\n"],"names":["normalizeLocalePath","cache","WeakMap","pathname","locales","lowercasedLocales","get","map","locale","toLowerCase","set","detectedLocale","segments","split","segment","index","indexOf","slice","length"],"mappings":";;;;+BAqBgBA;;;eAAAA;;;AAhBhB;;;;CAIC,GACD,MAAMC,QAAQ,IAAIC;AAWX,SAASF,oBACdG,QAAgB,EAChBC,OAA2B;IAE3B,sDAAsD;IACtD,IAAI,CAACA,SAAS,OAAO;QAAED;IAAS;IAEhC,iEAAiE;IACjE,IAAIE,oBAAoBJ,MAAMK,GAAG,CAACF;IAClC,IAAI,CAACC,mBAAmB;QACtBA,oBAAoBD,QAAQG,GAAG,CAAC,CAACC,SAAWA,OAAOC,WAAW;QAC9DR,MAAMS,GAAG,CAACN,SAASC;IACrB;IAEA,IAAIM;IAEJ,oEAAoE;IACpE,yEAAyE;IACzE,MAAMC,WAAWT,SAASU,KAAK,CAAC,KAAK;IAErC,0EAA0E;IAC1E,UAAU;IACV,IAAI,CAACD,QAAQ,CAAC,EAAE,EAAE,OAAO;QAAET;IAAS;IAEpC,0DAA0D;IAC1D,MAAMW,UAAUF,QAAQ,CAAC,EAAE,CAACH,WAAW;IAEvC,yEAAyE;IACzE,mCAAmC;IACnC,MAAMM,QAAQV,kBAAkBW,OAAO,CAACF;IACxC,IAAIC,QAAQ,GAAG,OAAO;QAAEZ;IAAS;IAEjC,oCAAoC;IACpCQ,iBAAiBP,OAAO,CAACW,MAAM;IAE/B,gDAAgD;IAChDZ,WAAWA,SAASc,KAAK,CAACN,eAAeO,MAAM,GAAG,MAAM;IAExD,OAAO;QAAEf;QAAUQ;IAAe;AACpC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-blur-svg.d.ts b/e-commerce/node_modules/next/dist/shared/lib/image-blur-svg.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ba9fe9a9cfe26959017c5bdc00d4255be593e2e2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-blur-svg.d.ts @@ -0,0 +1,11 @@ +/** + * A shared function, used on both client and server, to generate a SVG blur placeholder. + */ +export declare function getImageBlurSvg({ widthInt, heightInt, blurWidth, blurHeight, blurDataURL, objectFit, }: { + widthInt?: number; + heightInt?: number; + blurWidth?: number; + blurHeight?: number; + blurDataURL: string; + objectFit?: string; +}): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-blur-svg.js b/e-commerce/node_modules/next/dist/shared/lib/image-blur-svg.js new file mode 100644 index 0000000000000000000000000000000000000000..12638833f733fd43316f9458403eef5cf8fe6b1d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-blur-svg.js @@ -0,0 +1,22 @@ +/** + * A shared function, used on both client and server, to generate a SVG blur placeholder. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getImageBlurSvg", { + enumerable: true, + get: function() { + return getImageBlurSvg; + } +}); +function getImageBlurSvg({ widthInt, heightInt, blurWidth, blurHeight, blurDataURL, objectFit }) { + const std = 20; + const svgWidth = blurWidth ? blurWidth * 40 : widthInt; + const svgHeight = blurHeight ? blurHeight * 40 : heightInt; + const viewBox = svgWidth && svgHeight ? `viewBox='0 0 ${svgWidth} ${svgHeight}'` : ''; + const preserveAspectRatio = viewBox ? 'none' : objectFit === 'contain' ? 'xMidYMid' : objectFit === 'cover' ? 'xMidYMid slice' : 'none'; + return `%3Csvg xmlns='http://www.w3.org/2000/svg' ${viewBox}%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='${std}'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='${std}'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='${preserveAspectRatio}' style='filter: url(%23b);' href='${blurDataURL}'/%3E%3C/svg%3E`; +} + +//# sourceMappingURL=image-blur-svg.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-blur-svg.js.map b/e-commerce/node_modules/next/dist/shared/lib/image-blur-svg.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a0b3a32620da714ffba84fc632e034fb1486afde --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-blur-svg.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/image-blur-svg.ts"],"sourcesContent":["/**\n * A shared function, used on both client and server, to generate a SVG blur placeholder.\n */\nexport function getImageBlurSvg({\n widthInt,\n heightInt,\n blurWidth,\n blurHeight,\n blurDataURL,\n objectFit,\n}: {\n widthInt?: number\n heightInt?: number\n blurWidth?: number\n blurHeight?: number\n blurDataURL: string\n objectFit?: string\n}): string {\n const std = 20\n const svgWidth = blurWidth ? blurWidth * 40 : widthInt\n const svgHeight = blurHeight ? blurHeight * 40 : heightInt\n\n const viewBox =\n svgWidth && svgHeight ? `viewBox='0 0 ${svgWidth} ${svgHeight}'` : ''\n const preserveAspectRatio = viewBox\n ? 'none'\n : objectFit === 'contain'\n ? 'xMidYMid'\n : objectFit === 'cover'\n ? 'xMidYMid slice'\n : 'none'\n\n return `%3Csvg xmlns='http://www.w3.org/2000/svg' ${viewBox}%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='${std}'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='${std}'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='${preserveAspectRatio}' style='filter: url(%23b);' href='${blurDataURL}'/%3E%3C/svg%3E`\n}\n"],"names":["getImageBlurSvg","widthInt","heightInt","blurWidth","blurHeight","blurDataURL","objectFit","std","svgWidth","svgHeight","viewBox","preserveAspectRatio"],"mappings":"AAAA;;CAEC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,gBAAgB,EAC9BC,QAAQ,EACRC,SAAS,EACTC,SAAS,EACTC,UAAU,EACVC,WAAW,EACXC,SAAS,EAQV;IACC,MAAMC,MAAM;IACZ,MAAMC,WAAWL,YAAYA,YAAY,KAAKF;IAC9C,MAAMQ,YAAYL,aAAaA,aAAa,KAAKF;IAEjD,MAAMQ,UACJF,YAAYC,YAAY,CAAC,aAAa,EAAED,SAAS,CAAC,EAAEC,UAAU,CAAC,CAAC,GAAG;IACrE,MAAME,sBAAsBD,UACxB,SACAJ,cAAc,YACZ,aACAA,cAAc,UACZ,mBACA;IAER,OAAO,CAAC,0CAA0C,EAAEI,QAAQ,yFAAyF,EAAEH,IAAI,+PAA+P,EAAEA,IAAI,2FAA2F,EAAEI,oBAAoB,mCAAmC,EAAEN,YAAY,eAAe,CAAC;AACplB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-config-context.shared-runtime.d.ts b/e-commerce/node_modules/next/dist/shared/lib/image-config-context.shared-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cbc00fa5530ccfbef01e5fae97620fb619cc863c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-config-context.shared-runtime.d.ts @@ -0,0 +1,3 @@ +import React from 'react'; +import type { ImageConfigComplete } from './image-config'; +export declare const ImageConfigContext: React.Context<ImageConfigComplete>; diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-config-context.shared-runtime.js b/e-commerce/node_modules/next/dist/shared/lib/image-config-context.shared-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..649f904a513eb2ff59bab238c541630bcf7c041f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-config-context.shared-runtime.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ImageConfigContext", { + enumerable: true, + get: function() { + return ImageConfigContext; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _react = /*#__PURE__*/ _interop_require_default._(require("react")); +const _imageconfig = require("./image-config"); +const ImageConfigContext = _react.default.createContext(_imageconfig.imageConfigDefault); +if (process.env.NODE_ENV !== 'production') { + ImageConfigContext.displayName = 'ImageConfigContext'; +} + +//# sourceMappingURL=image-config-context.shared-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-config-context.shared-runtime.js.map b/e-commerce/node_modules/next/dist/shared/lib/image-config-context.shared-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3d5560ac4b586974771c0cb366b96f78cde0380f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-config-context.shared-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/image-config-context.shared-runtime.ts"],"sourcesContent":["import React from 'react'\nimport type { ImageConfigComplete } from './image-config'\nimport { imageConfigDefault } from './image-config'\n\nexport const ImageConfigContext =\n React.createContext<ImageConfigComplete>(imageConfigDefault)\n\nif (process.env.NODE_ENV !== 'production') {\n ImageConfigContext.displayName = 'ImageConfigContext'\n}\n"],"names":["ImageConfigContext","React","createContext","imageConfigDefault","process","env","NODE_ENV","displayName"],"mappings":";;;;+BAIaA;;;eAAAA;;;;gEAJK;6BAEiB;AAE5B,MAAMA,qBACXC,cAAK,CAACC,aAAa,CAAsBC,+BAAkB;AAE7D,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCN,mBAAmBO,WAAW,GAAG;AACnC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-config.d.ts b/e-commerce/node_modules/next/dist/shared/lib/image-config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f06b6927230524fae6e17eb930825c6b85d12dfe --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-config.d.ts @@ -0,0 +1,127 @@ +export declare const VALID_LOADERS: readonly ["default", "imgix", "cloudinary", "akamai", "custom"]; +export type LoaderValue = (typeof VALID_LOADERS)[number]; +export type ImageLoaderProps = { + src: string; + width: number; + quality?: number; +}; +export type ImageLoaderPropsWithConfig = ImageLoaderProps & { + config: Readonly<ImageConfig>; +}; +export type LocalPattern = { + /** + * Can be literal or wildcard. + * Single `*` matches a single path segment. + * Double `**` matches any number of path segments. + */ + pathname?: string; + /** + * Can be literal query string such as `?v=1` or + * empty string meaning no query string. + */ + search?: string; +}; +export type RemotePattern = { + /** + * Must be `http` or `https`. + */ + protocol?: 'http' | 'https'; + /** + * Can be literal or wildcard. + * Single `*` matches a single subdomain. + * Double `**` matches any number of subdomains. + */ + hostname: string; + /** + * Can be literal port such as `8080` or empty string + * meaning no port. + */ + port?: string; + /** + * Can be literal or wildcard. + * Single `*` matches a single path segment. + * Double `**` matches any number of path segments. + */ + pathname?: string; + /** + * Can be literal query string such as `?v=1` or + * empty string meaning no query string. + */ + search?: string; +}; +type ImageFormat = 'image/avif' | 'image/webp'; +/** + * Image configurations + * + * @see [Image configuration options](https://nextjs.org/docs/api-reference/next/image#configuration-options) + */ +export type ImageConfigComplete = { + /** @see [Device sizes documentation](https://nextjs.org/docs/api-reference/next/image#device-sizes) */ + deviceSizes: number[]; + /** @see [Image sizing documentation](https://nextjs.org/docs/app/building-your-application/optimizing/images#image-sizing) */ + imageSizes: number[]; + /** @see [Image loaders configuration](https://nextjs.org/docs/api-reference/next/legacy/image#loader) */ + loader: LoaderValue; + /** @see [Image loader configuration](https://nextjs.org/docs/app/api-reference/components/image#path) */ + path: string; + /** @see [Image loader configuration](https://nextjs.org/docs/api-reference/next/image#loader-configuration) */ + loaderFile: string; + /** + * @deprecated Use `remotePatterns` instead. + */ + domains: string[]; + /** @see [Disable static image import configuration](https://nextjs.org/docs/api-reference/next/image#disable-static-imports) */ + disableStaticImages: boolean; + /** @see [Cache behavior](https://nextjs.org/docs/api-reference/next/image#caching-behavior) */ + minimumCacheTTL: number; + /** @see [Acceptable formats](https://nextjs.org/docs/api-reference/next/image#acceptable-formats) */ + formats: ImageFormat[]; + /** @see [Maximum Disk Cache Size (in bytes)](https://nextjs.org/docs/api-reference/next/image#maximumdiskcachesize) */ + maximumDiskCacheSize: number | undefined; + /** @see [Maximum Redirects](https://nextjs.org/docs/api-reference/next/image#maximumredirects) */ + maximumRedirects: number; + /** @see [Maximum Response Body](https://nextjs.org/docs/api-reference/next/image#maximumresponsebody) */ + maximumResponseBody: number; + /** @see [Dangerously Allow Local IP](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-local-ip) */ + dangerouslyAllowLocalIP: boolean; + /** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */ + dangerouslyAllowSVG: boolean; + /** @see [Content Security Policy](https://nextjs.org/docs/api-reference/next/image#contentsecuritypolicy) */ + contentSecurityPolicy: string; + /** @see [Content Disposition Type](https://nextjs.org/docs/api-reference/next/image#contentdispositiontype) */ + contentDispositionType: 'inline' | 'attachment'; + /** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remotepatterns) */ + remotePatterns: Array<URL | RemotePattern>; + /** @see [Local Patterns](https://nextjs.org/docs/api-reference/next/image#localPatterns) */ + localPatterns: LocalPattern[] | undefined; + /** @see [Qualities](https://nextjs.org/docs/api-reference/next/image#qualities) */ + qualities: number[] | undefined; + /** @see [Unoptimized](https://nextjs.org/docs/api-reference/next/image#unoptimized) */ + unoptimized: boolean; + /** + * When true, the `cacheHandler` configured in next.config.js will also be used + * for caching optimized images. When false, images use the default filesystem cache. + * @see [Image Optimization Caching](https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheHandler#image-optimization-caching) + */ + customCacheHandler: boolean; +}; +export type ImageConfig = Partial<ImageConfigComplete>; +type RequiredImageConfigForRendering = Pick<ImageConfigComplete, 'deviceSizes' | 'imageSizes' | 'loader' | 'path' | 'dangerouslyAllowSVG' | 'unoptimized'>; +export type ImageConfigForRendering = RequiredImageConfigForRendering & Partial<Pick<ImageConfigComplete, 'qualities' | 'domains' | 'remotePatterns' | 'localPatterns'>> & { + output?: 'standalone' | 'export'; +}; +export type PreparedImageConfig = RequiredImageConfigForRendering & { + allSizes: number[]; + qualities: ImageConfigComplete['qualities']; + domains: ImageConfigComplete['domains'] | undefined; + remotePatterns: ImageConfigComplete['remotePatterns'] | undefined; + localPatterns: ImageConfigComplete['localPatterns']; + output: 'standalone' | 'export' | undefined; +}; +/** + * Prepare owned, sorted image options once for each env/context pair. + * Changed options require new objects because results are cached by identity. + */ +export declare function prepareImageConfig(envConfig?: ImageConfigForRendering, contextConfig?: ImageConfigComplete): PreparedImageConfig; +export declare const imageConfigDefault: ImageConfigComplete; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-config.js b/e-commerce/node_modules/next/dist/shared/lib/image-config.js new file mode 100644 index 0000000000000000000000000000000000000000..f94752711f125c5a3dd2c7396ed2705722a365d4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-config.js @@ -0,0 +1,128 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + VALID_LOADERS: null, + imageConfigDefault: null, + prepareImageConfig: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + VALID_LOADERS: function() { + return VALID_LOADERS; + }, + imageConfigDefault: function() { + return imageConfigDefault; + }, + prepareImageConfig: function() { + return prepareImageConfig; + } +}); +const VALID_LOADERS = [ + 'default', + 'imgix', + 'cloudinary', + 'akamai', + 'custom' +]; +const missingImageConfig = {}; +const preparedImageConfigs = new WeakMap(); +function prepareImageConfig(envConfig, contextConfig) { + const envKey = envConfig ?? missingImageConfig; + const contextKey = contextConfig ?? missingImageConfig; + let preparedByContext = preparedImageConfigs.get(envKey); + if (preparedByContext) { + const cached = preparedByContext.get(contextKey); + if (cached) { + return cached; + } + } + const source = envConfig || contextConfig || imageConfigDefault; + const deviceSizes = [ + ...source.deviceSizes + ].sort((a, b)=>a - b); + const imageSizes = [ + ...source.imageSizes + ]; + const prepared = { + deviceSizes, + imageSizes, + allSizes: [ + ...deviceSizes, + ...imageSizes + ].sort((a, b)=>a - b), + qualities: source.qualities === undefined ? undefined : [ + ...source.qualities + ].sort((a, b)=>a - b), + path: source.path, + loader: source.loader, + dangerouslyAllowSVG: source.dangerouslyAllowSVG, + unoptimized: source.unoptimized, + domains: source.domains, + remotePatterns: source.remotePatterns, + // The inlined browser options supply their own patterns. During SSR the + // context supplies security-sensitive patterns omitted from the inline data. + localPatterns: typeof window === 'undefined' && contextConfig !== undefined ? contextConfig.localPatterns : source.localPatterns, + output: source.output + }; + if (!preparedByContext) { + preparedByContext = new WeakMap(); + preparedImageConfigs.set(envKey, preparedByContext); + } + preparedByContext.set(contextKey, prepared); + return prepared; +} +const imageConfigDefault = { + deviceSizes: [ + 640, + 750, + 828, + 1080, + 1200, + 1920, + 2048, + 3840 + ], + imageSizes: [ + 32, + 48, + 64, + 96, + 128, + 256, + 384 + ], + path: '/_next/image', + loader: 'default', + loaderFile: '', + /** + * @deprecated Use `remotePatterns` instead to protect your application from malicious users. + */ domains: [], + disableStaticImages: false, + minimumCacheTTL: 14400, + formats: [ + 'image/webp' + ], + maximumDiskCacheSize: undefined, + maximumRedirects: 3, + maximumResponseBody: 50000000, + dangerouslyAllowLocalIP: false, + dangerouslyAllowSVG: false, + contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`, + contentDispositionType: 'attachment', + localPatterns: undefined, + remotePatterns: [], + qualities: [ + 75 + ], + unoptimized: false, + customCacheHandler: false +}; + +//# sourceMappingURL=image-config.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-config.js.map b/e-commerce/node_modules/next/dist/shared/lib/image-config.js.map new file mode 100644 index 0000000000000000000000000000000000000000..058a0588cd7c06cc8e777e3c5327e1b88fb154e7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-config.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/image-config.ts"],"sourcesContent":["export const VALID_LOADERS = [\n 'default',\n 'imgix',\n 'cloudinary',\n 'akamai',\n 'custom',\n] as const\n\nexport type LoaderValue = (typeof VALID_LOADERS)[number]\n\nexport type ImageLoaderProps = {\n src: string\n width: number\n quality?: number\n}\n\nexport type ImageLoaderPropsWithConfig = ImageLoaderProps & {\n config: Readonly<ImageConfig>\n}\n\nexport type LocalPattern = {\n /**\n * Can be literal or wildcard.\n * Single `*` matches a single path segment.\n * Double `**` matches any number of path segments.\n */\n pathname?: string\n\n /**\n * Can be literal query string such as `?v=1` or\n * empty string meaning no query string.\n */\n search?: string\n}\n\nexport type RemotePattern = {\n /**\n * Must be `http` or `https`.\n */\n protocol?: 'http' | 'https'\n\n /**\n * Can be literal or wildcard.\n * Single `*` matches a single subdomain.\n * Double `**` matches any number of subdomains.\n */\n hostname: string\n\n /**\n * Can be literal port such as `8080` or empty string\n * meaning no port.\n */\n port?: string\n\n /**\n * Can be literal or wildcard.\n * Single `*` matches a single path segment.\n * Double `**` matches any number of path segments.\n */\n pathname?: string\n\n /**\n * Can be literal query string such as `?v=1` or\n * empty string meaning no query string.\n */\n search?: string\n}\n\ntype ImageFormat = 'image/avif' | 'image/webp'\n\n/**\n * Image configurations\n *\n * @see [Image configuration options](https://nextjs.org/docs/api-reference/next/image#configuration-options)\n */\nexport type ImageConfigComplete = {\n /** @see [Device sizes documentation](https://nextjs.org/docs/api-reference/next/image#device-sizes) */\n deviceSizes: number[]\n\n /** @see [Image sizing documentation](https://nextjs.org/docs/app/building-your-application/optimizing/images#image-sizing) */\n imageSizes: number[]\n\n /** @see [Image loaders configuration](https://nextjs.org/docs/api-reference/next/legacy/image#loader) */\n loader: LoaderValue\n\n /** @see [Image loader configuration](https://nextjs.org/docs/app/api-reference/components/image#path) */\n path: string\n\n /** @see [Image loader configuration](https://nextjs.org/docs/api-reference/next/image#loader-configuration) */\n loaderFile: string\n\n /**\n * @deprecated Use `remotePatterns` instead.\n */\n domains: string[]\n\n /** @see [Disable static image import configuration](https://nextjs.org/docs/api-reference/next/image#disable-static-imports) */\n disableStaticImages: boolean\n\n /** @see [Cache behavior](https://nextjs.org/docs/api-reference/next/image#caching-behavior) */\n minimumCacheTTL: number\n\n /** @see [Acceptable formats](https://nextjs.org/docs/api-reference/next/image#acceptable-formats) */\n formats: ImageFormat[]\n\n /** @see [Maximum Disk Cache Size (in bytes)](https://nextjs.org/docs/api-reference/next/image#maximumdiskcachesize) */\n maximumDiskCacheSize: number | undefined\n\n /** @see [Maximum Redirects](https://nextjs.org/docs/api-reference/next/image#maximumredirects) */\n maximumRedirects: number\n\n /** @see [Maximum Response Body](https://nextjs.org/docs/api-reference/next/image#maximumresponsebody) */\n maximumResponseBody: number\n\n /** @see [Dangerously Allow Local IP](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-local-ip) */\n dangerouslyAllowLocalIP: boolean\n\n /** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */\n dangerouslyAllowSVG: boolean\n\n /** @see [Content Security Policy](https://nextjs.org/docs/api-reference/next/image#contentsecuritypolicy) */\n contentSecurityPolicy: string\n\n /** @see [Content Disposition Type](https://nextjs.org/docs/api-reference/next/image#contentdispositiontype) */\n contentDispositionType: 'inline' | 'attachment'\n\n /** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remotepatterns) */\n remotePatterns: Array<URL | RemotePattern>\n\n /** @see [Local Patterns](https://nextjs.org/docs/api-reference/next/image#localPatterns) */\n localPatterns: LocalPattern[] | undefined\n\n /** @see [Qualities](https://nextjs.org/docs/api-reference/next/image#qualities) */\n qualities: number[] | undefined\n\n /** @see [Unoptimized](https://nextjs.org/docs/api-reference/next/image#unoptimized) */\n unoptimized: boolean\n\n /**\n * When true, the `cacheHandler` configured in next.config.js will also be used\n * for caching optimized images. When false, images use the default filesystem cache.\n * @see [Image Optimization Caching](https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheHandler#image-optimization-caching)\n */\n customCacheHandler: boolean\n}\n\nexport type ImageConfig = Partial<ImageConfigComplete>\n\ntype RequiredImageConfigForRendering = Pick<\n ImageConfigComplete,\n | 'deviceSizes'\n | 'imageSizes'\n | 'loader'\n | 'path'\n | 'dangerouslyAllowSVG'\n | 'unoptimized'\n>\n\nexport type ImageConfigForRendering = RequiredImageConfigForRendering &\n Partial<\n Pick<\n ImageConfigComplete,\n 'qualities' | 'domains' | 'remotePatterns' | 'localPatterns'\n >\n > & {\n output?: 'standalone' | 'export'\n }\n\nexport type PreparedImageConfig = RequiredImageConfigForRendering & {\n allSizes: number[]\n qualities: ImageConfigComplete['qualities']\n domains: ImageConfigComplete['domains'] | undefined\n remotePatterns: ImageConfigComplete['remotePatterns'] | undefined\n localPatterns: ImageConfigComplete['localPatterns']\n output: 'standalone' | 'export' | undefined\n}\n\nconst missingImageConfig = {}\nconst preparedImageConfigs = new WeakMap<\n object,\n WeakMap<object, PreparedImageConfig>\n>()\n\n/**\n * Prepare owned, sorted image options once for each env/context pair.\n * Changed options require new objects because results are cached by identity.\n */\nexport function prepareImageConfig(\n envConfig?: ImageConfigForRendering,\n contextConfig?: ImageConfigComplete\n): PreparedImageConfig {\n const envKey = envConfig ?? missingImageConfig\n const contextKey = contextConfig ?? missingImageConfig\n let preparedByContext = preparedImageConfigs.get(envKey)\n if (preparedByContext) {\n const cached = preparedByContext.get(contextKey)\n if (cached) {\n return cached\n }\n }\n\n const source: ImageConfigForRendering =\n envConfig || contextConfig || imageConfigDefault\n const deviceSizes = [...source.deviceSizes].sort((a, b) => a - b)\n const imageSizes = [...source.imageSizes]\n const prepared: PreparedImageConfig = {\n deviceSizes,\n imageSizes,\n allSizes: [...deviceSizes, ...imageSizes].sort((a, b) => a - b),\n qualities:\n source.qualities === undefined\n ? undefined\n : [...source.qualities].sort((a, b) => a - b),\n path: source.path,\n loader: source.loader,\n dangerouslyAllowSVG: source.dangerouslyAllowSVG,\n unoptimized: source.unoptimized,\n domains: source.domains,\n remotePatterns: source.remotePatterns,\n // The inlined browser options supply their own patterns. During SSR the\n // context supplies security-sensitive patterns omitted from the inline data.\n localPatterns:\n typeof window === 'undefined' && contextConfig !== undefined\n ? contextConfig.localPatterns\n : source.localPatterns,\n output: source.output,\n }\n\n if (!preparedByContext) {\n preparedByContext = new WeakMap()\n preparedImageConfigs.set(envKey, preparedByContext)\n }\n preparedByContext.set(contextKey, prepared)\n return prepared\n}\n\nexport const imageConfigDefault: ImageConfigComplete = {\n deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],\n imageSizes: [32, 48, 64, 96, 128, 256, 384],\n path: '/_next/image',\n loader: 'default',\n loaderFile: '',\n /**\n * @deprecated Use `remotePatterns` instead to protect your application from malicious users.\n */\n domains: [],\n disableStaticImages: false,\n minimumCacheTTL: 14400, // 4 hours\n formats: ['image/webp'],\n maximumDiskCacheSize: undefined, // auto-detect by default\n maximumRedirects: 3,\n maximumResponseBody: 50_000_000, // 50 MB\n dangerouslyAllowLocalIP: false,\n dangerouslyAllowSVG: false,\n contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`,\n contentDispositionType: 'attachment',\n localPatterns: undefined, // default: allow all local images\n remotePatterns: [], // default: allow no remote images\n qualities: [75],\n unoptimized: false,\n customCacheHandler: false,\n}\n"],"names":["VALID_LOADERS","imageConfigDefault","prepareImageConfig","missingImageConfig","preparedImageConfigs","WeakMap","envConfig","contextConfig","envKey","contextKey","preparedByContext","get","cached","source","deviceSizes","sort","a","b","imageSizes","prepared","allSizes","qualities","undefined","path","loader","dangerouslyAllowSVG","unoptimized","domains","remotePatterns","localPatterns","window","output","set","loaderFile","disableStaticImages","minimumCacheTTL","formats","maximumDiskCacheSize","maximumRedirects","maximumResponseBody","dangerouslyAllowLocalIP","contentSecurityPolicy","contentDispositionType","customCacheHandler"],"mappings":";;;;;;;;;;;;;;;;IAAaA,aAAa;eAAbA;;IA4OAC,kBAAkB;eAAlBA;;IAjDGC,kBAAkB;eAAlBA;;;AA3LT,MAAMF,gBAAgB;IAC3B;IACA;IACA;IACA;IACA;CACD;AA2KD,MAAMG,qBAAqB,CAAC;AAC5B,MAAMC,uBAAuB,IAAIC;AAS1B,SAASH,mBACdI,SAAmC,EACnCC,aAAmC;IAEnC,MAAMC,SAASF,aAAaH;IAC5B,MAAMM,aAAaF,iBAAiBJ;IACpC,IAAIO,oBAAoBN,qBAAqBO,GAAG,CAACH;IACjD,IAAIE,mBAAmB;QACrB,MAAME,SAASF,kBA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vBC,sBAAsBf;IACtBgB,kBAAkB;IAClBC,qBAAqB;IACrBC,yBAAyB;IACzBf,qBAAqB;IACrBgB,uBAAuB,CAAC,6CAA6C,CAAC;IACtEC,wBAAwB;IACxBb,eAAeP;IACfM,gBAAgB,EAAE;IAClBP,WAAW;QAAC;KAAG;IACfK,aAAa;IACbiB,oBAAoB;AACtB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-external-get-image-props.d.ts b/e-commerce/node_modules/next/dist/shared/lib/image-external-get-image-props.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4dae59d99fa5b796e04426366ea27b3f46dfd81 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-external-get-image-props.d.ts @@ -0,0 +1,11 @@ +import type { ImageProps } from './get-img-props'; +/** + * For more advanced use cases, you can call `getImageProps()` + * to get the props that would be passed to the underlying `<img>` element, + * and instead pass to them to another component, style, canvas, etc. + * + * Read more: [Next.js docs: `getImageProps`](https://nextjs.org/docs/app/api-reference/components/image#getimageprops) + */ +export declare function getImageProps(imgProps: ImageProps): { + props: import("./get-img-props").ImgProps; +}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-external-get-image-props.js b/e-commerce/node_modules/next/dist/shared/lib/image-external-get-image-props.js new file mode 100644 index 0000000000000000000000000000000000000000..ba09663619bce8f93f5fcdb83c32d9890a8cc329 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-external-get-image-props.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getImageProps", { + enumerable: true, + get: function() { + return getImageProps; + } +}); +const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"); +const _imageconfig = require("./image-config"); +const _getimgprops = require("./get-img-props"); +const _imageloader = /*#__PURE__*/ _interop_require_wildcard._(require("next/dist/shared/lib/image-loader")); +const defaultLoader = Reflect.get(_imageloader, 'default'); +// The bundler replaces this with fixed options. Public getImageProps has no +// context, so prepare those options once when the module is loaded. +const imageConfig = (0, _imageconfig.prepareImageConfig)(process.env.__NEXT_IMAGE_OPTS); +function getImageProps(imgProps) { + const { props } = (0, _getimgprops.getImgProps)(imgProps, { + defaultLoader, + imgConf: imageConfig + }); + // Normally we don't care about undefined props because we pass to JSX, + // but this exported function could be used by the end user for anything + // so we delete undefined props to clean it up a little. + for (const [key, value] of Object.entries(props)){ + if (value === undefined) { + delete props[key]; + } + } + return { + props + }; +} + +//# sourceMappingURL=image-external-get-image-props.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-external-get-image-props.js.map b/e-commerce/node_modules/next/dist/shared/lib/image-external-get-image-props.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bda904304f73da74d200fc5037f33bbe2eecee64 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-external-get-image-props.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/image-external-get-image-props.ts"],"sourcesContent":["import {\n prepareImageConfig,\n type ImageConfigForRendering,\n} from './image-config'\nimport type { ImageProps } from './get-img-props'\n\nimport { getImgProps } from './get-img-props'\n\n// This is replaced by a bundler alias. Use a namespace import so a custom\n// loader without a default export can reach the framework's runtime validation\n// instead of failing static ESM export validation first.\nimport * as defaultLoaderModule from 'next/dist/shared/lib/image-loader'\n\nconst defaultLoader = Reflect.get(defaultLoaderModule, 'default')\n// The bundler replaces this with fixed options. Public getImageProps has no\n// context, so prepare those options once when the module is loaded.\nconst imageConfig = prepareImageConfig(\n process.env.__NEXT_IMAGE_OPTS as any as ImageConfigForRendering | undefined\n)\n\n/**\n * For more advanced use cases, you can call `getImageProps()`\n * to get the props that would be passed to the underlying `<img>` element,\n * and instead pass to them to another component, style, canvas, etc.\n *\n * Read more: [Next.js docs: `getImageProps`](https://nextjs.org/docs/app/api-reference/components/image#getimageprops)\n */\nexport function getImageProps(imgProps: ImageProps) {\n const { props } = getImgProps(imgProps, {\n defaultLoader,\n imgConf: imageConfig,\n })\n // Normally we don't care about undefined props because we pass to JSX,\n // but this exported function could be used by the end user for anything\n // so we delete undefined props to clean it up a little.\n for (const [key, value] of Object.entries(props)) {\n if (value === undefined) {\n delete props[key as keyof typeof props]\n }\n }\n return { props }\n}\n"],"names":["getImageProps","defaultLoader","Reflect","get","defaultLoaderModule","imageConfig","prepareImageConfig","process","env","__NEXT_IMAGE_OPTS","imgProps","props","getImgProps","imgConf","key","value","Object","entries","undefined"],"mappings":";;;;+BA2BgBA;;;eAAAA;;;;6BAxBT;6BAGqB;uEAKS;AAErC,MAAMC,gBAAgBC,QAAQC,GAAG,CAACC,cAAqB;AACvD,4EAA4E;AAC5E,oEAAoE;AACpE,MAAMC,cAAcC,IAAAA,+BAAkB,EACpCC,QAAQC,GAAG,CAACC,iBAAiB;AAUxB,SAAST,cAAcU,QAAoB;IAChD,MAAM,EAAEC,KAAK,EAAE,GAAGC,IAAAA,wBAAW,EAACF,UAAU;QACtCT;QACAY,SAASR;IACX;IACA,uEAAuE;IACvE,wEAAwE;IACxE,wDAAwD;IACxD,KAAK,MAAM,CAACS,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACN,OAAQ;QAChD,IAAII,UAAUG,WAAW;YACvB,OAAOP,KAAK,CAACG,IAA0B;QACzC;IACF;IACA,OAAO;QAAEH;IAAM;AACjB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-external.d.ts b/e-commerce/node_modules/next/dist/shared/lib/image-external.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ca0c6dbbfe7b0bd161170c19721efc449c478cc --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-external.d.ts @@ -0,0 +1,5 @@ +import type { ImageLoaderProps } from './image-config'; +import type { ImageProps, ImageLoader, StaticImageData } from './get-img-props'; +export { Image as default } from '../../client/image-component'; +export { getImageProps } from './image-external-get-image-props'; +export type { ImageProps, ImageLoaderProps, ImageLoader, StaticImageData }; diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-external.js b/e-commerce/node_modules/next/dist/shared/lib/image-external.js new file mode 100644 index 0000000000000000000000000000000000000000..55a9cd81cef718c9a34804a20f26a71e1bc45455 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-external.js @@ -0,0 +1,27 @@ +'use turbopack: no side effects'; +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + default: null, + getImageProps: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + default: function() { + return _imagecomponent.Image; + }, + getImageProps: function() { + return _imageexternalgetimageprops.getImageProps; + } +}); +const _imagecomponent = require("../../client/image-component"); +const _imageexternalgetimageprops = require("./image-external-get-image-props"); + +//# sourceMappingURL=image-external.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-external.js.map b/e-commerce/node_modules/next/dist/shared/lib/image-external.js.map new file mode 100644 index 0000000000000000000000000000000000000000..13178c592c1bee0d96f241758a2dcebd8a45715f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-external.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/image-external.tsx"],"sourcesContent":["'use turbopack: no side effects'\nimport type { ImageLoaderProps } from './image-config'\nimport type { ImageProps, ImageLoader, StaticImageData } from './get-img-props'\n\nexport { Image as default } from '../../client/image-component'\nexport { getImageProps } from './image-external-get-image-props'\n\nexport type { ImageProps, ImageLoaderProps, ImageLoader, StaticImageData }\n"],"names":["default","Image","getImageProps"],"mappings":"AAAA;;;;;;;;;;;;;;;;IAIkBA,OAAO;eAAhBC,qBAAK;;IACLC,aAAa;eAAbA,yCAAa;;;gCADW;4CACH","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-loader.d.ts b/e-commerce/node_modules/next/dist/shared/lib/image-loader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3900120a883f9706750419e6a0674c1b484c15a4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-loader.d.ts @@ -0,0 +1,6 @@ +import type { ImageLoaderPropsWithConfig } from './image-config'; +declare function defaultLoader({ config, src, width, quality, }: ImageLoaderPropsWithConfig): string; +declare namespace defaultLoader { + var __next_img_default: boolean; +} +export default defaultLoader; diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-loader.js b/e-commerce/node_modules/next/dist/shared/lib/image-loader.js new file mode 100644 index 0000000000000000000000000000000000000000..d0d73153b1a8e0bf342b81d5e1b9370ed8431430 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-loader.js @@ -0,0 +1,94 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _findclosestquality = require("./find-closest-quality"); +const _deploymentid = require("./deployment-id"); +function defaultLoader({ config, src, width, quality }) { + if (process.env.NODE_ENV !== 'production') { + const missingValues = []; + // these should always be provided but make sure they are + if (!src) missingValues.push('src'); + if (!width) missingValues.push('width'); + if (missingValues.length > 0) { + throw new Error(`Next Image Optimization requires ${missingValues.join(', ')} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify({ + src, + width, + quality + })}`); + } + } + // Extract dpl parameter early so validation uses the clean URL. + // If a immutable asset token should be used, it was already added as a query parameter and will + // be extracted and reused here. + let deploymentId = (0, _deploymentid.getDeploymentId)(); + if (src.startsWith('/') && !src.startsWith('//')) { + if (src.includes('/_next/static/immutable') && !(0, _deploymentid.getAssetToken)()) { + // immutable static asset and supported by platform, don't add `?dpl=` + deploymentId = undefined; + } else { + // We unfortunately can't easily use `new URL()` here, because it normalizes the URL which causes + // double-encoding with the `encodeURIComponent(src)` below + const qIndex = src.indexOf('?'); + if (qIndex !== -1) { + const params = new URLSearchParams(src.slice(qIndex + 1)); + const srcDpl = params.get('dpl'); + if (srcDpl) { + deploymentId = srcDpl; + params.delete('dpl'); + const remaining = params.toString(); + src = src.slice(0, qIndex) + (remaining ? '?' + remaining : ''); + } + } + } + } + if (src.startsWith('/') && src.includes('?') && config.localPatterns?.length === 1 && config.localPatterns[0].pathname === '**' && config.localPatterns[0].search === '') { + throw new Error(`Image with src "${src}" is using a query string which is not configured in images.localPatterns.` + `\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`); + } + if (process.env.NODE_ENV !== 'production') { + if (src.startsWith('//')) { + throw new Error(`Failed to parse src "${src}" on \`next/image\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`); + } + if (src.startsWith('/') && config.localPatterns) { + if (process.env.NODE_ENV !== 'test' && // micromatch isn't compatible with edge runtime + process.env.NEXT_RUNTIME !== 'edge') { + // We use dynamic require because this should only error in development + const { hasLocalMatch } = require('./match-local-pattern'); + if (!hasLocalMatch(config.localPatterns, src)) { + throw new Error(`Invalid src prop (${src}) on \`next/image\` does not match \`images.localPatterns\` configured in your \`next.config.js\`\n` + `See more info: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`); + } + } + } + if (!src.startsWith('/') && (config.domains || config.remotePatterns)) { + let parsedSrc; + try { + parsedSrc = new URL(src); + } catch (err) { + console.error(err); + throw new Error(`Failed to parse src "${src}" on \`next/image\`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)`); + } + if (process.env.NODE_ENV !== 'test' && // micromatch isn't compatible with edge runtime + process.env.NEXT_RUNTIME !== 'edge') { + // We use dynamic require because this should only error in development + const { hasRemoteMatch } = require('./match-remote-pattern'); + if (!hasRemoteMatch(config.domains, config.remotePatterns, parsedSrc)) { + throw new Error(`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` + `See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`); + } + } + } + } + const q = (0, _findclosestquality.findClosestQuality)(quality, config); + return `${config.path}?url=${encodeURIComponent(src)}&w=${width}&q=${q}${src.startsWith('/') && deploymentId ? `&dpl=${deploymentId}` : ''}`; +} +// We use this to determine if the import is the default loader +// or a custom loader defined by the user in next.config.js +defaultLoader.__next_img_default = true; +const _default = defaultLoader; + +//# sourceMappingURL=image-loader.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/image-loader.js.map b/e-commerce/node_modules/next/dist/shared/lib/image-loader.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f1c14c088b2121289d919289a44ae41e476a4883 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/image-loader.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/image-loader.ts"],"sourcesContent":["import type { ImageLoaderPropsWithConfig } from './image-config'\nimport { findClosestQuality } from './find-closest-quality'\nimport { getAssetToken, getDeploymentId } from './deployment-id'\n\nfunction defaultLoader({\n config,\n src,\n width,\n quality,\n}: ImageLoaderPropsWithConfig): string {\n if (process.env.NODE_ENV !== 'production') {\n const missingValues = []\n\n // these should always be provided but make sure they are\n if (!src) missingValues.push('src')\n if (!width) missingValues.push('width')\n\n if (missingValues.length > 0) {\n throw new Error(\n `Next Image Optimization requires ${missingValues.join(\n ', '\n )} to be provided. Make sure you pass them as props to the \\`next/image\\` component. Received: ${JSON.stringify(\n { src, width, quality }\n )}`\n )\n }\n }\n\n // Extract dpl parameter early so validation uses the clean URL.\n // If a immutable asset token should be used, it was already added as a query parameter and will\n // be extracted and reused here.\n let deploymentId = getDeploymentId()\n if (src.startsWith('/') && !src.startsWith('//')) {\n if (src.includes('/_next/static/immutable') && !getAssetToken()) {\n // immutable static asset and supported by platform, don't add `?dpl=`\n deploymentId = undefined\n } else {\n // We unfortunately can't easily use `new URL()` here, because it normalizes the URL which causes\n // double-encoding with the `encodeURIComponent(src)` below\n const qIndex = src.indexOf('?')\n if (qIndex !== -1) {\n const params = new URLSearchParams(src.slice(qIndex + 1))\n const srcDpl = params.get('dpl')\n if (srcDpl) {\n deploymentId = srcDpl\n params.delete('dpl')\n const remaining = params.toString()\n src = src.slice(0, qIndex) + (remaining ? '?' + remaining : '')\n }\n }\n }\n }\n\n if (\n src.startsWith('/') &&\n src.includes('?') &&\n config.localPatterns?.length === 1 &&\n config.localPatterns[0].pathname === '**' &&\n config.localPatterns[0].search === ''\n ) {\n throw new Error(\n `Image with src \"${src}\" is using a query string which is not configured in images.localPatterns.` +\n `\\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`\n )\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (src.startsWith('//')) {\n throw new Error(\n `Failed to parse src \"${src}\" on \\`next/image\\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`\n )\n }\n\n if (src.startsWith('/') && config.localPatterns) {\n if (\n process.env.NODE_ENV !== 'test' &&\n // micromatch isn't compatible with edge runtime\n process.env.NEXT_RUNTIME !== 'edge'\n ) {\n // We use dynamic require because this should only error in development\n const { hasLocalMatch } =\n require('./match-local-pattern') as typeof import('./match-local-pattern')\n if (!hasLocalMatch(config.localPatterns, src)) {\n throw new Error(\n `Invalid src prop (${src}) on \\`next/image\\` does not match \\`images.localPatterns\\` configured in your \\`next.config.js\\`\\n` +\n `See more info: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`\n )\n }\n }\n }\n\n if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {\n let parsedSrc: URL\n try {\n parsedSrc = new URL(src)\n } catch (err) {\n console.error(err)\n throw new Error(\n `Failed to parse src \"${src}\" on \\`next/image\\`, if using relative image it must start with a leading slash \"/\" or be an absolute URL (http:// or https://)`\n )\n }\n\n if (\n process.env.NODE_ENV !== 'test' &&\n // micromatch isn't compatible with edge runtime\n process.env.NEXT_RUNTIME !== 'edge'\n ) {\n // We use dynamic require because this should only error in development\n const { hasRemoteMatch } =\n require('./match-remote-pattern') as typeof import('./match-remote-pattern')\n if (\n !hasRemoteMatch(config.domains!, config.remotePatterns!, parsedSrc)\n ) {\n throw new Error(\n `Invalid src prop (${src}) on \\`next/image\\`, hostname \"${parsedSrc.hostname}\" is not configured under images in your \\`next.config.js\\`\\n` +\n `See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`\n )\n }\n }\n }\n }\n\n const q = findClosestQuality(quality, config)\n\n return `${config.path}?url=${encodeURIComponent(src)}&w=${width}&q=${q}${\n src.startsWith('/') && deploymentId ? `&dpl=${deploymentId}` : ''\n }`\n}\n\n// We use this to determine if the import is the default loader\n// or a custom loader defined by the user in next.config.js\ndefaultLoader.__next_img_default = true\n\nexport default defaultLoader\n"],"names":["defaultLoader","config","src","width","quality","process","env","NODE_ENV","missingValues","push","length","Error","join","JSON","stringify","deploymentId","getDeploymentId","startsWith","includes","getAssetToken","undefined","qIndex","indexOf","params","URLSearchParams","slice","srcDpl","get","delete","remaining","toString","localPatterns","pathname","search","NEXT_RUNTIME","hasLocalMatch","require","domains","remotePatterns","parsedSrc","URL","err","console","error","hasRemoteMatch","hostname","q","findClosestQuality","path","encodeURIComponent","__next_img_default"],"mappings":";;;;+BAqIA;;;eAAA;;;oCApImC;8BACY;AAE/C,SAASA,cAAc,EACrBC,MAAM,EACNC,GAAG,EACHC,KAAK,EACLC,OAAO,EACoB;IAC3B,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;QACzC,MAAMC,gBAAgB,EAAE;QAExB,yDAAyD;QACzD,IAAI,CAACN,KAAKM,cAAcC,IAAI,CAAC;QAC7B,IAAI,CAACN,OAAOK,cAAcC,IAAI,CAAC;QAE/B,IAAID,cAAcE,MAAM,GAAG,GAAG;YAC5B,MAAM,IAAIC,MACR,CAAC,iCAAiC,EAAEH,cAAcI,IAAI,CACpD,MACA,6FAA6F,EAAEC,KAAKC,SAAS,CAC7G;gBAAEZ;gBAAKC;gBAAOC;YAAQ,IACrB;QAEP;IACF;IAEA,gEAAgE;IAChE,gGAAgG;IAChG,gCAAgC;IAChC,IAAIW,eAAeC,IAAAA,6BAAe;IAClC,IAAId,IAAIe,UAAU,CAAC,QAAQ,CAACf,IAAIe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messages.d.ts b/e-commerce/node_modules/next/dist/shared/lib/instant-messages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..98ff11d9f1e288077305daa3dee1821ef68d88f2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/instant-messages.d.ts @@ -0,0 +1,2 @@ +export declare function createUnrenderedSegmentError(route: string, missingFiles: readonly string[]): Error; +export declare function createLinkPrefetchPartialError(pathname: string): Error; diff --git a/e-commerce/node_modules/next/dist/shared/lib/instant-messages.js b/e-commerce/node_modules/next/dist/shared/lib/instant-messages.js new file mode 100644 index 0000000000000000000000000000000000000000..c5e5182ea6ed3c9bac35cc9693293e339d1e51a6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/instant-messages.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + createLinkPrefetchPartialError: null, + createUnrenderedSegmentError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + createLinkPrefetchPartialError: function() { + return createLinkPrefetchPartialError; + }, + createUnrenderedSegmentError: function() { + return createUnrenderedSegmentError; + } +}); +function createUnrenderedSegmentError(route, missingFiles) { + let message = `Route "${route}": Could not validate that a segment in your UI has instant navigation.`; + if (missingFiles.length > 0) { + const label = missingFiles.length === 1 ? 'Dropped segment' : 'Dropped segments'; + message += `\n\nThis segment was dropped from rendering. Issues that would prevent instant navigation will go undetected.` + `\n\n${label}:\n${missingFiles.map((p)=>` ${p}`).join('\n')}` + `\n\nWays to fix this:` + `\n - [render] Render the dropped segment` + `\n - [ignore] Set \`export const instant = false\` to opt the dropped segment out of instant-navigation validation` + `\n\nLearn more: https://nextjs.org/docs/messages/instant-unrendered-segment`; + } + return new Error(message); +} +function createLinkPrefetchPartialError(pathname) { + return new Error(`Next.js encountered dynamic data during prefetching for "${pathname}".\n\n` + `This will lead to slower, more expensive prefetches.\n\n` + `Ways to fix this:\n` + ` - [upgrade] Opt into Partial Prefetching by exporting \`const prefetch = 'partial'\` from the page or layout, or by setting \`partialPrefetching: true\` in next.config to opt the whole app in\n` + ` - [disable] Remove \`prefetch={true}\` from the <Link> to use the default prefetch\n` + ` - [ignore] Set \`export const instant = false\` to opt the route out of instant-navigation validation\n\n` + `Learn more: https://nextjs.org/docs/messages/instant-link-prefetch-partial`); +} + +//# sourceMappingURL=instant-messages.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/instant-messages.js.map b/e-commerce/node_modules/next/dist/shared/lib/instant-messages.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a4172e9092dedd319e2cec0ef4fc8ae08534904b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/instant-messages.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/instant-messages.ts"],"sourcesContent":["export function createUnrenderedSegmentError(\n route: string,\n missingFiles: readonly string[]\n): Error {\n let message = `Route \"${route}\": Could not validate that a segment in your UI has instant navigation.`\n if (missingFiles.length > 0) {\n const label =\n missingFiles.length === 1 ? 'Dropped segment' : 'Dropped segments'\n message +=\n `\\n\\nThis segment was dropped from rendering. Issues that would prevent instant navigation will go undetected.` +\n `\\n\\n${label}:\\n${missingFiles.map((p) => ` ${p}`).join('\\n')}` +\n `\\n\\nWays to fix this:` +\n `\\n - [render] Render the dropped segment` +\n `\\n - [ignore] Set \\`export const instant = false\\` to opt the dropped segment out of instant-navigation validation` +\n `\\n\\nLearn more: https://nextjs.org/docs/messages/instant-unrendered-segment`\n }\n return new Error(message)\n}\n\nexport function createLinkPrefetchPartialError(pathname: string): Error {\n return new Error(\n `Next.js encountered dynamic data during prefetching for \"${pathname}\".\\n\\n` +\n `This will lead to slower, more expensive prefetches.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [upgrade] Opt into Partial Prefetching by exporting \\`const prefetch = 'partial'\\` from the page or layout, or by setting \\`partialPrefetching: true\\` in next.config to opt the whole app in\\n` +\n ` - [disable] Remove \\`prefetch={true}\\` from the <Link> to use the default prefetch\\n` +\n ` - [ignore] Set \\`export const instant = false\\` to opt the route out of instant-navigation validation\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/instant-link-prefetch-partial`\n )\n}\n"],"names":["createLinkPrefetchPartialError","createUnrenderedSegmentError","route","missingFiles","message","length","label","map","p","join","Error","pathname"],"mappings":";;;;;;;;;;;;;;;IAmBgBA,8BAA8B;eAA9BA;;IAnBAC,4BAA4B;eAA5BA;;;AAAT,SAASA,6BACdC,KAAa,EACbC,YAA+B;IAE/B,IAAIC,UAAU,CAAC,OAAO,EAAEF,MAAM,uEAAuE,CAAC;IACtG,IAAIC,aAAaE,MAAM,GAAG,GAAG;QAC3B,MAAMC,QACJH,aAAaE,MAAM,KAAK,IAAI,oBAAoB;QAClDD,WACE,CAAC,6GAA6G,CAAC,GAC/G,CAAC,IAAI,EAAEE,MAAM,GAAG,EAAEH,aAAaI,GAAG,CAAC,CAACC,IAAM,CAAC,EAAE,EAAEA,GAAG,EAAEC,IAAI,CAAC,OAAO,GAChE,CAAC,qBAAqB,CAAC,GACvB,CAAC,yCAAyC,CAAC,GAC3C,CAAC,mHAAmH,CAAC,GACrH,CAAC,2EAA2E,CAAC;IACjF;IACA,OAAO,IAAIC,MAAMN;AACnB;AAEO,SAASJ,+BAA+BW,QAAgB;IAC7D,OAAO,IAAID,MACT,CAAC,yDAAyD,EAAEC,SAAS,MAAM,CAAC,GAC1E,CAAC,wDAAwD,CAAC,GAC1D,CAAC,mBAAmB,CAAC,GACrB,CAAC,mMAAmM,CAAC,GACrM,CAAC,sFAAsF,CAAC,GACxF,CAAC,2GAA2G,CAAC,GAC7G,CAAC,0EAA0E,CAAC;AAElF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/instant-nav-cookie.d.ts b/e-commerce/node_modules/next/dist/shared/lib/instant-nav-cookie.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..03be480eed266ed6909ad00b7932a10da634cf1b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/instant-nav-cookie.d.ts @@ -0,0 +1,11 @@ +import type { FlightRouterState } from './app-router-types'; +export type InstantNavCookieData = { + state: 'pending'; +} | { + state: 'mpa'; +} | { + state: 'spa'; + fromTree: FlightRouterState; + toTree: FlightRouterState | null; +}; +export declare function parseInstantNavCookieValue(raw: string): InstantNavCookieData; diff --git a/e-commerce/node_modules/next/dist/shared/lib/instant-nav-cookie.js b/e-commerce/node_modules/next/dist/shared/lib/instant-nav-cookie.js new file mode 100644 index 0000000000000000000000000000000000000000..03510711121b10d30a3668fbf224e6a525444c85 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/instant-nav-cookie.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "parseInstantNavCookieValue", { + enumerable: true, + get: function() { + return parseInstantNavCookieValue; + } +}); +function parseInstantNavCookieValue(raw) { + try { + const parsed = JSON.parse(raw); + if (Array.isArray(parsed) && parsed.length >= 3) { + const rawState = parsed[2]; + if (rawState === null) { + return { + state: 'mpa' + }; + } + // SPA capture: rawState is { from, to } + if (typeof rawState === 'object' && rawState !== null) { + const fromTree = rawState.from ?? [ + '', + {} + ]; + const toTree = rawState.to ?? null; + return { + state: 'spa', + fromTree, + toTree + }; + } + return { + state: 'spa', + fromTree: [ + '', + {} + ], + toTree: null + }; + } + } catch {} + return { + state: 'pending' + }; +} + +//# sourceMappingURL=instant-nav-cookie.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/instant-nav-cookie.js.map b/e-commerce/node_modules/next/dist/shared/lib/instant-nav-cookie.js.map new file mode 100644 index 0000000000000000000000000000000000000000..417655544c2ad679f6dee9d5bc018f6b890ee3d3 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/instant-nav-cookie.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/instant-nav-cookie.ts"],"sourcesContent":["import type { FlightRouterState } from './app-router-types'\n\nexport type InstantNavCookieData =\n | { state: 'pending' }\n | { state: 'mpa' }\n | {\n state: 'spa'\n fromTree: FlightRouterState\n toTree: FlightRouterState | null\n }\n\nexport function parseInstantNavCookieValue(raw: string): InstantNavCookieData {\n try {\n const parsed = JSON.parse(raw)\n if (Array.isArray(parsed) && parsed.length >= 3) {\n const rawState = parsed[2]\n if (rawState === null) {\n return { state: 'mpa' }\n }\n // SPA capture: rawState is { from, to }\n if (typeof rawState === 'object' && rawState !== null) {\n const fromTree: FlightRouterState = rawState.from ?? ['', {}]\n const toTree: FlightRouterState | null = rawState.to ?? null\n return { state: 'spa', fromTree, toTree }\n }\n return { state: 'spa', fromTree: ['', {}], toTree: null }\n }\n } catch {}\n return { state: 'pending' }\n}\n"],"names":["parseInstantNavCookieValue","raw","parsed","JSON","parse","Array","isArray","length","rawState","state","fromTree","from","toTree","to"],"mappings":";;;;+BAWgBA;;;eAAAA;;;AAAT,SAASA,2BAA2BC,GAAW;IACpD,IAAI;QACF,MAAMC,SAASC,KAAKC,KAAK,CAACH;QAC1B,IAAII,MAAMC,OAAO,CAACJ,WAAWA,OAAOK,MAAM,IAAI,GAAG;YAC/C,MAAMC,WAAWN,MAAM,CAAC,EAAE;YAC1B,IAAIM,aAAa,MAAM;gBACrB,OAAO;oBAAEC,OAAO;gBAAM;YACxB;YACA,wCAAwC;YACxC,IAAI,OAAOD,aAAa,YAAYA,aAAa,MAAM;gBACrD,MAAME,WAA8BF,SAASG,IAAI,IAAI;oBAAC;oBAAI,CAAC;iBAAE;gBAC7D,MAAMC,SAAmCJ,SAASK,EAAE,IAAI;gBACxD,OAAO;oBAAEJ,OAAO;oBAAOC;oBAAUE;gBAAO;YAC1C;YACA,OAAO;gBAAEH,OAAO;gBAAOC,UAAU;oBAAC;oBAAI,CAAC;iBAAE;gBAAEE,QAAQ;YAAK;QAC1D;IACF,EAAE,OAAM,CAAC;IACT,OAAO;QAAEH,OAAO;IAAU;AAC5B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/invariant-error.d.ts b/e-commerce/node_modules/next/dist/shared/lib/invariant-error.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3bbbd8509781ec87ffae2ab5ab623f898c109446 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/invariant-error.d.ts @@ -0,0 +1,3 @@ +export declare class InvariantError extends Error { + constructor(message: string, options?: ErrorOptions); +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/invariant-error.js b/e-commerce/node_modules/next/dist/shared/lib/invariant-error.js new file mode 100644 index 0000000000000000000000000000000000000000..b4180b52f5c2f5cfcdcd677ffab2eb759f01deee --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/invariant-error.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "InvariantError", { + enumerable: true, + get: function() { + return InvariantError; + } +}); +class InvariantError extends Error { + constructor(message, options){ + super(`Invariant: ${message.endsWith('.') ? message : message + '.'} This is a bug in Next.js.`, options); + this.name = 'InvariantError'; + } +} + +//# sourceMappingURL=invariant-error.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/invariant-error.js.map b/e-commerce/node_modules/next/dist/shared/lib/invariant-error.js.map new file mode 100644 index 0000000000000000000000000000000000000000..231695cd5bbbf5d5fa8e3bcbdc5972b5d1ea5c2c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/invariant-error.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/invariant-error.ts"],"sourcesContent":["export class InvariantError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(\n `Invariant: ${message.endsWith('.') ? message : message + '.'} This is a bug in Next.js.`,\n options\n )\n this.name = 'InvariantError'\n }\n}\n"],"names":["InvariantError","Error","constructor","message","options","endsWith","name"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA,uBAAuBC;IAClCC,YAAYC,OAAe,EAAEC,OAAsB,CAAE;QACnD,KAAK,CACH,CAAC,WAAW,EAAED,QAAQE,QAAQ,CAAC,OAAOF,UAAUA,UAAU,IAAI,0BAA0B,CAAC,EACzFC;QAEF,IAAI,CAACE,IAAI,GAAG;IACd;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/is-internal.d.ts b/e-commerce/node_modules/next/dist/shared/lib/is-internal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..feb08fe225b13a1745dd36c165f0bd49a1445add --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/is-internal.d.ts @@ -0,0 +1,6 @@ +/** React that's compiled with `next`. Used by App Router. */ +export declare const reactVendoredRe: RegExp; +/** React the user installed. Used by Pages Router, or user imports in App Router. */ +export declare const reactNodeModulesRe: RegExp; +export declare const nextInternalsRe: RegExp; +export default function isInternal(file: string | null): boolean; diff --git a/e-commerce/node_modules/next/dist/shared/lib/is-internal.js b/e-commerce/node_modules/next/dist/shared/lib/is-internal.js new file mode 100644 index 0000000000000000000000000000000000000000..8da46819336fb9a039eb4246600534fad6c5e265 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/is-internal.js @@ -0,0 +1,41 @@ +/** React that's compiled with `next`. Used by App Router. */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + default: null, + nextInternalsRe: null, + reactNodeModulesRe: null, + reactVendoredRe: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + default: function() { + return isInternal; + }, + nextInternalsRe: function() { + return nextInternalsRe; + }, + reactNodeModulesRe: function() { + return reactNodeModulesRe; + }, + reactVendoredRe: function() { + return reactVendoredRe; + } +}); +const reactVendoredRe = /[\\/]next[\\/]dist[\\/]compiled[\\/](react|react-dom|react-server-dom-(webpack|turbopack)|scheduler)[\\/]/; +const reactNodeModulesRe = /node_modules[\\/](react|react-dom|scheduler)[\\/]/; +const nextInternalsRe = /(node_modules[\\/]next[\\/]|[\\/].next[\\/]static[\\/]chunks[\\/]webpack\.js$|(edge-runtime-webpack|webpack-runtime)\.js$)/; +function isInternal(file) { + if (!file) return false; + // NOTE: native code has a version of the same logic in crates/next-napi-bindings/src/next_api/utils.rs + // keep them in sync. + return nextInternalsRe.test(file) || reactVendoredRe.test(file) || reactNodeModulesRe.test(file); +} + +//# sourceMappingURL=is-internal.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/is-internal.js.map b/e-commerce/node_modules/next/dist/shared/lib/is-internal.js.map new file mode 100644 index 0000000000000000000000000000000000000000..24287398353d359cd2eda0b150f1c1b04d119037 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/is-internal.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/is-internal.ts"],"sourcesContent":["/** React that's compiled with `next`. Used by App Router. */\nexport const reactVendoredRe =\n /[\\\\/]next[\\\\/]dist[\\\\/]compiled[\\\\/](react|react-dom|react-server-dom-(webpack|turbopack)|scheduler)[\\\\/]/\n\n/** React the user installed. Used by Pages Router, or user imports in App Router. */\nexport const reactNodeModulesRe =\n /node_modules[\\\\/](react|react-dom|scheduler)[\\\\/]/\n\nexport const nextInternalsRe =\n /(node_modules[\\\\/]next[\\\\/]|[\\\\/].next[\\\\/]static[\\\\/]chunks[\\\\/]webpack\\.js$|(edge-runtime-webpack|webpack-runtime)\\.js$)/\n\nexport default function isInternal(file: string | null) {\n if (!file) return false\n // NOTE: native code has a version of the same logic in crates/next-napi-bindings/src/next_api/utils.rs\n // keep them in sync.\n\n return (\n nextInternalsRe.test(file) ||\n reactVendoredRe.test(file) ||\n reactNodeModulesRe.test(file)\n )\n}\n"],"names":["isInternal","nextInternalsRe","reactNodeModulesRe","reactVendoredRe","file","test"],"mappings":"AAAA,2DAA2D;;;;;;;;;;;;;;;;;IAW3D,OAUC;eAVuBA;;IAHXC,eAAe;eAAfA;;IAHAC,kBAAkB;eAAlBA;;IAJAC,eAAe;eAAfA;;;AAAN,MAAMA,kBACX;AAGK,MAAMD,qBACX;AAEK,MAAMD,kBACX;AAEa,SAASD,WAAWI,IAAmB;IACpD,IAAI,CAACA,MAAM,OAAO;IAClB,uGAAuG;IACvG,qBAAqB;IAErB,OACEH,gBAAgBI,IAAI,CAACD,SACrBD,gBAAgBE,IAAI,CAACD,SACrBF,mBAAmBG,IAAI,CAACD;AAE5B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/is-plain-object.d.ts b/e-commerce/node_modules/next/dist/shared/lib/is-plain-object.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0c1edd824223be8d25872d517804d58698dace4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/is-plain-object.d.ts @@ -0,0 +1,2 @@ +export declare function getObjectClassLabel(value: any): string; +export declare function isPlainObject(value: any): boolean; diff --git a/e-commerce/node_modules/next/dist/shared/lib/is-plain-object.js b/e-commerce/node_modules/next/dist/shared/lib/is-plain-object.js new file mode 100644 index 0000000000000000000000000000000000000000..3ea90e26fb412a890a85a338b8d97c97aa1842b5 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/is-plain-object.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getObjectClassLabel: null, + isPlainObject: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getObjectClassLabel: function() { + return getObjectClassLabel; + }, + isPlainObject: function() { + return isPlainObject; + } +}); +function getObjectClassLabel(value) { + return Object.prototype.toString.call(value); +} +function isPlainObject(value) { + if (getObjectClassLabel(value) !== '[object Object]') { + return false; + } + const prototype = Object.getPrototypeOf(value); + /** + * this used to be previously: + * + * `return prototype === null || prototype === Object.prototype` + * + * but Edge Runtime expose Object from vm, being that kind of type-checking wrongly fail. + * + * It was changed to the current implementation since it's resilient to serialization. + */ return prototype === null || prototype.hasOwnProperty('isPrototypeOf'); +} + +//# sourceMappingURL=is-plain-object.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/is-plain-object.js.map b/e-commerce/node_modules/next/dist/shared/lib/is-plain-object.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b7ae66037d40a37380086490c2735c1c23afb8bc --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/is-plain-object.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/is-plain-object.ts"],"sourcesContent":["export function getObjectClassLabel(value: any): string {\n return Object.prototype.toString.call(value)\n}\n\nexport function isPlainObject(value: any): boolean {\n if (getObjectClassLabel(value) !== '[object Object]') {\n return false\n }\n\n const prototype = Object.getPrototypeOf(value)\n\n /**\n * this used to be previously:\n *\n * `return prototype === null || prototype === Object.prototype`\n *\n * but Edge Runtime expose Object from vm, being that kind of type-checking wrongly fail.\n *\n * It was changed to the current implementation since it's resilient to serialization.\n */\n return prototype === null || prototype.hasOwnProperty('isPrototypeOf')\n}\n"],"names":["getObjectClassLabel","isPlainObject","value","Object","prototype","toString","call","getPrototypeOf","hasOwnProperty"],"mappings":";;;;;;;;;;;;;;;IAAgBA,mBAAmB;eAAnBA;;IAIAC,aAAa;eAAbA;;;AAJT,SAASD,oBAAoBE,KAAU;IAC5C,OAAOC,OAAOC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACJ;AACxC;AAEO,SAASD,cAAcC,KAAU;IACtC,IAAIF,oBAAoBE,WAAW,mBAAmB;QACpD,OAAO;IACT;IAEA,MAAME,YAAYD,OAAOI,cAAc,CAACL;IAExC;;;;;;;;GAQC,GACD,OAAOE,cAAc,QAAQA,UAAUI,cAAc,CAAC;AACxD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/is-thenable.d.ts b/e-commerce/node_modules/next/dist/shared/lib/is-thenable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed40f14bd81dacd477f66291bf236a06a88bc1ca --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/is-thenable.d.ts @@ -0,0 +1,7 @@ +/** + * Check to see if a value is Thenable. + * + * @param promise the maybe-thenable value + * @returns true if the value is thenable + */ +export declare function isThenable<T = unknown>(promise: Promise<T> | T): promise is Promise<T>; diff --git a/e-commerce/node_modules/next/dist/shared/lib/is-thenable.js b/e-commerce/node_modules/next/dist/shared/lib/is-thenable.js new file mode 100644 index 0000000000000000000000000000000000000000..0273fda12cbca9e44fd00454d4a4eeefe1cb6676 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/is-thenable.js @@ -0,0 +1,20 @@ +/** + * Check to see if a value is Thenable. + * + * @param promise the maybe-thenable value + * @returns true if the value is thenable + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isThenable", { + enumerable: true, + get: function() { + return isThenable; + } +}); +function isThenable(promise) { + return promise !== null && typeof promise === 'object' && 'then' in promise && typeof promise.then === 'function'; +} + +//# sourceMappingURL=is-thenable.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/is-thenable.js.map b/e-commerce/node_modules/next/dist/shared/lib/is-thenable.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0f4f0a891c2aa15fa8bb6b8847c6b252c9b8ed43 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/is-thenable.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/is-thenable.ts"],"sourcesContent":["/**\n * Check to see if a value is Thenable.\n *\n * @param promise the maybe-thenable value\n * @returns true if the value is thenable\n */\nexport function isThenable<T = unknown>(\n promise: Promise<T> | T\n): promise is Promise<T> {\n return (\n promise !== null &&\n typeof promise === 'object' &&\n 'then' in promise &&\n typeof promise.then === 'function'\n )\n}\n"],"names":["isThenable","promise","then"],"mappings":"AAAA;;;;;CAKC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,WACdC,OAAuB;IAEvB,OACEA,YAAY,QACZ,OAAOA,YAAY,YACnB,UAAUA,WACV,OAAOA,QAAQC,IAAI,KAAK;AAE5B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/isomorphic/path.d.ts b/e-commerce/node_modules/next/dist/shared/lib/isomorphic/path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..74050d397f4d2774aa36d60c984d8de0fb1d56f1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/isomorphic/path.d.ts @@ -0,0 +1 @@ +export { default } from 'path' diff --git a/e-commerce/node_modules/next/dist/shared/lib/isomorphic/path.js b/e-commerce/node_modules/next/dist/shared/lib/isomorphic/path.js new file mode 100644 index 0000000000000000000000000000000000000000..c8576c72b5130c11059bd07303c4c9ff8e9ae1cd --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/isomorphic/path.js @@ -0,0 +1,14 @@ +/** + * This module is for next.js server internal usage of path module. + * It will use native path module for nodejs runtime. + * It will use path-browserify polyfill for edge runtime. + */ "use strict"; +let path; +if (process.env.NEXT_RUNTIME === 'edge') { + path = require('next/dist/compiled/path-browserify'); +} else { + path = require('path'); +} +module.exports = path; + +//# sourceMappingURL=path.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/isomorphic/path.js.map b/e-commerce/node_modules/next/dist/shared/lib/isomorphic/path.js.map new file mode 100644 index 0000000000000000000000000000000000000000..20a377d2a9d079e24bb1389366801878acf2a506 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/isomorphic/path.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/isomorphic/path.js"],"sourcesContent":["/**\n * This module is for next.js server internal usage of path module.\n * It will use native path module for nodejs runtime.\n * It will use path-browserify polyfill for edge runtime.\n */\nlet path\n\nif (process.env.NEXT_RUNTIME === 'edge') {\n path = require('next/dist/compiled/path-browserify')\n} else {\n path = require('path')\n}\n\nmodule.exports = path\n"],"names":["path","process","env","NEXT_RUNTIME","require","module","exports"],"mappings":"AAAA;;;;CAIC;AACD,IAAIA;AAEJ,IAAIC,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;IACvCH,OAAOI,QAAQ;AACjB,OAAO;IACLJ,OAAOI,QAAQ;AACjB;AAEAC,OAAOC,OAAO,GAAGN","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/bailout-to-csr.d.ts b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/bailout-to-csr.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d671f26dfe0c6fb641e02e8215ff0431eb847ac4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/bailout-to-csr.d.ts @@ -0,0 +1,8 @@ +/** An error that should be thrown when we want to bail out to client-side rendering. */ +export declare class BailoutToCSRError extends Error { + readonly reason: string; + readonly digest = "BAILOUT_TO_CLIENT_SIDE_RENDERING"; + constructor(reason: string); +} +/** Checks if a passed argument is an error that is thrown if we want to bail out to client-side rendering. */ +export declare function isBailoutToCSRError(err: unknown): err is BailoutToCSRError; diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/bailout-to-csr.js b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/bailout-to-csr.js new file mode 100644 index 0000000000000000000000000000000000000000..9a0cd676c4302274d2e57b853975846ef82b27be --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/bailout-to-csr.js @@ -0,0 +1,37 @@ +// This has to be a shared module which is shared between client component error boundary and dynamic component +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + BailoutToCSRError: null, + isBailoutToCSRError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + BailoutToCSRError: function() { + return BailoutToCSRError; + }, + isBailoutToCSRError: function() { + return isBailoutToCSRError; + } +}); +const BAILOUT_TO_CSR = 'BAILOUT_TO_CLIENT_SIDE_RENDERING'; +class BailoutToCSRError extends Error { + constructor(reason){ + super(`Bail out to client-side rendering: ${reason}`), this.reason = reason, this.digest = BAILOUT_TO_CSR; + } +} +function isBailoutToCSRError(err) { + if (typeof err !== 'object' || err === null || !('digest' in err)) { + return false; + } + return err.digest === BAILOUT_TO_CSR; +} + +//# sourceMappingURL=bailout-to-csr.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/bailout-to-csr.js.map b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/bailout-to-csr.js.map new file mode 100644 index 0000000000000000000000000000000000000000..006e40b001aa41cc811970d4ac0c85a529b8153a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/bailout-to-csr.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/lazy-dynamic/bailout-to-csr.ts"],"sourcesContent":["// This has to be a shared module which is shared between client component error boundary and dynamic component\nconst BAILOUT_TO_CSR = 'BAILOUT_TO_CLIENT_SIDE_RENDERING'\n\n/** An error that should be thrown when we want to bail out to client-side rendering. */\nexport class BailoutToCSRError extends Error {\n public readonly digest = BAILOUT_TO_CSR\n\n constructor(public readonly reason: string) {\n super(`Bail out to client-side rendering: ${reason}`)\n }\n}\n\n/** Checks if a passed argument is an error that is thrown if we want to bail out to client-side rendering. */\nexport function isBailoutToCSRError(err: unknown): err is BailoutToCSRError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === BAILOUT_TO_CSR\n}\n"],"names":["BailoutToCSRError","isBailoutToCSRError","BAILOUT_TO_CSR","Error","constructor","reason","digest","err"],"mappings":"AAAA,+GAA+G;;;;;;;;;;;;;;;;IAIlGA,iBAAiB;eAAjBA;;IASGC,mBAAmB;eAAnBA;;;AAZhB,MAAMC,iBAAiB;AAGhB,MAAMF,0BAA0BG;IAGrCC,YAAY,AAAgBC,MAAc,CAAE;QAC1C,KAAK,CAAC,CAAC,mCAAmC,EAAEA,QAAQ,QAD1BA,SAAAA,aAFZC,SAASJ;IAIzB;AACF;AAGO,SAASD,oBAAoBM,GAAY;IAC9C,IAAI,OAAOA,QAAQ,YAAYA,QAAQ,QAAQ,CAAE,CAAA,YAAYA,GAAE,GAAI;QACjE,OAAO;IACT;IAEA,OAAOA,IAAID,MAAM,KAAKJ;AACxB","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.d.ts b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3f03a10b9958f041b9c1ef6e9d2826ba52d8760 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.d.ts @@ -0,0 +1,9 @@ +import { type ReactElement } from 'react'; +interface BailoutToCSRForNextDynamicProps { + children: ReactElement; +} +/** + * Signals during server rendering that this subtree should be client-rendered. + */ +export declare function BailoutToCSRForNextDynamic({ children, }: BailoutToCSRForNextDynamicProps): ReactElement<unknown, string | import("react").JSXElementConstructor<any>>; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.js b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.js new file mode 100644 index 0000000000000000000000000000000000000000..481557fa5119f3dcf33013f43b374c7434301101 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.js @@ -0,0 +1,30 @@ +'use client'; +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "BailoutToCSRForNextDynamic", { + enumerable: true, + get: function() { + return BailoutToCSRForNextDynamic; + } +}); +const _react = require("react"); +const _reactdom = require("react-dom"); +const _bailouttocsr = require("./bailout-to-csr"); +const _reactbrowserbailout = require("./react-browser-bailout"); +const NEXT_DYNAMIC_BAILOUT_REASON = 'next/dynamic'; +const getNextDynamicBailoutReason = _reactbrowserbailout.createReactBrowserBailoutReason.bind(null, NEXT_DYNAMIC_BAILOUT_REASON); +function BailoutToCSRForNextDynamic({ children }) { + if (process.env.__NEXT_EXPERIMENTAL_REACT_BROWSER_BAILOUT) { + // @ts-expect-error TODO: Update @types/react-dom to include the reason argument. + (0, _react.use)((0, _reactdom.browser)(getNextDynamicBailoutReason)); + return children; + } + if (typeof window === 'undefined') { + throw new _bailouttocsr.BailoutToCSRError(NEXT_DYNAMIC_BAILOUT_REASON); + } + return children; +} + +//# sourceMappingURL=dynamic-bailout-to-csr.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.js.map b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.js.map new file mode 100644 index 0000000000000000000000000000000000000000..954f8b28afbfd17a2f80063ca8d43c6438c6e81a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.tsx"],"sourcesContent":["'use client'\n\nimport { use, type ReactElement } from 'react'\nimport { browser } from 'react-dom'\nimport { BailoutToCSRError } from './bailout-to-csr'\nimport { createReactBrowserBailoutReason } from './react-browser-bailout'\n\ninterface BailoutToCSRForNextDynamicProps {\n children: ReactElement\n}\n\nconst NEXT_DYNAMIC_BAILOUT_REASON = 'next/dynamic'\nconst getNextDynamicBailoutReason = createReactBrowserBailoutReason.bind(\n null,\n NEXT_DYNAMIC_BAILOUT_REASON\n)\n\n/**\n * Signals during server rendering that this subtree should be client-rendered.\n */\nexport function BailoutToCSRForNextDynamic({\n children,\n}: BailoutToCSRForNextDynamicProps) {\n if (process.env.__NEXT_EXPERIMENTAL_REACT_BROWSER_BAILOUT) {\n // @ts-expect-error TODO: Update @types/react-dom to include the reason argument.\n use(browser(getNextDynamicBailoutReason))\n return children\n }\n\n if (typeof window === 'undefined') {\n throw new BailoutToCSRError(NEXT_DYNAMIC_BAILOUT_REASON)\n }\n\n return children\n}\n"],"names":["BailoutToCSRForNextDynamic","NEXT_DYNAMIC_BAILOUT_REASON","getNextDynamicBailoutReason","createReactBrowserBailoutReason","bind","children","process","env","__NEXT_EXPERIMENTAL_REACT_BROWSER_BAILOUT","use","browser","window","BailoutToCSRError"],"mappings":"AAAA;;;;;+BAoBgBA;;;eAAAA;;;uBAlBuB;0BACf;8BACU;qCACc;AAMhD,MAAMC,8BAA8B;AACpC,MAAMC,8BAA8BC,oDAA+B,CAACC,IAAI,CACtE,MACAH;AAMK,SAASD,2BAA2B,EACzCK,QAAQ,EACwB;IAChC,IAAIC,QAAQC,GAAG,CAACC,yCAAyC,EAAE;QACzD,iFAAiF;QACjFC,IAAAA,UAAG,EAACC,IAAAA,iBAAO,EAACR;QACZ,OAAOG;IACT;IAEA,IAAI,OAAOM,WAAW,aAAa;QACjC,MAAM,IAAIC,+BAAiB,CAACX;IAC9B;IAEA,OAAOI;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/loadable.d.ts b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/loadable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd02bc43c38dffb0051cf439359cb0712341d4e6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/loadable.d.ts @@ -0,0 +1,12 @@ +import type { ComponentModule } from './types'; +interface LoadableOptions { + loader?: () => Promise<React.ComponentType<any> | ComponentModule<any>>; + loading?: React.ComponentType<any> | null; + ssr?: boolean; + modules?: string[]; +} +declare function Loadable(options: LoadableOptions): { + (props: any): import("react").JSX.Element; + displayName: string; +}; +export default Loadable; diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/loadable.js b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/loadable.js new file mode 100644 index 0000000000000000000000000000000000000000..28cc4c126ddf929f579e12f53ea87c963d95ba69 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/loadable.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _jsxruntime = require("react/jsx-runtime"); +const _react = require("react"); +const _dynamicbailouttocsr = require("./dynamic-bailout-to-csr"); +const _preloadchunks = require("./preload-chunks"); +// Normalize loader to return the module as form { default: Component } for `React.lazy`. +// Also for backward compatible since next/dynamic allows to resolve a component directly with loader +// Client component reference proxy need to be converted to a module. +function convertModule(mod) { + // Check "default" prop before accessing it, as it could be client reference proxy that could break it reference. + // Cases: + // mod: { default: Component } + // mod: Component + // mod: { default: proxy(Component) } + // mod: proxy(Component) + const hasDefault = mod && 'default' in mod; + return { + default: hasDefault ? mod.default : mod + }; +} +const defaultOptions = { + loader: ()=>Promise.resolve(convertModule(()=>null)), + loading: null, + ssr: true +}; +function Loadable(options) { + const opts = { + ...defaultOptions, + ...options + }; + const Lazy = /*#__PURE__*/ (0, _react.lazy)(()=>opts.loader().then(convertModule)); + const Loading = opts.loading; + function LoadableComponent(props) { + const fallbackElement = Loading ? /*#__PURE__*/ (0, _jsxruntime.jsx)(Loading, { + isLoading: true, + pastDelay: true, + error: null + }) : null; + // If it's non-SSR or provided a loading component, wrap it in a suspense boundary + const hasSuspenseBoundary = !opts.ssr || !!opts.loading; + const Wrap = hasSuspenseBoundary ? _react.Suspense : _react.Fragment; + const wrapProps = hasSuspenseBoundary ? { + fallback: fallbackElement + } : {}; + const children = opts.ssr ? /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, { + children: [ + typeof window === 'undefined' ? /*#__PURE__*/ (0, _jsxruntime.jsx)(_preloadchunks.PreloadChunks, { + moduleIds: opts.modules + }) : null, + /*#__PURE__*/ (0, _jsxruntime.jsx)(Lazy, { + ...props + }) + ] + }) : /*#__PURE__*/ (0, _jsxruntime.jsx)(_dynamicbailouttocsr.BailoutToCSRForNextDynamic, { + children: /*#__PURE__*/ (0, _jsxruntime.jsx)(Lazy, { + ...props + }) + }); + return /*#__PURE__*/ (0, _jsxruntime.jsx)(Wrap, { + ...wrapProps, + children: children + }); + } + LoadableComponent.displayName = 'LoadableComponent'; + return LoadableComponent; +} +const _default = Loadable; + +//# sourceMappingURL=loadable.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/loadable.js.map b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/loadable.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d58421822674647c194d5642acd97d4458c59c8c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/loadable.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/lazy-dynamic/loadable.tsx"],"sourcesContent":["import { Suspense, Fragment, lazy } from 'react'\nimport { BailoutToCSRForNextDynamic } from './dynamic-bailout-to-csr'\nimport type { ComponentModule } from './types'\nimport { PreloadChunks } from './preload-chunks'\n\n// Normalize loader to return the module as form { default: Component } for `React.lazy`.\n// Also for backward compatible since next/dynamic allows to resolve a component directly with loader\n// Client component reference proxy need to be converted to a module.\nfunction convertModule<P>(\n mod: React.ComponentType<P> | ComponentModule<P> | undefined\n): {\n default: React.ComponentType<P>\n} {\n // Check \"default\" prop before accessing it, as it could be client reference proxy that could break it reference.\n // Cases:\n // mod: { default: Component }\n // mod: Component\n // mod: { default: proxy(Component) }\n // mod: proxy(Component)\n const hasDefault = mod && 'default' in mod\n return {\n default: hasDefault\n ? (mod as ComponentModule<P>).default\n : (mod as React.ComponentType<P>),\n }\n}\n\nconst defaultOptions = {\n loader: () => Promise.resolve(convertModule(() => null)),\n loading: null,\n ssr: true,\n}\n\ninterface LoadableOptions {\n loader?: () => Promise<React.ComponentType<any> | ComponentModule<any>>\n loading?: React.ComponentType<any> | null\n ssr?: boolean\n modules?: string[]\n}\n\nfunction Loadable(options: LoadableOptions) {\n const opts = { ...defaultOptions, ...options }\n const Lazy = lazy(() => opts.loader().then(convertModule))\n const Loading = opts.loading\n\n function LoadableComponent(props: any) {\n const fallbackElement = Loading ? (\n <Loading isLoading={true} pastDelay={true} error={null} />\n ) : null\n\n // If it's non-SSR or provided a loading component, wrap it in a suspense boundary\n const hasSuspenseBoundary = !opts.ssr || !!opts.loading\n const Wrap = hasSuspenseBoundary ? Suspense : Fragment\n const wrapProps = hasSuspenseBoundary ? { fallback: fallbackElement } : {}\n const children = opts.ssr ? (\n <>\n {/* During SSR, we need to preload the CSS from the dynamic component to avoid flash of unstyled content */}\n {typeof window === 'undefined' ? (\n <PreloadChunks moduleIds={opts.modules} />\n ) : null}\n <Lazy {...props} />\n </>\n ) : (\n <BailoutToCSRForNextDynamic>\n <Lazy {...props} />\n </BailoutToCSRForNextDynamic>\n )\n\n return <Wrap {...wrapProps}>{children}</Wrap>\n }\n\n LoadableComponent.displayName = 'LoadableComponent'\n\n return LoadableComponent\n}\n\nexport default Loadable\n"],"names":["convertModule","mod","hasDefault","default","defaultOptions","loader","Promise","resolve","loading","ssr","Loadable","options","opts","Lazy","lazy","then","Loading","LoadableComponent","props","fallbackElement","isLoading","pastDelay","error","hasSuspenseBoundary","Wrap","Suspense","Fragment","wrapProps","fallback","children","window","PreloadChunks","moduleIds","modules","BailoutToCSRForNextDynamic","displayName"],"mappings":";;;;+BA4EA;;;eAAA;;;;uBA5EyC;qCACE;+BAEb;AAE9B,yFAAyF;AACzF,qGAAqG;AACrG,qEAAqE;AACrE,SAASA,cACPC,GAA4D;IAI5D,iHAAiH;IACjH,SAAS;IACT,8BAA8B;IAC9B,iBAAiB;IACjB,qCAAqC;IACrC,wBAAwB;IACxB,MAAMC,aAAaD,OAAO,aAAaA;IACvC,OAAO;QACLE,SAASD,aACL,AAACD,IAA2BE,OAAO,GAClCF;IACP;AACF;AAEA,MAAMG,iBAAiB;IACrBC,QAAQ,IAAMC,QAAQC,OAAO,CAACP,cAAc,IAAM;IAClDQ,SAAS;IACTC,KAAK;AACP;AASA,SAASC,SAASC,OAAwB;IACxC,MAAMC,OAAO;QAAE,GAAGR,cAAc;QAAE,GAAGO,OAAO;IAAC;IAC7C,MAAME,qBAAOC,IAAAA,WAAI,EAAC,IAAMF,KAAKP,MAAM,GAAGU,IAAI,CAACf;IAC3C,MAAMgB,UAAUJ,KAAKJ,OAAO;IAE5B,SAASS,kBAAkBC,KAAU;QACnC,MAAMC,kBAAkBH,wBACtB,qBAACA;YAAQI,WAAW;YAAMC,WAAW;YAAMC,OAAO;aAChD;QAEJ,kFAAkF;QAClF,MAAMC,sBAAsB,CAACX,KAAKH,GAAG,IAAI,CAAC,CAACG,KAAKJ,OAAO;QACvD,MAAMgB,OAAOD,sBAAsBE,eAAQ,GAAGC,eAAQ;QACtD,MAAMC,YAAYJ,sBAAsB;YAAEK,UAAUT;QAAgB,IAAI,CAAC;QACzE,MAAMU,WAAWjB,KAAKH,GAAG,iBACvB;;gBAEG,OAAOqB,WAAW,4BACjB,qBAACC,4BAAa;oBAACC,WAAWpB,KAAKqB,OAAO;qBACpC;8BACJ,qBAACpB;oBAAM,GAAGK,KAAK;;;2BAGjB,qBAACgB,+CAA0B;sBACzB,cAAA,qBAACrB;gBAAM,GAAGK,KAAK;;;QAInB,qBAAO,qBAACM;YAAM,GAAGG,SAAS;sBAAGE;;IAC/B;IAEAZ,kBAAkBkB,WAAW,GAAG;IAEhC,OAAOlB;AACT;MAEA,WAAeP","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/preload-chunks.d.ts b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/preload-chunks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0acb82d8f338f9f4ac2a09c3dfd5ee5392345350 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/preload-chunks.d.ts @@ -0,0 +1,3 @@ +export declare function PreloadChunks({ moduleIds, }: { + moduleIds: string[] | undefined; +}): import("react").JSX.Element | null; diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/preload-chunks.js b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/preload-chunks.js new file mode 100644 index 0000000000000000000000000000000000000000..ddbdc223a2e6f9ef0502a16ade34122d62f595b9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/preload-chunks.js @@ -0,0 +1,70 @@ +'use client'; +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "PreloadChunks", { + enumerable: true, + get: function() { + return PreloadChunks; + } +}); +const _jsxruntime = require("react/jsx-runtime"); +const _reactdom = require("react-dom"); +const _workasyncstorageexternal = require("../../../server/app-render/work-async-storage.external"); +const _encodeuripath = require("../encode-uri-path"); +const _deploymentid = require("../deployment-id"); +function PreloadChunks({ moduleIds }) { + // Early return in client compilation and only load requestStore on server side + if (typeof window !== 'undefined') { + return null; + } + const workStore = _workasyncstorageexternal.workAsyncStorage.getStore(); + if (workStore === undefined) { + return null; + } + const allFiles = []; + // Search the current dynamic call unique key id in react loadable manifest, + // and find the corresponding CSS files to preload + if (workStore.reactLoadableManifest && moduleIds) { + const manifest = workStore.reactLoadableManifest; + for (const key of moduleIds){ + if (!manifest[key]) continue; + const chunks = manifest[key].files; + allFiles.push(...chunks); + } + } + if (allFiles.length === 0) { + return null; + } + const query = (0, _deploymentid.getAssetTokenQuery)(); + return /*#__PURE__*/ (0, _jsxruntime.jsx)(_jsxruntime.Fragment, { + children: allFiles.map((chunk)=>{ + const href = `${workStore.assetPrefix}/_next/${(0, _encodeuripath.encodeURIPath)(chunk)}${query}`; + const isCss = chunk.endsWith('.css'); + // If it's stylesheet we use `precedence` o help hoist with React Float. + // For stylesheets we actually need to render the CSS because nothing else is going to do it so it needs to be part of the component tree. + // The `preload` for stylesheet is not optional. + if (isCss) { + return /*#__PURE__*/ (0, _jsxruntime.jsx)("link", { + // @ts-ignore + precedence: "dynamic", + href: href, + rel: "stylesheet", + as: "style", + nonce: workStore.nonce + }, chunk); + } else { + // If it's script we use ReactDOM.preload to preload the resources + (0, _reactdom.preload)(href, { + as: 'script', + fetchPriority: 'low', + nonce: workStore.nonce + }); + return null; + } + }) + }); +} + +//# sourceMappingURL=preload-chunks.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/preload-chunks.js.map b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/preload-chunks.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4e37016b8ea4014bb8f14be39c7c8c9b0dcfc101 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/preload-chunks.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/lazy-dynamic/preload-chunks.tsx"],"sourcesContent":["'use client'\n\nimport { preload } from 'react-dom'\n\nimport { workAsyncStorage } from '../../../server/app-render/work-async-storage.external'\nimport { encodeURIPath } from '../encode-uri-path'\nimport { getAssetTokenQuery } from '../deployment-id'\n\nexport function PreloadChunks({\n moduleIds,\n}: {\n moduleIds: string[] | undefined\n}) {\n // Early return in client compilation and only load requestStore on server side\n if (typeof window !== 'undefined') {\n return null\n }\n\n const workStore = workAsyncStorage.getStore()\n if (workStore === undefined) {\n return null\n }\n\n const allFiles = []\n\n // Search the current dynamic call unique key id in react loadable manifest,\n // and find the corresponding CSS files to preload\n if (workStore.reactLoadableManifest && moduleIds) {\n const manifest = workStore.reactLoadableManifest\n for (const key of moduleIds) {\n if (!manifest[key]) continue\n const chunks = manifest[key].files\n allFiles.push(...chunks)\n }\n }\n\n if (allFiles.length === 0) {\n return null\n }\n\n const query = getAssetTokenQuery()\n\n return (\n <>\n {allFiles.map((chunk) => {\n const href = `${workStore.assetPrefix}/_next/${encodeURIPath(chunk)}${query}`\n const isCss = chunk.endsWith('.css')\n // If it's stylesheet we use `precedence` o help hoist with React Float.\n // For stylesheets we actually need to render the CSS because nothing else is going to do it so it needs to be part of the component tree.\n // The `preload` for stylesheet is not optional.\n if (isCss) {\n return (\n <link\n key={chunk}\n // @ts-ignore\n precedence=\"dynamic\"\n href={href}\n rel=\"stylesheet\"\n as=\"style\"\n nonce={workStore.nonce}\n />\n )\n } else {\n // If it's script we use ReactDOM.preload to preload the resources\n preload(href, {\n as: 'script',\n fetchPriority: 'low',\n nonce: workStore.nonce,\n })\n return null\n }\n })}\n </>\n )\n}\n"],"names":["PreloadChunks","moduleIds","window","workStore","workAsyncStorage","getStore","undefined","allFiles","reactLoadableManifest","manifest","key","chunks","files","push","length","query","getAssetTokenQuery","map","chunk","href","assetPrefix","encodeURIPath","isCss","endsWith","link","precedence","rel","as","nonce","preload","fetchPriority"],"mappings":"AAAA;;;;;+BAQgBA;;;eAAAA;;;;0BANQ;0CAES;+BACH;8BACK;AAE5B,SAASA,cAAc,EAC5BC,SAAS,EAGV;IACC,+EAA+E;IAC/E,IAAI,OAAOC,WAAW,aAAa;QACjC,OAAO;IACT;IAEA,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAIF,cAAcG,WAAW;QAC3B,OAAO;IACT;IAEA,MAAMC,WAAW,EAAE;IAEnB,4EAA4E;IAC5E,kDAAkD;IAClD,IAAIJ,UAAUK,qBAAqB,IAAIP,WAAW;QAChD,MAAMQ,WAAWN,UAAUK,qBAAqB;QAChD,KAAK,MAAME,OAAOT,UAAW;YAC3B,IAAI,CAACQ,QAAQ,CAACC,IAAI,EAAE;YACpB,MAAMC,SAASF,QAAQ,CAACC,IAAI,CAACE,KAAK;YAClCL,SAASM,IAAI,IAAIF;QACnB;IACF;IAEA,IAAIJ,SAASO,MAAM,KAAK,GAAG;QACzB,OAAO;IACT;IAEA,MAAMC,QAAQC,IAAAA,gCAAkB;IAEhC,qBACE;kBACGT,SAASU,GAAG,CAAC,CAACC;YACb,MAAMC,OAAO,GAAGhB,UAAUiB,WAAW,CAAC,OAAO,EAAEC,IAAAA,4BAAa,EAACH,SAASH,OAAO;YAC7E,MAAMO,QAAQJ,MAAMK,QAAQ,CAAC;YAC7B,wEAAwE;YACxE,0IAA0I;YAC1I,gDAAgD;YAChD,IAAID,OAAO;gBACT,qBACE,qBAACE;oBAEC,aAAa;oBACbC,YAAW;oBACXN,MAAMA;oBACNO,KAAI;oBACJC,IAAG;oBACHC,OAAOzB,UAAUyB,KAAK;mBANjBV;YASX,OAAO;gBACL,kEAAkE;gBAClEW,IAAAA,iBAAO,EAACV,MAAM;oBACZQ,IAAI;oBACJG,eAAe;oBACfF,OAAOzB,UAAUyB,KAAK;gBACxB;gBACA,OAAO;YACT;QACF;;AAGN","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.d.ts b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f35aff96ae809c064b69effe753627d460e4cdf9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.d.ts @@ -0,0 +1,8 @@ +type ReactBrowserBailoutReason = { + $$typeof: symbol; + reason: string; +}; +export declare function createReactBrowserBailoutReason(reason: string): ReactBrowserBailoutReason; +export declare function getReactBrowserBailoutReason(error: unknown): string | undefined; +export declare function isNextBrowserBailoutError(error: unknown): boolean; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.js b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.js new file mode 100644 index 0000000000000000000000000000000000000000..4d6eeab8322c0a3e9e35673ed3b420e4621fa25c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.js @@ -0,0 +1,45 @@ +// This module is bundled separately into user code and the precompiled App +// Router runtime. Use the global symbol registry so both copies recognize the +// same browser bailout reason. +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + createReactBrowserBailoutReason: null, + getReactBrowserBailoutReason: null, + isNextBrowserBailoutError: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + createReactBrowserBailoutReason: function() { + return createReactBrowserBailoutReason; + }, + getReactBrowserBailoutReason: function() { + return getReactBrowserBailoutReason; + }, + isNextBrowserBailoutError: function() { + return isNextBrowserBailoutError; + } +}); +const REACT_BROWSER_BAILOUT_REASON = Symbol.for('next.browser-bailout-reason'); +function createReactBrowserBailoutReason(reason) { + return { + $$typeof: REACT_BROWSER_BAILOUT_REASON, + reason + }; +} +function getReactBrowserBailoutReason(error) { + const cause = error?.cause; + return cause?.$$typeof === REACT_BROWSER_BAILOUT_REASON ? cause.reason : undefined; +} +function isNextBrowserBailoutError(error) { + return getReactBrowserBailoutReason(error) !== undefined; +} + +//# sourceMappingURL=react-browser-bailout.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.js.map b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.js.map new file mode 100644 index 0000000000000000000000000000000000000000..90d6ca26a8cce0404d9e14f074a630d3e847f812 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/lazy-dynamic/react-browser-bailout.ts"],"sourcesContent":["// This module is bundled separately into user code and the precompiled App\n// Router runtime. Use the global symbol registry so both copies recognize the\n// same browser bailout reason.\nconst REACT_BROWSER_BAILOUT_REASON = Symbol.for('next.browser-bailout-reason')\n\ntype ReactBrowserBailoutReason = {\n $$typeof: symbol\n reason: string\n}\n\nexport function createReactBrowserBailoutReason(\n reason: string\n): ReactBrowserBailoutReason {\n return {\n $$typeof: REACT_BROWSER_BAILOUT_REASON,\n reason,\n }\n}\n\nexport function getReactBrowserBailoutReason(\n error: unknown\n): string | undefined {\n const cause = (error as Error)?.cause as ReactBrowserBailoutReason | undefined\n\n return cause?.$$typeof === REACT_BROWSER_BAILOUT_REASON\n ? cause.reason\n : undefined\n}\n\nexport function isNextBrowserBailoutError(error: unknown): boolean {\n return getReactBrowserBailoutReason(error) !== undefined\n}\n"],"names":["createReactBrowserBailoutReason","getReactBrowserBailoutReason","isNextBrowserBailoutError","REACT_BROWSER_BAILOUT_REASON","Symbol","for","reason","$$typeof","error","cause","undefined"],"mappings":"AAAA,2EAA2E;AAC3E,8EAA8E;AAC9E,+BAA+B;;;;;;;;;;;;;;;;;IAQfA,+BAA+B;eAA/BA;;IASAC,4BAA4B;eAA5BA;;IAUAC,yBAAyB;eAAzBA;;;AA1BhB,MAAMC,+BAA+BC,OAAOC,GAAG,CAAC;AAOzC,SAASL,gCACdM,MAAc;IAEd,OAAO;QACLC,UAAUJ;QACVG;IACF;AACF;AAEO,SAASL,6BACdO,KAAc;IAEd,MAAMC,QAASD,OAAiBC;IAEhC,OAAOA,OAAOF,aAAaJ,+BACvBM,MAAMH,MAAM,GACZI;AACN;AAEO,SAASR,0BAA0BM,KAAc;IACtD,OAAOP,6BAA6BO,WAAWE;AACjD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/types.d.ts b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..80856d10233c8e27b06afca880e622cde00a22be --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/types.d.ts @@ -0,0 +1,15 @@ +export type ComponentModule<P = {}> = { + default: React.ComponentType<P>; +}; +export declare type LoaderComponent<P = {}> = Promise<React.ComponentType<P> | ComponentModule<P>>; +export declare type Loader<P = {}> = () => LoaderComponent<P>; +export type LoadableGeneratedOptions = { + modules?: string[]; +}; +export type DynamicOptionsLoadingProps = { + error?: Error | null; + isLoading?: boolean; + pastDelay?: boolean; + retry?: () => void; + timedOut?: boolean; +}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/types.js b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/types.js new file mode 100644 index 0000000000000000000000000000000000000000..f89b9ccce54e89b62b432c4802c4612600a703d4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/types.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/types.js.map b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/lazy-dynamic/types.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/loadable-context.shared-runtime.d.ts b/e-commerce/node_modules/next/dist/shared/lib/loadable-context.shared-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c21442d0c848454af1c6fb6ede1b201440566f55 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/loadable-context.shared-runtime.d.ts @@ -0,0 +1,4 @@ +import React from 'react'; +type CaptureFn = (moduleName: string) => void; +export declare const LoadableContext: React.Context<CaptureFn | null>; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/loadable-context.shared-runtime.js b/e-commerce/node_modules/next/dist/shared/lib/loadable-context.shared-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..c469e205e15e492b9f1b27024152a658730f2f06 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/loadable-context.shared-runtime.js @@ -0,0 +1,19 @@ +'use client'; +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "LoadableContext", { + enumerable: true, + get: function() { + return LoadableContext; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _react = /*#__PURE__*/ _interop_require_default._(require("react")); +const LoadableContext = _react.default.createContext(null); +if (process.env.NODE_ENV !== 'production') { + LoadableContext.displayName = 'LoadableContext'; +} + +//# sourceMappingURL=loadable-context.shared-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/loadable-context.shared-runtime.js.map b/e-commerce/node_modules/next/dist/shared/lib/loadable-context.shared-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..adbd4587ae0f3f6f1a70ac5f9608844fcd1f957e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/loadable-context.shared-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/loadable-context.shared-runtime.ts"],"sourcesContent":["'use client'\n\nimport React from 'react'\n\ntype CaptureFn = (moduleName: string) => void\n\nexport const LoadableContext = React.createContext<CaptureFn | null>(null)\n\nif (process.env.NODE_ENV !== 'production') {\n LoadableContext.displayName = 'LoadableContext'\n}\n"],"names":["LoadableContext","React","createContext","process","env","NODE_ENV","displayName"],"mappings":"AAAA;;;;;+BAMaA;;;eAAAA;;;;gEAJK;AAIX,MAAMA,kBAAkBC,cAAK,CAACC,aAAa,CAAmB;AAErE,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCL,gBAAgBM,WAAW,GAAG;AAChC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/loadable.shared-runtime.d.ts b/e-commerce/node_modules/next/dist/shared/lib/loadable.shared-runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..17c656b756820744f06425f706be5d0abf1d8593 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/loadable.shared-runtime.d.ts @@ -0,0 +1,32 @@ +/** +@copyright (c) 2017-present James Kyle <me@thejameskyle.com> + MIT License + Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE +*/ +import React from 'react'; +declare function Loadable(opts: any): React.ForwardRefExoticComponent<Omit<any, "ref"> & React.RefAttributes<unknown>>; +declare namespace Loadable { + var preloadAll: () => Promise<unknown>; + var preloadReady: (ids?: (string | number)[]) => Promise<void>; +} +declare global { + interface Window { + __NEXT_PRELOADREADY?: (ids?: (string | number)[]) => Promise<void>; + } +} +export default Loadable; diff --git a/e-commerce/node_modules/next/dist/shared/lib/loadable.shared-runtime.js b/e-commerce/node_modules/next/dist/shared/lib/loadable.shared-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..6dc1a1b44cc6aef54927158f1015891d43916ef7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/loadable.shared-runtime.js @@ -0,0 +1,246 @@ +// TODO: Remove use of `any` type. +/** +@copyright (c) 2017-present James Kyle <me@thejameskyle.com> + MIT License + Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE +*/ // https://github.com/jamiebuilds/react-loadable/blob/v5.5.0/src/index.js +// Modified to be compatible with webpack 4 / Next.js +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _react = /*#__PURE__*/ _interop_require_default._(require("react")); +const _loadablecontextsharedruntime = require("./loadable-context.shared-runtime"); +function resolve(obj) { + return obj && obj.default ? obj.default : obj; +} +const ALL_INITIALIZERS = []; +const READY_INITIALIZERS = []; +let initialized = false; +function load(loader) { + let promise = loader(); + let state = { + loading: true, + loaded: null, + error: null + }; + state.promise = promise.then((loaded)=>{ + state.loading = false; + state.loaded = loaded; + return loaded; + }).catch((err)=>{ + state.loading = false; + state.error = err; + throw err; + }); + return state; +} +function createLoadableComponent(loadFn, options) { + let opts = Object.assign({ + loader: null, + loading: null, + delay: 200, + timeout: null, + webpack: null, + modules: null + }, options); + /** @type LoadableSubscription */ let subscription = null; + function init() { + if (!subscription) { + const sub = new LoadableSubscription(loadFn, opts); + subscription = { + getCurrentValue: sub.getCurrentValue.bind(sub), + subscribe: sub.subscribe.bind(sub), + retry: sub.retry.bind(sub), + promise: sub.promise.bind(sub) + }; + } + return subscription.promise(); + } + // Server only + if (typeof window === 'undefined') { + ALL_INITIALIZERS.push(init); + } + // Client only + if (!initialized && typeof window !== 'undefined') { + // require.resolveWeak check is needed for environments that don't have it available like Jest + const moduleIds = opts.webpack && typeof require.resolveWeak === 'function' ? opts.webpack() : opts.modules; + if (moduleIds) { + READY_INITIALIZERS.push((ids)=>{ + for (const moduleId of moduleIds){ + if (ids.includes(moduleId)) { + return init(); + } + } + }); + } + } + function useLoadableModule() { + init(); + const context = _react.default.useContext(_loadablecontextsharedruntime.LoadableContext); + if (context && Array.isArray(opts.modules)) { + opts.modules.forEach((moduleName)=>{ + context(moduleName); + }); + } + } + function LoadableComponent(props, ref) { + useLoadableModule(); + const state = _react.default.useSyncExternalStore(subscription.subscribe, subscription.getCurrentValue, subscription.getCurrentValue); + _react.default.useImperativeHandle(ref, ()=>({ + retry: subscription.retry + }), []); + return _react.default.useMemo(()=>{ + if (state.loading || state.error) { + return /*#__PURE__*/ _react.default.createElement(opts.loading, { + isLoading: state.loading, + pastDelay: state.pastDelay, + timedOut: state.timedOut, + error: state.error, + retry: subscription.retry + }); + } else if (state.loaded) { + return /*#__PURE__*/ _react.default.createElement(resolve(state.loaded), props); + } else { + return null; + } + }, [ + props, + state + ]); + } + LoadableComponent.preload = ()=>init(); + LoadableComponent.displayName = 'LoadableComponent'; + return /*#__PURE__*/ _react.default.forwardRef(LoadableComponent); +} +class LoadableSubscription { + constructor(loadFn, opts){ + this._loadFn = loadFn; + this._opts = opts; + this._callbacks = new Set(); + this._delay = null; + this._timeout = null; + this.retry(); + } + promise() { + return this._res.promise; + } + retry() { + this._clearTimeouts(); + this._res = this._loadFn(this._opts.loader); + this._state = { + pastDelay: false, + timedOut: false + }; + const { _res: res, _opts: opts } = this; + if (res.loading) { + if (typeof opts.delay === 'number') { + if (opts.delay === 0) { + this._state.pastDelay = true; + } else { + this._delay = setTimeout(()=>{ + this._update({ + pastDelay: true + }); + }, opts.delay); + } + } + if (typeof opts.timeout === 'number') { + this._timeout = setTimeout(()=>{ + this._update({ + timedOut: true + }); + }, opts.timeout); + } + } + this._res.promise.then(()=>{ + this._update({}); + this._clearTimeouts(); + }).catch((_err)=>{ + this._update({}); + this._clearTimeouts(); + }); + this._update({}); + } + _update(partial) { + this._state = { + ...this._state, + error: this._res.error, + loaded: this._res.loaded, + loading: this._res.loading, + ...partial + }; + this._callbacks.forEach((callback)=>callback()); + } + _clearTimeouts() { + clearTimeout(this._delay); + clearTimeout(this._timeout); + } + getCurrentValue() { + return this._state; + } + subscribe(callback) { + this._callbacks.add(callback); + return ()=>{ + this._callbacks.delete(callback); + }; + } +} +function Loadable(opts) { + return createLoadableComponent(load, opts); +} +function flushInitializers(initializers, ids) { + let promises = []; + while(initializers.length){ + let init = initializers.pop(); + promises.push(init(ids)); + } + return Promise.all(promises).then(()=>{ + if (initializers.length) { + return flushInitializers(initializers, ids); + } + }); +} +Loadable.preloadAll = ()=>{ + return new Promise((resolveInitializers, reject)=>{ + flushInitializers(ALL_INITIALIZERS).then(resolveInitializers, reject); + }); +}; +Loadable.preloadReady = (ids = [])=>{ + return new Promise((resolvePreload)=>{ + const res = ()=>{ + initialized = true; + return resolvePreload(); + }; + // We always will resolve, errors should be handled within loading UIs. + flushInitializers(READY_INITIALIZERS, ids).then(res, res); + }); +}; +if (typeof window !== 'undefined') { + window.__NEXT_PRELOADREADY = Loadable.preloadReady; +} +const _default = Loadable; + +//# sourceMappingURL=loadable.shared-runtime.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/loadable.shared-runtime.js.map b/e-commerce/node_modules/next/dist/shared/lib/loadable.shared-runtime.js.map new file mode 100644 index 0000000000000000000000000000000000000000..49bb4635922411c1347c3cd2765082fb48c70b68 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/loadable.shared-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/loadable.shared-runtime.tsx"],"sourcesContent":["// TODO: Remove use of `any` type.\n/**\n@copyright (c) 2017-present James Kyle <me@thejameskyle.com>\n MIT License\n Permission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n The above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE\n*/\n// https://github.com/jamiebuilds/react-loadable/blob/v5.5.0/src/index.js\n// Modified to be compatible with webpack 4 / Next.js\n\nimport React from 'react'\nimport { LoadableContext } from './loadable-context.shared-runtime'\n\nfunction resolve(obj: any) {\n return obj && obj.default ? obj.default : obj\n}\n\nconst ALL_INITIALIZERS: any[] = []\nconst READY_INITIALIZERS: any[] = []\nlet initialized = false\n\nfunction load(loader: any) {\n let promise = loader()\n\n let state: any = {\n loading: true,\n loaded: null,\n error: null,\n }\n\n state.promise = promise\n .then((loaded: any) => {\n state.loading = false\n state.loaded = loaded\n return loaded\n })\n .catch((err: any) => {\n state.loading = false\n state.error = err\n throw err\n })\n\n return state\n}\n\nfunction createLoadableComponent(loadFn: any, options: any) {\n let opts = Object.assign(\n {\n loader: null,\n loading: null,\n delay: 200,\n timeout: null,\n webpack: null,\n modules: null,\n },\n options\n )\n\n /** @type LoadableSubscription */\n let subscription: any = null\n function init() {\n if (!subscription) {\n const sub = new LoadableSubscription(loadFn, opts)\n subscription = {\n getCurrentValue: sub.getCurrentValue.bind(sub),\n subscribe: sub.subscribe.bind(sub),\n retry: sub.retry.bind(sub),\n promise: sub.promise.bind(sub),\n }\n }\n return subscription.promise()\n }\n\n // Server only\n if (typeof window === 'undefined') {\n ALL_INITIALIZERS.push(init)\n }\n\n // Client only\n if (!initialized && typeof window !== 'undefined') {\n // require.resolveWeak check is needed for environments that don't have it available like Jest\n const moduleIds =\n opts.webpack && typeof (require as any).resolveWeak === 'function'\n ? opts.webpack()\n : opts.modules\n if (moduleIds) {\n READY_INITIALIZERS.push((ids: any) => {\n for (const moduleId of moduleIds) {\n if (ids.includes(moduleId)) {\n return init()\n }\n }\n })\n }\n }\n\n function useLoadableModule() {\n init()\n\n const context = React.useContext(LoadableContext)\n if (context && Array.isArray(opts.modules)) {\n opts.modules.forEach((moduleName: any) => {\n context(moduleName)\n })\n }\n }\n\n function LoadableComponent(props: any, ref: any) {\n useLoadableModule()\n\n const state = (React as any).useSyncExternalStore(\n subscription.subscribe,\n subscription.getCurrentValue,\n subscription.getCurrentValue\n )\n\n React.useImperativeHandle(\n ref,\n () => ({\n retry: subscription.retry,\n }),\n []\n )\n\n return React.useMemo(() => {\n if (state.loading || state.error) {\n return React.createElement(opts.loading, {\n isLoading: state.loading,\n pastDelay: state.pastDelay,\n timedOut: state.timedOut,\n error: state.error,\n retry: subscription.retry,\n })\n } else if (state.loaded) {\n return React.createElement(resolve(state.loaded), props)\n } else {\n return null\n }\n }, [props, state])\n }\n\n LoadableComponent.preload = () => init()\n LoadableComponent.displayName = 'LoadableComponent'\n\n return React.forwardRef(LoadableComponent)\n}\n\nclass LoadableSubscription {\n _loadFn: any\n _opts: any\n _callbacks: any\n _delay: any\n _timeout: any\n _res: any\n _state: any\n constructor(loadFn: any, opts: any) {\n this._loadFn = loadFn\n this._opts = opts\n this._callbacks = new Set()\n this._delay = null\n this._timeout = null\n\n this.retry()\n }\n\n promise() {\n return this._res.promise\n }\n\n retry() {\n this._clearTimeouts()\n this._res = this._loadFn(this._opts.loader)\n\n this._state = {\n pastDelay: false,\n timedOut: false,\n }\n\n const { _res: res, _opts: opts } = this\n\n if (res.loading) {\n if (typeof opts.delay === 'number') {\n if (opts.delay === 0) {\n this._state.pastDelay = true\n } else {\n this._delay = setTimeout(() => {\n this._update({\n pastDelay: true,\n })\n }, opts.delay)\n }\n }\n\n if (typeof opts.timeout === 'number') {\n this._timeout = setTimeout(() => {\n this._update({ timedOut: true })\n }, opts.timeout)\n }\n }\n\n this._res.promise\n .then(() => {\n this._update({})\n this._clearTimeouts()\n })\n .catch((_err: any) => {\n this._update({})\n this._clearTimeouts()\n })\n this._update({})\n }\n\n _update(partial: any) {\n this._state = {\n ...this._state,\n error: this._res.error,\n loaded: this._res.loaded,\n loading: this._res.loading,\n ...partial,\n }\n this._callbacks.forEach((callback: any) => callback())\n }\n\n _clearTimeouts() {\n clearTimeout(this._delay)\n clearTimeout(this._timeout)\n }\n\n getCurrentValue() {\n return this._state\n }\n\n subscribe(callback: any) {\n this._callbacks.add(callback)\n return () => {\n this._callbacks.delete(callback)\n }\n }\n}\n\nfunction Loadable(opts: any) {\n return createLoadableComponent(load, opts)\n}\n\nfunction flushInitializers(initializers: any, ids?: any): any {\n let promises = []\n\n while (initializers.length) {\n let init = initializers.pop()\n promises.push(init(ids))\n }\n\n return Promise.all(promises).then(() => {\n if (initializers.length) {\n return flushInitializers(initializers, ids)\n }\n })\n}\n\nLoadable.preloadAll = () => {\n return new Promise((resolveInitializers, reject) => {\n flushInitializers(ALL_INITIALIZERS).then(resolveInitializers, reject)\n })\n}\n\nLoadable.preloadReady = (ids: (string | number)[] = []): Promise<void> => {\n return new Promise<void>((resolvePreload) => {\n const res = () => {\n initialized = true\n return resolvePreload()\n }\n // We always will resolve, errors should be handled within loading UIs.\n flushInitializers(READY_INITIALIZERS, ids).then(res, res)\n })\n}\n\ndeclare global {\n interface Window {\n __NEXT_PRELOADREADY?: (ids?: (string | number)[]) => Promise<void>\n }\n}\n\nif (typeof window !== 'undefined') {\n window.__NEXT_PRELOADREADY = Loadable.preloadReady\n}\n\nexport default Loadable\n"],"names":["resolve","obj","default","ALL_INITIALIZERS","READY_INITIALIZERS","initialized","load","loader","promise","state","loading","loaded","error","then","catch","err","createLoadableComponent","loadFn","options","opts","Object","assign","delay","timeout","webpack","modules","subscription","init","sub","LoadableSubscription","getCurrentValue","bind","subscribe","retry","window","push","moduleIds","require","resolveWeak","ids","moduleId","includes","useLoadableModule","context","React","useContext","LoadableContext","Array","isArray","forEach","moduleName","LoadableComponent","props","ref","useSyncExternalStore","useImperativeHandle","useMemo","createElement","isLoading","pastDelay","timedOut","preload","displayName","forwardRef","constructor","_loadFn","_opts","_callbacks","Set","_delay","_timeout","_res","_clearTimeouts","_state","res","setTimeout","_update","_err","partial","callback","clearTimeout","add","delete","Loadable","flushInitializers","initializers","promises","length","pop","Promise","all","preloadAll","resolveInitializers","reject","preloadReady","resolvePreload","__NEXT_PRELOADREADY"],"mappings":"AAAA,kCAAkC;AAClC;;;;;;;;;;;;;;;;;;;AAmBA,GACA,yEAAyE;AACzE,qDAAqD;;;;;+BAsRrD;;;eAAA;;;;gEApRkB;8CACc;AAEhC,SAASA,QAAQC,GAAQ;IACvB,OAAOA,OAAOA,IAAIC,OAAO,GAAGD,IAAIC,OAAO,GAAGD;AAC5C;AAEA,MAAME,mBAA0B,EAAE;AAClC,MAAMC,qBAA4B,EAAE;AACpC,IAAIC,cAAc;AAElB,SAASC,KAAKC,MAAW;IACvB,IAAIC,UAAUD;IAEd,IAAIE,QAAa;QACfC,SAAS;QACTC,QAAQ;QACRC,OAAO;IACT;IAEAH,MAAMD,OAAO,GAAGA,QACbK,IAAI,CAAC,CAACF;QACLF,MAAMC,OAAO,GAAG;QAChBD,MAAME,MAAM,GAAGA;QACf,OAAOA;IACT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WAAeX","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/magic-identifier.d.ts b/e-commerce/node_modules/next/dist/shared/lib/magic-identifier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe75648137982472871c40043b5d14194eb0c862 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/magic-identifier.d.ts @@ -0,0 +1,30 @@ +export declare function decodeMagicIdentifier(identifier: string): string; +export declare const MAGIC_IDENTIFIER_REGEX: RegExp; +/** + * Cleans up module IDs by removing implementation details. + * - Replaces [project] with . + * - Removes content in brackets [], parentheses (), and angle brackets <> + */ +export declare function deobfuscateModuleId(moduleId: string): string; +/** + * Removes the free call wrapper pattern (0, expr) from expressions. + * This is a JavaScript pattern to call a function without binding 'this', + * but it's noise for developers reading error messages. + */ +export declare function removeFreeCallWrapper(text: string): string; +export type TextPartType = 'raw' | 'deobfuscated'; +/** + * Deobfuscates text and returns an array of discriminated parts. + * Each part is a tuple of [type, string] where type is either 'raw' (unchanged text) + * or 'deobfuscated' (a magic identifier that was decoded). + * + * This is useful when you need to process or display deobfuscated and raw text differently. + */ +export declare function deobfuscateTextParts(text: string): Array<[TextPartType, string]>; +/** + * Deobfuscates text by: + * 1. Decoding magic identifiers + * 2. Cleaning up module IDs + * 3. Removing free call wrappers + */ +export declare function deobfuscateText(text: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/magic-identifier.js b/e-commerce/node_modules/next/dist/shared/lib/magic-identifier.js new file mode 100644 index 0000000000000000000000000000000000000000..7f07cc1401c4ed2d76e3795a38624f477b097542 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/magic-identifier.js @@ -0,0 +1,198 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + MAGIC_IDENTIFIER_REGEX: null, + decodeMagicIdentifier: null, + deobfuscateModuleId: null, + deobfuscateText: null, + deobfuscateTextParts: null, + removeFreeCallWrapper: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + MAGIC_IDENTIFIER_REGEX: function() { + return MAGIC_IDENTIFIER_REGEX; + }, + decodeMagicIdentifier: function() { + return decodeMagicIdentifier; + }, + deobfuscateModuleId: function() { + return deobfuscateModuleId; + }, + deobfuscateText: function() { + return deobfuscateText; + }, + deobfuscateTextParts: function() { + return deobfuscateTextParts; + }, + removeFreeCallWrapper: function() { + return removeFreeCallWrapper; + } +}); +function decodeHex(hexStr) { + if (hexStr.trim() === '') { + throw new Error("can't decode empty hex"); + } + const num = parseInt(hexStr, 16); + if (isNaN(num)) { + throw new Error(`invalid hex: \`${hexStr}\``); + } + return String.fromCodePoint(num); +} +const DECODE_REGEX = /^__TURBOPACK__([a-zA-Z0-9_$]+)__$/; +function decodeMagicIdentifier(identifier) { + const matches = identifier.match(DECODE_REGEX); + if (!matches) { + return identifier; + } + const inner = matches[1]; + let output = ''; + let mode = 0; + let buffer = ''; + for(let i = 0; i < inner.length; i++){ + const char = inner[i]; + if (mode === 0) { + if (char === '_') { + mode = 1; + } else if (char === '$') { + mode = 2; + } else { + output += char; + } + } else if (mode === 1) { + if (char === '_') { + output += ' '; + mode = 0; + } else if (char === '$') { + output += '_'; + mode = 2; + } else { + output += char; + mode = 0; + } + } else if (mode === 2) { + if (buffer.length === 2) { + output += decodeHex(buffer); + buffer = ''; + } + if (char === '_') { + if (buffer !== '') { + throw new Error(`invalid hex: \`${buffer}\``); + } + mode = 3; + } else if (char === '$') { + if (buffer !== '') { + throw new Error(`invalid hex: \`${buffer}\``); + } + mode = 0; + } else { + buffer += char; + } + } else if (mode === 3) { + if (char === '_') { + throw new Error(`invalid hex: \`${buffer + char}\``); + } else if (char === '$') { + output += decodeHex(buffer); + buffer = ''; + mode = 0; + } else { + buffer += char; + } + } + } + return output; +} +const MAGIC_IDENTIFIER_REGEX = /__TURBOPACK__[a-zA-Z0-9_$]+__/g; +function deobfuscateModuleId(moduleId) { + return moduleId// Replace [project] with . + .replace(/\[project\]/g, '.')// Remove content in square brackets (e.g. [app-rsc]) + .replace(/\s\[([^\]]*)\]/g, '')// Remove content in parentheses (e.g. (ecmascript)) + .replace(/\s\(([^)]*)\)/g, '')// Remove content in angle brackets (e.g. <locals>) + .replace(/\s<([^>]*)>/g, '')// Clean up any extra whitespace + .trim(); +} +function removeFreeCallWrapper(text) { + // Match (0, <ident>.<ident>) patterns anywhere in the text the beginning + // Overzealous: accept any non-whitespace member expression after the dot. + // TODO: Fix https://linear.app/vercel/issue/NEXT-4875 to allow using unicode property escapes + return text.replace(/\(0\s*,\s*(__TURBOPACK__[a-zA-Z0-9_$]+__\.[^\s)]+)\)/g, '$1'); +} +function deobfuscateTextParts(text) { + // First, remove free call wrappers + const withoutFreeCall = removeFreeCallWrapper(text); + const parts = []; + let lastIndex = 0; + // Create a new regex instance for global matching + const regex = new RegExp(MAGIC_IDENTIFIER_REGEX.source, 'g'); + for(let match = regex.exec(withoutFreeCall); match !== null; match = regex.exec(withoutFreeCall)){ + const matchStart = match.index; + const matchEnd = regex.lastIndex; + const ident = match[0]; + // Add raw text before this match (if any) + if (matchStart > lastIndex) { + const rawText = withoutFreeCall.substring(lastIndex, matchStart); + parts.push([ + 'raw', + rawText + ]); + } + // Process and add the deobfuscated part + try { + const decoded = decodeMagicIdentifier(ident); + // If it was a magic identifier, clean up the module ID + if (decoded !== ident) { + // Check if this is an "imported module" reference + const importedModuleMatch = decoded.match(/^imported module (.+)$/); + if (importedModuleMatch) { + // Clean the entire module path (which includes [app-rsc], etc.) + const modulePathWithMetadata = importedModuleMatch[1]; + const cleaned = deobfuscateModuleId(modulePathWithMetadata); + parts.push([ + 'deobfuscated', + `{imported module ${cleaned}}` + ]); + } else { + const cleaned = deobfuscateModuleId(decoded); + parts.push([ + 'deobfuscated', + `{${cleaned}}` + ]); + } + } else { + // Not actually a magic identifier, treat as raw + parts.push([ + 'raw', + ident + ]); + } + } catch (e) { + parts.push([ + 'deobfuscated', + `{${ident} (decoding failed: ${e})}` + ]); + } + lastIndex = matchEnd; + } + // Add any remaining raw text after the last match + if (lastIndex < withoutFreeCall.length) { + const rawText = withoutFreeCall.substring(lastIndex); + parts.push([ + 'raw', + rawText + ]); + } + return parts; +} +function deobfuscateText(text) { + const parts = deobfuscateTextParts(text); + return parts.map((part)=>part[1]).join(''); +} + +//# sourceMappingURL=magic-identifier.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/magic-identifier.js.map b/e-commerce/node_modules/next/dist/shared/lib/magic-identifier.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f86f2b37f740fb00f10822aae27b992dad85cbe4 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/magic-identifier.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/magic-identifier.ts"],"sourcesContent":["function decodeHex(hexStr: string): string {\n if (hexStr.trim() === '') {\n throw new Error(\"can't decode empty hex\")\n }\n\n const num = parseInt(hexStr, 16)\n if (isNaN(num)) {\n throw new Error(`invalid hex: \\`${hexStr}\\``)\n }\n\n return String.fromCodePoint(num)\n}\n\nconst enum Mode {\n Text,\n Underscore,\n Hex,\n LongHex,\n}\n\nconst DECODE_REGEX = /^__TURBOPACK__([a-zA-Z0-9_$]+)__$/\n\nexport function decodeMagicIdentifier(identifier: string): string {\n const matches = identifier.match(DECODE_REGEX)\n if (!matches) {\n return identifier\n }\n\n const inner = matches[1]\n\n let output = ''\n\n let mode: Mode = Mode.Text\n let buffer = ''\n for (let i = 0; i < inner.length; i++) {\n const char = inner[i]\n\n if (mode === Mode.Text) {\n if (char === '_') {\n mode = Mode.Underscore\n } else if (char === '$') {\n mode = Mode.Hex\n } else {\n output += char\n }\n } else if (mode === Mode.Underscore) {\n if (char === '_') {\n output += ' '\n mode = Mode.Text\n } else if (char === '$') {\n output += '_'\n mode = Mode.Hex\n } else {\n output += char\n mode = Mode.Text\n }\n } else if (mode === Mode.Hex) {\n if (buffer.length === 2) {\n output += decodeHex(buffer)\n buffer = ''\n }\n\n if (char === '_') {\n if (buffer !== '') {\n throw new Error(`invalid hex: \\`${buffer}\\``)\n }\n\n mode = Mode.LongHex\n } else if (char === '$') {\n if (buffer !== '') {\n throw new Error(`invalid hex: \\`${buffer}\\``)\n }\n\n mode = Mode.Text\n } else {\n buffer += char\n }\n } else if (mode === Mode.LongHex) {\n if (char === '_') {\n throw new Error(`invalid hex: \\`${buffer + char}\\``)\n } else if (char === '$') {\n output += decodeHex(buffer)\n buffer = ''\n\n mode = Mode.Text\n } else {\n buffer += char\n }\n }\n }\n\n return output\n}\n\nexport const MAGIC_IDENTIFIER_REGEX = /__TURBOPACK__[a-zA-Z0-9_$]+__/g\n\n/**\n * Cleans up module IDs by removing implementation details.\n * - Replaces [project] with .\n * - Removes content in brackets [], parentheses (), and angle brackets <>\n */\nexport function deobfuscateModuleId(moduleId: string): string {\n return (\n moduleId\n // Replace [project] with .\n .replace(/\\[project\\]/g, '.')\n // Remove content in square brackets (e.g. [app-rsc])\n .replace(/\\s\\[([^\\]]*)\\]/g, '')\n // Remove content in parentheses (e.g. (ecmascript))\n .replace(/\\s\\(([^)]*)\\)/g, '')\n // Remove content in angle brackets (e.g. <locals>)\n .replace(/\\s<([^>]*)>/g, '')\n // Clean up any extra whitespace\n .trim()\n )\n}\n\n/**\n * Removes the free call wrapper pattern (0, expr) from expressions.\n * This is a JavaScript pattern to call a function without binding 'this',\n * but it's noise for developers reading error messages.\n */\nexport function removeFreeCallWrapper(text: string): string {\n // Match (0, <ident>.<ident>) patterns anywhere in the text the beginning\n // Overzealous: accept any non-whitespace member expression after the dot.\n // TODO: Fix https://linear.app/vercel/issue/NEXT-4875 to allow using unicode property escapes\n return text.replace(\n /\\(0\\s*,\\s*(__TURBOPACK__[a-zA-Z0-9_$]+__\\.[^\\s)]+)\\)/g,\n '$1'\n )\n}\n\nexport type TextPartType = 'raw' | 'deobfuscated'\n\n/**\n * Deobfuscates text and returns an array of discriminated parts.\n * Each part is a tuple of [type, string] where type is either 'raw' (unchanged text)\n * or 'deobfuscated' (a magic identifier that was decoded).\n *\n * This is useful when you need to process or display deobfuscated and raw text differently.\n */\nexport function deobfuscateTextParts(\n text: string\n): Array<[TextPartType, string]> {\n // First, remove free call wrappers\n const withoutFreeCall = removeFreeCallWrapper(text)\n\n const parts: Array<[TextPartType, string]> = []\n let lastIndex = 0\n\n // Create a new regex instance for global matching\n const regex = new RegExp(MAGIC_IDENTIFIER_REGEX.source, 'g')\n\n for (\n let match = regex.exec(withoutFreeCall);\n match !== null;\n match = regex.exec(withoutFreeCall)\n ) {\n const matchStart = match.index\n const matchEnd = regex.lastIndex\n const ident = match[0]\n\n // Add raw text before this match (if any)\n if (matchStart > lastIndex) {\n const rawText = withoutFreeCall.substring(lastIndex, matchStart)\n parts.push(['raw', rawText])\n }\n\n // Process and add the deobfuscated part\n try {\n const decoded = decodeMagicIdentifier(ident)\n // If it was a magic identifier, clean up the module ID\n if (decoded !== ident) {\n // Check if this is an \"imported module\" reference\n const importedModuleMatch = decoded.match(/^imported module (.+)$/)\n if (importedModuleMatch) {\n // Clean the entire module path (which includes [app-rsc], etc.)\n const modulePathWithMetadata = importedModuleMatch[1]\n const cleaned = deobfuscateModuleId(modulePathWithMetadata)\n parts.push(['deobfuscated', `{imported module ${cleaned}}`])\n } else {\n const cleaned = deobfuscateModuleId(decoded)\n parts.push(['deobfuscated', `{${cleaned}}`])\n }\n } else {\n // Not actually a magic identifier, treat as raw\n parts.push(['raw', ident])\n }\n } catch (e) {\n parts.push(['deobfuscated', `{${ident} (decoding failed: ${e})}`])\n }\n\n lastIndex = matchEnd\n }\n\n // Add any remaining raw text after the last match\n if (lastIndex < withoutFreeCall.length) {\n const rawText = withoutFreeCall.substring(lastIndex)\n parts.push(['raw', rawText])\n }\n\n return parts\n}\n\n/**\n * Deobfuscates text by:\n * 1. Decoding magic identifiers\n * 2. Cleaning up module IDs\n * 3. Removing free call wrappers\n */\nexport function deobfuscateText(text: string): string {\n const parts = deobfuscateTextParts(text)\n return parts.map((part) => part[1]).join('')\n}\n"],"names":["MAGIC_IDENTIFIER_REGEX","decodeMagicIdentifier","deobfuscateModuleId","deobfuscateText","deobfuscateTextParts","removeFreeCallWrapper","decodeHex","hexStr","trim","Error","num","parseInt","isNaN","String","fromCodePoint","DECODE_REGEX","identifier","matches","match","inner","output","mode","buffer","i","length","char","moduleId","replace","text","withoutFreeCall","parts","lastIndex","regex","RegExp","source","exec","matchStart","index","matchEnd","ident","rawText","substring","push","decoded","importedModuleMatch","modulePathWithMetadata","cleaned","e","map","part","join"],"mappings":";;;;;;;;;;;;;;;;;;;IA8FaA,sBAAsB;eAAtBA;;IAxEGC,qBAAqB;eAArBA;;IA+EAC,mBAAmB;eAAnBA;;IA6GAC,eAAe;eAAfA;;IArEAC,oBAAoB;eAApBA;;IAnBAC,qBAAqB;eAArBA;;;AA1HhB,SAASC,UAAUC,MAAc;IAC/B,IAAIA,OAAOC,IAAI,OAAO,IAAI;QACxB,MAAM,IAAIC,MAAM;IAClB;IAEA,MAAMC,MAAMC,SAASJ,QAAQ;IAC7B,IAAIK,MAAMF,MAAM;QACd,MAAM,IAAID,MAAM,CAAC,eAAe,EAAEF,OAAO,EAAE,CAAC;IAC9C;IAEA,OAAOM,OAAOC,aAAa,CAACJ;AAC9B;AASA,MAAMK,eAAe;AAEd,SAASd,sBAAsBe,UAAkB;IACtD,MAAMC,UAAUD,WAAWE,KAAK,CAACH;IACjC,IAAI,CAACE,SAAS;QACZ,OAAOD;IACT;IAEA,MAAMG,QAAQF,OAAO,CAAC,EAAE;IAExB,IAAIG,SAAS;IAEb,IAAIC;IACJ,IAAIC,SAAS;IACb,IAAK,IAAIC,IAAI,GAAGA,IAAIJ,MAAMK,MAAM,EAAED,IAAK;QACrC,MAAME,OAAON,KAAK,CAACI,EAAE;QAErB,IAAIF,YAAoB;YACtB,IAAII,SAAS,KAAK;gBAChBJ;YACF,OAAO,IAAII,SAAS,KAAK;gBACvBJ;YACF,OAAO;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,CAAC,CAAC,EAAEH,MAAM,mBAAmB,EAAEQ,EAAE,EAAE,CAAC;aAAC;QACnE;QAEAhB,YAAYO;IACd;IAEA,kDAAkD;IAClD,IAAIP,YAAYF,gBAAgBL,MAAM,EAAE;QACtC,MAAMgB,UAAUX,gBAAgBY,SAAS,CAACV;QAC1CD,MAAMY,IAAI,CAAC;YAAC;YAAOF;SAAQ;IAC7B;IAEA,OAAOV;AACT;AAQO,SAAS3B,gBAAgByB,IAAY;IAC1C,MAAME,QAAQ1B,qBAAqBwB;IACnC,OAAOE,MAAMkB,GAAG,CAAC,CAACC,OAASA,IAAI,CAAC,EAAE,EAAEC,IAAI,CAAC;AAC3C","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/match-local-pattern.d.ts b/e-commerce/node_modules/next/dist/shared/lib/match-local-pattern.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a53cf26a429795ff674af02a11f82df7022b59eb --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/match-local-pattern.d.ts @@ -0,0 +1,3 @@ +import type { LocalPattern } from './image-config'; +export declare function matchLocalPattern(pattern: LocalPattern, url: URL): boolean; +export declare function hasLocalMatch(localPatterns: LocalPattern[] | undefined, urlPathAndQuery: string): boolean; diff --git a/e-commerce/node_modules/next/dist/shared/lib/match-local-pattern.js b/e-commerce/node_modules/next/dist/shared/lib/match-local-pattern.js new file mode 100644 index 0000000000000000000000000000000000000000..daab491510a1dbcfa07e555cee35104ee0e2d125 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/match-local-pattern.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + hasLocalMatch: null, + matchLocalPattern: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + hasLocalMatch: function() { + return hasLocalMatch; + }, + matchLocalPattern: function() { + return matchLocalPattern; + } +}); +const _picomatch = require("next/dist/compiled/picomatch"); +function matchLocalPattern(pattern, url) { + if (pattern.search !== undefined) { + if (pattern.search !== url.search) { + return false; + } + } + if (!(0, _picomatch.makeRe)(pattern.pathname ?? '**', { + dot: true + }).test(url.pathname)) { + return false; + } + return true; +} +function hasLocalMatch(localPatterns, urlPathAndQuery) { + if (!localPatterns) { + // if the user didn't define "localPatterns", we allow all local images + return true; + } + const url = new URL(urlPathAndQuery, 'http://n'); + return localPatterns.some((p)=>matchLocalPattern(p, url)); +} + +//# sourceMappingURL=match-local-pattern.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/match-local-pattern.js.map b/e-commerce/node_modules/next/dist/shared/lib/match-local-pattern.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e26a1fd05f9e2c1990ea12c8fab9f9ff64cff11f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/match-local-pattern.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/match-local-pattern.ts"],"sourcesContent":["import type { LocalPattern } from './image-config'\nimport { makeRe } from 'next/dist/compiled/picomatch'\n\n// Modifying this function should also modify writeImagesManifest()\nexport function matchLocalPattern(pattern: LocalPattern, url: URL): boolean {\n if (pattern.search !== undefined) {\n if (pattern.search !== url.search) {\n return false\n }\n }\n\n if (!makeRe(pattern.pathname ?? '**', { dot: true }).test(url.pathname)) {\n return false\n }\n\n return true\n}\n\nexport function hasLocalMatch(\n localPatterns: LocalPattern[] | undefined,\n urlPathAndQuery: string\n): boolean {\n if (!localPatterns) {\n // if the user didn't define \"localPatterns\", we allow all local images\n return true\n }\n const url = new URL(urlPathAndQuery, 'http://n')\n return localPatterns.some((p) => matchLocalPattern(p, url))\n}\n"],"names":["hasLocalMatch","matchLocalPattern","pattern","url","search","undefined","makeRe","pathname","dot","test","localPatterns","urlPathAndQuery","URL","some","p"],"mappings":";;;;;;;;;;;;;;;IAkBgBA,aAAa;eAAbA;;IAdAC,iBAAiB;eAAjBA;;;2BAHO;AAGhB,SAASA,kBAAkBC,OAAqB,EAAEC,GAAQ;IAC/D,IAAID,QAAQE,MAAM,KAAKC,WAAW;QAChC,IAAIH,QAAQE,MAAM,KAAKD,IAAIC,MAAM,EAAE;YACjC,OAAO;QACT;IACF;IAEA,IAAI,CAACE,IAAAA,iBAAM,EAACJ,QAAQK,QAAQ,IAAI,MAAM;QAAEC,KAAK;IAAK,GAAGC,IAAI,CAACN,IAAII,QAAQ,GAAG;QACvE,OAAO;IACT;IAEA,OAAO;AACT;AAEO,SAASP,cACdU,aAAyC,EACzCC,eAAuB;IAEvB,IAAI,CAACD,eAAe;QAClB,uEAAuE;QACvE,OAAO;IACT;IACA,MAAMP,MAAM,IAAIS,IAAID,iBAAiB;IACrC,OAAOD,cAAcG,IAAI,CAAC,CAACC,IAAMb,kBAAkBa,GAAGX;AACxD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/match-remote-pattern.d.ts b/e-commerce/node_modules/next/dist/shared/lib/match-remote-pattern.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c8424fa2727c2a0dc52b2141c128e81bce4fae2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/match-remote-pattern.d.ts @@ -0,0 +1,3 @@ +import type { RemotePattern } from './image-config'; +export declare function matchRemotePattern(pattern: RemotePattern | URL, url: URL): boolean; +export declare function hasRemoteMatch(domains: string[], remotePatterns: Array<RemotePattern | URL>, url: URL): boolean; diff --git a/e-commerce/node_modules/next/dist/shared/lib/match-remote-pattern.js b/e-commerce/node_modules/next/dist/shared/lib/match-remote-pattern.js new file mode 100644 index 0000000000000000000000000000000000000000..6493649ea97c0784325e5bf5f9e4ac8f6d4d9b63 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/match-remote-pattern.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + hasRemoteMatch: null, + matchRemotePattern: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + hasRemoteMatch: function() { + return hasRemoteMatch; + }, + matchRemotePattern: function() { + return matchRemotePattern; + } +}); +const _picomatch = require("next/dist/compiled/picomatch"); +function matchRemotePattern(pattern, url) { + if (pattern.protocol !== undefined) { + if (pattern.protocol.replace(/:$/, '') !== url.protocol.replace(/:$/, '')) { + return false; + } + } + if (pattern.port !== undefined) { + if (pattern.port !== url.port) { + return false; + } + } + if (pattern.hostname === undefined) { + throw new Error(`Pattern should define hostname but found\n${JSON.stringify(pattern)}`); + } else { + if (!(0, _picomatch.makeRe)(pattern.hostname).test(url.hostname)) { + return false; + } + } + if (pattern.search !== undefined) { + if (pattern.search !== url.search) { + return false; + } + } + // Should be the same as writeImagesManifest() + if (!(0, _picomatch.makeRe)(pattern.pathname ?? '**', { + dot: true + }).test(url.pathname)) { + return false; + } + return true; +} +function hasRemoteMatch(domains, remotePatterns, url) { + return domains.some((domain)=>url.hostname === domain) || remotePatterns.some((p)=>matchRemotePattern(p, url)); +} + +//# sourceMappingURL=match-remote-pattern.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/match-remote-pattern.js.map b/e-commerce/node_modules/next/dist/shared/lib/match-remote-pattern.js.map new file mode 100644 index 0000000000000000000000000000000000000000..104b3a9f4da40c9f7115a94284bea46f9505dfc9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/match-remote-pattern.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/match-remote-pattern.ts"],"sourcesContent":["import type { RemotePattern } from './image-config'\nimport { makeRe } from 'next/dist/compiled/picomatch'\n\n// Modifying this function should also modify writeImagesManifest()\nexport function matchRemotePattern(\n pattern: RemotePattern | URL,\n url: URL\n): boolean {\n if (pattern.protocol !== undefined) {\n if (pattern.protocol.replace(/:$/, '') !== url.protocol.replace(/:$/, '')) {\n return false\n }\n }\n if (pattern.port !== undefined) {\n if (pattern.port !== url.port) {\n return false\n }\n }\n\n if (pattern.hostname === undefined) {\n throw new Error(\n `Pattern should define hostname but found\\n${JSON.stringify(pattern)}`\n )\n } else {\n if (!makeRe(pattern.hostname).test(url.hostname)) {\n return false\n }\n }\n\n if (pattern.search !== undefined) {\n if (pattern.search !== url.search) {\n return false\n }\n }\n\n // Should be the same as writeImagesManifest()\n if (!makeRe(pattern.pathname ?? '**', { dot: true }).test(url.pathname)) {\n return false\n }\n\n return true\n}\n\nexport function hasRemoteMatch(\n domains: string[],\n remotePatterns: Array<RemotePattern | URL>,\n url: URL\n): boolean {\n return (\n domains.some((domain) => url.hostname === domain) ||\n remotePatterns.some((p) => matchRemotePattern(p, url))\n )\n}\n"],"names":["hasRemoteMatch","matchRemotePattern","pattern","url","protocol","undefined","replace","port","hostname","Error","JSON","stringify","makeRe","test","search","pathname","dot","domains","remotePatterns","some","domain","p"],"mappings":";;;;;;;;;;;;;;;IA2CgBA,cAAc;eAAdA;;IAvCAC,kBAAkB;eAAlBA;;;2BAHO;AAGhB,SAASA,mBACdC,OAA4B,EAC5BC,GAAQ;IAER,IAAID,QAAQE,QAAQ,KAAKC,WAAW;QAClC,IAAIH,QAAQE,QAAQ,CAACE,OAAO,CAAC,MAAM,QAAQH,IAAIC,QAAQ,CAACE,OAAO,CAAC,MAAM,KAAK;YACzE,OAAO;QACT;IACF;IACA,IAAIJ,QAAQK,IAAI,KAAKF,WAAW;QAC9B,IAAIH,QAAQK,IAAI,KAAKJ,IAAII,IAAI,EAAE;YAC7B,OAAO;QACT;IACF;IAEA,IAAIL,QAAQM,QAAQ,KAAKH,WAAW;QAClC,MAAM,IAAII,MACR,CAAC,0CAA0C,EAAEC,KAAKC,SAAS,CAACT,UAAU;IAE1E,OAAO;QACL,IAAI,CAACU,IAAAA,iBAAM,EAACV,QAAQM,QAAQ,EAAEK,IAAI,CAACV,IAAIK,QAAQ,GAAG;YAChD,OAAO;QACT;IACF;IAEA,IAAIN,QAAQY,MAAM,KAAKT,WAAW;QAChC,IAAIH,QAAQY,MAAM,KAAKX,IAAIW,MAAM,EAAE;YACjC,OAAO;QACT;IACF;IAEA,8CAA8C;IAC9C,IAAI,CAACF,IAAAA,iBAAM,EAACV,QAAQa,QAAQ,IAAI,MAAM;QAAEC,KAAK;IAAK,GAAGH,IAAI,CAACV,IAAIY,QAAQ,GAAG;QACvE,OAAO;IACT;IAEA,OAAO;AACT;AAEO,SAASf,eACdiB,OAAiB,EACjBC,cAA0C,EAC1Cf,GAAQ;IAER,OACEc,QAAQE,IAAI,CAAC,CAACC,SAAWjB,IAAIK,QAAQ,KAAKY,WAC1CF,eAAeC,IAAI,CAAC,CAACE,IAAMpB,mBAAmBoB,GAAGlB;AAErD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/mcp-error-types.d.ts b/e-commerce/node_modules/next/dist/shared/lib/mcp-error-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0574c60deb4f7a886a79028afee2378dc9f0ca0d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/mcp-error-types.d.ts @@ -0,0 +1,11 @@ +import type { OverlayState } from '../../next-devtools/dev-overlay/shared'; +export interface OverlayStateWithUrl { + url: string; + errorState: OverlayState | null; +} +export interface McpErrorStateResponse { + event: string; + requestId: string; + errorState: OverlayState | null; + url: string; +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/mcp-error-types.js b/e-commerce/node_modules/next/dist/shared/lib/mcp-error-types.js new file mode 100644 index 0000000000000000000000000000000000000000..b165b5593d42841700851796703c78c98ce43f11 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/mcp-error-types.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=mcp-error-types.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/mcp-error-types.js.map b/e-commerce/node_modules/next/dist/shared/lib/mcp-error-types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/mcp-error-types.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/mcp-page-metadata-types.d.ts b/e-commerce/node_modules/next/dist/shared/lib/mcp-page-metadata-types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c021de4aacefcb87aeb6959b5542863a36f9744 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/mcp-page-metadata-types.d.ts @@ -0,0 +1,24 @@ +import type { SegmentTrieNode } from '../../next-devtools/dev-overlay/segment-explorer-trie'; +export type SegmentTrieData = { + segmentTrie: SegmentTrieNode | null; + routerType: 'app' | 'pages'; +}; +export type PageSegment = { + type: string; + pagePath: string; + boundaryType: string | null; +}; +export type PageMetadata = { + segments: PageSegment[]; + routerType: 'app' | 'pages'; +}; +export type PageMetadataWithUrl = { + url: string; + metadata: PageMetadata | null; +}; +export interface McpPageMetadataResponse { + event: string; + requestId: string; + segmentTrieData: SegmentTrieData | null; + url: string; +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/mcp-page-metadata-types.js b/e-commerce/node_modules/next/dist/shared/lib/mcp-page-metadata-types.js new file mode 100644 index 0000000000000000000000000000000000000000..f250986c1b3c05b0fe079c0b96c4c0cc9f005d7d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/mcp-page-metadata-types.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); + +//# sourceMappingURL=mcp-page-metadata-types.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/mcp-page-metadata-types.js.map b/e-commerce/node_modules/next/dist/shared/lib/mcp-page-metadata-types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ad48a910f81e5873737ebce8e9fa87278c9f7cd9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/mcp-page-metadata-types.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/mitt.d.ts b/e-commerce/node_modules/next/dist/shared/lib/mitt.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b397b2cb1bd6b27328fdc465d49f92a65cf6664 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/mitt.d.ts @@ -0,0 +1,8 @@ +type Handler = (...evts: any[]) => void; +export type MittEmitter<T> = { + on(type: T, handler: Handler): void; + off(type: T, handler: Handler): void; + emit(type: T, ...evts: any[]): void; +}; +export default function mitt(): MittEmitter<string>; +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/mitt.js b/e-commerce/node_modules/next/dist/shared/lib/mitt.js new file mode 100644 index 0000000000000000000000000000000000000000..7fb19505ba3b4aba740b9120ff1eebdaa869be74 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/mitt.js @@ -0,0 +1,46 @@ +/* +MIT License + +Copyright (c) Jason Miller (https://jasonformat.com/) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ // This file is based on https://github.com/developit/mitt/blob/v1.1.3/src/index.js +// It's been edited for the needs of this script +// See the LICENSE at the top of the file +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return mitt; + } +}); +function mitt() { + const all = Object.create(null); + return { + on (type, handler) { + ; + (all[type] || (all[type] = [])).push(handler); + }, + off (type, handler) { + if (all[type]) { + all[type].splice(all[type].indexOf(handler) >>> 0, 1); + } + }, + emit (type, ...evts) { + // eslint-disable-next-line array-callback-return + ; + (all[type] || []).slice().map((handler)=>{ + handler(...evts); + }); + } + }; +} + +//# sourceMappingURL=mitt.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/mitt.js.map b/e-commerce/node_modules/next/dist/shared/lib/mitt.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f3b00f6819a61ab4d447307aa781eef9ae258ffb --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/mitt.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/mitt.ts"],"sourcesContent":["/*\nMIT License\n\nCopyright (c) Jason Miller (https://jasonformat.com/)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n// This file is based on https://github.com/developit/mitt/blob/v1.1.3/src/index.js\n// It's been edited for the needs of this script\n// See the LICENSE at the top of the file\n\ntype Handler = (...evts: any[]) => void\n\nexport type MittEmitter<T> = {\n on(type: T, handler: Handler): void\n off(type: T, handler: Handler): void\n emit(type: T, ...evts: any[]): void\n}\n\nexport default function mitt(): MittEmitter<string> {\n const all: { [s: string]: Handler[] } = Object.create(null)\n\n return {\n on(type: string, handler: Handler) {\n ;(all[type] || (all[type] = [])).push(handler)\n },\n\n off(type: string, handler: Handler) {\n if (all[type]) {\n all[type].splice(all[type].indexOf(handler) >>> 0, 1)\n }\n },\n\n emit(type: string, ...evts: any[]) {\n // eslint-disable-next-line array-callback-return\n ;(all[type] || []).slice().map((handler: Handler) => {\n handler(...evts)\n })\n },\n }\n}\n"],"names":["mitt","all","Object","create","on","type","handler","push","off","splice","indexOf","emit","evts","slice","map"],"mappings":"AAAA;;;;;;;;;;AAUA,GAEA,mFAAmF;AACnF,gDAAgD;AAChD,yCAAyC;;;;;+BAUzC;;;eAAwBA;;;AAAT,SAASA;IACtB,MAAMC,MAAkCC,OAAOC,MAAM,CAAC;IAEtD,OAAO;QACLC,IAAGC,IAAY,EAAEC,OAAgB;;YAC7BL,CAAAA,GAAG,CAACI,KAAK,IAAKJ,CAAAA,GAAG,CAACI,KAAK,GAAG,EAAE,AAAD,CAAC,EAAGE,IAAI,CAACD;QACxC;QAEAE,KAAIH,IAAY,EAAEC,OAAgB;YAChC,IAAIL,GAAG,CAACI,KAAK,EAAE;gBACbJ,GAAG,CAACI,KAAK,CAACI,MAAM,CAACR,GAAG,CAACI,KAAK,CAACK,OAAO,CAACJ,aAAa,GAAG;YACrD;QACF;QAEAK,MAAKN,IAAY,EAAE,GAAGO,IAAW;YAC/B,iDAAiD;;YAC/CX,CAAAA,GAAG,CAACI,KAAK,IAAI,EAAE,AAAD,EAAGQ,KAAK,GAAGC,GAAG,CAAC,CAACR;gBAC9BA,WAAWM;YACb;QACF;IACF;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/modern-browserslist-target.d.ts b/e-commerce/node_modules/next/dist/shared/lib/modern-browserslist-target.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..805502ef23d91b5b89f018a83f35c02ca8cb349c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/modern-browserslist-target.d.ts @@ -0,0 +1,2 @@ +declare const MODERN_BROWSERSLIST_TARGET: Array<string> +export default MODERN_BROWSERSLIST_TARGET diff --git a/e-commerce/node_modules/next/dist/shared/lib/modern-browserslist-target.js b/e-commerce/node_modules/next/dist/shared/lib/modern-browserslist-target.js new file mode 100644 index 0000000000000000000000000000000000000000..3841ccfc2e2bc00350f8c8633abc740846616aef --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/modern-browserslist-target.js @@ -0,0 +1,15 @@ +// Note: This file is JS because it's used by the taskfile-swc.js file, which is JS. +// Keep file changes in sync with the corresponding `.d.ts` files. +/** + * These are the minimum browser versions that we consider "modern" and thus compile for by default. + * This list was generated using `pnpm browserslist "baseline widely available"` on 2025-10-01. + */ "use strict"; +const MODERN_BROWSERSLIST_TARGET = [ + 'chrome 111', + 'edge 111', + 'firefox 111', + 'safari 16.4' +]; +module.exports = MODERN_BROWSERSLIST_TARGET; + +//# sourceMappingURL=modern-browserslist-target.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/modern-browserslist-target.js.map b/e-commerce/node_modules/next/dist/shared/lib/modern-browserslist-target.js.map new file mode 100644 index 0000000000000000000000000000000000000000..73480586ac5bcc245096070b9ee121551fd7eafe --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/modern-browserslist-target.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/modern-browserslist-target.js"],"sourcesContent":["// Note: This file is JS because it's used by the taskfile-swc.js file, which is JS.\n// Keep file changes in sync with the corresponding `.d.ts` files.\n\n/**\n * These are the minimum browser versions that we consider \"modern\" and thus compile for by default.\n * This list was generated using `pnpm browserslist \"baseline widely available\"` on 2025-10-01.\n */\nconst MODERN_BROWSERSLIST_TARGET = [\n 'chrome 111',\n 'edge 111',\n 'firefox 111',\n 'safari 16.4',\n]\n\nmodule.exports = MODERN_BROWSERSLIST_TARGET\n"],"names":["MODERN_BROWSERSLIST_TARGET","module","exports"],"mappings":"AAAA,oFAAoF;AACpF,kEAAkE;AAElE;;;CAGC;AACD,MAAMA,6BAA6B;IACjC;IACA;IACA;IACA;CACD;AAEDC,OAAOC,OAAO,GAAGF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/no-fallback-error.external.d.ts b/e-commerce/node_modules/next/dist/shared/lib/no-fallback-error.external.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b08f1229f2863d569eb9c4774b5c3de4b38033f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/no-fallback-error.external.d.ts @@ -0,0 +1,3 @@ +export declare class NoFallbackError extends Error { + constructor(); +} diff --git a/e-commerce/node_modules/next/dist/shared/lib/no-fallback-error.external.js b/e-commerce/node_modules/next/dist/shared/lib/no-fallback-error.external.js new file mode 100644 index 0000000000000000000000000000000000000000..66ac9a031abe83dbdf037ba7c52556c8c97f61af --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/no-fallback-error.external.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NoFallbackError", { + enumerable: true, + get: function() { + return NoFallbackError; + } +}); +class NoFallbackError extends Error { + constructor(){ + super(); + this.message = 'Internal: NoFallbackError'; + } +} + +//# sourceMappingURL=no-fallback-error.external.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/no-fallback-error.external.js.map b/e-commerce/node_modules/next/dist/shared/lib/no-fallback-error.external.js.map new file mode 100644 index 0000000000000000000000000000000000000000..38331a607d5a93d3f1bc594bc910707a09b1003a --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/no-fallback-error.external.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/no-fallback-error.external.ts"],"sourcesContent":["export class NoFallbackError extends Error {\n constructor() {\n super()\n this.message = 'Internal: NoFallbackError'\n }\n}\n"],"names":["NoFallbackError","Error","constructor","message"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA,wBAAwBC;IACnCC,aAAc;QACZ,KAAK;QACL,IAAI,CAACC,OAAO,GAAG;IACjB;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/normalized-asset-prefix.d.ts b/e-commerce/node_modules/next/dist/shared/lib/normalized-asset-prefix.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dca0a0691387024a6a270601a16482931278bccf --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/normalized-asset-prefix.d.ts @@ -0,0 +1 @@ +export declare function normalizedAssetPrefix(assetPrefix: string | undefined): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/normalized-asset-prefix.js b/e-commerce/node_modules/next/dist/shared/lib/normalized-asset-prefix.js new file mode 100644 index 0000000000000000000000000000000000000000..c976f55f8083ce7c159fc2fcf2b1c7502539b19d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/normalized-asset-prefix.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "normalizedAssetPrefix", { + enumerable: true, + get: function() { + return normalizedAssetPrefix; + } +}); +function normalizedAssetPrefix(assetPrefix) { + // remove all leading slashes and trailing slashes + const escapedAssetPrefix = assetPrefix?.replace(/^\/+|\/+$/g, '') || false; + // if an assetPrefix was '/', we return empty string + // because it could be an unnecessary trailing slash + if (!escapedAssetPrefix) { + return ''; + } + if (URL.canParse(escapedAssetPrefix)) { + const url = new URL(escapedAssetPrefix).toString(); + return url.endsWith('/') ? url.slice(0, -1) : url; + } + // assuming assetPrefix here is a pathname-style, + // restore the leading slash + return `/${escapedAssetPrefix}`; +} + +//# sourceMappingURL=normalized-asset-prefix.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/normalized-asset-prefix.js.map b/e-commerce/node_modules/next/dist/shared/lib/normalized-asset-prefix.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0bb57f6772a92549244451d3452969e1cd02a140 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/normalized-asset-prefix.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/normalized-asset-prefix.ts"],"sourcesContent":["export function normalizedAssetPrefix(assetPrefix: string | undefined): string {\n // remove all leading slashes and trailing slashes\n const escapedAssetPrefix = assetPrefix?.replace(/^\\/+|\\/+$/g, '') || false\n\n // if an assetPrefix was '/', we return empty string\n // because it could be an unnecessary trailing slash\n if (!escapedAssetPrefix) {\n return ''\n }\n\n if (URL.canParse(escapedAssetPrefix)) {\n const url = new URL(escapedAssetPrefix).toString()\n return url.endsWith('/') ? url.slice(0, -1) : url\n }\n\n // assuming assetPrefix here is a pathname-style,\n // restore the leading slash\n return `/${escapedAssetPrefix}`\n}\n"],"names":["normalizedAssetPrefix","assetPrefix","escapedAssetPrefix","replace","URL","canParse","url","toString","endsWith","slice"],"mappings":";;;;+BAAgBA;;;eAAAA;;;AAAT,SAASA,sBAAsBC,WAA+B;IACnE,kDAAkD;IAClD,MAAMC,qBAAqBD,aAAaE,QAAQ,cAAc,OAAO;IAErE,oDAAoD;IACpD,oDAAoD;IACpD,IAAI,CAACD,oBAAoB;QACvB,OAAO;IACT;IAEA,IAAIE,IAAIC,QAAQ,CAACH,qBAAqB;QACpC,MAAMI,MAAM,IAAIF,IAAIF,oBAAoBK,QAAQ;QAChD,OAAOD,IAAIE,QAAQ,CAAC,OAAOF,IAAIG,KAAK,CAAC,GAAG,CAAC,KAAKH;IAChD;IAEA,iDAAiD;IACjD,4BAA4B;IAC5B,OAAO,CAAC,CAAC,EAAEJ,oBAAoB;AACjC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.d.ts b/e-commerce/node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1cce258eb740176776d0b1761b12fd294d9b4df6 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.d.ts @@ -0,0 +1,22 @@ +import type { PAGE_TYPES } from '../../../lib/page-types'; +/** + * Given the absolute path to the pages folder, an absolute file path for a + * page and the page extensions, this function will return the page path + * relative to the pages folder. It doesn't consider index tail. Example: + * - `/Users/rick/my-project/pages/foo/bar/baz.js` -> `/foo/bar/baz` + * + * It also handles special metadata routes mapping. Example: + * - `/Users/rick/my-project/app/sitemap.js` -> `/sitemap/route` + * + * @param filepath Absolute path to the page. + * @param opts.dir Absolute path to the pages/app folder. + * @param opts.extensions Extensions allowed for the page. + * @param opts.keepIndex When true the trailing `index` kept in the path. + * @param opts.pagesType Whether the page is in the pages or app directory. + */ +export declare function absolutePathToPage(pagePath: string, options: { + extensions: string[] | readonly string[]; + keepIndex: boolean; + dir: string; + pagesType: PAGE_TYPES; +}): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.js b/e-commerce/node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.js new file mode 100644 index 0000000000000000000000000000000000000000..84cab6a6d630f84f6a24b14c46df6b8658b71658 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "absolutePathToPage", { + enumerable: true, + get: function() { + return absolutePathToPage; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _ensureleadingslash = require("./ensure-leading-slash"); +const _normalizepathsep = require("./normalize-path-sep"); +const _path = /*#__PURE__*/ _interop_require_default._(require("../isomorphic/path")); +const _removepagepathtail = require("./remove-page-path-tail"); +const _getmetadataroute = require("../../../lib/metadata/get-metadata-route"); +function absolutePathToPage(pagePath, options) { + const isAppDir = options.pagesType === 'app'; + const page = (0, _removepagepathtail.removePagePathTail)((0, _normalizepathsep.normalizePathSep)((0, _ensureleadingslash.ensureLeadingSlash)(_path.default.relative(options.dir, pagePath))), { + extensions: options.extensions, + keepIndex: options.keepIndex + }); + return isAppDir ? (0, _getmetadataroute.normalizeMetadataRoute)(page) : page; +} + +//# sourceMappingURL=absolute-path-to-page.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.js.map b/e-commerce/node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.js.map new file mode 100644 index 0000000000000000000000000000000000000000..eee2264fa52f6798c78e70c0e6d5b1919a92898b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/page-path/absolute-path-to-page.ts"],"sourcesContent":["import { ensureLeadingSlash } from './ensure-leading-slash'\nimport { normalizePathSep } from './normalize-path-sep'\nimport path from '../isomorphic/path'\nimport { removePagePathTail } from './remove-page-path-tail'\nimport { normalizeMetadataRoute } from '../../../lib/metadata/get-metadata-route'\nimport type { PAGE_TYPES } from '../../../lib/page-types'\n\n/**\n * Given the absolute path to the pages folder, an absolute file path for a\n * page and the page extensions, this function will return the page path\n * relative to the pages folder. It doesn't consider index tail. Example:\n * - `/Users/rick/my-project/pages/foo/bar/baz.js` -> `/foo/bar/baz`\n *\n * It also handles special metadata routes mapping. Example:\n * - `/Users/rick/my-project/app/sitemap.js` -> `/sitemap/route`\n *\n * @param filepath Absolute path to the page.\n * @param opts.dir Absolute path to the pages/app folder.\n * @param opts.extensions Extensions allowed for the page.\n * @param opts.keepIndex When true the trailing `index` kept in the path.\n * @param opts.pagesType Whether the page is in the pages or app directory.\n */\nexport function absolutePathToPage(\n pagePath: string,\n options: {\n extensions: string[] | readonly string[]\n keepIndex: boolean\n dir: string\n pagesType: PAGE_TYPES\n }\n) {\n const isAppDir = options.pagesType === 'app'\n const page = removePagePathTail(\n normalizePathSep(ensureLeadingSlash(path.relative(options.dir, pagePath))),\n {\n extensions: options.extensions,\n keepIndex: options.keepIndex,\n }\n )\n return isAppDir ? normalizeMetadataRoute(page) : page\n}\n"],"names":["absolutePathToPage","pagePath","options","isAppDir","pagesType","page","removePagePathTail","normalizePathSep","ensureLeadingSlash","path","relative","dir","extensions","keepIndex","normalizeMetadataRoute"],"mappings":";;;;+BAsBgBA;;;eAAAA;;;;oCAtBmB;kCACF;+DAChB;oCACkB;kCACI;AAkBhC,SAASA,mBACdC,QAAgB,EAChBC,OAKC;IAED,MAAMC,WAAWD,QAAQE,SAAS,KAAK;IACvC,MAAMC,OAAOC,IAAAA,sCAAkB,EAC7BC,IAAAA,kCAAgB,EAACC,IAAAA,sCAAkB,EAACC,aAAI,CAACC,QAAQ,CAACR,QAAQS,GAAG,EAAEV,aAC/D;QACEW,YAAYV,QAAQU,UAAU;QAC9BC,WAAWX,QAAQW,SAAS;IAC9B;IAEF,OAAOV,WAAWW,IAAAA,wCAAsB,EAACT,QAAQA;AACnD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-app-path.d.ts b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-app-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d9b4e516086734628278c73ddade2cc81ee63b5e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-app-path.d.ts @@ -0,0 +1 @@ +export declare function denormalizeAppPagePath(page: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-app-path.js b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-app-path.js new file mode 100644 index 0000000000000000000000000000000000000000..1e47d61543112ac50d7ff756d7bf89fadf058183 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-app-path.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "denormalizeAppPagePath", { + enumerable: true, + get: function() { + return denormalizeAppPagePath; + } +}); +function denormalizeAppPagePath(page) { + // `/` is normalized to `/index` + if (page === '/index') { + return '/'; + } + return page; +} + +//# sourceMappingURL=denormalize-app-path.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-app-path.js.map b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-app-path.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8de4047a3b90e64664c5b4a8c6a7b9287a343605 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-app-path.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/page-path/denormalize-app-path.ts"],"sourcesContent":["export function denormalizeAppPagePath(page: string): string {\n // `/` is normalized to `/index`\n if (page === '/index') {\n return '/'\n }\n\n return page\n}\n"],"names":["denormalizeAppPagePath","page"],"mappings":";;;;+BAAgBA;;;eAAAA;;;AAAT,SAASA,uBAAuBC,IAAY;IACjD,gCAAgC;IAChC,IAAIA,SAAS,UAAU;QACrB,OAAO;IACT;IAEA,OAAOA;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-page-path.d.ts b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-page-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d48310786aaafc8febf7aadc47758f95e914a297 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-page-path.d.ts @@ -0,0 +1,9 @@ +/** + * Performs the opposite transformation of `normalizePagePath`. Note that + * this function is not idempotent either in cases where there are multiple + * leading `/index` for the page. Examples: + * - `/index` -> `/` + * - `/index/foo` -> `/foo` + * - `/index/index` -> `/index` + */ +export declare function denormalizePagePath(page: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js new file mode 100644 index 0000000000000000000000000000000000000000..ad5ec625a926d1b4f903434095a2d9e2a0988b70 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "denormalizePagePath", { + enumerable: true, + get: function() { + return denormalizePagePath; + } +}); +const _utils = require("../router/utils"); +const _normalizepathsep = require("./normalize-path-sep"); +function denormalizePagePath(page) { + let _page = (0, _normalizepathsep.normalizePathSep)(page); + return _page.startsWith('/index/') && !(0, _utils.isDynamicRoute)(_page) ? _page.slice(6) : _page !== '/index' ? _page : '/'; +} + +//# sourceMappingURL=denormalize-page-path.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js.map b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5b663a3261fcef3b19d9c50f331d0e3052e40a5f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/page-path/denormalize-page-path.ts"],"sourcesContent":["import { isDynamicRoute } from '../router/utils'\nimport { normalizePathSep } from './normalize-path-sep'\n\n/**\n * Performs the opposite transformation of `normalizePagePath`. Note that\n * this function is not idempotent either in cases where there are multiple\n * leading `/index` for the page. Examples:\n * - `/index` -> `/`\n * - `/index/foo` -> `/foo`\n * - `/index/index` -> `/index`\n */\nexport function denormalizePagePath(page: string) {\n let _page = normalizePathSep(page)\n return _page.startsWith('/index/') && !isDynamicRoute(_page)\n ? _page.slice(6)\n : _page !== '/index'\n ? _page\n : '/'\n}\n"],"names":["denormalizePagePath","page","_page","normalizePathSep","startsWith","isDynamicRoute","slice"],"mappings":";;;;+BAWgBA;;;eAAAA;;;uBAXe;kCACE;AAU1B,SAASA,oBAAoBC,IAAY;IAC9C,IAAIC,QAAQC,IAAAA,kCAAgB,EAACF;IAC7B,OAAOC,MAAME,UAAU,CAAC,cAAc,CAACC,IAAAA,qBAAc,EAACH,SAClDA,MAAMI,KAAK,CAAC,KACZJ,UAAU,WACRA,QACA;AACR","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.d.ts b/e-commerce/node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b3d00fbe7bbc2ad7ad8078819b1c961b300133d --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.d.ts @@ -0,0 +1,5 @@ +/** + * For a given page path, this function ensures that there is a leading slash. + * If there is not a leading slash, one is added, otherwise it is noop. + */ +export declare function ensureLeadingSlash(path: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js b/e-commerce/node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js new file mode 100644 index 0000000000000000000000000000000000000000..6c4733da5e59d431d7708b77f2d61d2504a69926 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js @@ -0,0 +1,18 @@ +/** + * For a given page path, this function ensures that there is a leading slash. + * If there is not a leading slash, one is added, otherwise it is noop. + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ensureLeadingSlash", { + enumerable: true, + get: function() { + return ensureLeadingSlash; + } +}); +function ensureLeadingSlash(path) { + return path.startsWith('/') ? path : `/${path}`; +} + +//# sourceMappingURL=ensure-leading-slash.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js.map b/e-commerce/node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js.map new file mode 100644 index 0000000000000000000000000000000000000000..768d21c17f949e1bb7ab62a03af64c8f9e9984b1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/page-path/ensure-leading-slash.ts"],"sourcesContent":["/**\n * For a given page path, this function ensures that there is a leading slash.\n * If there is not a leading slash, one is added, otherwise it is noop.\n */\nexport function ensureLeadingSlash(path: string) {\n return path.startsWith('/') ? path : `/${path}`\n}\n"],"names":["ensureLeadingSlash","path","startsWith"],"mappings":"AAAA;;;CAGC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,mBAAmBC,IAAY;IAC7C,OAAOA,KAAKC,UAAU,CAAC,OAAOD,OAAO,CAAC,CAAC,EAAEA,MAAM;AACjD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/get-page-paths.d.ts b/e-commerce/node_modules/next/dist/shared/lib/page-path/get-page-paths.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7fa4990b201c69abea9033c0dae492b337837bdb --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/get-page-paths.d.ts @@ -0,0 +1,13 @@ +/** + * Calculate all possible pagePaths for a given normalized pagePath along with + * allowed extensions. This can be used to check which one of the files exists + * and to debug inspected locations. + * + * For pages, map `/route` to [`/route.[ext]`, `/route/index.[ext]`] + * For app paths, map `/route/page` to [`/route/page.[ext]`] or `/route/route` + * to [`/route/route.[ext]`] + * + * @param normalizedPagePath Normalized page path (it will denormalize). + * @param extensions Allowed extensions. + */ +export declare function getPagePaths(normalizedPagePath: string, extensions: string[], isAppDir: boolean): string[]; diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/get-page-paths.js b/e-commerce/node_modules/next/dist/shared/lib/page-path/get-page-paths.js new file mode 100644 index 0000000000000000000000000000000000000000..b2c11343dbd303e4e41bbdf19ac6b390403c52ef --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/get-page-paths.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getPagePaths", { + enumerable: true, + get: function() { + return getPagePaths; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _denormalizepagepath = require("./denormalize-page-path"); +const _path = /*#__PURE__*/ _interop_require_default._(require("../isomorphic/path")); +function getPagePaths(normalizedPagePath, extensions, isAppDir) { + const page = (0, _denormalizepagepath.denormalizePagePath)(normalizedPagePath); + let prefixes; + if (isAppDir) { + prefixes = [ + page + ]; + } else if (normalizedPagePath.endsWith('/index')) { + prefixes = [ + _path.default.join(page, 'index') + ]; + } else { + prefixes = [ + page, + _path.default.join(page, 'index') + ]; + } + const paths = []; + for (const extension of extensions){ + for (const prefix of prefixes){ + paths.push(`${prefix}.${extension}`); + } + } + return paths; +} + +//# sourceMappingURL=get-page-paths.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/get-page-paths.js.map b/e-commerce/node_modules/next/dist/shared/lib/page-path/get-page-paths.js.map new file mode 100644 index 0000000000000000000000000000000000000000..305e8f8c808a686a60f85da89e8f0fb8eceaf8d0 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/get-page-paths.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/page-path/get-page-paths.ts"],"sourcesContent":["import { denormalizePagePath } from './denormalize-page-path'\nimport path from '../isomorphic/path'\n\n/**\n * Calculate all possible pagePaths for a given normalized pagePath along with\n * allowed extensions. This can be used to check which one of the files exists\n * and to debug inspected locations.\n *\n * For pages, map `/route` to [`/route.[ext]`, `/route/index.[ext]`]\n * For app paths, map `/route/page` to [`/route/page.[ext]`] or `/route/route`\n * to [`/route/route.[ext]`]\n *\n * @param normalizedPagePath Normalized page path (it will denormalize).\n * @param extensions Allowed extensions.\n */\nexport function getPagePaths(\n normalizedPagePath: string,\n extensions: string[],\n isAppDir: boolean\n) {\n const page = denormalizePagePath(normalizedPagePath)\n\n let prefixes: string[]\n if (isAppDir) {\n prefixes = [page]\n } else if (normalizedPagePath.endsWith('/index')) {\n prefixes = [path.join(page, 'index')]\n } else {\n prefixes = [page, path.join(page, 'index')]\n }\n\n const paths: string[] = []\n for (const extension of extensions) {\n for (const prefix of prefixes) {\n paths.push(`${prefix}.${extension}`)\n }\n }\n\n return paths\n}\n"],"names":["getPagePaths","normalizedPagePath","extensions","isAppDir","page","denormalizePagePath","prefixes","endsWith","path","join","paths","extension","prefix","push"],"mappings":";;;;+BAegBA;;;eAAAA;;;;qCAfoB;+DACnB;AAcV,SAASA,aACdC,kBAA0B,EAC1BC,UAAoB,EACpBC,QAAiB;IAEjB,MAAMC,OAAOC,IAAAA,wCAAmB,EAACJ;IAEjC,IAAIK;IACJ,IAAIH,UAAU;QACZG,WAAW;YAACF;SAAK;IACnB,OAAO,IAAIH,mBAAmBM,QAAQ,CAAC,WAAW;QAChDD,WAAW;YAACE,aAAI,CAACC,IAAI,CAACL,MAAM;SAAS;IACvC,OAAO;QACLE,WAAW;YAACF;YAAMI,aAAI,CAACC,IAAI,CAACL,MAAM;SAAS;IAC7C;IAEA,MAAMM,QAAkB,EAAE;IAC1B,KAAK,MAAMC,aAAaT,WAAY;QAClC,KAAK,MAAMU,UAAUN,SAAU;YAC7BI,MAAMG,IAAI,CAAC,GAAGD,OAAO,CAAC,EAAED,WAAW;QACrC;IACF;IAEA,OAAOD;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-data-path.d.ts b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-data-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..72df775124594d7048a152b4a77f96373a749efb --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-data-path.d.ts @@ -0,0 +1,4 @@ +/** + * strip _next/data/<build-id>/ prefix and .json suffix + */ +export declare function normalizeDataPath(pathname: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-data-path.js b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-data-path.js new file mode 100644 index 0000000000000000000000000000000000000000..047433b61af6b630923d14abb934d37c1daa08b8 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-data-path.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "normalizeDataPath", { + enumerable: true, + get: function() { + return normalizeDataPath; + } +}); +const _pathhasprefix = require("../router/utils/path-has-prefix"); +function normalizeDataPath(pathname) { + if (!(0, _pathhasprefix.pathHasPrefix)(pathname || '/', '/_next/data')) { + return pathname; + } + pathname = pathname.replace(/\/_next\/data\/[^/]{1,}/, '').replace(/\.json$/, ''); + if (pathname === '/index') { + return '/'; + } + return pathname; +} + +//# sourceMappingURL=normalize-data-path.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-data-path.js.map b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-data-path.js.map new file mode 100644 index 0000000000000000000000000000000000000000..0475118fc93a855f868dbc05b8b97b2d6121d292 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-data-path.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/page-path/normalize-data-path.ts"],"sourcesContent":["import { pathHasPrefix } from '../router/utils/path-has-prefix'\n\n/**\n * strip _next/data/<build-id>/ prefix and .json suffix\n */\nexport function normalizeDataPath(pathname: string) {\n if (!pathHasPrefix(pathname || '/', '/_next/data')) {\n return pathname\n }\n pathname = pathname\n .replace(/\\/_next\\/data\\/[^/]{1,}/, '')\n .replace(/\\.json$/, '')\n\n if (pathname === '/index') {\n return '/'\n }\n return pathname\n}\n"],"names":["normalizeDataPath","pathname","pathHasPrefix","replace"],"mappings":";;;;+BAKgBA;;;eAAAA;;;+BALc;AAKvB,SAASA,kBAAkBC,QAAgB;IAChD,IAAI,CAACC,IAAAA,4BAAa,EAACD,YAAY,KAAK,gBAAgB;QAClD,OAAOA;IACT;IACAA,WAAWA,SACRE,OAAO,CAAC,2BAA2B,IACnCA,OAAO,CAAC,WAAW;IAEtB,IAAIF,aAAa,UAAU;QACzB,OAAO;IACT;IACA,OAAOA;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-page-path.d.ts b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-page-path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bd8ab76e3627bd154b39b2ee16701ccd218fab7 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-page-path.d.ts @@ -0,0 +1,10 @@ +/** + * Takes a page and transforms it into its file counterpart ensuring that the + * output is normalized. Note this function is not idempotent because a page + * `/index` can be referencing `/index/index.js` and `/index/index` could be + * referencing `/index/index/index.js`. Examples: + * - `/` -> `/index` + * - `/index/foo` -> `/index/index/foo` + * - `/index` -> `/index/index` + */ +export declare function normalizePagePath(page: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-page-path.js b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-page-path.js new file mode 100644 index 0000000000000000000000000000000000000000..2f4105999047114fb399b3e0b0f0aa9c273e93dd --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-page-path.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "normalizePagePath", { + enumerable: true, + get: function() { + return normalizePagePath; + } +}); +const _ensureleadingslash = require("./ensure-leading-slash"); +const _utils = require("../router/utils"); +const _utils1 = require("../utils"); +function normalizePagePath(page) { + const normalized = /^\/index(\/|$)/.test(page) && !(0, _utils.isDynamicRoute)(page) ? `/index${page}` : page === '/' ? '/index' : (0, _ensureleadingslash.ensureLeadingSlash)(page); + if (process.env.NEXT_RUNTIME !== 'edge') { + const { posix } = require('path'); + const resolvedPage = posix.normalize(normalized); + if (resolvedPage !== normalized) { + throw new _utils1.NormalizeError(`Requested and resolved page mismatch: ${normalized} ${resolvedPage}`); + } + } + return normalized; +} + +//# sourceMappingURL=normalize-page-path.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-page-path.js.map b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-page-path.js.map new file mode 100644 index 0000000000000000000000000000000000000000..86ecc385913dbfcbf6e0da9ed6c4862cbd815046 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-page-path.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/page-path/normalize-page-path.ts"],"sourcesContent":["import { ensureLeadingSlash } from './ensure-leading-slash'\nimport { isDynamicRoute } from '../router/utils'\nimport { NormalizeError } from '../utils'\n\n/**\n * Takes a page and transforms it into its file counterpart ensuring that the\n * output is normalized. Note this function is not idempotent because a page\n * `/index` can be referencing `/index/index.js` and `/index/index` could be\n * referencing `/index/index/index.js`. Examples:\n * - `/` -> `/index`\n * - `/index/foo` -> `/index/index/foo`\n * - `/index` -> `/index/index`\n */\nexport function normalizePagePath(page: string): string {\n const normalized =\n /^\\/index(\\/|$)/.test(page) && !isDynamicRoute(page)\n ? `/index${page}`\n : page === '/'\n ? '/index'\n : ensureLeadingSlash(page)\n\n if (process.env.NEXT_RUNTIME !== 'edge') {\n const { posix } = require('path') as typeof import('path')\n const resolvedPage = posix.normalize(normalized)\n if (resolvedPage !== normalized) {\n throw new NormalizeError(\n `Requested and resolved page mismatch: ${normalized} ${resolvedPage}`\n )\n }\n }\n\n return normalized\n}\n"],"names":["normalizePagePath","page","normalized","test","isDynamicRoute","ensureLeadingSlash","process","env","NEXT_RUNTIME","posix","require","resolvedPage","normalize","NormalizeError"],"mappings":";;;;+BAagBA;;;eAAAA;;;oCAbmB;uBACJ;wBACA;AAWxB,SAASA,kBAAkBC,IAAY;IAC5C,MAAMC,aACJ,iBAAiBC,IAAI,CAACF,SAAS,CAACG,IAAAA,qBAAc,EAACH,QAC3C,CAAC,MAAM,EAAEA,MAAM,GACfA,SAAS,MACP,WACAI,IAAAA,sCAAkB,EAACJ;IAE3B,IAAIK,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;QACvC,MAAM,EAAEC,KAAK,EAAE,GAAGC,QAAQ;QAC1B,MAAMC,eAAeF,MAAMG,SAAS,CAACV;QACrC,IAAIS,iBAAiBT,YAAY;YAC/B,MAAM,IAAIW,sBAAc,CACtB,CAAC,sCAAsC,EAAEX,WAAW,CAAC,EAAES,cAAc;QAEzE;IACF;IAEA,OAAOT;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-path-sep.d.ts b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-path-sep.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a1566a17adf28cf5f07206b1fdc23cf05dcc6818 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-path-sep.d.ts @@ -0,0 +1,6 @@ +/** + * For a given page path, this function ensures that there is no backslash + * escaping slashes in the path. Example: + * - `foo\/bar\/baz` -> `foo/bar/baz` + */ +export declare function normalizePathSep(path: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js new file mode 100644 index 0000000000000000000000000000000000000000..2d040729bfd5a48f1ff3fe597579b45f2e1cca14 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js @@ -0,0 +1,19 @@ +/** + * For a given page path, this function ensures that there is no backslash + * escaping slashes in the path. Example: + * - `foo\/bar\/baz` -> `foo/bar/baz` + */ "use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "normalizePathSep", { + enumerable: true, + get: function() { + return normalizePathSep; + } +}); +function normalizePathSep(path) { + return path.replace(/\\/g, '/'); +} + +//# sourceMappingURL=normalize-path-sep.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js.map b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a3624a8cf7fff48fee6ef7abed71ee6a20febd9f --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/page-path/normalize-path-sep.ts"],"sourcesContent":["/**\n * For a given page path, this function ensures that there is no backslash\n * escaping slashes in the path. Example:\n * - `foo\\/bar\\/baz` -> `foo/bar/baz`\n */\nexport function normalizePathSep(path: string): string {\n return path.replace(/\\\\/g, '/')\n}\n"],"names":["normalizePathSep","path","replace"],"mappings":"AAAA;;;;CAIC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,iBAAiBC,IAAY;IAC3C,OAAOA,KAAKC,OAAO,CAAC,OAAO;AAC7B","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.d.ts b/e-commerce/node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e05b6d51cf07cde4362ecd63b5c490b0eb11fb2 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.d.ts @@ -0,0 +1,15 @@ +/** + * Removes the file extension for a page and the trailing `index` if it exists + * making sure to not return an empty string. The page head is not touched + * and returned as it is passed. Examples: + * - `/foo/bar/baz/index.js` -> `/foo/bar/baz` + * - `/foo/bar/baz.js` -> `/foo/bar/baz` + * + * @param pagePath A page to a page file (absolute or relative) + * @param options.extensions Extensions allowed for the page. + * @param options.keepIndex When true the trailing `index` is _not_ removed. + */ +export declare function removePagePathTail(pagePath: string, options: { + extensions: ReadonlyArray<string>; + keepIndex?: boolean; +}): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.js b/e-commerce/node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.js new file mode 100644 index 0000000000000000000000000000000000000000..f875c83a7eb834e85fbe382b3419507c028ff848 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "removePagePathTail", { + enumerable: true, + get: function() { + return removePagePathTail; + } +}); +const _normalizepathsep = require("./normalize-path-sep"); +function removePagePathTail(pagePath, options) { + pagePath = (0, _normalizepathsep.normalizePathSep)(pagePath).replace(new RegExp(`\\.+(?:${options.extensions.join('|')})$`), ''); + if (options.keepIndex !== true) { + pagePath = pagePath.replace(/\/index$/, '') || '/'; + } + return pagePath; +} + +//# sourceMappingURL=remove-page-path-tail.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.js.map b/e-commerce/node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8073f18c231b5ad0e3c847a800159ee20ae7425b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/page-path/remove-page-path-tail.ts"],"sourcesContent":["import { normalizePathSep } from './normalize-path-sep'\n\n/**\n * Removes the file extension for a page and the trailing `index` if it exists\n * making sure to not return an empty string. The page head is not touched\n * and returned as it is passed. Examples:\n * - `/foo/bar/baz/index.js` -> `/foo/bar/baz`\n * - `/foo/bar/baz.js` -> `/foo/bar/baz`\n *\n * @param pagePath A page to a page file (absolute or relative)\n * @param options.extensions Extensions allowed for the page.\n * @param options.keepIndex When true the trailing `index` is _not_ removed.\n */\nexport function removePagePathTail(\n pagePath: string,\n options: {\n extensions: ReadonlyArray<string>\n keepIndex?: boolean\n }\n) {\n pagePath = normalizePathSep(pagePath).replace(\n new RegExp(`\\\\.+(?:${options.extensions.join('|')})$`),\n ''\n )\n\n if (options.keepIndex !== true) {\n pagePath = pagePath.replace(/\\/index$/, '') || '/'\n }\n\n return pagePath\n}\n"],"names":["removePagePathTail","pagePath","options","normalizePathSep","replace","RegExp","extensions","join","keepIndex"],"mappings":";;;;+BAagBA;;;eAAAA;;;kCAbiB;AAa1B,SAASA,mBACdC,QAAgB,EAChBC,OAGC;IAEDD,WAAWE,IAAAA,kCAAgB,EAACF,UAAUG,OAAO,CAC3C,IAAIC,OAAO,CAAC,OAAO,EAAEH,QAAQI,UAAU,CAACC,IAAI,CAAC,KAAK,EAAE,CAAC,GACrD;IAGF,IAAIL,QAAQM,SAAS,KAAK,MAAM;QAC9BP,WAAWA,SAASG,OAAO,CAAC,YAAY,OAAO;IACjD;IAEA,OAAOH;AACT","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/promise-with-resolvers.d.ts b/e-commerce/node_modules/next/dist/shared/lib/promise-with-resolvers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d982012276e8c94e5f62b90b5a063abfa9c2ae74 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/promise-with-resolvers.d.ts @@ -0,0 +1 @@ +export declare function createPromiseWithResolvers<T>(): PromiseWithResolvers<T>; diff --git a/e-commerce/node_modules/next/dist/shared/lib/promise-with-resolvers.js b/e-commerce/node_modules/next/dist/shared/lib/promise-with-resolvers.js new file mode 100644 index 0000000000000000000000000000000000000000..cfb3179832696a21dd2e70d7826a312b3f2e7cbb --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/promise-with-resolvers.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "createPromiseWithResolvers", { + enumerable: true, + get: function() { + return createPromiseWithResolvers; + } +}); +function createPromiseWithResolvers() { + // Shim of Stage 4 Promise.withResolvers proposal + let resolve; + let reject; + const promise = new Promise((res, rej)=>{ + resolve = res; + reject = rej; + }); + return { + resolve: resolve, + reject: reject, + promise + }; +} + +//# sourceMappingURL=promise-with-resolvers.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/promise-with-resolvers.js.map b/e-commerce/node_modules/next/dist/shared/lib/promise-with-resolvers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..308353ba08e0d43ae95dda793f0a3f02b74d5f94 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/promise-with-resolvers.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/promise-with-resolvers.ts"],"sourcesContent":["export function createPromiseWithResolvers<T>(): PromiseWithResolvers<T> {\n // Shim of Stage 4 Promise.withResolvers proposal\n let resolve: (value: T | PromiseLike<T>) => void\n let reject: (reason: any) => void\n const promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n return { resolve: resolve!, reject: reject!, promise }\n}\n"],"names":["createPromiseWithResolvers","resolve","reject","promise","Promise","res","rej"],"mappings":";;;;+BAAgBA;;;eAAAA;;;AAAT,SAASA;IACd,iDAAiD;IACjD,IAAIC;IACJ,IAAIC;IACJ,MAAMC,UAAU,IAAIC,QAAW,CAACC,KAAKC;QACnCL,UAAUI;QACVH,SAASI;IACX;IACA,OAAO;QAAEL,SAASA;QAAUC,QAAQA;QAASC;IAAQ;AACvD","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/request-insights.d.ts b/e-commerce/node_modules/next/dist/shared/lib/request-insights.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..352dce02d3eddbacdb31d288544e3e517238c87c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/request-insights.d.ts @@ -0,0 +1,7 @@ +export type RequestInsightKind = 'request' | 'instant-insights'; +export type RequestInsightIdentity = { + requestId: string; + kind?: RequestInsightKind; +}; +export declare function getRequestInsightKind(insight: Pick<RequestInsightIdentity, 'kind'>): RequestInsightKind; +export declare function getRequestInsightKey(insight: RequestInsightIdentity): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/request-insights.js b/e-commerce/node_modules/next/dist/shared/lib/request-insights.js new file mode 100644 index 0000000000000000000000000000000000000000..2f33358e7e68ca6964889ec78174c3c4cb529ccc --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/request-insights.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + getRequestInsightKey: null, + getRequestInsightKind: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + getRequestInsightKey: function() { + return getRequestInsightKey; + }, + getRequestInsightKind: function() { + return getRequestInsightKind; + } +}); +function getRequestInsightKind(insight) { + return insight.kind ?? 'request'; +} +function getRequestInsightKey(insight) { + return `${getRequestInsightKind(insight)}:${insight.requestId}`; +} + +//# sourceMappingURL=request-insights.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/request-insights.js.map b/e-commerce/node_modules/next/dist/shared/lib/request-insights.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1f041d77f9b650b8d0657787b5a25aeb3f409e10 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/request-insights.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/shared/lib/request-insights.ts"],"sourcesContent":["export type RequestInsightKind = 'request' | 'instant-insights'\n\nexport type RequestInsightIdentity = {\n requestId: string\n kind?: RequestInsightKind\n}\n\nexport function getRequestInsightKind(\n insight: Pick<RequestInsightIdentity, 'kind'>\n): RequestInsightKind {\n return insight.kind ?? 'request'\n}\n\nexport function getRequestInsightKey(insight: RequestInsightIdentity): string {\n return `${getRequestInsightKind(insight)}:${insight.requestId}`\n}\n"],"names":["getRequestInsightKey","getRequestInsightKind","insight","kind","requestId"],"mappings":";;;;;;;;;;;;;;;IAagBA,oBAAoB;eAApBA;;IANAC,qBAAqB;eAArBA;;;AAAT,SAASA,sBACdC,OAA6C;IAE7C,OAAOA,QAAQC,IAAI,IAAI;AACzB;AAEO,SAASH,qBAAqBE,OAA+B;IAClE,OAAO,GAAGD,sBAAsBC,SAAS,CAAC,EAAEA,QAAQE,SAAS,EAAE;AACjE","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/adapters.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/adapters.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..196d04d7e206855abcbbc564c9838bdae26fca31 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/adapters.d.ts @@ -0,0 +1,18 @@ +import type { AppRouterInstance } from '../app-router-context.shared-runtime'; +import type { Params } from '../../../server/request/params'; +import type { NextRouter } from './router'; +import React from 'react'; +/** It adapts a Pages Router (`NextRouter`) to the App Router Instance. */ +export declare function adaptForAppRouterInstance(pagesRouter: NextRouter): AppRouterInstance; +/** + * adaptForSearchParams transforms the ParsedURLQuery into URLSearchParams. + * + * @param router the router that contains the query. + * @returns the search params in the URLSearchParams format + */ +export declare function adaptForSearchParams(router: Pick<NextRouter, 'isReady' | 'query' | 'asPath'>): URLSearchParams; +export declare function adaptForPathParams(router: Pick<NextRouter, 'isReady' | 'pathname' | 'query' | 'asPath'>): Params | null; +export declare function PathnameContextProviderAdapter({ children, router, ...props }: React.PropsWithChildren<{ + router: Pick<NextRouter, 'pathname' | 'asPath' | 'isReady' | 'isFallback'>; + isAutoExport: boolean; +}>): React.JSX.Element; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/adapters.js b/e-commerce/node_modules/next/dist/shared/lib/router/adapters.js new file mode 100644 index 0000000000000000000000000000000000000000..c3d13440474230a34868e87a19a01f5f243a0f5e --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/adapters.js @@ -0,0 +1,139 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + PathnameContextProviderAdapter: null, + adaptForAppRouterInstance: null, + adaptForPathParams: null, + adaptForSearchParams: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + PathnameContextProviderAdapter: function() { + return PathnameContextProviderAdapter; + }, + adaptForAppRouterInstance: function() { + return adaptForAppRouterInstance; + }, + adaptForPathParams: function() { + return adaptForPathParams; + }, + adaptForSearchParams: function() { + return adaptForSearchParams; + } +}); +const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"); +const _jsxruntime = require("react/jsx-runtime"); +const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react")); +const _hooksclientcontextsharedruntime = require("../hooks-client-context.shared-runtime"); +const _utils = require("./utils"); +const _aspathtosearchparams = require("./utils/as-path-to-search-params"); +const _routeregex = require("./utils/route-regex"); +function adaptForAppRouterInstance(pagesRouter) { + return { + back () { + pagesRouter.back(); + }, + forward () { + pagesRouter.forward(); + }, + refresh () { + pagesRouter.reload(); + }, + hmrRefresh () {}, + push (href, { scroll } = {}) { + void pagesRouter.push(href, undefined, { + scroll + }); + }, + replace (href, { scroll } = {}) { + void pagesRouter.replace(href, undefined, { + scroll + }); + }, + prefetch (href) { + void pagesRouter.prefetch(href); + }, + // The bfcacheId concept is App Router-only. Surfaced as a stable + // placeholder so consumers using this adapter don't crash. + bfcacheId: '0' + }; +} +function adaptForSearchParams(router) { + if (!router.isReady || !router.query) { + return new URLSearchParams(); + } + return (0, _aspathtosearchparams.asPathToSearchParams)(router.asPath); +} +function adaptForPathParams(router) { + if (!router.isReady || !router.query) { + return null; + } + const pathParams = {}; + const routeRegex = (0, _routeregex.getRouteRegex)(router.pathname); + const keys = Object.keys(routeRegex.groups); + for (const key of keys){ + pathParams[key] = router.query[key]; + } + return pathParams; +} +function PathnameContextProviderAdapter({ children, router, ...props }) { + const ref = (0, _react.useRef)(props.isAutoExport); + const value = (0, _react.useMemo)(()=>{ + // isAutoExport is only ever `true` on the first render from the server, + // so reset it to `false` after we read it for the first time as `true`. If + // we don't use the value, then we don't need it. + const isAutoExport = ref.current; + if (isAutoExport) { + ref.current = false; + } + // When the route is a dynamic route, we need to do more processing to + // determine if we need to stop showing the pathname. + if ((0, _utils.isDynamicRoute)(router.pathname)) { + // When the router is rendering the fallback page, it can't possibly know + // the path, so return `null` here. Read more about fallback pages over + // at: + // https://nextjs.org/docs/api-reference/data-fetching/get-static-paths#fallback-pages + if (router.isFallback) { + return null; + } + // When `isAutoExport` is true, meaning this is a page page has been + // automatically statically optimized, and the router is not ready, then + // we can't know the pathname yet. Read more about automatic static + // optimization at: + // https://nextjs.org/docs/advanced-features/automatic-static-optimization + if (isAutoExport && !router.isReady) { + return null; + } + } + // The `router.asPath` contains the pathname seen by the browser (including + // any query strings), so it should have that stripped. Read more about the + // `asPath` option over at: + // https://nextjs.org/docs/api-reference/next/router#router-object + let url; + try { + url = new URL(router.asPath, 'http://f'); + } catch (_) { + // fallback to / for invalid asPath values e.g. // + return '/'; + } + return url.pathname; + }, [ + router.asPath, + router.isFallback, + router.isReady, + router.pathname + ]); + return /*#__PURE__*/ (0, _jsxruntime.jsx)(_hooksclientcontextsharedruntime.PathnameContext.Provider, { + value: value, + children: children + }); +} + +//# sourceMappingURL=adapters.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/adapters.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/adapters.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8e44b3ea659264e555e90ce0e60e3d3fba9ab728 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/adapters.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/router/adapters.tsx"],"sourcesContent":["import type { AppRouterInstance } from '../app-router-context.shared-runtime'\nimport type { Params } from '../../../server/request/params'\nimport type { NextRouter } from './router'\n\nimport React, { useMemo, useRef } from 'react'\nimport { PathnameContext } from '../hooks-client-context.shared-runtime'\nimport { isDynamicRoute } from './utils'\nimport { asPathToSearchParams } from './utils/as-path-to-search-params'\nimport { getRouteRegex } from './utils/route-regex'\n\n/** It adapts a Pages Router (`NextRouter`) to the App Router Instance. */\nexport function adaptForAppRouterInstance(\n pagesRouter: NextRouter\n): AppRouterInstance {\n return {\n back() {\n pagesRouter.back()\n },\n forward() {\n pagesRouter.forward()\n },\n refresh() {\n pagesRouter.reload()\n },\n hmrRefresh() {},\n push(href, { scroll } = {}) {\n void pagesRouter.push(href, undefined, { scroll })\n },\n replace(href, { scroll } = {}) {\n void pagesRouter.replace(href, undefined, { scroll })\n },\n prefetch(href) {\n void pagesRouter.prefetch(href)\n },\n // The bfcacheId concept is App Router-only. Surfaced as a stable\n // placeholder so consumers using this adapter don't crash.\n bfcacheId: '0',\n }\n}\n\n/**\n * adaptForSearchParams transforms the ParsedURLQuery into URLSearchParams.\n *\n * @param router the router that contains the query.\n * @returns the search params in the URLSearchParams format\n */\nexport function adaptForSearchParams(\n router: Pick<NextRouter, 'isReady' | 'query' | 'asPath'>\n): URLSearchParams {\n if (!router.isReady || !router.query) {\n return new URLSearchParams()\n }\n\n return asPathToSearchParams(router.asPath)\n}\n\nexport function adaptForPathParams(\n router: Pick<NextRouter, 'isReady' | 'pathname' | 'query' | 'asPath'>\n): Params | null {\n if (!router.isReady || !router.query) {\n return null\n }\n const pathParams: Params = {}\n const routeRegex = getRouteRegex(router.pathname)\n const keys = Object.keys(routeRegex.groups)\n for (const key of keys) {\n pathParams[key] = router.query[key]!\n }\n return pathParams\n}\n\nexport function PathnameContextProviderAdapter({\n children,\n router,\n ...props\n}: React.PropsWithChildren<{\n router: Pick<NextRouter, 'pathname' | 'asPath' | 'isReady' | 'isFallback'>\n isAutoExport: boolean\n}>) {\n const ref = useRef(props.isAutoExport)\n const value = useMemo(() => {\n // isAutoExport is only ever `true` on the first render from the server,\n // so reset it to `false` after we read it for the first time as `true`. If\n // we don't use the value, then we don't need it.\n const isAutoExport = ref.current\n if (isAutoExport) {\n ref.current = false\n }\n\n // When the route is a dynamic route, we need to do more processing to\n // determine if we need to stop showing the pathname.\n if (isDynamicRoute(router.pathname)) {\n // When the router is rendering the fallback page, it can't possibly know\n // the path, so return `null` here. Read more about fallback pages over\n // at:\n // https://nextjs.org/docs/api-reference/data-fetching/get-static-paths#fallback-pages\n if (router.isFallback) {\n return null\n }\n\n // When `isAutoExport` is true, meaning this is a page page has been\n // automatically statically optimized, and the router is not ready, then\n // we can't know the pathname yet. Read more about automatic static\n // optimization at:\n // https://nextjs.org/docs/advanced-features/automatic-static-optimization\n if (isAutoExport && !router.isReady) {\n return null\n }\n }\n\n // The `router.asPath` contains the pathname seen by the browser (including\n // any query strings), so it should have that stripped. Read more about the\n // `asPath` option over at:\n // https://nextjs.org/docs/api-reference/next/router#router-object\n let url: URL\n try {\n url = new URL(router.asPath, 'http://f')\n } catch (_) {\n // fallback to / for invalid asPath values e.g. //\n return '/'\n }\n\n return url.pathname\n }, [router.asPath, router.isFallback, router.isReady, router.pathname])\n\n return (\n <PathnameContext.Provider value={value}>\n {children}\n </PathnameContext.Provider>\n )\n}\n"],"names":["PathnameContextProviderAdapter","adaptForAppRouterInstance","adaptForPathParams","adaptForSearchParams","pagesRouter","back","forward","refresh","reload","hmrRefresh","push","href","scroll","undefined","replace","prefetch","bfcacheId","router","isReady","query","URLSearchParams","asPathToSearchParams","asPath","pathParams","routeRegex","getRouteRegex","pathname","keys","Object","groups","key","children","props","ref","useRef","isAutoExport","value","useMemo","current","isDynamicRoute","isFallback","url","URL","_","PathnameContext","Provider"],"mappings":";;;;;;;;;;;;;;;;;IAuEgBA,8BAA8B;eAA9BA;;IA5DAC,yBAAyB;eAAzBA;;IA6CAC,kBAAkB;eAAlBA;;IAVAC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,IAAAA,cAAO,EAAC;QACpB,wEAAwE;QACxE,2EAA2E;QAC3E,iDAAiD;QACjD,MAAMF,eAAeF,IAAIK,OAAO;QAChC,IAAIH,cAAc;YAChBF,IAAIK,OAAO,GAAG;QAChB;QAEA,sEAAsE;QACtE,qDAAqD;QACrD,IAAIC,IAAAA,qBAAc,EAACtB,OAAOS,QAAQ,GAAG;YACnC,yEAAyE;YACzE,uEAAuE;YACvE,MAAM;YACN,sFAAsF;YACtF,IAAIT,OAAOuB,UAAU,EAAE;gBACrB,OAAO;YACT;YAEA,oEAAoE;YACpE,wEAAwE;YACxE,mEAAmE;YACnE,mBAAmB;YACnB,0EAA0E;YAC1E,IAAIL,gBAAgB,CAAClB,OAAOC,OAAO,EAAE;gBACnC,OAAO;YACT;QACF;QAEA,2EAA2E;QAC3E,2EAA2E;QAC3E,2BAA2B;QAC3B,kEAAkE;QAClE,IAAIuB;QACJ,IAAI;YACFA,MAAM,IAAIC,IAAIzB,OAAOK,MAAM,EAAE;QAC/B,EAAE,OAAOqB,GAAG;YACV,kDAAkD;YAClD,OAAO;QACT;QAEA,OAAOF,IAAIf,QAAQ;IACrB,GAAG;QAACT,OAAOK,MAAM;QAAEL,OAAOuB,UAAU;QAAEvB,OAAOC,OAAO;QAAED,OAAOS,QAAQ;KAAC;IAEtE,qBACE,qBAACkB,gDAAe,CAACC,QAAQ;QAACT,OAAOA;kBAC9BL;;AAGP","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/router.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/router.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d56d32ab90afcf68e35eb93660bc6d750d6cefd --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/router.d.ts @@ -0,0 +1,229 @@ +import type { ComponentType } from 'react'; +import type { DomainLocale } from '../../../server/config'; +import type { MittEmitter } from '../mitt'; +import type { ParsedUrlQuery } from 'querystring'; +import type { RouterEvent } from '../../../client/router'; +import type { StyleSheetTuple } from '../../../client/page-loader'; +import type { UrlObject } from 'url'; +import type PageLoader from '../../../client/page-loader'; +import type { NextPageContext, NEXT_DATA } from '../utils'; +declare global { + interface Window { + __NEXT_DATA__: NEXT_DATA; + } +} +interface RouteProperties { + shallow: boolean; +} +interface TransitionOptions { + shallow?: boolean; + locale?: string | false; + scroll?: boolean; + unstable_skipClientCache?: boolean; +} +interface NextHistoryState { + url: string; + as: string; + options: TransitionOptions; +} +export type HistoryState = null | { + __NA: true; + __N?: false; +} | { + __N: false; + __NA?: false; +} | ({ + __NA?: false; + __N: true; + key: string; +} & NextHistoryState); +interface MiddlewareEffectParams<T extends FetchDataOutput> { + fetchData?: () => Promise<T>; + locale?: string; + asPath: string; + router: Router; +} +export declare function matchesMiddleware<T extends FetchDataOutput>(options: MiddlewareEffectParams<T>): Promise<boolean>; +export type Url = UrlObject | string; +export type BaseRouter = { + route: string; + pathname: string; + query: ParsedUrlQuery; + asPath: string; + basePath: string; + locale?: string | undefined; + locales?: readonly string[] | undefined; + defaultLocale?: string | undefined; + domainLocales?: readonly DomainLocale[] | undefined; + isLocaleDomain: boolean; +}; +export type NextRouter = BaseRouter & Pick<Router, 'push' | 'replace' | 'reload' | 'back' | 'forward' | 'prefetch' | 'beforePopState' | 'events' | 'isFallback' | 'isReady' | 'isPreview'>; +export type PrefetchOptions = { + priority?: boolean; + locale?: string | false; + unstable_skipClientCache?: boolean; +}; +export type PrivateRouteInfo = (Omit<CompletePrivateRouteInfo, 'styleSheets'> & { + initial: true; +}) | CompletePrivateRouteInfo; +export type CompletePrivateRouteInfo = { + Component: ComponentType; + styleSheets: StyleSheetTuple[]; + __N_SSG?: boolean; + __N_SSP?: boolean; + props?: Record<string, any>; + err?: Error; + error?: any; + route?: string; + resolvedAs?: string; + query?: ParsedUrlQuery; +}; +export type AppProps = Pick<CompletePrivateRouteInfo, 'Component' | 'err'> & { + router: Router; +} & Record<string, any>; +export type AppComponent = ComponentType<AppProps>; +type Subscription = (data: PrivateRouteInfo, App: AppComponent, resetScroll: { + x: number; + y: number; +} | null) => Promise<void>; +type BeforePopStateCallback = (state: NextHistoryState) => boolean; +type ComponentLoadCancel = (() => void) | null; +type HistoryMethod = 'replaceState' | 'pushState'; +interface FetchDataOutput { + dataHref: string; + json: Record<string, any> | null; + response: Response; + text: string; + cacheKey: string; +} +interface NextDataCache { + [asPath: string]: Promise<FetchDataOutput>; +} +export declare function createKey(): string; +export default class Router implements BaseRouter { + basePath: string; + /** + * Map of all components loaded in `Router` + */ + components: { + [pathname: string]: PrivateRouteInfo; + }; + sdc: NextDataCache; + sbc: NextDataCache; + sub: Subscription; + clc: ComponentLoadCancel; + pageLoader: PageLoader; + _bps: BeforePopStateCallback | undefined; + events: MittEmitter<RouterEvent>; + _wrapApp: (App: AppComponent) => any; + isSsr: boolean; + _inFlightRoute?: string | undefined; + _shallow?: boolean | undefined; + locales?: readonly string[] | undefined; + defaultLocale?: string | undefined; + domainLocales?: readonly DomainLocale[] | undefined; + isReady: boolean; + isLocaleDomain: boolean; + isFirstPopStateEvent: boolean; + _initialMatchesMiddlewarePromise: Promise<boolean>; + _bfl_s?: import('../../lib/bloom-filter').BloomFilter; + _bfl_d?: import('../../lib/bloom-filter').BloomFilter; + private state; + private _key; + static events: MittEmitter<RouterEvent>; + constructor(pathname: string, query: ParsedUrlQuery, as: string, { initialProps, pageLoader, App, wrapApp, Component, err, subscription, isFallback, locale, locales, defaultLocale, domainLocales, isPreview, }: { + subscription: Subscription; + initialProps: any; + pageLoader: any; + Component: ComponentType; + App: AppComponent; + wrapApp: (WrapAppComponent: AppComponent) => any; + err?: Error; + isFallback: boolean; + locale?: string; + locales?: readonly string[]; + defaultLocale?: string; + domainLocales?: readonly DomainLocale[]; + isPreview?: boolean; + }); + onPopState: (e: PopStateEvent) => void; + reload(): void; + /** + * Go back in history + */ + back(): void; + /** + * Go forward in history + */ + forward(): void; + /** + * Performs a `pushState` with arguments + * @param url of the route + * @param as masks `url` for the browser + * @param options object you can define `shallow` and other options + */ + push(url: Url, as?: Url, options?: TransitionOptions): Promise<boolean>; + /** + * Performs a `replaceState` with arguments + * @param url of the route + * @param as masks `url` for the browser + * @param options object you can define `shallow` and other options + */ + replace(url: Url, as?: Url, options?: TransitionOptions): Promise<boolean>; + _bfl(as: string, resolvedAs?: string, locale?: string | false, skipNavigate?: boolean): Promise<unknown>; + private change; + changeState(method: HistoryMethod, url: string, as: string, options?: TransitionOptions): void; + handleRouteInfoError(err: Error & { + code?: any; + cancelled?: boolean; + }, pathname: string, query: ParsedUrlQuery, as: string, routeProps: RouteProperties, loadErrorFail?: boolean): Promise<CompletePrivateRouteInfo>; + getRouteInfo({ route: requestedRoute, pathname, query, as, resolvedAs, routeProps, locale, hasMiddleware, isPreview, unstable_skipClientCache, isQueryUpdating, isMiddlewareRewrite, isNotFound, }: { + route: string; + pathname: string; + query: ParsedUrlQuery; + as: string; + resolvedAs: string; + hasMiddleware?: boolean; + routeProps: RouteProperties; + locale: string | undefined; + isPreview: boolean; + unstable_skipClientCache?: boolean; + isQueryUpdating?: boolean; + isMiddlewareRewrite?: boolean; + isNotFound?: boolean; + }): Promise<{ + type: "redirect-external"; + destination: string; + } | { + type: "redirect-internal"; + newAs: string; + newUrl: string; + } | PrivateRouteInfo>; + private set; + /** + * Callback to execute before replacing router state + * @param cb callback to be executed + */ + beforePopState(cb: BeforePopStateCallback): void; + onlyAHashChange(as: string): boolean; + scrollToHash(as: string): void; + urlIsNew(asPath: string): boolean; + /** + * Prefetch page code, you may wait for the data during page rendering. + * This feature only works in production! + * @param url the href of prefetched page + * @param asPath the as path of the prefetched page + */ + prefetch(url: string, asPath?: string, options?: PrefetchOptions): Promise<void>; + fetchComponent(route: string): Promise<import("../../../client/page-loader").GoodPageCache>; + _getData<T>(fn: () => Promise<T>): Promise<T>; + getInitialProps(Component: ComponentType, ctx: NextPageContext): Promise<Record<string, any>>; + get route(): string; + get pathname(): string; + get query(): ParsedUrlQuery; + get asPath(): string; + get locale(): string | undefined; + get isFallback(): boolean; + get isPreview(): boolean; +} +export {}; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/router.js b/e-commerce/node_modules/next/dist/shared/lib/router/router.js new file mode 100644 index 0000000000000000000000000000000000000000..c2a69a68ad6c59fe6827e0f0b88c6c62f440ac75 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/router.js @@ -0,0 +1,1852 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + createKey: null, + default: null, + matchesMiddleware: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + createKey: function() { + return createKey; + }, + default: function() { + return Router; + }, + matchesMiddleware: function() { + return matchesMiddleware; + } +}); +const _interop_require_default = require("@swc/helpers/_/_interop_require_default"); +const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"); +const _removetrailingslash = require("./utils/remove-trailing-slash"); +const _routeloader = require("../../../client/route-loader"); +const _script = require("../../../client/script"); +const _iserror = /*#__PURE__*/ _interop_require_wildcard._(require("../../../lib/is-error")); +const _denormalizepagepath = require("../page-path/denormalize-page-path"); +const _normalizelocalepath = require("../i18n/normalize-locale-path"); +const _mitt = /*#__PURE__*/ _interop_require_default._(require("../mitt")); +const _utils = require("../utils"); +const _isdynamic = require("./utils/is-dynamic"); +const _parserelativeurl = require("./utils/parse-relative-url"); +const _routematcher = require("./utils/route-matcher"); +const _routeregex = require("./utils/route-regex"); +const _dynamicfilterpattern = require("./utils/dynamic-filter-pattern"); +const _formaturl = require("./utils/format-url"); +const _detectdomainlocale = require("../../../client/detect-domain-locale"); +const _parsepath = require("./utils/parse-path"); +const _addlocale = require("../../../client/add-locale"); +const _removelocale = require("../../../client/remove-locale"); +const _removebasepath = require("../../../client/remove-base-path"); +const _addbasepath = require("../../../client/add-base-path"); +const _hasbasepath = require("../../../client/has-base-path"); +const _resolvehref = require("../../../client/resolve-href"); +const _isapiroute = require("../../../lib/is-api-route"); +const _getnextpathnameinfo = require("./utils/get-next-pathname-info"); +const _formatnextpathnameinfo = require("./utils/format-next-pathname-info"); +const _comparestates = require("./utils/compare-states"); +const _islocalurl = require("./utils/is-local-url"); +const _isbot = require("./utils/is-bot"); +const _omit = require("./utils/omit"); +const _interpolateas = require("./utils/interpolate-as"); +const _disablesmoothscroll = require("./utils/disable-smooth-scroll"); +const _constants = require("../../../lib/constants"); +const _deploymentid = require("../deployment-id"); +const _javascripturl = require("../../../client/lib/javascript-url"); +let resolveRewrites; +if (process.env.__NEXT_HAS_REWRITES) { + resolveRewrites = require('./utils/resolve-rewrites').default; +} +function buildCancellationError() { + return Object.assign(new Error('Route Cancelled'), { + cancelled: true + }); +} +async function matchesMiddleware(options) { + const matchers = await Promise.resolve(options.router.pageLoader.getMiddleware()); + if (!matchers) return false; + const { pathname: asPathname } = (0, _parsepath.parsePath)(options.asPath); + // remove basePath first since path prefix has to be in the order of `/${basePath}/${locale}` + const cleanedAs = (0, _hasbasepath.hasBasePath)(asPathname) ? (0, _removebasepath.removeBasePath)(asPathname) : asPathname; + const asWithBasePathAndLocale = (0, _addbasepath.addBasePath)((0, _addlocale.addLocale)(cleanedAs, options.locale)); + // Check only path match on client. Matching "has" should be done on server + // where we can access more info such as headers, HttpOnly cookie, etc. + return matchers.some((m)=>new RegExp(m.regexp).test(asWithBasePathAndLocale)); +} +function stripOrigin(url) { + const origin = (0, _utils.getLocationOrigin)(); + return url.startsWith(origin) ? url.substring(origin.length) : url; +} +function prepareUrlAs(router, url, as) { + // If url and as provided as an object representation, + // we'll format them into the string version here. + let [resolvedHref, resolvedAs] = (0, _resolvehref.resolveHref)(router, url, true); + const origin = (0, _utils.getLocationOrigin)(); + const hrefWasAbsolute = resolvedHref.startsWith(origin); + const asWasAbsolute = resolvedAs && resolvedAs.startsWith(origin); + resolvedHref = stripOrigin(resolvedHref); + resolvedAs = resolvedAs ? stripOrigin(resolvedAs) : resolvedAs; + const preparedUrl = hrefWasAbsolute ? resolvedHref : (0, _addbasepath.addBasePath)(resolvedHref); + const preparedAs = as ? stripOrigin((0, _resolvehref.resolveHref)(router, as)) : resolvedAs || resolvedHref; + return { + url: preparedUrl, + as: asWasAbsolute ? preparedAs : (0, _addbasepath.addBasePath)(preparedAs) + }; +} +/** + * Key under which `prefetch()` stores the `{ __appRouter: true }` marker in + * `router.components` and under which `change()` looks it up again. + * + * The client router filter (`_bfl`) is evaluated against the `as` path, so the + * marker has to be keyed by the `as` path as well. Keying it by the `href` + * pathname is only equivalent while `href` and `as` are the same URL. When + * they differ (for example the "route as modal" pattern where `href` stays on + * the current page and `as` shows a pretty URL) a filter match on `as` would + * otherwise mark the pages route behind `href` as an App Router path and + * break every later navigation to that route. + * + * `as` is expected without the `basePath`, which is what both call sites + * hold: `prefetch()` receives it that way from `next/link` and `change()` + * strips it before computing `cleanedAs`. Stripping it again here would turn + * a route that merely starts with the `basePath` (for example the app route + * `/docs` with `basePath: '/docs'`) into `/` and poison the index page. + * + * The key also carries the effective locale, mirroring how `_bfl` evaluates + * `addLocale(as, locale)` against the filter. A match for a French-only + * redirect at `/fr/legacy` must not mark the English `/legacy` page. + * + * Returns `null` when `as` is not a local URL (for example `mailto:` or a + * different origin). Such an `as` can never be an App Router path, and + * `change()` reports it as an invalid `href`/`as` pair further down. + */ function getAppRouterMarkerKey(router, as, locale) { + if (!(0, _islocalurl.isLocalURL)(as)) { + return null; + } + let { pathname } = (0, _parserelativeurl.parseRelativeUrl)(as); + let effectiveLocale = locale || router.locale; + if (process.env.__NEXT_I18N_SUPPORT) { + const localePathResult = (0, _normalizelocalepath.normalizeLocalePath)(pathname, router.locales); + pathname = localePathResult.pathname; + effectiveLocale = localePathResult.detectedLocale || effectiveLocale; + } + return (0, _removetrailingslash.removeTrailingSlash)((0, _addlocale.addLocale)((0, _removetrailingslash.removeTrailingSlash)(pathname), effectiveLocale)); +} +function resolveDynamicRoute(pathname, pages) { + const cleanPathname = (0, _removetrailingslash.removeTrailingSlash)((0, _denormalizepagepath.denormalizePagePath)(pathname)); + if (cleanPathname === '/404' || cleanPathname === '/_error') { + return pathname; + } + // handle resolving href for dynamic routes + if (!pages.includes(cleanPathname)) { + // eslint-disable-next-line array-callback-return + pages.some((page)=>{ + if ((0, _isdynamic.isDynamicRoute)(page) && (0, _routeregex.getRouteRegex)(page).re.test(cleanPathname)) { + pathname = page; + return true; + } + }); + } + return (0, _removetrailingslash.removeTrailingSlash)(pathname); +} +function getMiddlewareData(source, response, options) { + const nextConfig = { + basePath: options.router.basePath, + i18n: { + locales: options.router.locales + }, + trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH) + }; + const rewriteHeader = response.headers.get('x-nextjs-rewrite'); + let rewriteTarget = rewriteHeader || response.headers.get('x-nextjs-matched-path'); + const matchedPath = response.headers.get(_constants.MATCHED_PATH_HEADER); + if (matchedPath && !rewriteTarget && !matchedPath.includes('__next_data_catchall') && !matchedPath.includes('/_error') && !matchedPath.includes('/404')) { + // leverage x-matched-path to detect next.config.js rewrites + rewriteTarget = matchedPath; + } + if (rewriteTarget) { + if (rewriteTarget.startsWith('/') || process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE) { + const parsedRewriteTarget = (0, _parserelativeurl.parseRelativeUrl)(rewriteTarget); + const pathnameInfo = (0, _getnextpathnameinfo.getNextPathnameInfo)(parsedRewriteTarget.pathname, { + nextConfig, + parseData: true + }); + let fsPathname = (0, _removetrailingslash.removeTrailingSlash)(pathnameInfo.pathname); + return Promise.all([ + options.router.pageLoader.getPageList(), + (0, _routeloader.getClientBuildManifest)() + ]).then(([pages, { __rewrites: rewrites }])=>{ + let as = (0, _addlocale.addLocale)(pathnameInfo.pathname, pathnameInfo.locale); + if ((0, _isdynamic.isDynamicRoute)(as) || !rewriteHeader && pages.includes((0, _normalizelocalepath.normalizeLocalePath)((0, _removebasepath.removeBasePath)(as), options.router.locales).pathname)) { + const parsedSource = (0, _getnextpathnameinfo.getNextPathnameInfo)((0, _parserelativeurl.parseRelativeUrl)(source).pathname, { + // Pass basePath (and trailingSlash) so the basePath prefix is + // stripped before the `_next/data/` check, but omit `i18n` so the + // locale prefix is preserved here — the rewrite resolver below + // handles the locale-prefixed `as`. + nextConfig: { + basePath: nextConfig.basePath, + trailingSlash: nextConfig.trailingSlash + }, + parseData: true + }); + as = (0, _addbasepath.addBasePath)(parsedSource.pathname); + parsedRewriteTarget.pathname = as; + } + if (process.env.__NEXT_HAS_REWRITES) { + const result = resolveRewrites(as, pages, rewrites, parsedRewriteTarget.query, (path)=>resolveDynamicRoute(path, pages), options.router.locales); + if (result.matchedPage) { + parsedRewriteTarget.pathname = result.parsedAs.pathname; + as = parsedRewriteTarget.pathname; + Object.assign(parsedRewriteTarget.query, result.parsedAs.query); + } + } else if (!pages.includes(fsPathname)) { + const resolvedPathname = resolveDynamicRoute(fsPathname, pages); + if (resolvedPathname !== fsPathname) { + fsPathname = resolvedPathname; + } + } + const resolvedHref = !pages.includes(fsPathname) ? resolveDynamicRoute((0, _normalizelocalepath.normalizeLocalePath)((0, _removebasepath.removeBasePath)(parsedRewriteTarget.pathname), options.router.locales).pathname, pages) : fsPathname; + if ((0, _isdynamic.isDynamicRoute)(resolvedHref)) { + const matches = (0, _routematcher.getRouteMatcher)((0, _routeregex.getRouteRegex)(resolvedHref))(as); + Object.assign(parsedRewriteTarget.query, matches || {}); + } + return { + type: 'rewrite', + parsedAs: parsedRewriteTarget, + resolvedHref + }; + }); + } + const src = (0, _parsepath.parsePath)(source); + const pathname = (0, _formatnextpathnameinfo.formatNextPathnameInfo)({ + ...(0, _getnextpathnameinfo.getNextPathnameInfo)(src.pathname, { + nextConfig, + parseData: true + }), + defaultLocale: options.router.defaultLocale, + buildId: '' + }); + return Promise.resolve({ + type: 'redirect-external', + destination: `${pathname}${src.query}${src.hash}` + }); + } + const redirectTarget = response.headers.get('x-nextjs-redirect'); + if (redirectTarget) { + if (redirectTarget.startsWith('/')) { + const src = (0, _parsepath.parsePath)(redirectTarget); + const pathname = (0, _formatnextpathnameinfo.formatNextPathnameInfo)({ + ...(0, _getnextpathnameinfo.getNextPathnameInfo)(src.pathname, { + nextConfig, + parseData: true + }), + defaultLocale: options.router.defaultLocale, + buildId: '' + }); + return Promise.resolve({ + type: 'redirect-internal', + newAs: `${pathname}${src.query}${src.hash}`, + newUrl: `${pathname}${src.query}${src.hash}` + }); + } + return Promise.resolve({ + type: 'redirect-external', + destination: redirectTarget + }); + } + return Promise.resolve({ + type: 'next' + }); +} +async function withMiddlewareEffects(options) { + const matches = await matchesMiddleware(options); + if (!matches || !options.fetchData) { + return null; + } + const data = await options.fetchData(); + const effect = await getMiddlewareData(data.dataHref, data.response, options); + return { + dataHref: data.dataHref, + json: data.json, + response: data.response, + text: data.text, + cacheKey: data.cacheKey, + effect + }; +} +const manualScrollRestoration = process.env.__NEXT_SCROLL_RESTORATION && typeof window !== 'undefined' && 'scrollRestoration' in window.history && !!function() { + try { + let v = '__next'; + return sessionStorage.setItem(v, v), sessionStorage.removeItem(v), true; + } catch (n) {} +}(); +const SSG_DATA_NOT_FOUND = Symbol('SSG_DATA_NOT_FOUND'); +function fetchRetry(url, attempts, options) { + return fetch(url, { + // Cookies are required to be present for Next.js' SSG "Preview Mode". + // Cookies may also be required for `getServerSideProps`. + // + // > `fetch` won’t send cookies, unless you set the credentials init + // > option. + // https://developer.mozilla.org/docs/Web/API/Fetch_API/Using_Fetch + // + // > For maximum browser compatibility when it comes to sending & + // > receiving cookies, always supply the `credentials: 'same-origin'` + // > option instead of relying on the default. + // https://github.com/github/fetch#caveats + credentials: 'same-origin', + method: options.method || 'GET', + headers: Object.assign({}, options.headers, { + 'x-nextjs-data': '1' + }) + }).then((response)=>{ + return !response.ok && attempts > 1 && response.status >= 500 ? fetchRetry(url, attempts - 1, options) : response; + }); +} +function tryToParseAsJSON(text) { + try { + return JSON.parse(text); + } catch (error) { + return null; + } +} +function fetchNextData({ dataHref, inflightCache, isPrefetch, hasMiddleware, isServerRender, parseJSON, persistCache, isBackground, unstable_skipClientCache }) { + const { href: cacheKey } = new URL(dataHref, window.location.href); + const deploymentId = (0, _deploymentid.getDeploymentId)(); + const getData = (params)=>fetchRetry(dataHref, isServerRender ? 3 : 1, { + headers: Object.assign({}, isPrefetch ? { + purpose: 'prefetch' + } : {}, isPrefetch && hasMiddleware ? { + 'x-middleware-prefetch': '1' + } : {}, deploymentId ? { + 'x-deployment-id': deploymentId + } : {}), + method: params?.method ?? 'GET' + }).then((response)=>{ + if (response.ok && params?.method === 'HEAD') { + return { + dataHref, + response, + text: '', + json: {}, + cacheKey + }; + } + return response.text().then((text)=>{ + if (!response.ok) { + /** + * When the data response is a redirect because of a middleware + * we do not consider it an error. The headers must bring the + * mapped location. + * TODO: Change the status code in the handler. + */ if (hasMiddleware && [ + 301, + 302, + 307, + 308 + ].includes(response.status)) { + return { + dataHref, + response, + text, + json: {}, + cacheKey + }; + } + if (response.status === 404) { + if (tryToParseAsJSON(text)?.notFound) { + return { + dataHref, + json: { + notFound: SSG_DATA_NOT_FOUND + }, + response, + text, + cacheKey + }; + } + } + const error = new Error(`Failed to load static props`); + /** + * We should only trigger a server-side transition if this was + * caused on a client-side transition. Otherwise, we'd get into + * an infinite loop. + */ if (!isServerRender) { + (0, _routeloader.markAssetError)(error); + } + throw error; + } + let dplResponseHeader = response.headers.get(_constants.NEXT_NAV_DEPLOYMENT_ID_HEADER); + if (dplResponseHeader != null && dplResponseHeader !== deploymentId) { + // When not found, or we want to force a MPA navigation because of Skew Protection + const error = new Error(`Loaded static props were from an outdated deployment, forcing a hard reload`); + /** + * We should only trigger a server-side transition if this was + * caused on a client-side transition. Otherwise, we'd get into + * an infinite loop. + */ if (!isServerRender) { + (0, _routeloader.markAssetError)(error); + } + throw error; + } + return { + dataHref, + json: parseJSON ? tryToParseAsJSON(text) : null, + response, + text, + cacheKey + }; + }); + }).then((data)=>{ + if (!persistCache || process.env.NODE_ENV !== 'production' || data.response.headers.get('x-middleware-cache') === 'no-cache') { + delete inflightCache[cacheKey]; + } + return data; + }).catch((err)=>{ + if (!unstable_skipClientCache) { + delete inflightCache[cacheKey]; + } + if (// chrome + err.message === 'Failed to fetch' || // firefox + err.message === 'NetworkError when attempting to fetch resource.' || // safari + err.message === 'Load failed') { + (0, _routeloader.markAssetError)(err); + } + throw err; + }); + // when skipping client cache we wait to update + // inflight cache until successful data response + // this allows racing click event with fetching newer data + // without blocking navigation when stale data is available + if (unstable_skipClientCache && persistCache) { + return getData({}).then((data)=>{ + if (data.response.headers.get('x-middleware-cache') !== 'no-cache') { + // only update cache if not marked as no-cache + inflightCache[cacheKey] = Promise.resolve(data); + } + return data; + }); + } + if (inflightCache[cacheKey] !== undefined) { + return inflightCache[cacheKey]; + } + return inflightCache[cacheKey] = getData(isBackground ? { + method: 'HEAD' + } : {}); +} +function createKey() { + return Math.random().toString(36).slice(2, 10); +} +function handleHardNavigation({ url, router }) { + // ensure we don't trigger a hard navigation to the same + // URL as this can end up with an infinite refresh + if (url === (0, _addbasepath.addBasePath)((0, _addlocale.addLocale)(router.asPath, router.locale))) { + throw new Error(`Invariant: attempted to hard navigate to the same URL ${url} ${location.href}`); + } + window.location.href = url; +} +const getCancelledHandler = ({ route, router })=>{ + let cancelled = false; + const cancel = router.clc = ()=>{ + cancelled = true; + }; + const handleCancelled = ()=>{ + if (cancelled) { + const error = new Error(`Abort fetching component for route: "${route}"`); + error.cancelled = true; + throw error; + } + if (cancel === router.clc) { + router.clc = null; + } + }; + return handleCancelled; +}; +class Router { + static{ + this.events = (0, _mitt.default)(); + } + constructor(pathname, query, as, { initialProps, pageLoader, App, wrapApp, Component, err, subscription, isFallback, locale, locales, defaultLocale, domainLocales, isPreview }){ + // Server Data Cache (full data requests) + this.sdc = {}; + // Server Background Cache (HEAD requests) + this.sbc = {}; + this.isFirstPopStateEvent = true; + this._key = createKey(); + this.onPopState = (e)=>{ + const { isFirstPopStateEvent } = this; + this.isFirstPopStateEvent = false; + const state = e.state; + if (!state) { + // We get state as undefined for two reasons. + // 1. With older safari (< 8) and older chrome (< 34) + // 2. When the URL changed with # + // + // In the both cases, we don't need to proceed and change the route. + // (as it's already changed) + // But we can simply replace the state with the new changes. + // Actually, for (1) we don't need to nothing. But it's hard to detect that event. + // So, doing the following for (1) does no harm. + const { pathname, query } = this; + this.changeState('replaceState', (0, _formaturl.formatWithValidation)({ + pathname: (0, _addbasepath.addBasePath)(pathname), + query + }), (0, _utils.getURL)()); + return; + } + // __NA is used to identify if the history entry can be handled by the app-router. + if (state.__NA) { + window.location.reload(); + return; + } + if (!state.__N) { + return; + } + // Safari fires popstateevent when reopening the browser. + if (isFirstPopStateEvent && this.locale === state.options.locale && state.as === this.asPath) { + return; + } + let forcedScroll; + const { url, as, options, key } = state; + if (process.env.__NEXT_SCROLL_RESTORATION) { + if (manualScrollRestoration) { + if (this._key !== key) { + // Snapshot current scroll position: + try { + sessionStorage.setItem('__next_scroll_' + this._key, JSON.stringify({ + x: self.pageXOffset, + y: self.pageYOffset + })); + } catch {} + // Restore old scroll position: + try { + const v = sessionStorage.getItem('__next_scroll_' + key); + forcedScroll = JSON.parse(v); + } catch { + forcedScroll = { + x: 0, + y: 0 + }; + } + } + } + } + this._key = key; + const { pathname } = (0, _parserelativeurl.parseRelativeUrl)(url); + // Make sure we don't re-render on initial load, + // can be caused by navigating back from an external site + if (this.isSsr && as === (0, _addbasepath.addBasePath)(this.asPath) && pathname === (0, _addbasepath.addBasePath)(this.pathname)) { + return; + } + // If the downstream application returns falsy, return. + // They will then be responsible for handling the event. + if (this._bps && !this._bps(state)) { + return; + } + this.change('replaceState', url, as, Object.assign({}, options, { + shallow: options.shallow && this._shallow, + locale: options.locale || this.defaultLocale, + // @ts-ignore internal value not exposed on types + _h: 0 + }), forcedScroll); + }; + // represents the current component key + const route = (0, _removetrailingslash.removeTrailingSlash)(pathname); + // set up the component cache (by route keys) + this.components = {}; + // We should not keep the cache, if there's an error + // Otherwise, this cause issues when when going back and + // come again to the errored page. + if (pathname !== '/_error') { + this.components[route] = { + Component, + initial: true, + props: initialProps, + err, + __N_SSG: initialProps && initialProps.__N_SSG, + __N_SSP: initialProps && initialProps.__N_SSP + }; + } + this.components['/_app'] = { + Component: App, + styleSheets: [] + }; + // Backwards compat for Router.router.events + // TODO: Should be remove the following major version as it was never documented + this.events = Router.events; + this.pageLoader = pageLoader; + // if auto prerendered and dynamic route wait to update asPath + // until after mount to prevent hydration mismatch + const autoExportDynamic = (0, _isdynamic.isDynamicRoute)(pathname) && self.__NEXT_DATA__.autoExport; + this.basePath = process.env.__NEXT_ROUTER_BASEPATH || ''; + this.sub = subscription; + this.clc = null; + this._wrapApp = wrapApp; + // make sure to ignore extra popState in safari on navigating + // back from external site + this.isSsr = true; + this.isLocaleDomain = false; + this.isReady = !!(self.__NEXT_DATA__.gssp || self.__NEXT_DATA__.gip || self.__NEXT_DATA__.isExperimentalCompile || self.__NEXT_DATA__.appGip && !self.__NEXT_DATA__.gsp || !autoExportDynamic && !self.location.search && !process.env.__NEXT_HAS_REWRITES); + if (process.env.__NEXT_I18N_SUPPORT) { + this.locales = locales; + this.defaultLocale = defaultLocale; + this.domainLocales = domainLocales; + this.isLocaleDomain = !!(0, _detectdomainlocale.detectDomainLocale)(domainLocales, self.location.hostname); + } + this.state = { + route, + pathname, + query, + asPath: autoExportDynamic ? pathname : as, + isPreview: !!isPreview, + locale: process.env.__NEXT_I18N_SUPPORT ? locale : undefined, + isFallback + }; + this._initialMatchesMiddlewarePromise = Promise.resolve(false); + if (typeof window !== 'undefined') { + // make sure "as" doesn't start with double slashes or else it can + // throw an error as it's considered invalid + if (!as.startsWith('//')) { + // in order for `e.state` to work on the `onpopstate` event + // we have to register the initial route upon initialization + const options = { + locale + }; + const asPath = (0, _utils.getURL)(); + this._initialMatchesMiddlewarePromise = matchesMiddleware({ + router: this, + locale, + asPath + }).then((matches)=>{ + // if middleware matches we leave resolving to the change function + // as the server needs to resolve for correct priority + ; + options._shouldResolveHref = as !== pathname; + this.changeState('replaceState', matches ? asPath : (0, _formaturl.formatWithValidation)({ + pathname: (0, _addbasepath.addBasePath)(pathname), + query + }), asPath, options); + return matches; + }); + } + window.addEventListener('popstate', this.onPopState); + // enable custom scroll restoration handling when available + // otherwise fallback to browser's default handling + if (process.env.__NEXT_SCROLL_RESTORATION) { + if (manualScrollRestoration) { + window.history.scrollRestoration = 'manual'; + } + } + } + } + reload() { + window.location.reload(); + } + /** + * Go back in history + */ back() { + window.history.back(); + } + /** + * Go forward in history + */ forward() { + window.history.forward(); + } + /** + * Performs a `pushState` with arguments + * @param url of the route + * @param as masks `url` for the browser + * @param options object you can define `shallow` and other options + */ push(url, as, options = {}) { + if ((0, _javascripturl.isJavaScriptURLString)(url.toString()) || as && (0, _javascripturl.isJavaScriptURLString)(as.toString())) { + throw new Error('Next.js has blocked a javascript: URL as a security precaution.'); + } + if (process.env.__NEXT_SCROLL_RESTORATION) { + // TODO: remove in the future when we update history before route change + // is complete, as the popstate event should handle this capture. + if (manualScrollRestoration) { + try { + // Snapshot scroll position right before navigating to a new page: + sessionStorage.setItem('__next_scroll_' + this._key, JSON.stringify({ + x: self.pageXOffset, + y: self.pageYOffset + })); + } catch {} + } + } + ; + ({ url, as } = prepareUrlAs(this, url, as)); + return this.change('pushState', url, as, options); + } + /** + * Performs a `replaceState` with arguments + * @param url of the route + * @param as masks `url` for the browser + * @param options object you can define `shallow` and other options + */ replace(url, as, options = {}) { + if ((0, _javascripturl.isJavaScriptURLString)(url.toString()) || as && (0, _javascripturl.isJavaScriptURLString)(as.toString())) { + throw new Error('Next.js has blocked a javascript: URL as a security precaution.'); + } + ; + ({ url, as } = prepareUrlAs(this, url, as)); + return this.change('replaceState', url, as, options); + } + async _bfl(as, resolvedAs, locale, skipNavigate) { + if (process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED) { + if (!this._bfl_s && !this._bfl_d) { + const { BloomFilter } = require('../../lib/bloom-filter'); + let staticFilterData; + let dynamicFilterData; + try { + ; + ({ __routerFilterStatic: staticFilterData, __routerFilterDynamic: dynamicFilterData } = await (0, _routeloader.getClientBuildManifest)()); + } catch (err) { + // failed to load build manifest hard navigate + // to be safe + console.error(err); + if (skipNavigate) { + return true; + } + handleHardNavigation({ + url: (0, _addbasepath.addBasePath)((0, _addlocale.addLocale)(as, locale || this.locale, this.defaultLocale)), + router: this + }); + return new Promise(()=>{}); + } + const routerFilterSValue = process.env.__NEXT_CLIENT_ROUTER_S_FILTER; + if (!staticFilterData && routerFilterSValue) { + staticFilterData = routerFilterSValue ? routerFilterSValue : undefined; + } + const routerFilterDValue = process.env.__NEXT_CLIENT_ROUTER_D_FILTER; + if (!dynamicFilterData && routerFilterDValue) { + dynamicFilterData = routerFilterDValue ? routerFilterDValue : undefined; + } + if (staticFilterData?.numHashes) { + this._bfl_s = new BloomFilter(staticFilterData.numItems, staticFilterData.errorRate); + this._bfl_s.import(staticFilterData); + } + if (dynamicFilterData?.numHashes) { + this._bfl_d = new BloomFilter(dynamicFilterData.numItems, dynamicFilterData.errorRate); + this._bfl_d.import(dynamicFilterData); + } + } + let matchesBflStatic = false; + let matchesBflDynamic = false; + const pathsToCheck = [ + { + as + }, + { + as: resolvedAs + } + ]; + for (const { as: curAs, allowMatchCurrent } of pathsToCheck){ + if (curAs) { + const asNoSlash = (0, _removetrailingslash.removeTrailingSlash)(new URL(curAs, 'http://n').pathname); + const asNoSlashLocale = (0, _addbasepath.addBasePath)((0, _addlocale.addLocale)(asNoSlash, locale || this.locale)); + if (allowMatchCurrent || asNoSlash !== (0, _removetrailingslash.removeTrailingSlash)(new URL(this.asPath, 'http://n').pathname)) { + matchesBflStatic = matchesBflStatic || !!this._bfl_s?.contains(asNoSlash) || !!this._bfl_s?.contains(asNoSlashLocale); + for (const normalizedAS of [ + asNoSlash, + asNoSlashLocale + ]){ + // if any sub-path of as matches a dynamic filter path + // it should be hard navigated + const curAsParts = normalizedAS.split('/'); + for(let i = 0; !matchesBflDynamic && i < curAsParts.length + 1; i++){ + const currentPart = curAsParts.slice(0, i).join('/'); + if (currentPart && this._bfl_d?.contains(currentPart)) { + matchesBflDynamic = true; + break; + } + } + } + // if the client router filter is matched then we trigger + // a hard navigation + if (matchesBflStatic || matchesBflDynamic) { + if (skipNavigate) { + return true; + } + handleHardNavigation({ + url: (0, _addbasepath.addBasePath)((0, _addlocale.addLocale)(as, locale || this.locale, this.defaultLocale)), + router: this + }); + return new Promise(()=>{}); + } + } + } + } + } + return false; + } + async change(method, url, as, options, forcedScroll) { + if (!(0, _islocalurl.isLocalURL)(url)) { + handleHardNavigation({ + url, + router: this + }); + return false; + } + // WARNING: `_h` is an internal option for handing Next.js client-side + // hydration. Your app should _never_ use this property. It may change at + // any time without notice. + const isQueryUpdating = options._h === 1; + if (!isQueryUpdating && !options.shallow) { + await this._bfl(as, undefined, options.locale); + } + let shouldResolveHref = isQueryUpdating || options._shouldResolveHref || (0, _parsepath.parsePath)(url).pathname === (0, _parsepath.parsePath)(as).pathname; + const nextState = { + ...this.state + }; + // for static pages with query params in the URL we delay + // marking the router ready until after the query is updated + // or a navigation has occurred + const readyStateChange = this.isReady !== true; + this.isReady = true; + const isSsr = this.isSsr; + if (!isQueryUpdating) { + this.isSsr = false; + } + // if a route transition is already in progress before + // the query updating is triggered ignore query updating + if (isQueryUpdating && this.clc) { + return false; + } + const prevLocale = nextState.locale; + if (process.env.__NEXT_I18N_SUPPORT) { + nextState.locale = options.locale === false ? this.defaultLocale : options.locale || nextState.locale; + if (typeof options.locale === 'undefined') { + options.locale = nextState.locale; + } + const parsedAs = (0, _parserelativeurl.parseRelativeUrl)((0, _hasbasepath.hasBasePath)(as) ? (0, _removebasepath.removeBasePath)(as) : as); + const localePathResult = (0, _normalizelocalepath.normalizeLocalePath)(parsedAs.pathname, this.locales); + if (localePathResult.detectedLocale) { + nextState.locale = localePathResult.detectedLocale; + parsedAs.pathname = (0, _addbasepath.addBasePath)(parsedAs.pathname); + as = (0, _formaturl.formatWithValidation)(parsedAs); + url = (0, _addbasepath.addBasePath)((0, _normalizelocalepath.normalizeLocalePath)((0, _hasbasepath.hasBasePath)(url) ? (0, _removebasepath.removeBasePath)(url) : url, this.locales).pathname); + } + let didNavigate = false; + // we need to wrap this in the env check again since regenerator runtime + // moves this on its own due to the return + if (process.env.__NEXT_I18N_SUPPORT) { + // if the locale isn't configured hard navigate to show 404 page + if (!this.locales?.includes(nextState.locale)) { + parsedAs.pathname = (0, _addlocale.addLocale)(parsedAs.pathname, nextState.locale); + handleHardNavigation({ + url: (0, _formaturl.formatWithValidation)(parsedAs), + router: this + }); + // this was previously a return but was removed in favor + // of better dead code elimination with regenerator runtime + didNavigate = true; + } + } + const detectedDomain = (0, _detectdomainlocale.detectDomainLocale)(this.domainLocales, undefined, nextState.locale); + // we need to wrap this in the env check again since regenerator runtime + // moves this on its own due to the return + if (process.env.__NEXT_I18N_SUPPORT) { + // if we are navigating to a domain locale ensure we redirect to the + // correct domain + if (!didNavigate && detectedDomain && this.isLocaleDomain && self.location.hostname !== detectedDomain.domain) { + const asNoBasePath = (0, _removebasepath.removeBasePath)(as); + handleHardNavigation({ + url: `http${detectedDomain.http ? '' : 's'}://${detectedDomain.domain}${(0, _addbasepath.addBasePath)(`${nextState.locale === detectedDomain.defaultLocale ? '' : `/${nextState.locale}`}${asNoBasePath === '/' ? '' : asNoBasePath}` || '/')}`, + router: this + }); + // this was previously a return but was removed in favor + // of better dead code elimination with regenerator runtime + didNavigate = true; + } + } + if (didNavigate) { + return new Promise(()=>{}); + } + } + // marking route changes as a navigation start entry + if (_utils.ST) { + performance.mark('routeChange'); + } + const { shallow = false, scroll = true } = options; + const routeProps = { + shallow + }; + if (this._inFlightRoute && this.clc) { + if (!isSsr) { + Router.events.emit('routeChangeError', buildCancellationError(), this._inFlightRoute, routeProps); + } + this.clc(); + this.clc = null; + } + as = (0, _addbasepath.addBasePath)((0, _addlocale.addLocale)((0, _hasbasepath.hasBasePath)(as) ? (0, _removebasepath.removeBasePath)(as) : as, options.locale, this.defaultLocale)); + const cleanedAs = (0, _removelocale.removeLocale)((0, _hasbasepath.hasBasePath)(as) ? (0, _removebasepath.removeBasePath)(as) : as, nextState.locale); + this._inFlightRoute = as; + const localeChange = prevLocale !== nextState.locale; + // If the url change is only related to a hash change + // We should not proceed. We should only change the state. + if (!isQueryUpdating && this.onlyAHashChange(cleanedAs) && !localeChange) { + nextState.asPath = cleanedAs; + Router.events.emit('hashChangeStart', as, routeProps); + // TODO: do we need the resolved href when only a hash change? + this.changeState(method, url, as, { + ...options, + scroll: false + }); + if (scroll) { + this.scrollToHash(cleanedAs); + } + try { + await this.set(nextState, this.components[nextState.route], null); + } catch (err) { + if ((0, _iserror.default)(err) && err.cancelled) { + Router.events.emit('routeChangeError', err, cleanedAs, routeProps); + } + throw err; + } + Router.events.emit('hashChangeComplete', as, routeProps); + return true; + } + let parsed = (0, _parserelativeurl.parseRelativeUrl)(url); + let { pathname, query } = parsed; + // The build manifest needs to be loaded before auto-static dynamic pages + // get their query parameters to allow ensuring they can be parsed properly + // when rewritten to + let pages, rewrites; + try { + ; + [pages, { __rewrites: rewrites }] = await Promise.all([ + this.pageLoader.getPageList(), + (0, _routeloader.getClientBuildManifest)(), + this.pageLoader.getMiddleware() + ]); + } catch (err) { + // If we fail to resolve the page list or client-build manifest, we must + // do a server-side transition: + handleHardNavigation({ + url: as, + router: this + }); + return false; + } + // If asked to change the current URL we should reload the current page + // (not location.reload() but reload getInitialProps and other Next.js stuffs) + // We also need to set the method = replaceState always + // as this should not go into the history (That's how browsers work) + // We should compare the new asPath to the current asPath, not the url + if (!this.urlIsNew(cleanedAs) && !localeChange) { + method = 'replaceState'; + } + // we need to resolve the as value using rewrites for dynamic SSG + // pages to allow building the data URL correctly + let resolvedAs = as; + // url and as should always be prefixed with basePath by this + // point by either next/link or router.push/replace so strip the + // basePath from the pathname to match the pages dir 1-to-1 + pathname = pathname ? (0, _removetrailingslash.removeTrailingSlash)((0, _removebasepath.removeBasePath)(pathname)) : pathname; + let route = (0, _removetrailingslash.removeTrailingSlash)(pathname); + const parsedAsPathname = as.startsWith('/') && (0, _parserelativeurl.parseRelativeUrl)(as).pathname; + // if we detected the `as` path as app route during prefetching + // trigger hard navigation. The marker is keyed by the `as` path, but a + // marker can also sit under the href route when both paths share a + // pages route (`pages/modal.js` next to `app/modal/[id]/page.js`). + // Check both so `getRouteInfo()` never reads a marker as component data. + const appRouterMarkerKey = getAppRouterMarkerKey(this, cleanedAs, nextState.locale); + if (appRouterMarkerKey !== null && this.components[appRouterMarkerKey]?.__appRouter || this.components[route]?.__appRouter) { + handleHardNavigation({ + url: as, + router: this + }); + return new Promise(()=>{}); + } + const isMiddlewareRewrite = !!(parsedAsPathname && route !== parsedAsPathname && (!(0, _isdynamic.isDynamicRoute)(route) || !(0, _routematcher.getRouteMatcher)((0, _routeregex.getRouteRegex)(route))(parsedAsPathname))); + // we don't attempt resolve asPath when we need to execute + // middleware as the resolving will occur server-side + const isMiddlewareMatch = !options.shallow && await matchesMiddleware({ + asPath: as, + locale: nextState.locale, + router: this + }); + if (isQueryUpdating && isMiddlewareMatch) { + shouldResolveHref = false; + } + if (shouldResolveHref && pathname !== '/_error') { + ; + options._shouldResolveHref = true; + if (process.env.__NEXT_HAS_REWRITES && as.startsWith('/')) { + const rewritesResult = resolveRewrites((0, _addbasepath.addBasePath)((0, _addlocale.addLocale)(cleanedAs, nextState.locale), true), pages, rewrites, query, (p)=>resolveDynamicRoute(p, pages), this.locales); + if (rewritesResult.externalDest) { + handleHardNavigation({ + url: as, + router: this + }); + return true; + } + if (!isMiddlewareMatch) { + resolvedAs = rewritesResult.asPath; + } + if (rewritesResult.matchedPage && rewritesResult.resolvedHref) { + // if this directly matches a page we need to update the href to + // allow the correct page chunk to be loaded + pathname = rewritesResult.resolvedHref; + parsed.pathname = (0, _addbasepath.addBasePath)(pathname); + if (!isMiddlewareMatch) { + url = (0, _formaturl.formatWithValidation)(parsed); + } + } + } else { + parsed.pathname = resolveDynamicRoute(pathname, pages); + if (parsed.pathname !== pathname) { + pathname = parsed.pathname; + parsed.pathname = (0, _addbasepath.addBasePath)(pathname); + if (!isMiddlewareMatch) { + url = (0, _formaturl.formatWithValidation)(parsed); + } + } + } + } + // The pages client router resolves a navigation against pages routes only. + // When it resolves to a dynamic pages route, an app route that begins with + // a dynamic segment may be more specific and own this path on the server + // (e.g. `/en/about` resolves to the pages route `/[locale]/[category]`, but + // the app route `/[locale]/about` should win). Such app routes have no + // static prefix for the early `_bfl` check, so reconstruct the candidate + // patterns from the resolved route and hard navigate when one is in the + // dynamic filter. + if (!isQueryUpdating && !options.shallow && process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED && this._bfl_d && (0, _isdynamic.isDynamicRoute)(pathname)) { + const concretePathname = (0, _removetrailingslash.removeTrailingSlash)((0, _parserelativeurl.parseRelativeUrl)(cleanedAs).pathname); + const isShadowedByAppRoute = (0, _dynamicfilterpattern.hasDynamicFilterCandidate)(pathname, concretePathname, (candidate)=>!!this._bfl_d?.contains(candidate)); + if (isShadowedByAppRoute) { + handleHardNavigation({ + url: as, + router: this + }); + return new Promise(()=>{}); + } + } + if (!(0, _islocalurl.isLocalURL)(as)) { + if (process.env.NODE_ENV !== 'production') { + throw new Error(`Invalid href: "${url}" and as: "${as}", received relative href and external as` + `\nSee more info: https://nextjs.org/docs/messages/invalid-relative-url-external-as`); + } + handleHardNavigation({ + url: as, + router: this + }); + return false; + } + resolvedAs = (0, _removelocale.removeLocale)((0, _removebasepath.removeBasePath)(resolvedAs), nextState.locale); + route = (0, _removetrailingslash.removeTrailingSlash)(pathname); + // A config rewrite can resolve `href` to another pages route after the + // marker guard above ran. That route can hold a marker from an earlier + // prefetch, so check it again before `getRouteInfo()` reads the cache. + if (this.components[route]?.__appRouter) { + handleHardNavigation({ + url: as, + router: this + }); + return new Promise(()=>{}); + } + let routeMatch = false; + if ((0, _isdynamic.isDynamicRoute)(route)) { + const parsedAs = (0, _parserelativeurl.parseRelativeUrl)(resolvedAs); + const asPathname = parsedAs.pathname; + const routeRegex = (0, _routeregex.getRouteRegex)(route); + routeMatch = (0, _routematcher.getRouteMatcher)(routeRegex)(asPathname); + const shouldInterpolate = route === asPathname; + const interpolatedAs = shouldInterpolate ? (0, _interpolateas.interpolateAs)(route, asPathname, query) : {}; + if (!routeMatch || shouldInterpolate && !interpolatedAs.result) { + const missingParams = Object.keys(routeRegex.groups).filter((param)=>!query[param] && !routeRegex.groups[param].optional); + if (missingParams.length > 0 && !isMiddlewareMatch) { + if (process.env.NODE_ENV !== 'production') { + console.warn(`${shouldInterpolate ? `Interpolating href` : `Mismatching \`as\` and \`href\``} failed to manually provide ` + `the params: ${missingParams.join(', ')} in the \`href\`'s \`query\``); + } + throw new Error((shouldInterpolate ? `The provided \`href\` (${url}) value is missing query values (${missingParams.join(', ')}) to be interpolated properly. ` : `The provided \`as\` value (${asPathname}) is incompatible with the \`href\` value (${route}). `) + `Read more: https://nextjs.org/docs/messages/${shouldInterpolate ? 'href-interpolation-failed' : 'incompatible-href-as'}`); + } + } else if (shouldInterpolate) { + as = (0, _formaturl.formatWithValidation)(Object.assign({}, parsedAs, { + pathname: interpolatedAs.result, + query: (0, _omit.omit)(query, interpolatedAs.params) + })); + } else { + // Merge params into `query`, overwriting any specified in search + Object.assign(query, routeMatch); + } + } + if (!isQueryUpdating) { + Router.events.emit('routeChangeStart', as, routeProps); + } + const isErrorRoute = this.pathname === '/404' || this.pathname === '/_error'; + try { + let routeInfo = await this.getRouteInfo({ + route, + pathname, + query, + as, + resolvedAs, + routeProps, + locale: nextState.locale, + isPreview: nextState.isPreview, + hasMiddleware: isMiddlewareMatch, + unstable_skipClientCache: options.unstable_skipClientCache, + isQueryUpdating: isQueryUpdating && !this.isFallback, + isMiddlewareRewrite + }); + if (!isQueryUpdating && !options.shallow) { + await this._bfl(as, 'resolvedAs' in routeInfo ? routeInfo.resolvedAs : undefined, nextState.locale); + } + if ('route' in routeInfo && isMiddlewareMatch) { + pathname = routeInfo.route || route; + route = pathname; + if (!routeProps.shallow) { + query = Object.assign({}, routeInfo.query || {}, query); + } + const cleanedParsedPathname = (0, _hasbasepath.hasBasePath)(parsed.pathname) ? (0, _removebasepath.removeBasePath)(parsed.pathname) : parsed.pathname; + if (routeMatch && pathname !== cleanedParsedPathname) { + Object.keys(routeMatch).forEach((key)=>{ + if (routeMatch && query[key] === routeMatch[key]) { + delete query[key]; + } + }); + } + if ((0, _isdynamic.isDynamicRoute)(pathname)) { + const prefixedAs = !routeProps.shallow && routeInfo.resolvedAs ? routeInfo.resolvedAs : (0, _addbasepath.addBasePath)((0, _addlocale.addLocale)(new URL(as, location.href).pathname, nextState.locale), true); + let rewriteAs = prefixedAs; + if ((0, _hasbasepath.hasBasePath)(rewriteAs)) { + rewriteAs = (0, _removebasepath.removeBasePath)(rewriteAs); + } + if (process.env.__NEXT_I18N_SUPPORT) { + const localeResult = (0, _normalizelocalepath.normalizeLocalePath)(rewriteAs, this.locales); + nextState.locale = localeResult.detectedLocale || nextState.locale; + rewriteAs = localeResult.pathname; + } + const routeRegex = (0, _routeregex.getRouteRegex)(pathname); + const curRouteMatch = (0, _routematcher.getRouteMatcher)(routeRegex)(new URL(rewriteAs, location.href).pathname); + if (curRouteMatch) { + Object.assign(query, curRouteMatch); + } + } + } + // If the routeInfo brings a redirect we simply apply it. + if ('type' in routeInfo) { + if (routeInfo.type === 'redirect-internal') { + return this.change(method, routeInfo.newUrl, routeInfo.newAs, options); + } else { + handleHardNavigation({ + url: routeInfo.destination, + router: this + }); + return new Promise(()=>{}); + } + } + const component = routeInfo.Component; + if (component && component.unstable_scriptLoader) { + const scripts = [].concat(component.unstable_scriptLoader()); + scripts.forEach((script)=>{ + (0, _script.handleClientScriptLoad)(script.props); + }); + } + // handle redirect on client-transition + if ((routeInfo.__N_SSG || routeInfo.__N_SSP) && routeInfo.props) { + if (routeInfo.props.pageProps && routeInfo.props.pageProps.__N_REDIRECT) { + // Use the destination from redirect without adding locale + options.locale = false; + const destination = routeInfo.props.pageProps.__N_REDIRECT; + // check if destination is internal (resolves to a page) and attempt + // client-navigation if it is falling back to hard navigation if + // it's not + if (destination.startsWith('/') && routeInfo.props.pageProps.__N_REDIRECT_BASE_PATH !== false) { + const parsedHref = (0, _parserelativeurl.parseRelativeUrl)(destination); + parsedHref.pathname = resolveDynamicRoute(parsedHref.pathname, pages); + const { url: newUrl, as: newAs } = prepareUrlAs(this, destination, destination); + return this.change(method, newUrl, newAs, options); + } + handleHardNavigation({ + url: destination, + router: this + }); + return new Promise(()=>{}); + } + nextState.isPreview = !!routeInfo.props.__N_PREVIEW; + // handle SSG data 404 + if (routeInfo.props.notFound === SSG_DATA_NOT_FOUND) { + let notFoundRoute; + try { + await this.fetchComponent('/404'); + notFoundRoute = '/404'; + } catch (_) { + notFoundRoute = '/_error'; + } + routeInfo = await this.getRouteInfo({ + route: notFoundRoute, + pathname: notFoundRoute, + query, + as, + resolvedAs, + routeProps: { + shallow: false + }, + locale: nextState.locale, + isPreview: nextState.isPreview, + isNotFound: true + }); + if ('type' in routeInfo) { + throw new Error(`Unexpected middleware effect on /404`); + } + } + } + if (isQueryUpdating && this.pathname === '/_error' && self.__NEXT_DATA__.props?.pageProps?.statusCode === 500 && routeInfo.props?.pageProps) { + // ensure statusCode is still correct for static 500 page + // when updating query information + routeInfo.props.pageProps.statusCode = 500; + } + // shallow routing is only allowed for same page URL changes. + const isValidShallowRoute = options.shallow && nextState.route === (routeInfo.route ?? route); + const shouldScroll = options.scroll ?? (!isQueryUpdating && !isValidShallowRoute); + const resetScroll = shouldScroll ? { + x: 0, + y: 0 + } : null; + const upcomingScrollState = forcedScroll ?? resetScroll; + // the new state that the router gonna set + const upcomingRouterState = { + ...nextState, + route, + pathname, + query, + asPath: cleanedAs, + isFallback: false + }; + // When the page being rendered is the 404 page, we should only update the + // query parameters. Route changes here might add the basePath when it + // wasn't originally present. This is also why this block is before the + // below `changeState` call which updates the browser's history (changing + // the URL). + if (isQueryUpdating && isErrorRoute) { + routeInfo = await this.getRouteInfo({ + route: this.pathname, + pathname: this.pathname, + query, + as, + resolvedAs, + routeProps: { + shallow: false + }, + locale: nextState.locale, + isPreview: nextState.isPreview, + isQueryUpdating: isQueryUpdating && !this.isFallback + }); + if ('type' in routeInfo) { + throw new Error(`Unexpected middleware effect on ${this.pathname}`); + } + if (this.pathname === '/_error' && self.__NEXT_DATA__.props?.pageProps?.statusCode === 500 && routeInfo.props?.pageProps) { + // ensure statusCode is still correct for static 500 page + // when updating query information + routeInfo.props.pageProps.statusCode = 500; + } + try { + await this.set(upcomingRouterState, routeInfo, upcomingScrollState); + } catch (err) { + if ((0, _iserror.default)(err) && err.cancelled) { + Router.events.emit('routeChangeError', err, cleanedAs, routeProps); + } + throw err; + } + return true; + } + Router.events.emit('beforeHistoryChange', as, routeProps); + this.changeState(method, url, as, options); + // for query updates we can skip it if the state is unchanged and we don't + // need to scroll + // https://github.com/vercel/next.js/issues/37139 + const canSkipUpdating = isQueryUpdating && !upcomingScrollState && !readyStateChange && !localeChange && (0, _comparestates.compareRouterStates)(upcomingRouterState, this.state); + if (!canSkipUpdating) { + try { + await this.set(upcomingRouterState, routeInfo, upcomingScrollState); + } catch (e) { + if (e.cancelled) routeInfo.error = routeInfo.error || e; + else throw e; + } + if (routeInfo.error) { + if (!isQueryUpdating) { + Router.events.emit('routeChangeError', routeInfo.error, cleanedAs, routeProps); + } + throw routeInfo.error; + } + if (process.env.__NEXT_I18N_SUPPORT) { + if (nextState.locale) { + document.documentElement.lang = nextState.locale; + } + } + if (!isQueryUpdating) { + Router.events.emit('routeChangeComplete', as, routeProps); + } + // A hash mark # is the optional last part of a URL + const hashRegex = /#.+$/; + if (shouldScroll && hashRegex.test(as)) { + this.scrollToHash(as); + } + } + return true; + } catch (err) { + if ((0, _iserror.default)(err) && err.cancelled) { + return false; + } + throw err; + } + } + changeState(method, url, as, options = {}) { + if (process.env.NODE_ENV !== 'production') { + if (typeof window.history === 'undefined') { + console.error(`Warning: window.history is not available.`); + return; + } + if (typeof window.history[method] === 'undefined') { + console.error(`Warning: window.history.${method} is not available`); + return; + } + } + if (method !== 'pushState' || (0, _utils.getURL)() !== as) { + this._shallow = options.shallow; + window.history[method]({ + url, + as, + options, + __N: true, + key: this._key = method !== 'pushState' ? this._key : createKey() + }, // Most browsers currently ignores this parameter, although they may use it in the future. + // Passing the empty string here should be safe against future changes to the method. + // https://developer.mozilla.org/docs/Web/API/History/replaceState + '', as); + } + } + async handleRouteInfoError(err, pathname, query, as, routeProps, loadErrorFail) { + if (err.cancelled) { + // bubble up cancellation errors + throw err; + } + if ((0, _routeloader.isAssetError)(err) || loadErrorFail) { + Router.events.emit('routeChangeError', err, as, routeProps); + // If we can't load the page it could be one of following reasons + // 1. Page doesn't exists + // 2. Page does exist in a different zone + // 3. Internal error while loading the page + // So, doing a hard reload is the proper way to deal with this. + handleHardNavigation({ + url: as, + router: this + }); + // Changing the URL doesn't block executing the current code path. + // So let's throw a cancellation error stop the routing logic. + throw buildCancellationError(); + } + console.error(err); + try { + let props; + const { page: Component, styleSheets } = await this.fetchComponent('/_error'); + const routeInfo = { + props, + Component, + styleSheets, + err, + error: err + }; + if (!routeInfo.props) { + try { + routeInfo.props = await this.getInitialProps(Component, { + err, + pathname, + query + }); + } catch (gipErr) { + console.error('Error in error page `getInitialProps`: ', gipErr); + routeInfo.props = {}; + } + } + return routeInfo; + } catch (routeInfoErr) { + return this.handleRouteInfoError((0, _iserror.default)(routeInfoErr) ? routeInfoErr : new Error(routeInfoErr + ''), pathname, query, as, routeProps, true); + } + } + async getRouteInfo({ route: requestedRoute, pathname, query, as, resolvedAs, routeProps, locale, hasMiddleware, isPreview, unstable_skipClientCache, isQueryUpdating, isMiddlewareRewrite, isNotFound }) { + /** + * This `route` binding can change if there's a rewrite + * so we keep a reference to the original requested route + * so we can store the cache for it and avoid re-requesting every time + * for shallow routing purposes. + */ let route = requestedRoute; + try { + let existingInfo = this.components[route]; + // `prefetch()` stores a `{ __appRouter: true }` marker in + // `this.components` when the client router filter matches a path. That + // marker is not route info: it has no `Component` and no `props`, so + // rendering it crashes `_app`. Treat it as a cache miss and fetch the + // route info again; `change()` is responsible for the hard navigation. + if (existingInfo && existingInfo.__appRouter) { + existingInfo = undefined; + } + if (routeProps.shallow && existingInfo && this.route === route) { + return existingInfo; + } + const handleCancelled = getCancelledHandler({ + route, + router: this + }); + if (hasMiddleware) { + existingInfo = undefined; + } + let cachedRouteInfo = existingInfo && !('initial' in existingInfo) && process.env.NODE_ENV !== 'development' ? existingInfo : undefined; + const isBackground = isQueryUpdating; + const fetchNextDataParams = { + dataHref: this.pageLoader.getDataHref({ + href: (0, _formaturl.formatWithValidation)({ + pathname, + query + }), + skipInterpolation: true, + asPath: isNotFound ? '/404' : resolvedAs, + locale + }), + hasMiddleware: true, + isServerRender: this.isSsr, + parseJSON: true, + inflightCache: isBackground ? this.sbc : this.sdc, + persistCache: !isPreview, + isPrefetch: false, + unstable_skipClientCache, + isBackground + }; + let data = isQueryUpdating && !isMiddlewareRewrite ? null : await withMiddlewareEffects({ + fetchData: ()=>fetchNextData(fetchNextDataParams), + asPath: isNotFound ? '/404' : resolvedAs, + locale: locale, + router: this + }).catch((err)=>{ + // we don't hard error during query updating + // as it's un-necessary and doesn't need to be fatal + // unless it is a fallback route and the props can't + // be loaded + if (isQueryUpdating) { + return null; + } + throw err; + }); + // when rendering error routes we don't apply middleware + // effects + if (data && (pathname === '/_error' || pathname === '/404')) { + data.effect = undefined; + } + if (isQueryUpdating) { + if (!data) { + data = { + json: self.__NEXT_DATA__.props + }; + } else { + data.json = self.__NEXT_DATA__.props; + } + } + handleCancelled(); + if (data?.effect?.type === 'redirect-internal' || data?.effect?.type === 'redirect-external') { + return data.effect; + } + if (data?.effect?.type === 'rewrite') { + const resolvedRoute = (0, _removetrailingslash.removeTrailingSlash)(data.effect.resolvedHref); + const pages = await this.pageLoader.getPageList(); + // during query updating the page must match although during + // client-transition a redirect that doesn't match a page + // can be returned and this should trigger a hard navigation + // which is valid for incremental migration + if (!isQueryUpdating || pages.includes(resolvedRoute)) { + route = resolvedRoute; + pathname = data.effect.resolvedHref; + query = { + ...query, + ...data.effect.parsedAs.query + }; + resolvedAs = (0, _removebasepath.removeBasePath)((0, _normalizelocalepath.normalizeLocalePath)(data.effect.parsedAs.pathname, this.locales).pathname); + // Check again the cache with the new destination. + existingInfo = this.components[route]; + if (existingInfo && existingInfo.__appRouter) { + existingInfo = undefined; + } + if (routeProps.shallow && existingInfo && this.route === route && !hasMiddleware) { + // If we have a match with the current route due to rewrite, + // we can copy the existing information to the rewritten one. + // Then, we return the information along with the matched route. + return { + ...existingInfo, + route + }; + } + } + } + if ((0, _isapiroute.isAPIRoute)(route)) { + handleHardNavigation({ + url: as, + router: this + }); + return new Promise(()=>{}); + } + const routeInfo = cachedRouteInfo || await this.fetchComponent(route).then((res)=>({ + Component: res.page, + styleSheets: res.styleSheets, + __N_SSG: res.mod.__N_SSG, + __N_SSP: res.mod.__N_SSP + })); + if (process.env.NODE_ENV !== 'production') { + const { isValidElementType } = require('next/dist/compiled/react-is'); + if (!isValidElementType(routeInfo.Component)) { + throw new Error(`The default export is not a React Component in page: "${pathname}"`); + } + } + const wasBailedPrefetch = data?.response?.headers.get('x-middleware-skip'); + const shouldFetchData = routeInfo.__N_SSG || routeInfo.__N_SSP; + // For non-SSG prefetches that bailed before sending data + // we clear the cache to fetch full response + if (wasBailedPrefetch && data?.dataHref) { + delete this.sdc[data.dataHref]; + } + const { props, cacheKey } = await this._getData(async ()=>{ + if (shouldFetchData) { + if (data?.json && !wasBailedPrefetch) { + return { + cacheKey: data.cacheKey, + props: data.json + }; + } + const dataHref = data?.dataHref ? data.dataHref : this.pageLoader.getDataHref({ + href: (0, _formaturl.formatWithValidation)({ + pathname, + query + }), + asPath: resolvedAs, + locale + }); + const fetched = await fetchNextData({ + dataHref, + isServerRender: this.isSsr, + parseJSON: true, + inflightCache: wasBailedPrefetch ? {} : this.sdc, + persistCache: !isPreview, + isPrefetch: false, + unstable_skipClientCache + }); + return { + cacheKey: fetched.cacheKey, + props: fetched.json || {} + }; + } + return { + headers: {}, + props: await this.getInitialProps(routeInfo.Component, // we provide AppTree later so this needs to be `any` + { + pathname, + query, + asPath: as, + locale, + locales: this.locales, + defaultLocale: this.defaultLocale + }) + }; + }); + // Only bust the data cache for SSP routes although + // middleware can skip cache per request with + // x-middleware-cache: no-cache as well + if (routeInfo.__N_SSP && fetchNextDataParams.dataHref && cacheKey) { + delete this.sdc[cacheKey]; + } + // we kick off a HEAD request in the background + // when a non-prefetch request is made to signal revalidation + if (!this.isPreview && routeInfo.__N_SSG && process.env.NODE_ENV !== 'development' && !isQueryUpdating) { + fetchNextData(Object.assign({}, fetchNextDataParams, { + isBackground: true, + persistCache: false, + inflightCache: this.sbc + })).catch(()=>{}); + } + props.pageProps = Object.assign({}, props.pageProps); + routeInfo.props = props; + routeInfo.route = route; + routeInfo.query = query; + routeInfo.resolvedAs = resolvedAs; + this.components[route] = routeInfo; + return routeInfo; + } catch (err) { + return this.handleRouteInfoError((0, _iserror.getProperError)(err), pathname, query, as, routeProps); + } + } + set(state, data, resetScroll) { + this.state = state; + return this.sub(data, this.components['/_app'].Component, resetScroll); + } + /** + * Callback to execute before replacing router state + * @param cb callback to be executed + */ beforePopState(cb) { + this._bps = cb; + } + onlyAHashChange(as) { + if (!this.asPath) return false; + const [oldUrlNoHash, oldHash] = this.asPath.split('#', 2); + const [newUrlNoHash, newHash] = as.split('#', 2); + // Makes sure we scroll to the provided hash if the url/hash are the same + if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) { + return true; + } + // If the urls are change, there's more than a hash change + if (oldUrlNoHash !== newUrlNoHash) { + return false; + } + // If the hash has changed, then it's a hash only change. + // This check is necessary to handle both the enter and + // leave hash === '' cases. The identity case falls through + // and is treated as a next reload. + return oldHash !== newHash; + } + scrollToHash(as) { + const [, hash = ''] = as.split('#', 2); + (0, _disablesmoothscroll.disableSmoothScrollDuringRouteTransition)(()=>{ + // Scroll to top if the hash is just `#` with no value or `#top` + // To mirror browsers + if (hash === '' || hash === 'top') { + window.scrollTo(0, 0); + return; + } + // Decode hash to make non-latin anchor works. + const rawHash = decodeURIComponent(hash); + // First we check if the element by id is found + const idEl = document.getElementById(rawHash); + if (idEl) { + idEl.scrollIntoView(); + return; + } + // If there's no element with the id, we check the `name` property + // To mirror browsers + const nameEl = document.getElementsByName(rawHash)[0]; + if (nameEl) { + nameEl.scrollIntoView(); + } + }, { + onlyHashChange: this.onlyAHashChange(as) + }); + } + urlIsNew(asPath) { + return this.asPath !== asPath; + } + /** + * Prefetch page code, you may wait for the data during page rendering. + * This feature only works in production! + * @param url the href of prefetched page + * @param asPath the as path of the prefetched page + */ async prefetch(url, asPath = url, options = {}) { + // Prefetch is not supported in development mode because it would trigger on-demand-entries + if (process.env.NODE_ENV !== 'production') { + return; + } + if (typeof window !== 'undefined' && (0, _isbot.isBot)(window.navigator.userAgent)) { + // No prefetches for bots that render the link since they are typically navigating + // links via the equivalent of a hard navigation and hence never utilize these + // prefetches. + return; + } + let parsed = (0, _parserelativeurl.parseRelativeUrl)(url); + let { pathname, query } = parsed; + const originalPathname = pathname; + if (process.env.__NEXT_I18N_SUPPORT) { + if (options.locale === false) { + pathname = (0, _normalizelocalepath.normalizeLocalePath)(pathname, this.locales).pathname; + parsed.pathname = pathname; + url = (0, _formaturl.formatWithValidation)(parsed); + let parsedAs = (0, _parserelativeurl.parseRelativeUrl)(asPath); + const localePathResult = (0, _normalizelocalepath.normalizeLocalePath)(parsedAs.pathname, this.locales); + parsedAs.pathname = localePathResult.pathname; + options.locale = localePathResult.detectedLocale || this.defaultLocale; + asPath = (0, _formaturl.formatWithValidation)(parsedAs); + } + } + const pages = await this.pageLoader.getPageList(); + let resolvedAs = asPath; + const locale = typeof options.locale !== 'undefined' ? options.locale || undefined : this.locale; + const isMiddlewareMatch = await matchesMiddleware({ + asPath: asPath, + locale: locale, + router: this + }); + if (process.env.__NEXT_HAS_REWRITES && asPath.startsWith('/')) { + let rewrites; + ({ __rewrites: rewrites } = await (0, _routeloader.getClientBuildManifest)()); + const rewritesResult = resolveRewrites((0, _addbasepath.addBasePath)((0, _addlocale.addLocale)(asPath, this.locale), true), pages, rewrites, parsed.query, (p)=>resolveDynamicRoute(p, pages), this.locales); + if (rewritesResult.externalDest) { + return; + } + if (!isMiddlewareMatch) { + resolvedAs = (0, _removelocale.removeLocale)((0, _removebasepath.removeBasePath)(rewritesResult.asPath), this.locale); + } + if (rewritesResult.matchedPage && rewritesResult.resolvedHref) { + // if this directly matches a page we need to update the href to + // allow the correct page chunk to be loaded + pathname = rewritesResult.resolvedHref; + parsed.pathname = pathname; + if (!isMiddlewareMatch) { + url = (0, _formaturl.formatWithValidation)(parsed); + } + } + } + parsed.pathname = resolveDynamicRoute(parsed.pathname, pages); + if ((0, _isdynamic.isDynamicRoute)(parsed.pathname)) { + pathname = parsed.pathname; + parsed.pathname = pathname; + Object.assign(query, (0, _routematcher.getRouteMatcher)((0, _routeregex.getRouteRegex)(parsed.pathname))((0, _parsepath.parsePath)(asPath).pathname) || {}); + if (!isMiddlewareMatch) { + url = (0, _formaturl.formatWithValidation)(parsed); + } + } + const data = process.env.__NEXT_MIDDLEWARE_PREFETCH === 'strict' ? null : await withMiddlewareEffects({ + fetchData: ()=>fetchNextData({ + dataHref: this.pageLoader.getDataHref({ + href: (0, _formaturl.formatWithValidation)({ + pathname: originalPathname, + query + }), + skipInterpolation: true, + asPath: resolvedAs, + locale + }), + hasMiddleware: true, + isServerRender: false, + parseJSON: true, + inflightCache: this.sdc, + persistCache: !this.isPreview, + isPrefetch: true + }), + asPath: asPath, + locale: locale, + router: this + }); + /** + * If there was a rewrite we apply the effects of the rewrite on the + * current parameters for the prefetch. + */ if (data?.effect.type === 'rewrite') { + parsed.pathname = data.effect.resolvedHref; + pathname = data.effect.resolvedHref; + query = { + ...query, + ...data.effect.parsedAs.query + }; + resolvedAs = data.effect.parsedAs.pathname; + url = (0, _formaturl.formatWithValidation)(parsed); + } + /** + * If there is a redirect to an external destination then we don't have + * to prefetch content as it will be unused. + */ if (data?.effect.type === 'redirect-external') { + return; + } + const route = (0, _removetrailingslash.removeTrailingSlash)(pathname); + if (await this._bfl(asPath, resolvedAs, options.locale, true)) { + const appRouterMarkerKey = getAppRouterMarkerKey(this, asPath, options.locale); + // A loaded pages route in the cache is ground truth: the page behind + // this key exists and was rendered. This is the case when the current + // page was reached through a rewrite and the canonical URL is + // prefetched, or when a prefetch is still in flight while a navigation + // stores the same route. Replacing that entry with the marker would + // break hash-only changes and shallow navigations, which render the + // cached entry of the current route directly. Non-shallow navigations + // consult the client router filter themselves, so they do not depend + // on the marker to hard navigate. + if (appRouterMarkerKey !== null && this.components[appRouterMarkerKey] === undefined) { + this.components[appRouterMarkerKey] = { + __appRouter: true + }; + } + } + await Promise.all([ + this.pageLoader._isSsg(route).then((isSsg)=>{ + return isSsg ? fetchNextData({ + dataHref: data?.json ? data?.dataHref : this.pageLoader.getDataHref({ + href: url, + asPath: resolvedAs, + locale: locale + }), + isServerRender: false, + parseJSON: true, + inflightCache: this.sdc, + persistCache: !this.isPreview, + isPrefetch: true, + unstable_skipClientCache: options.unstable_skipClientCache || options.priority && !!process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE + }).then(()=>false).catch(()=>false) : false; + }), + this.pageLoader[options.priority ? 'loadPage' : 'prefetch'](route) + ]); + } + async fetchComponent(route) { + const handleCancelled = getCancelledHandler({ + route, + router: this + }); + try { + const componentResult = await this.pageLoader.loadPage(route); + handleCancelled(); + return componentResult; + } catch (err) { + handleCancelled(); + throw err; + } + } + _getData(fn) { + let cancelled = false; + const cancel = ()=>{ + cancelled = true; + }; + this.clc = cancel; + return fn().then((data)=>{ + if (cancel === this.clc) { + this.clc = null; + } + if (cancelled) { + const err = new Error('Loading initial props cancelled'); + err.cancelled = true; + throw err; + } + return data; + }); + } + getInitialProps(Component, ctx) { + const { Component: App } = this.components['/_app']; + const AppTree = this._wrapApp(App); + ctx.AppTree = AppTree; + return (0, _utils.loadGetInitialProps)(App, { + AppTree, + Component, + router: this, + ctx + }); + } + get route() { + return this.state.route; + } + get pathname() { + return this.state.pathname; + } + get query() { + return this.state.query; + } + get asPath() { + return this.state.asPath; + } + get locale() { + return this.state.locale; + } + get isFallback() { + return this.state.isFallback; + } + get isPreview() { + return this.state.isPreview; + } +} + +//# sourceMappingURL=router.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/router.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/router.js.map new file mode 100644 index 0000000000000000000000000000000000000000..fabbcf8fb4c6458d89eb38ddeb168970e11be93b --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/router.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../src/shared/lib/router/router.ts"],"sourcesContent":["import type { ComponentType } from 'react'\nimport type { DomainLocale } from '../../../server/config'\nimport type { MittEmitter } from '../mitt'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { RouterEvent } from '../../../client/router'\nimport type { StyleSheetTuple } from '../../../client/page-loader'\nimport type { UrlObject } from 'url'\nimport type PageLoader from '../../../client/page-loader'\nimport type { AppContextType, NextPageContext, NEXT_DATA } from '../utils'\nimport { removeTrailingSlash } from './utils/remove-trailing-slash'\nimport {\n getClientBuildManifest,\n isAssetError,\n markAssetError,\n} from '../../../client/route-loader'\nimport { handleClientScriptLoad } from '../../../client/script'\nimport isError, { getProperError } from '../../../lib/is-error'\nimport { denormalizePagePath } from '../page-path/denormalize-page-path'\nimport { normalizeLocalePath } from '../i18n/normalize-locale-path'\nimport mitt from '../mitt'\nimport { getLocationOrigin, getURL, loadGetInitialProps, ST } from '../utils'\nimport { isDynamicRoute } from './utils/is-dynamic'\nimport { parseRelativeUrl } from './utils/parse-relative-url'\nimport { getRouteMatcher } from './utils/route-matcher'\nimport { getRouteRegex } from './utils/route-regex'\nimport { hasDynamicFilterCandidate } from './utils/dynamic-filter-pattern'\nimport { formatWithValidation } from './utils/format-url'\nimport { detectDomainLocale } from '../../../client/detect-domain-locale'\nimport { parsePath } from './utils/parse-path'\nimport { addLocale } from '../../../client/add-locale'\nimport { removeLocale } from '../../../client/remove-locale'\nimport { removeBasePath } from '../../../client/remove-base-path'\nimport { addBasePath } from '../../../client/add-base-path'\nimport { hasBasePath } from '../../../client/has-base-path'\nimport { resolveHref } from '../../../client/resolve-href'\nimport { isAPIRoute } from '../../../lib/is-api-route'\nimport { getNextPathnameInfo } from './utils/get-next-pathname-info'\nimport { formatNextPathnameInfo } from './utils/format-next-pathname-info'\nimport { compareRouterStates } from './utils/compare-states'\nimport { isLocalURL } from './utils/is-local-url'\nimport { isBot } from './utils/is-bot'\nimport { omit } from './utils/omit'\nimport { interpolateAs } from './utils/interpolate-as'\nimport { disableSmoothScrollDuringRouteTransition } from './utils/disable-smooth-scroll'\nimport type { Params } from '../../../server/request/params'\nimport {\n MATCHED_PATH_HEADER,\n NEXT_NAV_DEPLOYMENT_ID_HEADER,\n} from '../../../lib/constants'\nimport { getDeploymentId } from '../deployment-id'\nimport { isJavaScriptURLString } from '../../../client/lib/javascript-url'\n\nlet resolveRewrites: typeof import('./utils/resolve-rewrites').default\nif (process.env.__NEXT_HAS_REWRITES) {\n resolveRewrites = (\n require('./utils/resolve-rewrites') as typeof import('./utils/resolve-rewrites')\n ).default\n}\n\ndeclare global {\n interface Window {\n /* prod */\n __NEXT_DATA__: NEXT_DATA\n }\n}\n\ninterface RouteProperties {\n shallow: boolean\n}\n\ninterface TransitionOptions {\n shallow?: boolean\n locale?: string | false\n scroll?: boolean\n unstable_skipClientCache?: boolean\n}\n\ninterface NextHistoryState {\n url: string\n as: string\n options: TransitionOptions\n}\n\nexport type HistoryState =\n | null\n | { __NA: true; __N?: false }\n | { __N: false; __NA?: false }\n | ({ __NA?: false; __N: true; key: string } & NextHistoryState)\n\nfunction buildCancellationError() {\n return Object.assign(new Error('Route Cancelled'), {\n cancelled: true,\n })\n}\n\ninterface MiddlewareEffectParams<T extends FetchDataOutput> {\n fetchData?: () => Promise<T>\n locale?: string\n asPath: string\n router: Router\n}\n\nexport async function matchesMiddleware<T extends FetchDataOutput>(\n options: MiddlewareEffectParams<T>\n): Promise<boolean> {\n const matchers = await Promise.resolve(\n options.router.pageLoader.getMiddleware()\n )\n if (!matchers) return false\n\n const { pathname: asPathname } = parsePath(options.asPath)\n // remove basePath first since path prefix has to be in the order of `/${basePath}/${locale}`\n const cleanedAs = hasBasePath(asPathname)\n ? removeBasePath(asPathname)\n : asPathname\n const asWithBasePathAndLocale = addBasePath(\n addLocale(cleanedAs, options.locale)\n )\n\n // Check only path match on client. Matching \"has\" should be done on server\n // where we can access more info such as headers, HttpOnly cookie, etc.\n return matchers.some((m) =>\n new RegExp(m.regexp).test(asWithBasePathAndLocale)\n )\n}\n\nfunction stripOrigin(url: string) {\n const origin = getLocationOrigin()\n\n return url.startsWith(origin) ? url.substring(origin.length) : url\n}\n\nfunction prepareUrlAs(router: NextRouter, url: Url, as?: Url) {\n // If url and as provided as an object representation,\n // we'll format them into the string version here.\n let [resolvedHref, resolvedAs] = resolveHref(router, url, true)\n const origin = getLocationOrigin()\n const hrefWasAbsolute = resolvedHref.startsWith(origin)\n const asWasAbsolute = resolvedAs && resolvedAs.startsWith(origin)\n\n resolvedHref = stripOrigin(resolvedHref)\n resolvedAs = resolvedAs ? stripOrigin(resolvedAs) : resolvedAs\n\n const preparedUrl = hrefWasAbsolute ? resolvedHref : addBasePath(resolvedHref)\n const preparedAs = as\n ? stripOrigin(resolveHref(router, as))\n : resolvedAs || resolvedHref\n\n return {\n url: preparedUrl,\n as: asWasAbsolute ? preparedAs : addBasePath(preparedAs),\n }\n}\n\n/**\n * Key under which `prefetch()` stores the `{ __appRouter: true }` marker in\n * `router.components` and under which `change()` looks it up again.\n *\n * The client router filter (`_bfl`) is evaluated against the `as` path, so the\n * marker has to be keyed by the `as` path as well. Keying it by the `href`\n * pathname is only equivalent while `href` and `as` are the same URL. When\n * they differ (for example the \"route as modal\" pattern where `href` stays on\n * the current page and `as` shows a pretty URL) a filter match on `as` would\n * otherwise mark the pages route behind `href` as an App Router path and\n * break every later navigation to that route.\n *\n * `as` is expected without the `basePath`, which is what both call sites\n * hold: `prefetch()` receives it that way from `next/link` and `change()`\n * strips it before computing `cleanedAs`. Stripping it again here would turn\n * a route that merely starts with the `basePath` (for example the app route\n * `/docs` with `basePath: '/docs'`) into `/` and poison the index page.\n *\n * The key also carries the effective locale, mirroring how `_bfl` evaluates\n * `addLocale(as, locale)` against the filter. A match for a French-only\n * redirect at `/fr/legacy` must not mark the English `/legacy` page.\n *\n * Returns `null` when `as` is not a local URL (for example `mailto:` or a\n * different origin). Such an `as` can never be an App Router path, and\n * `change()` reports it as an invalid `href`/`as` pair further down.\n */\nfunction getAppRouterMarkerKey(\n router: Router,\n as: string,\n locale: string | false | undefined\n): string | null {\n if (!isLocalURL(as)) {\n return null\n }\n\n let { pathname } = parseRelativeUrl(as)\n let effectiveLocale = locale || router.locale\n\n if (process.env.__NEXT_I18N_SUPPORT) {\n const localePathResult = normalizeLocalePath(pathname, router.locales)\n pathname = localePathResult.pathname\n effectiveLocale = localePathResult.detectedLocale || effectiveLocale\n }\n\n return removeTrailingSlash(\n addLocale(removeTrailingSlash(pathname), effectiveLocale)\n )\n}\n\nfunction resolveDynamicRoute(pathname: string, pages: string[]) {\n const cleanPathname = removeTrailingSlash(denormalizePagePath(pathname))\n if (cleanPathname === '/404' || cleanPathname === '/_error') {\n return pathname\n }\n\n // handle resolving href for dynamic routes\n if (!pages.includes(cleanPathname)) {\n // eslint-disable-next-line array-callback-return\n pages.some((page) => {\n if (isDynamicRoute(page) && getRouteRegex(page).re.test(cleanPathname)) {\n pathname = page\n return true\n }\n })\n }\n return removeTrailingSlash(pathname)\n}\n\nfunction getMiddlewareData<T extends FetchDataOutput>(\n source: string,\n response: Response,\n options: MiddlewareEffectParams<T>\n) {\n const nextConfig = {\n basePath: options.router.basePath,\n i18n: { locales: options.router.locales },\n trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),\n }\n const rewriteHeader = response.headers.get('x-nextjs-rewrite')\n\n let rewriteTarget =\n rewriteHeader || response.headers.get('x-nextjs-matched-path')\n\n const matchedPath = response.headers.get(MATCHED_PATH_HEADER)\n\n if (\n matchedPath &&\n !rewriteTarget &&\n !matchedPath.includes('__next_data_catchall') &&\n !matchedPath.includes('/_error') &&\n !matchedPath.includes('/404')\n ) {\n // leverage x-matched-path to detect next.config.js rewrites\n rewriteTarget = matchedPath\n }\n\n if (rewriteTarget) {\n if (\n rewriteTarget.startsWith('/') ||\n process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE\n ) {\n const parsedRewriteTarget = parseRelativeUrl(rewriteTarget)\n const pathnameInfo = getNextPathnameInfo(parsedRewriteTarget.pathname, {\n nextConfig,\n parseData: true,\n })\n\n let fsPathname = removeTrailingSlash(pathnameInfo.pathname)\n return Promise.all([\n options.router.pageLoader.getPageList(),\n getClientBuildManifest(),\n ]).then(([pages, { __rewrites: rewrites }]: any) => {\n let as = addLocale(pathnameInfo.pathname, pathnameInfo.locale)\n\n if (\n isDynamicRoute(as) ||\n (!rewriteHeader &&\n pages.includes(\n normalizeLocalePath(removeBasePath(as), options.router.locales)\n .pathname\n ))\n ) {\n const parsedSource = getNextPathnameInfo(\n parseRelativeUrl(source).pathname,\n {\n // Pass basePath (and trailingSlash) so the basePath prefix is\n // stripped before the `_next/data/` check, but omit `i18n` so the\n // locale prefix is preserved here — the rewrite resolver below\n // handles the locale-prefixed `as`.\n nextConfig: {\n basePath: nextConfig.basePath,\n trailingSlash: nextConfig.trailingSlash,\n },\n parseData: true,\n }\n )\n\n as = addBasePath(parsedSource.pathname)\n parsedRewriteTarget.pathname = as\n }\n\n if (process.env.__NEXT_HAS_REWRITES) {\n const result = resolveRewrites(\n as,\n pages,\n rewrites,\n parsedRewriteTarget.query,\n (path: string) => resolveDynamicRoute(path, pages),\n options.router.locales\n )\n\n if (result.matchedPage) {\n parsedRewriteTarget.pathname = result.parsedAs.pathname\n as = parsedRewriteTarget.pathname\n Object.assign(parsedRewriteTarget.query, result.parsedAs.query)\n }\n } else if (!pages.includes(fsPathname)) {\n const resolvedPathname = resolveDynamicRoute(fsPathname, pages)\n\n if (resolvedPathname !== fsPathname) {\n fsPathname = resolvedPathname\n }\n }\n\n const resolvedHref = !pages.includes(fsPathname)\n ? resolveDynamicRoute(\n normalizeLocalePath(\n removeBasePath(parsedRewriteTarget.pathname),\n options.router.locales\n ).pathname,\n pages\n )\n : fsPathname\n\n if (isDynamicRoute(resolvedHref)) {\n const matches = getRouteMatcher(getRouteRegex(resolvedHref))(as)\n Object.assign(parsedRewriteTarget.query, matches || {})\n }\n\n return {\n type: 'rewrite' as const,\n parsedAs: parsedRewriteTarget,\n resolvedHref,\n }\n })\n }\n const src = parsePath(source)\n const pathname = formatNextPathnameInfo({\n ...getNextPathnameInfo(src.pathname, { nextConfig, parseData: true }),\n defaultLocale: options.router.defaultLocale,\n buildId: '',\n })\n\n return Promise.resolve({\n type: 'redirect-external' as const,\n destination: `${pathname}${src.query}${src.hash}`,\n })\n }\n\n const redirectTarget = response.headers.get('x-nextjs-redirect')\n\n if (redirectTarget) {\n if (redirectTarget.startsWith('/')) {\n const src = parsePath(redirectTarget)\n const pathname = formatNextPathnameInfo({\n ...getNextPathnameInfo(src.pathname, { nextConfig, parseData: true }),\n defaultLocale: options.router.defaultLocale,\n buildId: '',\n })\n\n return Promise.resolve({\n type: 'redirect-internal' as const,\n newAs: `${pathname}${src.query}${src.hash}`,\n newUrl: `${pathname}${src.query}${src.hash}`,\n })\n }\n\n return Promise.resolve({\n type: 'redirect-external' as const,\n destination: redirectTarget,\n })\n }\n\n return Promise.resolve({ type: 'next' as const })\n}\n\ninterface WithMiddlewareEffectsOutput extends FetchDataOutput {\n effect: Awaited<ReturnType<typeof getMiddlewareData>>\n}\n\nasync function withMiddlewareEffects<T extends FetchDataOutput>(\n options: MiddlewareEffectParams<T>\n): Promise<WithMiddlewareEffectsOutput | null> {\n const matches = await matchesMiddleware(options)\n if (!matches || !options.fetchData) {\n return null\n }\n\n const data = await options.fetchData()\n\n const effect = await getMiddlewareData(data.dataHref, data.response, options)\n\n return {\n dataHref: data.dataHref,\n json: data.json,\n response: data.response,\n text: data.text,\n cacheKey: data.cacheKey,\n effect,\n }\n}\n\nexport type Url = UrlObject | string\n\nexport type BaseRouter = {\n route: string\n pathname: string\n query: ParsedUrlQuery\n asPath: string\n basePath: string\n locale?: string | undefined\n locales?: readonly string[] | undefined\n defaultLocale?: string | undefined\n domainLocales?: readonly DomainLocale[] | undefined\n isLocaleDomain: boolean\n}\n\nexport type NextRouter = BaseRouter &\n Pick<\n Router,\n | 'push'\n | 'replace'\n | 'reload'\n | 'back'\n | 'forward'\n | 'prefetch'\n | 'beforePopState'\n | 'events'\n | 'isFallback'\n | 'isReady'\n | 'isPreview'\n >\n\nexport type PrefetchOptions = {\n priority?: boolean\n locale?: string | false\n unstable_skipClientCache?: boolean\n}\n\nexport type PrivateRouteInfo =\n | (Omit<CompletePrivateRouteInfo, 'styleSheets'> & { initial: true })\n | CompletePrivateRouteInfo\n\nexport type CompletePrivateRouteInfo = {\n Component: ComponentType\n styleSheets: StyleSheetTuple[]\n __N_SSG?: boolean\n __N_SSP?: boolean\n props?: Record<string, any>\n err?: Error\n error?: any\n route?: string\n resolvedAs?: string\n query?: ParsedUrlQuery\n}\n\nexport type AppProps = Pick<CompletePrivateRouteInfo, 'Component' | 'err'> & {\n router: Router\n} & Record<string, any>\nexport type AppComponent = ComponentType<AppProps>\n\ntype Subscription = (\n data: PrivateRouteInfo,\n App: AppComponent,\n resetScroll: { x: number; y: number } | null\n) => Promise<void>\n\ntype BeforePopStateCallback = (state: NextHistoryState) => boolean\n\ntype ComponentLoadCancel = (() => void) | null\n\ntype HistoryMethod = 'replaceState' | 'pushState'\n\nconst manualScrollRestoration =\n process.env.__NEXT_SCROLL_RESTORATION &&\n typeof window !== 'undefined' &&\n 'scrollRestoration' in window.history &&\n !!(function () {\n try {\n let v = '__next'\n return (sessionStorage.setItem(v, v), sessionStorage.removeItem(v), true)\n } catch (n) {}\n })()\n\nconst SSG_DATA_NOT_FOUND = Symbol('SSG_DATA_NOT_FOUND')\n\nfunction fetchRetry(\n url: string,\n attempts: number,\n options: Pick<RequestInit, 'method' | 'headers'>\n): Promise<Response> {\n return fetch(url, {\n // Cookies are required to be present for Next.js' SSG \"Preview Mode\".\n // Cookies may also be required for `getServerSideProps`.\n //\n // > `fetch` won’t send cookies, unless you set the credentials init\n // > option.\n // https://developer.mozilla.org/docs/Web/API/Fetch_API/Using_Fetch\n //\n // > For maximum browser compatibility when it comes to sending &\n // > receiving cookies, always supply the `credentials: 'same-origin'`\n // > option instead of relying on the default.\n // https://github.com/github/fetch#caveats\n credentials: 'same-origin',\n method: options.method || 'GET',\n headers: Object.assign({}, options.headers, {\n 'x-nextjs-data': '1',\n }),\n }).then((response) => {\n return !response.ok && attempts > 1 && response.status >= 500\n ? fetchRetry(url, attempts - 1, options)\n : response\n })\n}\n\ninterface FetchDataOutput {\n dataHref: string\n json: Record<string, any> | null\n response: Response\n text: string\n cacheKey: string\n}\n\ninterface FetchNextDataParams {\n dataHref: string\n isServerRender: boolean\n parseJSON: boolean | undefined\n hasMiddleware?: boolean\n inflightCache: NextDataCache\n persistCache: boolean\n isPrefetch: boolean\n isBackground?: boolean\n unstable_skipClientCache?: boolean\n}\n\nfunction tryToParseAsJSON(text: string) {\n try {\n return JSON.parse(text)\n } catch (error) {\n return null\n }\n}\n\nfunction fetchNextData({\n dataHref,\n inflightCache,\n isPrefetch,\n hasMiddleware,\n isServerRender,\n parseJSON,\n persistCache,\n isBackground,\n unstable_skipClientCache,\n}: FetchNextDataParams): Promise<FetchDataOutput> {\n const { href: cacheKey } = new URL(dataHref, window.location.href)\n const deploymentId = getDeploymentId()\n const getData = (params?: { method?: 'HEAD' | 'GET' }) =>\n fetchRetry(dataHref, isServerRender ? 3 : 1, {\n headers: Object.assign(\n {} as HeadersInit,\n isPrefetch ? { purpose: 'prefetch' } : {},\n isPrefetch && hasMiddleware ? { 'x-middleware-prefetch': '1' } : {},\n deploymentId ? { 'x-deployment-id': deploymentId } : {}\n ),\n method: params?.method ?? 'GET',\n })\n .then((response) => {\n if (response.ok && params?.method === 'HEAD') {\n return { dataHref, response, text: '', json: {}, cacheKey }\n }\n\n return response.text().then((text) => {\n if (!response.ok) {\n /**\n * When the data response is a redirect because of a middleware\n * we do not consider it an error. The headers must bring the\n * mapped location.\n * TODO: Change the status code in the handler.\n */\n if (\n hasMiddleware &&\n [301, 302, 307, 308].includes(response.status)\n ) {\n return { dataHref, response, text, json: {}, cacheKey }\n }\n\n if (response.status === 404) {\n if (tryToParseAsJSON(text)?.notFound) {\n return {\n dataHref,\n json: { notFound: SSG_DATA_NOT_FOUND },\n response,\n text,\n cacheKey,\n }\n }\n }\n\n const error = new Error(`Failed to load static props`)\n\n /**\n * We should only trigger a server-side transition if this was\n * caused on a client-side transition. Otherwise, we'd get into\n * an infinite loop.\n */\n if (!isServerRender) {\n markAssetError(error)\n }\n\n throw error\n }\n\n let dplResponseHeader = response.headers.get(\n NEXT_NAV_DEPLOYMENT_ID_HEADER\n )\n if (dplResponseHeader != null && dplResponseHeader !== deploymentId) {\n // When not found, or we want to force a MPA navigation because of Skew Protection\n const error = new Error(\n `Loaded static props were from an outdated deployment, forcing a hard reload`\n )\n /**\n * We should only trigger a server-side transition if this was\n * caused on a client-side transition. Otherwise, we'd get into\n * an infinite loop.\n */\n if (!isServerRender) {\n markAssetError(error)\n }\n throw error\n }\n\n return {\n dataHref,\n json: parseJSON ? tryToParseAsJSON(text) : null,\n response,\n text,\n cacheKey,\n }\n })\n })\n .then((data) => {\n if (\n !persistCache ||\n process.env.NODE_ENV !== 'production' ||\n data.response.headers.get('x-middleware-cache') === 'no-cache'\n ) {\n delete inflightCache[cacheKey]\n }\n return data\n })\n .catch((err) => {\n if (!unstable_skipClientCache) {\n delete inflightCache[cacheKey]\n }\n if (\n // chrome\n err.message === 'Failed to fetch' ||\n // firefox\n err.message === 'NetworkError when attempting to fetch resource.' ||\n // safari\n err.message === 'Load failed'\n ) {\n markAssetError(err)\n }\n throw err\n })\n\n // when skipping client cache we wait to update\n // inflight cache until successful data response\n // this allows racing click event with fetching newer data\n // without blocking navigation when stale data is available\n if (unstable_skipClientCache && persistCache) {\n return getData({}).then((data) => {\n if (data.response.headers.get('x-middleware-cache') !== 'no-cache') {\n // only update cache if not marked as no-cache\n inflightCache[cacheKey] = Promise.resolve(data)\n }\n\n return data\n })\n }\n\n if (inflightCache[cacheKey] !== undefined) {\n return inflightCache[cacheKey]\n }\n return (inflightCache[cacheKey] = getData(\n isBackground ? { method: 'HEAD' } : {}\n ))\n}\n\ninterface NextDataCache {\n [asPath: string]: Promise<FetchDataOutput>\n}\n\nexport function createKey() {\n return Math.random().toString(36).slice(2, 10)\n}\n\nfunction handleHardNavigation({\n url,\n router,\n}: {\n url: string\n router: Router\n}) {\n // ensure we don't trigger a hard navigation to the same\n // URL as this can end up with an infinite refresh\n if (url === addBasePath(addLocale(router.asPath, router.locale))) {\n throw new Error(\n `Invariant: attempted to hard navigate to the same URL ${url} ${location.href}`\n )\n }\n window.location.href = url\n}\n\nconst getCancelledHandler = ({\n route,\n router,\n}: {\n route: string\n router: Router\n}) => {\n let cancelled = false\n const cancel = (router.clc = () => {\n cancelled = true\n })\n\n const handleCancelled = () => {\n if (cancelled) {\n const error: any = new Error(\n `Abort fetching component for route: \"${route}\"`\n )\n error.cancelled = true\n throw error\n }\n\n if (cancel === router.clc) {\n router.clc = null\n }\n }\n return handleCancelled\n}\n\nexport default class Router implements BaseRouter {\n basePath: string\n\n /**\n * Map of all components loaded in `Router`\n */\n components: { [pathname: string]: PrivateRouteInfo }\n // Server Data Cache (full data requests)\n sdc: NextDataCache = {}\n // Server Background Cache (HEAD requests)\n sbc: NextDataCache = {}\n\n sub: Subscription\n clc: ComponentLoadCancel\n pageLoader: PageLoader\n _bps: BeforePopStateCallback | undefined\n events: MittEmitter<RouterEvent>\n _wrapApp: (App: AppComponent) => any\n isSsr: boolean\n _inFlightRoute?: string | undefined\n _shallow?: boolean | undefined\n locales?: readonly string[] | undefined\n defaultLocale?: string | undefined\n domainLocales?: readonly DomainLocale[] | undefined\n isReady: boolean\n isLocaleDomain: boolean\n isFirstPopStateEvent = true\n _initialMatchesMiddlewarePromise: Promise<boolean>\n // static entries filter\n _bfl_s?: import('../../lib/bloom-filter').BloomFilter\n // dynamic entires filter\n _bfl_d?: import('../../lib/bloom-filter').BloomFilter\n\n private state: Readonly<{\n route: string\n pathname: string\n query: ParsedUrlQuery\n asPath: string\n locale: string | undefined\n isFallback: boolean\n isPreview: boolean\n }>\n\n private _key: string = createKey()\n\n static events: MittEmitter<RouterEvent> = mitt()\n\n constructor(\n pathname: string,\n query: ParsedUrlQuery,\n as: string,\n {\n initialProps,\n pageLoader,\n App,\n wrapApp,\n Component,\n err,\n subscription,\n isFallback,\n locale,\n locales,\n defaultLocale,\n domainLocales,\n isPreview,\n }: {\n subscription: Subscription\n initialProps: any\n pageLoader: any\n Component: ComponentType\n App: AppComponent\n wrapApp: (WrapAppComponent: AppComponent) => any\n err?: Error\n isFallback: boolean\n locale?: string\n locales?: readonly string[]\n defaultLocale?: string\n domainLocales?: readonly DomainLocale[]\n isPreview?: boolean\n }\n ) {\n // represents the current component key\n const route = removeTrailingSlash(pathname)\n\n // set up the component cache (by route keys)\n this.components = {}\n // We should not keep the cache, if there's an error\n // Otherwise, this cause issues when when going back and\n // come again to the errored page.\n if (pathname !== '/_error') {\n this.components[route] = {\n Component,\n initial: true,\n props: initialProps,\n err,\n __N_SSG: initialProps && initialProps.__N_SSG,\n __N_SSP: initialProps && initialProps.__N_SSP,\n }\n }\n\n this.components['/_app'] = {\n Component: App as ComponentType,\n styleSheets: [\n /* /_app does not need its stylesheets managed */\n ],\n }\n\n // Backwards compat for Router.router.events\n // TODO: Should be remove the following major version as it was never documented\n this.events = Router.events\n\n this.pageLoader = pageLoader\n // if auto prerendered and dynamic route wait to update asPath\n // until after mount to prevent hydration mismatch\n const autoExportDynamic =\n isDynamicRoute(pathname) && self.__NEXT_DATA__.autoExport\n\n this.basePath = process.env.__NEXT_ROUTER_BASEPATH || ''\n this.sub = subscription\n this.clc = null\n this._wrapApp = wrapApp\n // make sure to ignore extra popState in safari on navigating\n // back from external site\n this.isSsr = true\n this.isLocaleDomain = false\n this.isReady = !!(\n self.__NEXT_DATA__.gssp ||\n self.__NEXT_DATA__.gip ||\n self.__NEXT_DATA__.isExperimentalCompile ||\n (self.__NEXT_DATA__.appGip && !self.__NEXT_DATA__.gsp) ||\n (!autoExportDynamic &&\n !self.location.search &&\n !process.env.__NEXT_HAS_REWRITES)\n )\n\n if (process.env.__NEXT_I18N_SUPPORT) {\n this.locales = locales\n this.defaultLocale = defaultLocale\n this.domainLocales = domainLocales\n this.isLocaleDomain = !!detectDomainLocale(\n domainLocales,\n self.location.hostname\n )\n }\n\n this.state = {\n route,\n pathname,\n query,\n asPath: autoExportDynamic ? pathname : as,\n isPreview: !!isPreview,\n locale: process.env.__NEXT_I18N_SUPPORT ? locale : undefined,\n isFallback,\n }\n\n this._initialMatchesMiddlewarePromise = Promise.resolve(false)\n\n if (typeof window !== 'undefined') {\n // make sure \"as\" doesn't start with double slashes or else it can\n // throw an error as it's considered invalid\n if (!as.startsWith('//')) {\n // in order for `e.state` to work on the `onpopstate` event\n // we have to register the initial route upon initialization\n const options: TransitionOptions = { locale }\n const asPath = getURL()\n\n this._initialMatchesMiddlewarePromise = matchesMiddleware({\n router: this,\n locale,\n asPath,\n }).then((matches) => {\n // if middleware matches we leave resolving to the change function\n // as the server needs to resolve for correct priority\n ;(options as any)._shouldResolveHref = as !== pathname\n\n this.changeState(\n 'replaceState',\n matches\n ? asPath\n : formatWithValidation({\n pathname: addBasePath(pathname),\n query,\n }),\n asPath,\n options\n )\n return matches\n })\n }\n\n window.addEventListener('popstate', this.onPopState)\n\n // enable custom scroll restoration handling when available\n // otherwise fallback to browser's default handling\n if (process.env.__NEXT_SCROLL_RESTORATION) {\n if (manualScrollRestoration) {\n window.history.scrollRestoration = 'manual'\n }\n }\n }\n }\n\n onPopState = (e: PopStateEvent): void => {\n const { isFirstPopStateEvent } = this\n this.isFirstPopStateEvent = false\n\n const state = e.state as HistoryState\n\n if (!state) {\n // We get state as undefined for two reasons.\n // 1. With older safari (< 8) and older chrome (< 34)\n // 2. When the URL changed with #\n //\n // In the both cases, we don't need to proceed and change the route.\n // (as it's already changed)\n // But we can simply replace the state with the new changes.\n // Actually, for (1) we don't need to nothing. But it's hard to detect that event.\n // So, doing the following for (1) does no harm.\n const { pathname, query } = this\n this.changeState(\n 'replaceState',\n formatWithValidation({ pathname: addBasePath(pathname), query }),\n getURL()\n )\n return\n }\n\n // __NA is used to identify if the history entry can be handled by the app-router.\n if (state.__NA) {\n window.location.reload()\n return\n }\n\n if (!state.__N) {\n return\n }\n\n // Safari fires popstateevent when reopening the browser.\n if (\n isFirstPopStateEvent &&\n this.locale === state.options.locale &&\n state.as === this.asPath\n ) {\n return\n }\n\n let forcedScroll: { x: number; y: number } | undefined\n const { url, as, options, key } = state\n if (process.env.__NEXT_SCROLL_RESTORATION) {\n if (manualScrollRestoration) {\n if (this._key !== key) {\n // Snapshot current scroll position:\n try {\n sessionStorage.setItem(\n '__next_scroll_' + this._key,\n JSON.stringify({ x: self.pageXOffset, y: self.pageYOffset })\n )\n } catch {}\n\n // Restore old scroll position:\n try {\n const v = sessionStorage.getItem('__next_scroll_' + key)\n forcedScroll = JSON.parse(v!)\n } catch {\n forcedScroll = { x: 0, y: 0 }\n }\n }\n }\n }\n this._key = key\n\n const { pathname } = parseRelativeUrl(url)\n\n // Make sure we don't re-render on initial load,\n // can be caused by navigating back from an external site\n if (\n this.isSsr &&\n as === addBasePath(this.asPath) &&\n pathname === addBasePath(this.pathname)\n ) {\n return\n }\n\n // If the downstream application returns falsy, return.\n // They will then be responsible for handling the event.\n if (this._bps && !this._bps(state)) {\n return\n }\n\n this.change(\n 'replaceState',\n url,\n as,\n Object.assign<{}, TransitionOptions, TransitionOptions>({}, options, {\n shallow: options.shallow && this._shallow,\n locale: options.locale || this.defaultLocale,\n // @ts-ignore internal value not exposed on types\n _h: 0,\n }),\n forcedScroll\n )\n }\n\n reload(): void {\n window.location.reload()\n }\n\n /**\n * Go back in history\n */\n back() {\n window.history.back()\n }\n\n /**\n * Go forward in history\n */\n forward() {\n window.history.forward()\n }\n\n /**\n * Performs a `pushState` with arguments\n * @param url of the route\n * @param as masks `url` for the browser\n * @param options object you can define `shallow` and other options\n */\n push(url: Url, as?: Url, options: TransitionOptions = {}) {\n if (\n isJavaScriptURLString(url.toString()) ||\n (as && isJavaScriptURLString(as.toString()))\n ) {\n throw new Error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n }\n if (process.env.__NEXT_SCROLL_RESTORATION) {\n // TODO: remove in the future when we update history before route change\n // is complete, as the popstate event should handle this capture.\n if (manualScrollRestoration) {\n try {\n // Snapshot scroll position right before navigating to a new page:\n sessionStorage.setItem(\n '__next_scroll_' + this._key,\n JSON.stringify({ x: self.pageXOffset, y: self.pageYOffset })\n )\n } catch {}\n }\n }\n ;({ url, as } = prepareUrlAs(this, url, as))\n return this.change('pushState', url, as, options)\n }\n\n /**\n * Performs a `replaceState` with arguments\n * @param url of the route\n * @param as masks `url` for the browser\n * @param options object you can define `shallow` and other options\n */\n replace(url: Url, as?: Url, options: TransitionOptions = {}) {\n if (\n isJavaScriptURLString(url.toString()) ||\n (as && isJavaScriptURLString(as.toString()))\n ) {\n throw new Error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n }\n ;({ url, as } = prepareUrlAs(this, url, as))\n return this.change('replaceState', url, as, options)\n }\n\n async _bfl(\n as: string,\n resolvedAs?: string,\n locale?: string | false,\n skipNavigate?: boolean\n ) {\n if (process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED) {\n if (!this._bfl_s && !this._bfl_d) {\n const { BloomFilter } =\n require('../../lib/bloom-filter') as typeof import('../../lib/bloom-filter')\n\n type Filter = ReturnType<\n import('../../lib/bloom-filter').BloomFilter['export']\n >\n let staticFilterData: Filter | undefined\n let dynamicFilterData: Filter | undefined\n\n try {\n ;({\n __routerFilterStatic: staticFilterData,\n __routerFilterDynamic: dynamicFilterData,\n } = (await getClientBuildManifest()) as any as {\n __routerFilterStatic?: Filter\n __routerFilterDynamic?: Filter\n })\n } catch (err) {\n // failed to load build manifest hard navigate\n // to be safe\n console.error(err)\n if (skipNavigate) {\n return true\n }\n handleHardNavigation({\n url: addBasePath(\n addLocale(as, locale || this.locale, this.defaultLocale)\n ),\n router: this,\n })\n return new Promise(() => {})\n }\n\n const routerFilterSValue: Filter | false = process.env\n .__NEXT_CLIENT_ROUTER_S_FILTER as any\n\n if (!staticFilterData && routerFilterSValue) {\n staticFilterData = routerFilterSValue ? routerFilterSValue : undefined\n }\n\n const routerFilterDValue: Filter | false = process.env\n .__NEXT_CLIENT_ROUTER_D_FILTER as any\n\n if (!dynamicFilterData && routerFilterDValue) {\n dynamicFilterData = routerFilterDValue\n ? routerFilterDValue\n : undefined\n }\n\n if (staticFilterData?.numHashes) {\n this._bfl_s = new BloomFilter(\n staticFilterData.numItems,\n staticFilterData.errorRate\n )\n this._bfl_s.import(staticFilterData)\n }\n\n if (dynamicFilterData?.numHashes) {\n this._bfl_d = new BloomFilter(\n dynamicFilterData.numItems,\n dynamicFilterData.errorRate\n )\n this._bfl_d.import(dynamicFilterData)\n }\n }\n\n let matchesBflStatic = false\n let matchesBflDynamic = false\n const pathsToCheck: Array<{ as?: string; allowMatchCurrent?: boolean }> =\n [{ as }, { as: resolvedAs }]\n\n for (const { as: curAs, allowMatchCurrent } of pathsToCheck) {\n if (curAs) {\n const asNoSlash = removeTrailingSlash(\n new URL(curAs, 'http://n').pathname\n )\n const asNoSlashLocale = addBasePath(\n addLocale(asNoSlash, locale || this.locale)\n )\n\n if (\n allowMatchCurrent ||\n asNoSlash !==\n removeTrailingSlash(new URL(this.asPath, 'http://n').pathname)\n ) {\n matchesBflStatic =\n matchesBflStatic ||\n !!this._bfl_s?.contains(asNoSlash) ||\n !!this._bfl_s?.contains(asNoSlashLocale)\n\n for (const normalizedAS of [asNoSlash, asNoSlashLocale]) {\n // if any sub-path of as matches a dynamic filter path\n // it should be hard navigated\n const curAsParts = normalizedAS.split('/')\n for (\n let i = 0;\n !matchesBflDynamic && i < curAsParts.length + 1;\n i++\n ) {\n const currentPart = curAsParts.slice(0, i).join('/')\n if (currentPart && this._bfl_d?.contains(currentPart)) {\n matchesBflDynamic = true\n break\n }\n }\n }\n\n // if the client router filter is matched then we trigger\n // a hard navigation\n if (matchesBflStatic || matchesBflDynamic) {\n if (skipNavigate) {\n return true\n }\n handleHardNavigation({\n url: addBasePath(\n addLocale(as, locale || this.locale, this.defaultLocale)\n ),\n router: this,\n })\n return new Promise(() => {})\n }\n }\n }\n }\n }\n return false\n }\n\n private async change(\n method: HistoryMethod,\n url: string,\n as: string,\n options: TransitionOptions,\n forcedScroll?: { x: number; y: number }\n ): Promise<boolean> {\n if (!isLocalURL(url)) {\n handleHardNavigation({ url, router: this })\n return false\n }\n // WARNING: `_h` is an internal option for handing Next.js client-side\n // hydration. Your app should _never_ use this property. It may change at\n // any time without notice.\n const isQueryUpdating = (options as any)._h === 1\n\n if (!isQueryUpdating && !options.shallow) {\n await this._bfl(as, undefined, options.locale)\n }\n\n let shouldResolveHref =\n isQueryUpdating ||\n (options as any)._shouldResolveHref ||\n parsePath(url).pathname === parsePath(as).pathname\n\n const nextState = {\n ...this.state,\n }\n\n // for static pages with query params in the URL we delay\n // marking the router ready until after the query is updated\n // or a navigation has occurred\n const readyStateChange = this.isReady !== true\n this.isReady = true\n const isSsr = this.isSsr\n\n if (!isQueryUpdating) {\n this.isSsr = false\n }\n\n // if a route transition is already in progress before\n // the query updating is triggered ignore query updating\n if (isQueryUpdating && this.clc) {\n return false\n }\n\n const prevLocale = nextState.locale\n\n if (process.env.__NEXT_I18N_SUPPORT) {\n nextState.locale =\n options.locale === false\n ? this.defaultLocale\n : options.locale || nextState.locale\n\n if (typeof options.locale === 'undefined') {\n options.locale = nextState.locale\n }\n\n const parsedAs = parseRelativeUrl(\n hasBasePath(as) ? removeBasePath(as) : as\n )\n const localePathResult = normalizeLocalePath(\n parsedAs.pathname,\n this.locales\n )\n\n if (localePathResult.detectedLocale) {\n nextState.locale = localePathResult.detectedLocale\n parsedAs.pathname = addBasePath(parsedAs.pathname)\n as = formatWithValidation(parsedAs)\n url = addBasePath(\n normalizeLocalePath(\n hasBasePath(url) ? removeBasePath(url) : url,\n this.locales\n ).pathname\n )\n }\n let didNavigate = false\n\n // we need to wrap this in the env check again since regenerator runtime\n // moves this on its own due to the return\n if (process.env.__NEXT_I18N_SUPPORT) {\n // if the locale isn't configured hard navigate to show 404 page\n if (!this.locales?.includes(nextState.locale!)) {\n parsedAs.pathname = addLocale(parsedAs.pathname, nextState.locale)\n handleHardNavigation({\n url: formatWithValidation(parsedAs),\n router: this,\n })\n // this was previously a return but was removed in favor\n // of better dead code elimination with regenerator runtime\n didNavigate = true\n }\n }\n\n const detectedDomain = detectDomainLocale(\n this.domainLocales,\n undefined,\n nextState.locale\n )\n\n // we need to wrap this in the env check again since regenerator runtime\n // moves this on its own due to the return\n if (process.env.__NEXT_I18N_SUPPORT) {\n // if we are navigating to a domain locale ensure we redirect to the\n // correct domain\n if (\n !didNavigate &&\n detectedDomain &&\n this.isLocaleDomain &&\n self.location.hostname !== detectedDomain.domain\n ) {\n const asNoBasePath = removeBasePath(as)\n handleHardNavigation({\n url: `http${detectedDomain.http ? '' : 's'}://${\n detectedDomain.domain\n }${addBasePath(\n `${\n nextState.locale === detectedDomain.defaultLocale\n ? ''\n : `/${nextState.locale}`\n }${asNoBasePath === '/' ? '' : asNoBasePath}` || '/'\n )}`,\n router: this,\n })\n // this was previously a return but was removed in favor\n // of better dead code elimination with regenerator runtime\n didNavigate = true\n }\n }\n\n if (didNavigate) {\n return new Promise(() => {})\n }\n }\n\n // marking route changes as a navigation start entry\n if (ST) {\n performance.mark('routeChange')\n }\n\n const { shallow = false, scroll = true } = options\n const routeProps = { shallow }\n\n if (this._inFlightRoute && this.clc) {\n if (!isSsr) {\n Router.events.emit(\n 'routeChangeError',\n buildCancellationError(),\n this._inFlightRoute,\n routeProps\n )\n }\n this.clc()\n this.clc = null\n }\n\n as = addBasePath(\n addLocale(\n hasBasePath(as) ? removeBasePath(as) : as,\n options.locale,\n this.defaultLocale\n )\n )\n const cleanedAs = removeLocale(\n hasBasePath(as) ? removeBasePath(as) : as,\n nextState.locale\n )\n this._inFlightRoute = as\n\n const localeChange = prevLocale !== nextState.locale\n\n // If the url change is only related to a hash change\n // We should not proceed. We should only change the state.\n if (!isQueryUpdating && this.onlyAHashChange(cleanedAs) && !localeChange) {\n nextState.asPath = cleanedAs\n Router.events.emit('hashChangeStart', as, routeProps)\n // TODO: do we need the resolved href when only a hash change?\n this.changeState(method, url, as, {\n ...options,\n scroll: false,\n })\n if (scroll) {\n this.scrollToHash(cleanedAs)\n }\n try {\n await this.set(nextState, this.components[nextState.route], null)\n } catch (err) {\n if (isError(err) && err.cancelled) {\n Router.events.emit('routeChangeError', err, cleanedAs, routeProps)\n }\n throw err\n }\n\n Router.events.emit('hashChangeComplete', as, routeProps)\n return true\n }\n\n let parsed = parseRelativeUrl(url)\n let { pathname, query } = parsed\n\n // The build manifest needs to be loaded before auto-static dynamic pages\n // get their query parameters to allow ensuring they can be parsed properly\n // when rewritten to\n let pages: string[], rewrites: any\n try {\n ;[pages, { __rewrites: rewrites }] = await Promise.all([\n this.pageLoader.getPageList(),\n getClientBuildManifest(),\n this.pageLoader.getMiddleware(),\n ])\n } catch (err) {\n // If we fail to resolve the page list or client-build manifest, we must\n // do a server-side transition:\n handleHardNavigation({ url: as, router: this })\n return false\n }\n\n // If asked to change the current URL we should reload the current page\n // (not location.reload() but reload getInitialProps and other Next.js stuffs)\n // We also need to set the method = replaceState always\n // as this should not go into the history (That's how browsers work)\n // We should compare the new asPath to the current asPath, not the url\n if (!this.urlIsNew(cleanedAs) && !localeChange) {\n method = 'replaceState'\n }\n\n // we need to resolve the as value using rewrites for dynamic SSG\n // pages to allow building the data URL correctly\n let resolvedAs = as\n\n // url and as should always be prefixed with basePath by this\n // point by either next/link or router.push/replace so strip the\n // basePath from the pathname to match the pages dir 1-to-1\n pathname = pathname\n ? removeTrailingSlash(removeBasePath(pathname))\n : pathname\n\n let route = removeTrailingSlash(pathname)\n const parsedAsPathname = as.startsWith('/') && parseRelativeUrl(as).pathname\n\n // if we detected the `as` path as app route during prefetching\n // trigger hard navigation. The marker is keyed by the `as` path, but a\n // marker can also sit under the href route when both paths share a\n // pages route (`pages/modal.js` next to `app/modal/[id]/page.js`).\n // Check both so `getRouteInfo()` never reads a marker as component data.\n const appRouterMarkerKey = getAppRouterMarkerKey(\n this,\n cleanedAs,\n nextState.locale\n )\n if (\n (appRouterMarkerKey !== null &&\n (this.components[appRouterMarkerKey] as any)?.__appRouter) ||\n (this.components[route] as any)?.__appRouter\n ) {\n handleHardNavigation({ url: as, router: this })\n return new Promise(() => {})\n }\n\n const isMiddlewareRewrite = !!(\n parsedAsPathname &&\n route !== parsedAsPathname &&\n (!isDynamicRoute(route) ||\n !getRouteMatcher(getRouteRegex(route))(parsedAsPathname))\n )\n\n // we don't attempt resolve asPath when we need to execute\n // middleware as the resolving will occur server-side\n const isMiddlewareMatch =\n !options.shallow &&\n (await matchesMiddleware({\n asPath: as,\n locale: nextState.locale,\n router: this,\n }))\n\n if (isQueryUpdating && isMiddlewareMatch) {\n shouldResolveHref = false\n }\n\n if (shouldResolveHref && pathname !== '/_error') {\n ;(options as any)._shouldResolveHref = true\n\n if (process.env.__NEXT_HAS_REWRITES && as.startsWith('/')) {\n const rewritesResult = resolveRewrites(\n addBasePath(addLocale(cleanedAs, nextState.locale), true),\n pages,\n rewrites,\n query,\n (p: string) => resolveDynamicRoute(p, pages),\n this.locales\n )\n\n if (rewritesResult.externalDest) {\n handleHardNavigation({ url: as, router: this })\n return true\n }\n if (!isMiddlewareMatch) {\n resolvedAs = rewritesResult.asPath\n }\n\n if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {\n // if this directly matches a page we need to update the href to\n // allow the correct page chunk to be loaded\n pathname = rewritesResult.resolvedHref\n parsed.pathname = addBasePath(pathname)\n\n if (!isMiddlewareMatch) {\n url = formatWithValidation(parsed)\n }\n }\n } else {\n parsed.pathname = resolveDynamicRoute(pathname, pages)\n\n if (parsed.pathname !== pathname) {\n pathname = parsed.pathname\n parsed.pathname = addBasePath(pathname)\n\n if (!isMiddlewareMatch) {\n url = formatWithValidation(parsed)\n }\n }\n }\n }\n\n // The pages client router resolves a navigation against pages routes only.\n // When it resolves to a dynamic pages route, an app route that begins with\n // a dynamic segment may be more specific and own this path on the server\n // (e.g. `/en/about` resolves to the pages route `/[locale]/[category]`, but\n // the app route `/[locale]/about` should win). Such app routes have no\n // static prefix for the early `_bfl` check, so reconstruct the candidate\n // patterns from the resolved route and hard navigate when one is in the\n // dynamic filter.\n if (\n !isQueryUpdating &&\n !options.shallow &&\n process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED &&\n this._bfl_d &&\n isDynamicRoute(pathname)\n ) {\n const concretePathname = removeTrailingSlash(\n parseRelativeUrl(cleanedAs).pathname\n )\n const isShadowedByAppRoute = hasDynamicFilterCandidate(\n pathname,\n concretePathname,\n (candidate) => !!this._bfl_d?.contains(candidate)\n )\n\n if (isShadowedByAppRoute) {\n handleHardNavigation({ url: as, router: this })\n return new Promise(() => {})\n }\n }\n\n if (!isLocalURL(as)) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n `Invalid href: \"${url}\" and as: \"${as}\", received relative href and external as` +\n `\\nSee more info: https://nextjs.org/docs/messages/invalid-relative-url-external-as`\n )\n }\n handleHardNavigation({ url: as, router: this })\n return false\n }\n\n resolvedAs = removeLocale(removeBasePath(resolvedAs), nextState.locale)\n\n route = removeTrailingSlash(pathname)\n\n // A config rewrite can resolve `href` to another pages route after the\n // marker guard above ran. That route can hold a marker from an earlier\n // prefetch, so check it again before `getRouteInfo()` reads the cache.\n if ((this.components[route] as any)?.__appRouter) {\n handleHardNavigation({ url: as, router: this })\n return new Promise(() => {})\n }\n\n let routeMatch: Params | false = false\n\n if (isDynamicRoute(route)) {\n const parsedAs = parseRelativeUrl(resolvedAs)\n const asPathname = parsedAs.pathname\n\n const routeRegex = getRouteRegex(route)\n routeMatch = getRouteMatcher(routeRegex)(asPathname)\n const shouldInterpolate = route === asPathname\n const interpolatedAs = shouldInterpolate\n ? interpolateAs(route, asPathname, query)\n : ({} as { result: undefined; params: undefined })\n\n if (!routeMatch || (shouldInterpolate && !interpolatedAs.result)) {\n const missingParams = Object.keys(routeRegex.groups).filter(\n (param) => !query[param] && !routeRegex.groups[param].optional\n )\n\n if (missingParams.length > 0 && !isMiddlewareMatch) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `${\n shouldInterpolate\n ? `Interpolating href`\n : `Mismatching \\`as\\` and \\`href\\``\n } failed to manually provide ` +\n `the params: ${missingParams.join(\n ', '\n )} in the \\`href\\`'s \\`query\\``\n )\n }\n\n throw new Error(\n (shouldInterpolate\n ? `The provided \\`href\\` (${url}) value is missing query values (${missingParams.join(\n ', '\n )}) to be interpolated properly. `\n : `The provided \\`as\\` value (${asPathname}) is incompatible with the \\`href\\` value (${route}). `) +\n `Read more: https://nextjs.org/docs/messages/${\n shouldInterpolate\n ? 'href-interpolation-failed'\n : 'incompatible-href-as'\n }`\n )\n }\n } else if (shouldInterpolate) {\n as = formatWithValidation(\n Object.assign({}, parsedAs, {\n pathname: interpolatedAs.result,\n query: omit(query, interpolatedAs.params!),\n })\n )\n } else {\n // Merge params into `query`, overwriting any specified in search\n Object.assign(query, routeMatch)\n }\n }\n\n if (!isQueryUpdating) {\n Router.events.emit('routeChangeStart', as, routeProps)\n }\n\n const isErrorRoute = this.pathname === '/404' || this.pathname === '/_error'\n\n try {\n let routeInfo = await this.getRouteInfo({\n route,\n pathname,\n query,\n as,\n resolvedAs,\n routeProps,\n locale: nextState.locale,\n isPreview: nextState.isPreview,\n hasMiddleware: isMiddlewareMatch,\n unstable_skipClientCache: options.unstable_skipClientCache,\n isQueryUpdating: isQueryUpdating && !this.isFallback,\n isMiddlewareRewrite,\n })\n\n if (!isQueryUpdating && !options.shallow) {\n await this._bfl(\n as,\n 'resolvedAs' in routeInfo ? routeInfo.resolvedAs : undefined,\n nextState.locale\n )\n }\n\n if ('route' in routeInfo && isMiddlewareMatch) {\n pathname = routeInfo.route || route\n route = pathname\n\n if (!routeProps.shallow) {\n query = Object.assign({}, routeInfo.query || {}, query)\n }\n\n const cleanedParsedPathname = hasBasePath(parsed.pathname)\n ? removeBasePath(parsed.pathname)\n : parsed.pathname\n\n if (routeMatch && pathname !== cleanedParsedPathname) {\n Object.keys(routeMatch).forEach((key) => {\n if (routeMatch && query[key] === routeMatch[key]) {\n delete query[key]\n }\n })\n }\n\n if (isDynamicRoute(pathname)) {\n const prefixedAs =\n !routeProps.shallow && routeInfo.resolvedAs\n ? routeInfo.resolvedAs\n : addBasePath(\n addLocale(\n new URL(as, location.href).pathname,\n nextState.locale\n ),\n true\n )\n\n let rewriteAs = prefixedAs\n\n if (hasBasePath(rewriteAs)) {\n rewriteAs = removeBasePath(rewriteAs)\n }\n\n if (process.env.__NEXT_I18N_SUPPORT) {\n const localeResult = normalizeLocalePath(rewriteAs, this.locales)\n nextState.locale = localeResult.detectedLocale || nextState.locale\n rewriteAs = localeResult.pathname\n }\n const routeRegex = getRouteRegex(pathname)\n const curRouteMatch = getRouteMatcher(routeRegex)(\n new URL(rewriteAs, location.href).pathname\n )\n\n if (curRouteMatch) {\n Object.assign(query, curRouteMatch)\n }\n }\n }\n\n // If the routeInfo brings a redirect we simply apply it.\n if ('type' in routeInfo) {\n if (routeInfo.type === 'redirect-internal') {\n return this.change(method, routeInfo.newUrl, routeInfo.newAs, options)\n } else {\n handleHardNavigation({ url: routeInfo.destination, router: this })\n return new Promise(() => {})\n }\n }\n\n const component: any = routeInfo.Component\n if (component && component.unstable_scriptLoader) {\n const scripts = [].concat(component.unstable_scriptLoader())\n\n scripts.forEach((script: any) => {\n handleClientScriptLoad(script.props)\n })\n }\n\n // handle redirect on client-transition\n if ((routeInfo.__N_SSG || routeInfo.__N_SSP) && routeInfo.props) {\n if (\n routeInfo.props.pageProps &&\n routeInfo.props.pageProps.__N_REDIRECT\n ) {\n // Use the destination from redirect without adding locale\n options.locale = false\n\n const destination = routeInfo.props.pageProps.__N_REDIRECT\n\n // check if destination is internal (resolves to a page) and attempt\n // client-navigation if it is falling back to hard navigation if\n // it's not\n if (\n destination.startsWith('/') &&\n routeInfo.props.pageProps.__N_REDIRECT_BASE_PATH !== false\n ) {\n const parsedHref = parseRelativeUrl(destination)\n parsedHref.pathname = resolveDynamicRoute(\n parsedHref.pathname,\n pages\n )\n\n const { url: newUrl, as: newAs } = prepareUrlAs(\n this,\n destination,\n destination\n )\n return this.change(method, newUrl, newAs, options)\n }\n handleHardNavigation({ url: destination, router: this })\n return new Promise(() => {})\n }\n\n nextState.isPreview = !!routeInfo.props.__N_PREVIEW\n\n // handle SSG data 404\n if (routeInfo.props.notFound === SSG_DATA_NOT_FOUND) {\n let notFoundRoute\n\n try {\n await this.fetchComponent('/404')\n notFoundRoute = '/404'\n } catch (_) {\n notFoundRoute = '/_error'\n }\n\n routeInfo = await this.getRouteInfo({\n route: notFoundRoute,\n pathname: notFoundRoute,\n query,\n as,\n resolvedAs,\n routeProps: { shallow: false },\n locale: nextState.locale,\n isPreview: nextState.isPreview,\n isNotFound: true,\n })\n\n if ('type' in routeInfo) {\n throw new Error(`Unexpected middleware effect on /404`)\n }\n }\n }\n\n if (\n isQueryUpdating &&\n this.pathname === '/_error' &&\n self.__NEXT_DATA__.props?.pageProps?.statusCode === 500 &&\n routeInfo.props?.pageProps\n ) {\n // ensure statusCode is still correct for static 500 page\n // when updating query information\n routeInfo.props.pageProps.statusCode = 500\n }\n\n // shallow routing is only allowed for same page URL changes.\n const isValidShallowRoute =\n options.shallow && nextState.route === (routeInfo.route ?? route)\n\n const shouldScroll =\n options.scroll ?? (!isQueryUpdating && !isValidShallowRoute)\n const resetScroll = shouldScroll ? { x: 0, y: 0 } : null\n const upcomingScrollState = forcedScroll ?? resetScroll\n\n // the new state that the router gonna set\n const upcomingRouterState = {\n ...nextState,\n route,\n pathname,\n query,\n asPath: cleanedAs,\n isFallback: false,\n }\n\n // When the page being rendered is the 404 page, we should only update the\n // query parameters. Route changes here might add the basePath when it\n // wasn't originally present. This is also why this block is before the\n // below `changeState` call which updates the browser's history (changing\n // the URL).\n if (isQueryUpdating && isErrorRoute) {\n routeInfo = await this.getRouteInfo({\n route: this.pathname,\n pathname: this.pathname,\n query,\n as,\n resolvedAs,\n routeProps: { shallow: false },\n locale: nextState.locale,\n isPreview: nextState.isPreview,\n isQueryUpdating: isQueryUpdating && !this.isFallback,\n })\n\n if ('type' in routeInfo) {\n throw new Error(`Unexpected middleware effect on ${this.pathname}`)\n }\n\n if (\n this.pathname === '/_error' &&\n self.__NEXT_DATA__.props?.pageProps?.statusCode === 500 &&\n routeInfo.props?.pageProps\n ) {\n // ensure statusCode is still correct for static 500 page\n // when updating query information\n routeInfo.props.pageProps.statusCode = 500\n }\n\n try {\n await this.set(upcomingRouterState, routeInfo, upcomingScrollState)\n } catch (err) {\n if (isError(err) && err.cancelled) {\n Router.events.emit('routeChangeError', err, cleanedAs, routeProps)\n }\n throw err\n }\n\n return true\n }\n\n Router.events.emit('beforeHistoryChange', as, routeProps)\n this.changeState(method, url, as, options)\n\n // for query updates we can skip it if the state is unchanged and we don't\n // need to scroll\n // https://github.com/vercel/next.js/issues/37139\n const canSkipUpdating =\n isQueryUpdating &&\n !upcomingScrollState &&\n !readyStateChange &&\n !localeChange &&\n compareRouterStates(upcomingRouterState, this.state)\n\n if (!canSkipUpdating) {\n try {\n await this.set(upcomingRouterState, routeInfo, upcomingScrollState)\n } catch (e: any) {\n if (e.cancelled) routeInfo.error = routeInfo.error || e\n else throw e\n }\n\n if (routeInfo.error) {\n if (!isQueryUpdating) {\n Router.events.emit(\n 'routeChangeError',\n routeInfo.error,\n cleanedAs,\n routeProps\n )\n }\n\n throw routeInfo.error\n }\n\n if (process.env.__NEXT_I18N_SUPPORT) {\n if (nextState.locale) {\n document.documentElement.lang = nextState.locale\n }\n }\n\n if (!isQueryUpdating) {\n Router.events.emit('routeChangeComplete', as, routeProps)\n }\n\n // A hash mark # is the optional last part of a URL\n const hashRegex = /#.+$/\n if (shouldScroll && hashRegex.test(as)) {\n this.scrollToHash(as)\n }\n }\n\n return true\n } catch (err) {\n if (isError(err) && err.cancelled) {\n return false\n }\n throw err\n }\n }\n\n changeState(\n method: HistoryMethod,\n url: string,\n as: string,\n options: TransitionOptions = {}\n ): void {\n if (process.env.NODE_ENV !== 'production') {\n if (typeof window.history === 'undefined') {\n console.error(`Warning: window.history is not available.`)\n return\n }\n\n if (typeof window.history[method] === 'undefined') {\n console.error(`Warning: window.history.${method} is not available`)\n return\n }\n }\n\n if (method !== 'pushState' || getURL() !== as) {\n this._shallow = options.shallow\n window.history[method](\n {\n url,\n as,\n options,\n __N: true,\n key: (this._key = method !== 'pushState' ? this._key : createKey()),\n } as HistoryState,\n // Most browsers currently ignores this parameter, although they may use it in the future.\n // Passing the empty string here should be safe against future changes to the method.\n // https://developer.mozilla.org/docs/Web/API/History/replaceState\n '',\n as\n )\n }\n }\n\n async handleRouteInfoError(\n err: Error & { code?: any; cancelled?: boolean },\n pathname: string,\n query: ParsedUrlQuery,\n as: string,\n routeProps: RouteProperties,\n loadErrorFail?: boolean\n ): Promise<CompletePrivateRouteInfo> {\n if (err.cancelled) {\n // bubble up cancellation errors\n throw err\n }\n\n if (isAssetError(err) || loadErrorFail) {\n Router.events.emit('routeChangeError', err, as, routeProps)\n\n // If we can't load the page it could be one of following reasons\n // 1. Page doesn't exists\n // 2. Page does exist in a different zone\n // 3. Internal error while loading the page\n\n // So, doing a hard reload is the proper way to deal with this.\n handleHardNavigation({\n url: as,\n router: this,\n })\n\n // Changing the URL doesn't block executing the current code path.\n // So let's throw a cancellation error stop the routing logic.\n throw buildCancellationError()\n }\n\n console.error(err)\n\n try {\n let props: Record<string, any> | undefined\n const { page: Component, styleSheets } =\n await this.fetchComponent('/_error')\n\n const routeInfo: CompletePrivateRouteInfo = {\n props,\n Component,\n styleSheets,\n err,\n error: err,\n }\n\n if (!routeInfo.props) {\n try {\n routeInfo.props = await this.getInitialProps(Component, {\n err,\n pathname,\n query,\n } as any)\n } catch (gipErr) {\n console.error('Error in error page `getInitialProps`: ', gipErr)\n routeInfo.props = {}\n }\n }\n\n return routeInfo\n } catch (routeInfoErr) {\n return this.handleRouteInfoError(\n isError(routeInfoErr) ? routeInfoErr : new Error(routeInfoErr + ''),\n pathname,\n query,\n as,\n routeProps,\n true\n )\n }\n }\n\n async getRouteInfo({\n route: requestedRoute,\n pathname,\n query,\n as,\n resolvedAs,\n routeProps,\n locale,\n hasMiddleware,\n isPreview,\n unstable_skipClientCache,\n isQueryUpdating,\n isMiddlewareRewrite,\n isNotFound,\n }: {\n route: string\n pathname: string\n query: ParsedUrlQuery\n as: string\n resolvedAs: string\n hasMiddleware?: boolean\n routeProps: RouteProperties\n locale: string | undefined\n isPreview: boolean\n unstable_skipClientCache?: boolean\n isQueryUpdating?: boolean\n isMiddlewareRewrite?: boolean\n isNotFound?: boolean\n }) {\n /**\n * This `route` binding can change if there's a rewrite\n * so we keep a reference to the original requested route\n * so we can store the cache for it and avoid re-requesting every time\n * for shallow routing purposes.\n */\n let route = requestedRoute\n\n try {\n let existingInfo: PrivateRouteInfo | undefined = this.components[route]\n\n // `prefetch()` stores a `{ __appRouter: true }` marker in\n // `this.components` when the client router filter matches a path. That\n // marker is not route info: it has no `Component` and no `props`, so\n // rendering it crashes `_app`. Treat it as a cache miss and fetch the\n // route info again; `change()` is responsible for the hard navigation.\n if (existingInfo && (existingInfo as any).__appRouter) {\n existingInfo = undefined\n }\n\n if (routeProps.shallow && existingInfo && this.route === route) {\n return existingInfo\n }\n\n const handleCancelled = getCancelledHandler({ route, router: this })\n\n if (hasMiddleware) {\n existingInfo = undefined\n }\n\n let cachedRouteInfo =\n existingInfo &&\n !('initial' in existingInfo) &&\n process.env.NODE_ENV !== 'development'\n ? existingInfo\n : undefined\n\n const isBackground = isQueryUpdating\n const fetchNextDataParams: FetchNextDataParams = {\n dataHref: this.pageLoader.getDataHref({\n href: formatWithValidation({ pathname, query }),\n skipInterpolation: true,\n asPath: isNotFound ? '/404' : resolvedAs,\n locale,\n }),\n hasMiddleware: true,\n isServerRender: this.isSsr,\n parseJSON: true,\n inflightCache: isBackground ? this.sbc : this.sdc,\n persistCache: !isPreview,\n isPrefetch: false,\n unstable_skipClientCache,\n isBackground,\n }\n\n let data:\n | WithMiddlewareEffectsOutput\n | (Pick<WithMiddlewareEffectsOutput, 'json'> &\n Omit<Partial<WithMiddlewareEffectsOutput>, 'json'>)\n | null =\n isQueryUpdating && !isMiddlewareRewrite\n ? null\n : await withMiddlewareEffects({\n fetchData: () => fetchNextData(fetchNextDataParams),\n asPath: isNotFound ? '/404' : resolvedAs,\n locale: locale,\n router: this,\n }).catch((err) => {\n // we don't hard error during query updating\n // as it's un-necessary and doesn't need to be fatal\n // unless it is a fallback route and the props can't\n // be loaded\n if (isQueryUpdating) {\n return null\n }\n throw err\n })\n\n // when rendering error routes we don't apply middleware\n // effects\n if (data && (pathname === '/_error' || pathname === '/404')) {\n data.effect = undefined\n }\n\n if (isQueryUpdating) {\n if (!data) {\n data = { json: self.__NEXT_DATA__.props }\n } else {\n data.json = self.__NEXT_DATA__.props\n }\n }\n\n handleCancelled()\n\n if (\n data?.effect?.type === 'redirect-internal' ||\n data?.effect?.type === 'redirect-external'\n ) {\n return data.effect\n }\n\n if (data?.effect?.type === 'rewrite') {\n const resolvedRoute = removeTrailingSlash(data.effect.resolvedHref)\n const pages = await this.pageLoader.getPageList()\n\n // during query updating the page must match although during\n // client-transition a redirect that doesn't match a page\n // can be returned and this should trigger a hard navigation\n // which is valid for incremental migration\n if (!isQueryUpdating || pages.includes(resolvedRoute)) {\n route = resolvedRoute\n pathname = data.effect.resolvedHref\n query = { ...query, ...data.effect.parsedAs.query }\n resolvedAs = removeBasePath(\n normalizeLocalePath(data.effect.parsedAs.pathname, this.locales)\n .pathname\n )\n\n // Check again the cache with the new destination.\n existingInfo = this.components[route]\n if (existingInfo && (existingInfo as any).__appRouter) {\n existingInfo = undefined\n }\n if (\n routeProps.shallow &&\n existingInfo &&\n this.route === route &&\n !hasMiddleware\n ) {\n // If we have a match with the current route due to rewrite,\n // we can copy the existing information to the rewritten one.\n // Then, we return the information along with the matched route.\n return { ...existingInfo, route }\n }\n }\n }\n\n if (isAPIRoute(route)) {\n handleHardNavigation({ url: as, router: this })\n return new Promise<never>(() => {})\n }\n\n const routeInfo =\n cachedRouteInfo ||\n (await this.fetchComponent(route).then<CompletePrivateRouteInfo>(\n (res) => ({\n Component: res.page,\n styleSheets: res.styleSheets,\n __N_SSG: res.mod.__N_SSG,\n __N_SSP: res.mod.__N_SSP,\n })\n ))\n\n if (process.env.NODE_ENV !== 'production') {\n const { isValidElementType } =\n require('next/dist/compiled/react-is') as typeof import('next/dist/compiled/react-is')\n if (!isValidElementType(routeInfo.Component)) {\n throw new Error(\n `The default export is not a React Component in page: \"${pathname}\"`\n )\n }\n }\n const wasBailedPrefetch = data?.response?.headers.get('x-middleware-skip')\n\n const shouldFetchData = routeInfo.__N_SSG || routeInfo.__N_SSP\n\n // For non-SSG prefetches that bailed before sending data\n // we clear the cache to fetch full response\n if (wasBailedPrefetch && data?.dataHref) {\n delete this.sdc[data.dataHref]\n }\n\n const { props, cacheKey } = await this._getData(async () => {\n if (shouldFetchData) {\n if (data?.json && !wasBailedPrefetch) {\n return { cacheKey: data.cacheKey, props: data.json }\n }\n\n const dataHref = data?.dataHref\n ? data.dataHref\n : this.pageLoader.getDataHref({\n href: formatWithValidation({ pathname, query }),\n asPath: resolvedAs,\n locale,\n })\n\n const fetched = await fetchNextData({\n dataHref,\n isServerRender: this.isSsr,\n parseJSON: true,\n inflightCache: wasBailedPrefetch ? {} : this.sdc,\n persistCache: !isPreview,\n isPrefetch: false,\n unstable_skipClientCache,\n })\n\n return {\n cacheKey: fetched.cacheKey,\n props: fetched.json || {},\n }\n }\n\n return {\n headers: {},\n props: await this.getInitialProps(\n routeInfo.Component,\n // we provide AppTree later so this needs to be `any`\n {\n pathname,\n query,\n asPath: as,\n locale,\n locales: this.locales,\n defaultLocale: this.defaultLocale,\n } as any\n ),\n }\n })\n\n // Only bust the data cache for SSP routes although\n // middleware can skip cache per request with\n // x-middleware-cache: no-cache as well\n if (routeInfo.__N_SSP && fetchNextDataParams.dataHref && cacheKey) {\n delete this.sdc[cacheKey]\n }\n\n // we kick off a HEAD request in the background\n // when a non-prefetch request is made to signal revalidation\n if (\n !this.isPreview &&\n routeInfo.__N_SSG &&\n process.env.NODE_ENV !== 'development' &&\n !isQueryUpdating\n ) {\n fetchNextData(\n Object.assign({}, fetchNextDataParams, {\n isBackground: true,\n persistCache: false,\n inflightCache: this.sbc,\n })\n ).catch(() => {})\n }\n\n props.pageProps = Object.assign({}, props.pageProps)\n routeInfo.props = props\n routeInfo.route = route\n routeInfo.query = query\n routeInfo.resolvedAs = resolvedAs\n this.components[route] = routeInfo\n\n return routeInfo\n } catch (err) {\n return this.handleRouteInfoError(\n getProperError(err),\n pathname,\n query,\n as,\n routeProps\n )\n }\n }\n\n private set(\n state: typeof this.state,\n data: PrivateRouteInfo,\n resetScroll: { x: number; y: number } | null\n ): Promise<void> {\n this.state = state\n\n return this.sub(\n data,\n this.components['/_app'].Component as AppComponent,\n resetScroll\n )\n }\n\n /**\n * Callback to execute before replacing router state\n * @param cb callback to be executed\n */\n beforePopState(cb: BeforePopStateCallback) {\n this._bps = cb\n }\n\n onlyAHashChange(as: string): boolean {\n if (!this.asPath) return false\n const [oldUrlNoHash, oldHash] = this.asPath.split('#', 2)\n const [newUrlNoHash, newHash] = as.split('#', 2)\n\n // Makes sure we scroll to the provided hash if the url/hash are the same\n if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) {\n return true\n }\n\n // If the urls are change, there's more than a hash change\n if (oldUrlNoHash !== newUrlNoHash) {\n return false\n }\n\n // If the hash has changed, then it's a hash only change.\n // This check is necessary to handle both the enter and\n // leave hash === '' cases. The identity case falls through\n // and is treated as a next reload.\n return oldHash !== newHash\n }\n\n scrollToHash(as: string): void {\n const [, hash = ''] = as.split('#', 2)\n\n disableSmoothScrollDuringRouteTransition(\n () => {\n // Scroll to top if the hash is just `#` with no value or `#top`\n // To mirror browsers\n if (hash === '' || hash === 'top') {\n window.scrollTo(0, 0)\n return\n }\n\n // Decode hash to make non-latin anchor works.\n const rawHash = decodeURIComponent(hash)\n // First we check if the element by id is found\n const idEl = document.getElementById(rawHash)\n if (idEl) {\n idEl.scrollIntoView()\n return\n }\n // If there's no element with the id, we check the `name` property\n // To mirror browsers\n const nameEl = document.getElementsByName(rawHash)[0]\n if (nameEl) {\n nameEl.scrollIntoView()\n }\n },\n {\n onlyHashChange: this.onlyAHashChange(as),\n }\n )\n }\n\n urlIsNew(asPath: string): boolean {\n return this.asPath !== asPath\n }\n\n /**\n * Prefetch page code, you may wait for the data during page rendering.\n * This feature only works in production!\n * @param url the href of prefetched page\n * @param asPath the as path of the prefetched page\n */\n async prefetch(\n url: string,\n asPath: string = url,\n options: PrefetchOptions = {}\n ): Promise<void> {\n // Prefetch is not supported in development mode because it would trigger on-demand-entries\n if (process.env.NODE_ENV !== 'production') {\n return\n }\n\n if (typeof window !== 'undefined' && isBot(window.navigator.userAgent)) {\n // No prefetches for bots that render the link since they are typically navigating\n // links via the equivalent of a hard navigation and hence never utilize these\n // prefetches.\n return\n }\n let parsed = parseRelativeUrl(url)\n\n let { pathname, query } = parsed\n const originalPathname = pathname\n\n if (process.env.__NEXT_I18N_SUPPORT) {\n if (options.locale === false) {\n pathname = normalizeLocalePath!(pathname, this.locales).pathname\n parsed.pathname = pathname\n url = formatWithValidation(parsed)\n\n let parsedAs = parseRelativeUrl(asPath)\n const localePathResult = normalizeLocalePath!(\n parsedAs.pathname,\n this.locales\n )\n parsedAs.pathname = localePathResult.pathname\n options.locale = localePathResult.detectedLocale || this.defaultLocale\n asPath = formatWithValidation(parsedAs)\n }\n }\n\n const pages = await this.pageLoader.getPageList()\n let resolvedAs = asPath\n\n const locale =\n typeof options.locale !== 'undefined'\n ? options.locale || undefined\n : this.locale\n\n const isMiddlewareMatch = await matchesMiddleware({\n asPath: asPath,\n locale: locale,\n router: this,\n })\n\n if (process.env.__NEXT_HAS_REWRITES && asPath.startsWith('/')) {\n let rewrites: any\n ;({ __rewrites: rewrites } = await getClientBuildManifest())\n\n const rewritesResult = resolveRewrites(\n addBasePath(addLocale(asPath, this.locale), true),\n pages,\n rewrites,\n parsed.query,\n (p: string) => resolveDynamicRoute(p, pages),\n this.locales\n )\n\n if (rewritesResult.externalDest) {\n return\n }\n\n if (!isMiddlewareMatch) {\n resolvedAs = removeLocale(\n removeBasePath(rewritesResult.asPath),\n this.locale\n )\n }\n\n if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {\n // if this directly matches a page we need to update the href to\n // allow the correct page chunk to be loaded\n pathname = rewritesResult.resolvedHref\n parsed.pathname = pathname\n\n if (!isMiddlewareMatch) {\n url = formatWithValidation(parsed)\n }\n }\n }\n parsed.pathname = resolveDynamicRoute(parsed.pathname, pages)\n\n if (isDynamicRoute(parsed.pathname)) {\n pathname = parsed.pathname\n parsed.pathname = pathname\n Object.assign(\n query,\n getRouteMatcher(getRouteRegex(parsed.pathname))(\n parsePath(asPath).pathname\n ) || {}\n )\n\n if (!isMiddlewareMatch) {\n url = formatWithValidation(parsed)\n }\n }\n\n const data =\n process.env.__NEXT_MIDDLEWARE_PREFETCH === 'strict'\n ? null\n : await withMiddlewareEffects({\n fetchData: () =>\n fetchNextData({\n dataHref: this.pageLoader.getDataHref({\n href: formatWithValidation({\n pathname: originalPathname,\n query,\n }),\n skipInterpolation: true,\n asPath: resolvedAs,\n locale,\n }),\n hasMiddleware: true,\n isServerRender: false,\n parseJSON: true,\n inflightCache: this.sdc,\n persistCache: !this.isPreview,\n isPrefetch: true,\n }),\n asPath: asPath,\n locale: locale,\n router: this,\n })\n\n /**\n * If there was a rewrite we apply the effects of the rewrite on the\n * current parameters for the prefetch.\n */\n if (data?.effect.type === 'rewrite') {\n parsed.pathname = data.effect.resolvedHref\n pathname = data.effect.resolvedHref\n query = { ...query, ...data.effect.parsedAs.query }\n resolvedAs = data.effect.parsedAs.pathname\n url = formatWithValidation(parsed)\n }\n\n /**\n * If there is a redirect to an external destination then we don't have\n * to prefetch content as it will be unused.\n */\n if (data?.effect.type === 'redirect-external') {\n return\n }\n\n const route = removeTrailingSlash(pathname)\n\n if (await this._bfl(asPath, resolvedAs, options.locale, true)) {\n const appRouterMarkerKey = getAppRouterMarkerKey(\n this,\n asPath,\n options.locale\n )\n // A loaded pages route in the cache is ground truth: the page behind\n // this key exists and was rendered. This is the case when the current\n // page was reached through a rewrite and the canonical URL is\n // prefetched, or when a prefetch is still in flight while a navigation\n // stores the same route. Replacing that entry with the marker would\n // break hash-only changes and shallow navigations, which render the\n // cached entry of the current route directly. Non-shallow navigations\n // consult the client router filter themselves, so they do not depend\n // on the marker to hard navigate.\n if (\n appRouterMarkerKey !== null &&\n this.components[appRouterMarkerKey] === undefined\n ) {\n this.components[appRouterMarkerKey] = { __appRouter: true } as any\n }\n }\n\n await Promise.all([\n this.pageLoader._isSsg(route).then((isSsg) => {\n return isSsg\n ? fetchNextData({\n dataHref: data?.json\n ? data?.dataHref\n : this.pageLoader.getDataHref({\n href: url,\n asPath: resolvedAs,\n locale: locale,\n }),\n isServerRender: false,\n parseJSON: true,\n inflightCache: this.sdc,\n persistCache: !this.isPreview,\n isPrefetch: true,\n unstable_skipClientCache:\n options.unstable_skipClientCache ||\n (options.priority &&\n !!process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE),\n })\n .then(() => false)\n .catch(() => false)\n : false\n }),\n this.pageLoader[options.priority ? 'loadPage' : 'prefetch'](route),\n ])\n }\n\n async fetchComponent(route: string) {\n const handleCancelled = getCancelledHandler({ route, router: this })\n\n try {\n const componentResult = await this.pageLoader.loadPage(route)\n handleCancelled()\n\n return componentResult\n } catch (err) {\n handleCancelled()\n throw err\n }\n }\n\n _getData<T>(fn: () => Promise<T>): Promise<T> {\n let cancelled = false\n const cancel = () => {\n cancelled = true\n }\n this.clc = cancel\n return fn().then((data) => {\n if (cancel === this.clc) {\n this.clc = null\n }\n\n if (cancelled) {\n const err: any = new Error('Loading initial props cancelled')\n err.cancelled = true\n throw err\n }\n\n return data\n })\n }\n\n getInitialProps(\n Component: ComponentType,\n ctx: NextPageContext\n ): Promise<Record<string, any>> {\n const { Component: App } = this.components['/_app']\n const AppTree = this._wrapApp(App as AppComponent)\n ctx.AppTree = AppTree\n return loadGetInitialProps<AppContextType<Router>>(App, {\n AppTree,\n Component,\n router: this,\n ctx,\n })\n }\n\n get route(): string {\n return this.state.route\n }\n\n get pathname(): string {\n return this.state.pathname\n }\n\n get query(): ParsedUrlQuery {\n return this.state.query\n }\n\n get asPath(): string {\n return this.state.asPath\n }\n\n get locale(): string | undefined {\n return this.state.locale\n }\n\n get isFallback(): boolean {\n return this.state.isFallback\n }\n\n get isPreview(): boolean {\n return this.state.isPreview\n }\n}\n"],"names":["createKey","Router","matchesMiddleware","resolveRewrites","process","env","__NEXT_HAS_REWRITES","require","default","buildCancellationError","Object","assign","Error","cancelled","options","matchers","Promise","resolve","router","pageLoader","getMiddleware","pathname","asPathname","parsePath","asPath","cleanedAs","hasBasePath","removeBasePath","asWithBasePathAndLocale","addBasePath","addLocale","locale","some","m","RegExp","regexp","test","stripOrigin","url","origin","getLocationOrigin","startsWith","substring","length","prepareUrlAs","as","resolvedHref","resolvedAs","resolveHref","hrefWasAbsolute","asWasAbsolute","preparedUrl","preparedAs","getAppRouterMarkerKey","isLocalURL","parseRelativeUrl","effectiveLocale","__NEXT_I18N_SUPPORT","localePathResult","normalizeLocalePath","locales","detectedLocale","removeTrailingSlash","resolveDynamicRoute","pages","cleanPathname","denormalizePagePath","includes","page","isDynamicRoute","getRouteRegex","re","getMiddlewareData","source","response","nextConfig","basePath","i18n","trailingSlash","Boolean","__NEXT_TRAILING_SLASH","rewriteHeader","headers","get","rewriteTarget","matchedPath","MATCHED_PATH_HEADER","__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE","parsedRewriteTarget","pathnameInfo","getNextPathnameInfo","parseData","fsPathname","all","getPageList","getClientBuildManifest","then","__rewrites","rewrites","parsedSource","result","query","path","matchedPage","parsedAs","resolvedPathname","matches","getRouteMatcher","type","src","formatNextPathnameInfo","defaultLocale","buildId","destination","hash","redirectTarget","newAs","newUrl","withMiddlewareEffects","fetchData","data","effect","dataHref","json","text","cacheKey","manualScrollRestoration","__NEXT_SCROLL_RESTORATION","window","history","v","sessionStorage","setItem","removeItem","n","SSG_DATA_NOT_FOUND","Symbol","fetchRetry","attempts","fetch","credentials","method","ok","status","tryToParseAsJSON","JSON","parse","error","fetchNextData","inflightCache","isPrefetch","hasMiddleware","isServerRender","parseJSON","persistCache","isBackground","unstable_skipClientCache","href","URL","location","deploymentId","getDeploymentId","getData","params","purpose","notFound","markAssetError","dplResponseHeader","NEXT_NAV_DEPLOYMENT_ID_HEADER","NODE_ENV","catch","err","message","undefined","Math","random","toString","slice","handleHardNavigation","getCancelledHandler","route","cancel","clc","handleCancelled","events","mitt","constructor","initialProps","App","wrapApp","Component","subscription","isFallback","domainLocales","isPreview","sdc","sbc","isFirstPopStateEvent","_key","onPopState","e","state","changeState","formatWithValidation","getURL","__NA","reload","__N","forcedScroll","key","stringify","x","self","pageXOffset","y","pageYOffset","getItem","isSsr","_bps","change","shallow","_shallow","_h","components","initial","props","__N_SSG","__N_SSP","styleSheets","autoExportDynamic","__NEXT_DATA__","autoExport","__NEXT_ROUTER_BASEPATH","sub","_wrapApp","isLocaleDomain","isReady","gssp","gip","isExperimentalCompile","appGip","gsp","search","detectDomainLocale","hostname","_initialMatchesMiddlewarePromise","_shouldResolveHref","addEventListener","scrollRestoration","back","forward","push","isJavaScriptURLString","replace","_bfl","skipNavigate","__NEXT_CLIENT_ROUTER_FILTER_ENABLED","_bfl_s","_bfl_d","BloomFilter","staticFilterData","dynamicFilterData","__routerFilterStatic","__routerFilterDynamic","console","routerFilterSValue","__NEXT_CLIENT_ROUTER_S_FILTER","routerFilterDValue","__NEXT_CLIENT_ROUTER_D_FILTER","numHashes","numItems","errorRate","import","matchesBflStatic","matchesBflDynamic","pathsToCheck","curAs","allowMatchCurrent","asNoSlash","asNoSlashLocale","contains","normalizedAS","curAsParts","split","i","currentPart","join","isQueryUpdating","shouldResolveHref","nextState","readyStateChange","prevLocale","didNavigate","detectedDomain","domain","asNoBasePath","http","ST","performance","mark","scroll","routeProps","_inFlightRoute","emit","removeLocale","localeChange","onlyAHashChange","scrollToHash","set","isError","parsed","urlIsNew","parsedAsPathname","appRouterMarkerKey","__appRouter","isMiddlewareRewrite","isMiddlewareMatch","rewritesResult","p","externalDest","concretePathname","isShadowedByAppRoute","hasDynamicFilterCandidate","candidate","routeMatch","routeRegex","shouldInterpolate","interpolatedAs","interpolateAs","missingParams","keys","groups","filter","param","optional","warn","omit","isErrorRoute","routeInfo","getRouteInfo","cleanedParsedPathname","forEach","prefixedAs","rewriteAs","localeResult","curRouteMatch","component","unstable_scriptLoader","scripts","concat","script","handleClientScriptLoad","pageProps","__N_REDIRECT","__N_REDIRECT_BASE_PATH","parsedHref","__N_PREVIEW","notFoundRoute","fetchComponent","_","isNotFound","statusCode","isValidShallowRoute","shouldScroll","resetScroll","upcomingScrollState","upcomingRouterState","canSkipUpdating","compareRouterStates","document","documentElement","lang","hashRegex","handleRouteInfoError","loadErrorFail","isAssetError","getInitialProps","gipErr","routeInfoErr","requestedRoute","existingInfo","cachedRouteInfo","fetchNextDataParams","getDataHref","skipInterpolation","resolvedRoute","isAPIRoute","res","mod","isValidElementType","wasBailedPrefetch","shouldFetchData","_getData","fetched","getProperError","beforePopState","cb","oldUrlNoHash","oldHash","newUrlNoHash","newHash","disableSmoothScrollDuringRouteTransition","scrollTo","rawHash","decodeURIComponent","idEl","getElementById","scrollIntoView","nameEl","getElementsByName","onlyHashChange","prefetch","isBot","navigator","userAgent","originalPathname","__NEXT_MIDDLEWARE_PREFETCH","_isSsg","isSsg","priority","__NEXT_OPTIMISTIC_CLIENT_CACHE","componentResult","loadPage","fn","ctx","AppTree","loadGetInitialProps"],"mappings":";;;;;;;;;;;;;;;;IA0rBgBA,SAAS;eAATA;;IAiDhB,OAk+DC;eAl+DoBC;;IAroBCC,iBAAiB;eAAjBA;;;;;qCA7Fc;6BAK7B;wBACgC;mEACC;qCACJ;qCACA;+DACnB;uBACkD;2BACpC;kCACE;8BACD;4BACF;sCACY;2BACL;oCACF;2BACT;2BACA;8BACG;gCACE;6BACH;6BACA;6BACA;4BACD;qCACS;wCACG;+BACH;4BACT;uBACL;sBACD;+BACS;qCAC2B;2BAKlD;8BACyB;+BACM;AAEtC,IAAIC;AACJ,IAAIC,QAAQC,GAAG,CAACC,mBAAmB,EAAE;IACnCH,kBAAkB,AAChBI,QAAQ,4BACRC,OAAO;AACX;AAgCA,SAASC;IACP,OAAOC,OAAOC,MAAM,CAAC,IAAIC,MAAM,oBAAoB;QACjDC,WAAW;IACb;AACF;AASO,eAAeX,kBACpBY,OAAkC;IAElC,MAAMC,WAAW,MAAMC,QAAQC,OAAO,CACpCH,QAAQI,MAAM,CAACC,UAAU,CAACC,aAAa;IAEzC,IAAI,CAACL,UAAU,OAAO;IAEtB,MAAM,EAAEM,UAAUC,UAAU,EAAE,GAAGC,IAAAA,oBAAS,EAACT,QAAQU,MAAM;IACzD,6FAA6F;IAC7F,MAAMC,YAAYC,IAAAA,wBAAW,EAACJ,cAC1BK,IAAAA,8BAAc,EAACL,cACfA;IACJ,MAAMM,0BAA0BC,IAAAA,wBAAW,EACzCC,IAAAA,oBAAS,EAACL,WAAWX,QAAQiB,MAAM;IAGrC,2EAA2E;IAC3E,uEAAuE;IACvE,OAAOhB,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EA,IAAI/J,WAAmB;QACrB,OAAO,IAAI,CAACoL,KAAK,CAACpL,QAAQ;IAC5B;IAEA,IAAIgF,QAAwB;QAC1B,OAAO,IAAI,CAACoG,KAAK,CAACpG,KAAK;IACzB;IAEA,IAAI7E,SAAiB;QACnB,OAAO,IAAI,CAACiL,KAAK,CAACjL,MAAM;IAC1B;IAEA,IAAIO,SAA6B;QAC/B,OAAO,IAAI,CAAC0K,KAAK,CAAC1K,MAAM;IAC1B;IAEA,IAAIiK,aAAsB;QACxB,OAAO,IAAI,CAACS,KAAK,CAACT,UAAU;IAC9B;IAEA,IAAIE,YAAqB;QACvB,OAAO,IAAI,CAACO,KAAK,CAACP,SAAS;IAC7B;AACF","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/routes/app.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/routes/app.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3be5fdedae5e7f0db4ba393d7811b06a5dc6df85 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/routes/app.d.ts @@ -0,0 +1,81 @@ +import { type SegmentParam } from '../utils/get-segment-param'; +import { type InterceptionMarker } from '../utils/interception-routes'; +export type RouteGroupAppRouteSegment = { + type: 'route-group'; + name: string; + /** + * If present, this segment has an interception marker prefixing it. + */ + interceptionMarker?: InterceptionMarker; +}; +export type ParallelRouteAppRouteSegment = { + type: 'parallel-route'; + name: string; + /** + * If present, this segment has an interception marker prefixing it. + */ + interceptionMarker?: InterceptionMarker; +}; +export type StaticAppRouteSegment = { + type: 'static'; + name: string; + /** + * If present, this segment has an interception marker prefixing it. + */ + interceptionMarker?: InterceptionMarker; +}; +export type DynamicAppRouteSegment = { + type: 'dynamic'; + name: string; + param: SegmentParam; + /** + * If present, this segment has an interception marker prefixing it. + */ + interceptionMarker?: InterceptionMarker; +}; +/** + * Represents a single segment in a route path. + * Can be either static (e.g., "blog") or dynamic (e.g., "[slug]"). + */ +export type AppRouteSegment = StaticAppRouteSegment | DynamicAppRouteSegment | RouteGroupAppRouteSegment | ParallelRouteAppRouteSegment; +export type NormalizedAppRouteSegment = StaticAppRouteSegment | DynamicAppRouteSegment; +export declare function parseAppRouteSegment(segment: string): AppRouteSegment | null; +export type AppRoute = { + normalized: boolean; + pathname: string; + segments: AppRouteSegment[]; + dynamicSegments: DynamicAppRouteSegment[]; + interceptionMarker: InterceptionMarker | undefined; + interceptingRoute: AppRoute | undefined; + interceptedRoute: AppRoute | undefined; +}; +export type NormalizedAppRoute = Omit<AppRoute, 'normalized' | 'segments'> & { + normalized: true; + segments: NormalizedAppRouteSegment[]; +}; +export declare function isNormalizedAppRoute(route: InterceptionAppRoute): route is NormalizedInterceptionAppRoute; +export type InterceptionAppRoute = Omit<AppRoute, 'interceptionMarker' | 'interceptingRoute' | 'interceptedRoute'> & { + interceptionMarker: InterceptionMarker; + interceptingRoute: AppRoute; + interceptedRoute: AppRoute; +}; +export type NormalizedInterceptionAppRoute = Omit<InterceptionAppRoute, 'normalized' | 'segments' | 'interceptionMarker' | 'interceptingRoute' | 'interceptedRoute'> & { + normalized: true; + segments: NormalizedAppRouteSegment[]; + interceptionMarker: InterceptionMarker; + interceptingRoute: NormalizedAppRoute; + interceptedRoute: NormalizedAppRoute; +}; +export declare function isInterceptionAppRoute(route: NormalizedAppRoute): route is NormalizedInterceptionAppRoute; +/** + * Parse an app route that has been fully normalized (no @slot or () + * group segments). Throws if either is present. + */ +export declare function parseNormalizedAppRoute(pathname: string): NormalizedAppRoute; +/** + * Parse an app route that may contain @slot segments but not () + * group segments. Slot segments are preserved as parallel-route + * type segments so callers can distinguish routes in different + * parallel slots. + */ +export declare function parseAppRouteWithSlots(pathname: string): AppRoute; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/routes/app.js b/e-commerce/node_modules/next/dist/shared/lib/router/routes/app.js new file mode 100644 index 0000000000000000000000000000000000000000..f08e546a058e90c69424f569bb5211c16e988cb9 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/routes/app.js @@ -0,0 +1,146 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +0 && (module.exports = { + isInterceptionAppRoute: null, + isNormalizedAppRoute: null, + parseAppRouteSegment: null, + parseAppRouteWithSlots: null, + parseNormalizedAppRoute: null +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + isInterceptionAppRoute: function() { + return isInterceptionAppRoute; + }, + isNormalizedAppRoute: function() { + return isNormalizedAppRoute; + }, + parseAppRouteSegment: function() { + return parseAppRouteSegment; + }, + parseAppRouteWithSlots: function() { + return parseAppRouteWithSlots; + }, + parseNormalizedAppRoute: function() { + return parseNormalizedAppRoute; + } +}); +const _invarianterror = require("../../invariant-error"); +const _getsegmentparam = require("../utils/get-segment-param"); +const _interceptionroutes = require("../utils/interception-routes"); +function normalizeEncodedDynamicPlaceholder(segment) { + if (!/%5b|%5d/i.test(segment)) { + return segment; + } + try { + const decodedSegment = decodeURIComponent(segment); + return (0, _getsegmentparam.getSegmentParam)(decodedSegment) ? decodedSegment : segment; + } catch { + return segment; + } +} +function parseAppRouteSegment(segment) { + if (segment === '') { + return null; + } + // Check if the segment starts with an interception marker + const interceptionMarker = _interceptionroutes.INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m)); + const param = (0, _getsegmentparam.getSegmentParam)(segment); + if (param) { + return { + type: 'dynamic', + name: segment, + param, + interceptionMarker + }; + } else if (segment.startsWith('(') && segment.endsWith(')')) { + return { + type: 'route-group', + name: segment, + interceptionMarker + }; + } else if (segment.startsWith('@')) { + return { + type: 'parallel-route', + name: segment, + interceptionMarker + }; + } else { + return { + type: 'static', + name: segment, + interceptionMarker + }; + } +} +function isNormalizedAppRoute(route) { + return route.normalized; +} +function isInterceptionAppRoute(route) { + return route.interceptionMarker !== undefined && route.interceptingRoute !== undefined && route.interceptedRoute !== undefined; +} +// Bitmask for which non-URL segment types to allow during parsing. +// By default, route groups and parallel routes are rejected because +// they should have been stripped by normalizeAppPath. These flags +// let callers opt in to allowing specific types. +const OnlyRoutableSegments = /* */ 0; +const AllowParallelSegments = /* */ 1; +const AllowGroupSegments = /* */ 2; +function parseAppRouteImpl(pathname, allowedTypes) { + const pathnameSegments = pathname.split('/').filter(Boolean); + // Build segments array with static and dynamic segments + const segments = []; + // Parse if this is an interception route. + let interceptionMarker; + let interceptingRoute; + let interceptedRoute; + for (const segment of pathnameSegments){ + const normalizedSegment = normalizeEncodedDynamicPlaceholder(segment); + // Parse the segment into an AppSegment. + const appSegment = parseAppRouteSegment(normalizedSegment); + if (!appSegment) { + continue; + } + if (appSegment.type === 'route-group' && !(allowedTypes & AllowGroupSegments)) { + throw new _invarianterror.InvariantError(`${pathname} is being parsed as a normalized route, but it has a route group segment.`); + } + if (appSegment.type === 'parallel-route' && !(allowedTypes & AllowParallelSegments)) { + throw new _invarianterror.InvariantError(`${pathname} is being parsed as a normalized route, but it has a parallel route segment.`); + } + segments.push(appSegment); + if (appSegment.interceptionMarker) { + const parts = pathname.split(appSegment.interceptionMarker); + if (parts.length !== 2) { + throw new Error(`Invalid interception route: ${pathname}`); + } + interceptingRoute = parseAppRouteImpl(parts[0], allowedTypes); + interceptedRoute = parseAppRouteImpl(parts[1], allowedTypes); + interceptionMarker = appSegment.interceptionMarker; + } + } + const dynamicSegments = segments.filter((segment)=>segment.type === 'dynamic'); + return { + normalized: allowedTypes === OnlyRoutableSegments, + pathname, + segments, + dynamicSegments, + interceptionMarker, + interceptingRoute, + interceptedRoute + }; +} +function parseNormalizedAppRoute(pathname) { + return parseAppRouteImpl(pathname, OnlyRoutableSegments); +} +function parseAppRouteWithSlots(pathname) { + return parseAppRouteImpl(pathname, AllowParallelSegments); +} + +//# sourceMappingURL=app.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/routes/app.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/routes/app.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8e1f987baa91c734832a3febb510b9002cf58c63 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/routes/app.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/routes/app.ts"],"sourcesContent":["import { InvariantError } from '../../invariant-error'\nimport { getSegmentParam, type SegmentParam } from '../utils/get-segment-param'\nimport {\n INTERCEPTION_ROUTE_MARKERS,\n type InterceptionMarker,\n} from '../utils/interception-routes'\n\nexport type RouteGroupAppRouteSegment = {\n type: 'route-group'\n name: string\n\n /**\n * If present, this segment has an interception marker prefixing it.\n */\n interceptionMarker?: InterceptionMarker\n}\n\nexport type ParallelRouteAppRouteSegment = {\n type: 'parallel-route'\n name: string\n\n /**\n * If present, this segment has an interception marker prefixing it.\n */\n interceptionMarker?: InterceptionMarker\n}\n\nexport type StaticAppRouteSegment = {\n type: 'static'\n name: string\n\n /**\n * If present, this segment has an interception marker prefixing it.\n */\n interceptionMarker?: InterceptionMarker\n}\n\nexport type DynamicAppRouteSegment = {\n type: 'dynamic'\n name: string\n param: SegmentParam\n\n /**\n * If present, this segment has an interception marker prefixing it.\n */\n interceptionMarker?: InterceptionMarker\n}\n\n/**\n * Represents a single segment in a route path.\n * Can be either static (e.g., \"blog\") or dynamic (e.g., \"[slug]\").\n */\nexport type AppRouteSegment =\n | StaticAppRouteSegment\n | DynamicAppRouteSegment\n | RouteGroupAppRouteSegment\n | ParallelRouteAppRouteSegment\n\nexport type NormalizedAppRouteSegment =\n | StaticAppRouteSegment\n | DynamicAppRouteSegment\n\nfunction normalizeEncodedDynamicPlaceholder(segment: string): string {\n if (!/%5b|%5d/i.test(segment)) {\n return segment\n }\n\n try {\n const decodedSegment = decodeURIComponent(segment)\n return getSegmentParam(decodedSegment) ? decodedSegment : segment\n } catch {\n return segment\n }\n}\n\nexport function parseAppRouteSegment(segment: string): AppRouteSegment | null {\n if (segment === '') {\n return null\n }\n\n // Check if the segment starts with an interception marker\n const interceptionMarker = INTERCEPTION_ROUTE_MARKERS.find((m) =>\n segment.startsWith(m)\n )\n\n const param = getSegmentParam(segment)\n if (param) {\n return {\n type: 'dynamic',\n name: segment,\n param,\n interceptionMarker,\n }\n } else if (segment.startsWith('(') && segment.endsWith(')')) {\n return {\n type: 'route-group',\n name: segment,\n interceptionMarker,\n }\n } else if (segment.startsWith('@')) {\n return {\n type: 'parallel-route',\n name: segment,\n interceptionMarker,\n }\n } else {\n return {\n type: 'static',\n name: segment,\n interceptionMarker,\n }\n }\n}\n\nexport type AppRoute = {\n normalized: boolean\n pathname: string\n segments: AppRouteSegment[]\n dynamicSegments: DynamicAppRouteSegment[]\n interceptionMarker: InterceptionMarker | undefined\n interceptingRoute: AppRoute | undefined\n interceptedRoute: AppRoute | undefined\n}\n\nexport type NormalizedAppRoute = Omit<AppRoute, 'normalized' | 'segments'> & {\n normalized: true\n segments: NormalizedAppRouteSegment[]\n}\n\nexport function isNormalizedAppRoute(\n route: InterceptionAppRoute\n): route is NormalizedInterceptionAppRoute\nexport function isNormalizedAppRoute(\n route: AppRoute | InterceptionAppRoute\n): route is NormalizedAppRoute {\n return route.normalized\n}\n\nexport type InterceptionAppRoute = Omit<\n AppRoute,\n 'interceptionMarker' | 'interceptingRoute' | 'interceptedRoute'\n> & {\n interceptionMarker: InterceptionMarker\n interceptingRoute: AppRoute\n interceptedRoute: AppRoute\n}\n\nexport type NormalizedInterceptionAppRoute = Omit<\n InterceptionAppRoute,\n | 'normalized'\n | 'segments'\n | 'interceptionMarker'\n | 'interceptingRoute'\n | 'interceptedRoute'\n> & {\n normalized: true\n segments: NormalizedAppRouteSegment[]\n interceptionMarker: InterceptionMarker\n interceptingRoute: NormalizedAppRoute\n interceptedRoute: NormalizedAppRoute\n}\n\nexport function isInterceptionAppRoute(\n route: NormalizedAppRoute\n): route is NormalizedInterceptionAppRoute\nexport function isInterceptionAppRoute(\n route: AppRoute\n): route is InterceptionAppRoute {\n return (\n route.interceptionMarker !== undefined &&\n route.interceptingRoute !== undefined &&\n route.interceptedRoute !== undefined\n )\n}\n\n// Bitmask for which non-URL segment types to allow during parsing.\n// By default, route groups and parallel routes are rejected because\n// they should have been stripped by normalizeAppPath. These flags\n// let callers opt in to allowing specific types.\nconst OnlyRoutableSegments = /* */ 0b00\nconst AllowParallelSegments = /* */ 0b01\nconst AllowGroupSegments = /* */ 0b10\n\nfunction parseAppRouteImpl(\n pathname: string,\n allowedTypes: number\n): AppRoute | NormalizedAppRoute {\n const pathnameSegments = pathname.split('/').filter(Boolean)\n\n // Build segments array with static and dynamic segments\n const segments: AppRouteSegment[] = []\n\n // Parse if this is an interception route.\n let interceptionMarker: InterceptionMarker | undefined\n let interceptingRoute: AppRoute | NormalizedAppRoute | undefined\n let interceptedRoute: AppRoute | NormalizedAppRoute | undefined\n\n for (const segment of pathnameSegments) {\n const normalizedSegment = normalizeEncodedDynamicPlaceholder(segment)\n\n // Parse the segment into an AppSegment.\n const appSegment = parseAppRouteSegment(normalizedSegment)\n if (!appSegment) {\n continue\n }\n\n if (\n appSegment.type === 'route-group' &&\n !(allowedTypes & AllowGroupSegments)\n ) {\n throw new InvariantError(\n `${pathname} is being parsed as a normalized route, but it has a route group segment.`\n )\n }\n\n if (\n appSegment.type === 'parallel-route' &&\n !(allowedTypes & AllowParallelSegments)\n ) {\n throw new InvariantError(\n `${pathname} is being parsed as a normalized route, but it has a parallel route segment.`\n )\n }\n\n segments.push(appSegment)\n\n if (appSegment.interceptionMarker) {\n const parts = pathname.split(appSegment.interceptionMarker)\n if (parts.length !== 2) {\n throw new Error(`Invalid interception route: ${pathname}`)\n }\n\n interceptingRoute = parseAppRouteImpl(parts[0], allowedTypes)\n interceptedRoute = parseAppRouteImpl(parts[1], allowedTypes)\n interceptionMarker = appSegment.interceptionMarker\n }\n }\n\n const dynamicSegments = segments.filter(\n (segment) => segment.type === 'dynamic'\n )\n\n return {\n normalized: allowedTypes === OnlyRoutableSegments,\n pathname,\n segments,\n dynamicSegments,\n interceptionMarker,\n interceptingRoute,\n interceptedRoute,\n }\n}\n\n/**\n * Parse an app route that has been fully normalized (no @slot or ()\n * group segments). Throws if either is present.\n */\nexport function parseNormalizedAppRoute(pathname: string): NormalizedAppRoute {\n return parseAppRouteImpl(pathname, OnlyRoutableSegments) as NormalizedAppRoute\n}\n\n/**\n * Parse an app route that may contain @slot segments but not ()\n * group segments. Slot segments are preserved as parallel-route\n * type segments so callers can distinguish routes in different\n * parallel slots.\n */\nexport function parseAppRouteWithSlots(pathname: string): AppRoute {\n return parseAppRouteImpl(pathname, AllowParallelSegments) as AppRoute\n}\n"],"names":["isInterceptionAppRoute","isNormalizedAppRoute","parseAppRouteSegment","parseAppRouteWithSlots","parseNormalizedAppRoute","normalizeEncodedDynamicPlaceholder","segment","test","decodedSegment","decodeURIComponent","getSegmentParam","interceptionMarker","INTERCEPTION_ROUTE_MARKERS","find","m","startsWith","param","type","name","endsWith","route","normalized","undefined","interceptingRoute","interceptedRoute","OnlyRoutableSegments","AllowParallelSegments","AllowGroupSegments","parseAppRouteImpl","pathname","allowedTypes","pathnameSegments","split","filter","Boolean","segments","normalizedSegment","appSegment","InvariantError","push","parts","length","Error","dynamicSegments"],"mappings":";;;;;;;;;;;;;;;;;;IAqKgBA,sBAAsB;eAAtBA;;IAjCAC,oBAAoB;eAApBA;;IAzDAC,oBAAoB;eAApBA;;IAgMAC,sBAAsB;eAAtBA;;IAVAC,uBAAuB;eAAvBA;;;gCAjQe;iCACoB;oCAI5C;AAyDP,SAASC,mCAAmCC,OAAe;IACzD,IAAI,CAAC,WAAWC,IAAI,CAACD,UAAU;QAC7B,OAAOA;IACT;IAEA,IAAI;QACF,MAAME,iBAAiBC,mBAAmBH;QAC1C,OAAOI,IAAAA,gCAAe,EAACF,kBAAkBA,iBAAiBF;IAC5D,EAAE,OAAM;QACN,OAAOA;IACT;AACF;AAEO,SAASJ,qBAAqBI,OAAe;IAClD,IAAIA,YAAY,IAAI;QAClB,OAAO;IACT;IAEA,0DAA0D;IAC1D,MAAMK,qBAAqBC,8C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AAiB,GAClC;YACA,MAAM,IAAIW,8BAAc,CACtB,GAAGT,SAAS,yEAAyE,CAAC;QAE1F;QAEA,IACEQ,WAAWpB,IAAI,KAAK,oBACpB,CAAEa,CAAAA,eAAeJ,qBAAoB,GACrC;YACA,MAAM,IAAIY,8BAAc,CACtB,GAAGT,SAAS,4EAA4E,CAAC;QAE7F;QAEAM,SAASI,IAAI,CAACF;QAEd,IAAIA,WAAW1B,kBAAkB,EAAE;YACjC,MAAM6B,QAAQX,SAASG,KAAK,CAACK,WAAW1B,kBAAkB;YAC1D,IAAI6B,MAAMC,MAAM,KAAK,GAAG;gBACtB,MAAM,IAAIC,MAAM,CAAC,4BAA4B,EAAEb,UAAU;YAC3D;YAEAN,oBAAoBK,kBAAkBY,KAAK,CAAC,EAAE,EAAEV;YAChDN,mBAAmBI,kBAAkBY,KAAK,CAAC,EAAE,EAAEV;YAC/CnB,qBAAqB0B,WAAW1B,kBAAkB;QACpD;IACF;IAEA,MAAMgC,kBAAkBR,SAASF,MAAM,CACrC,CAAC3B,UAAYA,QAAQW,IAAI,KAAK;IAGhC,OAAO;QACLI,YAAYS,iBAAiBL;QAC7BI;QACAM;QACAQ;QACAhC;QACAY;QACAC;IACF;AACF;AAMO,SAASpB,wBAAwByB,QAAgB;IACtD,OAAOD,kBAAkBC,UAAUJ;AACrC;AAQO,SAAStB,uBAAuB0B,QAAgB;IACrD,OAAOD,kBAAkBC,UAAUH;AACrC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-locale.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-locale.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..276f2d6146a42b86779632936893d6ce01c97c71 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-locale.d.ts @@ -0,0 +1,6 @@ +/** + * For a given path and a locale, if the locale is given, it will prefix the + * locale. The path shouldn't be an API path. If a default locale is given the + * prefix will be omitted if the locale is already the default locale. + */ +export declare function addLocale(path: string, locale?: string | false, defaultLocale?: string, ignorePrefix?: boolean): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-locale.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-locale.js new file mode 100644 index 0000000000000000000000000000000000000000..23a05b9fc0347349b4776f6b0d29546e6580e855 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-locale.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "addLocale", { + enumerable: true, + get: function() { + return addLocale; + } +}); +const _addpathprefix = require("./add-path-prefix"); +const _pathhasprefix = require("./path-has-prefix"); +function addLocale(path, locale, defaultLocale, ignorePrefix) { + // If no locale was given or the locale is the default locale, we don't need + // to prefix the path. + if (!locale || locale === defaultLocale) return path; + const lower = path.toLowerCase(); + // If the path is an API path or the path already has the locale prefix, we + // don't need to prefix the path. + if (!ignorePrefix) { + if ((0, _pathhasprefix.pathHasPrefix)(lower, '/api')) return path; + if ((0, _pathhasprefix.pathHasPrefix)(lower, `/${locale.toLowerCase()}`)) return path; + } + // Add the locale prefix to the path. + return (0, _addpathprefix.addPathPrefix)(path, `/${locale}`); +} + +//# sourceMappingURL=add-locale.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-locale.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-locale.js.map new file mode 100644 index 0000000000000000000000000000000000000000..50e30de0d8cb4dc7b94dd4756cea1e1f3b8a125c --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-locale.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/add-locale.ts"],"sourcesContent":["import { addPathPrefix } from './add-path-prefix'\nimport { pathHasPrefix } from './path-has-prefix'\n\n/**\n * For a given path and a locale, if the locale is given, it will prefix the\n * locale. The path shouldn't be an API path. If a default locale is given the\n * prefix will be omitted if the locale is already the default locale.\n */\nexport function addLocale(\n path: string,\n locale?: string | false,\n defaultLocale?: string,\n ignorePrefix?: boolean\n) {\n // If no locale was given or the locale is the default locale, we don't need\n // to prefix the path.\n if (!locale || locale === defaultLocale) return path\n\n const lower = path.toLowerCase()\n\n // If the path is an API path or the path already has the locale prefix, we\n // don't need to prefix the path.\n if (!ignorePrefix) {\n if (pathHasPrefix(lower, '/api')) return path\n if (pathHasPrefix(lower, `/${locale.toLowerCase()}`)) return path\n }\n\n // Add the locale prefix to the path.\n return addPathPrefix(path, `/${locale}`)\n}\n"],"names":["addLocale","path","locale","defaultLocale","ignorePrefix","lower","toLowerCase","pathHasPrefix","addPathPrefix"],"mappings":";;;;+BAQgBA;;;eAAAA;;;+BARc;+BACA;AAOvB,SAASA,UACdC,IAAY,EACZC,MAAuB,EACvBC,aAAsB,EACtBC,YAAsB;IAEtB,4EAA4E;IAC5E,sBAAsB;IACtB,IAAI,CAACF,UAAUA,WAAWC,eAAe,OAAOF;IAEhD,MAAMI,QAAQJ,KAAKK,WAAW;IAE9B,2EAA2E;IAC3E,iCAAiC;IACjC,IAAI,CAACF,cAAc;QACjB,IAAIG,IAAAA,4BAAa,EAACF,OAAO,SAAS,OAAOJ;QACzC,IAAIM,IAAAA,4BAAa,EAACF,OAAO,CAAC,CAAC,EAAEH,OAAOI,WAAW,IAAI,GAAG,OAAOL;IAC/D;IAEA,qCAAqC;IACrC,OAAOO,IAAAA,4BAAa,EAACP,MAAM,CAAC,CAAC,EAAEC,QAAQ;AACzC","ignoreList":[0]} \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-prefix.d.ts b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-prefix.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..65fdbd0fbe062072ed385ef635248e7451740762 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-prefix.d.ts @@ -0,0 +1,5 @@ +/** + * Adds the provided prefix to the given path. It first ensures that the path + * is indeed starting with a slash. + */ +export declare function addPathPrefix(path: string, prefix?: string): string; diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js new file mode 100644 index 0000000000000000000000000000000000000000..03517d944528bfac26d1dcd662f5f4b22f440092 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "addPathPrefix", { + enumerable: true, + get: function() { + return addPathPrefix; + } +}); +const _parsepath = require("./parse-path"); +function addPathPrefix(path, prefix) { + if (!path.startsWith('/') || !prefix) { + return path; + } + const { pathname, query, hash } = (0, _parsepath.parsePath)(path); + return `${prefix}${pathname}${query}${hash}`; +} + +//# sourceMappingURL=add-path-prefix.js.map \ No newline at end of file diff --git a/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js.map b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f695364ee76a9a319668209c63e7b7e614394fb1 --- /dev/null +++ b/e-commerce/node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../src/shared/lib/router/utils/add-path-prefix.ts"],"sourcesContent":["import { parsePath } from './parse-path'\n\n/**\n * Adds the provided prefix to the given path. It first ensures that the path\n * is indeed starting with a slash.\n */\nexport function addPathPrefix(path: string, prefix?: string) {\n if (!path.startsWith('/') || !prefix) {\n return path\n }\n\n const { pathname, query, hash } = parsePath(path)\n return `${prefix}${pathname}${query}${hash}`\n}\n"],"names":["addPathPrefix","path","prefix","startsWith","pathname","query","hash","parsePath"],"mappings":";;;;+BAMgBA;;;eAAAA;;;2BANU;AAMnB,SAASA,cAAcC,IAAY,EAAEC,MAAe;IACzD,IAAI,CAACD,KAAKE,UAAU,CAAC,QAAQ,CAACD,QAAQ;QACpC,OAAOD;IACT;IAEA,MAAM,EAAEG,QAAQ,EAAEC,KAAK,EAAEC,IAAI,EAAE,GAAGC,IAAAA,oBAAS,EAACN;IAC5C,OAAO,GAAGC,SAASE,WAAWC,QAAQC,MAAM;AAC9C","ignoreList":[0]} \ No newline at end of file