1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579 |
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.matchesMiddleware = matchesMiddleware;
- exports.isLocalURL = isLocalURL;
- exports.interpolateAs = interpolateAs;
- exports.resolveHref = resolveHref;
- exports.createKey = createKey;
- exports.default = void 0;
- var _async_to_generator = require("@swc/helpers/lib/_async_to_generator.js").default;
- var _extends = require("@swc/helpers/lib/_extends.js").default;
- var _interop_require_default = require("@swc/helpers/lib/_interop_require_default.js").default;
- var _interop_require_wildcard = require("@swc/helpers/lib/_interop_require_wildcard.js").default;
- var _normalizeTrailingSlash = require("../../../client/normalize-trailing-slash");
- var _removeTrailingSlash = require("./utils/remove-trailing-slash");
- var _routeLoader = require("../../../client/route-loader");
- var _script = require("../../../client/script");
- var _isError = _interop_require_wildcard(require("../../../lib/is-error"));
- var _denormalizePagePath = require("../page-path/denormalize-page-path");
- var _normalizeLocalePath = require("../i18n/normalize-locale-path");
- var _mitt = _interop_require_default(require("../mitt"));
- var _utils = require("../utils");
- var _isDynamic = require("./utils/is-dynamic");
- var _parseRelativeUrl = require("./utils/parse-relative-url");
- var _querystring = require("./utils/querystring");
- var _resolveRewrites = _interop_require_default(require("./utils/resolve-rewrites"));
- var _routeMatcher = require("./utils/route-matcher");
- var _routeRegex = require("./utils/route-regex");
- var _formatUrl = require("./utils/format-url");
- var _detectDomainLocale = require("../../../client/detect-domain-locale");
- var _parsePath = require("./utils/parse-path");
- var _addLocale = require("../../../client/add-locale");
- var _removeLocale = require("../../../client/remove-locale");
- var _removeBasePath = require("../../../client/remove-base-path");
- var _addBasePath = require("../../../client/add-base-path");
- var _hasBasePath = require("../../../client/has-base-path");
- var _getNextPathnameInfo = require("./utils/get-next-pathname-info");
- var _formatNextPathnameInfo = require("./utils/format-next-pathname-info");
- var _compareStates = require("./utils/compare-states");
- var _isBot = require("./utils/is-bot");
- function buildCancellationError() {
- return Object.assign(new Error('Route Cancelled'), {
- cancelled: true
- });
- }
- function matchesMiddleware(options) {
- return _matchesMiddleware.apply(this, arguments);
- }
- function _matchesMiddleware() {
- _matchesMiddleware = _async_to_generator(function*(options) {
- const matchers = yield Promise.resolve(options.router.pageLoader.getMiddleware());
- if (!matchers) return false;
- const { pathname: asPathname } = (0, _parsePath).parsePath(options.asPath);
-
- const cleanedAs = (0, _hasBasePath).hasBasePath(asPathname) ? (0, _removeBasePath).removeBasePath(asPathname) : asPathname;
- const asWithBasePathAndLocale = (0, _addBasePath).addBasePath((0, _addLocale).addLocale(cleanedAs, options.locale));
-
-
- return matchers.some((m)=>new RegExp(m.regexp).test(asWithBasePathAndLocale));
- });
- return _matchesMiddleware.apply(this, arguments);
- }
- function stripOrigin(url) {
- const origin = (0, _utils).getLocationOrigin();
- return url.startsWith(origin) ? url.substring(origin.length) : url;
- }
- function omit(object, keys) {
- const omitted = {};
- Object.keys(object).forEach((key)=>{
- if (!keys.includes(key)) {
- omitted[key] = object[key];
- }
- });
- return omitted;
- }
- function isLocalURL(url) {
-
- if (!(0, _utils).isAbsoluteUrl(url)) return true;
- try {
-
- const locationOrigin = (0, _utils).getLocationOrigin();
- const resolved = new URL(url, locationOrigin);
- return resolved.origin === locationOrigin && (0, _hasBasePath).hasBasePath(resolved.pathname);
- } catch (_) {
- return false;
- }
- }
- function interpolateAs(route, asPathname, query) {
- let interpolatedRoute = '';
- const dynamicRegex = (0, _routeRegex).getRouteRegex(route);
- const dynamicGroups = dynamicRegex.groups;
- const dynamicMatches =
- (asPathname !== route ? (0, _routeMatcher).getRouteMatcher(dynamicRegex)(asPathname) : '') ||
-
- query;
- interpolatedRoute = route;
- const params = Object.keys(dynamicGroups);
- if (!params.every((param)=>{
- let value = dynamicMatches[param] || '';
- const { repeat , optional } = dynamicGroups[param];
-
-
- let replaced = `[${repeat ? '...' : ''}${param}]`;
- if (optional) {
- replaced = `${!value ? '/' : ''}[${replaced}]`;
- }
- if (repeat && !Array.isArray(value)) value = [
- value
- ];
- return (optional || param in dynamicMatches) &&
- (interpolatedRoute = interpolatedRoute.replace(replaced, repeat ? value.map(
-
-
-
- (segment)=>encodeURIComponent(segment)).join('/') : encodeURIComponent(value)) || '/');
- })) {
- interpolatedRoute = ''
- ;
-
-
- }
- return {
- params,
- result: interpolatedRoute
- };
- }
- function resolveHref(router, href, resolveAs) {
-
- let base;
- let urlAsString = typeof href === 'string' ? href : (0, _formatUrl).formatWithValidation(href);
-
-
- const urlProtoMatch = urlAsString.match(/^[a-zA-Z]{1,}:\/\//);
- const urlAsStringNoProto = urlProtoMatch ? urlAsString.slice(urlProtoMatch[0].length) : urlAsString;
- const urlParts = urlAsStringNoProto.split('?');
- if ((urlParts[0] || '').match(/(\/\/|\\)/)) {
- console.error(`Invalid href passed to next/router: ${urlAsString}, repeated forward-slashes (//) or backslashes \\ are not valid in the href`);
- const normalizedUrl = (0, _utils).normalizeRepeatedSlashes(urlAsStringNoProto);
- urlAsString = (urlProtoMatch ? urlProtoMatch[0] : '') + normalizedUrl;
- }
-
- if (!isLocalURL(urlAsString)) {
- return resolveAs ? [
- urlAsString
- ] : urlAsString;
- }
- try {
- base = new URL(urlAsString.startsWith('#') ? router.asPath : router.pathname, 'http://n');
- } catch (_) {
-
- base = new URL('/', 'http://n');
- }
- try {
- const finalUrl = new URL(urlAsString, base);
- finalUrl.pathname = (0, _normalizeTrailingSlash).normalizePathTrailingSlash(finalUrl.pathname);
- let interpolatedAs = '';
- if ((0, _isDynamic).isDynamicRoute(finalUrl.pathname) && finalUrl.searchParams && resolveAs) {
- const query = (0, _querystring).searchParamsToUrlQuery(finalUrl.searchParams);
- const { result , params } = interpolateAs(finalUrl.pathname, finalUrl.pathname, query);
- if (result) {
- interpolatedAs = (0, _formatUrl).formatWithValidation({
- pathname: result,
- hash: finalUrl.hash,
- query: omit(query, params)
- });
- }
- }
-
- const resolvedHref = finalUrl.origin === base.origin ? finalUrl.href.slice(finalUrl.origin.length) : finalUrl.href;
- return resolveAs ? [
- resolvedHref,
- interpolatedAs || resolvedHref
- ] : resolvedHref;
- } catch (_1) {
- return resolveAs ? [
- urlAsString
- ] : urlAsString;
- }
- }
- function prepareUrlAs(router, url, as) {
-
-
- let [resolvedHref, resolvedAs] = resolveHref(router, url, true);
- const origin = (0, _utils).getLocationOrigin();
- const hrefHadOrigin = resolvedHref.startsWith(origin);
- const asHadOrigin = resolvedAs && resolvedAs.startsWith(origin);
- resolvedHref = stripOrigin(resolvedHref);
- resolvedAs = resolvedAs ? stripOrigin(resolvedAs) : resolvedAs;
- const preparedUrl = hrefHadOrigin ? resolvedHref : (0, _addBasePath).addBasePath(resolvedHref);
- const preparedAs = as ? stripOrigin(resolveHref(router, as)) : resolvedAs || resolvedHref;
- return {
- url: preparedUrl,
- as: asHadOrigin ? preparedAs : (0, _addBasePath).addBasePath(preparedAs)
- };
- }
- function resolveDynamicRoute(pathname, pages) {
- const cleanPathname = (0, _removeTrailingSlash).removeTrailingSlash((0, _denormalizePagePath).denormalizePagePath(pathname));
- if (cleanPathname === '/404' || cleanPathname === '/_error') {
- return pathname;
- }
-
- if (!pages.includes(cleanPathname)) {
-
- pages.some((page)=>{
- if ((0, _isDynamic).isDynamicRoute(page) && (0, _routeRegex).getRouteRegex(page).re.test(cleanPathname)) {
- pathname = page;
- return true;
- }
- });
- }
- return (0, _removeTrailingSlash).removeTrailingSlash(pathname);
- }
- function getMiddlewareData(source, response, options) {
- const nextConfig = {
- basePath: options.router.basePath,
- i18n: {
- locales: options.router.locales
- },
- trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH)
- };
- const rewriteHeader = response.headers.get('x-nextjs-rewrite');
- let rewriteTarget = rewriteHeader || response.headers.get('x-nextjs-matched-path');
- const matchedPath = response.headers.get('x-matched-path');
- if (matchedPath && !rewriteTarget && !matchedPath.includes('__next_data_catchall') && !matchedPath.includes('/_error') && !matchedPath.includes('/404')) {
-
- rewriteTarget = matchedPath;
- }
- if (rewriteTarget) {
- if (rewriteTarget.startsWith('/')) {
- const parsedRewriteTarget = (0, _parseRelativeUrl).parseRelativeUrl(rewriteTarget);
- const pathnameInfo = (0, _getNextPathnameInfo).getNextPathnameInfo(parsedRewriteTarget.pathname, {
- nextConfig,
- parseData: true
- });
- let fsPathname = (0, _removeTrailingSlash).removeTrailingSlash(pathnameInfo.pathname);
- return Promise.all([
- options.router.pageLoader.getPageList(),
- (0, _routeLoader).getClientBuildManifest(),
- ]).then(([pages, { __rewrites: rewrites }])=>{
- let as = (0, _addLocale).addLocale(pathnameInfo.pathname, pathnameInfo.locale);
- if ((0, _isDynamic).isDynamicRoute(as) || !rewriteHeader && pages.includes((0, _normalizeLocalePath).normalizeLocalePath((0, _removeBasePath).removeBasePath(as), options.router.locales).pathname)) {
- const parsedSource = (0, _getNextPathnameInfo).getNextPathnameInfo((0, _parseRelativeUrl).parseRelativeUrl(source).pathname, {
- parseData: true
- });
- as = (0, _addBasePath).addBasePath(parsedSource.pathname);
- parsedRewriteTarget.pathname = as;
- }
- if (process.env.__NEXT_HAS_REWRITES) {
- const result = (0, _resolveRewrites).default(as, pages, rewrites, parsedRewriteTarget.query, (path)=>resolveDynamicRoute(path, pages), options.router.locales);
- if (result.matchedPage) {
- parsedRewriteTarget.pathname = result.parsedAs.pathname;
- as = parsedRewriteTarget.pathname;
- Object.assign(parsedRewriteTarget.query, result.parsedAs.query);
- }
- } else if (!pages.includes(fsPathname)) {
- const resolvedPathname = resolveDynamicRoute(fsPathname, pages);
- if (resolvedPathname !== fsPathname) {
- fsPathname = resolvedPathname;
- }
- }
- const resolvedHref = !pages.includes(fsPathname) ? resolveDynamicRoute((0, _normalizeLocalePath).normalizeLocalePath((0, _removeBasePath).removeBasePath(parsedRewriteTarget.pathname), options.router.locales).pathname, pages) : fsPathname;
- if ((0, _isDynamic).isDynamicRoute(resolvedHref)) {
- const matches = (0, _routeMatcher).getRouteMatcher((0, _routeRegex).getRouteRegex(resolvedHref))(as);
- Object.assign(parsedRewriteTarget.query, matches || {});
- }
- return {
- type: 'rewrite',
- parsedAs: parsedRewriteTarget,
- resolvedHref
- };
- });
- }
- const src = (0, _parsePath).parsePath(source);
- const pathname = (0, _formatNextPathnameInfo).formatNextPathnameInfo(_extends({}, (0, _getNextPathnameInfo).getNextPathnameInfo(src.pathname, {
- nextConfig,
- parseData: true
- }), {
- defaultLocale: options.router.defaultLocale,
- buildId: ''
- }));
- return Promise.resolve({
- type: 'redirect-external',
- destination: `${pathname}${src.query}${src.hash}`
- });
- }
- const redirectTarget = response.headers.get('x-nextjs-redirect');
- if (redirectTarget) {
- if (redirectTarget.startsWith('/')) {
- const src = (0, _parsePath).parsePath(redirectTarget);
- const pathname = (0, _formatNextPathnameInfo).formatNextPathnameInfo(_extends({}, (0, _getNextPathnameInfo).getNextPathnameInfo(src.pathname, {
- nextConfig,
- parseData: true
- }), {
- defaultLocale: options.router.defaultLocale,
- buildId: ''
- }));
- return Promise.resolve({
- type: 'redirect-internal',
- newAs: `${pathname}${src.query}${src.hash}`,
- newUrl: `${pathname}${src.query}${src.hash}`
- });
- }
- return Promise.resolve({
- type: 'redirect-external',
- destination: redirectTarget
- });
- }
- return Promise.resolve({
- type: 'next'
- });
- }
- function withMiddlewareEffects(options) {
- return matchesMiddleware(options).then((matches)=>{
- if (matches && options.fetchData) {
- return options.fetchData().then((data)=>getMiddlewareData(data.dataHref, data.response, options).then((effect)=>({
- dataHref: data.dataHref,
- cacheKey: data.cacheKey,
- json: data.json,
- response: data.response,
- text: data.text,
- effect
- }))).catch((_err)=>{
-
- return null;
- });
- }
- return null;
- });
- }
- const manualScrollRestoration = process.env.__NEXT_SCROLL_RESTORATION && typeof window !== 'undefined' && 'scrollRestoration' in window.history && !!function() {
- try {
- let v = '__next';
-
- return sessionStorage.setItem(v, v), sessionStorage.removeItem(v), true;
- } catch (n) {}
- }();
- const SSG_DATA_NOT_FOUND = Symbol('SSG_DATA_NOT_FOUND');
- function fetchRetry(url, attempts, options) {
- return fetch(url, {
-
-
-
-
-
-
-
-
-
-
-
- credentials: 'same-origin',
- method: options.method || 'GET',
- headers: Object.assign({}, options.headers, {
- 'x-nextjs-data': '1'
- })
- }).then((response)=>{
- return !response.ok && attempts > 1 && response.status >= 500 ? fetchRetry(url, attempts - 1, options) : response;
- });
- }
- const backgroundCache = {};
- function handleSmoothScroll(fn) {
- const htmlElement = document.documentElement;
- const existing = htmlElement.style.scrollBehavior;
- htmlElement.style.scrollBehavior = 'auto';
- fn();
- htmlElement.style.scrollBehavior = existing;
- }
- function tryToParseAsJSON(text) {
- try {
- return JSON.parse(text);
- } catch (error) {
- return null;
- }
- }
- function fetchNextData({ dataHref , inflightCache , isPrefetch , hasMiddleware , isServerRender , parseJSON , persistCache , isBackground , unstable_skipClientCache }) {
- const { href: cacheKey } = new URL(dataHref, window.location.href);
- var ref1;
- const getData = (params)=>{
- return fetchRetry(dataHref, isServerRender ? 3 : 1, {
- headers: isPrefetch ? {
- purpose: 'prefetch'
- } : {},
- method: (ref1 = params == null ? void 0 : params.method) != null ? ref1 : 'GET'
- }).then((response)=>{
- if (response.ok && (params == null ? void 0 : params.method) === 'HEAD') {
- return {
- dataHref,
- response,
- text: '',
- json: {},
- cacheKey
- };
- }
- return response.text().then((text)=>{
- if (!response.ok) {
-
- if (hasMiddleware && [
- 301,
- 302,
- 307,
- 308
- ].includes(response.status)) {
- return {
- dataHref,
- response,
- text,
- json: {},
- cacheKey
- };
- }
- if (!hasMiddleware && response.status === 404) {
- var ref;
- if ((ref = tryToParseAsJSON(text)) == null ? void 0 : ref.notFound) {
- return {
- dataHref,
- json: {
- notFound: SSG_DATA_NOT_FOUND
- },
- response,
- text,
- cacheKey
- };
- }
- }
- const error = new Error(`Failed to load static props`);
-
- if (!isServerRender) {
- (0, _routeLoader).markAssetError(error);
- }
- throw error;
- }
- return {
- dataHref,
- json: parseJSON ? tryToParseAsJSON(text) : null,
- response,
- text,
- cacheKey
- };
- });
- }).then((data)=>{
- if (!persistCache || process.env.NODE_ENV !== 'production' || data.response.headers.get('x-middleware-cache') === 'no-cache') {
- delete inflightCache[cacheKey];
- }
- return data;
- }).catch((err)=>{
- delete inflightCache[cacheKey];
- throw err;
- });
- };
-
-
-
-
- if (unstable_skipClientCache && persistCache) {
- return getData({}).then((data)=>{
- inflightCache[cacheKey] = Promise.resolve(data);
- return data;
- });
- }
- if (inflightCache[cacheKey] !== undefined) {
- return inflightCache[cacheKey];
- }
- return inflightCache[cacheKey] = getData(isBackground ? {
- method: 'HEAD'
- } : {});
- }
- function createKey() {
- return Math.random().toString(36).slice(2, 10);
- }
- function handleHardNavigation({ url , router }) {
-
-
- if (url === (0, _addBasePath).addBasePath((0, _addLocale).addLocale(router.asPath, router.locale))) {
- throw new Error(`Invariant: attempted to hard navigate to the same URL ${url} ${location.href}`);
- }
- window.location.href = url;
- }
- const getCancelledHandler = ({ route , router })=>{
- let cancelled = false;
- const cancel = router.clc = ()=>{
- cancelled = true;
- };
- const handleCancelled = ()=>{
- if (cancelled) {
- const error = new Error(`Abort fetching component for route: "${route}"`);
- error.cancelled = true;
- throw error;
- }
- if (cancel === router.clc) {
- router.clc = null;
- }
- };
- return handleCancelled;
- };
- class Router {
- reload() {
- window.location.reload();
- }
-
- back() {
- window.history.back();
- }
-
- push(url, as, options = {}) {
- if (process.env.__NEXT_SCROLL_RESTORATION) {
-
-
- if (manualScrollRestoration) {
- try {
-
- sessionStorage.setItem('__next_scroll_' + this._key, JSON.stringify({
- x: self.pageXOffset,
- y: self.pageYOffset
- }));
- } catch (e) {}
- }
- }
- ({ url , as } = prepareUrlAs(this, url, as));
- return this.change('pushState', url, as, options);
- }
-
- replace(url, as, options = {}) {
- ({ url , as } = prepareUrlAs(this, url, as));
- return this.change('replaceState', url, as, options);
- }
- change(method, url, as, options, forcedScroll) {
- var _this = this;
- return _async_to_generator(function*() {
- if (!isLocalURL(url)) {
- handleHardNavigation({
- url,
- router: _this
- });
- return false;
- }
-
-
-
- const isQueryUpdating = options._h;
- const shouldResolveHref = isQueryUpdating || options._shouldResolveHref || (0, _parsePath).parsePath(url).pathname === (0, _parsePath).parsePath(as).pathname;
- const nextState = _extends({}, _this.state);
-
-
-
- const readyStateChange = _this.isReady !== true;
- _this.isReady = true;
- const isSsr = _this.isSsr;
- if (!isQueryUpdating) {
- _this.isSsr = false;
- }
-
-
- if (isQueryUpdating && _this.clc) {
- return false;
- }
- const prevLocale = nextState.locale;
- if (process.env.__NEXT_I18N_SUPPORT) {
- nextState.locale = options.locale === false ? _this.defaultLocale : options.locale || nextState.locale;
- if (typeof options.locale === 'undefined') {
- options.locale = nextState.locale;
- }
- const parsedAs = (0, _parseRelativeUrl).parseRelativeUrl((0, _hasBasePath).hasBasePath(as) ? (0, _removeBasePath).removeBasePath(as) : as);
- const localePathResult = (0, _normalizeLocalePath).normalizeLocalePath(parsedAs.pathname, _this.locales);
- if (localePathResult.detectedLocale) {
- nextState.locale = localePathResult.detectedLocale;
- parsedAs.pathname = (0, _addBasePath).addBasePath(parsedAs.pathname);
- as = (0, _formatUrl).formatWithValidation(parsedAs);
- url = (0, _addBasePath).addBasePath((0, _normalizeLocalePath).normalizeLocalePath((0, _hasBasePath).hasBasePath(url) ? (0, _removeBasePath).removeBasePath(url) : url, _this.locales).pathname);
- }
- let didNavigate = false;
-
-
- if (process.env.__NEXT_I18N_SUPPORT) {
- var ref;
-
- if (!((ref = _this.locales) == null ? void 0 : ref.includes(nextState.locale))) {
- parsedAs.pathname = (0, _addLocale).addLocale(parsedAs.pathname, nextState.locale);
- handleHardNavigation({
- url: (0, _formatUrl).formatWithValidation(parsedAs),
- router: _this
- });
-
-
- didNavigate = true;
- }
- }
- const detectedDomain = (0, _detectDomainLocale).detectDomainLocale(_this.domainLocales, undefined, nextState.locale);
-
-
- if (process.env.__NEXT_I18N_SUPPORT) {
-
-
- if (!didNavigate && detectedDomain && _this.isLocaleDomain && self.location.hostname !== detectedDomain.domain) {
- const asNoBasePath = (0, _removeBasePath).removeBasePath(as);
- handleHardNavigation({
- url: `http${detectedDomain.http ? '' : 's'}://${detectedDomain.domain}${(0, _addBasePath).addBasePath(`${nextState.locale === detectedDomain.defaultLocale ? '' : `/${nextState.locale}`}${asNoBasePath === '/' ? '' : asNoBasePath}` || '/')}`,
- router: _this
- });
-
-
- didNavigate = true;
- }
- }
- if (didNavigate) {
- return new Promise(()=>{});
- }
- }
-
- if (_utils.ST) {
- performance.mark('routeChange');
- }
- const { shallow =false , scroll =true } = options;
- const routeProps = {
- shallow
- };
- if (_this._inFlightRoute && _this.clc) {
- if (!isSsr) {
- Router.events.emit('routeChangeError', buildCancellationError(), _this._inFlightRoute, routeProps);
- }
- _this.clc();
- _this.clc = null;
- }
- as = (0, _addBasePath).addBasePath((0, _addLocale).addLocale((0, _hasBasePath).hasBasePath(as) ? (0, _removeBasePath).removeBasePath(as) : as, options.locale, _this.defaultLocale));
- const cleanedAs = (0, _removeLocale).removeLocale((0, _hasBasePath).hasBasePath(as) ? (0, _removeBasePath).removeBasePath(as) : as, nextState.locale);
- _this._inFlightRoute = as;
- const localeChange = prevLocale !== nextState.locale;
-
-
- if (!isQueryUpdating && _this.onlyAHashChange(cleanedAs) && !localeChange) {
- nextState.asPath = cleanedAs;
- Router.events.emit('hashChangeStart', as, routeProps);
-
- _this.changeState(method, url, as, _extends({}, options, {
- scroll: false
- }));
- if (scroll) {
- _this.scrollToHash(cleanedAs);
- }
- try {
- yield _this.set(nextState, _this.components[nextState.route], null);
- } catch (err) {
- if ((0, _isError).default(err) && err.cancelled) {
- Router.events.emit('routeChangeError', err, cleanedAs, routeProps);
- }
- throw err;
- }
- Router.events.emit('hashChangeComplete', as, routeProps);
- return true;
- }
- let parsed = (0, _parseRelativeUrl).parseRelativeUrl(url);
- let { pathname , query } = parsed;
-
-
-
- let pages, rewrites;
- try {
- [pages, { __rewrites: rewrites }] = yield Promise.all([
- _this.pageLoader.getPageList(),
- (0, _routeLoader).getClientBuildManifest(),
- _this.pageLoader.getMiddleware(),
- ]);
- } catch (err) {
-
-
- handleHardNavigation({
- url: as,
- router: _this
- });
- return false;
- }
-
-
-
-
-
- if (!_this.urlIsNew(cleanedAs) && !localeChange) {
- method = 'replaceState';
- }
-
-
- let resolvedAs = as;
-
-
-
- pathname = pathname ? (0, _removeTrailingSlash).removeTrailingSlash((0, _removeBasePath).removeBasePath(pathname)) : pathname;
-
-
- const isMiddlewareMatch = yield matchesMiddleware({
- asPath: as,
- locale: nextState.locale,
- router: _this
- });
- if (options.shallow && isMiddlewareMatch) {
- pathname = _this.pathname;
- }
- if (shouldResolveHref && pathname !== '/_error') {
- options._shouldResolveHref = true;
- if (process.env.__NEXT_HAS_REWRITES && as.startsWith('/')) {
- const rewritesResult = (0, _resolveRewrites).default((0, _addBasePath).addBasePath((0, _addLocale).addLocale(cleanedAs, nextState.locale), true), pages, rewrites, query, (p)=>resolveDynamicRoute(p, pages), _this.locales);
- if (rewritesResult.externalDest) {
- handleHardNavigation({
- url: as,
- router: _this
- });
- return true;
- }
- if (!isMiddlewareMatch) {
- resolvedAs = rewritesResult.asPath;
- }
- if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {
-
-
- pathname = rewritesResult.resolvedHref;
- parsed.pathname = (0, _addBasePath).addBasePath(pathname);
- if (!isMiddlewareMatch) {
- url = (0, _formatUrl).formatWithValidation(parsed);
- }
- }
- } else {
- parsed.pathname = resolveDynamicRoute(pathname, pages);
- if (parsed.pathname !== pathname) {
- pathname = parsed.pathname;
- parsed.pathname = (0, _addBasePath).addBasePath(pathname);
- if (!isMiddlewareMatch) {
- url = (0, _formatUrl).formatWithValidation(parsed);
- }
- }
- }
- }
- if (!isLocalURL(as)) {
- if (process.env.NODE_ENV !== 'production') {
- 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`);
- }
- handleHardNavigation({
- url: as,
- router: _this
- });
- return false;
- }
- resolvedAs = (0, _removeLocale).removeLocale((0, _removeBasePath).removeBasePath(resolvedAs), nextState.locale);
- let route = (0, _removeTrailingSlash).removeTrailingSlash(pathname);
- let routeMatch = false;
- if ((0, _isDynamic).isDynamicRoute(route)) {
- const parsedAs = (0, _parseRelativeUrl).parseRelativeUrl(resolvedAs);
- const asPathname = parsedAs.pathname;
- const routeRegex = (0, _routeRegex).getRouteRegex(route);
- routeMatch = (0, _routeMatcher).getRouteMatcher(routeRegex)(asPathname);
- const shouldInterpolate = route === asPathname;
- const interpolatedAs = shouldInterpolate ? interpolateAs(route, asPathname, query) : {};
- if (!routeMatch || shouldInterpolate && !interpolatedAs.result) {
- const missingParams = Object.keys(routeRegex.groups).filter((param)=>!query[param]);
- if (missingParams.length > 0 && !isMiddlewareMatch) {
- if (process.env.NODE_ENV !== 'production') {
- console.warn(`${shouldInterpolate ? `Interpolating href` : `Mismatching \`as\` and \`href\``} failed to manually provide ` + `the params: ${missingParams.join(', ')} in the \`href\`'s \`query\``);
- }
- 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'}`);
- }
- } else if (shouldInterpolate) {
- as = (0, _formatUrl).formatWithValidation(Object.assign({}, parsedAs, {
- pathname: interpolatedAs.result,
- query: omit(query, interpolatedAs.params)
- }));
- } else {
-
- Object.assign(query, routeMatch);
- }
- }
- if (!isQueryUpdating) {
- Router.events.emit('routeChangeStart', as, routeProps);
- }
- try {
- var ref2, ref3;
- let routeInfo = yield _this.getRouteInfo({
- route,
- pathname,
- query,
- as,
- resolvedAs,
- routeProps,
- locale: nextState.locale,
- isPreview: nextState.isPreview,
- hasMiddleware: isMiddlewareMatch
- });
- if ('route' in routeInfo && isMiddlewareMatch) {
- pathname = routeInfo.route || route;
- route = pathname;
- if (!routeProps.shallow) {
- query = Object.assign({}, routeInfo.query || {}, query);
- }
- const cleanedParsedPathname = (0, _hasBasePath).hasBasePath(parsed.pathname) ? (0, _removeBasePath).removeBasePath(parsed.pathname) : parsed.pathname;
- if (routeMatch && pathname !== cleanedParsedPathname) {
- Object.keys(routeMatch).forEach((key)=>{
- if (routeMatch && query[key] === routeMatch[key]) {
- delete query[key];
- }
- });
- }
- if ((0, _isDynamic).isDynamicRoute(pathname)) {
- const prefixedAs = !routeProps.shallow && routeInfo.resolvedAs ? routeInfo.resolvedAs : (0, _addBasePath).addBasePath((0, _addLocale).addLocale(new URL(as, location.href).pathname, nextState.locale), true);
- let rewriteAs = prefixedAs;
- if ((0, _hasBasePath).hasBasePath(rewriteAs)) {
- rewriteAs = (0, _removeBasePath).removeBasePath(rewriteAs);
- }
- if (process.env.__NEXT_I18N_SUPPORT) {
- const localeResult = (0, _normalizeLocalePath).normalizeLocalePath(rewriteAs, _this.locales);
- nextState.locale = localeResult.detectedLocale || nextState.locale;
- rewriteAs = localeResult.pathname;
- }
- const routeRegex = (0, _routeRegex).getRouteRegex(pathname);
- const curRouteMatch = (0, _routeMatcher).getRouteMatcher(routeRegex)(rewriteAs);
- if (curRouteMatch) {
- Object.assign(query, curRouteMatch);
- }
- }
- }
-
- if ('type' in routeInfo) {
- if (routeInfo.type === 'redirect-internal') {
- return _this.change(method, routeInfo.newUrl, routeInfo.newAs, options);
- } else {
- handleHardNavigation({
- url: routeInfo.destination,
- router: _this
- });
- return new Promise(()=>{});
- }
- }
- let { error , props , __N_SSG , __N_SSP } = routeInfo;
- const component = routeInfo.Component;
- if (component && component.unstable_scriptLoader) {
- const scripts = [].concat(component.unstable_scriptLoader());
- scripts.forEach((script)=>{
- (0, _script).handleClientScriptLoad(script.props);
- });
- }
-
- if ((__N_SSG || __N_SSP) && props) {
- if (props.pageProps && props.pageProps.__N_REDIRECT) {
-
- options.locale = false;
- const destination = props.pageProps.__N_REDIRECT;
-
-
-
- if (destination.startsWith('/') && props.pageProps.__N_REDIRECT_BASE_PATH !== false) {
- const parsedHref = (0, _parseRelativeUrl).parseRelativeUrl(destination);
- parsedHref.pathname = resolveDynamicRoute(parsedHref.pathname, pages);
- const { url: newUrl , as: newAs } = prepareUrlAs(_this, destination, destination);
- return _this.change(method, newUrl, newAs, options);
- }
- handleHardNavigation({
- url: destination,
- router: _this
- });
- return new Promise(()=>{});
- }
- nextState.isPreview = !!props.__N_PREVIEW;
-
- if (props.notFound === SSG_DATA_NOT_FOUND) {
- let notFoundRoute;
- try {
- yield _this.fetchComponent('/404');
- notFoundRoute = '/404';
- } catch (_) {
- notFoundRoute = '/_error';
- }
- routeInfo = yield _this.getRouteInfo({
- route: notFoundRoute,
- pathname: notFoundRoute,
- query,
- as,
- resolvedAs,
- routeProps: {
- shallow: false
- },
- locale: nextState.locale,
- isPreview: nextState.isPreview
- });
- if ('type' in routeInfo) {
- throw new Error(`Unexpected middleware effect on /404`);
- }
- }
- }
- Router.events.emit('beforeHistoryChange', as, routeProps);
- _this.changeState(method, url, as, options);
- 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)) {
-
-
- props.pageProps.statusCode = 500;
- }
- var _route;
-
- const isValidShallowRoute = options.shallow && nextState.route === ((_route = routeInfo.route) != null ? _route : route);
- var _scroll;
- const shouldScroll = (_scroll = options.scroll) != null ? _scroll : !options._h && !isValidShallowRoute;
- const resetScroll = shouldScroll ? {
- x: 0,
- y: 0
- } : null;
-
- const upcomingRouterState = _extends({}, nextState, {
- route,
- pathname,
- query,
- asPath: cleanedAs,
- isFallback: false
- });
- const upcomingScrollState = forcedScroll != null ? forcedScroll : resetScroll;
-
-
-
- const canSkipUpdating = options._h && !upcomingScrollState && !readyStateChange && !localeChange && (0, _compareStates).compareRouterStates(upcomingRouterState, _this.state);
- if (!canSkipUpdating) {
- yield _this.set(upcomingRouterState, routeInfo, upcomingScrollState).catch((e)=>{
- if (e.cancelled) error = error || e;
- else throw e;
- });
- if (error) {
- if (!isQueryUpdating) {
- Router.events.emit('routeChangeError', error, cleanedAs, routeProps);
- }
- throw error;
- }
- if (process.env.__NEXT_I18N_SUPPORT) {
- if (nextState.locale) {
- document.documentElement.lang = nextState.locale;
- }
- }
- if (!isQueryUpdating) {
- Router.events.emit('routeChangeComplete', as, routeProps);
- }
-
- const hashRegex = /#.+$/;
- if (shouldScroll && hashRegex.test(as)) {
- _this.scrollToHash(as);
- }
- }
- return true;
- } catch (err1) {
- if ((0, _isError).default(err1) && err1.cancelled) {
- return false;
- }
- throw err1;
- }
- })();
- }
- changeState(method, url, as, options = {}) {
- if (process.env.NODE_ENV !== 'production') {
- if (typeof window.history === 'undefined') {
- console.error(`Warning: window.history is not available.`);
- return;
- }
- if (typeof window.history[method] === 'undefined') {
- console.error(`Warning: window.history.${method} is not available`);
- return;
- }
- }
- if (method !== 'pushState' || (0, _utils).getURL() !== as) {
- this._shallow = options.shallow;
- window.history[method]({
- url,
- as,
- options,
- __N: true,
- key: this._key = method !== 'pushState' ? this._key : createKey()
- },
-
-
- '', as);
- }
- }
- handleRouteInfoError(err, pathname, query, as, routeProps, loadErrorFail) {
- var _this = this;
- return _async_to_generator(function*() {
- console.error(err);
- if (err.cancelled) {
-
- throw err;
- }
- if ((0, _routeLoader).isAssetError(err) || loadErrorFail) {
- Router.events.emit('routeChangeError', err, as, routeProps);
-
-
-
-
-
- handleHardNavigation({
- url: as,
- router: _this
- });
-
-
- throw buildCancellationError();
- }
- try {
- let props;
- const { page: Component , styleSheets } = yield _this.fetchComponent('/_error');
- const routeInfo = {
- props,
- Component,
- styleSheets,
- err,
- error: err
- };
- if (!routeInfo.props) {
- try {
- routeInfo.props = yield _this.getInitialProps(Component, {
- err,
- pathname,
- query
- });
- } catch (gipErr) {
- console.error('Error in error page `getInitialProps`: ', gipErr);
- routeInfo.props = {};
- }
- }
- return routeInfo;
- } catch (routeInfoErr) {
- return _this.handleRouteInfoError((0, _isError).default(routeInfoErr) ? routeInfoErr : new Error(routeInfoErr + ''), pathname, query, as, routeProps, true);
- }
- })();
- }
- getRouteInfo({ route: requestedRoute , pathname , query , as , resolvedAs , routeProps , locale , hasMiddleware , isPreview , unstable_skipClientCache }) {
- var _this = this;
- return _async_to_generator(function*() {
-
- let route = requestedRoute;
- try {
- var ref, ref4, ref5;
- const handleCancelled = getCancelledHandler({
- route,
- router: _this
- });
- let existingInfo = _this.components[route];
- if (routeProps.shallow && existingInfo && _this.route === route) {
- return existingInfo;
- }
- if (hasMiddleware) {
- existingInfo = undefined;
- }
- let cachedRouteInfo = existingInfo && !('initial' in existingInfo) && process.env.NODE_ENV !== 'development' ? existingInfo : undefined;
- const fetchNextDataParams = {
- dataHref: _this.pageLoader.getDataHref({
- href: (0, _formatUrl).formatWithValidation({
- pathname,
- query
- }),
- skipInterpolation: true,
- asPath: resolvedAs,
- locale
- }),
- hasMiddleware: true,
- isServerRender: _this.isSsr,
- parseJSON: true,
- inflightCache: _this.sdc,
- persistCache: !isPreview,
- isPrefetch: false,
- unstable_skipClientCache
- };
- const data = yield withMiddlewareEffects({
- fetchData: ()=>fetchNextData(fetchNextDataParams),
- asPath: resolvedAs,
- locale: locale,
- router: _this
- });
- handleCancelled();
- 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') {
- return data.effect;
- }
- if ((data == null ? void 0 : (ref5 = data.effect) == null ? void 0 : ref5.type) === 'rewrite') {
- route = (0, _removeTrailingSlash).removeTrailingSlash(data.effect.resolvedHref);
- pathname = data.effect.resolvedHref;
- query = _extends({}, query, data.effect.parsedAs.query);
- resolvedAs = (0, _removeBasePath).removeBasePath((0, _normalizeLocalePath).normalizeLocalePath(data.effect.parsedAs.pathname, _this.locales).pathname);
-
- existingInfo = _this.components[route];
- if (routeProps.shallow && existingInfo && _this.route === route && !hasMiddleware) {
-
-
-
- return _extends({}, existingInfo, {
- route
- });
- }
- }
- if (route === '/api' || route.startsWith('/api/')) {
- handleHardNavigation({
- url: as,
- router: _this
- });
- return new Promise(()=>{});
- }
- const routeInfo = cachedRouteInfo || (yield _this.fetchComponent(route).then((res)=>({
- Component: res.page,
- styleSheets: res.styleSheets,
- __N_SSG: res.mod.__N_SSG,
- __N_SSP: res.mod.__N_SSP
- })));
- if (process.env.NODE_ENV !== 'production') {
- const { isValidElementType } = require('next/dist/compiled/react-is');
- if (!isValidElementType(routeInfo.Component)) {
- throw new Error(`The default export is not a React Component in page: "${pathname}"`);
- }
- }
- const shouldFetchData = routeInfo.__N_SSG || routeInfo.__N_SSP;
- const { props , cacheKey } = yield _this._getData(_async_to_generator(function*() {
- if (shouldFetchData) {
- const { json , cacheKey: _cacheKey } = (data == null ? void 0 : data.json) ? data : yield fetchNextData({
- dataHref: _this.pageLoader.getDataHref({
- href: (0, _formatUrl).formatWithValidation({
- pathname,
- query
- }),
- asPath: resolvedAs,
- locale
- }),
- isServerRender: _this.isSsr,
- parseJSON: true,
- inflightCache: _this.sdc,
- persistCache: !isPreview,
- isPrefetch: false,
- unstable_skipClientCache
- });
- return {
- cacheKey: _cacheKey,
- props: json || {}
- };
- }
- return {
- headers: {},
- cacheKey: '',
- props: yield _this.getInitialProps(routeInfo.Component,
- {
- pathname,
- query,
- asPath: as,
- locale,
- locales: _this.locales,
- defaultLocale: _this.defaultLocale
- })
- };
- }));
-
-
-
- if (routeInfo.__N_SSP && fetchNextDataParams.dataHref) {
- delete _this.sdc[cacheKey];
- }
-
-
- if (!_this.isPreview && routeInfo.__N_SSG && process.env.NODE_ENV !== 'development') {
- fetchNextData(Object.assign({}, fetchNextDataParams, {
- isBackground: true,
- persistCache: false,
- inflightCache: backgroundCache
- })).catch(()=>{});
- }
- props.pageProps = Object.assign({}, props.pageProps);
- routeInfo.props = props;
- routeInfo.route = route;
- routeInfo.query = query;
- routeInfo.resolvedAs = resolvedAs;
- _this.components[route] = routeInfo;
- return routeInfo;
- } catch (err) {
- return _this.handleRouteInfoError((0, _isError).getProperError(err), pathname, query, as, routeProps);
- }
- })();
- }
- set(state, data, resetScroll) {
- this.state = state;
- return this.sub(data, this.components['/_app'].Component, resetScroll);
- }
-
- beforePopState(cb) {
- this._bps = cb;
- }
- onlyAHashChange(as) {
- if (!this.asPath) return false;
- const [oldUrlNoHash, oldHash] = this.asPath.split('#');
- const [newUrlNoHash, newHash] = as.split('#');
-
- if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) {
- return true;
- }
-
- if (oldUrlNoHash !== newUrlNoHash) {
- return false;
- }
-
-
-
-
- return oldHash !== newHash;
- }
- scrollToHash(as) {
- const [, hash = ''] = as.split('#');
-
-
- if (hash === '' || hash === 'top') {
- handleSmoothScroll(()=>window.scrollTo(0, 0));
- return;
- }
-
- const rawHash = decodeURIComponent(hash);
-
- const idEl = document.getElementById(rawHash);
- if (idEl) {
- handleSmoothScroll(()=>idEl.scrollIntoView());
- return;
- }
-
-
- const nameEl = document.getElementsByName(rawHash)[0];
- if (nameEl) {
- handleSmoothScroll(()=>nameEl.scrollIntoView());
- }
- }
- urlIsNew(asPath) {
- return this.asPath !== asPath;
- }
-
- prefetch(url, asPath = url, options = {}) {
- var _this = this;
- return _async_to_generator(function*() {
- if (typeof window !== 'undefined' && (0, _isBot).isBot(window.navigator.userAgent)) {
-
-
-
- return;
- }
- let parsed = (0, _parseRelativeUrl).parseRelativeUrl(url);
- let { pathname , query } = parsed;
- if (process.env.__NEXT_I18N_SUPPORT) {
- if (options.locale === false) {
- pathname = (0, _normalizeLocalePath).normalizeLocalePath(pathname, _this.locales).pathname;
- parsed.pathname = pathname;
- url = (0, _formatUrl).formatWithValidation(parsed);
- let parsedAs = (0, _parseRelativeUrl).parseRelativeUrl(asPath);
- const localePathResult = (0, _normalizeLocalePath).normalizeLocalePath(parsedAs.pathname, _this.locales);
- parsedAs.pathname = localePathResult.pathname;
- options.locale = localePathResult.detectedLocale || _this.defaultLocale;
- asPath = (0, _formatUrl).formatWithValidation(parsedAs);
- }
- }
- const pages = yield _this.pageLoader.getPageList();
- let resolvedAs = asPath;
- const locale = typeof options.locale !== 'undefined' ? options.locale || undefined : _this.locale;
- if (process.env.__NEXT_HAS_REWRITES && asPath.startsWith('/')) {
- let rewrites;
- ({ __rewrites: rewrites } = yield (0, _routeLoader).getClientBuildManifest());
- 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);
- if (rewritesResult.externalDest) {
- return;
- }
- resolvedAs = (0, _removeLocale).removeLocale((0, _removeBasePath).removeBasePath(rewritesResult.asPath), _this.locale);
- if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {
-
-
- pathname = rewritesResult.resolvedHref;
- parsed.pathname = pathname;
- url = (0, _formatUrl).formatWithValidation(parsed);
- }
- }
- parsed.pathname = resolveDynamicRoute(parsed.pathname, pages);
- if ((0, _isDynamic).isDynamicRoute(parsed.pathname)) {
- pathname = parsed.pathname;
- parsed.pathname = pathname;
- Object.assign(query, (0, _routeMatcher).getRouteMatcher((0, _routeRegex).getRouteRegex(parsed.pathname))((0, _parsePath).parsePath(asPath).pathname) || {});
- url = (0, _formatUrl).formatWithValidation(parsed);
- }
-
- if (process.env.NODE_ENV !== 'production') {
- return;
- }
- const route = (0, _removeTrailingSlash).removeTrailingSlash(pathname);
- yield Promise.all([
- _this.pageLoader._isSsg(route).then((isSsg)=>{
- return isSsg ? fetchNextData({
- dataHref: _this.pageLoader.getDataHref({
- href: url,
- asPath: resolvedAs,
- locale: locale
- }),
- isServerRender: false,
- parseJSON: true,
- inflightCache: _this.sdc,
- persistCache: !_this.isPreview,
- isPrefetch: true,
- unstable_skipClientCache: options.unstable_skipClientCache || options.priority && !!process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE
- }).then(()=>false) : false;
- }),
- _this.pageLoader[options.priority ? 'loadPage' : 'prefetch'](route),
- ]);
- })();
- }
- fetchComponent(route) {
- var _this = this;
- return _async_to_generator(function*() {
- const handleCancelled = getCancelledHandler({
- route,
- router: _this
- });
- try {
- const componentResult = yield _this.pageLoader.loadPage(route);
- handleCancelled();
- return componentResult;
- } catch (err) {
- handleCancelled();
- throw err;
- }
- })();
- }
- _getData(fn) {
- let cancelled = false;
- const cancel = ()=>{
- cancelled = true;
- };
- this.clc = cancel;
- return fn().then((data)=>{
- if (cancel === this.clc) {
- this.clc = null;
- }
- if (cancelled) {
- const err = new Error('Loading initial props cancelled');
- err.cancelled = true;
- throw err;
- }
- return data;
- });
- }
- _getFlightData(dataHref) {
-
- return fetchNextData({
- dataHref,
- isServerRender: true,
- parseJSON: false,
- inflightCache: this.sdc,
- persistCache: false,
- isPrefetch: false
- }).then(({ text })=>({
- data: text
- }));
- }
- getInitialProps(Component, ctx) {
- const { Component: App } = this.components['/_app'];
- const AppTree = this._wrapApp(App);
- ctx.AppTree = AppTree;
- return (0, _utils).loadGetInitialProps(App, {
- AppTree,
- Component,
- router: this,
- ctx
- });
- }
- get route() {
- return this.state.route;
- }
- get pathname() {
- return this.state.pathname;
- }
- get query() {
- return this.state.query;
- }
- get asPath() {
- return this.state.asPath;
- }
- get locale() {
- return this.state.locale;
- }
- get isFallback() {
- return this.state.isFallback;
- }
- get isPreview() {
- return this.state.isPreview;
- }
- constructor(pathname1, query1, as1, { initialProps , pageLoader , App , wrapApp , Component , err , subscription , isFallback , locale , locales , defaultLocale , domainLocales , isPreview }){
-
- this.sdc = {};
- this.isFirstPopStateEvent = true;
- this._key = createKey();
- this.onPopState = (e)=>{
- const { isFirstPopStateEvent } = this;
- this.isFirstPopStateEvent = false;
- const state = e.state;
- if (!state) {
-
-
-
-
-
-
-
-
-
- const { pathname , query } = this;
- this.changeState('replaceState', (0, _formatUrl).formatWithValidation({
- pathname: (0, _addBasePath).addBasePath(pathname),
- query
- }), (0, _utils).getURL());
- return;
- }
-
- if (state.__NA) {
- window.location.reload();
- return;
- }
- if (!state.__N) {
- return;
- }
-
- if (isFirstPopStateEvent && this.locale === state.options.locale && state.as === this.asPath) {
- return;
- }
- let forcedScroll;
- const { url , as , options , key } = state;
- if (process.env.__NEXT_SCROLL_RESTORATION) {
- if (manualScrollRestoration) {
- if (this._key !== key) {
-
- try {
- sessionStorage.setItem('__next_scroll_' + this._key, JSON.stringify({
- x: self.pageXOffset,
- y: self.pageYOffset
- }));
- } catch (e) {}
-
- try {
- const v = sessionStorage.getItem('__next_scroll_' + key);
- forcedScroll = JSON.parse(v);
- } catch (e1) {
- forcedScroll = {
- x: 0,
- y: 0
- };
- }
- }
- }
- }
- this._key = key;
- const { pathname } = (0, _parseRelativeUrl).parseRelativeUrl(url);
-
-
- if (this.isSsr && as === (0, _addBasePath).addBasePath(this.asPath) && pathname === (0, _addBasePath).addBasePath(this.pathname)) {
- return;
- }
-
-
- if (this._bps && !this._bps(state)) {
- return;
- }
- this.change('replaceState', url, as, Object.assign({}, options, {
- shallow: options.shallow && this._shallow,
- locale: options.locale || this.defaultLocale,
-
- _h: 0
- }), forcedScroll);
- };
-
- const route = (0, _removeTrailingSlash).removeTrailingSlash(pathname1);
-
- this.components = {};
-
-
-
- if (pathname1 !== '/_error') {
- this.components[route] = {
- Component,
- initial: true,
- props: initialProps,
- err,
- __N_SSG: initialProps && initialProps.__N_SSG,
- __N_SSP: initialProps && initialProps.__N_SSP
- };
- }
- this.components['/_app'] = {
- Component: App,
- styleSheets: []
- };
-
-
- this.events = Router.events;
- this.pageLoader = pageLoader;
-
-
- const autoExportDynamic = (0, _isDynamic).isDynamicRoute(pathname1) && self.__NEXT_DATA__.autoExport;
- this.basePath = process.env.__NEXT_ROUTER_BASEPATH || '';
- this.sub = subscription;
- this.clc = null;
- this._wrapApp = wrapApp;
-
-
- this.isSsr = true;
- this.isLocaleDomain = false;
- 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);
- if (process.env.__NEXT_I18N_SUPPORT) {
- this.locales = locales;
- this.defaultLocale = defaultLocale;
- this.domainLocales = domainLocales;
- this.isLocaleDomain = !!(0, _detectDomainLocale).detectDomainLocale(domainLocales, self.location.hostname);
- }
- this.state = {
- route,
- pathname: pathname1,
- query: query1,
- asPath: autoExportDynamic ? pathname1 : as1,
- isPreview: !!isPreview,
- locale: process.env.__NEXT_I18N_SUPPORT ? locale : undefined,
- isFallback
- };
- this._initialMatchesMiddlewarePromise = Promise.resolve(false);
- if (typeof window !== 'undefined') {
-
-
- if (!as1.startsWith('//')) {
-
-
- const options = {
- locale
- };
- const asPath = (0, _utils).getURL();
- this._initialMatchesMiddlewarePromise = matchesMiddleware({
- router: this,
- locale,
- asPath
- }).then((matches)=>{
- options._shouldResolveHref = as1 !== pathname1;
- this.changeState('replaceState', matches ? asPath : (0, _formatUrl).formatWithValidation({
- pathname: (0, _addBasePath).addBasePath(pathname1),
- query: query1
- }), asPath, options);
- return matches;
- });
- }
- window.addEventListener('popstate', this.onPopState);
-
-
- if (process.env.__NEXT_SCROLL_RESTORATION) {
- if (manualScrollRestoration) {
- window.history.scrollRestoration = 'manual';
- }
- }
- }
- }
- }
- Router.events = (0, _mitt).default();
- exports.default = Router;
|