"use strict";exports.__esModule=true;exports.default=onDemandEntryHandler;exports.entries=exports.BUILT=exports.BUILDING=exports.ADDED=void0;var_events=require("events");var_path=require("path");var_url=require("url");var_webpack=require("next/dist/compiled/webpack/webpack");varLog=_interopRequireWildcard(require("../build/output/log"));var_normalizePagePath=require("../next-server/server/normalize-page-path");var_require=require("../next-server/server/require");var_findPageFile=require("./lib/find-page-file");var_getRouteFromEntrypoint=_interopRequireDefault(require("../next-server/server/get-route-from-entrypoint"));function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{default:obj};}function_getRequireWildcardCache(){if(typeofWeakMap!=="function")returnnull;varcache=newWeakMap();_getRequireWildcardCache=function(){returncache;};returncache;}function_interopRequireWildcard(obj){if(obj&&obj.__esModule){returnobj;}if(obj===null||typeofobj!=="object"&&typeofobj!=="function"){return{default:obj};}varcache=_getRequireWildcardCache();if(cache&&cache.has(obj)){returncache.get(obj);}varnewObj={};varhasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(varkeyinobj){if(Object.prototype.hasOwnProperty.call(obj,key)){vardesc=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);}returnnewObj;}constADDED=Symbol('added');exports.ADDED=ADDED;constBUILDING=Symbol('building');exports.BUILDING=BUILDING;constBUILT=Symbol('built');exports.BUILT=BUILT;letentries={};exports.entries=entries;functiononDemandEntryHandler(watcher,multiCompiler,{pagesDir,pageExtensions,maxInactiveAge,pagesBufferLength}){const{compilers}=multiCompiler;constinvalidator=newInvalidator(watcher,multiCompiler);letlastAccessPages=[''];letdoneCallbacks=new_events.EventEmitter();for(constcompilerofcompilers){compiler.hooks.make.tap('NextJsOnDemandEntries',_compilation=>{invalidator.startBuilding();});}functiongetPagePathsFromEntrypoints(entrypoints){constpagePaths=[];for(constentrypointofentrypoints.values()){constpage=(0,_getRouteFromEntrypoint.default)(entrypoint.name);if(page){pagePaths.push(page);}}returnpagePaths;}multiCompiler.hooks.done.tap('NextJsOnDemandEntries',multiStats=>{const[clientStats,serverStats]=multiStats.stats;constpagePaths=newSet([...getPagePathsFromEntrypoints(clientStats.compilation.entrypoints),...getPagePathsFromEntrypoints(serverStats.compilation.entrypoints)]);for(constpageofpagePaths){constentry=entries[page];if(!entry){continue;}if(entry.status!==BUILDING){continue;}entry.status=BUILT;entry.lastActiveTime=Date.now();doneCallbacks.emit(page);}invalidator.doneBuilding();});constdisposeHandler=setInterval(function(){disposeInactiveEntries(watcher,lastAccessPages,maxInactiveAge);},5000);disposeHandler.unref();functionhandlePing(pg){constpage=(0,_normalizePagePath.normalizePathSep)(pg);constentryInfo=entries[page];lettoSend;// 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 pagereturn{invalid:true};}// 404 is an on demand entry but when a new page is added we have to refresh the pageif(page==='/_error'){toSend={invalid:true};}else{toSend={success:true};}// We don't need to maintain active state of anything other than BUILT entriesif(entryInfo.status!==BUILT)return;// If there's an entryInfoif(!lastAccessPages.includes(page)){lastAccessPages.unshift(page);// Maintain the buffer max lengthif(lastAccessPages.length>pagesBufferLength){lastAccessPages.pop();}}entryInfo.lastActiveTime=Date.now();returntoSend;}return{asyncensurePage(page){letnormalizedPagePath;try{normalizedPagePath=(0,_normalizePagePath.normalizePagePath)(page);}catch(err){console.error(err);throw(0,_require.pageNotFoundError)(page);}letpagePath=await(0,_findPageFile.findPageFile)(pagesDir,normalizedPagePath,pageExtensions);// Default the /_error route to the Next.js provided default pageif(page==='/_error'&&pagePath===null){pagePath='next/dist/pages/_error';}if(pagePath===null){throw(0,_require.pageNotFoundError)(normalizedPagePath);}letpageUrl=pagePath.replace(/\\/g,'/');pageUrl=`${pageUrl[0]!=='/'?'/':''}${pageUrl.replace(newRegExp(`\\.+(?:${pageExtensions.join('|')})$`),'').replace(/\/index$/,'')}`;pageUrl=pageUrl===''?'/':pageUrl;constbundleFile=(0,_normalizePagePath.normalizePagePath)(pageUrl);constserverBundlePath=_path.posix.join('pages',bundleFile);constclientBundlePath=_path.posix.join('pages',bundleFile);constabsolutePagePath=pagePath.startsWith('next/dist/pages')?require.resolve(pagePath):(0,_path.join)(pagesDir,pagePath);page=_path.posix.normalize(pageUrl);returnnewPromise((resolve,reject)=>{// Makes sure the page that is being kept in on-demand-entries matches the webpack outputconstnormalizedPage=(0,_normalizePagePath.normalizePathSep)(page);constentryInfo=entries[normalizedPage];if(entryInfo){if(entryInfo.status===BUILT){resolve();return;}if(entryInfo.status===BUILDING){doneCallbacks.once(normalizedPage,handleCallback);return;}}Log.event(`build page: ${normalizedPage}`);entries[normalizedPage]={serverBundlePath,clientBundlePath,absolutePagePath,status:ADDED};doneCallbacks.once(normalizedPage,handleCallback);invalidator.invalidate();functionhandleCallback(err){if(err)returnreject(err);resolve();}});},middleware(req,res,next){var_req$url;if(!((_req$url=req.url)!=null&&_req$url.startsWith('/_next/webpack-hmr')))returnnext();const{query}=(0,_url.parse)(req.url,true);constpage=query.page;if(!page)returnnext();construnPing=()=>{constdata=handlePing(query.page);if(!data)return;res.write('data: '+JSON.stringify(data)+'\n\n');};constpingInterval=setInterval(()=>runPing(),5000);req.on('close',()=>{clearInterval(pingInterval);});next();}};}functiondisposeInactiveEntries(watcher,lastAccessPages,maxInactiveAge){constdisposingPages=[];Object.keys(entries).forEach(page=>{const{lastActiveTime,status}=entries[page];// 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 pageif(lastAccessPages.includes(page))return;if(lastActiveTime&&Date.now()-lastActiveTime>maxInactiveAge){disposingPages.push(page);}});if(disposingPages.length>0){disposingPages.forEach(page=>{deleteentries[page];});// disposing inactive page(s)watcher.invalidate();}}// Make sure only one invalidation happens at a time// Otherwise, webpack hash gets changed and it'll force the client to reload.classInvalidator{constructor(watcher,multiCompiler){this.multiCompiler=void0;this.watcher=void0;this.building=void0;this.rebuildAgain=void0;this.multiCompiler=multiCompiler;this.watcher=watcher;// contains an array of types of compilers currently buildingthis.building=false;this.rebuildAgain=false;}invalidate(){// 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){this.rebuildAgain=true;return;}this.building=true;if(!_webpack.isWebpack5){// Work around a bug in webpack, calling `invalidate` on Watching.js// doesn't trigger the invalid call used to keep track of the `.done` hook on multiCompilerfor(constcompilerofthis.multiCompiler.compilers){compiler.hooks.invalid.call();}}this.watcher.invalidate();}startBuilding(){this.building=true;}doneBuilding(){this.building=false;if(this.rebuildAgain){this.rebuildAgain=false;this.invalidate();}}}//# sourceMappingURL=on-demand-entry-handler.js.map