router.js 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.matchesMiddleware = matchesMiddleware;
  6. exports.isLocalURL = isLocalURL;
  7. exports.interpolateAs = interpolateAs;
  8. exports.resolveHref = resolveHref;
  9. exports.createKey = createKey;
  10. exports.default = void 0;
  11. var _async_to_generator = require("@swc/helpers/lib/_async_to_generator.js").default;
  12. var _extends = require("@swc/helpers/lib/_extends.js").default;
  13. var _interop_require_default = require("@swc/helpers/lib/_interop_require_default.js").default;
  14. var _interop_require_wildcard = require("@swc/helpers/lib/_interop_require_wildcard.js").default;
  15. var _normalizeTrailingSlash = require("../../../client/normalize-trailing-slash");
  16. var _removeTrailingSlash = require("./utils/remove-trailing-slash");
  17. var _routeLoader = require("../../../client/route-loader");
  18. var _script = require("../../../client/script");
  19. var _isError = _interop_require_wildcard(require("../../../lib/is-error"));
  20. var _denormalizePagePath = require("../page-path/denormalize-page-path");
  21. var _normalizeLocalePath = require("../i18n/normalize-locale-path");
  22. var _mitt = _interop_require_default(require("../mitt"));
  23. var _utils = require("../utils");
  24. var _isDynamic = require("./utils/is-dynamic");
  25. var _parseRelativeUrl = require("./utils/parse-relative-url");
  26. var _querystring = require("./utils/querystring");
  27. var _resolveRewrites = _interop_require_default(require("./utils/resolve-rewrites"));
  28. var _routeMatcher = require("./utils/route-matcher");
  29. var _routeRegex = require("./utils/route-regex");
  30. var _formatUrl = require("./utils/format-url");
  31. var _detectDomainLocale = require("../../../client/detect-domain-locale");
  32. var _parsePath = require("./utils/parse-path");
  33. var _addLocale = require("../../../client/add-locale");
  34. var _removeLocale = require("../../../client/remove-locale");
  35. var _removeBasePath = require("../../../client/remove-base-path");
  36. var _addBasePath = require("../../../client/add-base-path");
  37. var _hasBasePath = require("../../../client/has-base-path");
  38. var _getNextPathnameInfo = require("./utils/get-next-pathname-info");
  39. var _formatNextPathnameInfo = require("./utils/format-next-pathname-info");
  40. var _compareStates = require("./utils/compare-states");
  41. var _isBot = require("./utils/is-bot");
  42. function buildCancellationError() {
  43. return Object.assign(new Error('Route Cancelled'), {
  44. cancelled: true
  45. });
  46. }
  47. function matchesMiddleware(options) {
  48. return _matchesMiddleware.apply(this, arguments);
  49. }
  50. function _matchesMiddleware() {
  51. _matchesMiddleware = _async_to_generator(function*(options) {
  52. const matchers = yield Promise.resolve(options.router.pageLoader.getMiddleware());
  53. if (!matchers) return false;
  54. const { pathname: asPathname } = (0, _parsePath).parsePath(options.asPath);
  55. // remove basePath first since path prefix has to be in the order of `/${basePath}/${locale}`
  56. const cleanedAs = (0, _hasBasePath).hasBasePath(asPathname) ? (0, _removeBasePath).removeBasePath(asPathname) : asPathname;
  57. const asWithBasePathAndLocale = (0, _addBasePath).addBasePath((0, _addLocale).addLocale(cleanedAs, options.locale));
  58. // Check only path match on client. Matching "has" should be done on server
  59. // where we can access more info such as headers, HttpOnly cookie, etc.
  60. return matchers.some((m)=>new RegExp(m.regexp).test(asWithBasePathAndLocale));
  61. });
  62. return _matchesMiddleware.apply(this, arguments);
  63. }
  64. function stripOrigin(url) {
  65. const origin = (0, _utils).getLocationOrigin();
  66. return url.startsWith(origin) ? url.substring(origin.length) : url;
  67. }
  68. function omit(object, keys) {
  69. const omitted = {};
  70. Object.keys(object).forEach((key)=>{
  71. if (!keys.includes(key)) {
  72. omitted[key] = object[key];
  73. }
  74. });
  75. return omitted;
  76. }
  77. function isLocalURL(url) {
  78. // prevent a hydration mismatch on href for url with anchor refs
  79. if (!(0, _utils).isAbsoluteUrl(url)) return true;
  80. try {
  81. // absolute urls can be local if they are on the same origin
  82. const locationOrigin = (0, _utils).getLocationOrigin();
  83. const resolved = new URL(url, locationOrigin);
  84. return resolved.origin === locationOrigin && (0, _hasBasePath).hasBasePath(resolved.pathname);
  85. } catch (_) {
  86. return false;
  87. }
  88. }
  89. function interpolateAs(route, asPathname, query) {
  90. let interpolatedRoute = '';
  91. const dynamicRegex = (0, _routeRegex).getRouteRegex(route);
  92. const dynamicGroups = dynamicRegex.groups;
  93. const dynamicMatches = // Try to match the dynamic route against the asPath
  94. (asPathname !== route ? (0, _routeMatcher).getRouteMatcher(dynamicRegex)(asPathname) : '') || // Fall back to reading the values from the href
  95. // TODO: should this take priority; also need to change in the router.
  96. query;
  97. interpolatedRoute = route;
  98. const params = Object.keys(dynamicGroups);
  99. if (!params.every((param)=>{
  100. let value = dynamicMatches[param] || '';
  101. const { repeat , optional } = dynamicGroups[param];
  102. // support single-level catch-all
  103. // TODO: more robust handling for user-error (passing `/`)
  104. let replaced = `[${repeat ? '...' : ''}${param}]`;
  105. if (optional) {
  106. replaced = `${!value ? '/' : ''}[${replaced}]`;
  107. }
  108. if (repeat && !Array.isArray(value)) value = [
  109. value
  110. ];
  111. return (optional || param in dynamicMatches) && // Interpolate group into data URL if present
  112. (interpolatedRoute = interpolatedRoute.replace(replaced, repeat ? value.map(// these values should be fully encoded instead of just
  113. // path delimiter escaped since they are being inserted
  114. // into the URL and we expect URL encoded segments
  115. // when parsing dynamic route params
  116. (segment)=>encodeURIComponent(segment)).join('/') : encodeURIComponent(value)) || '/');
  117. })) {
  118. interpolatedRoute = '' // did not satisfy all requirements
  119. ;
  120. // n.b. We ignore this error because we handle warning for this case in
  121. // development in the `<Link>` component directly.
  122. }
  123. return {
  124. params,
  125. result: interpolatedRoute
  126. };
  127. }
  128. function resolveHref(router, href, resolveAs) {
  129. // we use a dummy base url for relative urls
  130. let base;
  131. let urlAsString = typeof href === 'string' ? href : (0, _formatUrl).formatWithValidation(href);
  132. // repeated slashes and backslashes in the URL are considered
  133. // invalid and will never match a Next.js page/file
  134. const urlProtoMatch = urlAsString.match(/^[a-zA-Z]{1,}:\/\//);
  135. const urlAsStringNoProto = urlProtoMatch ? urlAsString.slice(urlProtoMatch[0].length) : urlAsString;
  136. const urlParts = urlAsStringNoProto.split('?');
  137. if ((urlParts[0] || '').match(/(\/\/|\\)/)) {
  138. console.error(`Invalid href passed to next/router: ${urlAsString}, repeated forward-slashes (//) or backslashes \\ are not valid in the href`);
  139. const normalizedUrl = (0, _utils).normalizeRepeatedSlashes(urlAsStringNoProto);
  140. urlAsString = (urlProtoMatch ? urlProtoMatch[0] : '') + normalizedUrl;
  141. }
  142. // Return because it cannot be routed by the Next.js router
  143. if (!isLocalURL(urlAsString)) {
  144. return resolveAs ? [
  145. urlAsString
  146. ] : urlAsString;
  147. }
  148. try {
  149. base = new URL(urlAsString.startsWith('#') ? router.asPath : router.pathname, 'http://n');
  150. } catch (_) {
  151. // fallback to / for invalid asPath values e.g. //
  152. base = new URL('/', 'http://n');
  153. }
  154. try {
  155. const finalUrl = new URL(urlAsString, base);
  156. finalUrl.pathname = (0, _normalizeTrailingSlash).normalizePathTrailingSlash(finalUrl.pathname);
  157. let interpolatedAs = '';
  158. if ((0, _isDynamic).isDynamicRoute(finalUrl.pathname) && finalUrl.searchParams && resolveAs) {
  159. const query = (0, _querystring).searchParamsToUrlQuery(finalUrl.searchParams);
  160. const { result , params } = interpolateAs(finalUrl.pathname, finalUrl.pathname, query);
  161. if (result) {
  162. interpolatedAs = (0, _formatUrl).formatWithValidation({
  163. pathname: result,
  164. hash: finalUrl.hash,
  165. query: omit(query, params)
  166. });
  167. }
  168. }
  169. // if the origin didn't change, it means we received a relative href
  170. const resolvedHref = finalUrl.origin === base.origin ? finalUrl.href.slice(finalUrl.origin.length) : finalUrl.href;
  171. return resolveAs ? [
  172. resolvedHref,
  173. interpolatedAs || resolvedHref
  174. ] : resolvedHref;
  175. } catch (_1) {
  176. return resolveAs ? [
  177. urlAsString
  178. ] : urlAsString;
  179. }
  180. }
  181. function prepareUrlAs(router, url, as) {
  182. // If url and as provided as an object representation,
  183. // we'll format them into the string version here.
  184. let [resolvedHref, resolvedAs] = resolveHref(router, url, true);
  185. const origin = (0, _utils).getLocationOrigin();
  186. const hrefHadOrigin = resolvedHref.startsWith(origin);
  187. const asHadOrigin = resolvedAs && resolvedAs.startsWith(origin);
  188. resolvedHref = stripOrigin(resolvedHref);
  189. resolvedAs = resolvedAs ? stripOrigin(resolvedAs) : resolvedAs;
  190. const preparedUrl = hrefHadOrigin ? resolvedHref : (0, _addBasePath).addBasePath(resolvedHref);
  191. const preparedAs = as ? stripOrigin(resolveHref(router, as)) : resolvedAs || resolvedHref;
  192. return {
  193. url: preparedUrl,
  194. as: asHadOrigin ? preparedAs : (0, _addBasePath).addBasePath(preparedAs)
  195. };
  196. }
  197. function resolveDynamicRoute(pathname, pages) {
  198. const cleanPathname = (0, _removeTrailingSlash).removeTrailingSlash((0, _denormalizePagePath).denormalizePagePath(pathname));
  199. if (cleanPathname === '/404' || cleanPathname === '/_error') {
  200. return pathname;
  201. }
  202. // handle resolving href for dynamic routes
  203. if (!pages.includes(cleanPathname)) {
  204. // eslint-disable-next-line array-callback-return
  205. pages.some((page)=>{
  206. if ((0, _isDynamic).isDynamicRoute(page) && (0, _routeRegex).getRouteRegex(page).re.test(cleanPathname)) {
  207. pathname = page;
  208. return true;
  209. }
  210. });
  211. }
  212. return (0, _removeTrailingSlash).removeTrailingSlash(pathname);
  213. }
  214. function getMiddlewareData(source, response, options) {
  215. const nextConfig = {
  216. basePath: options.router.basePath,
  217. i18n: {
  218. locales: options.router.locales
  219. },
  220. trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH)
  221. };
  222. const rewriteHeader = response.headers.get('x-nextjs-rewrite');
  223. let rewriteTarget = rewriteHeader || response.headers.get('x-nextjs-matched-path');
  224. const matchedPath = response.headers.get('x-matched-path');
  225. if (matchedPath && !rewriteTarget && !matchedPath.includes('__next_data_catchall') && !matchedPath.includes('/_error') && !matchedPath.includes('/404')) {
  226. // leverage x-matched-path to detect next.config.js rewrites
  227. rewriteTarget = matchedPath;
  228. }
  229. if (rewriteTarget) {
  230. if (rewriteTarget.startsWith('/')) {
  231. const parsedRewriteTarget = (0, _parseRelativeUrl).parseRelativeUrl(rewriteTarget);
  232. const pathnameInfo = (0, _getNextPathnameInfo).getNextPathnameInfo(parsedRewriteTarget.pathname, {
  233. nextConfig,
  234. parseData: true
  235. });
  236. let fsPathname = (0, _removeTrailingSlash).removeTrailingSlash(pathnameInfo.pathname);
  237. return Promise.all([
  238. options.router.pageLoader.getPageList(),
  239. (0, _routeLoader).getClientBuildManifest(),
  240. ]).then(([pages, { __rewrites: rewrites }])=>{
  241. let as = (0, _addLocale).addLocale(pathnameInfo.pathname, pathnameInfo.locale);
  242. if ((0, _isDynamic).isDynamicRoute(as) || !rewriteHeader && pages.includes((0, _normalizeLocalePath).normalizeLocalePath((0, _removeBasePath).removeBasePath(as), options.router.locales).pathname)) {
  243. const parsedSource = (0, _getNextPathnameInfo).getNextPathnameInfo((0, _parseRelativeUrl).parseRelativeUrl(source).pathname, {
  244. parseData: true
  245. });
  246. as = (0, _addBasePath).addBasePath(parsedSource.pathname);
  247. parsedRewriteTarget.pathname = as;
  248. }
  249. if (process.env.__NEXT_HAS_REWRITES) {
  250. const result = (0, _resolveRewrites).default(as, pages, rewrites, parsedRewriteTarget.query, (path)=>resolveDynamicRoute(path, pages), options.router.locales);
  251. if (result.matchedPage) {
  252. parsedRewriteTarget.pathname = result.parsedAs.pathname;
  253. as = parsedRewriteTarget.pathname;
  254. Object.assign(parsedRewriteTarget.query, result.parsedAs.query);
  255. }
  256. } else if (!pages.includes(fsPathname)) {
  257. const resolvedPathname = resolveDynamicRoute(fsPathname, pages);
  258. if (resolvedPathname !== fsPathname) {
  259. fsPathname = resolvedPathname;
  260. }
  261. }
  262. const resolvedHref = !pages.includes(fsPathname) ? resolveDynamicRoute((0, _normalizeLocalePath).normalizeLocalePath((0, _removeBasePath).removeBasePath(parsedRewriteTarget.pathname), options.router.locales).pathname, pages) : fsPathname;
  263. if ((0, _isDynamic).isDynamicRoute(resolvedHref)) {
  264. const matches = (0, _routeMatcher).getRouteMatcher((0, _routeRegex).getRouteRegex(resolvedHref))(as);
  265. Object.assign(parsedRewriteTarget.query, matches || {});
  266. }
  267. return {
  268. type: 'rewrite',
  269. parsedAs: parsedRewriteTarget,
  270. resolvedHref
  271. };
  272. });
  273. }
  274. const src = (0, _parsePath).parsePath(source);
  275. const pathname = (0, _formatNextPathnameInfo).formatNextPathnameInfo(_extends({}, (0, _getNextPathnameInfo).getNextPathnameInfo(src.pathname, {
  276. nextConfig,
  277. parseData: true
  278. }), {
  279. defaultLocale: options.router.defaultLocale,
  280. buildId: ''
  281. }));
  282. return Promise.resolve({
  283. type: 'redirect-external',
  284. destination: `${pathname}${src.query}${src.hash}`
  285. });
  286. }
  287. const redirectTarget = response.headers.get('x-nextjs-redirect');
  288. if (redirectTarget) {
  289. if (redirectTarget.startsWith('/')) {
  290. const src = (0, _parsePath).parsePath(redirectTarget);
  291. const pathname = (0, _formatNextPathnameInfo).formatNextPathnameInfo(_extends({}, (0, _getNextPathnameInfo).getNextPathnameInfo(src.pathname, {
  292. nextConfig,
  293. parseData: true
  294. }), {
  295. defaultLocale: options.router.defaultLocale,
  296. buildId: ''
  297. }));
  298. return Promise.resolve({
  299. type: 'redirect-internal',
  300. newAs: `${pathname}${src.query}${src.hash}`,
  301. newUrl: `${pathname}${src.query}${src.hash}`
  302. });
  303. }
  304. return Promise.resolve({
  305. type: 'redirect-external',
  306. destination: redirectTarget
  307. });
  308. }
  309. return Promise.resolve({
  310. type: 'next'
  311. });
  312. }
  313. function withMiddlewareEffects(options) {
  314. return matchesMiddleware(options).then((matches)=>{
  315. if (matches && options.fetchData) {
  316. return options.fetchData().then((data)=>getMiddlewareData(data.dataHref, data.response, options).then((effect)=>({
  317. dataHref: data.dataHref,
  318. cacheKey: data.cacheKey,
  319. json: data.json,
  320. response: data.response,
  321. text: data.text,
  322. effect
  323. }))).catch((_err)=>{
  324. /**
  325. * TODO: Revisit this in the future.
  326. * For now we will not consider middleware data errors to be fatal.
  327. * maybe we should revisit in the future.
  328. */ return null;
  329. });
  330. }
  331. return null;
  332. });
  333. }
  334. const manualScrollRestoration = process.env.__NEXT_SCROLL_RESTORATION && typeof window !== 'undefined' && 'scrollRestoration' in window.history && !!function() {
  335. try {
  336. let v = '__next';
  337. // eslint-disable-next-line no-sequences
  338. return sessionStorage.setItem(v, v), sessionStorage.removeItem(v), true;
  339. } catch (n) {}
  340. }();
  341. const SSG_DATA_NOT_FOUND = Symbol('SSG_DATA_NOT_FOUND');
  342. function fetchRetry(url, attempts, options) {
  343. return fetch(url, {
  344. // Cookies are required to be present for Next.js' SSG "Preview Mode".
  345. // Cookies may also be required for `getServerSideProps`.
  346. //
  347. // > `fetch` won’t send cookies, unless you set the credentials init
  348. // > option.
  349. // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
  350. //
  351. // > For maximum browser compatibility when it comes to sending &
  352. // > receiving cookies, always supply the `credentials: 'same-origin'`
  353. // > option instead of relying on the default.
  354. // https://github.com/github/fetch#caveats
  355. credentials: 'same-origin',
  356. method: options.method || 'GET',
  357. headers: Object.assign({}, options.headers, {
  358. 'x-nextjs-data': '1'
  359. })
  360. }).then((response)=>{
  361. return !response.ok && attempts > 1 && response.status >= 500 ? fetchRetry(url, attempts - 1, options) : response;
  362. });
  363. }
  364. const backgroundCache = {};
  365. function handleSmoothScroll(fn) {
  366. const htmlElement = document.documentElement;
  367. const existing = htmlElement.style.scrollBehavior;
  368. htmlElement.style.scrollBehavior = 'auto';
  369. fn();
  370. htmlElement.style.scrollBehavior = existing;
  371. }
  372. function tryToParseAsJSON(text) {
  373. try {
  374. return JSON.parse(text);
  375. } catch (error) {
  376. return null;
  377. }
  378. }
  379. function fetchNextData({ dataHref , inflightCache , isPrefetch , hasMiddleware , isServerRender , parseJSON , persistCache , isBackground , unstable_skipClientCache }) {
  380. const { href: cacheKey } = new URL(dataHref, window.location.href);
  381. var ref1;
  382. const getData = (params)=>{
  383. return fetchRetry(dataHref, isServerRender ? 3 : 1, {
  384. headers: isPrefetch ? {
  385. purpose: 'prefetch'
  386. } : {},
  387. method: (ref1 = params == null ? void 0 : params.method) != null ? ref1 : 'GET'
  388. }).then((response)=>{
  389. if (response.ok && (params == null ? void 0 : params.method) === 'HEAD') {
  390. return {
  391. dataHref,
  392. response,
  393. text: '',
  394. json: {},
  395. cacheKey
  396. };
  397. }
  398. return response.text().then((text)=>{
  399. if (!response.ok) {
  400. /**
  401. * When the data response is a redirect because of a middleware
  402. * we do not consider it an error. The headers must bring the
  403. * mapped location.
  404. * TODO: Change the status code in the handler.
  405. */ if (hasMiddleware && [
  406. 301,
  407. 302,
  408. 307,
  409. 308
  410. ].includes(response.status)) {
  411. return {
  412. dataHref,
  413. response,
  414. text,
  415. json: {},
  416. cacheKey
  417. };
  418. }
  419. if (!hasMiddleware && response.status === 404) {
  420. var ref;
  421. if ((ref = tryToParseAsJSON(text)) == null ? void 0 : ref.notFound) {
  422. return {
  423. dataHref,
  424. json: {
  425. notFound: SSG_DATA_NOT_FOUND
  426. },
  427. response,
  428. text,
  429. cacheKey
  430. };
  431. }
  432. }
  433. const error = new Error(`Failed to load static props`);
  434. /**
  435. * We should only trigger a server-side transition if this was
  436. * caused on a client-side transition. Otherwise, we'd get into
  437. * an infinite loop.
  438. */ if (!isServerRender) {
  439. (0, _routeLoader).markAssetError(error);
  440. }
  441. throw error;
  442. }
  443. return {
  444. dataHref,
  445. json: parseJSON ? tryToParseAsJSON(text) : null,
  446. response,
  447. text,
  448. cacheKey
  449. };
  450. });
  451. }).then((data)=>{
  452. if (!persistCache || process.env.NODE_ENV !== 'production' || data.response.headers.get('x-middleware-cache') === 'no-cache') {
  453. delete inflightCache[cacheKey];
  454. }
  455. return data;
  456. }).catch((err)=>{
  457. delete inflightCache[cacheKey];
  458. throw err;
  459. });
  460. };
  461. // when skipping client cache we wait to update
  462. // inflight cache until successful data response
  463. // this allows racing click event with fetching newer data
  464. // without blocking navigation when stale data is available
  465. if (unstable_skipClientCache && persistCache) {
  466. return getData({}).then((data)=>{
  467. inflightCache[cacheKey] = Promise.resolve(data);
  468. return data;
  469. });
  470. }
  471. if (inflightCache[cacheKey] !== undefined) {
  472. return inflightCache[cacheKey];
  473. }
  474. return inflightCache[cacheKey] = getData(isBackground ? {
  475. method: 'HEAD'
  476. } : {});
  477. }
  478. function createKey() {
  479. return Math.random().toString(36).slice(2, 10);
  480. }
  481. function handleHardNavigation({ url , router }) {
  482. // ensure we don't trigger a hard navigation to the same
  483. // URL as this can end up with an infinite refresh
  484. if (url === (0, _addBasePath).addBasePath((0, _addLocale).addLocale(router.asPath, router.locale))) {
  485. throw new Error(`Invariant: attempted to hard navigate to the same URL ${url} ${location.href}`);
  486. }
  487. window.location.href = url;
  488. }
  489. const getCancelledHandler = ({ route , router })=>{
  490. let cancelled = false;
  491. const cancel = router.clc = ()=>{
  492. cancelled = true;
  493. };
  494. const handleCancelled = ()=>{
  495. if (cancelled) {
  496. const error = new Error(`Abort fetching component for route: "${route}"`);
  497. error.cancelled = true;
  498. throw error;
  499. }
  500. if (cancel === router.clc) {
  501. router.clc = null;
  502. }
  503. };
  504. return handleCancelled;
  505. };
  506. class Router {
  507. reload() {
  508. window.location.reload();
  509. }
  510. /**
  511. * Go back in history
  512. */ back() {
  513. window.history.back();
  514. }
  515. /**
  516. * Performs a `pushState` with arguments
  517. * @param url of the route
  518. * @param as masks `url` for the browser
  519. * @param options object you can define `shallow` and other options
  520. */ push(url, as, options = {}) {
  521. if (process.env.__NEXT_SCROLL_RESTORATION) {
  522. // TODO: remove in the future when we update history before route change
  523. // is complete, as the popstate event should handle this capture.
  524. if (manualScrollRestoration) {
  525. try {
  526. // Snapshot scroll position right before navigating to a new page:
  527. sessionStorage.setItem('__next_scroll_' + this._key, JSON.stringify({
  528. x: self.pageXOffset,
  529. y: self.pageYOffset
  530. }));
  531. } catch (e) {}
  532. }
  533. }
  534. ({ url , as } = prepareUrlAs(this, url, as));
  535. return this.change('pushState', url, as, options);
  536. }
  537. /**
  538. * Performs a `replaceState` with arguments
  539. * @param url of the route
  540. * @param as masks `url` for the browser
  541. * @param options object you can define `shallow` and other options
  542. */ replace(url, as, options = {}) {
  543. ({ url , as } = prepareUrlAs(this, url, as));
  544. return this.change('replaceState', url, as, options);
  545. }
  546. change(method, url, as, options, forcedScroll) {
  547. var _this = this;
  548. return _async_to_generator(function*() {
  549. if (!isLocalURL(url)) {
  550. handleHardNavigation({
  551. url,
  552. router: _this
  553. });
  554. return false;
  555. }
  556. // WARNING: `_h` is an internal option for handing Next.js client-side
  557. // hydration. Your app should _never_ use this property. It may change at
  558. // any time without notice.
  559. const isQueryUpdating = options._h;
  560. const shouldResolveHref = isQueryUpdating || options._shouldResolveHref || (0, _parsePath).parsePath(url).pathname === (0, _parsePath).parsePath(as).pathname;
  561. const nextState = _extends({}, _this.state);
  562. // for static pages with query params in the URL we delay
  563. // marking the router ready until after the query is updated
  564. // or a navigation has occurred
  565. const readyStateChange = _this.isReady !== true;
  566. _this.isReady = true;
  567. const isSsr = _this.isSsr;
  568. if (!isQueryUpdating) {
  569. _this.isSsr = false;
  570. }
  571. // if a route transition is already in progress before
  572. // the query updating is triggered ignore query updating
  573. if (isQueryUpdating && _this.clc) {
  574. return false;
  575. }
  576. const prevLocale = nextState.locale;
  577. if (process.env.__NEXT_I18N_SUPPORT) {
  578. nextState.locale = options.locale === false ? _this.defaultLocale : options.locale || nextState.locale;
  579. if (typeof options.locale === 'undefined') {
  580. options.locale = nextState.locale;
  581. }
  582. const parsedAs = (0, _parseRelativeUrl).parseRelativeUrl((0, _hasBasePath).hasBasePath(as) ? (0, _removeBasePath).removeBasePath(as) : as);
  583. const localePathResult = (0, _normalizeLocalePath).normalizeLocalePath(parsedAs.pathname, _this.locales);
  584. if (localePathResult.detectedLocale) {
  585. nextState.locale = localePathResult.detectedLocale;
  586. parsedAs.pathname = (0, _addBasePath).addBasePath(parsedAs.pathname);
  587. as = (0, _formatUrl).formatWithValidation(parsedAs);
  588. url = (0, _addBasePath).addBasePath((0, _normalizeLocalePath).normalizeLocalePath((0, _hasBasePath).hasBasePath(url) ? (0, _removeBasePath).removeBasePath(url) : url, _this.locales).pathname);
  589. }
  590. let didNavigate = false;
  591. // we need to wrap this in the env check again since regenerator runtime
  592. // moves this on its own due to the return
  593. if (process.env.__NEXT_I18N_SUPPORT) {
  594. var ref;
  595. // if the locale isn't configured hard navigate to show 404 page
  596. if (!((ref = _this.locales) == null ? void 0 : ref.includes(nextState.locale))) {
  597. parsedAs.pathname = (0, _addLocale).addLocale(parsedAs.pathname, nextState.locale);
  598. handleHardNavigation({
  599. url: (0, _formatUrl).formatWithValidation(parsedAs),
  600. router: _this
  601. });
  602. // this was previously a return but was removed in favor
  603. // of better dead code elimination with regenerator runtime
  604. didNavigate = true;
  605. }
  606. }
  607. const detectedDomain = (0, _detectDomainLocale).detectDomainLocale(_this.domainLocales, undefined, nextState.locale);
  608. // we need to wrap this in the env check again since regenerator runtime
  609. // moves this on its own due to the return
  610. if (process.env.__NEXT_I18N_SUPPORT) {
  611. // if we are navigating to a domain locale ensure we redirect to the
  612. // correct domain
  613. if (!didNavigate && detectedDomain && _this.isLocaleDomain && self.location.hostname !== detectedDomain.domain) {
  614. const asNoBasePath = (0, _removeBasePath).removeBasePath(as);
  615. handleHardNavigation({
  616. url: `http${detectedDomain.http ? '' : 's'}://${detectedDomain.domain}${(0, _addBasePath).addBasePath(`${nextState.locale === detectedDomain.defaultLocale ? '' : `/${nextState.locale}`}${asNoBasePath === '/' ? '' : asNoBasePath}` || '/')}`,
  617. router: _this
  618. });
  619. // this was previously a return but was removed in favor
  620. // of better dead code elimination with regenerator runtime
  621. didNavigate = true;
  622. }
  623. }
  624. if (didNavigate) {
  625. return new Promise(()=>{});
  626. }
  627. }
  628. // marking route changes as a navigation start entry
  629. if (_utils.ST) {
  630. performance.mark('routeChange');
  631. }
  632. const { shallow =false , scroll =true } = options;
  633. const routeProps = {
  634. shallow
  635. };
  636. if (_this._inFlightRoute && _this.clc) {
  637. if (!isSsr) {
  638. Router.events.emit('routeChangeError', buildCancellationError(), _this._inFlightRoute, routeProps);
  639. }
  640. _this.clc();
  641. _this.clc = null;
  642. }
  643. as = (0, _addBasePath).addBasePath((0, _addLocale).addLocale((0, _hasBasePath).hasBasePath(as) ? (0, _removeBasePath).removeBasePath(as) : as, options.locale, _this.defaultLocale));
  644. const cleanedAs = (0, _removeLocale).removeLocale((0, _hasBasePath).hasBasePath(as) ? (0, _removeBasePath).removeBasePath(as) : as, nextState.locale);
  645. _this._inFlightRoute = as;
  646. const localeChange = prevLocale !== nextState.locale;
  647. // If the url change is only related to a hash change
  648. // We should not proceed. We should only change the state.
  649. if (!isQueryUpdating && _this.onlyAHashChange(cleanedAs) && !localeChange) {
  650. nextState.asPath = cleanedAs;
  651. Router.events.emit('hashChangeStart', as, routeProps);
  652. // TODO: do we need the resolved href when only a hash change?
  653. _this.changeState(method, url, as, _extends({}, options, {
  654. scroll: false
  655. }));
  656. if (scroll) {
  657. _this.scrollToHash(cleanedAs);
  658. }
  659. try {
  660. yield _this.set(nextState, _this.components[nextState.route], null);
  661. } catch (err) {
  662. if ((0, _isError).default(err) && err.cancelled) {
  663. Router.events.emit('routeChangeError', err, cleanedAs, routeProps);
  664. }
  665. throw err;
  666. }
  667. Router.events.emit('hashChangeComplete', as, routeProps);
  668. return true;
  669. }
  670. let parsed = (0, _parseRelativeUrl).parseRelativeUrl(url);
  671. let { pathname , query } = parsed;
  672. // The build manifest needs to be loaded before auto-static dynamic pages
  673. // get their query parameters to allow ensuring they can be parsed properly
  674. // when rewritten to
  675. let pages, rewrites;
  676. try {
  677. [pages, { __rewrites: rewrites }] = yield Promise.all([
  678. _this.pageLoader.getPageList(),
  679. (0, _routeLoader).getClientBuildManifest(),
  680. _this.pageLoader.getMiddleware(),
  681. ]);
  682. } catch (err) {
  683. // If we fail to resolve the page list or client-build manifest, we must
  684. // do a server-side transition:
  685. handleHardNavigation({
  686. url: as,
  687. router: _this
  688. });
  689. return false;
  690. }
  691. // If asked to change the current URL we should reload the current page
  692. // (not location.reload() but reload getInitialProps and other Next.js stuffs)
  693. // We also need to set the method = replaceState always
  694. // as this should not go into the history (That's how browsers work)
  695. // We should compare the new asPath to the current asPath, not the url
  696. if (!_this.urlIsNew(cleanedAs) && !localeChange) {
  697. method = 'replaceState';
  698. }
  699. // we need to resolve the as value using rewrites for dynamic SSG
  700. // pages to allow building the data URL correctly
  701. let resolvedAs = as;
  702. // url and as should always be prefixed with basePath by this
  703. // point by either next/link or router.push/replace so strip the
  704. // basePath from the pathname to match the pages dir 1-to-1
  705. pathname = pathname ? (0, _removeTrailingSlash).removeTrailingSlash((0, _removeBasePath).removeBasePath(pathname)) : pathname;
  706. // we don't attempt resolve asPath when we need to execute
  707. // middleware as the resolving will occur server-side
  708. const isMiddlewareMatch = yield matchesMiddleware({
  709. asPath: as,
  710. locale: nextState.locale,
  711. router: _this
  712. });
  713. if (options.shallow && isMiddlewareMatch) {
  714. pathname = _this.pathname;
  715. }
  716. if (shouldResolveHref && pathname !== '/_error') {
  717. options._shouldResolveHref = true;
  718. if (process.env.__NEXT_HAS_REWRITES && as.startsWith('/')) {
  719. const rewritesResult = (0, _resolveRewrites).default((0, _addBasePath).addBasePath((0, _addLocale).addLocale(cleanedAs, nextState.locale), true), pages, rewrites, query, (p)=>resolveDynamicRoute(p, pages), _this.locales);
  720. if (rewritesResult.externalDest) {
  721. handleHardNavigation({
  722. url: as,
  723. router: _this
  724. });
  725. return true;
  726. }
  727. if (!isMiddlewareMatch) {
  728. resolvedAs = rewritesResult.asPath;
  729. }
  730. if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {
  731. // if this directly matches a page we need to update the href to
  732. // allow the correct page chunk to be loaded
  733. pathname = rewritesResult.resolvedHref;
  734. parsed.pathname = (0, _addBasePath).addBasePath(pathname);
  735. if (!isMiddlewareMatch) {
  736. url = (0, _formatUrl).formatWithValidation(parsed);
  737. }
  738. }
  739. } else {
  740. parsed.pathname = resolveDynamicRoute(pathname, pages);
  741. if (parsed.pathname !== pathname) {
  742. pathname = parsed.pathname;
  743. parsed.pathname = (0, _addBasePath).addBasePath(pathname);
  744. if (!isMiddlewareMatch) {
  745. url = (0, _formatUrl).formatWithValidation(parsed);
  746. }
  747. }
  748. }
  749. }
  750. if (!isLocalURL(as)) {
  751. if (process.env.NODE_ENV !== 'production') {
  752. throw new Error(`Invalid href: "${url}" and as: "${as}", received relative href and external as` + `\nSee more info: https://nextjs.org/docs/messages/invalid-relative-url-external-as`);
  753. }
  754. handleHardNavigation({
  755. url: as,
  756. router: _this
  757. });
  758. return false;
  759. }
  760. resolvedAs = (0, _removeLocale).removeLocale((0, _removeBasePath).removeBasePath(resolvedAs), nextState.locale);
  761. let route = (0, _removeTrailingSlash).removeTrailingSlash(pathname);
  762. let routeMatch = false;
  763. if ((0, _isDynamic).isDynamicRoute(route)) {
  764. const parsedAs = (0, _parseRelativeUrl).parseRelativeUrl(resolvedAs);
  765. const asPathname = parsedAs.pathname;
  766. const routeRegex = (0, _routeRegex).getRouteRegex(route);
  767. routeMatch = (0, _routeMatcher).getRouteMatcher(routeRegex)(asPathname);
  768. const shouldInterpolate = route === asPathname;
  769. const interpolatedAs = shouldInterpolate ? interpolateAs(route, asPathname, query) : {};
  770. if (!routeMatch || shouldInterpolate && !interpolatedAs.result) {
  771. const missingParams = Object.keys(routeRegex.groups).filter((param)=>!query[param]);
  772. if (missingParams.length > 0 && !isMiddlewareMatch) {
  773. if (process.env.NODE_ENV !== 'production') {
  774. console.warn(`${shouldInterpolate ? `Interpolating href` : `Mismatching \`as\` and \`href\``} failed to manually provide ` + `the params: ${missingParams.join(', ')} in the \`href\`'s \`query\``);
  775. }
  776. throw new Error((shouldInterpolate ? `The provided \`href\` (${url}) value is missing query values (${missingParams.join(', ')}) to be interpolated properly. ` : `The provided \`as\` value (${asPathname}) is incompatible with the \`href\` value (${route}). `) + `Read more: https://nextjs.org/docs/messages/${shouldInterpolate ? 'href-interpolation-failed' : 'incompatible-href-as'}`);
  777. }
  778. } else if (shouldInterpolate) {
  779. as = (0, _formatUrl).formatWithValidation(Object.assign({}, parsedAs, {
  780. pathname: interpolatedAs.result,
  781. query: omit(query, interpolatedAs.params)
  782. }));
  783. } else {
  784. // Merge params into `query`, overwriting any specified in search
  785. Object.assign(query, routeMatch);
  786. }
  787. }
  788. if (!isQueryUpdating) {
  789. Router.events.emit('routeChangeStart', as, routeProps);
  790. }
  791. try {
  792. var ref2, ref3;
  793. let routeInfo = yield _this.getRouteInfo({
  794. route,
  795. pathname,
  796. query,
  797. as,
  798. resolvedAs,
  799. routeProps,
  800. locale: nextState.locale,
  801. isPreview: nextState.isPreview,
  802. hasMiddleware: isMiddlewareMatch
  803. });
  804. if ('route' in routeInfo && isMiddlewareMatch) {
  805. pathname = routeInfo.route || route;
  806. route = pathname;
  807. if (!routeProps.shallow) {
  808. query = Object.assign({}, routeInfo.query || {}, query);
  809. }
  810. const cleanedParsedPathname = (0, _hasBasePath).hasBasePath(parsed.pathname) ? (0, _removeBasePath).removeBasePath(parsed.pathname) : parsed.pathname;
  811. if (routeMatch && pathname !== cleanedParsedPathname) {
  812. Object.keys(routeMatch).forEach((key)=>{
  813. if (routeMatch && query[key] === routeMatch[key]) {
  814. delete query[key];
  815. }
  816. });
  817. }
  818. if ((0, _isDynamic).isDynamicRoute(pathname)) {
  819. const prefixedAs = !routeProps.shallow && routeInfo.resolvedAs ? routeInfo.resolvedAs : (0, _addBasePath).addBasePath((0, _addLocale).addLocale(new URL(as, location.href).pathname, nextState.locale), true);
  820. let rewriteAs = prefixedAs;
  821. if ((0, _hasBasePath).hasBasePath(rewriteAs)) {
  822. rewriteAs = (0, _removeBasePath).removeBasePath(rewriteAs);
  823. }
  824. if (process.env.__NEXT_I18N_SUPPORT) {
  825. const localeResult = (0, _normalizeLocalePath).normalizeLocalePath(rewriteAs, _this.locales);
  826. nextState.locale = localeResult.detectedLocale || nextState.locale;
  827. rewriteAs = localeResult.pathname;
  828. }
  829. const routeRegex = (0, _routeRegex).getRouteRegex(pathname);
  830. const curRouteMatch = (0, _routeMatcher).getRouteMatcher(routeRegex)(rewriteAs);
  831. if (curRouteMatch) {
  832. Object.assign(query, curRouteMatch);
  833. }
  834. }
  835. }
  836. // If the routeInfo brings a redirect we simply apply it.
  837. if ('type' in routeInfo) {
  838. if (routeInfo.type === 'redirect-internal') {
  839. return _this.change(method, routeInfo.newUrl, routeInfo.newAs, options);
  840. } else {
  841. handleHardNavigation({
  842. url: routeInfo.destination,
  843. router: _this
  844. });
  845. return new Promise(()=>{});
  846. }
  847. }
  848. let { error , props , __N_SSG , __N_SSP } = routeInfo;
  849. const component = routeInfo.Component;
  850. if (component && component.unstable_scriptLoader) {
  851. const scripts = [].concat(component.unstable_scriptLoader());
  852. scripts.forEach((script)=>{
  853. (0, _script).handleClientScriptLoad(script.props);
  854. });
  855. }
  856. // handle redirect on client-transition
  857. if ((__N_SSG || __N_SSP) && props) {
  858. if (props.pageProps && props.pageProps.__N_REDIRECT) {
  859. // Use the destination from redirect without adding locale
  860. options.locale = false;
  861. const destination = props.pageProps.__N_REDIRECT;
  862. // check if destination is internal (resolves to a page) and attempt
  863. // client-navigation if it is falling back to hard navigation if
  864. // it's not
  865. if (destination.startsWith('/') && props.pageProps.__N_REDIRECT_BASE_PATH !== false) {
  866. const parsedHref = (0, _parseRelativeUrl).parseRelativeUrl(destination);
  867. parsedHref.pathname = resolveDynamicRoute(parsedHref.pathname, pages);
  868. const { url: newUrl , as: newAs } = prepareUrlAs(_this, destination, destination);
  869. return _this.change(method, newUrl, newAs, options);
  870. }
  871. handleHardNavigation({
  872. url: destination,
  873. router: _this
  874. });
  875. return new Promise(()=>{});
  876. }
  877. nextState.isPreview = !!props.__N_PREVIEW;
  878. // handle SSG data 404
  879. if (props.notFound === SSG_DATA_NOT_FOUND) {
  880. let notFoundRoute;
  881. try {
  882. yield _this.fetchComponent('/404');
  883. notFoundRoute = '/404';
  884. } catch (_) {
  885. notFoundRoute = '/_error';
  886. }
  887. routeInfo = yield _this.getRouteInfo({
  888. route: notFoundRoute,
  889. pathname: notFoundRoute,
  890. query,
  891. as,
  892. resolvedAs,
  893. routeProps: {
  894. shallow: false
  895. },
  896. locale: nextState.locale,
  897. isPreview: nextState.isPreview
  898. });
  899. if ('type' in routeInfo) {
  900. throw new Error(`Unexpected middleware effect on /404`);
  901. }
  902. }
  903. }
  904. Router.events.emit('beforeHistoryChange', as, routeProps);
  905. _this.changeState(method, url, as, options);
  906. if (isQueryUpdating && pathname === '/_error' && ((ref2 = self.__NEXT_DATA__.props) == null ? void 0 : (ref3 = ref2.pageProps) == null ? void 0 : ref3.statusCode) === 500 && (props == null ? void 0 : props.pageProps)) {
  907. // ensure statusCode is still correct for static 500 page
  908. // when updating query information
  909. props.pageProps.statusCode = 500;
  910. }
  911. var _route;
  912. // shallow routing is only allowed for same page URL changes.
  913. const isValidShallowRoute = options.shallow && nextState.route === ((_route = routeInfo.route) != null ? _route : route);
  914. var _scroll;
  915. const shouldScroll = (_scroll = options.scroll) != null ? _scroll : !options._h && !isValidShallowRoute;
  916. const resetScroll = shouldScroll ? {
  917. x: 0,
  918. y: 0
  919. } : null;
  920. // the new state that the router gonna set
  921. const upcomingRouterState = _extends({}, nextState, {
  922. route,
  923. pathname,
  924. query,
  925. asPath: cleanedAs,
  926. isFallback: false
  927. });
  928. const upcomingScrollState = forcedScroll != null ? forcedScroll : resetScroll;
  929. // for query updates we can skip it if the state is unchanged and we don't
  930. // need to scroll
  931. // https://github.com/vercel/next.js/issues/37139
  932. const canSkipUpdating = options._h && !upcomingScrollState && !readyStateChange && !localeChange && (0, _compareStates).compareRouterStates(upcomingRouterState, _this.state);
  933. if (!canSkipUpdating) {
  934. yield _this.set(upcomingRouterState, routeInfo, upcomingScrollState).catch((e)=>{
  935. if (e.cancelled) error = error || e;
  936. else throw e;
  937. });
  938. if (error) {
  939. if (!isQueryUpdating) {
  940. Router.events.emit('routeChangeError', error, cleanedAs, routeProps);
  941. }
  942. throw error;
  943. }
  944. if (process.env.__NEXT_I18N_SUPPORT) {
  945. if (nextState.locale) {
  946. document.documentElement.lang = nextState.locale;
  947. }
  948. }
  949. if (!isQueryUpdating) {
  950. Router.events.emit('routeChangeComplete', as, routeProps);
  951. }
  952. // A hash mark # is the optional last part of a URL
  953. const hashRegex = /#.+$/;
  954. if (shouldScroll && hashRegex.test(as)) {
  955. _this.scrollToHash(as);
  956. }
  957. }
  958. return true;
  959. } catch (err1) {
  960. if ((0, _isError).default(err1) && err1.cancelled) {
  961. return false;
  962. }
  963. throw err1;
  964. }
  965. })();
  966. }
  967. changeState(method, url, as, options = {}) {
  968. if (process.env.NODE_ENV !== 'production') {
  969. if (typeof window.history === 'undefined') {
  970. console.error(`Warning: window.history is not available.`);
  971. return;
  972. }
  973. if (typeof window.history[method] === 'undefined') {
  974. console.error(`Warning: window.history.${method} is not available`);
  975. return;
  976. }
  977. }
  978. if (method !== 'pushState' || (0, _utils).getURL() !== as) {
  979. this._shallow = options.shallow;
  980. window.history[method]({
  981. url,
  982. as,
  983. options,
  984. __N: true,
  985. key: this._key = method !== 'pushState' ? this._key : createKey()
  986. }, // Most browsers currently ignores this parameter, although they may use it in the future.
  987. // Passing the empty string here should be safe against future changes to the method.
  988. // https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState
  989. '', as);
  990. }
  991. }
  992. handleRouteInfoError(err, pathname, query, as, routeProps, loadErrorFail) {
  993. var _this = this;
  994. return _async_to_generator(function*() {
  995. console.error(err);
  996. if (err.cancelled) {
  997. // bubble up cancellation errors
  998. throw err;
  999. }
  1000. if ((0, _routeLoader).isAssetError(err) || loadErrorFail) {
  1001. Router.events.emit('routeChangeError', err, as, routeProps);
  1002. // If we can't load the page it could be one of following reasons
  1003. // 1. Page doesn't exists
  1004. // 2. Page does exist in a different zone
  1005. // 3. Internal error while loading the page
  1006. // So, doing a hard reload is the proper way to deal with this.
  1007. handleHardNavigation({
  1008. url: as,
  1009. router: _this
  1010. });
  1011. // Changing the URL doesn't block executing the current code path.
  1012. // So let's throw a cancellation error stop the routing logic.
  1013. throw buildCancellationError();
  1014. }
  1015. try {
  1016. let props;
  1017. const { page: Component , styleSheets } = yield _this.fetchComponent('/_error');
  1018. const routeInfo = {
  1019. props,
  1020. Component,
  1021. styleSheets,
  1022. err,
  1023. error: err
  1024. };
  1025. if (!routeInfo.props) {
  1026. try {
  1027. routeInfo.props = yield _this.getInitialProps(Component, {
  1028. err,
  1029. pathname,
  1030. query
  1031. });
  1032. } catch (gipErr) {
  1033. console.error('Error in error page `getInitialProps`: ', gipErr);
  1034. routeInfo.props = {};
  1035. }
  1036. }
  1037. return routeInfo;
  1038. } catch (routeInfoErr) {
  1039. return _this.handleRouteInfoError((0, _isError).default(routeInfoErr) ? routeInfoErr : new Error(routeInfoErr + ''), pathname, query, as, routeProps, true);
  1040. }
  1041. })();
  1042. }
  1043. getRouteInfo({ route: requestedRoute , pathname , query , as , resolvedAs , routeProps , locale , hasMiddleware , isPreview , unstable_skipClientCache }) {
  1044. var _this = this;
  1045. return _async_to_generator(function*() {
  1046. /**
  1047. * This `route` binding can change if there's a rewrite
  1048. * so we keep a reference to the original requested route
  1049. * so we can store the cache for it and avoid re-requesting every time
  1050. * for shallow routing purposes.
  1051. */ let route = requestedRoute;
  1052. try {
  1053. var ref, ref4, ref5;
  1054. const handleCancelled = getCancelledHandler({
  1055. route,
  1056. router: _this
  1057. });
  1058. let existingInfo = _this.components[route];
  1059. if (routeProps.shallow && existingInfo && _this.route === route) {
  1060. return existingInfo;
  1061. }
  1062. if (hasMiddleware) {
  1063. existingInfo = undefined;
  1064. }
  1065. let cachedRouteInfo = existingInfo && !('initial' in existingInfo) && process.env.NODE_ENV !== 'development' ? existingInfo : undefined;
  1066. const fetchNextDataParams = {
  1067. dataHref: _this.pageLoader.getDataHref({
  1068. href: (0, _formatUrl).formatWithValidation({
  1069. pathname,
  1070. query
  1071. }),
  1072. skipInterpolation: true,
  1073. asPath: resolvedAs,
  1074. locale
  1075. }),
  1076. hasMiddleware: true,
  1077. isServerRender: _this.isSsr,
  1078. parseJSON: true,
  1079. inflightCache: _this.sdc,
  1080. persistCache: !isPreview,
  1081. isPrefetch: false,
  1082. unstable_skipClientCache
  1083. };
  1084. const data = yield withMiddlewareEffects({
  1085. fetchData: ()=>fetchNextData(fetchNextDataParams),
  1086. asPath: resolvedAs,
  1087. locale: locale,
  1088. router: _this
  1089. });
  1090. handleCancelled();
  1091. if ((data == null ? void 0 : (ref = data.effect) == null ? void 0 : ref.type) === 'redirect-internal' || (data == null ? void 0 : (ref4 = data.effect) == null ? void 0 : ref4.type) === 'redirect-external') {
  1092. return data.effect;
  1093. }
  1094. if ((data == null ? void 0 : (ref5 = data.effect) == null ? void 0 : ref5.type) === 'rewrite') {
  1095. route = (0, _removeTrailingSlash).removeTrailingSlash(data.effect.resolvedHref);
  1096. pathname = data.effect.resolvedHref;
  1097. query = _extends({}, query, data.effect.parsedAs.query);
  1098. resolvedAs = (0, _removeBasePath).removeBasePath((0, _normalizeLocalePath).normalizeLocalePath(data.effect.parsedAs.pathname, _this.locales).pathname);
  1099. // Check again the cache with the new destination.
  1100. existingInfo = _this.components[route];
  1101. if (routeProps.shallow && existingInfo && _this.route === route && !hasMiddleware) {
  1102. // If we have a match with the current route due to rewrite,
  1103. // we can copy the existing information to the rewritten one.
  1104. // Then, we return the information along with the matched route.
  1105. return _extends({}, existingInfo, {
  1106. route
  1107. });
  1108. }
  1109. }
  1110. if (route === '/api' || route.startsWith('/api/')) {
  1111. handleHardNavigation({
  1112. url: as,
  1113. router: _this
  1114. });
  1115. return new Promise(()=>{});
  1116. }
  1117. const routeInfo = cachedRouteInfo || (yield _this.fetchComponent(route).then((res)=>({
  1118. Component: res.page,
  1119. styleSheets: res.styleSheets,
  1120. __N_SSG: res.mod.__N_SSG,
  1121. __N_SSP: res.mod.__N_SSP
  1122. })));
  1123. if (process.env.NODE_ENV !== 'production') {
  1124. const { isValidElementType } = require('next/dist/compiled/react-is');
  1125. if (!isValidElementType(routeInfo.Component)) {
  1126. throw new Error(`The default export is not a React Component in page: "${pathname}"`);
  1127. }
  1128. }
  1129. const shouldFetchData = routeInfo.__N_SSG || routeInfo.__N_SSP;
  1130. const { props , cacheKey } = yield _this._getData(_async_to_generator(function*() {
  1131. if (shouldFetchData) {
  1132. const { json , cacheKey: _cacheKey } = (data == null ? void 0 : data.json) ? data : yield fetchNextData({
  1133. dataHref: _this.pageLoader.getDataHref({
  1134. href: (0, _formatUrl).formatWithValidation({
  1135. pathname,
  1136. query
  1137. }),
  1138. asPath: resolvedAs,
  1139. locale
  1140. }),
  1141. isServerRender: _this.isSsr,
  1142. parseJSON: true,
  1143. inflightCache: _this.sdc,
  1144. persistCache: !isPreview,
  1145. isPrefetch: false,
  1146. unstable_skipClientCache
  1147. });
  1148. return {
  1149. cacheKey: _cacheKey,
  1150. props: json || {}
  1151. };
  1152. }
  1153. return {
  1154. headers: {},
  1155. cacheKey: '',
  1156. props: yield _this.getInitialProps(routeInfo.Component, // we provide AppTree later so this needs to be `any`
  1157. {
  1158. pathname,
  1159. query,
  1160. asPath: as,
  1161. locale,
  1162. locales: _this.locales,
  1163. defaultLocale: _this.defaultLocale
  1164. })
  1165. };
  1166. }));
  1167. // Only bust the data cache for SSP routes although
  1168. // middleware can skip cache per request with
  1169. // x-middleware-cache: no-cache as well
  1170. if (routeInfo.__N_SSP && fetchNextDataParams.dataHref) {
  1171. delete _this.sdc[cacheKey];
  1172. }
  1173. // we kick off a HEAD request in the background
  1174. // when a non-prefetch request is made to signal revalidation
  1175. if (!_this.isPreview && routeInfo.__N_SSG && process.env.NODE_ENV !== 'development') {
  1176. fetchNextData(Object.assign({}, fetchNextDataParams, {
  1177. isBackground: true,
  1178. persistCache: false,
  1179. inflightCache: backgroundCache
  1180. })).catch(()=>{});
  1181. }
  1182. props.pageProps = Object.assign({}, props.pageProps);
  1183. routeInfo.props = props;
  1184. routeInfo.route = route;
  1185. routeInfo.query = query;
  1186. routeInfo.resolvedAs = resolvedAs;
  1187. _this.components[route] = routeInfo;
  1188. return routeInfo;
  1189. } catch (err) {
  1190. return _this.handleRouteInfoError((0, _isError).getProperError(err), pathname, query, as, routeProps);
  1191. }
  1192. })();
  1193. }
  1194. set(state, data, resetScroll) {
  1195. this.state = state;
  1196. return this.sub(data, this.components['/_app'].Component, resetScroll);
  1197. }
  1198. /**
  1199. * Callback to execute before replacing router state
  1200. * @param cb callback to be executed
  1201. */ beforePopState(cb) {
  1202. this._bps = cb;
  1203. }
  1204. onlyAHashChange(as) {
  1205. if (!this.asPath) return false;
  1206. const [oldUrlNoHash, oldHash] = this.asPath.split('#');
  1207. const [newUrlNoHash, newHash] = as.split('#');
  1208. // Makes sure we scroll to the provided hash if the url/hash are the same
  1209. if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) {
  1210. return true;
  1211. }
  1212. // If the urls are change, there's more than a hash change
  1213. if (oldUrlNoHash !== newUrlNoHash) {
  1214. return false;
  1215. }
  1216. // If the hash has changed, then it's a hash only change.
  1217. // This check is necessary to handle both the enter and
  1218. // leave hash === '' cases. The identity case falls through
  1219. // and is treated as a next reload.
  1220. return oldHash !== newHash;
  1221. }
  1222. scrollToHash(as) {
  1223. const [, hash = ''] = as.split('#');
  1224. // Scroll to top if the hash is just `#` with no value or `#top`
  1225. // To mirror browsers
  1226. if (hash === '' || hash === 'top') {
  1227. handleSmoothScroll(()=>window.scrollTo(0, 0));
  1228. return;
  1229. }
  1230. // Decode hash to make non-latin anchor works.
  1231. const rawHash = decodeURIComponent(hash);
  1232. // First we check if the element by id is found
  1233. const idEl = document.getElementById(rawHash);
  1234. if (idEl) {
  1235. handleSmoothScroll(()=>idEl.scrollIntoView());
  1236. return;
  1237. }
  1238. // If there's no element with the id, we check the `name` property
  1239. // To mirror browsers
  1240. const nameEl = document.getElementsByName(rawHash)[0];
  1241. if (nameEl) {
  1242. handleSmoothScroll(()=>nameEl.scrollIntoView());
  1243. }
  1244. }
  1245. urlIsNew(asPath) {
  1246. return this.asPath !== asPath;
  1247. }
  1248. /**
  1249. * Prefetch page code, you may wait for the data during page rendering.
  1250. * This feature only works in production!
  1251. * @param url the href of prefetched page
  1252. * @param asPath the as path of the prefetched page
  1253. */ prefetch(url, asPath = url, options = {}) {
  1254. var _this = this;
  1255. return _async_to_generator(function*() {
  1256. if (typeof window !== 'undefined' && (0, _isBot).isBot(window.navigator.userAgent)) {
  1257. // No prefetches for bots that render the link since they are typically navigating
  1258. // links via the equivalent of a hard navigation and hence never utilize these
  1259. // prefetches.
  1260. return;
  1261. }
  1262. let parsed = (0, _parseRelativeUrl).parseRelativeUrl(url);
  1263. let { pathname , query } = parsed;
  1264. if (process.env.__NEXT_I18N_SUPPORT) {
  1265. if (options.locale === false) {
  1266. pathname = (0, _normalizeLocalePath).normalizeLocalePath(pathname, _this.locales).pathname;
  1267. parsed.pathname = pathname;
  1268. url = (0, _formatUrl).formatWithValidation(parsed);
  1269. let parsedAs = (0, _parseRelativeUrl).parseRelativeUrl(asPath);
  1270. const localePathResult = (0, _normalizeLocalePath).normalizeLocalePath(parsedAs.pathname, _this.locales);
  1271. parsedAs.pathname = localePathResult.pathname;
  1272. options.locale = localePathResult.detectedLocale || _this.defaultLocale;
  1273. asPath = (0, _formatUrl).formatWithValidation(parsedAs);
  1274. }
  1275. }
  1276. const pages = yield _this.pageLoader.getPageList();
  1277. let resolvedAs = asPath;
  1278. const locale = typeof options.locale !== 'undefined' ? options.locale || undefined : _this.locale;
  1279. if (process.env.__NEXT_HAS_REWRITES && asPath.startsWith('/')) {
  1280. let rewrites;
  1281. ({ __rewrites: rewrites } = yield (0, _routeLoader).getClientBuildManifest());
  1282. const rewritesResult = (0, _resolveRewrites).default((0, _addBasePath).addBasePath((0, _addLocale).addLocale(asPath, _this.locale), true), pages, rewrites, parsed.query, (p)=>resolveDynamicRoute(p, pages), _this.locales);
  1283. if (rewritesResult.externalDest) {
  1284. return;
  1285. }
  1286. resolvedAs = (0, _removeLocale).removeLocale((0, _removeBasePath).removeBasePath(rewritesResult.asPath), _this.locale);
  1287. if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {
  1288. // if this directly matches a page we need to update the href to
  1289. // allow the correct page chunk to be loaded
  1290. pathname = rewritesResult.resolvedHref;
  1291. parsed.pathname = pathname;
  1292. url = (0, _formatUrl).formatWithValidation(parsed);
  1293. }
  1294. }
  1295. parsed.pathname = resolveDynamicRoute(parsed.pathname, pages);
  1296. if ((0, _isDynamic).isDynamicRoute(parsed.pathname)) {
  1297. pathname = parsed.pathname;
  1298. parsed.pathname = pathname;
  1299. Object.assign(query, (0, _routeMatcher).getRouteMatcher((0, _routeRegex).getRouteRegex(parsed.pathname))((0, _parsePath).parsePath(asPath).pathname) || {});
  1300. url = (0, _formatUrl).formatWithValidation(parsed);
  1301. }
  1302. // Prefetch is not supported in development mode because it would trigger on-demand-entries
  1303. if (process.env.NODE_ENV !== 'production') {
  1304. return;
  1305. }
  1306. const route = (0, _removeTrailingSlash).removeTrailingSlash(pathname);
  1307. yield Promise.all([
  1308. _this.pageLoader._isSsg(route).then((isSsg)=>{
  1309. return isSsg ? fetchNextData({
  1310. dataHref: _this.pageLoader.getDataHref({
  1311. href: url,
  1312. asPath: resolvedAs,
  1313. locale: locale
  1314. }),
  1315. isServerRender: false,
  1316. parseJSON: true,
  1317. inflightCache: _this.sdc,
  1318. persistCache: !_this.isPreview,
  1319. isPrefetch: true,
  1320. unstable_skipClientCache: options.unstable_skipClientCache || options.priority && !!process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE
  1321. }).then(()=>false) : false;
  1322. }),
  1323. _this.pageLoader[options.priority ? 'loadPage' : 'prefetch'](route),
  1324. ]);
  1325. })();
  1326. }
  1327. fetchComponent(route) {
  1328. var _this = this;
  1329. return _async_to_generator(function*() {
  1330. const handleCancelled = getCancelledHandler({
  1331. route,
  1332. router: _this
  1333. });
  1334. try {
  1335. const componentResult = yield _this.pageLoader.loadPage(route);
  1336. handleCancelled();
  1337. return componentResult;
  1338. } catch (err) {
  1339. handleCancelled();
  1340. throw err;
  1341. }
  1342. })();
  1343. }
  1344. _getData(fn) {
  1345. let cancelled = false;
  1346. const cancel = ()=>{
  1347. cancelled = true;
  1348. };
  1349. this.clc = cancel;
  1350. return fn().then((data)=>{
  1351. if (cancel === this.clc) {
  1352. this.clc = null;
  1353. }
  1354. if (cancelled) {
  1355. const err = new Error('Loading initial props cancelled');
  1356. err.cancelled = true;
  1357. throw err;
  1358. }
  1359. return data;
  1360. });
  1361. }
  1362. _getFlightData(dataHref) {
  1363. // Do not cache RSC flight response since it's not a static resource
  1364. return fetchNextData({
  1365. dataHref,
  1366. isServerRender: true,
  1367. parseJSON: false,
  1368. inflightCache: this.sdc,
  1369. persistCache: false,
  1370. isPrefetch: false
  1371. }).then(({ text })=>({
  1372. data: text
  1373. }));
  1374. }
  1375. getInitialProps(Component, ctx) {
  1376. const { Component: App } = this.components['/_app'];
  1377. const AppTree = this._wrapApp(App);
  1378. ctx.AppTree = AppTree;
  1379. return (0, _utils).loadGetInitialProps(App, {
  1380. AppTree,
  1381. Component,
  1382. router: this,
  1383. ctx
  1384. });
  1385. }
  1386. get route() {
  1387. return this.state.route;
  1388. }
  1389. get pathname() {
  1390. return this.state.pathname;
  1391. }
  1392. get query() {
  1393. return this.state.query;
  1394. }
  1395. get asPath() {
  1396. return this.state.asPath;
  1397. }
  1398. get locale() {
  1399. return this.state.locale;
  1400. }
  1401. get isFallback() {
  1402. return this.state.isFallback;
  1403. }
  1404. get isPreview() {
  1405. return this.state.isPreview;
  1406. }
  1407. constructor(pathname1, query1, as1, { initialProps , pageLoader , App , wrapApp , Component , err , subscription , isFallback , locale , locales , defaultLocale , domainLocales , isPreview }){
  1408. // Server Data Cache
  1409. this.sdc = {};
  1410. this.isFirstPopStateEvent = true;
  1411. this._key = createKey();
  1412. this.onPopState = (e)=>{
  1413. const { isFirstPopStateEvent } = this;
  1414. this.isFirstPopStateEvent = false;
  1415. const state = e.state;
  1416. if (!state) {
  1417. // We get state as undefined for two reasons.
  1418. // 1. With older safari (< 8) and older chrome (< 34)
  1419. // 2. When the URL changed with #
  1420. //
  1421. // In the both cases, we don't need to proceed and change the route.
  1422. // (as it's already changed)
  1423. // But we can simply replace the state with the new changes.
  1424. // Actually, for (1) we don't need to nothing. But it's hard to detect that event.
  1425. // So, doing the following for (1) does no harm.
  1426. const { pathname , query } = this;
  1427. this.changeState('replaceState', (0, _formatUrl).formatWithValidation({
  1428. pathname: (0, _addBasePath).addBasePath(pathname),
  1429. query
  1430. }), (0, _utils).getURL());
  1431. return;
  1432. }
  1433. // __NA is used to identify if the history entry can be handled by the app-router.
  1434. if (state.__NA) {
  1435. window.location.reload();
  1436. return;
  1437. }
  1438. if (!state.__N) {
  1439. return;
  1440. }
  1441. // Safari fires popstateevent when reopening the browser.
  1442. if (isFirstPopStateEvent && this.locale === state.options.locale && state.as === this.asPath) {
  1443. return;
  1444. }
  1445. let forcedScroll;
  1446. const { url , as , options , key } = state;
  1447. if (process.env.__NEXT_SCROLL_RESTORATION) {
  1448. if (manualScrollRestoration) {
  1449. if (this._key !== key) {
  1450. // Snapshot current scroll position:
  1451. try {
  1452. sessionStorage.setItem('__next_scroll_' + this._key, JSON.stringify({
  1453. x: self.pageXOffset,
  1454. y: self.pageYOffset
  1455. }));
  1456. } catch (e) {}
  1457. // Restore old scroll position:
  1458. try {
  1459. const v = sessionStorage.getItem('__next_scroll_' + key);
  1460. forcedScroll = JSON.parse(v);
  1461. } catch (e1) {
  1462. forcedScroll = {
  1463. x: 0,
  1464. y: 0
  1465. };
  1466. }
  1467. }
  1468. }
  1469. }
  1470. this._key = key;
  1471. const { pathname } = (0, _parseRelativeUrl).parseRelativeUrl(url);
  1472. // Make sure we don't re-render on initial load,
  1473. // can be caused by navigating back from an external site
  1474. if (this.isSsr && as === (0, _addBasePath).addBasePath(this.asPath) && pathname === (0, _addBasePath).addBasePath(this.pathname)) {
  1475. return;
  1476. }
  1477. // If the downstream application returns falsy, return.
  1478. // They will then be responsible for handling the event.
  1479. if (this._bps && !this._bps(state)) {
  1480. return;
  1481. }
  1482. this.change('replaceState', url, as, Object.assign({}, options, {
  1483. shallow: options.shallow && this._shallow,
  1484. locale: options.locale || this.defaultLocale,
  1485. // @ts-ignore internal value not exposed on types
  1486. _h: 0
  1487. }), forcedScroll);
  1488. };
  1489. // represents the current component key
  1490. const route = (0, _removeTrailingSlash).removeTrailingSlash(pathname1);
  1491. // set up the component cache (by route keys)
  1492. this.components = {};
  1493. // We should not keep the cache, if there's an error
  1494. // Otherwise, this cause issues when when going back and
  1495. // come again to the errored page.
  1496. if (pathname1 !== '/_error') {
  1497. this.components[route] = {
  1498. Component,
  1499. initial: true,
  1500. props: initialProps,
  1501. err,
  1502. __N_SSG: initialProps && initialProps.__N_SSG,
  1503. __N_SSP: initialProps && initialProps.__N_SSP
  1504. };
  1505. }
  1506. this.components['/_app'] = {
  1507. Component: App,
  1508. styleSheets: []
  1509. };
  1510. // Backwards compat for Router.router.events
  1511. // TODO: Should be remove the following major version as it was never documented
  1512. this.events = Router.events;
  1513. this.pageLoader = pageLoader;
  1514. // if auto prerendered and dynamic route wait to update asPath
  1515. // until after mount to prevent hydration mismatch
  1516. const autoExportDynamic = (0, _isDynamic).isDynamicRoute(pathname1) && self.__NEXT_DATA__.autoExport;
  1517. this.basePath = process.env.__NEXT_ROUTER_BASEPATH || '';
  1518. this.sub = subscription;
  1519. this.clc = null;
  1520. this._wrapApp = wrapApp;
  1521. // make sure to ignore extra popState in safari on navigating
  1522. // back from external site
  1523. this.isSsr = true;
  1524. this.isLocaleDomain = false;
  1525. this.isReady = !!(self.__NEXT_DATA__.gssp || self.__NEXT_DATA__.gip || self.__NEXT_DATA__.appGip && !self.__NEXT_DATA__.gsp || !autoExportDynamic && !self.location.search && !process.env.__NEXT_HAS_REWRITES);
  1526. if (process.env.__NEXT_I18N_SUPPORT) {
  1527. this.locales = locales;
  1528. this.defaultLocale = defaultLocale;
  1529. this.domainLocales = domainLocales;
  1530. this.isLocaleDomain = !!(0, _detectDomainLocale).detectDomainLocale(domainLocales, self.location.hostname);
  1531. }
  1532. this.state = {
  1533. route,
  1534. pathname: pathname1,
  1535. query: query1,
  1536. asPath: autoExportDynamic ? pathname1 : as1,
  1537. isPreview: !!isPreview,
  1538. locale: process.env.__NEXT_I18N_SUPPORT ? locale : undefined,
  1539. isFallback
  1540. };
  1541. this._initialMatchesMiddlewarePromise = Promise.resolve(false);
  1542. if (typeof window !== 'undefined') {
  1543. // make sure "as" doesn't start with double slashes or else it can
  1544. // throw an error as it's considered invalid
  1545. if (!as1.startsWith('//')) {
  1546. // in order for `e.state` to work on the `onpopstate` event
  1547. // we have to register the initial route upon initialization
  1548. const options = {
  1549. locale
  1550. };
  1551. const asPath = (0, _utils).getURL();
  1552. this._initialMatchesMiddlewarePromise = matchesMiddleware({
  1553. router: this,
  1554. locale,
  1555. asPath
  1556. }).then((matches)=>{
  1557. options._shouldResolveHref = as1 !== pathname1;
  1558. this.changeState('replaceState', matches ? asPath : (0, _formatUrl).formatWithValidation({
  1559. pathname: (0, _addBasePath).addBasePath(pathname1),
  1560. query: query1
  1561. }), asPath, options);
  1562. return matches;
  1563. });
  1564. }
  1565. window.addEventListener('popstate', this.onPopState);
  1566. // enable custom scroll restoration handling when available
  1567. // otherwise fallback to browser's default handling
  1568. if (process.env.__NEXT_SCROLL_RESTORATION) {
  1569. if (manualScrollRestoration) {
  1570. window.history.scrollRestoration = 'manual';
  1571. }
  1572. }
  1573. }
  1574. }
  1575. }
  1576. Router.events = (0, _mitt).default();
  1577. exports.default = Router;
  1578. //# sourceMappingURL=router.js.map