entries.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.getPageFromPath = getPageFromPath;
  6. exports.createPagesMapping = createPagesMapping;
  7. exports.getEdgeServerEntry = getEdgeServerEntry;
  8. exports.getAppEntry = getAppEntry;
  9. exports.getServerlessEntry = getServerlessEntry;
  10. exports.getClientEntry = getClientEntry;
  11. exports.runDependingOnPageType = runDependingOnPageType;
  12. exports.createEntrypoints = createEntrypoints;
  13. exports.finalizeEntrypoint = finalizeEntrypoint;
  14. var _chalk = _interopRequireDefault(require("next/dist/compiled/chalk"));
  15. var _path = require("path");
  16. var _querystring = require("querystring");
  17. var _constants = require("../lib/constants");
  18. var _constants1 = require("../shared/lib/constants");
  19. var _utils = require("../server/utils");
  20. var _log = require("./output/log");
  21. var _utils1 = require("./utils");
  22. var _getPageStaticInfo = require("./analysis/get-page-static-info");
  23. var _normalizePathSep = require("../shared/lib/page-path/normalize-path-sep");
  24. var _normalizePagePath = require("../shared/lib/page-path/normalize-page-path");
  25. var _appPaths = require("../shared/lib/router/utils/app-paths");
  26. var _nextMiddlewareLoader = require("./webpack/loaders/next-middleware-loader");
  27. function _interopRequireDefault(obj) {
  28. return obj && obj.__esModule ? obj : {
  29. default: obj
  30. };
  31. }
  32. function getPageFromPath(pagePath, pageExtensions) {
  33. let page = (0, _normalizePathSep).normalizePathSep(pagePath.replace(new RegExp(`\\.+(${pageExtensions.join("|")})$`), ""));
  34. page = page.replace(/\/index$/, "");
  35. return page === "" ? "/" : page;
  36. }
  37. function createPagesMapping({ isDev , pageExtensions , pagePaths , pagesType , pagesDir }) {
  38. const previousPages = {};
  39. const pages = pagePaths.reduce((result, pagePath)=>{
  40. // Do not process .d.ts files inside the `pages` folder
  41. if (pagePath.endsWith(".d.ts") && pageExtensions.includes("ts")) {
  42. return result;
  43. }
  44. const pageKey = getPageFromPath(pagePath, pageExtensions);
  45. if (pageKey in result) {
  46. (0, _log).warn(`Duplicate page detected. ${_chalk.default.cyan((0, _path).join("pages", previousPages[pageKey]))} and ${_chalk.default.cyan((0, _path).join("pages", pagePath))} both resolve to ${_chalk.default.cyan(pageKey)}.`);
  47. } else {
  48. previousPages[pageKey] = pagePath;
  49. }
  50. result[pageKey] = (0, _normalizePathSep).normalizePathSep((0, _path).join(pagesType === "pages" ? _constants.PAGES_DIR_ALIAS : pagesType === "app" ? _constants.APP_DIR_ALIAS : _constants.ROOT_DIR_ALIAS, pagePath));
  51. return result;
  52. }, {});
  53. if (pagesType !== "pages") {
  54. return pages;
  55. }
  56. if (isDev) {
  57. delete pages["/_app"];
  58. delete pages["/_error"];
  59. delete pages["/_document"];
  60. }
  61. // In development we always alias these to allow Webpack to fallback to
  62. // the correct source file so that HMR can work properly when a file is
  63. // added or removed.
  64. const root = isDev && pagesDir ? _constants.PAGES_DIR_ALIAS : "next/dist/pages";
  65. return {
  66. "/_app": `${root}/_app`,
  67. "/_error": `${root}/_error`,
  68. "/_document": `${root}/_document`,
  69. ...pages
  70. };
  71. }
  72. function getEdgeServerEntry(opts) {
  73. var ref;
  74. if ((0, _utils1).isMiddlewareFile(opts.page)) {
  75. var ref1;
  76. const loaderParams = {
  77. absolutePagePath: opts.absolutePagePath,
  78. page: opts.page,
  79. rootDir: opts.rootDir,
  80. matchers: ((ref1 = opts.middleware) == null ? void 0 : ref1.matchers) ? (0, _nextMiddlewareLoader).encodeMatchers(opts.middleware.matchers) : ""
  81. };
  82. return `next-middleware-loader?${(0, _querystring).stringify(loaderParams)}!`;
  83. }
  84. if (opts.page.startsWith("/api/") || opts.page === "/api") {
  85. const loaderParams = {
  86. absolutePagePath: opts.absolutePagePath,
  87. page: opts.page,
  88. rootDir: opts.rootDir
  89. };
  90. return `next-edge-function-loader?${(0, _querystring).stringify(loaderParams)}!`;
  91. }
  92. const loaderParams = {
  93. absolute500Path: opts.pages["/500"] || "",
  94. absoluteAppPath: opts.pages["/_app"],
  95. absoluteDocumentPath: opts.pages["/_document"],
  96. absoluteErrorPath: opts.pages["/_error"],
  97. absolutePagePath: opts.absolutePagePath,
  98. buildId: opts.buildId,
  99. dev: opts.isDev,
  100. isServerComponent: opts.isServerComponent,
  101. page: opts.page,
  102. stringifiedConfig: JSON.stringify(opts.config),
  103. pagesType: opts.pagesType,
  104. appDirLoader: Buffer.from(opts.appDirLoader || "").toString("base64"),
  105. sriEnabled: !opts.isDev && !!((ref = opts.config.experimental.sri) == null ? void 0 : ref.algorithm)
  106. };
  107. return {
  108. import: `next-edge-ssr-loader?${(0, _querystring).stringify(loaderParams)}!`,
  109. layer: opts.isServerComponent ? _constants.WEBPACK_LAYERS.server : undefined
  110. };
  111. }
  112. function getAppEntry(opts) {
  113. return {
  114. import: `next-app-loader?${(0, _querystring).stringify(opts)}!`,
  115. layer: _constants.WEBPACK_LAYERS.server
  116. };
  117. }
  118. function getServerlessEntry(opts) {
  119. const loaderParams = {
  120. absolute404Path: opts.pages["/404"] || "",
  121. absoluteAppPath: opts.pages["/_app"],
  122. absoluteDocumentPath: opts.pages["/_document"],
  123. absoluteErrorPath: opts.pages["/_error"],
  124. absolutePagePath: opts.absolutePagePath,
  125. assetPrefix: opts.config.assetPrefix,
  126. basePath: opts.config.basePath,
  127. buildId: opts.buildId,
  128. canonicalBase: opts.config.amp.canonicalBase || "",
  129. distDir: _constants.DOT_NEXT_ALIAS,
  130. generateEtags: opts.config.generateEtags ? "true" : "",
  131. i18n: opts.config.i18n ? JSON.stringify(opts.config.i18n) : "",
  132. // base64 encode to make sure contents don't break webpack URL loading
  133. loadedEnvFiles: Buffer.from(JSON.stringify(opts.envFiles)).toString("base64"),
  134. page: opts.page,
  135. poweredByHeader: opts.config.poweredByHeader ? "true" : "",
  136. previewProps: JSON.stringify(opts.previewMode),
  137. runtimeConfig: Object.keys(opts.config.publicRuntimeConfig).length > 0 || Object.keys(opts.config.serverRuntimeConfig).length > 0 ? JSON.stringify({
  138. publicRuntimeConfig: opts.config.publicRuntimeConfig,
  139. serverRuntimeConfig: opts.config.serverRuntimeConfig
  140. }) : ""
  141. };
  142. return `next-serverless-loader?${(0, _querystring).stringify(loaderParams)}!`;
  143. }
  144. function getClientEntry(opts) {
  145. const loaderOptions = {
  146. absolutePagePath: opts.absolutePagePath,
  147. page: opts.page
  148. };
  149. const pageLoader = `next-client-pages-loader?${(0, _querystring).stringify(loaderOptions)}!`;
  150. // Make sure next/router is a dependency of _app or else chunk splitting
  151. // might cause the router to not be able to load causing hydration
  152. // to fail
  153. return opts.page === "/_app" ? [
  154. pageLoader,
  155. require.resolve("../client/router")
  156. ] : pageLoader;
  157. }
  158. async function runDependingOnPageType(params) {
  159. if ((0, _utils1).isMiddlewareFile(params.page)) {
  160. await params.onEdgeServer();
  161. return;
  162. }
  163. if (params.page.match(_constants.API_ROUTE)) {
  164. if (params.pageRuntime === _constants.SERVER_RUNTIME.edge) {
  165. await params.onEdgeServer();
  166. return;
  167. }
  168. await params.onServer();
  169. return;
  170. }
  171. if (params.page === "/_document") {
  172. await params.onServer();
  173. return;
  174. }
  175. if (params.page === "/_app" || params.page === "/_error" || params.page === "/404" || params.page === "/500") {
  176. await Promise.all([
  177. params.onClient(),
  178. params.onServer()
  179. ]);
  180. return;
  181. }
  182. if (params.pageRuntime === _constants.SERVER_RUNTIME.edge) {
  183. await Promise.all([
  184. params.onClient(),
  185. params.onEdgeServer()
  186. ]);
  187. return;
  188. }
  189. await Promise.all([
  190. params.onClient(),
  191. params.onServer()
  192. ]);
  193. return;
  194. }
  195. async function createEntrypoints(params) {
  196. const { config , pages , pagesDir , isDev , rootDir , rootPaths , target , appDir , appPaths , pageExtensions , } = params;
  197. const edgeServer = {};
  198. const server = {};
  199. const client = {};
  200. const nestedMiddleware = [];
  201. let middlewareMatchers = undefined;
  202. let appPathsPerRoute = {};
  203. if (appDir && appPaths) {
  204. for(const pathname in appPaths){
  205. const normalizedPath = (0, _appPaths).normalizeAppPath(pathname) || "/";
  206. if (!appPathsPerRoute[normalizedPath]) {
  207. appPathsPerRoute[normalizedPath] = [];
  208. }
  209. appPathsPerRoute[normalizedPath].push(pathname);
  210. }
  211. // Make sure to sort parallel routes to make the result deterministic.
  212. appPathsPerRoute = Object.fromEntries(Object.entries(appPathsPerRoute).map(([k, v])=>[
  213. k,
  214. v.sort()
  215. ]));
  216. }
  217. const getEntryHandler = (mappings, pagesType)=>{
  218. return async (page)=>{
  219. const bundleFile = (0, _normalizePagePath).normalizePagePath(page);
  220. const clientBundlePath = _path.posix.join(pagesType, bundleFile);
  221. const serverBundlePath = pagesType === "pages" ? _path.posix.join("pages", bundleFile) : pagesType === "app" ? _path.posix.join("app", bundleFile) : bundleFile.slice(1);
  222. const absolutePagePath = mappings[page];
  223. // Handle paths that have aliases
  224. const pageFilePath = (()=>{
  225. if (absolutePagePath.startsWith(_constants.PAGES_DIR_ALIAS) && pagesDir) {
  226. return absolutePagePath.replace(_constants.PAGES_DIR_ALIAS, pagesDir);
  227. }
  228. if (absolutePagePath.startsWith(_constants.APP_DIR_ALIAS) && appDir) {
  229. return absolutePagePath.replace(_constants.APP_DIR_ALIAS, appDir);
  230. }
  231. if (absolutePagePath.startsWith(_constants.ROOT_DIR_ALIAS)) {
  232. return absolutePagePath.replace(_constants.ROOT_DIR_ALIAS, rootDir);
  233. }
  234. return require.resolve(absolutePagePath);
  235. })();
  236. /**
  237. * When we find a middleware file that is not in the ROOT_DIR we fail.
  238. * There is no need to check on `dev` as this should only happen when
  239. * building for production.
  240. */ if (!absolutePagePath.startsWith(_constants.ROOT_DIR_ALIAS) && /[\\\\/]_middleware$/.test(page)) {
  241. nestedMiddleware.push(page);
  242. }
  243. const isInsideAppDir = !!appDir && (absolutePagePath.startsWith(_constants.APP_DIR_ALIAS) || absolutePagePath.startsWith(appDir));
  244. const staticInfo = await (0, _getPageStaticInfo).getPageStaticInfo({
  245. nextConfig: config,
  246. pageFilePath,
  247. isDev,
  248. page
  249. });
  250. const isServerComponent = isInsideAppDir && staticInfo.rsc !== _constants1.RSC_MODULE_TYPES.client;
  251. if ((0, _utils1).isMiddlewareFile(page)) {
  252. var ref;
  253. var ref2;
  254. middlewareMatchers = (ref2 = (ref = staticInfo.middleware) == null ? void 0 : ref.matchers) != null ? ref2 : [
  255. {
  256. regexp: ".*"
  257. },
  258. ];
  259. if (target === "serverless") {
  260. throw new _utils1.MiddlewareInServerlessTargetError();
  261. }
  262. }
  263. await runDependingOnPageType({
  264. page,
  265. pageRuntime: staticInfo.runtime,
  266. onClient: ()=>{
  267. if (isServerComponent || isInsideAppDir) {
  268. // We skip the initial entries for server component pages and let the
  269. // server compiler inject them instead.
  270. } else {
  271. client[clientBundlePath] = getClientEntry({
  272. absolutePagePath: mappings[page],
  273. page
  274. });
  275. }
  276. },
  277. onServer: ()=>{
  278. if (pagesType === "app" && appDir) {
  279. const matchedAppPaths = appPathsPerRoute[(0, _appPaths).normalizeAppPath(page) || "/"];
  280. server[serverBundlePath] = getAppEntry({
  281. name: serverBundlePath,
  282. pagePath: mappings[page],
  283. appDir,
  284. appPaths: matchedAppPaths,
  285. pageExtensions
  286. });
  287. } else if ((0, _utils).isTargetLikeServerless(target)) {
  288. if (page !== "/_app" && page !== "/_document") {
  289. server[serverBundlePath] = getServerlessEntry({
  290. ...params,
  291. absolutePagePath: mappings[page],
  292. page
  293. });
  294. }
  295. } else {
  296. server[serverBundlePath] = [
  297. mappings[page]
  298. ];
  299. }
  300. },
  301. onEdgeServer: ()=>{
  302. let appDirLoader = "";
  303. if (pagesType === "app") {
  304. const matchedAppPaths = appPathsPerRoute[(0, _appPaths).normalizeAppPath(page) || "/"];
  305. appDirLoader = getAppEntry({
  306. name: serverBundlePath,
  307. pagePath: mappings[page],
  308. appDir: appDir,
  309. appPaths: matchedAppPaths,
  310. pageExtensions
  311. }).import;
  312. }
  313. edgeServer[serverBundlePath] = getEdgeServerEntry({
  314. ...params,
  315. rootDir,
  316. absolutePagePath: mappings[page],
  317. bundlePath: clientBundlePath,
  318. isDev: false,
  319. isServerComponent,
  320. page,
  321. middleware: staticInfo == null ? void 0 : staticInfo.middleware,
  322. pagesType,
  323. appDirLoader
  324. });
  325. }
  326. });
  327. };
  328. };
  329. if (appDir && appPaths) {
  330. const entryHandler = getEntryHandler(appPaths, "app");
  331. await Promise.all(Object.keys(appPaths).map(entryHandler));
  332. }
  333. if (rootPaths) {
  334. await Promise.all(Object.keys(rootPaths).map(getEntryHandler(rootPaths, "root")));
  335. }
  336. await Promise.all(Object.keys(pages).map(getEntryHandler(pages, "pages")));
  337. if (nestedMiddleware.length > 0) {
  338. throw new _utils1.NestedMiddlewareError(nestedMiddleware, rootDir, pagesDir);
  339. }
  340. return {
  341. client,
  342. server,
  343. edgeServer,
  344. middlewareMatchers
  345. };
  346. }
  347. function finalizeEntrypoint({ name , compilerType , value , isServerComponent , appDir }) {
  348. const entry = typeof value !== "object" || Array.isArray(value) ? {
  349. import: value
  350. } : value;
  351. const isApi = name.startsWith("pages/api/");
  352. if (compilerType === _constants1.COMPILER_NAMES.server) {
  353. return {
  354. publicPath: isApi ? "" : undefined,
  355. runtime: isApi ? "webpack-api-runtime" : "webpack-runtime",
  356. layer: isApi ? _constants.WEBPACK_LAYERS.api : isServerComponent ? _constants.WEBPACK_LAYERS.server : undefined,
  357. ...entry
  358. };
  359. }
  360. if (compilerType === _constants1.COMPILER_NAMES.edgeServer) {
  361. return {
  362. layer: (0, _utils1).isMiddlewareFilename(name) || isApi ? _constants.WEBPACK_LAYERS.middleware : undefined,
  363. library: {
  364. name: [
  365. "_ENTRIES",
  366. `middleware_[name]`
  367. ],
  368. type: "assign"
  369. },
  370. runtime: _constants1.EDGE_RUNTIME_WEBPACK,
  371. asyncChunks: false,
  372. ...entry
  373. };
  374. }
  375. if (// Client special cases
  376. name !== _constants1.CLIENT_STATIC_FILES_RUNTIME_POLYFILLS && name !== _constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN && name !== _constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN_APP && name !== _constants1.CLIENT_STATIC_FILES_RUNTIME_AMP && name !== _constants1.CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH) {
  377. // TODO-APP: this is a temporary fix. @shuding is going to change the handling of server components
  378. if (appDir && entry.import.includes("flight")) {
  379. return {
  380. dependOn: _constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
  381. ...entry
  382. };
  383. }
  384. return {
  385. dependOn: name.startsWith("pages/") && name !== "pages/_app" ? "pages/_app" : _constants1.CLIENT_STATIC_FILES_RUNTIME_MAIN,
  386. ...entry
  387. };
  388. }
  389. return entry;
  390. }
  391. //# sourceMappingURL=entries.js.map