123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491 |
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.onDemandEntryHandler = onDemandEntryHandler;
- exports.getInvalidator = exports.entries = exports.EntryTypes = exports.BUILT = exports.BUILDING = exports.ADDED = void 0;
- var _debug = _interopRequireDefault(require("next/dist/compiled/debug"));
- var _events = require("events");
- var _findPageFile = require("../lib/find-page-file");
- var _entries = require("../../build/entries");
- var _path = require("path");
- var _normalizePathSep = require("../../shared/lib/page-path/normalize-path-sep");
- var _normalizePagePath = require("../../shared/lib/page-path/normalize-page-path");
- var _ensureLeadingSlash = require("../../shared/lib/page-path/ensure-leading-slash");
- var _removePagePathTail = require("../../shared/lib/page-path/remove-page-path-tail");
- var _output = require("../../build/output");
- var _getRouteFromEntrypoint = _interopRequireDefault(require("../get-route-from-entrypoint"));
- var _getPageStaticInfo = require("../../build/analysis/get-page-static-info");
- var _utils = require("../../build/utils");
- var _utils1 = require("../../shared/lib/utils");
- var _constants = require("../../shared/lib/constants");
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- default: obj
- };
- }
- const debug = (0, _debug).default("next:on-demand-entry-handler");
- const keys = Object.keys;
- const COMPILER_KEYS = keys(_constants.COMPILER_INDEXES);
- function treePathToEntrypoint(segmentPath, parentPath) {
- const [parallelRouteKey, segment] = segmentPath;
-
- const path = (parentPath ? parentPath + "/" : "") + (parallelRouteKey !== "children" && !segment.startsWith("@") ? parallelRouteKey + "/" : "") + (segment === "" ? "page" : 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");
- }
- }
- function getEntrypointsFromTree(tree, isFirst, parentPath = []) {
- const [segment, parallelRoutes] = tree;
- const currentSegment = Array.isArray(segment) ? convertDynamicParamTypeToSyntax(segment[2], segment[0]) : segment;
- const currentPath = [
- ...parentPath,
- currentSegment
- ];
- if (!isFirst && currentSegment === "") {
-
- 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
- ];
- }, []);
- }
- const ADDED = Symbol("added");
- exports.ADDED = ADDED;
- const BUILDING = Symbol("building");
- exports.BUILDING = BUILDING;
- const BUILT = Symbol("built");
- exports.BUILT = BUILT;
- var EntryTypes;
- exports.EntryTypes = EntryTypes;
- (function(EntryTypes) {
- EntryTypes[EntryTypes["ENTRY"] = 0] = "ENTRY";
- EntryTypes[EntryTypes["CHILD_ENTRY"] = 1] = "CHILD_ENTRY";
- })(EntryTypes || (exports.EntryTypes = EntryTypes = {}));
- const entries = {};
- exports.entries = entries;
- let invalidator;
- const getInvalidator = ()=>invalidator;
- exports.getInvalidator = getInvalidator;
- const doneCallbacks = new _events.EventEmitter();
- const lastClientAccessPages = [
- ""
- ];
- const lastServerAccessPagesForAppDir = [
- ""
- ];
- class Invalidator {
- building = new Set();
- rebuildAgain = new Set();
- constructor(multiCompiler){
- this.multiCompiler = multiCompiler;
- }
- shouldRebuildAll() {
- return this.rebuildAgain.size > 0;
- }
- invalidate(compilerKeys = COMPILER_KEYS) {
- for (const key of compilerKeys){
- var ref;
-
-
-
-
- if (this.building.has(key)) {
- this.rebuildAgain.add(key);
- continue;
- }
- (ref = this.multiCompiler.compilers[_constants.COMPILER_INDEXES[key]].watching) == null ? void 0 : ref.invalidate();
- this.building.add(key);
- }
- }
- startBuilding(compilerKey) {
- this.building.add(compilerKey);
- }
- doneBuilding() {
- const rebuild = [];
- for (const key of COMPILER_KEYS){
- this.building.delete(key);
- if (this.rebuildAgain.has(key)) {
- rebuild.push(key);
- this.rebuildAgain.delete(key);
- }
- }
- this.invalidate(rebuild);
- }
- }
- function disposeInactiveEntries(maxInactiveAge) {
- Object.keys(entries).forEach((entryKey)=>{
- const entryData = entries[entryKey];
- const { lastActiveTime , status , dispose } = entryData;
-
- if (entryData.type === 1) {
- return;
- }
- if (dispose)
- return;
-
-
- if (status !== BUILT) return;
-
-
-
- if (lastClientAccessPages.includes(entryKey) || lastServerAccessPagesForAppDir.includes(entryKey)) return;
- if (lastActiveTime && Date.now() - lastActiveTime > maxInactiveAge) {
- entries[entryKey].dispose = true;
- }
- });
- }
- function tryToNormalizePagePath(page) {
- try {
- return (0, _normalizePagePath).normalizePagePath(page);
- } catch (err) {
- console.error(err);
- throw new _utils1.PageNotFoundError(page);
- }
- }
- async function findPagePathData(rootDir, page, extensions, pagesDir, appDir) {
- const normalizedPagePath = tryToNormalizePagePath(page);
- let pagePath = null;
- if ((0, _utils).isMiddlewareFile(normalizedPagePath)) {
- pagePath = await (0, _findPageFile).findPageFile(rootDir, normalizedPagePath, extensions, false);
- if (!pagePath) {
- throw new _utils1.PageNotFoundError(normalizedPagePath);
- }
- const pageUrl = (0, _ensureLeadingSlash).ensureLeadingSlash((0, _removePagePathTail).removePagePathTail((0, _normalizePathSep).normalizePathSep(pagePath), {
- extensions
- }));
- return {
- absolutePagePath: (0, _path).join(rootDir, pagePath),
- bundlePath: normalizedPagePath.slice(1),
- page: _path.posix.normalize(pageUrl)
- };
- }
-
- if (appDir) {
- pagePath = await (0, _findPageFile).findPageFile(appDir, normalizedPagePath, extensions, true);
- if (pagePath) {
- const pageUrl = (0, _ensureLeadingSlash).ensureLeadingSlash((0, _removePagePathTail).removePagePathTail((0, _normalizePathSep).normalizePathSep(pagePath), {
- keepIndex: true,
- extensions
- }));
- return {
- absolutePagePath: (0, _path).join(appDir, pagePath),
- bundlePath: _path.posix.join("app", (0, _normalizePagePath).normalizePagePath(pageUrl)),
- page: _path.posix.normalize(pageUrl)
- };
- }
- }
- if (!pagePath && pagesDir) {
- pagePath = await (0, _findPageFile).findPageFile(pagesDir, normalizedPagePath, extensions, false);
- }
- if (pagePath !== null && pagesDir) {
- const pageUrl = (0, _ensureLeadingSlash).ensureLeadingSlash((0, _removePagePathTail).removePagePathTail((0, _normalizePathSep).normalizePathSep(pagePath), {
- extensions
- }));
- return {
- absolutePagePath: (0, _path).join(pagesDir, pagePath),
- bundlePath: _path.posix.join("pages", (0, _normalizePagePath).normalizePagePath(pageUrl)),
- page: _path.posix.normalize(pageUrl)
- };
- }
- if (page === "/_error") {
- return {
- absolutePagePath: require.resolve("next/dist/pages/_error"),
- bundlePath: page,
- page: (0, _normalizePathSep).normalizePathSep(page)
- };
- } else {
- throw new _utils1.PageNotFoundError(normalizedPagePath);
- }
- }
- function onDemandEntryHandler({ maxInactiveAge , multiCompiler , nextConfig , pagesBufferLength , pagesDir , rootDir , appDir }) {
- invalidator = new Invalidator(multiCompiler);
- const startBuilding = (compilation)=>{
- const compilationName = compilation.name;
- invalidator.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 = (0, _getRouteFromEntrypoint).default(entrypoint.name, root);
- if (page) {
- pagePaths.push(`${type}${page}`);
- } else if (root && entrypoint.name === "root" || (0, _utils).isMiddlewareFilename(entrypoint.name)) {
- pagePaths.push(`${type}/${entrypoint.name}`);
- }
- }
- return pagePaths;
- }
- multiCompiler.hooks.done.tap("NextJsOnDemandEntries", (multiStats)=>{
- if (invalidator.shouldRebuildAll()) {
- return invalidator.doneBuilding();
- }
- const [clientStats, serverStats, edgeServerStats] = multiStats.stats;
- const root = !!appDir;
- const pagePaths = [
- ...getPagePathsFromEntrypoints(_constants.COMPILER_NAMES.client, clientStats.compilation.entrypoints, root),
- ...getPagePathsFromEntrypoints(_constants.COMPILER_NAMES.server, serverStats.compilation.entrypoints, root),
- ...edgeServerStats ? getPagePathsFromEntrypoints(_constants.COMPILER_NAMES.edgeServer, edgeServerStats.compilation.entrypoints, root) : [],
- ];
- for (const page of pagePaths){
- const entry = entries[page];
- if (!entry) {
- continue;
- }
- if (entry.status !== BUILDING) {
- continue;
- }
- entry.status = BUILT;
- doneCallbacks.emit(page);
- }
- invalidator.doneBuilding();
- });
- const pingIntervalTime = Math.max(1000, Math.min(5000, maxInactiveAge));
- setInterval(function() {
- disposeInactiveEntries(maxInactiveAge);
- }, pingIntervalTime + 1000).unref();
- function handleAppDirPing(tree) {
- const pages = getEntrypointsFromTree(tree, true);
- let toSend = {
- invalid: true
- };
- for (const page of pages){
- for (const compilerType of [
- _constants.COMPILER_NAMES.client,
- _constants.COMPILER_NAMES.server,
- _constants.COMPILER_NAMES.edgeServer,
- ]){
- const pageKey = `${compilerType}/${page}`;
- const entryInfo = entries[pageKey];
-
- if (!entryInfo) {
- continue;
- }
-
- if (entryInfo.status !== BUILT) continue;
-
- if (!lastServerAccessPagesForAppDir.includes(pageKey)) {
- lastServerAccessPagesForAppDir.unshift(pageKey);
-
-
- if (lastServerAccessPagesForAppDir.length > pagesBufferLength) {
- lastServerAccessPagesForAppDir.pop();
- }
- }
- entryInfo.lastActiveTime = Date.now();
- entryInfo.dispose = false;
- toSend = {
- success: true
- };
- }
- }
- return toSend;
- }
- function handlePing(pg) {
- const page = (0, _normalizePathSep).normalizePathSep(pg);
- let toSend = {
- invalid: true
- };
- for (const compilerType of [
- _constants.COMPILER_NAMES.client,
- _constants.COMPILER_NAMES.server,
- _constants.COMPILER_NAMES.edgeServer,
- ]){
- const pageKey = `${compilerType}${page}`;
- const entryInfo = entries[pageKey];
-
- if (!entryInfo) {
-
- if (compilerType === _constants.COMPILER_NAMES.client) {
- return {
- invalid: true
- };
- }
- continue;
- }
-
- toSend = page === "/_error" ? {
- invalid: true
- } : {
- success: true
- };
-
- if (entryInfo.status !== BUILT) continue;
-
- if (!lastClientAccessPages.includes(pageKey)) {
- lastClientAccessPages.unshift(pageKey);
-
- if (lastClientAccessPages.length > pagesBufferLength) {
- lastClientAccessPages.pop();
- }
- }
- entryInfo.lastActiveTime = Date.now();
- entryInfo.dispose = false;
- }
- return toSend;
- }
- return {
- async ensurePage ({ page , clientOnly , appPaths =null }) {
- 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);
- try {
- const pagePathData = await findPagePathData(rootDir, page, nextConfig.pageExtensions, pagesDir, appDir);
- const isInsideAppDir = !!appDir && pagePathData.absolutePagePath.startsWith(appDir);
- const addEntry = (compilerType)=>{
- const entryKey = `${compilerType}${pagePathData.page}`;
- if (entries[entryKey]) {
- entries[entryKey].dispose = false;
- entries[entryKey].lastActiveTime = Date.now();
- if (entries[entryKey].status === BUILT) {
- return {
- entryKey,
- newEntry: false,
- shouldInvalidate: false
- };
- }
- return {
- entryKey,
- newEntry: false,
- shouldInvalidate: true
- };
- }
- entries[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 (0, _getPageStaticInfo).getPageStaticInfo({
- pageFilePath: pagePathData.absolutePagePath,
- nextConfig,
- isDev: true
- });
- const added = new Map();
- const isServerComponent = isInsideAppDir && staticInfo.rsc !== _constants.RSC_MODULE_TYPES.client;
- await (0, _entries).runDependingOnPageType({
- page: pagePathData.page,
- pageRuntime: staticInfo.runtime,
- onClient: ()=>{
-
- if (isServerComponent || isInsideAppDir) {
- return;
- }
- added.set(_constants.COMPILER_NAMES.client, addEntry(_constants.COMPILER_NAMES.client));
- },
- onServer: ()=>{
- added.set(_constants.COMPILER_NAMES.server, addEntry(_constants.COMPILER_NAMES.server));
- const edgeServerEntry = `${_constants.COMPILER_NAMES.edgeServer}${pagePathData.page}`;
- if (entries[edgeServerEntry]) {
-
- delete entries[edgeServerEntry];
- }
- },
- onEdgeServer: ()=>{
- added.set(_constants.COMPILER_NAMES.edgeServer, addEntry(_constants.COMPILER_NAMES.edgeServer));
- const serverEntry = `${_constants.COMPILER_NAMES.server}${pagePathData.page}`;
- if (entries[serverEntry]) {
-
- delete entries[serverEntry];
- }
- }
- });
- const addedValues = [
- ...added.values()
- ];
- const entriesThatShouldBeInvalidated = addedValues.filter((entry)=>entry.shouldInvalidate);
- const hasNewEntry = addedValues.some((entry)=>entry.newEntry);
- if (hasNewEntry) {
- (0, _output).reportTrigger(!clientOnly && hasNewEntry ? `${pagePathData.page} (client and server)` : pagePathData.page);
- }
- if (entriesThatShouldBeInvalidated.length > 0) {
- const invalidatePromises = entriesThatShouldBeInvalidated.map(({ entryKey })=>{
- return new Promise((resolve, reject)=>{
- doneCallbacks.once(entryKey, (err)=>{
- if (err) {
- return reject(err);
- }
- resolve();
- });
- });
- });
- invalidator.invalidate([
- ...added.keys()
- ]);
- await Promise.all(invalidatePromises);
- }
- } finally{
- clearTimeout(stalledEnsureTimeout);
- }
- },
- onHMR (client) {
- client.addEventListener("message", ({ data })=>{
- try {
- const parsedData = JSON.parse(typeof data !== "string" ? data.toString() : data);
- if (parsedData.event === "ping") {
- const result = parsedData.appDirRoute ? handleAppDirPing(parsedData.tree) : handlePing(parsedData.page);
- client.send(JSON.stringify({
- ...result,
- [parsedData.appDirRoute ? "action" : "event"]: "pong"
- }));
- }
- } catch (_) {}
- });
- }
- };
- }
|