main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

204
node_modules/next/dist/esm/server/dev/hot-middleware.js generated vendored Normal file
View File

@@ -0,0 +1,204 @@
// Based on https://github.com/webpack-contrib/webpack-hot-middleware/blob/9708d781ae0e46179cf8ea1a94719de4679aaf53/middleware.js
// Included License below
// Copyright JS Foundation and other contributors
// 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 { isMiddlewareFilename } from "../../build/utils";
import { HMR_ACTIONS_SENT_TO_BROWSER } from "./hot-reloader-types";
function isMiddlewareStats(stats) {
for (const key of stats.compilation.entrypoints.keys()){
if (isMiddlewareFilename(key)) {
return true;
}
}
return false;
}
function statsToJson(stats) {
if (!stats) return {};
return stats.toJson({
all: false,
errors: true,
hash: true,
warnings: true
});
}
function getStatsForSyncEvent(clientStats, serverStats) {
if (!clientStats) return serverStats == null ? void 0 : serverStats.stats;
if (!serverStats) return clientStats == null ? void 0 : clientStats.stats;
// Prefer the server compiler stats if it has errors.
// Otherwise we may end up in a state where the client compilation is the latest but without errors.
// This causes the error overlay to not display the build error.
if (serverStats.stats.hasErrors()) {
return serverStats.stats;
}
// Return the latest stats
return serverStats.ts > clientStats.ts ? serverStats.stats : clientStats.stats;
}
class EventStream {
constructor(){
this.clients = new Set();
}
everyClient(fn) {
for (const client of this.clients){
fn(client);
}
}
close() {
this.everyClient((client)=>{
client.close();
});
this.clients.clear();
}
handler(client) {
this.clients.add(client);
client.addEventListener("close", ()=>{
this.clients.delete(client);
});
}
publish(payload) {
this.everyClient((client)=>{
client.send(JSON.stringify(payload));
});
}
}
export class WebpackHotMiddleware {
constructor(compilers, versionInfo){
this.onClientInvalid = ()=>{
var _this_serverLatestStats;
if (this.closed || ((_this_serverLatestStats = this.serverLatestStats) == null ? void 0 : _this_serverLatestStats.stats.hasErrors())) return;
this.publish({
action: HMR_ACTIONS_SENT_TO_BROWSER.BUILDING
});
};
this.onClientDone = (statsResult)=>{
var _this_serverLatestStats;
this.clientLatestStats = {
ts: Date.now(),
stats: statsResult
};
if (this.closed || ((_this_serverLatestStats = this.serverLatestStats) == null ? void 0 : _this_serverLatestStats.stats.hasErrors())) return;
this.publishStats(statsResult);
};
this.onServerInvalid = ()=>{
var _this_serverLatestStats, _this_clientLatestStats;
if (!((_this_serverLatestStats = this.serverLatestStats) == null ? void 0 : _this_serverLatestStats.stats.hasErrors())) return;
this.serverLatestStats = null;
if ((_this_clientLatestStats = this.clientLatestStats) == null ? void 0 : _this_clientLatestStats.stats) {
this.publishStats(this.clientLatestStats.stats);
}
};
this.onServerDone = (statsResult)=>{
if (this.closed) return;
if (statsResult.hasErrors()) {
this.serverLatestStats = {
ts: Date.now(),
stats: statsResult
};
this.publishStats(statsResult);
}
};
this.onEdgeServerInvalid = ()=>{
var _this_middlewareLatestStats, _this_clientLatestStats;
if (!((_this_middlewareLatestStats = this.middlewareLatestStats) == null ? void 0 : _this_middlewareLatestStats.stats.hasErrors())) return;
this.middlewareLatestStats = null;
if ((_this_clientLatestStats = this.clientLatestStats) == null ? void 0 : _this_clientLatestStats.stats) {
this.publishStats(this.clientLatestStats.stats);
}
};
this.onEdgeServerDone = (statsResult)=>{
if (!isMiddlewareStats(statsResult)) {
this.onServerDone(statsResult);
return;
}
if (statsResult.hasErrors()) {
this.middlewareLatestStats = {
ts: Date.now(),
stats: statsResult
};
this.publishStats(statsResult);
}
};
/**
* To sync we use the most recent stats but also we append middleware
* errors. This is because it is possible that middleware fails to compile
* and we still want to show the client overlay with the error while
* the error page should be rendered just fine.
*/ this.onHMR = (client)=>{
if (this.closed) return;
this.eventStream.handler(client);
const syncStats = getStatsForSyncEvent(this.clientLatestStats, this.serverLatestStats);
if (syncStats) {
var _this_middlewareLatestStats;
const stats = statsToJson(syncStats);
const middlewareStats = statsToJson((_this_middlewareLatestStats = this.middlewareLatestStats) == null ? void 0 : _this_middlewareLatestStats.stats);
this.publish({
action: HMR_ACTIONS_SENT_TO_BROWSER.SYNC,
hash: stats.hash,
errors: [
...stats.errors || [],
...middlewareStats.errors || []
],
warnings: [
...stats.warnings || [],
...middlewareStats.warnings || []
],
versionInfo: this.versionInfo
});
}
};
this.publishStats = (statsResult)=>{
const stats = statsResult.toJson({
all: false,
hash: true,
warnings: true,
errors: true,
moduleTrace: true
});
this.publish({
action: HMR_ACTIONS_SENT_TO_BROWSER.BUILT,
hash: stats.hash,
warnings: stats.warnings || [],
errors: stats.errors || []
});
};
this.publish = (payload)=>{
if (this.closed) return;
this.eventStream.publish(payload);
};
this.close = ()=>{
if (this.closed) return;
// Can't remove compiler plugins, so we just set a flag and noop if closed
// https://github.com/webpack/tapable/issues/32#issuecomment-350644466
this.closed = true;
this.eventStream.close();
};
this.eventStream = new EventStream();
this.clientLatestStats = null;
this.middlewareLatestStats = null;
this.serverLatestStats = null;
this.closed = false;
this.versionInfo = versionInfo;
compilers[0].hooks.invalid.tap("webpack-hot-middleware", this.onClientInvalid);
compilers[0].hooks.done.tap("webpack-hot-middleware", this.onClientDone);
compilers[1].hooks.invalid.tap("webpack-hot-middleware", this.onServerInvalid);
compilers[1].hooks.done.tap("webpack-hot-middleware", this.onServerDone);
compilers[2].hooks.done.tap("webpack-hot-middleware", this.onEdgeServerDone);
compilers[2].hooks.invalid.tap("webpack-hot-middleware", this.onEdgeServerInvalid);
}
}
//# sourceMappingURL=hot-middleware.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,18 @@
export var HMR_ACTIONS_SENT_TO_BROWSER;
(function(HMR_ACTIONS_SENT_TO_BROWSER) {
HMR_ACTIONS_SENT_TO_BROWSER["ADDED_PAGE"] = "addedPage";
HMR_ACTIONS_SENT_TO_BROWSER["REMOVED_PAGE"] = "removedPage";
HMR_ACTIONS_SENT_TO_BROWSER["RELOAD_PAGE"] = "reloadPage";
HMR_ACTIONS_SENT_TO_BROWSER["SERVER_COMPONENT_CHANGES"] = "serverComponentChanges";
HMR_ACTIONS_SENT_TO_BROWSER["MIDDLEWARE_CHANGES"] = "middlewareChanges";
HMR_ACTIONS_SENT_TO_BROWSER["SERVER_ONLY_CHANGES"] = "serverOnlyChanges";
HMR_ACTIONS_SENT_TO_BROWSER["SYNC"] = "sync";
HMR_ACTIONS_SENT_TO_BROWSER["BUILT"] = "built";
HMR_ACTIONS_SENT_TO_BROWSER["BUILDING"] = "building";
HMR_ACTIONS_SENT_TO_BROWSER["DEV_PAGES_MANIFEST_UPDATE"] = "devPagesManifestUpdate";
HMR_ACTIONS_SENT_TO_BROWSER["TURBOPACK_MESSAGE"] = "turbopack-message";
HMR_ACTIONS_SENT_TO_BROWSER["SERVER_ERROR"] = "serverError";
HMR_ACTIONS_SENT_TO_BROWSER["TURBOPACK_CONNECTED"] = "turbopack-connected";
})(HMR_ACTIONS_SENT_TO_BROWSER || (HMR_ACTIONS_SENT_TO_BROWSER = {}));
//# sourceMappingURL=hot-reloader-types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/dev/hot-reloader-types.ts"],"names":["HMR_ACTIONS_SENT_TO_BROWSER","ADDED_PAGE","REMOVED_PAGE","RELOAD_PAGE","SERVER_COMPONENT_CHANGES","MIDDLEWARE_CHANGES","SERVER_ONLY_CHANGES","SYNC","BUILT","BUILDING","DEV_PAGES_MANIFEST_UPDATE","TURBOPACK_MESSAGE","SERVER_ERROR","TURBOPACK_CONNECTED"],"mappings":"WASO;UAAWA,2BAA2B;IAA3BA,4BAChBC,gBAAa;IADGD,4BAEhBE,kBAAe;IAFCF,4BAGhBG,iBAAc;IAHEH,4BAIhBI,8BAA2B;IAJXJ,4BAKhBK,wBAAqB;IALLL,4BAMhBM,yBAAsB;IANNN,4BAOhBO,UAAO;IAPSP,4BAQhBQ,WAAQ;IARQR,4BAShBS,cAAW;IATKT,4BAUhBU,+BAA4B;IAVZV,4BAWhBW,uBAAoB;IAXJX,4BAYhBY,kBAAe;IAZCZ,4BAahBa,yBAAsB;GAbNb,gCAAAA"}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,23 @@
import isError from "../../lib/is-error";
import * as Log from "../../build/output/log";
export function logAppDirError(err) {
if (isError(err) && (err == null ? void 0 : err.stack)) {
const cleanedStack = err.stack.split("\n").map((line)=>// Remove 'webpack-internal:' noise from the path
line.replace(/(webpack-internal:\/\/\/|file:\/\/)(\(.*\)\/)?/, ""));
const filteredStack = cleanedStack// Only display stack frames from the user's code
.filter((line)=>!/next[\\/]dist[\\/]compiled/.test(line) && !/node_modules[\\/]/.test(line) && !/node:internal[\\/]/.test(line));
if (filteredStack.length === 1) {
// This is an error that happened outside of user code, keep full stack
Log.error(`Internal error: ${cleanedStack.join("\n")}`);
} else {
Log.error(filteredStack.join("\n"));
}
if (typeof err.digest !== "undefined") {
console.error(`digest: ${JSON.stringify(err.digest)}`);
}
} else {
Log.error(err);
}
}
//# sourceMappingURL=log-app-dir-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/dev/log-app-dir-error.ts"],"names":["isError","Log","logAppDirError","err","stack","cleanedStack","split","map","line","replace","filteredStack","filter","test","length","error","join","digest","console","JSON","stringify"],"mappings":"AAAA,OAAOA,aAAa,qBAAoB;AACxC,YAAYC,SAAS,yBAAwB;AAE7C,OAAO,SAASC,eAAeC,GAAQ;IACrC,IAAIH,QAAQG,SAAQA,uBAAAA,IAAKC,KAAK,GAAE;QAC9B,MAAMC,eAAeF,IAAIC,KAAK,CAACE,KAAK,CAAC,MAAMC,GAAG,CAAC,CAACC,OAC9C,iDAAiD;YACjDA,KAAKC,OAAO,CAAC,kDAAkD;QAEjE,MAAMC,gBAAgBL,YACpB,iDAAiD;SAChDM,MAAM,CACL,CAACH,OACC,CAAC,6BAA6BI,IAAI,CAACJ,SACnC,CAAC,oBAAoBI,IAAI,CAACJ,SAC1B,CAAC,qBAAqBI,IAAI,CAACJ;QAEjC,IAAIE,cAAcG,MAAM,KAAK,GAAG;YAC9B,uEAAuE;YACvEZ,IAAIa,KAAK,CAAC,CAAC,gBAAgB,EAAET,aAAaU,IAAI,CAAC,MAAM,CAAC;QACxD,OAAO;YACLd,IAAIa,KAAK,CAACJ,cAAcK,IAAI,CAAC;QAC/B;QACA,IAAI,OAAO,AAACZ,IAAYa,MAAM,KAAK,aAAa;YAC9CC,QAAQH,KAAK,CAAC,CAAC,QAAQ,EAAEI,KAAKC,SAAS,CAAC,AAAChB,IAAYa,MAAM,EAAE,CAAC;QAChE;IACF,OAAO;QACLf,IAAIa,KAAK,CAACX;IACZ;AACF"}

View File

@@ -0,0 +1,528 @@
import { Worker } from "next/dist/compiled/jest-worker";
import { join as pathJoin } from "path";
import { ampValidation } from "../../build/output";
import { INSTRUMENTATION_HOOK_FILENAME, PUBLIC_DIR_MIDDLEWARE_CONFLICT } from "../../lib/constants";
import { fileExists } from "../../lib/file-exists";
import { findPagesDir } from "../../lib/find-pages-dir";
import { PHASE_DEVELOPMENT_SERVER, PAGES_MANIFEST, APP_PATHS_MANIFEST } from "../../shared/lib/constants";
import Server, { WrappedBuildError } from "../next-server";
import { normalizePagePath } from "../../shared/lib/page-path/normalize-page-path";
import { pathHasPrefix } from "../../shared/lib/router/utils/path-has-prefix";
import { removePathPrefix } from "../../shared/lib/router/utils/remove-path-prefix";
import { Telemetry } from "../../telemetry/storage";
import { setGlobal } from "../../trace";
import { findPageFile } from "../lib/find-page-file";
import { getNodeOptionsWithoutInspect } from "../lib/utils";
import { withCoalescedInvoke } from "../../lib/coalesced-function";
import { loadDefaultErrorComponents } from "../load-default-error-components";
import { DecodeError, MiddlewareNotFoundError } from "../../shared/lib/utils";
import * as Log from "../../build/output/log";
import isError, { getProperError } from "../../lib/is-error";
import { isMiddlewareFile } from "../../build/utils";
import { formatServerError } from "../../lib/format-server-error";
import { DevRouteMatcherManager } from "../future/route-matcher-managers/dev-route-matcher-manager";
import { DevPagesRouteMatcherProvider } from "../future/route-matcher-providers/dev/dev-pages-route-matcher-provider";
import { DevPagesAPIRouteMatcherProvider } from "../future/route-matcher-providers/dev/dev-pages-api-route-matcher-provider";
import { DevAppPageRouteMatcherProvider } from "../future/route-matcher-providers/dev/dev-app-page-route-matcher-provider";
import { DevAppRouteRouteMatcherProvider } from "../future/route-matcher-providers/dev/dev-app-route-route-matcher-provider";
import { NodeManifestLoader } from "../future/route-matcher-providers/helpers/manifest-loaders/node-manifest-loader";
import { BatchedFileReader } from "../future/route-matcher-providers/dev/helpers/file-reader/batched-file-reader";
import { DefaultFileReader } from "../future/route-matcher-providers/dev/helpers/file-reader/default-file-reader";
import { NextBuildContext } from "../../build/build-context";
import LRUCache from "next/dist/compiled/lru-cache";
import { getMiddlewareRouteMatcher } from "../../shared/lib/router/utils/middleware-route-matcher";
// Load ReactDevOverlay only when needed
let ReactDevOverlayImpl;
const ReactDevOverlay = (props)=>{
if (ReactDevOverlayImpl === undefined) {
ReactDevOverlayImpl = require("next/dist/compiled/@next/react-dev-overlay/dist/client").ReactDevOverlay;
}
return ReactDevOverlayImpl(props);
};
export default class DevServer extends Server {
invokeDevMethod({ method, args }) {
return global._nextDevHandlers[method](this.dir, ...args);
}
getStaticPathsWorker() {
const worker = new Worker(require.resolve("./static-paths-worker"), {
maxRetries: 1,
// For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.
// This helps reusing the memory a lot.
numWorkers: 1,
enableWorkerThreads: this.nextConfig.experimental.workerThreads,
forkOptions: {
env: {
...process.env,
// discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers
// would be started if user launch Next.js in debugging mode. The number of debuggers is linked to
// the number of workers Next.js tries to launch. The only worker users are interested in debugging
// is the main Next.js one
NODE_OPTIONS: getNodeOptionsWithoutInspect()
}
}
});
worker.getStdout().pipe(process.stdout);
worker.getStderr().pipe(process.stderr);
return worker;
}
constructor(options){
var _this_nextConfig_experimental_amp, _this_nextConfig_experimental;
try {
// Increase the number of stack frames on the server
Error.stackTraceLimit = 50;
} catch {}
super({
...options,
dev: true
});
this.originalFetch = global.fetch;
this.renderOpts.dev = true;
this.renderOpts.appDirDevErrorLogger = (err)=>this.logErrorWithOriginalStack(err, "app-dir");
this.renderOpts.ErrorDebug = ReactDevOverlay;
this.devReady = new Promise((resolve)=>{
this.setDevReady = resolve;
});
this.staticPathsCache = new LRUCache({
// 5MB
max: 5 * 1024 * 1024,
length (value) {
return JSON.stringify(value.staticPaths).length;
}
});
this.renderOpts.ampSkipValidation = ((_this_nextConfig_experimental = this.nextConfig.experimental) == null ? void 0 : (_this_nextConfig_experimental_amp = _this_nextConfig_experimental.amp) == null ? void 0 : _this_nextConfig_experimental_amp.skipValidation) ?? false;
this.renderOpts.ampValidator = (html, pathname)=>{
const validatorPath = this.nextConfig.experimental && this.nextConfig.experimental.amp && this.nextConfig.experimental.amp.validator;
const AmpHtmlValidator = require("next/dist/compiled/amphtml-validator");
return AmpHtmlValidator.getInstance(validatorPath).then((validator)=>{
const result = validator.validateString(html);
ampValidation(pathname, result.errors.filter((e)=>e.severity === "ERROR").filter((e)=>this._filterAmpDevelopmentScript(html, e)), result.errors.filter((e)=>e.severity !== "ERROR"));
});
};
const { pagesDir, appDir } = findPagesDir(this.dir);
this.pagesDir = pagesDir;
this.appDir = appDir;
}
getRouteMatchers() {
const { pagesDir, appDir } = findPagesDir(this.dir);
const ensurer = {
ensure: async (match)=>{
await this.ensurePage({
match,
page: match.definition.page,
clientOnly: false
});
}
};
const matchers = new DevRouteMatcherManager(super.getRouteMatchers(), ensurer, this.dir);
const extensions = this.nextConfig.pageExtensions;
const extensionsExpression = new RegExp(`\\.(?:${extensions.join("|")})$`);
// If the pages directory is available, then configure those matchers.
if (pagesDir) {
const fileReader = new BatchedFileReader(new DefaultFileReader({
// Only allow files that have the correct extensions.
pathnameFilter: (pathname)=>extensionsExpression.test(pathname)
}));
matchers.push(new DevPagesRouteMatcherProvider(pagesDir, extensions, fileReader, this.localeNormalizer));
matchers.push(new DevPagesAPIRouteMatcherProvider(pagesDir, extensions, fileReader, this.localeNormalizer));
}
if (appDir) {
// We create a new file reader for the app directory because we don't want
// to include any folders or files starting with an underscore. This will
// prevent the reader from wasting time reading files that we know we
// don't care about.
const fileReader = new BatchedFileReader(new DefaultFileReader({
// Ignore any directory prefixed with an underscore.
ignorePartFilter: (part)=>part.startsWith("_")
}));
matchers.push(new DevAppPageRouteMatcherProvider(appDir, extensions, fileReader));
matchers.push(new DevAppRouteRouteMatcherProvider(appDir, extensions, fileReader));
}
return matchers;
}
getBuildId() {
return "development";
}
async prepareImpl() {
setGlobal("distDir", this.distDir);
setGlobal("phase", PHASE_DEVELOPMENT_SERVER);
const telemetry = new Telemetry({
distDir: this.distDir
});
await super.prepareImpl();
await this.runInstrumentationHookIfAvailable();
await this.matchers.reload();
this.setDevReady();
// This is required by the tracing subsystem.
setGlobal("appDir", this.appDir);
setGlobal("pagesDir", this.pagesDir);
setGlobal("telemetry", telemetry);
process.on("unhandledRejection", (reason)=>{
this.logErrorWithOriginalStack(reason, "unhandledRejection").catch(()=>{});
});
process.on("uncaughtException", (err)=>{
this.logErrorWithOriginalStack(err, "uncaughtException").catch(()=>{});
});
}
async close() {}
async hasPage(pathname) {
let normalizedPath;
try {
normalizedPath = normalizePagePath(pathname);
} catch (err) {
console.error(err);
// if normalizing the page fails it means it isn't valid
// so it doesn't exist so don't throw and return false
// to ensure we return 404 instead of 500
return false;
}
if (isMiddlewareFile(normalizedPath)) {
return findPageFile(this.dir, normalizedPath, this.nextConfig.pageExtensions, false).then(Boolean);
}
let appFile = null;
let pagesFile = null;
if (this.appDir) {
appFile = await findPageFile(this.appDir, normalizedPath + "/page", this.nextConfig.pageExtensions, true);
}
if (this.pagesDir) {
pagesFile = await findPageFile(this.pagesDir, normalizedPath, this.nextConfig.pageExtensions, false);
}
if (appFile && pagesFile) {
return false;
}
return Boolean(appFile || pagesFile);
}
async runMiddleware(params) {
try {
const result = await super.runMiddleware({
...params,
onWarning: (warn)=>{
this.logErrorWithOriginalStack(warn, "warning");
}
});
if ("finished" in result) {
return result;
}
result.waitUntil.catch((error)=>{
this.logErrorWithOriginalStack(error, "unhandledRejection");
});
return result;
} catch (error) {
if (error instanceof DecodeError) {
throw error;
}
/**
* We only log the error when it is not a MiddlewareNotFound error as
* in that case we should be already displaying a compilation error
* which is what makes the module not found.
*/ if (!(error instanceof MiddlewareNotFoundError)) {
this.logErrorWithOriginalStack(error);
}
const err = getProperError(error);
err.middleware = true;
const { request, response, parsedUrl } = params;
/**
* When there is a failure for an internal Next.js request from
* middleware we bypass the error without finishing the request
* so we can serve the required chunks to render the error.
*/ if (request.url.includes("/_next/static") || request.url.includes("/__nextjs_original-stack-frame")) {
return {
finished: false
};
}
response.statusCode = 500;
await this.renderError(err, request, response, parsedUrl.pathname);
return {
finished: true
};
}
}
async runEdgeFunction(params) {
try {
return super.runEdgeFunction({
...params,
onWarning: (warn)=>{
this.logErrorWithOriginalStack(warn, "warning");
}
});
} catch (error) {
if (error instanceof DecodeError) {
throw error;
}
this.logErrorWithOriginalStack(error, "warning");
const err = getProperError(error);
const { req, res, page } = params;
res.statusCode = 500;
await this.renderError(err, req, res, page);
return null;
}
}
async handleRequest(req, res, parsedUrl) {
await this.devReady;
return await super.handleRequest(req, res, parsedUrl);
}
async run(req, res, parsedUrl) {
await this.devReady;
const { basePath } = this.nextConfig;
let originalPathname = null;
// TODO: see if we can remove this in the future
if (basePath && pathHasPrefix(parsedUrl.pathname || "/", basePath)) {
// strip basePath before handling dev bundles
// If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`
originalPathname = parsedUrl.pathname;
parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || "/", basePath);
}
const { pathname } = parsedUrl;
if (pathname.startsWith("/_next")) {
if (await fileExists(pathJoin(this.publicDir, "_next"))) {
throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT);
}
}
if (originalPathname) {
// restore the path before continuing so that custom-routes can accurately determine
// if they should match against the basePath or not
parsedUrl.pathname = originalPathname;
}
try {
return await super.run(req, res, parsedUrl);
} catch (error) {
const err = getProperError(error);
formatServerError(err);
this.logErrorWithOriginalStack(err).catch(()=>{});
if (!res.sent) {
res.statusCode = 500;
try {
return await this.renderError(err, req, res, pathname, {
__NEXT_PAGE: isError(err) && err.page || pathname || ""
});
} catch (internalErr) {
console.error(internalErr);
res.body("Internal Server Error").send();
}
}
}
}
async logErrorWithOriginalStack(err, type) {
if (this.isRenderWorker) {
await this.invokeDevMethod({
method: "logErrorWithOriginalStack",
args: [
err,
type
]
});
return;
}
throw new Error("Invariant logErrorWithOriginalStack called outside render worker");
}
getPagesManifest() {
return NodeManifestLoader.require(pathJoin(this.serverDistDir, PAGES_MANIFEST)) ?? undefined;
}
getAppPathsManifest() {
if (!this.hasAppDir) return undefined;
return NodeManifestLoader.require(pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)) ?? undefined;
}
getMiddleware() {
var _this_middleware;
// We need to populate the match
// field as it isn't serializable
if (((_this_middleware = this.middleware) == null ? void 0 : _this_middleware.match) === null) {
this.middleware.match = getMiddlewareRouteMatcher(this.middleware.matchers || []);
}
return this.middleware;
}
getNextFontManifest() {
return undefined;
}
async hasMiddleware() {
return this.hasPage(this.actualMiddlewareFile);
}
async ensureMiddleware() {
return this.ensurePage({
page: this.actualMiddlewareFile,
clientOnly: false
});
}
async runInstrumentationHookIfAvailable() {
if (this.actualInstrumentationHookFile && await this.ensurePage({
page: this.actualInstrumentationHookFile,
clientOnly: false
}).then(()=>true).catch(()=>false)) {
NextBuildContext.hasInstrumentationHook = true;
try {
const instrumentationHook = await require(pathJoin(this.distDir, "server", INSTRUMENTATION_HOOK_FILENAME));
await instrumentationHook.register();
} catch (err) {
err.message = `An error occurred while loading instrumentation hook: ${err.message}`;
throw err;
}
}
}
async ensureEdgeFunction({ page, appPaths }) {
return this.ensurePage({
page,
appPaths,
clientOnly: false
});
}
generateRoutes(_dev) {
// In development we expose all compiled files for react-error-overlay's line show feature
// We use unshift so that we're sure the routes is defined before Next's default routes
// routes.unshift({
// match: getPathMatch('/_next/development/:path*'),
// type: 'route',
// name: '_next/development catchall',
// fn: async (req, res, params) => {
// const p = pathJoin(this.distDir, ...(params.path || []))
// await this.serveStatic(req, res, p)
// return {
// finished: true,
// }
// },
// })
}
_filterAmpDevelopmentScript(html, event) {
if (event.code !== "DISALLOWED_SCRIPT_TAG") {
return true;
}
const snippetChunks = html.split("\n");
let snippet;
if (!(snippet = html.split("\n")[event.line - 1]) || !(snippet = snippet.substring(event.col))) {
return true;
}
snippet = snippet + snippetChunks.slice(event.line).join("\n");
snippet = snippet.substring(0, snippet.indexOf("</script>"));
return !snippet.includes("data-amp-development-mode-only");
}
async getStaticPaths({ pathname, requestHeaders, page, isAppPath }) {
// we lazy load the staticPaths to prevent the user
// from waiting on them for the page to load in dev mode
const __getStaticPaths = async ()=>{
const { configFileName, publicRuntimeConfig, serverRuntimeConfig, httpAgentOptions } = this.nextConfig;
const { locales, defaultLocale } = this.nextConfig.i18n || {};
const staticPathsWorker = this.getStaticPathsWorker();
try {
const pathsResult = await staticPathsWorker.loadStaticPaths({
distDir: this.distDir,
pathname,
config: {
configFileName,
publicRuntimeConfig,
serverRuntimeConfig
},
httpAgentOptions,
locales,
defaultLocale,
page,
isAppPath,
requestHeaders,
incrementalCacheHandlerPath: this.nextConfig.experimental.incrementalCacheHandlerPath,
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize
});
return pathsResult;
} finally{
// we don't re-use workers so destroy the used one
staticPathsWorker.end();
}
};
const result = this.staticPathsCache.get(pathname);
const nextInvoke = withCoalescedInvoke(__getStaticPaths)(`staticPaths-${pathname}`, []).then((res)=>{
const { paths: staticPaths = [], fallback } = res.value;
if (!isAppPath && this.nextConfig.output === "export") {
if (fallback === "blocking") {
throw new Error('getStaticPaths with "fallback: blocking" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export');
} else if (fallback === true) {
throw new Error('getStaticPaths with "fallback: true" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export');
}
}
const value = {
staticPaths,
fallbackMode: fallback === "blocking" ? "blocking" : fallback === true ? "static" : fallback
};
this.staticPathsCache.set(pathname, value);
return value;
}).catch((err)=>{
this.staticPathsCache.del(pathname);
if (!result) throw err;
Log.error(`Failed to generate static paths for ${pathname}:`);
console.error(err);
});
if (result) {
return result;
}
return nextInvoke;
}
restorePatchedGlobals() {
global.fetch = this.originalFetch;
}
async ensurePage(opts) {
if (!this.isRenderWorker) {
throw new Error("Invariant ensurePage called outside render worker");
}
await this.invokeDevMethod({
method: "ensurePage",
args: [
opts
]
});
}
async findPageComponents({ page, query, params, isAppPath, appPaths = null, shouldEnsure }) {
await this.devReady;
const compilationErr = await this.getCompilationError(page);
if (compilationErr) {
// Wrap build errors so that they don't get logged again
throw new WrappedBuildError(compilationErr);
}
try {
if (shouldEnsure || this.renderOpts.customServer) {
await this.ensurePage({
page,
appPaths,
clientOnly: false
});
}
this.nextFontManifest = super.getNextFontManifest();
// before we re-evaluate a route module, we want to restore globals that might
// have been patched previously to their original state so that we don't
// patch on top of the previous patch, which would keep the context of the previous
// patched global in memory, creating a memory leak.
this.restorePatchedGlobals();
return await super.findPageComponents({
page,
query,
params,
isAppPath,
shouldEnsure
});
} catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
return null;
}
}
async getFallbackErrorComponents() {
if (this.isRenderWorker) {
await this.invokeDevMethod({
method: "getFallbackErrorComponents",
args: []
});
return await loadDefaultErrorComponents(this.distDir);
}
throw new Error(`Invariant getFallbackErrorComponents called outside render worker`);
}
async getCompilationError(page) {
if (this.isRenderWorker) {
return await this.invokeDevMethod({
method: "getCompilationError",
args: [
page
]
});
}
throw new Error("Invariant getCompilationError called outside render worker");
}
}
//# sourceMappingURL=next-dev-server.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,613 @@
import origDebug from "next/dist/compiled/debug";
import { EventEmitter } from "events";
import { findPageFile } from "../lib/find-page-file";
import { getStaticInfoIncludingLayouts, runDependingOnPageType } from "../../build/entries";
import { join, posix } from "path";
import { normalizePathSep } from "../../shared/lib/page-path/normalize-path-sep";
import { normalizePagePath } from "../../shared/lib/page-path/normalize-page-path";
import { ensureLeadingSlash } from "../../shared/lib/page-path/ensure-leading-slash";
import { removePagePathTail } from "../../shared/lib/page-path/remove-page-path-tail";
import { reportTrigger } from "../../build/output";
import getRouteFromEntrypoint from "../get-route-from-entrypoint";
import { isInstrumentationHookFile, isInstrumentationHookFilename, isMiddlewareFile, isMiddlewareFilename } from "../../build/utils";
import { PageNotFoundError, stringifyError } from "../../shared/lib/utils";
import { COMPILER_INDEXES, COMPILER_NAMES, RSC_MODULE_TYPES } from "../../shared/lib/constants";
import { isAppPageRouteMatch } from "../future/route-matches/app-page-route-match";
import { HMR_ACTIONS_SENT_TO_BROWSER } from "./hot-reloader-types";
const debug = origDebug("next:on-demand-entry-handler");
/**
* Returns object keys with type inferred from the object key
*/ const keys = Object.keys;
const COMPILER_KEYS = keys(COMPILER_INDEXES);
function treePathToEntrypoint(segmentPath, parentPath) {
const [parallelRouteKey, segment] = segmentPath;
// TODO-APP: modify this path to cover parallelRouteKey convention
const path = (parentPath ? parentPath + "/" : "") + (parallelRouteKey !== "children" && !segment.startsWith("@") ? `@${parallelRouteKey}/` : "") + (segment === "" ? "page" : segment);
// Last segment
if (segmentPath.length === 2) {
return path;
}
const childSegmentPath = segmentPath.slice(2);
return treePathToEntrypoint(childSegmentPath, path);
}
function convertDynamicParamTypeToSyntax(dynamicParamTypeShort, param) {
switch(dynamicParamTypeShort){
case "c":
return `[...${param}]`;
case "oc":
return `[[...${param}]]`;
case "d":
return `[${param}]`;
default:
throw new Error("Unknown dynamic param type");
}
}
/**
* format: {compiler type}@{page type}@{page path}
* e.g. client@pages@/index
* e.g. server@app@app/page
*
* This guarantees the uniqueness for each page, to avoid conflicts between app/ and pages/
*/ export function getEntryKey(compilerType, pageBundleType, page) {
// TODO: handle the /children slot better
// this is a quick hack to handle when children is provided as children/page instead of /page
const pageKey = page.replace(/(@[^/]+)\/children/g, "$1");
return `${compilerType}@${pageBundleType}@${pageKey}`;
}
function getPageBundleType(pageBundlePath) {
// Handle special case for /_error
if (pageBundlePath === "/_error") return "pages";
if (isMiddlewareFilename(pageBundlePath)) return "root";
return pageBundlePath.startsWith("pages/") ? "pages" : pageBundlePath.startsWith("app/") ? "app" : "root";
}
function getEntrypointsFromTree(tree, isFirst, parentPath = []) {
const [segment, parallelRoutes] = tree;
const currentSegment = Array.isArray(segment) ? convertDynamicParamTypeToSyntax(segment[2], segment[0]) : segment;
const isPageSegment = currentSegment.startsWith("__PAGE__");
const currentPath = [
...parentPath,
isPageSegment ? "" : currentSegment
];
if (!isFirst && isPageSegment) {
// TODO get rid of '' at the start of tree
return [
treePathToEntrypoint(currentPath.slice(1))
];
}
return Object.keys(parallelRoutes).reduce((paths, key)=>{
const childTree = parallelRoutes[key];
const childPages = getEntrypointsFromTree(childTree, false, [
...currentPath,
key
]);
return [
...paths,
...childPages
];
}, []);
}
export const ADDED = Symbol("added");
export const BUILDING = Symbol("building");
export const BUILT = Symbol("built");
export var EntryTypes;
(function(EntryTypes) {
EntryTypes[EntryTypes["ENTRY"] = 0] = "ENTRY";
EntryTypes[EntryTypes["CHILD_ENTRY"] = 1] = "CHILD_ENTRY";
})(EntryTypes || (EntryTypes = {}));
const entriesMap = new Map();
// remove /server from end of output for server compiler
const normalizeOutputPath = (dir)=>dir.replace(/[/\\]server$/, "");
export const getEntries = (dir)=>{
dir = normalizeOutputPath(dir);
const entries = entriesMap.get(dir) || {};
entriesMap.set(dir, entries);
return entries;
};
const invalidators = new Map();
export const getInvalidator = (dir)=>{
dir = normalizeOutputPath(dir);
return invalidators.get(dir);
};
const doneCallbacks = new EventEmitter();
const lastClientAccessPages = [
""
];
const lastServerAccessPagesForAppDir = [
""
];
// Make sure only one invalidation happens at a time
// Otherwise, webpack hash gets changed and it'll force the client to reload.
class Invalidator {
constructor(multiCompiler){
this.building = new Set();
this.rebuildAgain = new Set();
this.multiCompiler = multiCompiler;
}
shouldRebuildAll() {
return this.rebuildAgain.size > 0;
}
invalidate(compilerKeys = COMPILER_KEYS) {
for (const key of compilerKeys){
var _this_multiCompiler_compilers_COMPILER_INDEXES_key_watching;
// If there's a current build is processing, we won't abort it by invalidating.
// (If aborted, it'll cause a client side hard reload)
// But let it to invalidate just after the completion.
// So, it can re-build the queued pages at once.
if (this.building.has(key)) {
this.rebuildAgain.add(key);
continue;
}
this.building.add(key);
(_this_multiCompiler_compilers_COMPILER_INDEXES_key_watching = this.multiCompiler.compilers[COMPILER_INDEXES[key]].watching) == null ? void 0 : _this_multiCompiler_compilers_COMPILER_INDEXES_key_watching.invalidate();
}
}
startBuilding(compilerKey) {
this.building.add(compilerKey);
}
doneBuilding(compilerKeys = []) {
const rebuild = [];
for (const key of compilerKeys){
this.building.delete(key);
if (this.rebuildAgain.has(key)) {
rebuild.push(key);
this.rebuildAgain.delete(key);
}
}
this.invalidate(rebuild);
}
willRebuild(compilerKey) {
return this.rebuildAgain.has(compilerKey);
}
}
function disposeInactiveEntries(entries, maxInactiveAge) {
Object.keys(entries).forEach((entryKey)=>{
const entryData = entries[entryKey];
const { lastActiveTime, status, dispose, bundlePath } = entryData;
// TODO-APP: implement disposing of CHILD_ENTRY
if (entryData.type === 1) {
return;
}
// For the root middleware and the instrumentation hook files,
// we don't dispose them periodically as it's needed for every request.
if (isMiddlewareFilename(bundlePath) || isInstrumentationHookFilename(bundlePath)) {
return;
}
if (dispose) // Skip pages already scheduled for disposing
return;
// This means this entry is currently building or just added
// We don't need to dispose those entries.
if (status !== BUILT) return;
// We should not build the last accessed page even we didn't get any pings
// Sometimes, it's possible our XHR ping to wait before completing other requests.
// In that case, we should not dispose the current viewing page
if (lastClientAccessPages.includes(entryKey) || lastServerAccessPagesForAppDir.includes(entryKey)) return;
if (lastActiveTime && Date.now() - lastActiveTime > maxInactiveAge) {
entries[entryKey].dispose = true;
}
});
}
// Normalize both app paths and page paths
function tryToNormalizePagePath(page) {
try {
return normalizePagePath(page);
} catch (err) {
console.error(err);
throw new PageNotFoundError(page);
}
}
/**
* Attempts to find a page file path from the given pages absolute directory,
* a page and allowed extensions. If the page can't be found it will throw an
* error. It defaults the `/_error` page to Next.js internal error page.
*
* @param rootDir Absolute path to the project root.
* @param pagesDir Absolute path to the pages folder with trailing `/pages`.
* @param normalizedPagePath The page normalized (it will be denormalized).
* @param pageExtensions Array of page extensions.
*/ async function findPagePathData(rootDir, page, extensions, pagesDir, appDir) {
const normalizedPagePath = tryToNormalizePagePath(page);
let pagePath = null;
const isInstrumentation = isInstrumentationHookFile(normalizedPagePath);
if (isMiddlewareFile(normalizedPagePath) || isInstrumentation) {
pagePath = await findPageFile(rootDir, normalizedPagePath, extensions, false);
if (!pagePath) {
throw new PageNotFoundError(normalizedPagePath);
}
const pageUrl = ensureLeadingSlash(removePagePathTail(normalizePathSep(pagePath), {
extensions
}));
let bundlePath = normalizedPagePath;
let pageKey = posix.normalize(pageUrl);
if (isInstrumentation) {
bundlePath = bundlePath.replace("/src", "");
pageKey = page.replace("/src", "");
}
return {
absolutePagePath: join(rootDir, pagePath),
bundlePath: bundlePath.slice(1),
page: pageKey
};
}
// Check appDir first falling back to pagesDir
if (appDir) {
pagePath = await findPageFile(appDir, normalizedPagePath, extensions, true);
if (pagePath) {
const pageUrl = ensureLeadingSlash(removePagePathTail(normalizePathSep(pagePath), {
keepIndex: true,
extensions
}));
return {
absolutePagePath: join(appDir, pagePath),
bundlePath: posix.join("app", pageUrl),
page: posix.normalize(pageUrl)
};
}
}
if (!pagePath && pagesDir) {
pagePath = await findPageFile(pagesDir, normalizedPagePath, extensions, false);
}
if (pagePath !== null && pagesDir) {
const pageUrl = ensureLeadingSlash(removePagePathTail(normalizePathSep(pagePath), {
extensions
}));
return {
absolutePagePath: join(pagesDir, pagePath),
bundlePath: posix.join("pages", normalizePagePath(pageUrl)),
page: posix.normalize(pageUrl)
};
}
if (page === "/not-found" && appDir) {
return {
absolutePagePath: require.resolve("next/dist/client/components/not-found-error"),
bundlePath: "app/not-found",
page: "/not-found"
};
}
if (page === "/_error") {
return {
absolutePagePath: require.resolve("next/dist/pages/_error"),
bundlePath: page,
page: normalizePathSep(page)
};
} else {
throw new PageNotFoundError(normalizedPagePath);
}
}
async function findRoutePathData(rootDir, page, extensions, pagesDir, appDir, match) {
if (match) {
// If the match is available, we don't have to discover the data from the
// filesystem.
return {
absolutePagePath: match.definition.filename,
page: match.definition.page,
bundlePath: match.definition.bundlePath
};
}
return findPagePathData(rootDir, page, extensions, pagesDir, appDir);
}
export function onDemandEntryHandler({ hotReloader, maxInactiveAge, multiCompiler, nextConfig, pagesBufferLength, pagesDir, rootDir, appDir }) {
let curInvalidator = getInvalidator(multiCompiler.outputPath);
const curEntries = getEntries(multiCompiler.outputPath);
if (!curInvalidator) {
curInvalidator = new Invalidator(multiCompiler);
invalidators.set(multiCompiler.outputPath, curInvalidator);
}
const startBuilding = (compilation)=>{
const compilationName = compilation.name;
curInvalidator.startBuilding(compilationName);
};
for (const compiler of multiCompiler.compilers){
compiler.hooks.make.tap("NextJsOnDemandEntries", startBuilding);
}
function getPagePathsFromEntrypoints(type, entrypoints, root) {
const pagePaths = [];
for (const entrypoint of entrypoints.values()){
const page = getRouteFromEntrypoint(entrypoint.name, root);
if (page) {
var _entrypoint_name;
const pageBundleType = ((_entrypoint_name = entrypoint.name) == null ? void 0 : _entrypoint_name.startsWith("app/")) ? "app" : "pages";
pagePaths.push(getEntryKey(type, pageBundleType, page));
} else if (root && entrypoint.name === "root" || isMiddlewareFilename(entrypoint.name) || isInstrumentationHookFilename(entrypoint.name)) {
pagePaths.push(getEntryKey(type, "root", `/${entrypoint.name}`));
}
}
return pagePaths;
}
for (const compiler of multiCompiler.compilers){
compiler.hooks.done.tap("NextJsOnDemandEntries", ()=>{
var _getInvalidator;
return (_getInvalidator = getInvalidator(compiler.outputPath)) == null ? void 0 : _getInvalidator.doneBuilding([
compiler.name
]);
});
}
multiCompiler.hooks.done.tap("NextJsOnDemandEntries", (multiStats)=>{
var _getInvalidator;
const [clientStats, serverStats, edgeServerStats] = multiStats.stats;
const root = !!appDir;
const entryNames = [
...getPagePathsFromEntrypoints(COMPILER_NAMES.client, clientStats.compilation.entrypoints, root),
...getPagePathsFromEntrypoints(COMPILER_NAMES.server, serverStats.compilation.entrypoints, root),
...edgeServerStats ? getPagePathsFromEntrypoints(COMPILER_NAMES.edgeServer, edgeServerStats.compilation.entrypoints, root) : []
];
for (const name of entryNames){
const entry = curEntries[name];
if (!entry) {
continue;
}
if (entry.status !== BUILDING) {
continue;
}
entry.status = BUILT;
doneCallbacks.emit(name);
}
(_getInvalidator = getInvalidator(multiCompiler.outputPath)) == null ? void 0 : _getInvalidator.doneBuilding([
...COMPILER_KEYS
]);
});
const pingIntervalTime = Math.max(1000, Math.min(5000, maxInactiveAge));
setInterval(function() {
disposeInactiveEntries(curEntries, maxInactiveAge);
}, pingIntervalTime + 1000).unref();
function handleAppDirPing(tree) {
const pages = getEntrypointsFromTree(tree, true);
for (const page of pages){
for (const compilerType of [
COMPILER_NAMES.client,
COMPILER_NAMES.server,
COMPILER_NAMES.edgeServer
]){
const entryKey = getEntryKey(compilerType, "app", `/${page}`);
const entryInfo = curEntries[entryKey];
// If there's no entry, it may have been invalidated and needs to be re-built.
if (!entryInfo) {
continue;
}
// We don't need to maintain active state of anything other than BUILT entries
if (entryInfo.status !== BUILT) continue;
// If there's an entryInfo
if (!lastServerAccessPagesForAppDir.includes(entryKey)) {
lastServerAccessPagesForAppDir.unshift(entryKey);
// Maintain the buffer max length
// TODO: verify that the current pageKey is not at the end of the array as multiple entrypoints can exist
if (lastServerAccessPagesForAppDir.length > pagesBufferLength) {
lastServerAccessPagesForAppDir.pop();
}
}
entryInfo.lastActiveTime = Date.now();
entryInfo.dispose = false;
}
}
}
function handlePing(pg) {
const page = normalizePathSep(pg);
for (const compilerType of [
COMPILER_NAMES.client,
COMPILER_NAMES.server,
COMPILER_NAMES.edgeServer
]){
const entryKey = getEntryKey(compilerType, "pages", page);
const entryInfo = curEntries[entryKey];
// If there's no entry, it may have been invalidated and needs to be re-built.
if (!entryInfo) {
// if (page !== lastEntry) client pings, but there's no entry for page
if (compilerType === COMPILER_NAMES.client) {
return;
}
continue;
}
// We don't need to maintain active state of anything other than BUILT entries
if (entryInfo.status !== BUILT) continue;
// If there's an entryInfo
if (!lastClientAccessPages.includes(entryKey)) {
lastClientAccessPages.unshift(entryKey);
// Maintain the buffer max length
if (lastClientAccessPages.length > pagesBufferLength) {
lastClientAccessPages.pop();
}
}
entryInfo.lastActiveTime = Date.now();
entryInfo.dispose = false;
}
return;
}
async function ensurePageImpl({ page, clientOnly, appPaths = null, match, isApp }) {
const stalledTime = 60;
const stalledEnsureTimeout = setTimeout(()=>{
debug(`Ensuring ${page} has taken longer than ${stalledTime}s, if this continues to stall this may be a bug`);
}, stalledTime * 1000);
// If the route is actually an app page route, then we should have access
// to the app route match, and therefore, the appPaths from it.
if (!appPaths && match && isAppPageRouteMatch(match)) {
appPaths = match.definition.appPaths;
}
try {
const pagePathData = await findRoutePathData(rootDir, page, nextConfig.pageExtensions, pagesDir, appDir, match);
const isInsideAppDir = !!appDir && pagePathData.absolutePagePath.startsWith(appDir);
if (typeof isApp === "boolean" && isApp !== isInsideAppDir) {
Error.stackTraceLimit = 15;
throw new Error(`Ensure bailed, found path "${pagePathData.page}" does not match ensure type (${isApp ? "app" : "pages"})`);
}
const pageBundleType = getPageBundleType(pagePathData.bundlePath);
const addEntry = (compilerType)=>{
const entryKey = getEntryKey(compilerType, pageBundleType, pagePathData.page);
if (curEntries[entryKey] && // there can be an overlap in the entryKey for the instrumentation hook file and a page named the same
// this is a quick fix to support this scenario by overwriting the instrumentation hook entry, since we only use it one time
// any changes to the instrumentation hook file will require a restart of the dev server anyway
!isInstrumentationHookFilename(curEntries[entryKey].bundlePath)) {
curEntries[entryKey].dispose = false;
curEntries[entryKey].lastActiveTime = Date.now();
if (curEntries[entryKey].status === BUILT) {
return {
entryKey,
newEntry: false,
shouldInvalidate: false
};
}
return {
entryKey,
newEntry: false,
shouldInvalidate: true
};
}
curEntries[entryKey] = {
type: 0,
appPaths,
absolutePagePath: pagePathData.absolutePagePath,
request: pagePathData.absolutePagePath,
bundlePath: pagePathData.bundlePath,
dispose: false,
lastActiveTime: Date.now(),
status: ADDED
};
return {
entryKey: entryKey,
newEntry: true,
shouldInvalidate: true
};
};
const staticInfo = await getStaticInfoIncludingLayouts({
page,
pageFilePath: pagePathData.absolutePagePath,
isInsideAppDir,
pageExtensions: nextConfig.pageExtensions,
isDev: true,
config: nextConfig,
appDir
});
const added = new Map();
const isServerComponent = isInsideAppDir && staticInfo.rsc !== RSC_MODULE_TYPES.client;
runDependingOnPageType({
page: pagePathData.page,
pageRuntime: staticInfo.runtime,
pageType: pageBundleType,
onClient: ()=>{
// Skip adding the client entry for app / Server Components.
if (isServerComponent || isInsideAppDir) {
return;
}
added.set(COMPILER_NAMES.client, addEntry(COMPILER_NAMES.client));
},
onServer: ()=>{
added.set(COMPILER_NAMES.server, addEntry(COMPILER_NAMES.server));
const edgeServerEntry = getEntryKey(COMPILER_NAMES.edgeServer, pageBundleType, pagePathData.page);
if (curEntries[edgeServerEntry] && !isInstrumentationHookFile(pagePathData.page)) {
// Runtime switched from edge to server
delete curEntries[edgeServerEntry];
}
},
onEdgeServer: ()=>{
added.set(COMPILER_NAMES.edgeServer, addEntry(COMPILER_NAMES.edgeServer));
const serverEntry = getEntryKey(COMPILER_NAMES.server, pageBundleType, pagePathData.page);
if (curEntries[serverEntry] && !isInstrumentationHookFile(pagePathData.page)) {
// Runtime switched from server to edge
delete curEntries[serverEntry];
}
}
});
const addedValues = [
...added.values()
];
const entriesThatShouldBeInvalidated = [
...added.entries()
].filter(([, entry])=>entry.shouldInvalidate);
const hasNewEntry = addedValues.some((entry)=>entry.newEntry);
if (hasNewEntry) {
reportTrigger(!clientOnly && hasNewEntry ? `${pagePathData.page}` : pagePathData.page);
}
if (entriesThatShouldBeInvalidated.length > 0) {
const invalidatePromise = Promise.all(entriesThatShouldBeInvalidated.map(([compilerKey, { entryKey }])=>{
return new Promise((resolve, reject)=>{
doneCallbacks.once(entryKey, (err)=>{
if (err) {
return reject(err);
}
// If the invalidation also triggers a rebuild, we need to
// wait for that additional build to prevent race conditions.
const needsRebuild = curInvalidator.willRebuild(compilerKey);
if (needsRebuild) {
doneCallbacks.once(entryKey, (rebuildErr)=>{
if (rebuildErr) {
return reject(rebuildErr);
}
resolve();
});
} else {
resolve();
}
});
});
}));
curInvalidator.invalidate([
...added.keys()
]);
await invalidatePromise;
}
} finally{
clearTimeout(stalledEnsureTimeout);
}
}
// Make sure that we won't have multiple invalidations ongoing concurrently.
const curEnsurePage = new Map();
return {
async ensurePage ({ page, clientOnly, appPaths = null, match, isApp }) {
const ensureKey = JSON.stringify({
page,
clientOnly,
match,
appPaths
});
const pendingEnsure = curEnsurePage.get(ensureKey);
if (pendingEnsure) {
const res = await pendingEnsure;
if (res && res.err) {
throw res.err;
}
}
const promise = ensurePageImpl({
page,
clientOnly,
appPaths,
match,
isApp
}).catch((err)=>{
return {
err
};
}).finally(()=>{
curEnsurePage.delete(ensureKey);
});
curEnsurePage.set(ensureKey, promise);
return promise;
},
onHMR (client, getHmrServerError) {
let bufferedHmrServerError = null;
client.addEventListener("close", ()=>{
bufferedHmrServerError = null;
});
client.addEventListener("message", ({ data })=>{
try {
const error = getHmrServerError();
// New error occurred: buffered error is flushed and new error occurred
if (!bufferedHmrServerError && error) {
hotReloader.send({
action: HMR_ACTIONS_SENT_TO_BROWSER.SERVER_ERROR,
errorJSON: stringifyError(error)
});
bufferedHmrServerError = null;
}
const parsedData = JSON.parse(typeof data !== "string" ? data.toString() : data);
if (parsedData.event === "ping") {
if (parsedData.appDirRoute) {
handleAppDirPing(parsedData.tree);
} else {
handlePing(parsedData.page);
}
}
} catch {}
});
}
};
}
//# sourceMappingURL=on-demand-entry-handler.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,57 @@
import * as semver from "next/dist/compiled/semver";
export function parseVersionInfo(o) {
const latest = semver.parse(o.latest);
const canary = semver.parse(o.canary);
const installedParsed = semver.parse(o.installed);
const installed = o.installed;
if (installedParsed && latest && canary) {
if (installedParsed.major < latest.major) {
// Old major version
return {
staleness: "stale-major",
expected: latest.raw,
installed
};
} else if (installedParsed.prerelease[0] === "canary" && semver.lt(installedParsed, canary)) {
// Matching major, but old canary
return {
staleness: "stale-prerelease",
expected: canary.raw,
installed
};
} else if (!installedParsed.prerelease.length && semver.lt(installedParsed, latest)) {
// Stable, but not the latest
if (installedParsed.minor === latest.minor) {
// Same major and minor, but not the latest patch
return {
staleness: "stale-patch",
expected: latest.raw,
installed
};
}
return {
staleness: "stale-minor",
expected: latest.raw,
installed
};
} else if (semver.gt(installedParsed, latest) && installedParsed.version !== canary.version) {
// Newer major version
return {
staleness: "newer-than-npm",
installed
};
} else {
// Latest and greatest
return {
staleness: "fresh",
installed
};
}
}
return {
installed: (installedParsed == null ? void 0 : installedParsed.raw) ?? "0.0.0",
staleness: "unknown"
};
}
//# sourceMappingURL=parse-version-info.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/dev/parse-version-info.ts"],"names":["semver","parseVersionInfo","o","latest","parse","canary","installedParsed","installed","major","staleness","expected","raw","prerelease","lt","length","minor","gt","version"],"mappings":"AAAA,YAAYA,YAAY,4BAA2B;AAenD,OAAO,SAASC,iBAAiBC,CAIhC;IACC,MAAMC,SAASH,OAAOI,KAAK,CAACF,EAAEC,MAAM;IACpC,MAAME,SAASL,OAAOI,KAAK,CAACF,EAAEG,MAAM;IACpC,MAAMC,kBAAkBN,OAAOI,KAAK,CAACF,EAAEK,SAAS;IAChD,MAAMA,YAAYL,EAAEK,SAAS;IAC7B,IAAID,mBAAmBH,UAAUE,QAAQ;QACvC,IAAIC,gBAAgBE,KAAK,GAAGL,OAAOK,KAAK,EAAE;YACxC,oBAAoB;YACpB,OAAO;gBAAEC,WAAW;gBAAeC,UAAUP,OAAOQ,GAAG;gBAAEJ;YAAU;QACrE,OAAO,IACLD,gBAAgBM,UAAU,CAAC,EAAE,KAAK,YAClCZ,OAAOa,EAAE,CAACP,iBAAiBD,SAC3B;YACA,iCAAiC;YACjC,OAAO;gBACLI,WAAW;gBACXC,UAAUL,OAAOM,GAAG;gBACpBJ;YACF;QACF,OAAO,IACL,CAACD,gBAAgBM,UAAU,CAACE,MAAM,IAClCd,OAAOa,EAAE,CAACP,iBAAiBH,SAC3B;YACA,6BAA6B;YAC7B,IAAIG,gBAAgBS,KAAK,KAAKZ,OAAOY,KAAK,EAAE;gBAC1C,iDAAiD;gBACjD,OAAO;oBACLN,WAAW;oBACXC,UAAUP,OAAOQ,GAAG;oBACpBJ;gBACF;YACF;YACA,OAAO;gBAAEE,WAAW;gBAAeC,UAAUP,OAAOQ,GAAG;gBAAEJ;YAAU;QACrE,OAAO,IACLP,OAAOgB,EAAE,CAACV,iBAAiBH,WAC3BG,gBAAgBW,OAAO,KAAKZ,OAAOY,OAAO,EAC1C;YACA,sBAAsB;YACtB,OAAO;gBAAER,WAAW;gBAAkBF;YAAU;QAClD,OAAO;YACL,sBAAsB;YACtB,OAAO;gBAAEE,WAAW;gBAASF;YAAU;QACzC;IACF;IAEA,OAAO;QACLA,WAAWD,CAAAA,mCAAAA,gBAAiBK,GAAG,KAAI;QACnCF,WAAW;IACb;AACF"}

View File

@@ -0,0 +1,66 @@
import "../require-hook";
import "../node-polyfill-fetch";
import "../node-environment";
import { buildAppStaticPaths, buildStaticPaths, collectGenerateParams } from "../../build/utils";
import { loadComponents } from "../load-components";
import { setHttpClientAndAgentOptions } from "../setup-http-agent-env";
import * as serverHooks from "../../client/components/hooks-server-context";
import { staticGenerationAsyncStorage } from "../../client/components/static-generation-async-storage.external";
const { AppRouteRouteModule } = require("../future/route-modules/app-route/module.compiled");
// we call getStaticPaths in a separate process to ensure
// side-effects aren't relied on in dev that will break
// during a production build
export async function loadStaticPaths({ distDir, pathname, config, httpAgentOptions, locales, defaultLocale, isAppPath, page, isrFlushToDisk, fetchCacheKeyPrefix, maxMemoryCacheSize, requestHeaders, incrementalCacheHandlerPath }) {
// update work memory runtime-config
require("../../shared/lib/runtime-config.external").setConfig(config);
setHttpClientAndAgentOptions({
httpAgentOptions
});
const components = await loadComponents({
distDir,
// In `pages/`, the page is the same as the pathname.
page: page || pathname,
isAppPath
});
if (!components.getStaticPaths && !isAppPath) {
// we shouldn't get to this point since the worker should
// only be called for SSG pages with getStaticPaths
throw new Error(`Invariant: failed to load page with getStaticPaths for ${pathname}`);
}
if (isAppPath) {
const { routeModule } = components;
const generateParams = routeModule && AppRouteRouteModule.is(routeModule) ? [
{
config: {
revalidate: routeModule.userland.revalidate,
dynamic: routeModule.userland.dynamic,
dynamicParams: routeModule.userland.dynamicParams
},
generateStaticParams: routeModule.userland.generateStaticParams,
segmentPath: pathname
}
] : await collectGenerateParams(components.ComponentMod.tree);
return await buildAppStaticPaths({
page: pathname,
generateParams,
configFileName: config.configFileName,
distDir,
requestHeaders,
incrementalCacheHandlerPath,
serverHooks,
staticGenerationAsyncStorage,
isrFlushToDisk,
fetchCacheKeyPrefix,
maxMemoryCacheSize
});
}
return await buildStaticPaths({
page: pathname,
getStaticPaths: components.getStaticPaths,
configFileName: config.configFileName,
locales,
defaultLocale
});
}
//# sourceMappingURL=static-paths-worker.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/dev/static-paths-worker.ts"],"names":["buildAppStaticPaths","buildStaticPaths","collectGenerateParams","loadComponents","setHttpClientAndAgentOptions","serverHooks","staticGenerationAsyncStorage","AppRouteRouteModule","require","loadStaticPaths","distDir","pathname","config","httpAgentOptions","locales","defaultLocale","isAppPath","page","isrFlushToDisk","fetchCacheKeyPrefix","maxMemoryCacheSize","requestHeaders","incrementalCacheHandlerPath","setConfig","components","getStaticPaths","Error","routeModule","generateParams","is","revalidate","userland","dynamic","dynamicParams","generateStaticParams","segmentPath","ComponentMod","tree","configFileName"],"mappings":"AAEA,OAAO,kBAAiB;AACxB,OAAO,yBAAwB;AAC/B,OAAO,sBAAqB;AAE5B,SACEA,mBAAmB,EACnBC,gBAAgB,EAChBC,qBAAqB,QAEhB,oBAAmB;AAC1B,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,4BAA4B,QAAQ,0BAAyB;AAEtE,YAAYC,iBAAiB,+CAA8C;AAC3E,SAASC,4BAA4B,QAAQ,mEAAkE;AAE/G,MAAM,EAAEC,mBAAmB,EAAE,GAC3BC,QAAQ;AAIV,yDAAyD;AACzD,uDAAuD;AACvD,4BAA4B;AAC5B,OAAO,eAAeC,gBAAgB,EACpCC,OAAO,EACPC,QAAQ,EACRC,MAAM,EACNC,gBAAgB,EAChBC,OAAO,EACPC,aAAa,EACbC,SAAS,EACTC,IAAI,EACJC,cAAc,EACdC,mBAAmB,EACnBC,kBAAkB,EAClBC,cAAc,EACdC,2BAA2B,EAe5B;IAKC,oCAAoC;IACpCd,QAAQ,4CAA4Ce,SAAS,CAACX;IAC9DR,6BAA6B;QAC3BS;IACF;IAEA,MAAMW,aAAa,MAAMrB,eAAe;QACtCO;QACA,qDAAqD;QACrDO,MAAMA,QAAQN;QACdK;IACF;IAEA,IAAI,CAACQ,WAAWC,cAAc,IAAI,CAACT,WAAW;QAC5C,yDAAyD;QACzD,mDAAmD;QACnD,MAAM,IAAIU,MACR,CAAC,uDAAuD,EAAEf,SAAS,CAAC;IAExE;IAEA,IAAIK,WAAW;QACb,MAAM,EAAEW,WAAW,EAAE,GAAGH;QACxB,MAAMI,iBACJD,eAAepB,oBAAoBsB,EAAE,CAACF,eAClC;YACE;gBACEf,QAAQ;oBACNkB,YAAYH,YAAYI,QAAQ,CAACD,UAAU;oBAC3CE,SAASL,YAAYI,QAAQ,CAACC,OAAO;oBACrCC,eAAeN,YAAYI,QAAQ,CAACE,aAAa;gBACnD;gBACAC,sBAAsBP,YAAYI,QAAQ,CAACG,oBAAoB;gBAC/DC,aAAaxB;YACf;SACD,GACD,MAAMT,sBAAsBsB,WAAWY,YAAY,CAACC,IAAI;QAE9D,OAAO,MAAMrC,oBAAoB;YAC/BiB,MAAMN;YACNiB;YACAU,gBAAgB1B,OAAO0B,cAAc;YACrC5B;YACAW;YACAC;YACAjB;YACAC;YACAY;YACAC;YACAC;QACF;IACF;IAEA,OAAO,MAAMnB,iBAAiB;QAC5BgB,MAAMN;QACNc,gBAAgBD,WAAWC,cAAc;QACzCa,gBAAgB1B,OAAO0B,cAAc;QACrCxB;QACAC;IACF;AACF"}