next-dev-server.js 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _crypto = _interopRequireDefault(require("crypto"));
  7. var _fs = _interopRequireDefault(require("fs"));
  8. var _jestWorker = require("next/dist/compiled/jest-worker");
  9. var _findUp = _interopRequireDefault(require("next/dist/compiled/find-up"));
  10. var _path = require("path");
  11. var _react = _interopRequireDefault(require("react"));
  12. var _watchpack = _interopRequireDefault(require("next/dist/compiled/watchpack"));
  13. var _output = require("../../build/output");
  14. var _constants = require("../../lib/constants");
  15. var _fileExists = require("../../lib/file-exists");
  16. var _findPagesDir = require("../../lib/find-pages-dir");
  17. var _loadCustomRoutes = _interopRequireDefault(require("../../lib/load-custom-routes"));
  18. var _verifyTypeScriptSetup = require("../../lib/verifyTypeScriptSetup");
  19. var _verifyPartytownSetup = require("../../lib/verify-partytown-setup");
  20. var _constants1 = require("../../shared/lib/constants");
  21. var _nextServer = _interopRequireWildcard(require("../next-server"));
  22. var _routeMatcher = require("../../shared/lib/router/utils/route-matcher");
  23. var _middlewareRouteMatcher = require("../../shared/lib/router/utils/middleware-route-matcher");
  24. var _normalizePagePath = require("../../shared/lib/page-path/normalize-page-path");
  25. var _absolutePathToPage = require("../../shared/lib/page-path/absolute-path-to-page");
  26. var _router = _interopRequireDefault(require("../router"));
  27. var _pathMatch = require("../../shared/lib/router/utils/path-match");
  28. var _pathHasPrefix = require("../../shared/lib/router/utils/path-has-prefix");
  29. var _removePathPrefix = require("../../shared/lib/router/utils/remove-path-prefix");
  30. var _events = require("../../telemetry/events");
  31. var _storage = require("../../telemetry/storage");
  32. var _trace = require("../../trace");
  33. var _hotReloader = _interopRequireDefault(require("./hot-reloader"));
  34. var _findPageFile = require("../lib/find-page-file");
  35. var _utils = require("../lib/utils");
  36. var _coalescedFunction = require("../../lib/coalesced-function");
  37. var _loadComponents = require("../load-components");
  38. var _utils1 = require("../../shared/lib/utils");
  39. var _middleware = require("next/dist/compiled/@next/react-dev-overlay/dist/middleware");
  40. var Log = _interopRequireWildcard(require("../../build/output/log"));
  41. var _isError = _interopRequireWildcard(require("../../lib/is-error"));
  42. var _routeRegex = require("../../shared/lib/router/utils/route-regex");
  43. var _utils2 = require("../../shared/lib/router/utils");
  44. var _entries = require("../../build/entries");
  45. var _getPageStaticInfo = require("../../build/analysis/get-page-static-info");
  46. var _normalizePathSep = require("../../shared/lib/page-path/normalize-path-sep");
  47. var _appPaths = require("../../shared/lib/router/utils/app-paths");
  48. var _utils3 = require("../../build/utils");
  49. var _webpackConfig = require("../../build/webpack-config");
  50. var _loadJsconfig = _interopRequireDefault(require("../../build/load-jsconfig"));
  51. class DevServer extends _nextServer.default {
  52. addedUpgradeListener = false;
  53. getStaticPathsWorker() {
  54. if (this.staticPathsWorker) {
  55. return this.staticPathsWorker;
  56. }
  57. this.staticPathsWorker = new _jestWorker.Worker(require.resolve("./static-paths-worker"), {
  58. maxRetries: 1,
  59. numWorkers: this.nextConfig.experimental.cpus,
  60. enableWorkerThreads: this.nextConfig.experimental.workerThreads,
  61. forkOptions: {
  62. env: {
  63. ...process.env,
  64. // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers
  65. // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to
  66. // the number of workers Next.js tries to launch. The only worker users are interested in debugging
  67. // is the main Next.js one
  68. NODE_OPTIONS: (0, _utils).getNodeOptionsWithoutInspect()
  69. }
  70. }
  71. });
  72. this.staticPathsWorker.getStdout().pipe(process.stdout);
  73. this.staticPathsWorker.getStderr().pipe(process.stderr);
  74. return this.staticPathsWorker;
  75. }
  76. constructor(options){
  77. var ref, ref1;
  78. super({
  79. ...options,
  80. dev: true
  81. });
  82. this.renderOpts.dev = true;
  83. this.renderOpts.ErrorDebug = ReactDevOverlay;
  84. this.devReady = new Promise((resolve)=>{
  85. this.setDevReady = resolve;
  86. });
  87. var ref2;
  88. this.renderOpts.ampSkipValidation = (ref2 = (ref = this.nextConfig.experimental) == null ? void 0 : (ref1 = ref.amp) == null ? void 0 : ref1.skipValidation) != null ? ref2 : false;
  89. this.renderOpts.ampValidator = (html, pathname)=>{
  90. const validatorPath = this.nextConfig.experimental && this.nextConfig.experimental.amp && this.nextConfig.experimental.amp.validator;
  91. const AmpHtmlValidator = require("next/dist/compiled/amphtml-validator");
  92. return AmpHtmlValidator.getInstance(validatorPath).then((validator)=>{
  93. const result = validator.validateString(html);
  94. (0, _output).ampValidation(pathname, result.errors.filter((e)=>e.severity === "ERROR").filter((e)=>this._filterAmpDevelopmentScript(html, e)), result.errors.filter((e)=>e.severity !== "ERROR"));
  95. });
  96. };
  97. if (_fs.default.existsSync((0, _path).join(this.dir, "static"))) {
  98. console.warn(`The static directory has been deprecated in favor of the public directory. https://nextjs.org/docs/messages/static-dir-deprecated`);
  99. }
  100. // setup upgrade listener eagerly when we can otherwise
  101. // it will be done on the first request via req.socket.server
  102. if (options.httpServer) {
  103. this.setupWebSocketHandler(options.httpServer);
  104. }
  105. this.isCustomServer = !options.isNextDevCommand;
  106. // TODO: hot-reload root/pages dirs?
  107. const { pages: pagesDir , appDir } = (0, _findPagesDir).findPagesDir(this.dir, this.nextConfig.experimental.appDir);
  108. this.pagesDir = pagesDir;
  109. this.appDir = appDir;
  110. }
  111. getBuildId() {
  112. return "development";
  113. }
  114. async addExportPathMapRoutes() {
  115. // Makes `next export` exportPathMap work in development mode.
  116. // So that the user doesn't have to define a custom server reading the exportPathMap
  117. if (this.nextConfig.exportPathMap) {
  118. console.log("Defining routes from exportPathMap");
  119. const exportPathMap = await this.nextConfig.exportPathMap({}, {
  120. dev: true,
  121. dir: this.dir,
  122. outDir: null,
  123. distDir: this.distDir,
  124. buildId: this.buildId
  125. }) // In development we can't give a default path mapping
  126. ;
  127. for(const path in exportPathMap){
  128. const { page , query ={} } = exportPathMap[path];
  129. this.router.addFsRoute({
  130. match: (0, _pathMatch).getPathMatch(path),
  131. type: "route",
  132. name: `${path} exportpathmap route`,
  133. fn: async (req, res, _params, parsedUrl)=>{
  134. const { query: urlQuery } = parsedUrl;
  135. Object.keys(urlQuery).filter((key)=>query[key] === undefined).forEach((key)=>console.warn(`Url '${path}' defines a query parameter '${key}' that is missing in exportPathMap`));
  136. const mergedQuery = {
  137. ...urlQuery,
  138. ...query
  139. };
  140. await this.render(req, res, page, mergedQuery, parsedUrl, true);
  141. return {
  142. finished: true
  143. };
  144. }
  145. });
  146. }
  147. }
  148. }
  149. async startWatcher() {
  150. if (this.webpackWatcher) {
  151. return;
  152. }
  153. const regexPageExtension = new RegExp(`\\.+(?:${this.nextConfig.pageExtensions.join("|")})$`);
  154. let resolved = false;
  155. return new Promise(async (resolve, reject)=>{
  156. if (this.pagesDir) {
  157. // Watchpack doesn't emit an event for an empty directory
  158. _fs.default.readdir(this.pagesDir, (_, files)=>{
  159. if (files == null ? void 0 : files.length) {
  160. return;
  161. }
  162. if (!resolved) {
  163. resolve();
  164. resolved = true;
  165. }
  166. });
  167. }
  168. const pages = this.pagesDir ? [
  169. this.pagesDir
  170. ] : [];
  171. const app = this.appDir ? [
  172. this.appDir
  173. ] : [];
  174. const directories = [
  175. ...pages,
  176. ...app
  177. ];
  178. const files1 = this.pagesDir ? (0, _utils3).getPossibleMiddlewareFilenames((0, _path).join(this.pagesDir, ".."), this.nextConfig.pageExtensions) : [];
  179. let nestedMiddleware = [];
  180. const envFiles = [
  181. ".env.development.local",
  182. ".env.local",
  183. ".env.development",
  184. ".env",
  185. ].map((file)=>(0, _path).join(this.dir, file));
  186. files1.push(...envFiles);
  187. // tsconfig/jsonfig paths hot-reloading
  188. const tsconfigPaths = [
  189. (0, _path).join(this.dir, "tsconfig.json"),
  190. (0, _path).join(this.dir, "jsconfig.json"),
  191. ];
  192. files1.push(...tsconfigPaths);
  193. const wp = this.webpackWatcher = new _watchpack.default({
  194. ignored: (pathname)=>{
  195. return !files1.some((file)=>file.startsWith(pathname)) && !directories.some((dir)=>pathname.startsWith(dir));
  196. }
  197. });
  198. wp.watch({
  199. directories: [
  200. this.dir
  201. ],
  202. startTime: 0
  203. });
  204. const fileWatchTimes = new Map();
  205. let enabledTypeScript = this.usingTypeScript;
  206. wp.on("aggregated", async ()=>{
  207. let middlewareMatchers;
  208. const routedPages = [];
  209. const knownFiles = wp.getTimeInfoEntries();
  210. const appPaths = {};
  211. const edgeRoutesSet = new Set();
  212. let envChange = false;
  213. let tsconfigChange = false;
  214. for (const [fileName, meta] of knownFiles){
  215. if (!files1.includes(fileName) && !directories.some((dir)=>fileName.startsWith(dir))) {
  216. continue;
  217. }
  218. const watchTime = fileWatchTimes.get(fileName);
  219. const watchTimeChange = watchTime && watchTime !== (meta == null ? void 0 : meta.timestamp);
  220. fileWatchTimes.set(fileName, meta.timestamp);
  221. if (envFiles.includes(fileName)) {
  222. if (watchTimeChange) {
  223. envChange = true;
  224. }
  225. continue;
  226. }
  227. if (tsconfigPaths.includes(fileName)) {
  228. if (fileName.endsWith("tsconfig.json")) {
  229. enabledTypeScript = true;
  230. }
  231. if (watchTimeChange) {
  232. tsconfigChange = true;
  233. }
  234. continue;
  235. }
  236. if ((meta == null ? void 0 : meta.accuracy) === undefined || !regexPageExtension.test(fileName)) {
  237. continue;
  238. }
  239. const isAppPath = Boolean(this.appDir && (0, _normalizePathSep).normalizePathSep(fileName).startsWith((0, _normalizePathSep).normalizePathSep(this.appDir)));
  240. const rootFile = (0, _absolutePathToPage).absolutePathToPage(fileName, {
  241. pagesDir: this.dir,
  242. extensions: this.nextConfig.pageExtensions
  243. });
  244. const staticInfo = await (0, _getPageStaticInfo).getPageStaticInfo({
  245. pageFilePath: fileName,
  246. nextConfig: this.nextConfig,
  247. page: rootFile,
  248. isDev: true
  249. });
  250. if ((0, _utils3).isMiddlewareFile(rootFile)) {
  251. var ref;
  252. this.actualMiddlewareFile = rootFile;
  253. middlewareMatchers = ((ref = staticInfo.middleware) == null ? void 0 : ref.matchers) || [
  254. {
  255. regexp: ".*"
  256. },
  257. ];
  258. continue;
  259. }
  260. if (fileName.endsWith(".ts") || fileName.endsWith(".tsx")) {
  261. enabledTypeScript = true;
  262. }
  263. let pageName = (0, _absolutePathToPage).absolutePathToPage(fileName, {
  264. pagesDir: isAppPath ? this.appDir : this.pagesDir,
  265. extensions: this.nextConfig.pageExtensions,
  266. keepIndex: isAppPath
  267. });
  268. if (isAppPath) {
  269. if (!(0, _findPageFile).isLayoutsLeafPage(fileName)) {
  270. continue;
  271. }
  272. const originalPageName = pageName;
  273. pageName = (0, _appPaths).normalizeAppPath(pageName) || "/";
  274. if (!appPaths[pageName]) {
  275. appPaths[pageName] = [];
  276. }
  277. appPaths[pageName].push(originalPageName);
  278. if (routedPages.includes(pageName)) {
  279. continue;
  280. }
  281. } else {
  282. // /index is preserved for root folder
  283. pageName = pageName.replace(/\/index$/, "") || "/";
  284. }
  285. /**
  286. * If there is a middleware that is not declared in the root we will
  287. * warn without adding it so it doesn't make its way into the system.
  288. */ if (/[\\\\/]_middleware$/.test(pageName)) {
  289. nestedMiddleware.push(pageName);
  290. continue;
  291. }
  292. await (0, _entries).runDependingOnPageType({
  293. page: pageName,
  294. pageRuntime: staticInfo.runtime,
  295. onClient: ()=>{},
  296. onServer: ()=>{
  297. routedPages.push(pageName);
  298. },
  299. onEdgeServer: ()=>{
  300. routedPages.push(pageName);
  301. edgeRoutesSet.add(pageName);
  302. }
  303. });
  304. }
  305. if (!this.usingTypeScript && enabledTypeScript) {
  306. // we tolerate the error here as this is best effort
  307. // and the manual install command will be shown
  308. await this.verifyTypeScript().then(()=>{
  309. tsconfigChange = true;
  310. }).catch(()=>{});
  311. }
  312. if (envChange || tsconfigChange) {
  313. var ref3, ref4, ref5;
  314. if (envChange) {
  315. this.loadEnvConfig({
  316. dev: true,
  317. forceReload: true
  318. });
  319. }
  320. let tsconfigResult;
  321. if (tsconfigChange) {
  322. try {
  323. tsconfigResult = await (0, _loadJsconfig).default(this.dir, this.nextConfig);
  324. } catch (_) {
  325. /* do we want to log if there are syntax errors in tsconfig while editing? */ }
  326. }
  327. (ref3 = this.hotReloader) == null ? void 0 : (ref4 = ref3.activeConfigs) == null ? void 0 : ref4.forEach((config, idx)=>{
  328. const isClient = idx === 0;
  329. const isNodeServer = idx === 1;
  330. const isEdgeServer = idx === 2;
  331. const hasRewrites = this.customRoutes.rewrites.afterFiles.length > 0 || this.customRoutes.rewrites.beforeFiles.length > 0 || this.customRoutes.rewrites.fallback.length > 0;
  332. if (tsconfigChange) {
  333. var ref15, ref7;
  334. (ref15 = config.resolve) == null ? void 0 : (ref7 = ref15.plugins) == null ? void 0 : ref7.forEach((plugin)=>{
  335. // look for the JsConfigPathsPlugin and update with
  336. // the latest paths/baseUrl config
  337. if (plugin && plugin.jsConfigPlugin && tsconfigResult) {
  338. var ref, ref9, ref10;
  339. const { resolvedBaseUrl , jsConfig } = tsconfigResult;
  340. const currentResolvedBaseUrl = plugin.resolvedBaseUrl;
  341. const resolvedUrlIndex = (ref = config.resolve) == null ? void 0 : (ref9 = ref.modules) == null ? void 0 : ref9.findIndex((item)=>item === currentResolvedBaseUrl);
  342. if (resolvedBaseUrl && resolvedBaseUrl !== currentResolvedBaseUrl) {
  343. var ref11, ref12;
  344. // remove old baseUrl and add new one
  345. if (resolvedUrlIndex && resolvedUrlIndex > -1) {
  346. var ref13, ref14;
  347. (ref13 = config.resolve) == null ? void 0 : (ref14 = ref13.modules) == null ? void 0 : ref14.splice(resolvedUrlIndex, 1);
  348. }
  349. (ref11 = config.resolve) == null ? void 0 : (ref12 = ref11.modules) == null ? void 0 : ref12.push(resolvedBaseUrl);
  350. }
  351. if ((jsConfig == null ? void 0 : (ref10 = jsConfig.compilerOptions) == null ? void 0 : ref10.paths) && resolvedBaseUrl) {
  352. Object.keys(plugin.paths).forEach((key)=>{
  353. delete plugin.paths[key];
  354. });
  355. Object.assign(plugin.paths, jsConfig.compilerOptions.paths);
  356. plugin.resolvedBaseUrl = resolvedBaseUrl;
  357. }
  358. }
  359. });
  360. }
  361. if (envChange) {
  362. var ref8;
  363. (ref8 = config.plugins) == null ? void 0 : ref8.forEach((plugin)=>{
  364. // we look for the DefinePlugin definitions so we can
  365. // update them on the active compilers
  366. if (plugin && typeof plugin.definitions === "object" && plugin.definitions.__NEXT_DEFINE_ENV) {
  367. var ref;
  368. const newDefine = (0, _webpackConfig).getDefineEnv({
  369. dev: true,
  370. config: this.nextConfig,
  371. distDir: this.distDir,
  372. isClient,
  373. hasRewrites,
  374. hasReactRoot: (ref = this.hotReloader) == null ? void 0 : ref.hasReactRoot,
  375. isNodeServer,
  376. isEdgeServer
  377. });
  378. Object.keys(plugin.definitions).forEach((key)=>{
  379. if (!(key in newDefine)) {
  380. delete plugin.definitions[key];
  381. }
  382. });
  383. Object.assign(plugin.definitions, newDefine);
  384. }
  385. });
  386. }
  387. });
  388. (ref5 = this.hotReloader) == null ? void 0 : ref5.invalidate();
  389. }
  390. if (nestedMiddleware.length > 0) {
  391. Log.error(new _utils3.NestedMiddlewareError(nestedMiddleware, this.dir, this.pagesDir).message);
  392. nestedMiddleware = [];
  393. }
  394. // Make sure to sort parallel routes to make the result deterministic.
  395. this.appPathRoutes = Object.fromEntries(Object.entries(appPaths).map(([k, v])=>[
  396. k,
  397. v.sort()
  398. ]));
  399. const edgeRoutes = Array.from(edgeRoutesSet);
  400. this.edgeFunctions = (0, _utils2).getSortedRoutes(edgeRoutes).map((page)=>{
  401. const matchedAppPaths = this.getOriginalAppPaths(page);
  402. if (Array.isArray(matchedAppPaths)) {
  403. page = matchedAppPaths[0];
  404. }
  405. const edgeRegex = (0, _routeRegex).getRouteRegex(page);
  406. return {
  407. match: (0, _routeMatcher).getRouteMatcher(edgeRegex),
  408. page,
  409. re: edgeRegex.re
  410. };
  411. });
  412. this.middleware = middlewareMatchers ? {
  413. match: (0, _middlewareRouteMatcher).getMiddlewareRouteMatcher(middlewareMatchers),
  414. page: "/",
  415. matchers: middlewareMatchers
  416. } : undefined;
  417. try {
  418. var ref6;
  419. // we serve a separate manifest with all pages for the client in
  420. // dev mode so that we can match a page after a rewrite on the client
  421. // before it has been built and is populated in the _buildManifest
  422. const sortedRoutes = (0, _utils2).getSortedRoutes(routedPages);
  423. if (!((ref6 = this.sortedRoutes) == null ? void 0 : ref6.every((val, idx)=>val === sortedRoutes[idx]))) {
  424. // emit the change so clients fetch the update
  425. this.hotReloader.send(undefined, {
  426. devPagesManifest: true
  427. });
  428. }
  429. this.sortedRoutes = sortedRoutes;
  430. this.dynamicRoutes = this.sortedRoutes.filter(_utils2.isDynamicRoute).map((page)=>({
  431. page,
  432. match: (0, _routeMatcher).getRouteMatcher((0, _routeRegex).getRouteRegex(page))
  433. }));
  434. this.router.setDynamicRoutes(this.dynamicRoutes);
  435. this.router.setCatchallMiddleware(this.generateCatchAllMiddlewareRoute(true));
  436. if (!resolved) {
  437. resolve();
  438. resolved = true;
  439. }
  440. } catch (e) {
  441. if (!resolved) {
  442. reject(e);
  443. resolved = true;
  444. } else {
  445. console.warn("Failed to reload dynamic routes:", e);
  446. }
  447. }
  448. });
  449. });
  450. }
  451. async stopWatcher() {
  452. if (!this.webpackWatcher) {
  453. return;
  454. }
  455. this.webpackWatcher.close();
  456. this.webpackWatcher = null;
  457. }
  458. async verifyTypeScript() {
  459. if (this.verifyingTypeScript) {
  460. return;
  461. }
  462. try {
  463. this.verifyingTypeScript = true;
  464. const verifyResult = await (0, _verifyTypeScriptSetup).verifyTypeScriptSetup({
  465. dir: this.dir,
  466. intentDirs: [
  467. this.pagesDir,
  468. this.appDir
  469. ].filter(Boolean),
  470. typeCheckPreflight: false,
  471. tsconfigPath: this.nextConfig.typescript.tsconfigPath,
  472. disableStaticImages: this.nextConfig.images.disableStaticImages
  473. });
  474. if (verifyResult.version) {
  475. this.usingTypeScript = true;
  476. }
  477. } finally{
  478. this.verifyingTypeScript = false;
  479. }
  480. }
  481. async prepare() {
  482. (0, _trace).setGlobal("distDir", this.distDir);
  483. (0, _trace).setGlobal("phase", _constants1.PHASE_DEVELOPMENT_SERVER);
  484. await this.verifyTypeScript();
  485. this.customRoutes = await (0, _loadCustomRoutes).default(this.nextConfig);
  486. // reload router
  487. const { redirects , rewrites , headers } = this.customRoutes;
  488. if (rewrites.beforeFiles.length || rewrites.afterFiles.length || rewrites.fallback.length || redirects.length || headers.length) {
  489. this.router = new _router.default(this.generateRoutes());
  490. }
  491. this.hotReloader = new _hotReloader.default(this.dir, {
  492. pagesDir: this.pagesDir,
  493. distDir: this.distDir,
  494. config: this.nextConfig,
  495. previewProps: this.getPreviewProps(),
  496. buildId: this.buildId,
  497. rewrites,
  498. appDir: this.appDir
  499. });
  500. await super.prepare();
  501. await this.addExportPathMapRoutes();
  502. await this.hotReloader.start(true);
  503. await this.startWatcher();
  504. this.setDevReady();
  505. if (this.nextConfig.experimental.nextScriptWorkers) {
  506. await (0, _verifyPartytownSetup).verifyPartytownSetup(this.dir, (0, _path).join(this.distDir, _constants1.CLIENT_STATIC_FILES_PATH));
  507. }
  508. const telemetry = new _storage.Telemetry({
  509. distDir: this.distDir
  510. });
  511. telemetry.record((0, _events).eventCliSession(this.distDir, this.nextConfig, {
  512. webpackVersion: 5,
  513. cliCommand: "dev",
  514. isSrcDir: !!this.pagesDir && (0, _path).relative(this.dir, this.pagesDir).startsWith("src") || !!this.appDir && (0, _path).relative(this.dir, this.appDir).startsWith("src"),
  515. hasNowJson: !!await (0, _findUp).default("now.json", {
  516. cwd: this.dir
  517. }),
  518. isCustomServer: this.isCustomServer
  519. }));
  520. // This is required by the tracing subsystem.
  521. (0, _trace).setGlobal("telemetry", telemetry);
  522. process.on("unhandledRejection", (reason)=>{
  523. this.logErrorWithOriginalStack(reason, "unhandledRejection").catch(()=>{});
  524. });
  525. process.on("uncaughtException", (err)=>{
  526. this.logErrorWithOriginalStack(err, "uncaughtException").catch(()=>{});
  527. });
  528. }
  529. async close() {
  530. await this.stopWatcher();
  531. await this.getStaticPathsWorker().end();
  532. if (this.hotReloader) {
  533. await this.hotReloader.stop();
  534. }
  535. }
  536. async hasPage(pathname) {
  537. let normalizedPath;
  538. try {
  539. normalizedPath = (0, _normalizePagePath).normalizePagePath(pathname);
  540. } catch (err) {
  541. console.error(err);
  542. // if normalizing the page fails it means it isn't valid
  543. // so it doesn't exist so don't throw and return false
  544. // to ensure we return 404 instead of 500
  545. return false;
  546. }
  547. if ((0, _utils3).isMiddlewareFile(normalizedPath)) {
  548. return (0, _findPageFile).findPageFile(this.dir, normalizedPath, this.nextConfig.pageExtensions, false).then(Boolean);
  549. }
  550. // check appDir first if enabled
  551. if (this.appDir) {
  552. const pageFile = await (0, _findPageFile).findPageFile(this.appDir, normalizedPath, this.nextConfig.pageExtensions, true);
  553. if (pageFile) return true;
  554. }
  555. if (this.pagesDir) {
  556. const pageFile = await (0, _findPageFile).findPageFile(this.pagesDir, normalizedPath, this.nextConfig.pageExtensions, false);
  557. return !!pageFile;
  558. }
  559. return false;
  560. }
  561. async _beforeCatchAllRender(req, res, params, parsedUrl) {
  562. const { pathname } = parsedUrl;
  563. const pathParts = params.path || [];
  564. const path = `/${pathParts.join("/")}`;
  565. // check for a public file, throwing error if there's a
  566. // conflicting page
  567. let decodedPath;
  568. try {
  569. decodedPath = decodeURIComponent(path);
  570. } catch (_) {
  571. throw new _utils1.DecodeError("failed to decode param");
  572. }
  573. if (await this.hasPublicFile(decodedPath)) {
  574. if (await this.hasPage(pathname)) {
  575. const err = new Error(`A conflicting public file and page file was found for path ${pathname} https://nextjs.org/docs/messages/conflicting-public-file-page`);
  576. res.statusCode = 500;
  577. await this.renderError(err, req, res, pathname, {});
  578. return true;
  579. }
  580. await this.servePublic(req, res, pathParts);
  581. return true;
  582. }
  583. return false;
  584. }
  585. setupWebSocketHandler(server, _req) {
  586. if (!this.addedUpgradeListener) {
  587. var ref18;
  588. this.addedUpgradeListener = true;
  589. server = server || ((ref18 = _req == null ? void 0 : _req.originalRequest.socket) == null ? void 0 : ref18.server);
  590. if (!server) {
  591. // this is very unlikely to happen but show an error in case
  592. // it does somehow
  593. Log.error(`Invalid IncomingMessage received, make sure http.createServer is being used to handle requests.`);
  594. } else {
  595. const { basePath } = this.nextConfig;
  596. server.on("upgrade", (req, socket, head)=>{
  597. var ref;
  598. let assetPrefix = (this.nextConfig.assetPrefix || "").replace(/^\/+/, "");
  599. // assetPrefix can be a proxy server with a url locally
  600. // if so, it's needed to send these HMR requests with a rewritten url directly to /_next/webpack-hmr
  601. // otherwise account for a path-like prefix when listening to socket events
  602. if (assetPrefix.startsWith("http")) {
  603. assetPrefix = "";
  604. } else if (assetPrefix) {
  605. assetPrefix = `/${assetPrefix}`;
  606. }
  607. if ((ref = req.url) == null ? void 0 : ref.startsWith(`${basePath || assetPrefix || ""}/_next/webpack-hmr`)) {
  608. var ref17;
  609. (ref17 = this.hotReloader) == null ? void 0 : ref17.onHMR(req, socket, head);
  610. } else {
  611. this.handleUpgrade(req, socket, head);
  612. }
  613. });
  614. }
  615. }
  616. }
  617. async runMiddleware(params) {
  618. try {
  619. const result = await super.runMiddleware({
  620. ...params,
  621. onWarning: (warn)=>{
  622. this.logErrorWithOriginalStack(warn, "warning");
  623. }
  624. });
  625. if ("finished" in result) {
  626. return result;
  627. }
  628. result.waitUntil.catch((error)=>{
  629. this.logErrorWithOriginalStack(error, "unhandledRejection");
  630. });
  631. return result;
  632. } catch (error) {
  633. if (error instanceof _utils1.DecodeError) {
  634. throw error;
  635. }
  636. /**
  637. * We only log the error when it is not a MiddlewareNotFound error as
  638. * in that case we should be already displaying a compilation error
  639. * which is what makes the module not found.
  640. */ if (!(error instanceof _utils1.MiddlewareNotFoundError)) {
  641. this.logErrorWithOriginalStack(error);
  642. }
  643. const err = (0, _isError).getProperError(error);
  644. err.middleware = true;
  645. const { request , response , parsedUrl } = params;
  646. /**
  647. * When there is a failure for an internal Next.js request from
  648. * middleware we bypass the error without finishing the request
  649. * so we can serve the required chunks to render the error.
  650. */ if (request.url.includes("/_next/static") || request.url.includes("/__nextjs_original-stack-frame")) {
  651. return {
  652. finished: false
  653. };
  654. }
  655. response.statusCode = 500;
  656. this.renderError(err, request, response, parsedUrl.pathname);
  657. return {
  658. finished: true
  659. };
  660. }
  661. }
  662. async runEdgeFunction(params) {
  663. try {
  664. return super.runEdgeFunction({
  665. ...params,
  666. onWarning: (warn)=>{
  667. this.logErrorWithOriginalStack(warn, "warning");
  668. }
  669. });
  670. } catch (error) {
  671. if (error instanceof _utils1.DecodeError) {
  672. throw error;
  673. }
  674. this.logErrorWithOriginalStack(error, "warning");
  675. const err = (0, _isError).getProperError(error);
  676. const { req , res , page } = params;
  677. res.statusCode = 500;
  678. this.renderError(err, req, res, page);
  679. return null;
  680. }
  681. }
  682. async run(req, res, parsedUrl) {
  683. await this.devReady;
  684. this.setupWebSocketHandler(undefined, req);
  685. const { basePath } = this.nextConfig;
  686. let originalPathname = null;
  687. if (basePath && (0, _pathHasPrefix).pathHasPrefix(parsedUrl.pathname || "/", basePath)) {
  688. // strip basePath before handling dev bundles
  689. // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`
  690. originalPathname = parsedUrl.pathname;
  691. parsedUrl.pathname = (0, _removePathPrefix).removePathPrefix(parsedUrl.pathname || "/", basePath);
  692. }
  693. const { pathname } = parsedUrl;
  694. if (pathname.startsWith("/_next")) {
  695. if (await (0, _fileExists).fileExists((0, _path).join(this.publicDir, "_next"))) {
  696. throw new Error(_constants.PUBLIC_DIR_MIDDLEWARE_CONFLICT);
  697. }
  698. }
  699. const { finished =false } = await this.hotReloader.run(req.originalRequest, res.originalResponse, parsedUrl);
  700. if (finished) {
  701. return;
  702. }
  703. if (originalPathname) {
  704. // restore the path before continuing so that custom-routes can accurately determine
  705. // if they should match against the basePath or not
  706. parsedUrl.pathname = originalPathname;
  707. }
  708. try {
  709. return await super.run(req, res, parsedUrl);
  710. } catch (error) {
  711. res.statusCode = 500;
  712. const err = (0, _isError).getProperError(error);
  713. try {
  714. this.logErrorWithOriginalStack(err).catch(()=>{});
  715. return await this.renderError(err, req, res, pathname, {
  716. __NEXT_PAGE: (0, _isError).default(err) && err.page || pathname || ""
  717. });
  718. } catch (internalErr) {
  719. console.error(internalErr);
  720. res.body("Internal Server Error").send();
  721. }
  722. }
  723. }
  724. async logErrorWithOriginalStack(err, type) {
  725. let usedOriginalStack = false;
  726. if ((0, _isError).default(err) && err.stack) {
  727. try {
  728. const frames = (0, _middleware).parseStack(err.stack);
  729. const frame = frames.find(({ file })=>{
  730. return !(file == null ? void 0 : file.startsWith("eval")) && !(file == null ? void 0 : file.includes("web/adapter")) && !(file == null ? void 0 : file.includes("sandbox/context"));
  731. });
  732. if (frame.lineNumber && (frame == null ? void 0 : frame.file)) {
  733. var ref, ref20, ref21, ref22, ref23, ref24;
  734. const moduleId = frame.file.replace(/^(webpack-internal:\/\/\/|file:\/\/)/, "");
  735. const src = (0, _middleware).getErrorSource(err);
  736. const compilation = src === _constants1.COMPILER_NAMES.edgeServer ? (ref = this.hotReloader) == null ? void 0 : (ref20 = ref.edgeServerStats) == null ? void 0 : ref20.compilation : (ref21 = this.hotReloader) == null ? void 0 : (ref22 = ref21.serverStats) == null ? void 0 : ref22.compilation;
  737. const source = await (0, _middleware).getSourceById(!!((ref23 = frame.file) == null ? void 0 : ref23.startsWith(_path.sep)) || !!((ref24 = frame.file) == null ? void 0 : ref24.startsWith("file:")), moduleId, compilation);
  738. const originalFrame = await (0, _middleware).createOriginalStackFrame({
  739. line: frame.lineNumber,
  740. column: frame.column,
  741. source,
  742. frame,
  743. modulePath: moduleId,
  744. rootDirectory: this.dir,
  745. errorMessage: err.message,
  746. compilation
  747. });
  748. if (originalFrame) {
  749. const { originalCodeFrame , originalStackFrame } = originalFrame;
  750. const { file , lineNumber , column , methodName } = originalStackFrame;
  751. Log[type === "warning" ? "warn" : "error"](`${file} (${lineNumber}:${column}) @ ${methodName}`);
  752. if (src === _constants1.COMPILER_NAMES.edgeServer) {
  753. err = err.message;
  754. }
  755. if (type === "warning") {
  756. Log.warn(err);
  757. } else if (type) {
  758. Log.error(`${type}:`, err);
  759. } else {
  760. Log.error(err);
  761. }
  762. console[type === "warning" ? "warn" : "error"](originalCodeFrame);
  763. usedOriginalStack = true;
  764. }
  765. }
  766. } catch (_) {
  767. // failed to load original stack using source maps
  768. // this un-actionable by users so we don't show the
  769. // internal error and only show the provided stack
  770. }
  771. }
  772. if (!usedOriginalStack) {
  773. if (type === "warning") {
  774. Log.warn(err);
  775. } else if (type) {
  776. Log.error(`${type}:`, err);
  777. } else {
  778. Log.error(err);
  779. }
  780. }
  781. }
  782. // override production loading of routes-manifest
  783. getCustomRoutes() {
  784. // actual routes will be loaded asynchronously during .prepare()
  785. return {
  786. redirects: [],
  787. rewrites: {
  788. beforeFiles: [],
  789. afterFiles: [],
  790. fallback: []
  791. },
  792. headers: []
  793. };
  794. }
  795. getPreviewProps() {
  796. if (this._devCachedPreviewProps) {
  797. return this._devCachedPreviewProps;
  798. }
  799. return this._devCachedPreviewProps = {
  800. previewModeId: _crypto.default.randomBytes(16).toString("hex"),
  801. previewModeSigningKey: _crypto.default.randomBytes(32).toString("hex"),
  802. previewModeEncryptionKey: _crypto.default.randomBytes(32).toString("hex")
  803. };
  804. }
  805. getPagesManifest() {
  806. return undefined;
  807. }
  808. getAppPathsManifest() {
  809. return undefined;
  810. }
  811. getMiddleware() {
  812. return this.middleware;
  813. }
  814. getEdgeFunctions() {
  815. var _edgeFunctions;
  816. return (_edgeFunctions = this.edgeFunctions) != null ? _edgeFunctions : [];
  817. }
  818. getServerComponentManifest() {
  819. return undefined;
  820. }
  821. getServerCSSManifest() {
  822. return undefined;
  823. }
  824. async hasMiddleware() {
  825. return this.hasPage(this.actualMiddlewareFile);
  826. }
  827. async ensureMiddleware() {
  828. return this.hotReloader.ensurePage({
  829. page: this.actualMiddlewareFile,
  830. clientOnly: false
  831. });
  832. }
  833. async ensureEdgeFunction({ page , appPaths }) {
  834. return this.hotReloader.ensurePage({
  835. page,
  836. appPaths,
  837. clientOnly: false
  838. });
  839. }
  840. generateRoutes() {
  841. const { fsRoutes , ...otherRoutes } = super.generateRoutes();
  842. // In development we expose all compiled files for react-error-overlay's line show feature
  843. // We use unshift so that we're sure the routes is defined before Next's default routes
  844. fsRoutes.unshift({
  845. match: (0, _pathMatch).getPathMatch("/_next/development/:path*"),
  846. type: "route",
  847. name: "_next/development catchall",
  848. fn: async (req, res, params)=>{
  849. const p = (0, _path).join(this.distDir, ...params.path || []);
  850. await this.serveStatic(req, res, p);
  851. return {
  852. finished: true
  853. };
  854. }
  855. });
  856. fsRoutes.unshift({
  857. match: (0, _pathMatch).getPathMatch(`/_next/${_constants1.CLIENT_STATIC_FILES_PATH}/${this.buildId}/${_constants1.DEV_CLIENT_PAGES_MANIFEST}`),
  858. type: "route",
  859. name: `_next/${_constants1.CLIENT_STATIC_FILES_PATH}/${this.buildId}/${_constants1.DEV_CLIENT_PAGES_MANIFEST}`,
  860. fn: async (_req, res)=>{
  861. res.statusCode = 200;
  862. res.setHeader("Content-Type", "application/json; charset=utf-8");
  863. res.body(JSON.stringify({
  864. pages: this.sortedRoutes
  865. })).send();
  866. return {
  867. finished: true
  868. };
  869. }
  870. });
  871. fsRoutes.unshift({
  872. match: (0, _pathMatch).getPathMatch(`/_next/${_constants1.CLIENT_STATIC_FILES_PATH}/${this.buildId}/${_constants1.DEV_MIDDLEWARE_MANIFEST}`),
  873. type: "route",
  874. name: `_next/${_constants1.CLIENT_STATIC_FILES_PATH}/${this.buildId}/${_constants1.DEV_MIDDLEWARE_MANIFEST}`,
  875. fn: async (_req, res)=>{
  876. var ref;
  877. res.statusCode = 200;
  878. res.setHeader("Content-Type", "application/json; charset=utf-8");
  879. var ref25;
  880. res.body(JSON.stringify((ref25 = (ref = this.getMiddleware()) == null ? void 0 : ref.matchers) != null ? ref25 : [])).send();
  881. return {
  882. finished: true
  883. };
  884. }
  885. });
  886. fsRoutes.push({
  887. match: (0, _pathMatch).getPathMatch("/:path*"),
  888. type: "route",
  889. name: "catchall public directory route",
  890. fn: async (req, res, params, parsedUrl)=>{
  891. const { pathname } = parsedUrl;
  892. if (!pathname) {
  893. throw new Error("pathname is undefined");
  894. }
  895. // Used in development to check public directory paths
  896. if (await this._beforeCatchAllRender(req, res, params, parsedUrl)) {
  897. return {
  898. finished: true
  899. };
  900. }
  901. return {
  902. finished: false
  903. };
  904. }
  905. });
  906. return {
  907. fsRoutes,
  908. ...otherRoutes
  909. };
  910. }
  911. // In development public files are not added to the router but handled as a fallback instead
  912. generatePublicRoutes() {
  913. return [];
  914. }
  915. // In development dynamic routes cannot be known ahead of time
  916. getDynamicRoutes() {
  917. return [];
  918. }
  919. _filterAmpDevelopmentScript(html, event) {
  920. if (event.code !== "DISALLOWED_SCRIPT_TAG") {
  921. return true;
  922. }
  923. const snippetChunks = html.split("\n");
  924. let snippet;
  925. if (!(snippet = html.split("\n")[event.line - 1]) || !(snippet = snippet.substring(event.col))) {
  926. return true;
  927. }
  928. snippet = snippet + snippetChunks.slice(event.line).join("\n");
  929. snippet = snippet.substring(0, snippet.indexOf("</script>"));
  930. return !snippet.includes("data-amp-development-mode-only");
  931. }
  932. async getStaticPaths({ pathname , originalAppPath }) {
  933. // we lazy load the staticPaths to prevent the user
  934. // from waiting on them for the page to load in dev mode
  935. const __getStaticPaths = async ()=>{
  936. const { configFileName , publicRuntimeConfig , serverRuntimeConfig , httpAgentOptions , } = this.nextConfig;
  937. const { locales , defaultLocale } = this.nextConfig.i18n || {};
  938. const pathsResult = await this.getStaticPathsWorker().loadStaticPaths({
  939. distDir: this.distDir,
  940. pathname,
  941. serverless: !this.renderOpts.dev && this._isLikeServerless,
  942. config: {
  943. configFileName,
  944. publicRuntimeConfig,
  945. serverRuntimeConfig
  946. },
  947. httpAgentOptions,
  948. locales,
  949. defaultLocale,
  950. originalAppPath,
  951. isAppPath: !!originalAppPath
  952. });
  953. return pathsResult;
  954. };
  955. const { paths: staticPaths , fallback } = (await (0, _coalescedFunction).withCoalescedInvoke(__getStaticPaths)(`staticPaths-${pathname}`, [])).value;
  956. return {
  957. staticPaths,
  958. fallbackMode: fallback === "blocking" ? "blocking" : fallback === true ? "static" : fallback
  959. };
  960. }
  961. async ensureApiPage(pathname) {
  962. return this.hotReloader.ensurePage({
  963. page: pathname,
  964. clientOnly: false
  965. });
  966. }
  967. async findPageComponents({ pathname , query , params , isAppPath , appPaths }) {
  968. await this.devReady;
  969. const compilationErr = await this.getCompilationError(pathname);
  970. if (compilationErr) {
  971. // Wrap build errors so that they don't get logged again
  972. throw new _nextServer.WrappedBuildError(compilationErr);
  973. }
  974. try {
  975. await this.hotReloader.ensurePage({
  976. page: pathname,
  977. appPaths,
  978. clientOnly: false
  979. });
  980. const serverComponents = this.nextConfig.experimental.serverComponents;
  981. // When the new page is compiled, we need to reload the server component
  982. // manifest.
  983. if (serverComponents) {
  984. this.serverComponentManifest = super.getServerComponentManifest();
  985. this.serverCSSManifest = super.getServerCSSManifest();
  986. }
  987. return super.findPageComponents({
  988. pathname,
  989. query,
  990. params,
  991. isAppPath
  992. });
  993. } catch (err) {
  994. if (err.code !== "ENOENT") {
  995. throw err;
  996. }
  997. return null;
  998. }
  999. }
  1000. async getFallbackErrorComponents() {
  1001. await this.hotReloader.buildFallbackError();
  1002. // Build the error page to ensure the fallback is built too.
  1003. // TODO: See if this can be moved into hotReloader or removed.
  1004. await this.hotReloader.ensurePage({
  1005. page: "/_error",
  1006. clientOnly: false
  1007. });
  1008. return await (0, _loadComponents).loadDefaultErrorComponents(this.distDir);
  1009. }
  1010. setImmutableAssetCacheControl(res) {
  1011. res.setHeader("Cache-Control", "no-store, must-revalidate");
  1012. }
  1013. servePublic(req, res, pathParts) {
  1014. const p = (0, _path).join(this.publicDir, ...pathParts);
  1015. return this.serveStatic(req, res, p);
  1016. }
  1017. async hasPublicFile(path) {
  1018. try {
  1019. const info = await _fs.default.promises.stat((0, _path).join(this.publicDir, path));
  1020. return info.isFile();
  1021. } catch (_) {
  1022. return false;
  1023. }
  1024. }
  1025. async getCompilationError(page) {
  1026. const errors = await this.hotReloader.getCompilationErrors(page);
  1027. if (errors.length === 0) return;
  1028. // Return the very first error we found.
  1029. return errors[0];
  1030. }
  1031. isServeableUrl(untrustedFileUrl) {
  1032. // This method mimics what the version of `send` we use does:
  1033. // 1. decodeURIComponent:
  1034. // https://github.com/pillarjs/send/blob/0.17.1/index.js#L989
  1035. // https://github.com/pillarjs/send/blob/0.17.1/index.js#L518-L522
  1036. // 2. resolve:
  1037. // https://github.com/pillarjs/send/blob/de073ed3237ade9ff71c61673a34474b30e5d45b/index.js#L561
  1038. let decodedUntrustedFilePath;
  1039. try {
  1040. // (1) Decode the URL so we have the proper file name
  1041. decodedUntrustedFilePath = decodeURIComponent(untrustedFileUrl);
  1042. } catch {
  1043. return false;
  1044. }
  1045. // (2) Resolve "up paths" to determine real request
  1046. const untrustedFilePath = (0, _path).resolve(decodedUntrustedFilePath);
  1047. // don't allow null bytes anywhere in the file path
  1048. if (untrustedFilePath.indexOf("\0") !== -1) {
  1049. return false;
  1050. }
  1051. // During development mode, files can be added while the server is running.
  1052. // Checks for .next/static, .next/server, static and public.
  1053. // Note that in development .next/server is available for error reporting purposes.
  1054. // see `packages/next/server/next-server.ts` for more details.
  1055. if (untrustedFilePath.startsWith((0, _path).join(this.distDir, "static") + _path.sep) || untrustedFilePath.startsWith((0, _path).join(this.distDir, "server") + _path.sep) || untrustedFilePath.startsWith((0, _path).join(this.dir, "static") + _path.sep) || untrustedFilePath.startsWith((0, _path).join(this.dir, "public") + _path.sep)) {
  1056. return true;
  1057. }
  1058. return false;
  1059. }
  1060. }
  1061. exports.default = DevServer;
  1062. function _interopRequireDefault(obj) {
  1063. return obj && obj.__esModule ? obj : {
  1064. default: obj
  1065. };
  1066. }
  1067. function _getRequireWildcardCache() {
  1068. if (typeof WeakMap !== "function") return null;
  1069. var cache = new WeakMap();
  1070. _getRequireWildcardCache = function() {
  1071. return cache;
  1072. };
  1073. return cache;
  1074. }
  1075. function _interopRequireWildcard(obj) {
  1076. if (obj && obj.__esModule) {
  1077. return obj;
  1078. }
  1079. if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
  1080. return {
  1081. default: obj
  1082. };
  1083. }
  1084. var cache = _getRequireWildcardCache();
  1085. if (cache && cache.has(obj)) {
  1086. return cache.get(obj);
  1087. }
  1088. var newObj = {};
  1089. var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
  1090. for(var key in obj){
  1091. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1092. var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
  1093. if (desc && (desc.get || desc.set)) {
  1094. Object.defineProperty(newObj, key, desc);
  1095. } else {
  1096. newObj[key] = obj[key];
  1097. }
  1098. }
  1099. }
  1100. newObj.default = obj;
  1101. if (cache) {
  1102. cache.set(obj, newObj);
  1103. }
  1104. return newObj;
  1105. }
  1106. // Load ReactDevOverlay only when needed
  1107. let ReactDevOverlayImpl;
  1108. const ReactDevOverlay = (props)=>{
  1109. if (ReactDevOverlayImpl === undefined) {
  1110. ReactDevOverlayImpl = require("next/dist/compiled/@next/react-dev-overlay/dist/client").ReactDevOverlay;
  1111. }
  1112. return ReactDevOverlayImpl(props);
  1113. };
  1114. //# sourceMappingURL=next-dev-server.js.map