Initial boiler plate project

This commit is contained in:
2024-09-24 03:52:46 +00:00
parent 6120b2d6c3
commit 154b93e267
10034 changed files with 2079352 additions and 2 deletions

View File

@ -0,0 +1,4 @@
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime';
import type { FlightDataPath } from '../../../server/app-render/types';
import type { PrefetchCacheEntry } from './router-reducer-types';
export declare function applyFlightData(existingCache: CacheNode, cache: CacheNode, flightDataPath: FlightDataPath, prefetchEntry?: PrefetchCacheEntry): boolean;

View File

@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "applyFlightData", {
enumerable: true,
get: function() {
return applyFlightData;
}
});
const _filllazyitemstillleafwithhead = require("./fill-lazy-items-till-leaf-with-head");
const _fillcachewithnewsubtreedata = require("./fill-cache-with-new-subtree-data");
function applyFlightData(existingCache, cache, flightDataPath, prefetchEntry) {
// The one before last item is the router state tree patch
const [treePatch, cacheNodeSeedData, head] = flightDataPath.slice(-3);
// Handles case where prefetch only returns the router tree patch without rendered components.
if (cacheNodeSeedData === null) {
return false;
}
if (flightDataPath.length === 3) {
const rsc = cacheNodeSeedData[2];
const loading = cacheNodeSeedData[3];
cache.loading = loading;
cache.rsc = rsc;
// This is a PPR-only field. When PPR is enabled, we shouldn't hit
// this path during a navigation, but until PPR is fully implemented
// yet it's possible the existing node does have a non-null
// `prefetchRsc`. As an incremental step, we'll just de-opt to the
// old behavior — no PPR value.
cache.prefetchRsc = null;
(0, _filllazyitemstillleafwithhead.fillLazyItemsTillLeafWithHead)(cache, existingCache, treePatch, cacheNodeSeedData, head, prefetchEntry);
} else {
// Copy rsc for the root node of the cache.
cache.rsc = existingCache.rsc;
// This is a PPR-only field. Unlike the previous branch, since we're
// just cloning the existing cache node, we might as well keep the
// PPR value, if it exists.
cache.prefetchRsc = existingCache.prefetchRsc;
cache.parallelRoutes = new Map(existingCache.parallelRoutes);
cache.loading = existingCache.loading;
// Create a copy of the existing cache with the rsc applied.
(0, _fillcachewithnewsubtreedata.fillCacheWithNewSubTreeData)(cache, existingCache, flightDataPath, prefetchEntry);
}
return true;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=apply-flight-data.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/apply-flight-data.ts"],"names":["applyFlightData","existingCache","cache","flightDataPath","prefetchEntry","treePatch","cacheNodeSeedData","head","slice","length","rsc","loading","prefetchRsc","fillLazyItemsTillLeafWithHead","parallelRoutes","Map","fillCacheWithNewSubTreeData"],"mappings":";;;;+BAMgBA;;;eAAAA;;;+CAJ8B;6CACF;AAGrC,SAASA,gBACdC,aAAwB,EACxBC,KAAgB,EAChBC,cAA8B,EAC9BC,aAAkC;IAElC,0DAA0D;IAC1D,MAAM,CAACC,WAAWC,mBAAmBC,KAAK,GAAGJ,eAAeK,KAAK,CAAC,CAAC;IAEnE,8FAA8F;IAC9F,IAAIF,sBAAsB,MAAM;QAC9B,OAAO;IACT;IAEA,IAAIH,eAAeM,MAAM,KAAK,GAAG;QAC/B,MAAMC,MAAMJ,iBAAiB,CAAC,EAAE;QAChC,MAAMK,UAAUL,iBAAiB,CAAC,EAAE;QACpCJ,MAAMS,OAAO,GAAGA;QAChBT,MAAMQ,GAAG,GAAGA;QACZ,kEAAkE;QAClE,oEAAoE;QACpE,2DAA2D;QAC3D,kEAAkE;QAClE,+BAA+B;QAC/BR,MAAMU,WAAW,GAAG;QACpBC,IAAAA,4DAA6B,EAC3BX,OACAD,eACAI,WACAC,mBACAC,MACAH;IAEJ,OAAO;QACL,2CAA2C;QAC3CF,MAAMQ,GAAG,GAAGT,cAAcS,GAAG;QAC7B,oEAAoE;QACpE,kEAAkE;QAClE,2BAA2B;QAC3BR,MAAMU,WAAW,GAAGX,cAAcW,WAAW;QAC7CV,MAAMY,cAAc,GAAG,IAAIC,IAAId,cAAca,cAAc;QAC3DZ,MAAMS,OAAO,GAAGV,cAAcU,OAAO;QACrC,4DAA4D;QAC5DK,IAAAA,wDAA2B,EACzBd,OACAD,eACAE,gBACAC;IAEJ;IAEA,OAAO;AACT"}

View File

@ -0,0 +1,7 @@
import type { FlightRouterState, FlightSegmentPath } from '../../../server/app-render/types';
/**
* Apply the router state from the Flight response, but skip patching default segments.
* Useful for patching the router cache when navigating, where we persist the existing default segment if there isn't a new one.
* Creates a new router state tree.
*/
export declare function applyRouterStatePatchToTree(flightSegmentPath: FlightSegmentPath, flightRouterState: FlightRouterState, treePatch: FlightRouterState, path: string): FlightRouterState | null;

View File

@ -0,0 +1,104 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "applyRouterStatePatchToTree", {
enumerable: true,
get: function() {
return applyRouterStatePatchToTree;
}
});
const _segment = require("../../../shared/lib/segment");
const _matchsegments = require("../match-segments");
const _refetchinactiveparallelsegments = require("./refetch-inactive-parallel-segments");
/**
* Deep merge of the two router states. Parallel route keys are preserved if the patch doesn't have them.
*/ function applyPatch(initialTree, patchTree, flightSegmentPath) {
const [initialSegment, initialParallelRoutes] = initialTree;
const [patchSegment, patchParallelRoutes] = patchTree;
// if the applied patch segment is __DEFAULT__ then it can be ignored in favor of the initial tree
// this is because the __DEFAULT__ segment is used as a placeholder on navigation
if (patchSegment === _segment.DEFAULT_SEGMENT_KEY && initialSegment !== _segment.DEFAULT_SEGMENT_KEY) {
return initialTree;
}
if ((0, _matchsegments.matchSegment)(initialSegment, patchSegment)) {
const newParallelRoutes = {};
for(const key in initialParallelRoutes){
const isInPatchTreeParallelRoutes = typeof patchParallelRoutes[key] !== "undefined";
if (isInPatchTreeParallelRoutes) {
newParallelRoutes[key] = applyPatch(initialParallelRoutes[key], patchParallelRoutes[key], flightSegmentPath);
} else {
newParallelRoutes[key] = initialParallelRoutes[key];
}
}
for(const key in patchParallelRoutes){
if (newParallelRoutes[key]) {
continue;
}
newParallelRoutes[key] = patchParallelRoutes[key];
}
const tree = [
initialSegment,
newParallelRoutes
];
// Copy over the existing tree
if (initialTree[2]) {
tree[2] = initialTree[2];
}
if (initialTree[3]) {
tree[3] = initialTree[3];
}
if (initialTree[4]) {
tree[4] = initialTree[4];
}
return tree;
}
return patchTree;
}
function applyRouterStatePatchToTree(flightSegmentPath, flightRouterState, treePatch, path) {
const [segment, parallelRoutes, url, refetch, isRootLayout] = flightRouterState;
// Root refresh
if (flightSegmentPath.length === 1) {
const tree = applyPatch(flightRouterState, treePatch, flightSegmentPath);
(0, _refetchinactiveparallelsegments.addRefreshMarkerToActiveParallelSegments)(tree, path);
return tree;
}
const [currentSegment, parallelRouteKey] = flightSegmentPath;
// Tree path returned from the server should always match up with the current tree in the browser
if (!(0, _matchsegments.matchSegment)(currentSegment, segment)) {
return null;
}
const lastSegment = flightSegmentPath.length === 2;
let parallelRoutePatch;
if (lastSegment) {
parallelRoutePatch = applyPatch(parallelRoutes[parallelRouteKey], treePatch, flightSegmentPath);
} else {
parallelRoutePatch = applyRouterStatePatchToTree(flightSegmentPath.slice(2), parallelRoutes[parallelRouteKey], treePatch, path);
if (parallelRoutePatch === null) {
return null;
}
}
const tree = [
flightSegmentPath[0],
{
...parallelRoutes,
[parallelRouteKey]: parallelRoutePatch
},
url,
refetch
];
// Current segment is the root layout
if (isRootLayout) {
tree[4] = true;
}
(0, _refetchinactiveparallelsegments.addRefreshMarkerToActiveParallelSegments)(tree, path);
return tree;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=apply-router-state-patch-to-tree.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/apply-router-state-patch-to-tree.ts"],"names":["applyRouterStatePatchToTree","applyPatch","initialTree","patchTree","flightSegmentPath","initialSegment","initialParallelRoutes","patchSegment","patchParallelRoutes","DEFAULT_SEGMENT_KEY","matchSegment","newParallelRoutes","key","isInPatchTreeParallelRoutes","tree","flightRouterState","treePatch","path","segment","parallelRoutes","url","refetch","isRootLayout","length","addRefreshMarkerToActiveParallelSegments","currentSegment","parallelRouteKey","lastSegment","parallelRoutePatch","slice"],"mappings":";;;;+BA8EgBA;;;eAAAA;;;yBA1EoB;+BACP;iDAC4B;AAEzD;;CAEC,GACD,SAASC,WACPC,WAA8B,EAC9BC,SAA4B,EAC5BC,iBAAoC;IAEpC,MAAM,CAACC,gBAAgBC,sBAAsB,GAAGJ;IAChD,MAAM,CAACK,cAAcC,oBAAoB,GAAGL;IAE5C,kGAAkG;IAClG,iFAAiF;IACjF,IACEI,iBAAiBE,4BAAmB,IACpCJ,mBAAmBI,4BAAmB,EACtC;QACA,OAAOP;IACT;IAEA,IAAIQ,IAAAA,2BAAY,EAACL,gBAAgBE,eAAe;QAC9C,MAAMI,oBAA0C,CAAC;QACjD,IAAK,MAAMC,OAAON,sBAAuB;YACvC,MAAMO,8BACJ,OAAOL,mBAAmB,CAACI,IAAI,KAAK;YACtC,IAAIC,6BAA6B;gBAC/BF,iBAAiB,CAACC,IAAI,GAAGX,WACvBK,qBAAqB,CAACM,IAAI,EAC1BJ,mBAAmB,CAACI,IAAI,EACxBR;YAEJ,OAAO;gBACLO,iBAAiB,CAACC,IAAI,GAAGN,qBAAqB,CAACM,IAAI;YACrD;QACF;QAEA,IAAK,MAAMA,OAAOJ,oBAAqB;YACrC,IAAIG,iBAAiB,CAACC,IAAI,EAAE;gBAC1B;YACF;YAEAD,iBAAiB,CAACC,IAAI,GAAGJ,mBAAmB,CAACI,IAAI;QACnD;QAEA,MAAME,OAA0B;YAACT;YAAgBM;SAAkB;QAEnE,8BAA8B;QAC9B,IAAIT,WAAW,CAAC,EAAE,EAAE;YAClBY,IAAI,CAAC,EAAE,GAAGZ,WAAW,CAAC,EAAE;QAC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+1,6 @@
import type { FlightSegmentPath } from '../../../server/app-render/types';
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime';
/**
* This will clear the CacheNode data for a particular segment path. This will cause a lazy-fetch in layout router to fill in new data.
*/
export declare function clearCacheNodeDataForSegmentPath(newCache: CacheNode, existingCache: CacheNode, flightSegmentPath: FlightSegmentPath): void;

View File

@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "clearCacheNodeDataForSegmentPath", {
enumerable: true,
get: function() {
return clearCacheNodeDataForSegmentPath;
}
});
const _createroutercachekey = require("./create-router-cache-key");
function clearCacheNodeDataForSegmentPath(newCache, existingCache, flightSegmentPath) {
const isLastEntry = flightSegmentPath.length <= 2;
const [parallelRouteKey, segment] = flightSegmentPath;
const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segment);
const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey);
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey);
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap);
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap);
}
const existingChildCacheNode = existingChildSegmentMap == null ? void 0 : existingChildSegmentMap.get(cacheKey);
let childCacheNode = childSegmentMap.get(cacheKey);
// In case of last segment start off the fetch at this level and don't copy further down.
if (isLastEntry) {
if (!childCacheNode || !childCacheNode.lazyData || childCacheNode === existingChildCacheNode) {
childSegmentMap.set(cacheKey, {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
lazyDataResolved: false,
loading: null
});
}
return;
}
if (!childCacheNode || !existingChildCacheNode) {
// Start fetch in the place where the existing cache doesn't have the data yet.
if (!childCacheNode) {
childSegmentMap.set(cacheKey, {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
lazyDataResolved: false,
loading: null
});
}
return;
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
lazyData: childCacheNode.lazyData,
rsc: childCacheNode.rsc,
prefetchRsc: childCacheNode.prefetchRsc,
head: childCacheNode.head,
prefetchHead: childCacheNode.prefetchHead,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
lazyDataResolved: childCacheNode.lazyDataResolved,
loading: childCacheNode.loading
};
childSegmentMap.set(cacheKey, childCacheNode);
}
return clearCacheNodeDataForSegmentPath(childCacheNode, existingChildCacheNode, flightSegmentPath.slice(2));
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=clear-cache-node-data-for-segment-path.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/clear-cache-node-data-for-segment-path.ts"],"names":["clearCacheNodeDataForSegmentPath","newCache","existingCache","flightSegmentPath","isLastEntry","length","parallelRouteKey","segment","cacheKey","createRouterCacheKey","existingChildSegmentMap","parallelRoutes","get","childSegmentMap","Map","set","existingChildCacheNode","childCacheNode","lazyData","rsc","prefetchRsc","head","prefetchHead","lazyDataResolved","loading","slice"],"mappings":";;;;+BAOgBA;;;eAAAA;;;sCALqB;AAK9B,SAASA,iCACdC,QAAmB,EACnBC,aAAwB,EACxBC,iBAAoC;IAEpC,MAAMC,cAAcD,kBAAkBE,MAAM,IAAI;IAEhD,MAAM,CAACC,kBAAkBC,QAAQ,GAAGJ;IACpC,MAAMK,WAAWC,IAAAA,0CAAoB,EAACF;IAEtC,MAAMG,0BACJR,cAAcS,cAAc,CAACC,GAAG,CAACN;IAEnC,IAAIO,kBAAkBZ,SAASU,cAAc,CAACC,GAAG,CAACN;IAElD,IAAI,CAACO,mBAAmBA,oBAAoBH,yBAAyB;QACnEG,kBAAkB,IAAIC,IAAIJ;QAC1BT,SAASU,cAAc,CAACI,GAAG,CAACT,kBAAkBO;IAChD;IAEA,MAAMG,yBAAyBN,2CAAAA,wBAAyBE,GAAG,CAACJ;IAC5D,IAAIS,iBAAiBJ,gBAAgBD,GAAG,CAACJ;IAEzC,yFAAyF;IACzF,IAAIJ,aAAa;QACf,IACE,CAACa,kBACD,CAACA,eAAeC,QAAQ,IACxBD,mBAAmBD,wBACnB;YACAH,gBAAgBE,GAAG,CAACP,UAAU;gBAC5BU,UAAU;gBACVC,KAAK;gBACLC,aAAa;gBACbC,MAAM;gBACNC,cAAc;gBACdX,gBAAgB,IAAIG;gBACpBS,kBAAkB;gBAClBC,SAAS;YACX;QACF;QACA;IACF;IAEA,IAAI,CAACP,kBAAkB,CAACD,wBAAwB;QAC9C,+EAA+E;QAC/E,IAAI,CAACC,gBAAgB;YACnBJ,gBAAgBE,GAAG,CAACP,UAAU;gBAC5BU,UAAU;gBACVC,KAAK;gBACLC,aAAa;gBACbC,MAAM;gBACNC,cAAc;gBACdX,gBAAgB,IAAIG;gBACpBS,kBAAkB;gBAClBC,SAAS;YACX;QACF;QACA;IACF;IAEA,IAAIP,mBAAmBD,wBAAwB;QAC7CC,iBAAiB;YACfC,UAAUD,eAAeC,QAAQ;YACjCC,KAAKF,eAAeE,GAAG;YACvBC,aAAaH,eAAeG,WAAW;YACvCC,MAAMJ,eAAeI,IAAI;YACzBC,cAAcL,eAAeK,YAAY;YACzCX,gBAAgB,IAAIG,IAAIG,eAAeN,cAAc;YACrDY,kBAAkBN,eAAeM,gBAAgB;YACjDC,SAASP,eAAeO,OAAO;QACjC;QACAX,gBAAgBE,GAAG,CAACP,UAAUS;IAChC;IAEA,OAAOjB,iCACLiB,gBACAD,wBACAb,kBAAkBsB,KAAK,CAAC;AAE5B"}

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,3 @@
import type { FlightRouterState } from '../../../server/app-render/types';
export declare function extractPathFromFlightRouterState(flightRouterState: FlightRouterState): string | undefined;
export declare function computeChangedPath(treeA: FlightRouterState, treeB: FlightRouterState): string | null;

View File

@ -0,0 +1,108 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
computeChangedPath: null,
extractPathFromFlightRouterState: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
computeChangedPath: function() {
return computeChangedPath;
},
extractPathFromFlightRouterState: function() {
return extractPathFromFlightRouterState;
}
});
const _interceptionroutes = require("../../../server/future/helpers/interception-routes");
const _segment = require("../../../shared/lib/segment");
const _matchsegments = require("../match-segments");
const removeLeadingSlash = (segment)=>{
return segment[0] === "/" ? segment.slice(1) : segment;
};
const segmentToPathname = (segment)=>{
if (typeof segment === "string") {
// 'children' is not a valid path -- it's technically a parallel route that corresponds with the current segment's page
// if we don't skip it, then the computed pathname might be something like `/children` which doesn't make sense.
if (segment === "children") return "";
return segment;
}
return segment[1];
};
function normalizeSegments(segments) {
return segments.reduce((acc, segment)=>{
segment = removeLeadingSlash(segment);
if (segment === "" || (0, _segment.isGroupSegment)(segment)) {
return acc;
}
return acc + "/" + segment;
}, "") || "/";
}
function extractPathFromFlightRouterState(flightRouterState) {
const segment = Array.isArray(flightRouterState[0]) ? flightRouterState[0][1] : flightRouterState[0];
if (segment === _segment.DEFAULT_SEGMENT_KEY || _interceptionroutes.INTERCEPTION_ROUTE_MARKERS.some((m)=>segment.startsWith(m))) return undefined;
if (segment.startsWith(_segment.PAGE_SEGMENT_KEY)) return "";
const segments = [
segmentToPathname(segment)
];
var _flightRouterState_;
const parallelRoutes = (_flightRouterState_ = flightRouterState[1]) != null ? _flightRouterState_ : {};
const childrenPath = parallelRoutes.children ? extractPathFromFlightRouterState(parallelRoutes.children) : undefined;
if (childrenPath !== undefined) {
segments.push(childrenPath);
} else {
for (const [key, value] of Object.entries(parallelRoutes)){
if (key === "children") continue;
const childPath = extractPathFromFlightRouterState(value);
if (childPath !== undefined) {
segments.push(childPath);
}
}
}
return normalizeSegments(segments);
}
function computeChangedPathImpl(treeA, treeB) {
const [segmentA, parallelRoutesA] = treeA;
const [segmentB, parallelRoutesB] = treeB;
const normalizedSegmentA = segmentToPathname(segmentA);
const normalizedSegmentB = segmentToPathname(segmentB);
if (_interceptionroutes.INTERCEPTION_ROUTE_MARKERS.some((m)=>normalizedSegmentA.startsWith(m) || normalizedSegmentB.startsWith(m))) {
return "";
}
if (!(0, _matchsegments.matchSegment)(segmentA, segmentB)) {
var _extractPathFromFlightRouterState;
// once we find where the tree changed, we compute the rest of the path by traversing the tree
return (_extractPathFromFlightRouterState = extractPathFromFlightRouterState(treeB)) != null ? _extractPathFromFlightRouterState : "";
}
for(const parallelRouterKey in parallelRoutesA){
if (parallelRoutesB[parallelRouterKey]) {
const changedPath = computeChangedPathImpl(parallelRoutesA[parallelRouterKey], parallelRoutesB[parallelRouterKey]);
if (changedPath !== null) {
return segmentToPathname(segmentB) + "/" + changedPath;
}
}
}
return null;
}
function computeChangedPath(treeA, treeB) {
const changedPath = computeChangedPathImpl(treeA, treeB);
if (changedPath == null || changedPath === "/") {
return changedPath;
}
// lightweight normalization to remove route groups
return normalizeSegments(changedPath.split("/"));
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=compute-changed-path.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/compute-changed-path.ts"],"names":["computeChangedPath","extractPathFromFlightRouterState","removeLeadingSlash","segment","slice","segmentToPathname","normalizeSegments","segments","reduce","acc","isGroupSegment","flightRouterState","Array","isArray","DEFAULT_SEGMENT_KEY","INTERCEPTION_ROUTE_MARKERS","some","m","startsWith","undefined","PAGE_SEGMENT_KEY","parallelRoutes","childrenPath","children","push","key","value","Object","entries","childPath","computeChangedPathImpl","treeA","treeB","segmentA","parallelRoutesA","segmentB","parallelRoutesB","normalizedSegmentA","normalizedS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+1 @@
export declare function createHrefFromUrl(url: Pick<URL, 'pathname' | 'search' | 'hash'>, includeHash?: boolean): string;

View File

@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createHrefFromUrl", {
enumerable: true,
get: function() {
return createHrefFromUrl;
}
});
function createHrefFromUrl(url, includeHash) {
if (includeHash === void 0) includeHash = true;
return url.pathname + url.search + (includeHash ? url.hash : "");
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=create-href-from-url.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/create-href-from-url.ts"],"names":["createHrefFromUrl","url","includeHash","pathname","search","hash"],"mappings":";;;;+BAAgBA;;;eAAAA;;;AAAT,SAASA,kBACdC,GAA8C,EAC9CC,WAA2B;IAA3BA,IAAAA,wBAAAA,cAAuB;IAEvB,OAAOD,IAAIE,QAAQ,GAAGF,IAAIG,MAAM,GAAIF,CAAAA,cAAcD,IAAII,IAAI,GAAG,EAAC;AAChE"}

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,33 @@
import type { ReactNode } from 'react';
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime';
import type { FlightRouterState, CacheNodeSeedData } from '../../../server/app-render/types';
import { type PrefetchCacheEntry } from './router-reducer-types';
export interface InitialRouterStateParameters {
buildId: string;
initialTree: FlightRouterState;
urlParts: string[];
initialSeedData: CacheNodeSeedData;
initialParallelRoutes: CacheNode['parallelRoutes'];
location: Location | null;
initialHead: ReactNode;
couldBeIntercepted?: boolean;
}
export declare function createInitialRouterState({ buildId, initialTree, initialSeedData, urlParts, initialParallelRoutes, location, initialHead, couldBeIntercepted, }: InitialRouterStateParameters): {
buildId: string;
tree: FlightRouterState;
cache: import("../../../shared/lib/app-router-context.shared-runtime").ReadyCacheNode;
prefetchCache: Map<string, PrefetchCacheEntry>;
pushRef: {
pendingPush: boolean;
mpaNavigation: boolean;
preserveCustomHistoryState: boolean;
};
focusAndScrollRef: {
apply: boolean;
onlyHashChange: boolean;
hashFragment: null;
segmentPaths: never[];
};
canonicalUrl: string;
nextUrl: string | null;
};

View File

@ -0,0 +1,104 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createInitialRouterState", {
enumerable: true,
get: function() {
return createInitialRouterState;
}
});
const _createhreffromurl = require("./create-href-from-url");
const _filllazyitemstillleafwithhead = require("./fill-lazy-items-till-leaf-with-head");
const _computechangedpath = require("./compute-changed-path");
const _prefetchcacheutils = require("./prefetch-cache-utils");
const _routerreducertypes = require("./router-reducer-types");
const _refetchinactiveparallelsegments = require("./refetch-inactive-parallel-segments");
function createInitialRouterState(param) {
let { buildId, initialTree, initialSeedData, urlParts, initialParallelRoutes, location, initialHead, couldBeIntercepted } = param;
// When initialized on the server, the canonical URL is provided as an array of parts.
// This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it
// as a URL that should be crawled.
const initialCanonicalUrl = urlParts.join("/");
const isServer = !location;
const rsc = initialSeedData[2];
const cache = {
lazyData: null,
rsc: rsc,
prefetchRsc: null,
head: null,
prefetchHead: null,
// The cache gets seeded during the first render. `initialParallelRoutes` ensures the cache from the first render is there during the second render.
parallelRoutes: isServer ? new Map() : initialParallelRoutes,
lazyDataResolved: false,
loading: initialSeedData[3]
};
const canonicalUrl = // location.href is read as the initial value for canonicalUrl in the browser
// This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.
location ? (0, _createhreffromurl.createHrefFromUrl)(location) : initialCanonicalUrl;
(0, _refetchinactiveparallelsegments.addRefreshMarkerToActiveParallelSegments)(initialTree, canonicalUrl);
const prefetchCache = new Map();
// When the cache hasn't been seeded yet we fill the cache with the head.
if (initialParallelRoutes === null || initialParallelRoutes.size === 0) {
(0, _filllazyitemstillleafwithhead.fillLazyItemsTillLeafWithHead)(cache, undefined, initialTree, initialSeedData, initialHead);
}
var // the || operator is intentional, the pathname can be an empty string
_ref;
const initialState = {
buildId,
tree: initialTree,
cache,
prefetchCache,
pushRef: {
pendingPush: false,
mpaNavigation: false,
// First render needs to preserve the previous window.history.state
// to avoid it being overwritten on navigation back/forward with MPA Navigation.
preserveCustomHistoryState: true
},
focusAndScrollRef: {
apply: false,
onlyHashChange: false,
hashFragment: null,
segmentPaths: []
},
canonicalUrl,
nextUrl: (_ref = (0, _computechangedpath.extractPathFromFlightRouterState)(initialTree) || (location == null ? void 0 : location.pathname)) != null ? _ref : null
};
if (location) {
// Seed the prefetch cache with this page's data.
// This is to prevent needlessly re-prefetching a page that is already reusable,
// and will avoid triggering a loading state/data fetch stall when navigating back to the page.
const url = new URL("" + location.pathname + location.search, location.origin);
const initialFlightData = [
[
"",
initialTree,
null,
null
]
];
(0, _prefetchcacheutils.createPrefetchCacheEntryForInitialLoad)({
url,
kind: _routerreducertypes.PrefetchKind.AUTO,
data: [
initialFlightData,
undefined,
false,
couldBeIntercepted
],
tree: initialState.tree,
prefetchCache: initialState.prefetchCache,
nextUrl: initialState.nextUrl
});
}
return initialState;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=create-initial-router-state.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"names":["createInitialRouterState","buildId","initialTree","initialSeedData","urlParts","initialParallelRoutes","location","initialHead","couldBeIntercepted","initialCanonicalUrl","join","isServer","rsc","cache","lazyData","prefetchRsc","head","prefetchHead","parallelRoutes","Map","lazyDataResolved","loading","canonicalUrl","createHrefFromUrl","addRefreshMarkerToActiveParallelSegments","prefetchCache","size","fillLazyItemsTillLeafWithHead","undefined","extractPathFromFlightRouterState","initialState","tree","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","apply","onlyHashChange","hashFragment","segmentPaths","nextUrl","pathname","url","URL","search","origin","initialFlightData","createPrefetchCacheEntryForInitialLoad","kind","PrefetchKind","AUTO","data"],"mappings":";;;;+BA0BgBA;;;eAAAA;;;mCAlBkB;+CACY;oCACG;oCACM;oCACD;iDACG;AAalD,SAASA,yBAAyB,KASV;IATU,IAAA,EACvCC,OAAO,EACPC,WAAW,EACXC,eAAe,EACfC,QAAQ,EACRC,qBAAqB,EACrBC,QAAQ,EACRC,WAAW,EACXC,kBAAkB,EACW,GATU;IAUvC,sFAAsF;IACtF,kGAAkG;IAClG,mCAAmC;IACnC,MAAMC,sBAAsBL,SAASM,IAAI,CAAC;IAC1C,MAAMC,WAAW,CAACL;IAClB,MAAMM,MAAMT,eAAe,CAAC,EAAE;IAE9B,MAAMU,QAAmB;QACvBC,UAAU;QACVF,KAAKA;QACLG,aAAa;QACbC,MAAM;QACNC,cAAc;QACd,oJAAoJ;QACpJC,gBAAgBP,WAAW,IAAIQ,QAAQd;QACvCe,kBAAkB;QAClBC,SAASlB,eAAe,CAAC,EAAE;IAC7B;IAEA,MAAMmB,eACJ,6EAA6E;IAC7E,kJAAkJ;IAClJhB,WAEIiB,IAAAA,oCAAiB,EAACjB,YAClBG;IAENe,IAAAA,yEAAwC,EAACtB,aAAaoB;IAEtD,MAAMG,gBAAgB,IAAIN;IAE1B,yEAAyE;IACzE,IAAId,0BAA0B,QAAQA,sBAAsBqB,IAAI,KAAK,GAAG;QACtEC,IAAAA,4DAA6B,EAC3Bd,OACAe,WACA1B,aACAC,iBACAI;IAEJ;QAsBI,sEAAsE;IACrEsB;IArBL,MAAMC,eAAe;QACnB7B;QACA8B,MAAM7B;QACNW;QACAY;QACAO,SAAS;YACPC,aAAa;YACbC,eAAe;YACf,mEAAmE;YACnE,gFAAgF;YAChFC,4BAA4B;QAC9B;QACAC,mBAAmB;YACjBC,OAAO;YACPC,gBAAgB;YAChBC,cAAc;YACdC,cAAc,EAAE;QAClB;QACAlB;QACAmB,SAEE,CAACZ,OAAAA,IAAAA,oDAAgC,EAAC3B,iBAAgBI,4BAAAA,SAAUoC,QAAQ,aAAnEb,OACD;IACJ;IAEA,IAAIvB,UAAU;QACZ,iDAAiD;QACjD,gFAAgF;QAChF,+FAA+F;QAC/F,MAAMqC,MAAM,IAAIC,IACd,AAAC,KAAEtC,SAASoC,QAAQ,GAAGpC,SAASuC,MAAM,EACtCvC,SAASwC,MAAM;QAGjB,MAAMC,oBAAgC;YAAC;gBAAC;gBAAI7C;gBAAa;gBAAM;aAAK;SAAC;QACrE8C,IAAAA,0DAAsC,EAAC;YACrCL;YACAM,MAAMC,gCAAY,CAACC,IAAI;YACvBC,MAAM;gBAACL;gBAAmBnB;gBAAW;gBAAOpB;aAAmB;YAC/DuB,MAAMD,aAAaC,IAAI;YACvBN,eAAeK,aAAaL,aAAa;YACzCgB,SAASX,aAAaW,OAAO;QAC/B;IACF;IAEA,OAAOX;AACT"}

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,2 @@
import type { Segment } from '../../../server/app-render/types';
export declare function createRouterCacheKey(segment: Segment, withoutSearchParameters?: boolean): string;

View File

@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createRouterCacheKey", {
enumerable: true,
get: function() {
return createRouterCacheKey;
}
});
const _segment = require("../../../shared/lib/segment");
function createRouterCacheKey(segment, withoutSearchParameters) {
if (withoutSearchParameters === void 0) withoutSearchParameters = false;
// if the segment is an array, it means it's a dynamic segment
// for example, ['lang', 'en', 'd']. We need to convert it to a string to store it as a cache node key.
if (Array.isArray(segment)) {
return segment[0] + "|" + segment[1] + "|" + segment[2];
}
// Page segments might have search parameters, ie __PAGE__?foo=bar
// When `withoutSearchParameters` is true, we only want to return the page segment
if (withoutSearchParameters && segment.startsWith(_segment.PAGE_SEGMENT_KEY)) {
return _segment.PAGE_SEGMENT_KEY;
}
return segment;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=create-router-cache-key.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/create-router-cache-key.ts"],"names":["createRouterCacheKey","segment","withoutSearchParameters","Array","isArray","startsWith","PAGE_SEGMENT_KEY"],"mappings":";;;;+BAGgBA;;;eAAAA;;;yBAFiB;AAE1B,SAASA,qBACdC,OAAgB,EAChBC,uBAAwC;IAAxCA,IAAAA,oCAAAA,0BAAmC;IAEnC,8DAA8D;IAC9D,uGAAuG;IACvG,IAAIC,MAAMC,OAAO,CAACH,UAAU;QAC1B,OAAO,AAAGA,OAAO,CAAC,EAAE,GAAC,MAAGA,OAAO,CAAC,EAAE,GAAC,MAAGA,OAAO,CAAC,EAAE;IAClD;IAEA,kEAAkE;IAClE,kFAAkF;IAClF,IAAIC,2BAA2BD,QAAQI,UAAU,CAACC,yBAAgB,GAAG;QACnE,OAAOA,yBAAgB;IACzB;IAEA,OAAOL;AACT"}

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,12 @@
import type { FlightRouterState, FlightData } from '../../../server/app-render/types';
import { PrefetchKind } from './router-reducer-types';
export type FetchServerResponseResult = [
flightData: FlightData,
canonicalUrlOverride: URL | undefined,
postponed?: boolean,
intercepted?: boolean
];
/**
* Fetch the flight data for the provided url. Takes in the current router state to decide what to render server-side.
*/
export declare function fetchServerResponse(url: URL, flightRouterState: FlightRouterState, nextUrl: string | null, currentBuildId: string, prefetchKind?: PrefetchKind): Promise<FetchServerResponseResult>;

View File

@ -0,0 +1,130 @@
"use client";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "fetchServerResponse", {
enumerable: true,
get: function() {
return fetchServerResponse;
}
});
const _approuterheaders = require("../app-router-headers");
const _approuter = require("../app-router");
const _appcallserver = require("../../app-call-server");
const _routerreducertypes = require("./router-reducer-types");
const _hash = require("../../../shared/lib/hash");
// @ts-ignore
// eslint-disable-next-line import/no-extraneous-dependencies
// import { createFromFetch } from 'react-server-dom-webpack/client'
const { createFromFetch } = !!process.env.NEXT_RUNTIME ? require("react-server-dom-webpack/client.edge") : require("react-server-dom-webpack/client");
function doMpaNavigation(url) {
return [
(0, _approuter.urlToUrlWithoutFlightMarker)(url).toString(),
undefined,
false,
false
];
}
async function fetchServerResponse(url, flightRouterState, nextUrl, currentBuildId, prefetchKind) {
const headers = {
// Enable flight response
[_approuterheaders.RSC_HEADER]: "1",
// Provide the current router state
[_approuterheaders.NEXT_ROUTER_STATE_TREE]: encodeURIComponent(JSON.stringify(flightRouterState))
};
/**
* Three cases:
* - `prefetchKind` is `undefined`, it means it's a normal navigation, so we want to prefetch the page data fully
* - `prefetchKind` is `full` - we want to prefetch the whole page so same as above
* - `prefetchKind` is `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully
*/ if (prefetchKind === _routerreducertypes.PrefetchKind.AUTO) {
headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER] = "1";
}
if (nextUrl) {
headers[_approuterheaders.NEXT_URL] = nextUrl;
}
if (process.env.NEXT_DEPLOYMENT_ID) {
headers["x-deployment-id"] = process.env.NEXT_DEPLOYMENT_ID;
}
const uniqueCacheQuery = (0, _hash.hexHash)([
headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER] || "0",
headers[_approuterheaders.NEXT_ROUTER_STATE_TREE],
headers[_approuterheaders.NEXT_URL]
].join(","));
try {
var _res_headers_get;
let fetchUrl = new URL(url);
if (process.env.NODE_ENV === "production") {
if (process.env.__NEXT_CONFIG_OUTPUT === "export") {
if (fetchUrl.pathname.endsWith("/")) {
fetchUrl.pathname += "index.txt";
} else {
fetchUrl.pathname += ".txt";
}
}
}
// Add unique cache query to avoid caching conflicts on CDN which don't respect to Vary header
fetchUrl.searchParams.set(_approuterheaders.NEXT_RSC_UNION_QUERY, uniqueCacheQuery);
const res = await fetch(fetchUrl, {
// Backwards compat for older browsers. `same-origin` is the default in modern browsers.
credentials: "same-origin",
headers
});
const responseUrl = (0, _approuter.urlToUrlWithoutFlightMarker)(res.url);
const canonicalUrl = res.redirected ? responseUrl : undefined;
const contentType = res.headers.get("content-type") || "";
const postponed = !!res.headers.get(_approuterheaders.NEXT_DID_POSTPONE_HEADER);
const interception = !!((_res_headers_get = res.headers.get("vary")) == null ? void 0 : _res_headers_get.includes(_approuterheaders.NEXT_URL));
let isFlightResponse = contentType === _approuterheaders.RSC_CONTENT_TYPE_HEADER;
if (process.env.NODE_ENV === "production") {
if (process.env.__NEXT_CONFIG_OUTPUT === "export") {
if (!isFlightResponse) {
isFlightResponse = contentType.startsWith("text/plain");
}
}
}
// If fetch returns something different than flight response handle it like a mpa navigation
// If the fetch was not 200, we also handle it like a mpa navigation
if (!isFlightResponse || !res.ok) {
// in case the original URL came with a hash, preserve it before redirecting to the new URL
if (url.hash) {
responseUrl.hash = url.hash;
}
return doMpaNavigation(responseUrl.toString());
}
// Handle the `fetch` readable stream that can be unwrapped by `React.use`.
const [buildId, flightData] = await createFromFetch(Promise.resolve(res), {
callServer: _appcallserver.callServer
});
if (currentBuildId !== buildId) {
return doMpaNavigation(res.url);
}
return [
flightData,
canonicalUrl,
postponed,
interception
];
} catch (err) {
console.error("Failed to fetch RSC payload for " + url + ". Falling back to browser navigation.", err);
// If fetch fails handle it like a mpa navigation
// TODO-APP: Add a test for the case where a CORS request fails, e.g. external url redirect coming from the response.
// See https://github.com/vercel/next.js/issues/43605#issuecomment-1451617521 for a reproduction.
return [
url.toString(),
undefined,
false,
false
];
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=fetch-server-response.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/fetch-server-response.ts"],"names":["fetchServerResponse","createFromFetch","process","env","NEXT_RUNTIME","require","doMpaNavigation","url","urlToUrlWithoutFlightMarker","toString","undefined","flightRouterState","nextUrl","currentBuildId","prefetchKind","headers","RSC_HEADER","NEXT_ROUTER_STATE_TREE","encodeURIComponent","JSON","stringify","PrefetchKind","AUTO","NEXT_ROUTER_PREFETCH_HEADER","NEXT_URL","NEXT_DEPLOYMENT_ID","uniqueCacheQuery","hexHash","join","res","fetchUrl","URL","NODE_ENV","__NEXT_CONFIG_OUTPUT","pathname","endsWith","searchParams","set","NEXT_RSC_UNION_QUERY","fetch","credentials","responseUrl","canonicalUrl","redirected","contentType","get","postponed","NEXT_DID_POSTPONE_HEADER","interception","includes","isFlightResponse","RSC_CONTENT_TYPE_HEADER","startsWith","ok","hash","buildId","flightData","Promise","resolve","callServer","err","console","error"],"mappings":"AAAA;;;;;+BA8CsBA;;;eAAAA;;;kCApBf;2BACqC;+BACjB;oCACE;sBACL;AA5BxB,aAAa;AACb,6DAA6D;AAC7D,oEAAoE;AACpE,MAAM,EAAEC,eAAe,EAAE,GACvB,CAAC,CAACC,QAAQC,GAAG,CAACC,YAAY,GAEtBC,QAAQ,0CAERA,QAAQ;AA6Bd,SAASC,gBAAgBC,GAAW;IAClC,OAAO;QAACC,IAAAA,sCAA2B,EAACD,KAAKE,QAAQ;QAAIC;QAAW;QAAO;KAAM;AAC/E;AAKO,eAAeV,oBACpBO,GAAQ,EACRI,iBAAoC,EACpCC,OAAsB,EACtBC,cAAsB,EACtBC,YAA2B;IAE3B,MAAMC,UAMF;QACF,yBAAyB;QACzB,CAACC,4BAAU,CAAC,EAAE;QACd,mCAAmC;QACnC,CAACC,wCAAsB,CAAC,EAAEC,mBACxBC,KAAKC,SAAS,CAACT;IAEnB;IAEA;;;;;GAKC,GACD,IAAIG,iBAAiBO,gCAA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QAAQ,CAACzB,0BAAQ;QACjE,IAAI0B,mBAAmBN,gBAAgBO,yCAAuB;QAE9D,IAAIjD,QAAQC,GAAG,CAAC6B,QAAQ,KAAK,cAAc;YACzC,IAAI9B,QAAQC,GAAG,CAAC8B,oBAAoB,KAAK,UAAU;gBACjD,IAAI,CAACiB,kBAAkB;oBACrBA,mBAAmBN,YAAYQ,UAAU,CAAC;gBAC5C;YACF;QACF;QAEA,4FAA4F;QAC5F,oEAAoE;QACpE,IAAI,CAACF,oBAAoB,CAACrB,IAAIwB,EAAE,EAAE;YAChC,2FAA2F;YAC3F,IAAI9C,IAAI+C,IAAI,EAAE;gBACZb,YAAYa,IAAI,GAAG/C,IAAI+C,IAAI;YAC7B;YAEA,OAAOhD,gBAAgBmC,YAAYhC,QAAQ;QAC7C;QAEA,2EAA2E;QAC3E,MAAM,CAAC8C,SAASC,WAAW,GAAuB,MAAMvD,gBACtDwD,QAAQC,OAAO,CAAC7B,MAChB;YACE8B,YAAAA,yBAAU;QACZ;QAGF,IAAI9C,mBAAmB0C,SAAS;YAC9B,OAAOjD,gBAAgBuB,IAAItB,GAAG;QAChC;QAEA,OAAO;YAACiD;YAAYd;YAAcI;YAAWE;SAAa;IAC5D,EAAE,OAAOY,KAAK;QACZC,QAAQC,KAAK,CACX,AAAC,qCAAkCvD,MAAI,yCACvCqD;QAEF,iDAAiD;QACjD,qHAAqH;QACrH,iGAAiG;QACjG,OAAO;YAACrD,IAAIE,QAAQ;YAAIC;YAAW;YAAO;SAAM;IAClD;AACF"}

View File

@ -0,0 +1,7 @@
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime';
import type { FlightDataPath } from '../../../server/app-render/types';
import type { PrefetchCacheEntry } from './router-reducer-types';
/**
* Fill cache with rsc based on flightDataPath
*/
export declare function fillCacheWithNewSubTreeData(newCache: CacheNode, existingCache: CacheNode, flightDataPath: FlightDataPath, prefetchEntry?: PrefetchCacheEntry): void;

View File

@ -0,0 +1,82 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "fillCacheWithNewSubTreeData", {
enumerable: true,
get: function() {
return fillCacheWithNewSubTreeData;
}
});
const _invalidatecachebyrouterstate = require("./invalidate-cache-by-router-state");
const _filllazyitemstillleafwithhead = require("./fill-lazy-items-till-leaf-with-head");
const _createroutercachekey = require("./create-router-cache-key");
function fillCacheWithNewSubTreeData(newCache, existingCache, flightDataPath, prefetchEntry) {
const isLastEntry = flightDataPath.length <= 5;
const [parallelRouteKey, segment] = flightDataPath;
const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segment);
const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey);
if (!existingChildSegmentMap) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return;
}
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey);
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap);
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap);
}
const existingChildCacheNode = existingChildSegmentMap.get(cacheKey);
let childCacheNode = childSegmentMap.get(cacheKey);
if (isLastEntry) {
if (!childCacheNode || !childCacheNode.lazyData || childCacheNode === existingChildCacheNode) {
const seedData = flightDataPath[3];
const rsc = seedData[2];
const loading = seedData[3];
childCacheNode = {
lazyData: null,
rsc,
prefetchRsc: null,
head: null,
prefetchHead: null,
loading,
// Ensure segments other than the one we got data for are preserved.
parallelRoutes: existingChildCacheNode ? new Map(existingChildCacheNode.parallelRoutes) : new Map(),
lazyDataResolved: false
};
if (existingChildCacheNode) {
(0, _invalidatecachebyrouterstate.invalidateCacheByRouterState)(childCacheNode, existingChildCacheNode, flightDataPath[2]);
}
(0, _filllazyitemstillleafwithhead.fillLazyItemsTillLeafWithHead)(childCacheNode, existingChildCacheNode, flightDataPath[2], seedData, flightDataPath[4], prefetchEntry);
childSegmentMap.set(cacheKey, childCacheNode);
}
return;
}
if (!childCacheNode || !existingChildCacheNode) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return;
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
lazyData: childCacheNode.lazyData,
rsc: childCacheNode.rsc,
prefetchRsc: childCacheNode.prefetchRsc,
head: childCacheNode.head,
prefetchHead: childCacheNode.prefetchHead,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
lazyDataResolved: false,
loading: childCacheNode.loading
};
childSegmentMap.set(cacheKey, childCacheNode);
}
fillCacheWithNewSubTreeData(childCacheNode, existingChildCacheNode, flightDataPath.slice(2), prefetchEntry);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=fill-cache-with-new-subtree-data.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/fill-cache-with-new-subtree-data.ts"],"names":["fillCacheWithNewSubTreeData","newCache","existingCache","flightDataPath","prefetchEntry","isLastEntry","length","parallelRouteKey","segment","cacheKey","createRouterCacheKey","existingChildSegmentMap","parallelRoutes","get","childSegmentMap","Map","set","existingChildCacheNode","childCacheNode","lazyData","seedData","rsc","loading","prefetchRsc","head","prefetchHead","lazyDataResolved","invalidateCacheByRouterState","fillLazyItemsTillLeafWithHead","slice"],"mappings":";;;;+BAagBA;;;eAAAA;;;8CAR6B;+CACC;sCACT;AAM9B,SAASA,4BACdC,QAAmB,EACnBC,aAAwB,EACxBC,cAA8B,EAC9BC,aAAkC;IAElC,MAAMC,cAAcF,eAAeG,MAAM,IAAI;IAC7C,MAAM,CAACC,kBAAkBC,QAAQ,GAAGL;IAEpC,MAAMM,WAAWC,IAAAA,0CAAoB,EAACF;IAEtC,MAAMG,0BACJT,cAAcU,cAAc,CAACC,GAAG,CAACN;IAEnC,IAAI,CAACI,yBAAyB;QAC5B,6EAA6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gBAAgB,IAAIG,IAAIG,eAAeN,cAAc;YACrDc,kBAAkB;YAClBJ,SAASJ,eAAeI,OAAO;QACjC;QACAR,gBAAgBE,GAAG,CAACP,UAAUS;IAChC;IAEAlB,4BACEkB,gBACAD,wBACAd,eAAe0B,KAAK,CAAC,IACrBzB;AAEJ"}

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,5 @@
/// <reference types="react" />
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime';
import type { FlightRouterState, CacheNodeSeedData } from '../../../server/app-render/types';
import { type PrefetchCacheEntry } from './router-reducer-types';
export declare function fillLazyItemsTillLeafWithHead(newCache: CacheNode, existingCache: CacheNode | undefined, routerState: FlightRouterState, cacheNodeSeedData: CacheNodeSeedData | null, head: React.ReactNode, prefetchEntry?: PrefetchCacheEntry): void;

View File

@ -0,0 +1,149 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "fillLazyItemsTillLeafWithHead", {
enumerable: true,
get: function() {
return fillLazyItemsTillLeafWithHead;
}
});
const _createroutercachekey = require("./create-router-cache-key");
const _routerreducertypes = require("./router-reducer-types");
function fillLazyItemsTillLeafWithHead(newCache, existingCache, routerState, cacheNodeSeedData, head, prefetchEntry) {
const isLastSegment = Object.keys(routerState[1]).length === 0;
if (isLastSegment) {
newCache.head = head;
return;
}
// Remove segment that we got data for so that it is filled in during rendering of rsc.
for(const key in routerState[1]){
const parallelRouteState = routerState[1][key];
const segmentForParallelRoute = parallelRouteState[0];
const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segmentForParallelRoute);
// TODO: We should traverse the cacheNodeSeedData tree instead of the router
// state tree. Ideally, they would always be the same shape, but because of
// the loading.js pattern, cacheNodeSeedData sometimes only represents a
// partial tree. That's why this node is sometimes null. Once PPR lands,
// loading.js will no longer have special behavior and we can traverse the
// data tree instead.
//
// We should also consider merging the router state tree and the data tree
// in the response format, so that we don't have to send the keys twice.
// Then the client can convert them into separate representations.
const parallelSeedData = cacheNodeSeedData !== null && cacheNodeSeedData[1][key] !== undefined ? cacheNodeSeedData[1][key] : null;
if (existingCache) {
const existingParallelRoutesCacheNode = existingCache.parallelRoutes.get(key);
if (existingParallelRoutesCacheNode) {
const hasReusablePrefetch = (prefetchEntry == null ? void 0 : prefetchEntry.kind) === "auto" && prefetchEntry.status === _routerreducertypes.PrefetchCacheEntryStatus.reusable;
let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode);
const existingCacheNode = parallelRouteCacheNode.get(cacheKey);
let newCacheNode;
if (parallelSeedData !== null) {
// New data was sent from the server.
const seedNode = parallelSeedData[2];
const loading = parallelSeedData[3];
newCacheNode = {
lazyData: null,
rsc: seedNode,
// This is a PPR-only field. When PPR is enabled, we shouldn't hit
// this path during a navigation, but until PPR is fully implemented
// yet it's possible the existing node does have a non-null
// `prefetchRsc`. As an incremental step, we'll just de-opt to the
// old behavior — no PPR value.
prefetchRsc: null,
head: null,
prefetchHead: null,
loading,
parallelRoutes: new Map(existingCacheNode == null ? void 0 : existingCacheNode.parallelRoutes),
lazyDataResolved: false
};
} else if (hasReusablePrefetch && existingCacheNode) {
// No new data was sent from the server, but the existing cache node
// was prefetched, so we should reuse that.
newCacheNode = {
lazyData: existingCacheNode.lazyData,
rsc: existingCacheNode.rsc,
// This is a PPR-only field. Unlike the previous branch, since we're
// just cloning the existing cache node, we might as well keep the
// PPR value, if it exists.
prefetchRsc: existingCacheNode.prefetchRsc,
head: existingCacheNode.head,
prefetchHead: existingCacheNode.prefetchHead,
parallelRoutes: new Map(existingCacheNode.parallelRoutes),
lazyDataResolved: existingCacheNode.lazyDataResolved,
loading: existingCacheNode.loading
};
} else {
// No data available for this node. This will trigger a lazy fetch
// during render.
newCacheNode = {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(existingCacheNode == null ? void 0 : existingCacheNode.parallelRoutes),
lazyDataResolved: false,
loading: null
};
}
// Overrides the cache key with the new cache node.
parallelRouteCacheNode.set(cacheKey, newCacheNode);
// Traverse deeper to apply the head / fill lazy items till the head.
fillLazyItemsTillLeafWithHead(newCacheNode, existingCacheNode, parallelRouteState, parallelSeedData ? parallelSeedData : null, head, prefetchEntry);
newCache.parallelRoutes.set(key, parallelRouteCacheNode);
continue;
}
}
let newCacheNode;
if (parallelSeedData !== null) {
// New data was sent from the server.
const seedNode = parallelSeedData[2];
const loading = parallelSeedData[3];
newCacheNode = {
lazyData: null,
rsc: seedNode,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
lazyDataResolved: false,
loading
};
} else {
// No data available for this node. This will trigger a lazy fetch
// during render.
newCacheNode = {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
lazyDataResolved: false,
loading: null
};
}
const existingParallelRoutes = newCache.parallelRoutes.get(key);
if (existingParallelRoutes) {
existingParallelRoutes.set(cacheKey, newCacheNode);
} else {
newCache.parallelRoutes.set(key, new Map([
[
cacheKey,
newCacheNode
]
]));
}
fillLazyItemsTillLeafWithHead(newCacheNode, undefined, parallelRouteState, parallelSeedData, head, prefetchEntry);
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=fill-lazy-items-till-leaf-with-head.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.ts"],"names":["fillLazyItemsTillLeafWithHead","newCache","existingCache","routerState","cacheNodeSeedData","head","prefetchEntry","isLastSegment","Object","keys","length","key","parallelRouteState","segmentForParallelRoute","cacheKey","createRouterCacheKey","parallelSeedData","undefined","existingParallelRoutesCacheNode","parallelRoutes","get","hasReusablePrefetch","kind","status","PrefetchCacheEntryStatus","reusable","parallelRouteCacheNode","Map","existingCacheNode","newCacheNode","seedNode","loading","lazyData","rsc","prefetchRsc","prefetchHead","lazyDataResolved","set","existingParallelRoutes"],"mappings":";;;;+BAWgBA;;;eAAAA;;;sCANqB;oCAI9B;AAEA,SAASA,8BACdC,QAAmB,EACnBC,aAAoC,EACpCC,WAA8B,EAC9BC,iBAA2C,EAC3CC,IAAqB,EACrBC,aAAkC;IAElC,MAAMC,gBAAgBC,OAAOC,IAAI,CAACN,WAAW,CAAC,EAAE,EAAEO,MAAM,KAAK;IAC7D,IAAIH,eAAe;QACjBN,SAASI,IAAI,GAAGA;QAChB;IACF;IACA,uFAAuF;IACvF,IAAK,MAAMM,OAAOR,WAAW,CAAC,EAAE,CAAE;QAChC,MAAMS,qBAAqBT,WAAW,CAAC,EAAE,CAACQ,IAAI;QAC9C,MAAME,0BAA0BD,kBAAkB,CAAC,EAAE;QACrD,MAAME,WAAWC,IAAAA,0CAAoB,EAACF;QAEtC,4EAA4E;QAC5E,2EAA2E;QAC3E,wEAAwE;QACxE,wEAAwE;QACxE,0EAA0E;QAC1E,qBAAqB;QACrB,EAAE;QACF,0EAA0E;QAC1E,wEAAwE;QACxE,kEAAkE;QAClE,MAAMG,mBACJZ,sBAAsB,QAAQA,iBAAiB,CAAC,EAAE,CAACO,IAAI,KAAKM,YACxDb,iBAAiB,CAAC,EAAE,CAACO,IAAI,GACzB;QACN,IAAIT,eAAe;YACjB,MAAMgB,kCACJhB,cAAciB,cAAc,CAACC,GAAG,CAACT;YACnC,IAAIO,iCAAiC;gBACnC,MAAMG,sBACJf,CAAAA,iCAAAA,cAAegB,IAAI,MAAK,UACxBhB,cAAciB,MAAM,KAAKC,4CAAwB,CAACC,QAAQ;gBAE5D,IAAIC,yBAAyB,IAAIC,IAAIT;gBACrC,MAAMU,oBAAoBF,uBAAuBN,GAAG,CAACN;gBACrD,IAAIe;gBACJ,IAAIb,qBAAqB,MAAM;oBAC7B,qCAAqC;oBACrC,MAAMc,WAAWd,gBAAgB,CAAC,EAAE;oBACpC,MAAMe,UAAUf,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YACpC,MAAMe,UAAUf,gBAAgB,CAAC,EAAE;YACnCa,eAAe;gBACbG,UAAU;gBACVC,KAAKH;gBACLI,aAAa;gBACb7B,MAAM;gBACN8B,cAAc;gBACdhB,gBAAgB,IAAIQ;gBACpBS,kBAAkB;gBAClBL;YACF;QACF,OAAO;YACL,kEAAkE;YAClE,iBAAiB;YACjBF,eAAe;gBACbG,UAAU;gBACVC,KAAK;gBACLC,aAAa;gBACb7B,MAAM;gBACN8B,cAAc;gBACdhB,gBAAgB,IAAIQ;gBACpBS,kBAAkB;gBAClBL,SAAS;YACX;QACF;QAEA,MAAMO,yBAAyBrC,SAASkB,cAAc,CAACC,GAAG,CAACT;QAC3D,IAAI2B,wBAAwB;YAC1BA,uBAAuBD,GAAG,CAACvB,UAAUe;QACvC,OAAO;YACL5B,SAASkB,cAAc,CAACkB,GAAG,CAAC1B,KAAK,IAAIgB,IAAI;gBAAC;oBAACb;oBAAUe;iBAAa;aAAC;QACrE;QAEA7B,8BACE6B,cACAZ,WACAL,oBACAI,kBACAX,MACAC;IAEJ;AACF"}

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,2 @@
import type { Mutable, ReadonlyReducerState, ReducerState } from './router-reducer-types';
export declare function handleMutable(state: ReadonlyReducerState, mutable: Mutable): ReducerState;

View File

@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "handleMutable", {
enumerable: true,
get: function() {
return handleMutable;
}
});
const _computechangedpath = require("./compute-changed-path");
function isNotUndefined(value) {
return typeof value !== "undefined";
}
function handleMutable(state, mutable) {
var _mutable_canonicalUrl;
var _mutable_shouldScroll;
// shouldScroll is true by default, can override to false.
const shouldScroll = (_mutable_shouldScroll = mutable.shouldScroll) != null ? _mutable_shouldScroll : true;
let nextUrl = state.nextUrl;
if (isNotUndefined(mutable.patchedTree)) {
// If we received a patched tree, we need to compute the changed path.
const changedPath = (0, _computechangedpath.computeChangedPath)(state.tree, mutable.patchedTree);
if (changedPath) {
// If the tree changed, we need to update the nextUrl
nextUrl = changedPath;
} else if (!nextUrl) {
// if the tree ends up being the same (ie, no changed path), and we don't have a nextUrl, then we should use the canonicalUrl
nextUrl = state.canonicalUrl;
}
// otherwise this will be a no-op and continue to use the existing nextUrl
}
var _mutable_scrollableSegments;
return {
buildId: state.buildId,
// Set href.
canonicalUrl: isNotUndefined(mutable.canonicalUrl) ? mutable.canonicalUrl === state.canonicalUrl ? state.canonicalUrl : mutable.canonicalUrl : state.canonicalUrl,
pushRef: {
pendingPush: isNotUndefined(mutable.pendingPush) ? mutable.pendingPush : state.pushRef.pendingPush,
mpaNavigation: isNotUndefined(mutable.mpaNavigation) ? mutable.mpaNavigation : state.pushRef.mpaNavigation,
preserveCustomHistoryState: isNotUndefined(mutable.preserveCustomHistoryState) ? mutable.preserveCustomHistoryState : state.pushRef.preserveCustomHistoryState
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: {
apply: shouldScroll ? isNotUndefined(mutable == null ? void 0 : mutable.scrollableSegments) ? true : state.focusAndScrollRef.apply : false,
onlyHashChange: !!mutable.hashFragment && state.canonicalUrl.split("#", 1)[0] === ((_mutable_canonicalUrl = mutable.canonicalUrl) == null ? void 0 : _mutable_canonicalUrl.split("#", 1)[0]),
hashFragment: shouldScroll ? // #top is handled in layout-router.
mutable.hashFragment && mutable.hashFragment !== "" ? decodeURIComponent(mutable.hashFragment.slice(1)) : state.focusAndScrollRef.hashFragment : null,
segmentPaths: shouldScroll ? (_mutable_scrollableSegments = mutable == null ? void 0 : mutable.scrollableSegments) != null ? _mutable_scrollableSegments : state.focusAndScrollRef.segmentPaths : []
},
// Apply cache.
cache: mutable.cache ? mutable.cache : state.cache,
prefetchCache: mutable.prefetchCache ? mutable.prefetchCache : state.prefetchCache,
// Apply patched router state.
tree: isNotUndefined(mutable.patchedTree) ? mutable.patchedTree : state.tree,
nextUrl
};
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=handle-mutable.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/handle-mutable.ts"],"names":["handleMutable","isNotUndefined","value","state","mutable","shouldScroll","nextUrl","patchedTree","changedPath","computeChangedPath","tree","canonicalUrl","buildId","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","apply","scrollableSegments","onlyHashChange","hashFragment","split","decodeURIComponent","slice","segmentPaths","cache","prefetchCache"],"mappings":";;;;+BAWgBA;;;eAAAA;;;oCAXmB;AAOnC,SAASC,eAAkBC,KAAQ;IACjC,OAAO,OAAOA,UAAU;AAC1B;AAEO,SAASF,cACdG,KAA2B,EAC3BC,OAAgB;QAoDRA;QAjDaA;IADrB,0DAA0D;IAC1D,MAAMC,eAAeD,CAAAA,wBAAAA,QAAQC,YAAY,YAApBD,wBAAwB;IAE7C,IAAIE,UAAUH,MAAMG,OAAO;IAE3B,IAAIL,eAAeG,QAAQG,WAAW,GAAG;QACvC,sEAAsE;QACtE,MAAMC,cAAcC,IAAAA,sCAAkB,EAACN,MAAMO,IAAI,EAAEN,QAAQG,WAAW;QACtE,IAAIC,aAAa;YACf,qDAAqD;YACrDF,UAAUE;QACZ,OAAO,IAAI,CAACF,SAAS;YACnB,6HAA6H;YAC7HA,UAAUH,MAAMQ,YAAY;QAC9B;IACA,0EAA0E;IAC5E;QA6CQP;IA3CR,OAAO;QACLQ,SAAST,MAAMS,OAAO;QACtB,YAAY;QACZD,cAAcV,eAAeG,QAAQO,YAAY,IAC7CP,QAAQO,YAAY,KAAKR,MAAMQ,YAAY,GACzCR,MAAMQ,YAAY,GAClBP,QAAQO,YAAY,GACtBR,MAAMQ,YAAY;QACtBE,SAAS;YACPC,aAAab,eAAeG,QAAQU,WAAW,IAC3CV,QAAQU,WAAW,GACnBX,MAAMU,OAAO,CAACC,WAAW;YAC7BC,eAAed,eAAeG,QAAQW,aAAa,IAC/CX,QAAQW,aAAa,GACrBZ,MAAMU,OAAO,CAACE,aAAa;YAC/BC,4BAA4Bf,eAC1BG,QAAQY,0BAA0B,IAEhCZ,QAAQY,0BAA0B,GAClCb,MAAMU,OAAO,CAACG,0BAA0B;QAC9C;QACA,kEAAkE;QAClEC,mBAAmB;YACjBC,OAAOb,eACHJ,eAAeG,2BAAAA,QAASe,kBAAkB,IACxC,OACAhB,MAAMc,iBAAiB,CAACC,KAAK,GAE/B;YACJE,gBACE,CAAC,CAAChB,QAAQiB,YAAY,IACtBlB,MAAMQ,YAAY,CAACW,KAAK,CAAC,KAAK,EAAE,CAAC,EAAE,OACjClB,wBAAAA,QAAQO,YAAY,qBAApBP,sBAAsBkB,KAAK,CAAC,KAAK,EAAE,CAAC,EAAE;YAC1CD,cAAchB,eAEV,oCAAoC;YACpCD,QAAQiB,YAAY,IAAIjB,QAAQiB,YAAY,KAAK,KAE/CE,mBAAmBnB,QAAQiB,YAAY,CAACG,KAAK,CAAC,MAC9CrB,MAAMc,iBAAiB,CAACI,YAAY,GAEtC;YACJI,cAAcpB,eACVD,CAAAA,8BAAAA,2BAAAA,QAASe,kBAAkB,YAA3Bf,8BAA+BD,MAAMc,iBAAiB,CAACQ,YAAY,GAEnE,EAAE;QACR;QACA,eAAe;QACfC,OAAOtB,QAAQsB,KAAK,GAAGtB,QAAQsB,KAAK,GAAGvB,MAAMuB,KAAK;QAClDC,eAAevB,QAAQuB,aAAa,GAChCvB,QAAQuB,aAAa,GACrBxB,MAAMwB,aAAa;QACvB,8BAA8B;QAC9BjB,MAAMT,eAAeG,QAAQG,WAAW,IACpCH,QAAQG,WAAW,GACnBJ,MAAMO,IAAI;QACdJ;IACF;AACF"}

View File

@ -0,0 +1,7 @@
import type { FlightRouterState } from '../../../server/app-render/types';
import type { ReadonlyReducerState, ReducerActions } from './router-reducer-types';
/**
* Handles the case where the client router attempted to patch the tree but, due to a mismatch, the patch failed.
* This will perform an MPA navigation to return the router to a valid state.
*/
export declare function handleSegmentMismatch(state: ReadonlyReducerState, action: ReducerActions, treePatch: FlightRouterState): import("./router-reducer-types").ReducerState;

View File

@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "handleSegmentMismatch", {
enumerable: true,
get: function() {
return handleSegmentMismatch;
}
});
const _navigatereducer = require("./reducers/navigate-reducer");
function handleSegmentMismatch(state, action, treePatch) {
if (process.env.NODE_ENV === "development") {
console.warn("Performing hard navigation because your application experienced an unrecoverable error. If this keeps occurring, please file a Next.js issue.\n\n" + "Reason: Segment mismatch\n" + ("Last Action: " + action.type + "\n\n") + ("Current Tree: " + JSON.stringify(state.tree) + "\n\n") + ("Tree Patch Payload: " + JSON.stringify(treePatch)));
}
return (0, _navigatereducer.handleExternalUrl)(state, {}, state.canonicalUrl, true);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=handle-segment-mismatch.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/handle-segment-mismatch.ts"],"names":["handleSegmentMismatch","state","action","treePatch","process","env","NODE_ENV","console","warn","type","JSON","stringify","tree","handleExternalUrl","canonicalUrl"],"mappings":";;;;+BAWgBA;;;eAAAA;;;iCAVkB;AAU3B,SAASA,sBACdC,KAA2B,EAC3BC,MAAsB,EACtBC,SAA4B;IAE5B,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QAC1CC,QAAQC,IAAI,CACV,sJACE,+BACA,CAAA,AAAC,kBAAeN,OAAOO,IAAI,GAAC,MAAI,IAChC,CAAA,AAAC,mBAAgBC,KAAKC,SAAS,CAACV,MAAMW,IAAI,IAAE,MAAI,IAChD,CAAA,AAAC,yBAAsBF,KAAKC,SAAS,CAACR,UAAW;IAEvD;IAEA,OAAOU,IAAAA,kCAAiB,EAACZ,OAAO,CAAC,GAAGA,MAAMa,YAAY,EAAE;AAC1D"}

View File

@ -0,0 +1,6 @@
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime';
import type { FlightSegmentPath } from '../../../server/app-render/types';
/**
* Fill cache up to the end of the flightSegmentPath, invalidating anything below it.
*/
export declare function invalidateCacheBelowFlightSegmentPath(newCache: CacheNode, existingCache: CacheNode, flightSegmentPath: FlightSegmentPath): void;

View File

@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "invalidateCacheBelowFlightSegmentPath", {
enumerable: true,
get: function() {
return invalidateCacheBelowFlightSegmentPath;
}
});
const _createroutercachekey = require("./create-router-cache-key");
function invalidateCacheBelowFlightSegmentPath(newCache, existingCache, flightSegmentPath) {
const isLastEntry = flightSegmentPath.length <= 2;
const [parallelRouteKey, segment] = flightSegmentPath;
const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segment);
const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey);
if (!existingChildSegmentMap) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return;
}
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey);
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap);
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap);
}
// In case of last entry don't copy further down.
if (isLastEntry) {
childSegmentMap.delete(cacheKey);
return;
}
const existingChildCacheNode = existingChildSegmentMap.get(cacheKey);
let childCacheNode = childSegmentMap.get(cacheKey);
if (!childCacheNode || !existingChildCacheNode) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return;
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
lazyData: childCacheNode.lazyData,
rsc: childCacheNode.rsc,
prefetchRsc: childCacheNode.prefetchRsc,
head: childCacheNode.head,
prefetchHead: childCacheNode.prefetchHead,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
lazyDataResolved: childCacheNode.lazyDataResolved
};
childSegmentMap.set(cacheKey, childCacheNode);
}
invalidateCacheBelowFlightSegmentPath(childCacheNode, existingChildCacheNode, flightSegmentPath.slice(2));
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=invalidate-cache-below-flight-segmentpath.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/invalidate-cache-below-flight-segmentpath.ts"],"names":["invalidateCacheBelowFlightSegmentPath","newCache","existingCache","flightSegmentPath","isLastEntry","length","parallelRouteKey","segment","cacheKey","createRouterCacheKey","existingChildSegmentMap","parallelRoutes","get","childSegmentMap","Map","set","delete","existingChildCacheNode","childCacheNode","lazyData","rsc","prefetchRsc","head","prefetchHead","lazyDataResolved","slice"],"mappings":";;;;+BAOgBA;;;eAAAA;;;sCALqB;AAK9B,SAASA,sCACdC,QAAmB,EACnBC,aAAwB,EACxBC,iBAAoC;IAEpC,MAAMC,cAAcD,kBAAkBE,MAAM,IAAI;IAChD,MAAM,CAACC,kBAAkBC,QAAQ,GAAGJ;IAEpC,MAAMK,WAAWC,IAAAA,0CAAoB,EAACF;IAEtC,MAAMG,0BACJR,cAAcS,cAAc,CAACC,GAAG,CAACN;IAEnC,IAAI,CAACI,yBAAyB;QAC5B,6EAA6E;QAC7E,sEAAsE;QACtE;IACF;IAEA,IAAIG,kBAAkBZ,SAASU,cAAc,CAACC,GAAG,CAACN;IAClD,IAAI,CAACO,mBAAmBA,oBAAoBH,yBAAyB;QACnEG,kBAAkB,IAAIC,IAAIJ;QAC1BT,SAASU,cAAc,CAACI,GAAG,CAACT,kBAAkBO;IAChD;IAEA,iDAAiD;IACjD,IAAIT,aAAa;QACfS,gBAAgBG,MAAM,CAACR;QACvB;IACF;IAEA,MAAMS,yBAAyBP,wBAAwBE,GAAG,CAACJ;IAC3D,IAAIU,iBAAiBL,gBAAgBD,GAAG,CAACJ;IAEzC,IAAI,CAACU,kBAAkB,CAACD,wBAAwB;QAC9C,6EAA6E;QAC7E,sEAAsE;QACtE;IACF;IAEA,IAAIC,mBAAmBD,wBAAwB;QAC7CC,iBAAiB;YACfC,UAAUD,eAAeC,QAAQ;YACjCC,KAAKF,eAAeE,GAAG;YACvBC,aAAaH,eAAeG,WAAW;YACvCC,MAAMJ,eAAeI,IAAI;YACzBC,cAAcL,eAAeK,YAAY;YACzCZ,gBAAgB,IAAIG,IAAII,eAAeP,cAAc;YACrDa,kBAAkBN,eAAeM,gBAAgB;QACnD;QACAX,gBAAgBE,GAAG,CAACP,UAAUU;IAChC;IAEAlB,sCACEkB,gBACAD,wBACAd,kBAAkBsB,KAAK,CAAC;AAE5B"}

View File

@ -0,0 +1,6 @@
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime';
import type { FlightRouterState } from '../../../server/app-render/types';
/**
* Invalidate cache one level down from the router state.
*/
export declare function invalidateCacheByRouterState(newCache: CacheNode, existingCache: CacheNode, routerState: FlightRouterState): void;

View File

@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "invalidateCacheByRouterState", {
enumerable: true,
get: function() {
return invalidateCacheByRouterState;
}
});
const _createroutercachekey = require("./create-router-cache-key");
function invalidateCacheByRouterState(newCache, existingCache, routerState) {
// Remove segment that we got data for so that it is filled in during rendering of rsc.
for(const key in routerState[1]){
const segmentForParallelRoute = routerState[1][key][0];
const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segmentForParallelRoute);
const existingParallelRoutesCacheNode = existingCache.parallelRoutes.get(key);
if (existingParallelRoutesCacheNode) {
let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode);
parallelRouteCacheNode.delete(cacheKey);
newCache.parallelRoutes.set(key, parallelRouteCacheNode);
}
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=invalidate-cache-by-router-state.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/invalidate-cache-by-router-state.ts"],"names":["invalidateCacheByRouterState","newCache","existingCache","routerState","key","segmentForParallelRoute","cacheKey","createRouterCacheKey","existingParallelRoutesCacheNode","parallelRoutes","get","parallelRouteCacheNode","Map","delete","set"],"mappings":";;;;+BAOgBA;;;eAAAA;;;sCALqB;AAK9B,SAASA,6BACdC,QAAmB,EACnBC,aAAwB,EACxBC,WAA8B;IAE9B,uFAAuF;IACvF,IAAK,MAAMC,OAAOD,WAAW,CAAC,EAAE,CAAE;QAChC,MAAME,0BAA0BF,WAAW,CAAC,EAAE,CAACC,IAAI,CAAC,EAAE;QACtD,MAAME,WAAWC,IAAAA,0CAAoB,EAACF;QACtC,MAAMG,kCACJN,cAAcO,cAAc,CAACC,GAAG,CAACN;QACnC,IAAII,iCAAiC;YACnC,IAAIG,yBAAyB,IAAIC,IAAIJ;YACrCG,uBAAuBE,MAAM,CAACP;YAC9BL,SAASQ,cAAc,CAACK,GAAG,CAACV,KAAKO;QACnC;IACF;AACF"}

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,2 @@
import type { FlightRouterState } from '../../../server/app-render/types';
export declare function isNavigatingToNewRootLayout(currentTree: FlightRouterState, nextTree: FlightRouterState): boolean;

View File

@ -0,0 +1,51 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "isNavigatingToNewRootLayout", {
enumerable: true,
get: function() {
return isNavigatingToNewRootLayout;
}
});
function isNavigatingToNewRootLayout(currentTree, nextTree) {
// Compare segments
const currentTreeSegment = currentTree[0];
const nextTreeSegment = nextTree[0];
// If any segment is different before we find the root layout, the root layout has changed.
// E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js
// First segment is 'same' for both, keep looking. (group1) changed to (group2) before the root layout was found, it must have changed.
if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegment)) {
// Compare dynamic param name and type but ignore the value, different values would not affect the current root layout
// /[name] - /slug1 and /slug2, both values (slug1 & slug2) still has the same layout /[name]/layout.js
if (currentTreeSegment[0] !== nextTreeSegment[0] || currentTreeSegment[2] !== nextTreeSegment[2]) {
return true;
}
} else if (currentTreeSegment !== nextTreeSegment) {
return true;
}
// Current tree root layout found
if (currentTree[4]) {
// If the next tree doesn't have the root layout flag, it must have changed.
return !nextTree[4];
}
// Current tree didn't have its root layout here, must have changed.
if (nextTree[4]) {
return true;
}
// We can't assume it's `parallelRoutes.children` here in case the root layout is `app/@something/layout.js`
// But it's not possible to be more than one parallelRoutes before the root layout is found
// TODO-APP: change to traverse all parallel routes
const currentTreeChild = Object.values(currentTree[1])[0];
const nextTreeChild = Object.values(nextTree[1])[0];
if (!currentTreeChild || !nextTreeChild) return true;
return isNavigatingToNewRootLayout(currentTreeChild, nextTreeChild);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=is-navigating-to-new-root-layout.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/is-navigating-to-new-root-layout.ts"],"names":["isNavigatingToNewRootLayout","currentTree","nextTree","currentTreeSegment","nextTreeSegment","Array","isArray","currentTreeChild","Object","values","nextTreeChild"],"mappings":";;;;+BAEgBA;;;eAAAA;;;AAAT,SAASA,4BACdC,WAA8B,EAC9BC,QAA2B;IAE3B,mBAAmB;IACnB,MAAMC,qBAAqBF,WAAW,CAAC,EAAE;IACzC,MAAMG,kBAAkBF,QAAQ,CAAC,EAAE;IAEnC,2FAA2F;IAC3F,4DAA4D;IAC5D,uIAAuI;IACvI,IAAIG,MAAMC,OAAO,CAACH,uBAAuBE,MAAMC,OAAO,CAACF,kBAAkB;QACvE,sHAAsH;QACtH,uGAAuG;QACvG,IACED,kBAAkB,CAAC,EAAE,KAAKC,eAAe,CAAC,EAAE,IAC5CD,kBAAkB,CAAC,EAAE,KAAKC,eAAe,CAAC,EAAE,EAC5C;YACA,OAAO;QACT;IACF,OAAO,IAAID,uBAAuBC,iBAAiB;QACjD,OAAO;IACT;IAEA,iCAAiC;IACjC,IAAIH,WAAW,CAAC,EAAE,EAAE;QAClB,4EAA4E;QAC5E,OAAO,CAACC,QAAQ,CAAC,EAAE;IACrB;IACA,qEAAqE;IACrE,IAAIA,QAAQ,CAAC,EAAE,EAAE;QACf,OAAO;IACT;IACA,4GAA4G;IAC5G,2FAA2F;IAC3F,mDAAmD;IACnD,MAAMK,mBAAmBC,OAAOC,MAAM,CAACR,WAAW,CAAC,EAAE,CAAC,CAAC,EAAE;IACzD,MAAMS,gBAAgBF,OAAOC,MAAM,CAACP,QAAQ,CAAC,EAAE,CAAC,CAAC,EAAE;IACnD,IAAI,CAACK,oBAAoB,CAACG,eAAe,OAAO;IAChD,OAAOV,4BAA4BO,kBAAkBG;AACvD"}

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,23 @@
/// <reference types="react" />
import type { CacheNodeSeedData, FlightRouterState } from '../../../server/app-render/types';
import type { CacheNode, ChildSegmentMap } from '../../../shared/lib/app-router-context.shared-runtime';
import type { FetchServerResponseResult } from './fetch-server-response';
type Task = {
route: FlightRouterState;
node: CacheNode | null;
children: Map<string, Task> | null;
};
export declare function updateCacheNodeOnNavigation(oldCacheNode: CacheNode, oldRouterState: FlightRouterState, newRouterState: FlightRouterState, prefetchData: CacheNodeSeedData, prefetchHead: React.ReactNode): Task | null;
export declare function listenForDynamicRequest(task: Task, responsePromise: Promise<FetchServerResponseResult>): void;
export declare function abortTask(task: Task, error: any): void;
export declare function updateCacheNodeOnPopstateRestoration(oldCacheNode: CacheNode, routerState: FlightRouterState): {
lazyData: null;
rsc: import("react").ReactNode;
head: import("react").ReactNode;
prefetchHead: import("react").ReactNode;
prefetchRsc: import("react").ReactNode;
loading: import("../../../shared/lib/app-router-context.shared-runtime").LoadingModuleData;
parallelRoutes: Map<string, ChildSegmentMap>;
lazyDataResolved: boolean;
};
export {};

View File

@ -0,0 +1,568 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
abortTask: null,
listenForDynamicRequest: null,
updateCacheNodeOnNavigation: null,
updateCacheNodeOnPopstateRestoration: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
abortTask: function() {
return abortTask;
},
listenForDynamicRequest: function() {
return listenForDynamicRequest;
},
updateCacheNodeOnNavigation: function() {
return updateCacheNodeOnNavigation;
},
updateCacheNodeOnPopstateRestoration: function() {
return updateCacheNodeOnPopstateRestoration;
}
});
const _segment = require("../../../shared/lib/segment");
const _matchsegments = require("../match-segments");
const _createroutercachekey = require("./create-router-cache-key");
function updateCacheNodeOnNavigation(oldCacheNode, oldRouterState, newRouterState, prefetchData, prefetchHead) {
// Diff the old and new trees to reuse the shared layouts.
const oldRouterStateChildren = oldRouterState[1];
const newRouterStateChildren = newRouterState[1];
const prefetchDataChildren = prefetchData[1];
const oldParallelRoutes = oldCacheNode.parallelRoutes;
// Clone the current set of segment children, even if they aren't active in
// the new tree.
// TODO: We currently retain all the inactive segments indefinitely, until
// there's an explicit refresh, or a parent layout is lazily refreshed. We
// rely on this for popstate navigations, which update the Router State Tree
// but do not eagerly perform a data fetch, because they expect the segment
// data to already be in the Cache Node tree. For highly static sites that
// are mostly read-only, this may happen only rarely, causing memory to
// leak. We should figure out a better model for the lifetime of inactive
// segments, so we can maintain instant back/forward navigations without
// leaking memory indefinitely.
const prefetchParallelRoutes = new Map(oldParallelRoutes);
// As we diff the trees, we may sometimes modify (copy-on-write, not mutate)
// the Route Tree that was returned by the server — for example, in the case
// of default parallel routes, we preserve the currently active segment. To
// avoid mutating the original tree, we clone the router state children along
// the return path.
let patchedRouterStateChildren = {};
let taskChildren = null;
for(let parallelRouteKey in newRouterStateChildren){
const newRouterStateChild = newRouterStateChildren[parallelRouteKey];
const oldRouterStateChild = oldRouterStateChildren[parallelRouteKey];
const oldSegmentMapChild = oldParallelRoutes.get(parallelRouteKey);
const prefetchDataChild = prefetchDataChildren[parallelRouteKey];
const newSegmentChild = newRouterStateChild[0];
const newSegmentKeyChild = (0, _createroutercachekey.createRouterCacheKey)(newSegmentChild);
const oldSegmentChild = oldRouterStateChild !== undefined ? oldRouterStateChild[0] : undefined;
const oldCacheNodeChild = oldSegmentMapChild !== undefined ? oldSegmentMapChild.get(newSegmentKeyChild) : undefined;
let taskChild;
if (newSegmentChild === _segment.PAGE_SEGMENT_KEY) {
// This is a leaf segment — a page, not a shared layout. We always apply
// its data.
taskChild = spawnPendingTask(newRouterStateChild, prefetchDataChild !== undefined ? prefetchDataChild : null, prefetchHead);
} else if (newSegmentChild === _segment.DEFAULT_SEGMENT_KEY) {
// This is another kind of leaf segment — a default route.
//
// Default routes have special behavior. When there's no matching segment
// for a parallel route, Next.js preserves the currently active segment
// during a client navigation — but not for initial render. The server
// leaves it to the client to account for this. So we need to handle
// it here.
if (oldRouterStateChild !== undefined) {
// Reuse the existing Router State for this segment. We spawn a "task"
// just to keep track of the updated router state; unlike most, it's
// already fulfilled and won't be affected by the dynamic response.
taskChild = spawnReusedTask(oldRouterStateChild);
} else {
// There's no currently active segment. Switch to the "create" path.
taskChild = spawnPendingTask(newRouterStateChild, prefetchDataChild !== undefined ? prefetchDataChild : null, prefetchHead);
}
} else if (oldSegmentChild !== undefined && (0, _matchsegments.matchSegment)(newSegmentChild, oldSegmentChild)) {
if (oldCacheNodeChild !== undefined && oldRouterStateChild !== undefined) {
// This segment exists in both the old and new trees.
if (prefetchDataChild !== undefined && prefetchDataChild !== null) {
// Recursively update the children.
taskChild = updateCacheNodeOnNavigation(oldCacheNodeChild, oldRouterStateChild, newRouterStateChild, prefetchDataChild, prefetchHead);
} else {
// The server didn't send any prefetch data for this segment. This
// shouldn't happen because the Route Tree and the Seed Data tree
// should always be the same shape, but until we unify those types
// it's still possible. For now we're going to deopt and trigger a
// lazy fetch during render.
taskChild = spawnTaskForMissingData(newRouterStateChild);
}
} else {
// Either there's no existing Cache Node for this segment, or this
// segment doesn't exist in the old Router State tree. Switch to the
// "create" path.
taskChild = spawnPendingTask(newRouterStateChild, prefetchDataChild !== undefined ? prefetchDataChild : null, prefetchHead);
}
} else {
// This is a new tree. Switch to the "create" path.
taskChild = spawnPendingTask(newRouterStateChild, prefetchDataChild !== undefined ? prefetchDataChild : null, prefetchHead);
}
if (taskChild !== null) {
// Something changed in the child tree. Keep track of the child task.
if (taskChildren === null) {
taskChildren = new Map();
}
taskChildren.set(parallelRouteKey, taskChild);
const newCacheNodeChild = taskChild.node;
if (newCacheNodeChild !== null) {
const newSegmentMapChild = new Map(oldSegmentMapChild);
newSegmentMapChild.set(newSegmentKeyChild, newCacheNodeChild);
prefetchParallelRoutes.set(parallelRouteKey, newSegmentMapChild);
}
// The child tree's route state may be different from the prefetched
// route sent by the server. We need to clone it as we traverse back up
// the tree.
patchedRouterStateChildren[parallelRouteKey] = taskChild.route;
} else {
// The child didn't change. We can use the prefetched router state.
patchedRouterStateChildren[parallelRouteKey] = newRouterStateChild;
}
}
if (taskChildren === null) {
// No new tasks were spawned.
return null;
}
const newCacheNode = {
lazyData: null,
rsc: oldCacheNode.rsc,
// We intentionally aren't updating the prefetchRsc field, since this node
// is already part of the current tree, because it would be weird for
// prefetch data to be newer than the final data. It probably won't ever be
// observable anyway, but it could happen if the segment is unmounted then
// mounted again, because LayoutRouter will momentarily switch to rendering
// prefetchRsc, via useDeferredValue.
prefetchRsc: oldCacheNode.prefetchRsc,
head: oldCacheNode.head,
prefetchHead: oldCacheNode.prefetchHead,
loading: oldCacheNode.loading,
// Everything is cloned except for the children, which we computed above.
parallelRoutes: prefetchParallelRoutes,
lazyDataResolved: false
};
return {
// Return a cloned copy of the router state with updated children.
route: patchRouterStateWithNewChildren(newRouterState, patchedRouterStateChildren),
node: newCacheNode,
children: taskChildren
};
}
function patchRouterStateWithNewChildren(baseRouterState, newChildren) {
const clone = [
baseRouterState[0],
newChildren
];
// Based on equivalent logic in apply-router-state-patch-to-tree, but should
// confirm whether we need to copy all of these fields. Not sure the server
// ever sends, e.g. the refetch marker.
if (2 in baseRouterState) {
clone[2] = baseRouterState[2];
}
if (3 in baseRouterState) {
clone[3] = baseRouterState[3];
}
if (4 in baseRouterState) {
clone[4] = baseRouterState[4];
}
return clone;
}
function spawnPendingTask(routerState, prefetchData, prefetchHead) {
// Create a task that will later be fulfilled by data from the server.
const pendingCacheNode = createPendingCacheNode(routerState, prefetchData, prefetchHead);
return {
route: routerState,
node: pendingCacheNode,
children: null
};
}
function spawnReusedTask(reusedRouterState) {
// Create a task that reuses an existing segment, e.g. when reusing
// the current active segment in place of a default route.
return {
route: reusedRouterState,
node: null,
children: null
};
}
function spawnTaskForMissingData(routerState) {
// Create a task for a new subtree that wasn't prefetched by the server.
// This shouldn't really ever happen but it's here just in case the Seed Data
// Tree and the Router State Tree disagree unexpectedly.
const pendingCacheNode = createPendingCacheNode(routerState, null, null);
return {
route: routerState,
node: pendingCacheNode,
children: null
};
}
function listenForDynamicRequest(task, responsePromise) {
responsePromise.then((response)=>{
const flightData = response[0];
for (const flightDataPath of flightData){
const segmentPath = flightDataPath.slice(0, -3);
const serverRouterState = flightDataPath[flightDataPath.length - 3];
const dynamicData = flightDataPath[flightDataPath.length - 2];
const dynamicHead = flightDataPath[flightDataPath.length - 1];
if (typeof segmentPath === "string") {
continue;
}
writeDynamicDataIntoPendingTask(task, segmentPath, serverRouterState, dynamicData, dynamicHead);
}
// Now that we've exhausted all the data we received from the server, if
// there are any remaining pending tasks in the tree, abort them now.
// If there's any missing data, it will trigger a lazy fetch.
abortTask(task, null);
}, (error)=>{
// This will trigger an error during render
abortTask(task, error);
});
}
function writeDynamicDataIntoPendingTask(rootTask, segmentPath, serverRouterState, dynamicData, dynamicHead) {
// The data sent by the server represents only a subtree of the app. We need
// to find the part of the task tree that matches the server response, and
// fulfill it using the dynamic data.
//
// segmentPath represents the parent path of subtree. It's a repeating pattern
// of parallel route key and segment:
//
// [string, Segment, string, Segment, string, Segment, ...]
//
// Iterate through the path and finish any tasks that match this payload.
let task = rootTask;
for(let i = 0; i < segmentPath.length; i += 2){
const parallelRouteKey = segmentPath[i];
const segment = segmentPath[i + 1];
const taskChildren = task.children;
if (taskChildren !== null) {
const taskChild = taskChildren.get(parallelRouteKey);
if (taskChild !== undefined) {
const taskSegment = taskChild.route[0];
if ((0, _matchsegments.matchSegment)(segment, taskSegment)) {
// Found a match for this task. Keep traversing down the task tree.
task = taskChild;
continue;
}
}
}
// We didn't find a child task that matches the server data. Exit. We won't
// abort the task, though, because a different FlightDataPath may be able to
// fulfill it (see loop in listenForDynamicRequest). We only abort tasks
// once we've run out of data.
return;
}
finishTaskUsingDynamicDataPayload(task, serverRouterState, dynamicData, dynamicHead);
}
function finishTaskUsingDynamicDataPayload(task, serverRouterState, dynamicData, dynamicHead) {
// dynamicData may represent a larger subtree than the task. Before we can
// finish the task, we need to line them up.
const taskChildren = task.children;
const taskNode = task.node;
if (taskChildren === null) {
// We've reached the leaf node of the pending task. The server data tree
// lines up the pending Cache Node tree. We can now switch to the
// normal algorithm.
if (taskNode !== null) {
finishPendingCacheNode(taskNode, task.route, serverRouterState, dynamicData, dynamicHead);
// Null this out to indicate that the task is complete.
task.node = null;
}
return;
}
// The server returned more data than we need to finish the task. Skip over
// the extra segments until we reach the leaf task node.
const serverChildren = serverRouterState[1];
const dynamicDataChildren = dynamicData[1];
for(const parallelRouteKey in serverRouterState){
const serverRouterStateChild = serverChildren[parallelRouteKey];
const dynamicDataChild = dynamicDataChildren[parallelRouteKey];
const taskChild = taskChildren.get(parallelRouteKey);
if (taskChild !== undefined) {
const taskSegment = taskChild.route[0];
if ((0, _matchsegments.matchSegment)(serverRouterStateChild[0], taskSegment) && dynamicDataChild !== null && dynamicDataChild !== undefined) {
// Found a match for this task. Keep traversing down the task tree.
return finishTaskUsingDynamicDataPayload(taskChild, serverRouterStateChild, dynamicDataChild, dynamicHead);
}
}
// We didn't find a child task that matches the server data. We won't abort
// the task, though, because a different FlightDataPath may be able to
// fulfill it (see loop in listenForDynamicRequest). We only abort tasks
// once we've run out of data.
}
}
function createPendingCacheNode(routerState, prefetchData, prefetchHead) {
const routerStateChildren = routerState[1];
const prefetchDataChildren = prefetchData !== null ? prefetchData[1] : null;
const parallelRoutes = new Map();
for(let parallelRouteKey in routerStateChildren){
const routerStateChild = routerStateChildren[parallelRouteKey];
const prefetchDataChild = prefetchDataChildren !== null ? prefetchDataChildren[parallelRouteKey] : null;
const segmentChild = routerStateChild[0];
const segmentKeyChild = (0, _createroutercachekey.createRouterCacheKey)(segmentChild);
const newCacheNodeChild = createPendingCacheNode(routerStateChild, prefetchDataChild === undefined ? null : prefetchDataChild, prefetchHead);
const newSegmentMapChild = new Map();
newSegmentMapChild.set(segmentKeyChild, newCacheNodeChild);
parallelRoutes.set(parallelRouteKey, newSegmentMapChild);
}
// The head is assigned to every leaf segment delivered by the server. Based
// on corresponding logic in fill-lazy-items-till-leaf-with-head.ts
const isLeafSegment = parallelRoutes.size === 0;
const maybePrefetchRsc = prefetchData !== null ? prefetchData[2] : null;
const maybePrefetchLoading = prefetchData !== null ? prefetchData[3] : null;
return {
lazyData: null,
parallelRoutes: parallelRoutes,
prefetchRsc: maybePrefetchRsc !== undefined ? maybePrefetchRsc : null,
prefetchHead: isLeafSegment ? prefetchHead : null,
loading: maybePrefetchLoading !== undefined ? maybePrefetchLoading : null,
// Create a deferred promise. This will be fulfilled once the dynamic
// response is received from the server.
rsc: createDeferredRsc(),
head: isLeafSegment ? createDeferredRsc() : null,
lazyDataResolved: false
};
}
function finishPendingCacheNode(cacheNode, taskState, serverState, dynamicData, dynamicHead) {
// Writes a dynamic response into an existing Cache Node tree. This does _not_
// create a new tree, it updates the existing tree in-place. So it must follow
// the Suspense rules of cache safety — it can resolve pending promises, but
// it cannot overwrite existing data. It can add segments to the tree (because
// a missing segment will cause the layout router to suspend).
// but it cannot delete them.
//
// We must resolve every promise in the tree, or else it will suspend
// indefinitely. If we did not receive data for a segment, we will resolve its
// data promise to `null` to trigger a lazy fetch during render.
const taskStateChildren = taskState[1];
const serverStateChildren = serverState[1];
const dataChildren = dynamicData[1];
// The router state that we traverse the tree with (taskState) is the same one
// that we used to construct the pending Cache Node tree. That way we're sure
// to resolve all the pending promises.
const parallelRoutes = cacheNode.parallelRoutes;
for(let parallelRouteKey in taskStateChildren){
const taskStateChild = taskStateChildren[parallelRouteKey];
const serverStateChild = serverStateChildren[parallelRouteKey];
const dataChild = dataChildren[parallelRouteKey];
const segmentMapChild = parallelRoutes.get(parallelRouteKey);
const taskSegmentChild = taskStateChild[0];
const taskSegmentKeyChild = (0, _createroutercachekey.createRouterCacheKey)(taskSegmentChild);
const cacheNodeChild = segmentMapChild !== undefined ? segmentMapChild.get(taskSegmentKeyChild) : undefined;
if (cacheNodeChild !== undefined) {
if (serverStateChild !== undefined && (0, _matchsegments.matchSegment)(taskSegmentChild, serverStateChild[0])) {
if (dataChild !== undefined && dataChild !== null) {
// This is the happy path. Recursively update all the children.
finishPendingCacheNode(cacheNodeChild, taskStateChild, serverStateChild, dataChild, dynamicHead);
} else {
// The server never returned data for this segment. Trigger a lazy
// fetch during render. This shouldn't happen because the Route Tree
// and the Seed Data tree sent by the server should always be the same
// shape when part of the same server response.
abortPendingCacheNode(taskStateChild, cacheNodeChild, null);
}
} else {
// The server never returned data for this segment. Trigger a lazy
// fetch during render.
abortPendingCacheNode(taskStateChild, cacheNodeChild, null);
}
} else {
// The server response matches what was expected to receive, but there's
// no matching Cache Node in the task tree. This is a bug in the
// implementation because we should have created a node for every
// segment in the tree that's associated with this task.
}
}
// Use the dynamic data from the server to fulfill the deferred RSC promise
// on the Cache Node.
const rsc = cacheNode.rsc;
const dynamicSegmentData = dynamicData[2];
if (rsc === null) {
// This is a lazy cache node. We can overwrite it. This is only safe
// because we know that the LayoutRouter suspends if `rsc` is `null`.
cacheNode.rsc = dynamicSegmentData;
} else if (isDeferredRsc(rsc)) {
// This is a deferred RSC promise. We can fulfill it with the data we just
// received from the server. If it was already resolved by a different
// navigation, then this does nothing because we can't overwrite data.
rsc.resolve(dynamicSegmentData);
} else {
// This is not a deferred RSC promise, nor is it empty, so it must have
// been populated by a different navigation. We must not overwrite it.
}
// Check if this is a leaf segment. If so, it will have a `head` property with
// a pending promise that needs to be resolved with the dynamic head from
// the server.
const head = cacheNode.head;
if (isDeferredRsc(head)) {
head.resolve(dynamicHead);
}
}
function abortTask(task, error) {
const cacheNode = task.node;
if (cacheNode === null) {
// This indicates the task is already complete.
return;
}
const taskChildren = task.children;
if (taskChildren === null) {
// Reached the leaf task node. This is the root of a pending cache
// node tree.
abortPendingCacheNode(task.route, cacheNode, error);
} else {
// This is an intermediate task node. Keep traversing until we reach a
// task node with no children. That will be the root of the cache node tree
// that needs to be resolved.
for (const taskChild of taskChildren.values()){
abortTask(taskChild, error);
}
}
// Null this out to indicate that the task is complete.
task.node = null;
}
function abortPendingCacheNode(routerState, cacheNode, error) {
// For every pending segment in the tree, resolve its `rsc` promise to `null`
// to trigger a lazy fetch during render.
//
// Or, if an error object is provided, it will error instead.
const routerStateChildren = routerState[1];
const parallelRoutes = cacheNode.parallelRoutes;
for(let parallelRouteKey in routerStateChildren){
const routerStateChild = routerStateChildren[parallelRouteKey];
const segmentMapChild = parallelRoutes.get(parallelRouteKey);
if (segmentMapChild === undefined) {
continue;
}
const segmentChild = routerStateChild[0];
const segmentKeyChild = (0, _createroutercachekey.createRouterCacheKey)(segmentChild);
const cacheNodeChild = segmentMapChild.get(segmentKeyChild);
if (cacheNodeChild !== undefined) {
abortPendingCacheNode(routerStateChild, cacheNodeChild, error);
} else {
// This shouldn't happen because we're traversing the same tree that was
// used to construct the cache nodes in the first place.
}
}
const rsc = cacheNode.rsc;
if (isDeferredRsc(rsc)) {
if (error === null) {
// This will trigger a lazy fetch during render.
rsc.resolve(null);
} else {
// This will trigger an error during rendering.
rsc.reject(error);
}
}
// Check if this is a leaf segment. If so, it will have a `head` property with
// a pending promise that needs to be resolved. If an error was provided, we
// will not resolve it with an error, since this is rendered at the root of
// the app. We want the segment to error, not the entire app.
const head = cacheNode.head;
if (isDeferredRsc(head)) {
head.resolve(null);
}
}
function updateCacheNodeOnPopstateRestoration(oldCacheNode, routerState) {
// A popstate navigation reads data from the local cache. It does not issue
// new network requests (unless the cache entries have been evicted). So, we
// update the cache to drop the prefetch data for any segment whose dynamic
// data was already received. This prevents an unnecessary flash back to PPR
// state during a back/forward navigation.
//
// This function clones the entire cache node tree and sets the `prefetchRsc`
// field to `null` to prevent it from being rendered. We can't mutate the node
// in place because this is a concurrent data structure.
const routerStateChildren = routerState[1];
const oldParallelRoutes = oldCacheNode.parallelRoutes;
const newParallelRoutes = new Map(oldParallelRoutes);
for(let parallelRouteKey in routerStateChildren){
const routerStateChild = routerStateChildren[parallelRouteKey];
const segmentChild = routerStateChild[0];
const segmentKeyChild = (0, _createroutercachekey.createRouterCacheKey)(segmentChild);
const oldSegmentMapChild = oldParallelRoutes.get(parallelRouteKey);
if (oldSegmentMapChild !== undefined) {
const oldCacheNodeChild = oldSegmentMapChild.get(segmentKeyChild);
if (oldCacheNodeChild !== undefined) {
const newCacheNodeChild = updateCacheNodeOnPopstateRestoration(oldCacheNodeChild, routerStateChild);
const newSegmentMapChild = new Map(oldSegmentMapChild);
newSegmentMapChild.set(segmentKeyChild, newCacheNodeChild);
newParallelRoutes.set(parallelRouteKey, newSegmentMapChild);
}
}
}
// Only show prefetched data if the dynamic data is still pending.
//
// Tehnically, what we're actually checking is whether the dynamic network
// response was received. But since it's a streaming response, this does not
// mean that all the dynamic data has fully streamed in. It just means that
// _some_ of the dynamic data was received. But as a heuristic, we assume that
// the rest dynamic data will stream in quickly, so it's still better to skip
// the prefetch state.
const rsc = oldCacheNode.rsc;
const shouldUsePrefetch = isDeferredRsc(rsc) && rsc.status === "pending";
return {
lazyData: null,
rsc,
head: oldCacheNode.head,
prefetchHead: shouldUsePrefetch ? oldCacheNode.prefetchHead : null,
prefetchRsc: shouldUsePrefetch ? oldCacheNode.prefetchRsc : null,
loading: shouldUsePrefetch ? oldCacheNode.loading : null,
// These are the cloned children we computed above
parallelRoutes: newParallelRoutes,
lazyDataResolved: false
};
}
const DEFERRED = Symbol();
// This type exists to distinguish a DeferredRsc from a Flight promise. It's a
// compromise to avoid adding an extra field on every Cache Node, which would be
// awkward because the pre-PPR parts of codebase would need to account for it,
// too. We can remove it once type Cache Node type is more settled.
function isDeferredRsc(value) {
return value && value.tag === DEFERRED;
}
function createDeferredRsc() {
let resolve;
let reject;
const pendingRsc = new Promise((res, rej)=>{
resolve = res;
reject = rej;
});
pendingRsc.status = "pending";
pendingRsc.resolve = (value)=>{
if (pendingRsc.status === "pending") {
const fulfilledRsc = pendingRsc;
fulfilledRsc.status = "fulfilled";
fulfilledRsc.value = value;
resolve(value);
}
};
pendingRsc.reject = (error)=>{
if (pendingRsc.status === "pending") {
const rejectedRsc = pendingRsc;
rejectedRsc.status = "rejected";
rejectedRsc.reason = error;
reject(error);
}
};
pendingRsc.tag = DEFERRED;
return pendingRsc;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=ppr-navigations.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,27 @@
import { type FetchServerResponseResult } from './fetch-server-response';
import { PrefetchCacheEntryStatus, type PrefetchCacheEntry, PrefetchKind, type ReadonlyReducerState } from './router-reducer-types';
/**
* Returns a prefetch cache entry if one exists. Otherwise creates a new one and enqueues a fetch request
* to retrieve the prefetch data from the server.
*/
export declare function getOrCreatePrefetchCacheEntry({ url, nextUrl, tree, buildId, prefetchCache, kind, }: Pick<ReadonlyReducerState, 'nextUrl' | 'prefetchCache' | 'tree' | 'buildId'> & {
url: URL;
kind?: PrefetchKind;
}): PrefetchCacheEntry;
/**
* Use to seed the prefetch cache with data that has already been fetched.
*/
export declare function createPrefetchCacheEntryForInitialLoad({ nextUrl, tree, prefetchCache, url, kind, data, }: Pick<ReadonlyReducerState, 'nextUrl' | 'tree' | 'prefetchCache'> & {
url: URL;
kind: PrefetchKind;
data: FetchServerResponseResult;
}): {
treeAtTimeOfPrefetch: import("../../../server/app-render/types").FlightRouterState;
data: Promise<FetchServerResponseResult>;
kind: PrefetchKind;
prefetchTime: number;
lastUsedTime: number;
key: string;
status: PrefetchCacheEntryStatus;
};
export declare function prunePrefetchCache(prefetchCache: ReadonlyReducerState['prefetchCache']): void;

View File

@ -0,0 +1,207 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createPrefetchCacheEntryForInitialLoad: null,
getOrCreatePrefetchCacheEntry: null,
prunePrefetchCache: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createPrefetchCacheEntryForInitialLoad: function() {
return createPrefetchCacheEntryForInitialLoad;
},
getOrCreatePrefetchCacheEntry: function() {
return getOrCreatePrefetchCacheEntry;
},
prunePrefetchCache: function() {
return prunePrefetchCache;
}
});
const _createhreffromurl = require("./create-href-from-url");
const _fetchserverresponse = require("./fetch-server-response");
const _routerreducertypes = require("./router-reducer-types");
const _prefetchreducer = require("./reducers/prefetch-reducer");
/**
* Creates a cache key for the router prefetch cache
*
* @param url - The URL being navigated to
* @param nextUrl - an internal URL, primarily used for handling rewrites. Defaults to '/'.
* @return The generated prefetch cache key.
*/ function createPrefetchCacheKey(url, nextUrl) {
const pathnameFromUrl = (0, _createhreffromurl.createHrefFromUrl)(url, // Ensures the hash is not part of the cache key as it does not impact the server fetch
false);
// nextUrl is used as a cache key delimiter since entries can vary based on the Next-URL header
if (nextUrl) {
return nextUrl + "%" + pathnameFromUrl;
}
return pathnameFromUrl;
}
function getOrCreatePrefetchCacheEntry(param) {
let { url, nextUrl, tree, buildId, prefetchCache, kind } = param;
let existingCacheEntry = undefined;
// We first check if there's a more specific interception route prefetch entry
// This is because when we detect a prefetch that corresponds with an interception route, we prefix it with nextUrl (see `createPrefetchCacheKey`)
// to avoid conflicts with other pages that may have the same URL but render different things depending on the `Next-URL` header.
const interceptionCacheKey = createPrefetchCacheKey(url, nextUrl);
const interceptionData = prefetchCache.get(interceptionCacheKey);
if (interceptionData) {
existingCacheEntry = interceptionData;
} else {
// If we dont find a more specific interception route prefetch entry, we check for a regular prefetch entry
const prefetchCacheKey = createPrefetchCacheKey(url);
const prefetchData = prefetchCache.get(prefetchCacheKey);
if (prefetchData) {
existingCacheEntry = prefetchData;
}
}
if (existingCacheEntry) {
// Grab the latest status of the cache entry and update it
existingCacheEntry.status = getPrefetchEntryCacheStatus(existingCacheEntry);
// when `kind` is provided, an explicit prefetch was requested.
// if the requested prefetch is "full" and the current cache entry wasn't, we want to re-prefetch with the new intent
const switchedToFullPrefetch = existingCacheEntry.kind !== _routerreducertypes.PrefetchKind.FULL && kind === _routerreducertypes.PrefetchKind.FULL;
if (switchedToFullPrefetch) {
return createLazyPrefetchEntry({
tree,
url,
buildId,
nextUrl,
prefetchCache,
// If we didn't get an explicit prefetch kind, we want to set a temporary kind
// rather than assuming the same intent as the previous entry, to be consistent with how we
// lazily create prefetch entries when intent is left unspecified.
kind: kind != null ? kind : _routerreducertypes.PrefetchKind.TEMPORARY
});
}
// If the existing cache entry was marked as temporary, it means it was lazily created when attempting to get an entry,
// where we didn't have the prefetch intent. Now that we have the intent (in `kind`), we want to update the entry to the more accurate kind.
if (kind && existingCacheEntry.kind === _routerreducertypes.PrefetchKind.TEMPORARY) {
existingCacheEntry.kind = kind;
}
// We've determined that the existing entry we found is still valid, so we return it.
return existingCacheEntry;
}
// If we didn't return an entry, create a new one.
return createLazyPrefetchEntry({
tree,
url,
buildId,
nextUrl,
prefetchCache,
kind: kind || // in dev, there's never gonna be a prefetch entry so we want to prefetch here
(process.env.NODE_ENV === "development" ? _routerreducertypes.PrefetchKind.AUTO : _routerreducertypes.PrefetchKind.TEMPORARY)
});
}
/*
* Used to take an existing cache entry and prefix it with the nextUrl, if it exists.
* This ensures that we don't have conflicting cache entries for the same URL (as is the case with route interception).
*/ function prefixExistingPrefetchCacheEntry(param) {
let { url, nextUrl, prefetchCache } = param;
const existingCacheKey = createPrefetchCacheKey(url);
const existingCacheEntry = prefetchCache.get(existingCacheKey);
if (!existingCacheEntry) {
// no-op -- there wasn't an entry to move
return;
}
const newCacheKey = createPrefetchCacheKey(url, nextUrl);
prefetchCache.set(newCacheKey, existingCacheEntry);
prefetchCache.delete(existingCacheKey);
}
function createPrefetchCacheEntryForInitialLoad(param) {
let { nextUrl, tree, prefetchCache, url, kind, data } = param;
const [, , , intercept] = data;
// if the prefetch corresponds with an interception route, we use the nextUrl to prefix the cache key
const prefetchCacheKey = intercept ? createPrefetchCacheKey(url, nextUrl) : createPrefetchCacheKey(url);
const prefetchEntry = {
treeAtTimeOfPrefetch: tree,
data: Promise.resolve(data),
kind,
prefetchTime: Date.now(),
lastUsedTime: Date.now(),
key: prefetchCacheKey,
status: _routerreducertypes.PrefetchCacheEntryStatus.fresh
};
prefetchCache.set(prefetchCacheKey, prefetchEntry);
return prefetchEntry;
}
/**
* Creates a prefetch entry entry and enqueues a fetch request to retrieve the data.
*/ function createLazyPrefetchEntry(param) {
let { url, kind, tree, nextUrl, buildId, prefetchCache } = param;
const prefetchCacheKey = createPrefetchCacheKey(url);
// initiates the fetch request for the prefetch and attaches a listener
// to the promise to update the prefetch cache entry when the promise resolves (if necessary)
const data = _prefetchreducer.prefetchQueue.enqueue(()=>(0, _fetchserverresponse.fetchServerResponse)(url, tree, nextUrl, buildId, kind).then((prefetchResponse)=>{
// TODO: `fetchServerResponse` should be more tighly coupled to these prefetch cache operations
// to avoid drift between this cache key prefixing logic
// (which is currently directly influenced by the server response)
const [, , , intercepted] = prefetchResponse;
if (intercepted) {
prefixExistingPrefetchCacheEntry({
url,
nextUrl,
prefetchCache
});
}
return prefetchResponse;
}));
const prefetchEntry = {
treeAtTimeOfPrefetch: tree,
data,
kind,
prefetchTime: Date.now(),
lastUsedTime: null,
key: prefetchCacheKey,
status: _routerreducertypes.PrefetchCacheEntryStatus.fresh
};
prefetchCache.set(prefetchCacheKey, prefetchEntry);
return prefetchEntry;
}
function prunePrefetchCache(prefetchCache) {
for (const [href, prefetchCacheEntry] of prefetchCache){
if (getPrefetchEntryCacheStatus(prefetchCacheEntry) === _routerreducertypes.PrefetchCacheEntryStatus.expired) {
prefetchCache.delete(href);
}
}
}
// These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`)
// and default to 5 minutes (static) / 30 seconds (dynamic)
const DYNAMIC_STALETIME_MS = Number(process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME) * 1000;
const STATIC_STALETIME_MS = Number(process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME) * 1000;
function getPrefetchEntryCacheStatus(param) {
let { kind, prefetchTime, lastUsedTime } = param;
// We will re-use the cache entry data for up to the `dynamic` staletime window.
if (Date.now() < (lastUsedTime != null ? lastUsedTime : prefetchTime) + DYNAMIC_STALETIME_MS) {
return lastUsedTime ? _routerreducertypes.PrefetchCacheEntryStatus.reusable : _routerreducertypes.PrefetchCacheEntryStatus.fresh;
}
// For "auto" prefetching, we'll re-use only the loading boundary for up to `static` staletime window.
// A stale entry will only re-use the `loading` boundary, not the full data.
// This will trigger a "lazy fetch" for the full data.
if (kind === "auto") {
if (Date.now() < prefetchTime + STATIC_STALETIME_MS) {
return _routerreducertypes.PrefetchCacheEntryStatus.stale;
}
}
// for "full" prefetching, we'll re-use the cache entry data for up to `static` staletime window.
if (kind === "full") {
if (Date.now() < prefetchTime + STATIC_STALETIME_MS) {
return _routerreducertypes.PrefetchCacheEntryStatus.reusable;
}
}
return _routerreducertypes.PrefetchCacheEntryStatus.expired;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=prefetch-cache-utils.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/prefetch-cache-utils.ts"],"names":["createPrefetchCacheEntryForInitialLoad","getOrCreatePrefetchCacheEntry","prunePrefetchCache","createPrefetchCacheKey","url","nextUrl","pathnameFromUrl","createHrefFromUrl","tree","buildId","prefetchCache","kind","existingCacheEntry","undefined","interceptionCacheKey","interceptionData","get","prefetchCacheKey","prefetchData","status","getPrefetchEntryCacheStatus","switchedToFullPrefetch","PrefetchKind","FULL","createLazyPrefetchEntry","TEMPORARY","process","env","NODE_ENV","AUTO","prefixExistingPrefetchCacheEntry","existingCacheKey","newCacheKey","set","delete","data","intercept","prefetchEntry","treeAtTimeOfPrefetch","Promise","resolve","prefetchTime","Date","now","lastUsedTime","key","PrefetchCacheEntryStatus","fresh","prefetchQueue","enqueue","fetchServerResponse","then","prefetchResponse","intercepted","href","prefetchCacheEntry","expired","DYNAMIC_STALETIME_MS","Number","__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME","STATIC_STALETIME_MS","__NEXT_CLIENT_ROUTER_STATIC_STALETIME","reusable","stale"],"mappings":";;;;;;;;;;;;;;;;IAmJgBA,sCAAsC;eAAtCA;;IA5GAC,6BAA6B;eAA7BA;;IAiMAC,kBAAkB;eAAlBA;;;mCAxOkB;qCAI3B;oCAMA;iCACuB;AAE9B;;;;;;CAMC,GACD,SAASC,uBAAuBC,GAAQ,EAAEC,OAAuB;IA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C,GAAG,KAAKF,eAAemB,qBAAqB;YACnD,OAAOd,4CAAwB,CAACiB,KAAK;QACvC;IACF;IAEA,iGAAiG;IACjG,IAAIpD,SAAS,QAAQ;QACnB,IAAI+B,KAAKC,GAAG,KAAKF,eAAemB,qBAAqB;YACnD,OAAOd,4CAAwB,CAACgB,QAAQ;QAC1C;IACF;IAEA,OAAOhB,4CAAwB,CAACU,OAAO;AACzC"}

View File

@ -0,0 +1,4 @@
import type { ReadonlyReducerState, ReducerState, FastRefreshAction } from '../router-reducer-types';
declare function fastRefreshReducerNoop(state: ReadonlyReducerState, _action: FastRefreshAction): ReducerState;
export declare const fastRefreshReducer: typeof fastRefreshReducerNoop;
export {};

View File

@ -0,0 +1,95 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "fastRefreshReducer", {
enumerable: true,
get: function() {
return fastRefreshReducer;
}
});
const _fetchserverresponse = require("../fetch-server-response");
const _createhreffromurl = require("../create-href-from-url");
const _applyrouterstatepatchtotree = require("../apply-router-state-patch-to-tree");
const _isnavigatingtonewrootlayout = require("../is-navigating-to-new-root-layout");
const _navigatereducer = require("./navigate-reducer");
const _handlemutable = require("../handle-mutable");
const _applyflightdata = require("../apply-flight-data");
const _approuter = require("../../app-router");
const _handlesegmentmismatch = require("../handle-segment-mismatch");
const _hasinterceptionrouteincurrenttree = require("./has-interception-route-in-current-tree");
// A version of refresh reducer that keeps the cache around instead of wiping all of it.
function fastRefreshReducerImpl(state, action) {
const { origin } = action;
const mutable = {};
const href = state.canonicalUrl;
mutable.preserveCustomHistoryState = false;
const cache = (0, _approuter.createEmptyCacheNode)();
// If the current tree was intercepted, the nextUrl should be included in the request.
// This is to ensure that the refresh request doesn't get intercepted, accidentally triggering the interception route.
const includeNextUrl = (0, _hasinterceptionrouteincurrenttree.hasInterceptionRouteInCurrentTree)(state.tree);
// TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree.
cache.lazyData = (0, _fetchserverresponse.fetchServerResponse)(new URL(href, origin), [
state.tree[0],
state.tree[1],
state.tree[2],
"refetch"
], includeNextUrl ? state.nextUrl : null, state.buildId);
return cache.lazyData.then((param)=>{
let [flightData, canonicalUrlOverride] = param;
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === "string") {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, flightData, state.pushRef.pendingPush);
}
// Remove cache.lazyData as it has been resolved at this point.
cache.lazyData = null;
let currentTree = state.tree;
let currentCache = state.cache;
for (const flightDataPath of flightData){
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log("REFRESH FAILED");
return state;
}
// Given the path can only have two items the items are only the router state and rsc for the root.
const [treePatch] = flightDataPath;
const newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
[
""
], currentTree, treePatch, state.canonicalUrl);
if (newTree === null) {
return (0, _handlesegmentmismatch.handleSegmentMismatch)(state, action, treePatch);
}
if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, href, state.pushRef.pendingPush);
}
const canonicalUrlOverrideHref = canonicalUrlOverride ? (0, _createhreffromurl.createHrefFromUrl)(canonicalUrlOverride) : undefined;
if (canonicalUrlOverride) {
mutable.canonicalUrl = canonicalUrlOverrideHref;
}
const applied = (0, _applyflightdata.applyFlightData)(currentCache, cache, flightDataPath);
if (applied) {
mutable.cache = cache;
currentCache = cache;
}
mutable.patchedTree = newTree;
mutable.canonicalUrl = href;
currentTree = newTree;
}
return (0, _handlemutable.handleMutable)(state, mutable);
}, ()=>state);
}
function fastRefreshReducerNoop(state, _action) {
return state;
}
const fastRefreshReducer = process.env.NODE_ENV === "production" ? fastRefreshReducerNoop : fastRefreshReducerImpl;
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=fast-refresh-reducer.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/fast-refresh-reducer.ts"],"names":["fastRefreshReducer","fastRefreshReducerImpl","state","action","origin","mutable","href","canonicalUrl","preserveCustomHistoryState","cache","createEmptyCacheNode","includeNextUrl","hasInterceptionRouteInCurrentTree","tree","lazyData","fetchServerResponse","URL","nextUrl","buildId","then","flightData","canonicalUrlOverride","handleExternalUrl","pushRef","pendingPush","currentTree","currentCache","flightDataPath","length","console","log","treePatch","newTree","applyRouterStatePatchToTree","handleSegmentMismatch","isNavigatingToNewRootLayout","canonicalUrlOverrideHref","createHrefFromUrl","undefined","applied","applyFlightData","patchedTree","handleMutable","fastRefreshReducerNoop","_action","process","env","NODE_ENV"],"mappings":";;;;+BA4HaA;;;eAAAA;;;qCA5HuB;mCACF;6CACU;6CACA;iCAOV;+BACJ;iCACE;2BAEK;uCACC;mDACY;AAElD,wFAAwF;AACxF,SAASC,uBACPC,KAA2B,EAC3BC,MAAyB;IAEzB,MAAM,EAAEC,MAAM,EAAE,GAAGD;IACnB,MAAME,UAAmB,CAAC;IAC1B,MAAMC,OAAOJ,MAAMK,YAAY;IAE/BF,QAAQG,0BAA0B,GAAG;IAErC,MAAMC,QAAmBC,IAAAA,+BAAoB;IAC7C,sFAAsF;IACtF,sHAAsH;IACtH,MAAMC,iBAAiBC,IAAAA,oEAAiC,EAACV,MAAMW,IAAI;IAEnE,uDAAuD;IACvD,wCAAwC;IACxCJ,MAAMK,QAAQ,GAAGC,IAAAA,wCAAmB,EAClC,IAAIC,IAAIV,MAAMF,SACd;QAACF,MAAMW,IAAI,CAAC,EAAE;QAAEX,MAAMW,IAAI,CAAC,EAAE;QAAEX,MAAMW,IAAI,CAAC,EAAE;QAAE;KAAU,EACxDF,iBAAiBT,MAAMe,OAAO,GAAG,MACjCf,MAAMgB,OAAO;IAGf,OA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C9B,GACA,IAAMH;AAEV;AAEA,SAASyC,uBACPzC,KAA2B,EAC3B0C,OAA0B;IAE1B,OAAO1C;AACT;AAEO,MAAMF,qBACX6C,QAAQC,GAAG,CAACC,QAAQ,KAAK,eACrBJ,yBACA1C"}

View File

@ -0,0 +1,3 @@
import type { FlightRouterState } from '../../../../server/app-render/types';
import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime';
export declare function findHeadInCache(cache: CacheNode, parallelRoutes: FlightRouterState[1]): [CacheNode, string] | null;

View File

@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "findHeadInCache", {
enumerable: true,
get: function() {
return findHeadInCache;
}
});
const _createroutercachekey = require("../create-router-cache-key");
function findHeadInCache(cache, parallelRoutes) {
return findHeadInCacheImpl(cache, parallelRoutes, "");
}
function findHeadInCacheImpl(cache, parallelRoutes, keyPrefix) {
const isLastItem = Object.keys(parallelRoutes).length === 0;
if (isLastItem) {
// Returns the entire Cache Node of the segment whose head we will render.
return [
cache,
keyPrefix
];
}
for(const key in parallelRoutes){
const [segment, childParallelRoutes] = parallelRoutes[key];
const childSegmentMap = cache.parallelRoutes.get(key);
if (!childSegmentMap) {
continue;
}
const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segment);
const cacheNode = childSegmentMap.get(cacheKey);
if (!cacheNode) {
continue;
}
const item = findHeadInCacheImpl(cacheNode, childParallelRoutes, keyPrefix + "/" + cacheKey);
if (item) {
return item;
}
}
return null;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=find-head-in-cache.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/find-head-in-cache.ts"],"names":["findHeadInCache","cache","parallelRoutes","findHeadInCacheImpl","keyPrefix","isLastItem","Object","keys","length","key","segment","childParallelRoutes","childSegmentMap","get","cacheKey","createRouterCacheKey","cacheNode","item"],"mappings":";;;;+BAIgBA;;;eAAAA;;;sCAFqB;AAE9B,SAASA,gBACdC,KAAgB,EAChBC,cAAoC;IAEpC,OAAOC,oBAAoBF,OAAOC,gBAAgB;AACpD;AAEA,SAASC,oBACPF,KAAgB,EAChBC,cAAoC,EACpCE,SAAiB;IAEjB,MAAMC,aAAaC,OAAOC,IAAI,CAACL,gBAAgBM,MAAM,KAAK;IAC1D,IAAIH,YAAY;QACd,0EAA0E;QAC1E,OAAO;YAACJ;YAAOG;SAAU;IAC3B;IACA,IAAK,MAAMK,OAAOP,eAAgB;QAChC,MAAM,CAACQ,SAASC,oBAAoB,GAAGT,cAAc,CAACO,IAAI;QAC1D,MAAMG,kBAAkBX,MAAMC,cAAc,CAACW,GAAG,CAACJ;QACjD,IAAI,CAACG,iBAAiB;YACpB;QACF;QAEA,MAAME,WAAWC,IAAAA,0CAAoB,EAACL;QAEtC,MAAMM,YAAYJ,gBAAgBC,GAAG,CAACC;QACtC,IAAI,CAACE,WAAW;YACd;QACF;QAEA,MAAMC,OAAOd,oBACXa,WACAL,qBACAP,YAAY,MAAMU;QAEpB,IAAIG,MAAM;YACR,OAAOA;QACT;IACF;IAEA,OAAO;AACT"}

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,2 @@
import type { Segment } from '../../../../server/app-render/types';
export declare function getSegmentValue(segment: Segment): string;

View File

@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getSegmentValue", {
enumerable: true,
get: function() {
return getSegmentValue;
}
});
function getSegmentValue(segment) {
return Array.isArray(segment) ? segment[1] : segment;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=get-segment-value.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/get-segment-value.ts"],"names":["getSegmentValue","segment","Array","isArray"],"mappings":";;;;+BAEgBA;;;eAAAA;;;AAAT,SAASA,gBAAgBC,OAAgB;IAC9C,OAAOC,MAAMC,OAAO,CAACF,WAAWA,OAAO,CAAC,EAAE,GAAGA;AAC/C"}

View File

@ -0,0 +1,2 @@
import type { FlightRouterState } from '../../../../server/app-render/types';
export declare function hasInterceptionRouteInCurrentTree([segment, parallelRoutes,]: FlightRouterState): boolean;

View File

@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "hasInterceptionRouteInCurrentTree", {
enumerable: true,
get: function() {
return hasInterceptionRouteInCurrentTree;
}
});
const _interceptionroutes = require("../../../../server/future/helpers/interception-routes");
function hasInterceptionRouteInCurrentTree(param) {
let [segment, parallelRoutes] = param;
// If we have a dynamic segment, it's marked as an interception route by the presence of the `i` suffix.
if (Array.isArray(segment) && (segment[2] === "di" || segment[2] === "ci")) {
return true;
}
// If segment is not an array, apply the existing string-based check
if (typeof segment === "string" && (0, _interceptionroutes.isInterceptionRouteAppPath)(segment)) {
return true;
}
// Iterate through parallelRoutes if they exist
if (parallelRoutes) {
for(const key in parallelRoutes){
if (hasInterceptionRouteInCurrentTree(parallelRoutes[key])) {
return true;
}
}
}
return false;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=has-interception-route-in-current-tree.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/has-interception-route-in-current-tree.ts"],"names":["hasInterceptionRouteInCurrentTree","segment","parallelRoutes","Array","isArray","isInterceptionRouteAppPath","key"],"mappings":";;;;+BAGgBA;;;eAAAA;;;oCAF2B;AAEpC,SAASA,kCAAkC,KAG9B;IAH8B,IAAA,CAChDC,SACAC,eACkB,GAH8B;IAIhD,wGAAwG;IACxG,IAAIC,MAAMC,OAAO,CAACH,YAAaA,CAAAA,OAAO,CAAC,EAAE,KAAK,QAAQA,OAAO,CAAC,EAAE,KAAK,IAAG,GAAI;QAC1E,OAAO;IACT;IAEA,oEAAoE;IACpE,IAAI,OAAOA,YAAY,YAAYI,IAAAA,8CAA0B,EAACJ,UAAU;QACtE,OAAO;IACT;IAEA,+CAA+C;IAC/C,IAAIC,gBAAgB;QAClB,IAAK,MAAMI,OAAOJ,eAAgB;YAChC,IAAIF,kCAAkCE,cAAc,CAACI,IAAI,GAAG;gBAC1D,OAAO;YACT;QACF;IACF;IAEA,OAAO;AACT"}

View File

@ -0,0 +1,5 @@
import { type Mutable, type NavigateAction, type ReadonlyReducerState, type ReducerState } from '../router-reducer-types';
export declare function handleExternalUrl(state: ReadonlyReducerState, mutable: Mutable, url: string, pendingPush: boolean): ReducerState;
export declare const navigateReducer: typeof navigateReducer_PPR;
declare function navigateReducer_PPR(state: ReadonlyReducerState, action: NavigateAction): ReducerState;
export {};

View File

@ -0,0 +1,390 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
handleExternalUrl: null,
navigateReducer: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
handleExternalUrl: function() {
return handleExternalUrl;
},
navigateReducer: function() {
return navigateReducer;
}
});
const _fetchserverresponse = require("../fetch-server-response");
const _createhreffromurl = require("../create-href-from-url");
const _invalidatecachebelowflightsegmentpath = require("../invalidate-cache-below-flight-segmentpath");
const _applyrouterstatepatchtotree = require("../apply-router-state-patch-to-tree");
const _shouldhardnavigate = require("../should-hard-navigate");
const _isnavigatingtonewrootlayout = require("../is-navigating-to-new-root-layout");
const _routerreducertypes = require("../router-reducer-types");
const _handlemutable = require("../handle-mutable");
const _applyflightdata = require("../apply-flight-data");
const _prefetchreducer = require("./prefetch-reducer");
const _approuter = require("../../app-router");
const _segment = require("../../../../shared/lib/segment");
const _pprnavigations = require("../ppr-navigations");
const _prefetchcacheutils = require("../prefetch-cache-utils");
const _clearcachenodedataforsegmentpath = require("../clear-cache-node-data-for-segment-path");
function handleExternalUrl(state, mutable, url, pendingPush) {
mutable.mpaNavigation = true;
mutable.canonicalUrl = url;
mutable.pendingPush = pendingPush;
mutable.scrollableSegments = undefined;
return (0, _handlemutable.handleMutable)(state, mutable);
}
function generateSegmentsFromPatch(flightRouterPatch) {
const segments = [];
const [segment, parallelRoutes] = flightRouterPatch;
if (Object.keys(parallelRoutes).length === 0) {
return [
[
segment
]
];
}
for (const [parallelRouteKey, parallelRoute] of Object.entries(parallelRoutes)){
for (const childSegment of generateSegmentsFromPatch(parallelRoute)){
// If the segment is empty, it means we are at the root of the tree
if (segment === "") {
segments.push([
parallelRouteKey,
...childSegment
]);
} else {
segments.push([
segment,
parallelRouteKey,
...childSegment
]);
}
}
}
return segments;
}
function triggerLazyFetchForLeafSegments(newCache, currentCache, flightSegmentPath, treePatch) {
let appliedPatch = false;
newCache.rsc = currentCache.rsc;
newCache.prefetchRsc = currentCache.prefetchRsc;
newCache.loading = currentCache.loading;
newCache.parallelRoutes = new Map(currentCache.parallelRoutes);
const segmentPathsToFill = generateSegmentsFromPatch(treePatch).map((segment)=>[
...flightSegmentPath,
...segment
]);
for (const segmentPaths of segmentPathsToFill){
(0, _clearcachenodedataforsegmentpath.clearCacheNodeDataForSegmentPath)(newCache, currentCache, segmentPaths);
appliedPatch = true;
}
return appliedPatch;
}
const navigateReducer = process.env.__NEXT_PPR ? navigateReducer_PPR : navigateReducer_noPPR;
// This is the implementation when PPR is disabled. We can assume its behavior
// is relatively stable because it's been running in production for a while.
function navigateReducer_noPPR(state, action) {
const { url, isExternalUrl, navigateType, shouldScroll } = action;
const mutable = {};
const { hash } = url;
const href = (0, _createhreffromurl.createHrefFromUrl)(url);
const pendingPush = navigateType === "push";
// we want to prune the prefetch cache on every navigation to avoid it growing too large
(0, _prefetchcacheutils.prunePrefetchCache)(state.prefetchCache);
mutable.preserveCustomHistoryState = false;
if (isExternalUrl) {
return handleExternalUrl(state, mutable, url.toString(), pendingPush);
}
const prefetchValues = (0, _prefetchcacheutils.getOrCreatePrefetchCacheEntry)({
url,
nextUrl: state.nextUrl,
tree: state.tree,
buildId: state.buildId,
prefetchCache: state.prefetchCache
});
const { treeAtTimeOfPrefetch, data } = prefetchValues;
_prefetchreducer.prefetchQueue.bump(data);
return data.then((param)=>{
let [flightData, canonicalUrlOverride] = param;
let isFirstRead = false;
// we only want to mark this once
if (!prefetchValues.lastUsedTime) {
// important: we should only mark the cache node as dirty after we unsuspend from the call above
prefetchValues.lastUsedTime = Date.now();
isFirstRead = true;
}
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === "string") {
return handleExternalUrl(state, mutable, flightData, pendingPush);
}
// Handles case where `<meta http-equiv="refresh">` tag is present,
// which will trigger an MPA navigation.
if (document.getElementById("__next-page-redirect")) {
return handleExternalUrl(state, mutable, href, pendingPush);
}
let currentTree = state.tree;
let currentCache = state.cache;
let scrollableSegments = [];
for (const flightDataPath of flightData){
const flightSegmentPath = flightDataPath.slice(0, -4);
// The one before last item is the router state tree patch
const treePatch = flightDataPath.slice(-3)[0];
// TODO-APP: remove ''
const flightSegmentPathWithLeadingEmpty = [
"",
...flightSegmentPath
];
// Create new tree based on the flightSegmentPath and router state patch
let newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, currentTree, treePatch, href);
// If the tree patch can't be applied to the current tree then we use the tree at time of prefetch
// TODO-APP: This should instead fill in the missing pieces in `currentTree` with the data from `treeAtTimeOfPrefetch`, then apply the patch.
if (newTree === null) {
newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, treeAtTimeOfPrefetch, treePatch, href);
}
if (newTree !== null) {
if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush);
}
const cache = (0, _approuter.createEmptyCacheNode)();
let applied = false;
if (prefetchValues.status === _routerreducertypes.PrefetchCacheEntryStatus.stale && !isFirstRead) {
// When we have a stale prefetch entry, we only want to re-use the loading state of the route we're navigating to, to support instant loading navigations
// this will trigger a lazy fetch for the actual page data by nulling the `rsc` and `prefetchRsc` values for page data,
// while copying over the `loading` for the segment that contains the page data.
// We only do this on subsequent reads, as otherwise there'd be no loading data to re-use.
applied = triggerLazyFetchForLeafSegments(cache, currentCache, flightSegmentPath, treePatch);
// since we re-used the stale cache's loading state & refreshed the data,
// update the `lastUsedTime` so that it can continue to be re-used for the next 30s
prefetchValues.lastUsedTime = Date.now();
} else {
applied = (0, _applyflightdata.applyFlightData)(currentCache, cache, flightDataPath, prefetchValues);
}
const hardNavigate = (0, _shouldhardnavigate.shouldHardNavigate)(// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, currentTree);
if (hardNavigate) {
// Copy rsc for the root node of the cache.
cache.rsc = currentCache.rsc;
cache.prefetchRsc = currentCache.prefetchRsc;
(0, _invalidatecachebelowflightsegmentpath.invalidateCacheBelowFlightSegmentPath)(cache, currentCache, flightSegmentPath);
// Ensure the existing cache value is used when the cache was not invalidated.
mutable.cache = cache;
} else if (applied) {
mutable.cache = cache;
// If we applied the cache, we update the "current cache" value so any other
// segments in the FlightDataPath will be able to reference the updated cache.
currentCache = cache;
}
currentTree = newTree;
for (const subSegment of generateSegmentsFromPatch(treePatch)){
const scrollableSegmentPath = [
...flightSegmentPath,
...subSegment
];
// Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case.
if (scrollableSegmentPath[scrollableSegmentPath.length - 1] !== _segment.DEFAULT_SEGMENT_KEY) {
scrollableSegments.push(scrollableSegmentPath);
}
}
}
}
mutable.patchedTree = currentTree;
mutable.canonicalUrl = canonicalUrlOverride ? (0, _createhreffromurl.createHrefFromUrl)(canonicalUrlOverride) : href;
mutable.pendingPush = pendingPush;
mutable.scrollableSegments = scrollableSegments;
mutable.hashFragment = hash;
mutable.shouldScroll = shouldScroll;
return (0, _handlemutable.handleMutable)(state, mutable);
}, ()=>state);
}
// This is the experimental PPR implementation. It's closer to the behavior we
// want, but is likelier to include accidental regressions because it rewrites
// existing functionality.
function navigateReducer_PPR(state, action) {
const { url, isExternalUrl, navigateType, shouldScroll } = action;
const mutable = {};
const { hash } = url;
const href = (0, _createhreffromurl.createHrefFromUrl)(url);
const pendingPush = navigateType === "push";
// we want to prune the prefetch cache on every navigation to avoid it growing too large
(0, _prefetchcacheutils.prunePrefetchCache)(state.prefetchCache);
mutable.preserveCustomHistoryState = false;
if (isExternalUrl) {
return handleExternalUrl(state, mutable, url.toString(), pendingPush);
}
const prefetchValues = (0, _prefetchcacheutils.getOrCreatePrefetchCacheEntry)({
url,
nextUrl: state.nextUrl,
tree: state.tree,
buildId: state.buildId,
prefetchCache: state.prefetchCache
});
const { treeAtTimeOfPrefetch, data } = prefetchValues;
_prefetchreducer.prefetchQueue.bump(data);
return data.then((param)=>{
let [flightData, canonicalUrlOverride, _postponed] = param;
let isFirstRead = false;
// we only want to mark this once
if (!prefetchValues.lastUsedTime) {
// important: we should only mark the cache node as dirty after we unsuspend from the call above
prefetchValues.lastUsedTime = Date.now();
isFirstRead = true;
}
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === "string") {
return handleExternalUrl(state, mutable, flightData, pendingPush);
}
// Handles case where `<meta http-equiv="refresh">` tag is present,
// which will trigger an MPA navigation.
if (document.getElementById("__next-page-redirect")) {
return handleExternalUrl(state, mutable, href, pendingPush);
}
let currentTree = state.tree;
let currentCache = state.cache;
let scrollableSegments = [];
// TODO: In practice, this is always a single item array. We probably
// aren't going to every send multiple segments, at least not in this
// format. So we could remove the extra wrapper for now until
// that settles.
for (const flightDataPath of flightData){
const flightSegmentPath = flightDataPath.slice(0, -4);
// The one before last item is the router state tree patch
const treePatch = flightDataPath.slice(-3)[0];
// TODO-APP: remove ''
const flightSegmentPathWithLeadingEmpty = [
"",
...flightSegmentPath
];
// Create new tree based on the flightSegmentPath and router state patch
let newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, currentTree, treePatch, href);
// If the tree patch can't be applied to the current tree then we use the tree at time of prefetch
// TODO-APP: This should instead fill in the missing pieces in `currentTree` with the data from `treeAtTimeOfPrefetch`, then apply the patch.
if (newTree === null) {
newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, treeAtTimeOfPrefetch, treePatch, href);
}
if (newTree !== null) {
if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush);
}
if (// This is just a paranoid check. When PPR is enabled, the server
// will always send back a static response that's rendered from
// the root. If for some reason it doesn't, we fall back to the
// non-PPR implementation.
// TODO: We should get rid of the else branch and do all navigations
// via updateCacheNodeOnNavigation. The current structure is just
// an incremental step.
flightDataPath.length === 3) {
const prefetchedTree = flightDataPath[0];
const seedData = flightDataPath[1];
const head = flightDataPath[2];
const task = (0, _pprnavigations.updateCacheNodeOnNavigation)(currentCache, currentTree, prefetchedTree, seedData, head);
if (task !== null && task.node !== null) {
// We've created a new Cache Node tree that contains a prefetched
// version of the next page. This can be rendered instantly.
// Use the tree computed by updateCacheNodeOnNavigation instead
// of the one computed by applyRouterStatePatchToTree.
// TODO: We should remove applyRouterStatePatchToTree
// from the PPR path entirely.
const patchedRouterState = task.route;
newTree = patchedRouterState;
const newCache = task.node;
// The prefetched tree has dynamic holes in it. We initiate a
// dynamic request to fill them in.
//
// Do not block on the result. We'll immediately render the Cache
// Node tree and suspend on the dynamic parts. When the request
// comes in, we'll fill in missing data and ping React to
// re-render. Unlike the lazy fetching model in the non-PPR
// implementation, this is modeled as a single React update +
// streaming, rather than multiple top-level updates. (However,
// even in the new model, we'll still need to sometimes update the
// root multiple times per navigation, like if the server sends us
// a different response than we expected. For now, we revert back
// to the lazy fetching mechanism in that case.)
(0, _pprnavigations.listenForDynamicRequest)(task, (0, _fetchserverresponse.fetchServerResponse)(url, currentTree, state.nextUrl, state.buildId));
mutable.cache = newCache;
} else {
// Nothing changed, so reuse the old cache.
// TODO: What if the head changed but not any of the segment data?
// Is that possible? If so, we should clone the whole tree and
// update the head.
newTree = prefetchedTree;
}
} else {
// The static response does not include any dynamic holes, so
// there's no need to do a second request.
// TODO: As an incremental step this just reverts back to the
// non-PPR implementation. We can simplify this branch further,
// given that PPR prefetches are always static and return the whole
// tree. Or in the meantime we could factor it out into a
// separate function.
const cache = (0, _approuter.createEmptyCacheNode)();
let applied = false;
if (prefetchValues.status === _routerreducertypes.PrefetchCacheEntryStatus.stale && !isFirstRead) {
// When we have a stale prefetch entry, we only want to re-use the loading state of the route we're navigating to, to support instant loading navigations
// this will trigger a lazy fetch for the actual page data by nulling the `rsc` and `prefetchRsc` values for page data,
// while copying over the `loading` for the segment that contains the page data.
// We only do this on subsequent reads, as otherwise there'd be no loading data to re-use.
applied = triggerLazyFetchForLeafSegments(cache, currentCache, flightSegmentPath, treePatch);
// since we re-used the stale cache's loading state & refreshed the data,
// update the `lastUsedTime` so that it can continue to be re-used for the next 30s
prefetchValues.lastUsedTime = Date.now();
} else {
applied = (0, _applyflightdata.applyFlightData)(currentCache, cache, flightDataPath, prefetchValues);
}
const hardNavigate = (0, _shouldhardnavigate.shouldHardNavigate)(// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, currentTree);
if (hardNavigate) {
// Copy rsc for the root node of the cache.
cache.rsc = currentCache.rsc;
cache.prefetchRsc = currentCache.prefetchRsc;
(0, _invalidatecachebelowflightsegmentpath.invalidateCacheBelowFlightSegmentPath)(cache, currentCache, flightSegmentPath);
// Ensure the existing cache value is used when the cache was not invalidated.
mutable.cache = cache;
} else if (applied) {
mutable.cache = cache;
// If we applied the cache, we update the "current cache" value so any other
// segments in the FlightDataPath will be able to reference the updated cache.
currentCache = cache;
}
}
currentTree = newTree;
for (const subSegment of generateSegmentsFromPatch(treePatch)){
const scrollableSegmentPath = [
...flightSegmentPath,
...subSegment
];
// Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case.
if (scrollableSegmentPath[scrollableSegmentPath.length - 1] !== _segment.DEFAULT_SEGMENT_KEY) {
scrollableSegments.push(scrollableSegmentPath);
}
}
}
}
mutable.patchedTree = currentTree;
mutable.canonicalUrl = canonicalUrlOverride ? (0, _createhreffromurl.createHrefFromUrl)(canonicalUrlOverride) : href;
mutable.pendingPush = pendingPush;
mutable.scrollableSegments = scrollableSegments;
mutable.hashFragment = hash;
mutable.shouldScroll = shouldScroll;
return (0, _handlemutable.handleMutable)(state, mutable);
}, ()=>state);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=navigate-reducer.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,4 @@
import type { PrefetchAction, ReducerState, ReadonlyReducerState } from '../router-reducer-types';
import { PromiseQueue } from '../../promise-queue';
export declare const prefetchQueue: PromiseQueue;
export declare function prefetchReducer(state: ReadonlyReducerState, action: PrefetchAction): ReducerState;

View File

@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
prefetchQueue: null,
prefetchReducer: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
prefetchQueue: function() {
return prefetchQueue;
},
prefetchReducer: function() {
return prefetchReducer;
}
});
const _approuterheaders = require("../../app-router-headers");
const _promisequeue = require("../../promise-queue");
const _prefetchcacheutils = require("../prefetch-cache-utils");
const prefetchQueue = new _promisequeue.PromiseQueue(5);
function prefetchReducer(state, action) {
// let's prune the prefetch cache before we do anything else
(0, _prefetchcacheutils.prunePrefetchCache)(state.prefetchCache);
const { url } = action;
url.searchParams.delete(_approuterheaders.NEXT_RSC_UNION_QUERY);
(0, _prefetchcacheutils.getOrCreatePrefetchCacheEntry)({
url,
nextUrl: state.nextUrl,
prefetchCache: state.prefetchCache,
kind: action.kind,
tree: state.tree,
buildId: state.buildId
});
return state;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=prefetch-reducer.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/prefetch-reducer.ts"],"names":["prefetchQueue","prefetchReducer","PromiseQueue","state","action","prunePrefetchCache","prefetchCache","url","searchParams","delete","NEXT_RSC_UNION_QUERY","getOrCreatePrefetchCacheEntry","nextUrl","kind","tree","buildId"],"mappings":";;;;;;;;;;;;;;;IAYaA,aAAa;eAAbA;;IAEGC,eAAe;eAAfA;;;kCATqB;8BACR;oCAItB;AAEA,MAAMD,gBAAgB,IAAIE,0BAAY,CAAC;AAEvC,SAASD,gBACdE,KAA2B,EAC3BC,MAAsB;IAEtB,4DAA4D;IAC5DC,IAAAA,sCAAkB,EAACF,MAAMG,aAAa;IAEtC,MAAM,EAAEC,GAAG,EAAE,GAAGH;IAChBG,IAAIC,YAAY,CAACC,MAAM,CAACC,sCAAoB;IAE5CC,IAAAA,iDAA6B,EAAC;QAC5BJ;QACAK,SAAST,MAAMS,OAAO;QACtBN,eAAeH,MAAMG,aAAa;QAClCO,MAAMT,OAAOS,IAAI;QACjBC,MAAMX,MAAMW,IAAI;QAChBC,SAASZ,MAAMY,OAAO;IACxB;IAEA,OAAOZ;AACT"}

View File

@ -0,0 +1,2 @@
import type { ReadonlyReducerState, ReducerState, RefreshAction } from '../router-reducer-types';
export declare function refreshReducer(state: ReadonlyReducerState, action: RefreshAction): ReducerState;

View File

@ -0,0 +1,104 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "refreshReducer", {
enumerable: true,
get: function() {
return refreshReducer;
}
});
const _fetchserverresponse = require("../fetch-server-response");
const _createhreffromurl = require("../create-href-from-url");
const _applyrouterstatepatchtotree = require("../apply-router-state-patch-to-tree");
const _isnavigatingtonewrootlayout = require("../is-navigating-to-new-root-layout");
const _navigatereducer = require("./navigate-reducer");
const _handlemutable = require("../handle-mutable");
const _filllazyitemstillleafwithhead = require("../fill-lazy-items-till-leaf-with-head");
const _approuter = require("../../app-router");
const _handlesegmentmismatch = require("../handle-segment-mismatch");
const _hasinterceptionrouteincurrenttree = require("./has-interception-route-in-current-tree");
const _refetchinactiveparallelsegments = require("../refetch-inactive-parallel-segments");
function refreshReducer(state, action) {
const { origin } = action;
const mutable = {};
const href = state.canonicalUrl;
let currentTree = state.tree;
mutable.preserveCustomHistoryState = false;
const cache = (0, _approuter.createEmptyCacheNode)();
// If the current tree was intercepted, the nextUrl should be included in the request.
// This is to ensure that the refresh request doesn't get intercepted, accidentally triggering the interception route.
const includeNextUrl = (0, _hasinterceptionrouteincurrenttree.hasInterceptionRouteInCurrentTree)(state.tree);
// TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree.
cache.lazyData = (0, _fetchserverresponse.fetchServerResponse)(new URL(href, origin), [
currentTree[0],
currentTree[1],
currentTree[2],
"refetch"
], includeNextUrl ? state.nextUrl : null, state.buildId);
return cache.lazyData.then(async (param)=>{
let [flightData, canonicalUrlOverride] = param;
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === "string") {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, flightData, state.pushRef.pendingPush);
}
// Remove cache.lazyData as it has been resolved at this point.
cache.lazyData = null;
for (const flightDataPath of flightData){
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log("REFRESH FAILED");
return state;
}
// Given the path can only have two items the items are only the router state and rsc for the root.
const [treePatch] = flightDataPath;
const newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
[
""
], currentTree, treePatch, state.canonicalUrl);
if (newTree === null) {
return (0, _handlesegmentmismatch.handleSegmentMismatch)(state, action, treePatch);
}
if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, href, state.pushRef.pendingPush);
}
const canonicalUrlOverrideHref = canonicalUrlOverride ? (0, _createhreffromurl.createHrefFromUrl)(canonicalUrlOverride) : undefined;
if (canonicalUrlOverride) {
mutable.canonicalUrl = canonicalUrlOverrideHref;
}
// The one before last item is the router state tree patch
const [cacheNodeSeedData, head] = flightDataPath.slice(-2);
// Handles case where prefetch only returns the router tree patch without rendered components.
if (cacheNodeSeedData !== null) {
const rsc = cacheNodeSeedData[2];
cache.rsc = rsc;
cache.prefetchRsc = null;
(0, _filllazyitemstillleafwithhead.fillLazyItemsTillLeafWithHead)(cache, // Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined, treePatch, cacheNodeSeedData, head);
mutable.prefetchCache = new Map();
}
await (0, _refetchinactiveparallelsegments.refreshInactiveParallelSegments)({
state,
updatedTree: newTree,
updatedCache: cache,
includeNextUrl,
canonicalUrl: mutable.canonicalUrl || state.canonicalUrl
});
mutable.cache = cache;
mutable.patchedTree = newTree;
mutable.canonicalUrl = href;
currentTree = newTree;
}
return (0, _handlemutable.handleMutable)(state, mutable);
}, ()=>state);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=refresh-reducer.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/refresh-reducer.ts"],"names":["refreshReducer","state","action","origin","mutable","href","canonicalUrl","currentTree","tree","preserveCustomHistoryState","cache","createEmptyCacheNode","includeNextUrl","hasInterceptionRouteInCurrentTree","lazyData","fetchServerResponse","URL","nextUrl","buildId","then","flightData","canonicalUrlOverride","handleExternalUrl","pushRef","pendingPush","flightDataPath","length","console","log","treePatch","newTree","applyRouterStatePatchToTree","handleSegmentMismatch","isNavigatingToNewRootLayout","canonicalUrlOverrideHref","createHrefFromUrl","undefined","cacheNodeSeedData","head","slice","rsc","prefetchRsc","fillLazyItemsTillLeafWithHead","prefetchCache","Map","refreshInactiveParallelSegments","updatedTree","updatedCache","patchedTree","handleMutable"],"mappings":";;;;+BAmBgBA;;;eAAAA;;;qCAnBoB;mCACF;6CACU;6CACA;iCAOV;+BACJ;+CAEgB;2BACT;uCACC;mDACY;iDACF;AAEzC,SAASA,eACdC,KAA2B,EAC3BC,MAAqB;IAErB,MAAM,EAAEC,MAAM,EAAE,GAAGD;IACnB,MAAME,UAAmB,CAAC;IAC1B,MAAMC,OAAOJ,MAAMK,YAAY;IAE/B,IAAIC,cAAcN,MAAMO,IAAI;IAE5BJ,QAAQK,0BAA0B,GAAG;IAErC,MAAMC,QAAmBC,IAAAA,+BAAoB;IAE7C,sFAAsF;IACtF,sHAAsH;IACtH,MAAMC,iBAAiBC,IAAAA,oEAAiC,EAACZ,MAAMO,IAAI;IAEnE,uDAAuD;IACvD,wCAAwC;IACxCE,MAAMI,QAAQ,GAAGC,IAAAA,wCAAmB,EAClC,IAAIC,IAAIX,MAAMF,SACd;QAACI,WAAW,CAAC,EAAE;QAAEA,WAAW,CAAC,EAAE;QAAEA,WAAW,CAAC,EAAE;QAAE;KAAU,EAC3DK,iBAAiBX,MAAMgB,OAAO,GAAG,MACjChB,MAAMiB,OAAO;IAGf,OAAOR,MAAMI,QAAQ,CAACK,IAAI,CACxB;YAAO,CAACC,YAAYC,qB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,EAAC;gBACpC5C;gBACA6C,aAAahB;gBACbiB,cAAcrC;gBACdE;gBACAN,cAAcF,QAAQE,YAAY,IAAIL,MAAMK,YAAY;YAC1D;YAEAF,QAAQM,KAAK,GAAGA;YAChBN,QAAQ4C,WAAW,GAAGlB;YACtB1B,QAAQE,YAAY,GAAGD;YAEvBE,cAAcuB;QAChB;QAEA,OAAOmB,IAAAA,4BAAa,EAAChD,OAAOG;IAC9B,GACA,IAAMH;AAEV"}

View File

@ -0,0 +1,2 @@
import type { ReadonlyReducerState, ReducerState, RestoreAction } from '../router-reducer-types';
export declare function restoreReducer(state: ReadonlyReducerState, action: RestoreAction): ReducerState;

View File

@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "restoreReducer", {
enumerable: true,
get: function() {
return restoreReducer;
}
});
const _createhreffromurl = require("../create-href-from-url");
const _computechangedpath = require("../compute-changed-path");
const _pprnavigations = require("../ppr-navigations");
function restoreReducer(state, action) {
const { url, tree } = action;
const href = (0, _createhreffromurl.createHrefFromUrl)(url);
// This action is used to restore the router state from the history state.
// However, it's possible that the history state no longer contains the `FlightRouterState`.
// We will copy over the internal state on pushState/replaceState events, but if a history entry
// occurred before hydration, or if the user navigated to a hash using a regular anchor link,
// the history state will not contain the `FlightRouterState`.
// In this case, we'll continue to use the existing tree so the router doesn't get into an invalid state.
const treeToRestore = tree || state.tree;
const oldCache = state.cache;
const newCache = process.env.__NEXT_PPR ? // data for any segment whose dynamic data was already received. This
// prevents an unnecessary flash back to PPR state during a
// back/forward navigation.
(0, _pprnavigations.updateCacheNodeOnPopstateRestoration)(oldCache, treeToRestore) : oldCache;
var _extractPathFromFlightRouterState;
return {
buildId: state.buildId,
// Set canonical url
canonicalUrl: href,
pushRef: {
pendingPush: false,
mpaNavigation: false,
// Ensures that the custom history state that was set is preserved when applying this update.
preserveCustomHistoryState: true
},
focusAndScrollRef: state.focusAndScrollRef,
cache: newCache,
prefetchCache: state.prefetchCache,
// Restore provided tree
tree: treeToRestore,
nextUrl: (_extractPathFromFlightRouterState = (0, _computechangedpath.extractPathFromFlightRouterState)(treeToRestore)) != null ? _extractPathFromFlightRouterState : url.pathname
};
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=restore-reducer.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/restore-reducer.ts"],"names":["restoreReducer","state","action","url","tree","href","createHrefFromUrl","treeToRestore","oldCache","cache","newCache","process","env","__NEXT_PPR","updateCacheNodeOnPopstateRestoration","extractPathFromFlightRouterState","buildId","canonicalUrl","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","prefetchCache","nextUrl","pathname"],"mappings":";;;;+BASgBA;;;eAAAA;;;mCATkB;oCAMe;gCACI;AAE9C,SAASA,eACdC,KAA2B,EAC3BC,MAAqB;IAErB,MAAM,EAAEC,GAAG,EAAEC,IAAI,EAAE,GAAGF;IACtB,MAAMG,OAAOC,IAAAA,oCAAiB,EAACH;IAC/B,0EAA0E;IAC1E,4FAA4F;IAC5F,gGAAgG;IAChG,6FAA6F;IAC7F,8DAA8D;IAC9D,yGAAyG;IACzG,MAAMI,gBAAgBH,QAAQH,MAAMG,IAAI;IAExC,MAAMI,WAAWP,MAAMQ,KAAK;IAC5B,MAAMC,WAAWC,QAAQC,GAAG,CAACC,UAAU,GAEnC,qEAAqE;IACrE,2DAA2D;IAC3D,2BAA2B;IAC3BC,IAAAA,oDAAoC,EAACN,UAAUD,iBAC/CC;QAiBOO;IAfX,OAAO;QACLC,SAASf,MAAMe,OAAO;QACtB,oBAAoB;QACpBC,cAAcZ;QACda,SAAS;YACPC,aAAa;YACbC,eAAe;YACf,6FAA6F;YAC7FC,4BAA4B;QAC9B;QACAC,mBAAmBrB,MAAMqB,iBAAiB;QAC1Cb,OAAOC;QACPa,eAAetB,MAAMsB,aAAa;QAClC,wBAAwB;QACxBnB,MAAMG;QACNiB,SAAST,CAAAA,oCAAAA,IAAAA,oDAAgC,EAACR,0BAAjCQ,oCAAmDZ,IAAIsB,QAAQ;IAC1E;AACF"}

View File

@ -0,0 +1,2 @@
import type { ReadonlyReducerState, ReducerState, ServerActionAction } from '../router-reducer-types';
export declare function serverActionReducer(state: ReadonlyReducerState, action: ServerActionAction): ReducerState;

View File

@ -0,0 +1,188 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "serverActionReducer", {
enumerable: true,
get: function() {
return serverActionReducer;
}
});
const _appcallserver = require("../../../app-call-server");
const _approuterheaders = require("../../app-router-headers");
const _addbasepath = require("../../../add-base-path");
const _createhreffromurl = require("../create-href-from-url");
const _navigatereducer = require("./navigate-reducer");
const _applyrouterstatepatchtotree = require("../apply-router-state-patch-to-tree");
const _isnavigatingtonewrootlayout = require("../is-navigating-to-new-root-layout");
const _handlemutable = require("../handle-mutable");
const _filllazyitemstillleafwithhead = require("../fill-lazy-items-till-leaf-with-head");
const _approuter = require("../../app-router");
const _hasinterceptionrouteincurrenttree = require("./has-interception-route-in-current-tree");
const _handlesegmentmismatch = require("../handle-segment-mismatch");
const _refetchinactiveparallelsegments = require("../refetch-inactive-parallel-segments");
// // eslint-disable-next-line import/no-extraneous-dependencies
// import { createFromFetch } from 'react-server-dom-webpack/client'
// // eslint-disable-next-line import/no-extraneous-dependencies
// import { encodeReply } from 'react-server-dom-webpack/client'
const { createFromFetch, encodeReply } = !!process.env.NEXT_RUNTIME ? require("react-server-dom-webpack/client.edge") : require("react-server-dom-webpack/client");
async function fetchServerAction(state, nextUrl, param) {
let { actionId, actionArgs } = param;
const body = await encodeReply(actionArgs);
const res = await fetch("", {
method: "POST",
headers: {
Accept: _approuterheaders.RSC_CONTENT_TYPE_HEADER,
[_approuterheaders.ACTION]: actionId,
[_approuterheaders.NEXT_ROUTER_STATE_TREE]: encodeURIComponent(JSON.stringify(state.tree)),
...process.env.NEXT_DEPLOYMENT_ID ? {
"x-deployment-id": process.env.NEXT_DEPLOYMENT_ID
} : {},
...nextUrl ? {
[_approuterheaders.NEXT_URL]: nextUrl
} : {}
},
body
});
const location = res.headers.get("x-action-redirect");
let revalidatedParts;
try {
const revalidatedHeader = JSON.parse(res.headers.get("x-action-revalidated") || "[[],0,0]");
revalidatedParts = {
paths: revalidatedHeader[0] || [],
tag: !!revalidatedHeader[1],
cookie: revalidatedHeader[2]
};
} catch (e) {
revalidatedParts = {
paths: [],
tag: false,
cookie: false
};
}
const redirectLocation = location ? new URL((0, _addbasepath.addBasePath)(location), // Ensure relative redirects in Server Actions work, e.g. redirect('./somewhere-else')
new URL(state.canonicalUrl, window.location.href)) : undefined;
let isFlightResponse = res.headers.get("content-type") === _approuterheaders.RSC_CONTENT_TYPE_HEADER;
if (isFlightResponse) {
const response = await createFromFetch(Promise.resolve(res), {
callServer: _appcallserver.callServer
});
if (location) {
// if it was a redirection, then result is just a regular RSC payload
const [, actionFlightData] = response != null ? response : [];
return {
actionFlightData: actionFlightData,
redirectLocation,
revalidatedParts
};
}
// otherwise it's a tuple of [actionResult, actionFlightData]
const [actionResult, [, actionFlightData]] = response != null ? response : [];
return {
actionResult,
actionFlightData,
redirectLocation,
revalidatedParts
};
}
return {
redirectLocation,
revalidatedParts
};
}
function serverActionReducer(state, action) {
const { resolve, reject } = action;
const mutable = {};
const href = state.canonicalUrl;
let currentTree = state.tree;
mutable.preserveCustomHistoryState = false;
// only pass along the `nextUrl` param (used for interception routes) if the current route was intercepted.
// If the route has been intercepted, the action should be as well.
// Otherwise the server action might be intercepted with the wrong action id
// (ie, one that corresponds with the intercepted route)
const nextUrl = state.nextUrl && (0, _hasinterceptionrouteincurrenttree.hasInterceptionRouteInCurrentTree)(state.tree) ? state.nextUrl : null;
mutable.inFlightServerAction = fetchServerAction(state, nextUrl, action);
return mutable.inFlightServerAction.then(async (param)=>{
let { actionResult, actionFlightData: flightData, redirectLocation } = param;
// Make sure the redirection is a push instead of a replace.
// Issue: https://github.com/vercel/next.js/issues/53911
if (redirectLocation) {
state.pushRef.pendingPush = true;
mutable.pendingPush = true;
}
if (!flightData) {
resolve(actionResult);
// If there is a redirect but no flight data we need to do a mpaNavigation.
if (redirectLocation) {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, redirectLocation.href, state.pushRef.pendingPush);
}
return state;
}
if (typeof flightData === "string") {
// Handle case when navigating to page in `pages` from `app`
return (0, _navigatereducer.handleExternalUrl)(state, mutable, flightData, state.pushRef.pendingPush);
}
// Remove cache.data as it has been resolved at this point.
mutable.inFlightServerAction = null;
if (redirectLocation) {
const newHref = (0, _createhreffromurl.createHrefFromUrl)(redirectLocation, false);
mutable.canonicalUrl = newHref;
}
for (const flightDataPath of flightData){
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log("SERVER ACTION APPLY FAILED");
return state;
}
// Given the path can only have two items the items are only the router state and rsc for the root.
const [treePatch] = flightDataPath;
const newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
[
""
], currentTree, treePatch, redirectLocation ? (0, _createhreffromurl.createHrefFromUrl)(redirectLocation) : state.canonicalUrl);
if (newTree === null) {
return (0, _handlesegmentmismatch.handleSegmentMismatch)(state, action, treePatch);
}
if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, href, state.pushRef.pendingPush);
}
// The one before last item is the router state tree patch
const [cacheNodeSeedData, head] = flightDataPath.slice(-2);
const rsc = cacheNodeSeedData !== null ? cacheNodeSeedData[2] : null;
// Handles case where prefetch only returns the router tree patch without rendered components.
if (rsc !== null) {
const cache = (0, _approuter.createEmptyCacheNode)();
cache.rsc = rsc;
cache.prefetchRsc = null;
(0, _filllazyitemstillleafwithhead.fillLazyItemsTillLeafWithHead)(cache, // Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined, treePatch, cacheNodeSeedData, head);
await (0, _refetchinactiveparallelsegments.refreshInactiveParallelSegments)({
state,
updatedTree: newTree,
updatedCache: cache,
includeNextUrl: Boolean(nextUrl),
canonicalUrl: mutable.canonicalUrl || state.canonicalUrl
});
mutable.cache = cache;
mutable.prefetchCache = new Map();
}
mutable.patchedTree = newTree;
currentTree = newTree;
}
resolve(actionResult);
return (0, _handlemutable.handleMutable)(state, mutable);
}, (e)=>{
// When the server action is rejected we don't update the state and instead call the reject handler of the promise.
reject(e);
return state;
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=server-action-reducer.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,2 @@
import type { ServerPatchAction, ReducerState, ReadonlyReducerState } from '../router-reducer-types';
export declare function serverPatchReducer(state: ReadonlyReducerState, action: ServerPatchAction): ReducerState;

View File

@ -0,0 +1,65 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "serverPatchReducer", {
enumerable: true,
get: function() {
return serverPatchReducer;
}
});
const _createhreffromurl = require("../create-href-from-url");
const _applyrouterstatepatchtotree = require("../apply-router-state-patch-to-tree");
const _isnavigatingtonewrootlayout = require("../is-navigating-to-new-root-layout");
const _navigatereducer = require("./navigate-reducer");
const _applyflightdata = require("../apply-flight-data");
const _handlemutable = require("../handle-mutable");
const _approuter = require("../../app-router");
const _handlesegmentmismatch = require("../handle-segment-mismatch");
function serverPatchReducer(state, action) {
const { serverResponse } = action;
const [flightData, overrideCanonicalUrl] = serverResponse;
const mutable = {};
mutable.preserveCustomHistoryState = false;
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === "string") {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, flightData, state.pushRef.pendingPush);
}
let currentTree = state.tree;
let currentCache = state.cache;
for (const flightDataPath of flightData){
// Slices off the last segment (which is at -4) as it doesn't exist in the tree yet
const flightSegmentPath = flightDataPath.slice(0, -4);
const [treePatch] = flightDataPath.slice(-3, -2);
const newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)(// TODO-APP: remove ''
[
"",
...flightSegmentPath
], currentTree, treePatch, state.canonicalUrl);
if (newTree === null) {
return (0, _handlesegmentmismatch.handleSegmentMismatch)(state, action, treePatch);
}
if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) {
return (0, _navigatereducer.handleExternalUrl)(state, mutable, state.canonicalUrl, state.pushRef.pendingPush);
}
const canonicalUrlOverrideHref = overrideCanonicalUrl ? (0, _createhreffromurl.createHrefFromUrl)(overrideCanonicalUrl) : undefined;
if (canonicalUrlOverrideHref) {
mutable.canonicalUrl = canonicalUrlOverrideHref;
}
const cache = (0, _approuter.createEmptyCacheNode)();
(0, _applyflightdata.applyFlightData)(currentCache, cache, flightDataPath);
mutable.patchedTree = newTree;
mutable.cache = cache;
currentCache = cache;
currentTree = newTree;
}
return (0, _handlemutable.handleMutable)(state, mutable);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=server-patch-reducer.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/server-patch-reducer.ts"],"names":["serverPatchReducer","state","action","serverResponse","flightData","overrideCanonicalUrl","mutable","preserveCustomHistoryState","handleExternalUrl","pushRef","pendingPush","currentTree","tree","currentCache","cache","flightDataPath","flightSegmentPath","slice","treePatch","newTree","applyRouterStatePatchToTree","canonicalUrl","handleSegmentMismatch","isNavigatingToNewRootLayout","canonicalUrlOverrideHref","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AAAA,gCAAe,EAACf,cAAcC,OAAOC;QAErCT,QAAQuB,WAAW,GAAGV;QACtBb,QAAQQ,KAAK,GAAGA;QAEhBD,eAAeC;QACfH,cAAcQ;IAChB;IAEA,OAAOW,IAAAA,4BAAa,EAAC7B,OAAOK;AAC9B"}

View File

@ -0,0 +1,30 @@
import type { FlightRouterState } from '../../../server/app-render/types';
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime';
import type { AppRouterState } from './router-reducer-types';
interface RefreshInactiveParallelSegments {
state: AppRouterState;
updatedTree: FlightRouterState;
updatedCache: CacheNode;
includeNextUrl: boolean;
canonicalUrl: string;
}
/**
* Refreshes inactive segments that are still in the current FlightRouterState.
* A segment is considered "inactive" when the server response indicates it didn't match to a page component.
* This happens during a soft-navigation, where the server will want to patch in the segment
* with the "default" component, but we explicitly ignore the server in this case
* and keep the existing state for that segment. New data for inactive segments are inherently
* not part of the server response when we patch the tree, because they were associated with a response
* from an earlier navigation/request. For each segment, once it becomes "active", we encode the URL that provided
* the data for it. This function traverses parallel routes looking for these markers so that it can re-fetch
* and patch the new data into the tree.
*/
export declare function refreshInactiveParallelSegments(options: RefreshInactiveParallelSegments): Promise<void>;
/**
* Walks the current parallel segments to determine if they are "active".
* An active parallel route will have a `__PAGE__` segment in the FlightRouterState.
* As opposed to a `__DEFAULT__` segment, which means there was no match for that parallel route.
* We add a special marker here so that we know how to refresh its data when the router is revalidated.
*/
export declare function addRefreshMarkerToActiveParallelSegments(tree: FlightRouterState, path: string): void;
export {};

View File

@ -0,0 +1,101 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
addRefreshMarkerToActiveParallelSegments: null,
refreshInactiveParallelSegments: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
addRefreshMarkerToActiveParallelSegments: function() {
return addRefreshMarkerToActiveParallelSegments;
},
refreshInactiveParallelSegments: function() {
return refreshInactiveParallelSegments;
}
});
const _applyflightdata = require("./apply-flight-data");
const _fetchserverresponse = require("./fetch-server-response");
const _segment = require("../../../shared/lib/segment");
async function refreshInactiveParallelSegments(options) {
const fetchedSegments = new Set();
await refreshInactiveParallelSegmentsImpl({
...options,
rootTree: options.updatedTree,
fetchedSegments
});
}
async function refreshInactiveParallelSegmentsImpl(param) {
let { state, updatedTree, updatedCache, includeNextUrl, fetchedSegments, rootTree = updatedTree, canonicalUrl } = param;
const [, parallelRoutes, refetchPath, refetchMarker] = updatedTree;
const fetchPromises = [];
if (refetchPath && refetchPath !== canonicalUrl && refetchMarker === "refresh" && // it's possible for the tree to contain multiple segments that contain data at the same URL
// we keep track of them so we can dedupe the requests
!fetchedSegments.has(refetchPath)) {
fetchedSegments.add(refetchPath) // Mark this URL as fetched
;
// Eagerly kick off the fetch for the refetch path & the parallel routes. This should be fine to do as they each operate
// independently on their own cache nodes, and `applyFlightData` will copy anything it doesn't care about from the existing cache.
const fetchPromise = (0, _fetchserverresponse.fetchServerResponse)(new URL(refetchPath, location.origin), // refetch from the root of the updated tree, otherwise it will be scoped to the current segment
// and might not contain the data we need to patch in interception route data (such as dynamic params from a previous segment)
[
rootTree[0],
rootTree[1],
rootTree[2],
"refetch"
], includeNextUrl ? state.nextUrl : null, state.buildId).then((fetchResponse)=>{
const flightData = fetchResponse[0];
if (typeof flightData !== "string") {
for (const flightDataPath of flightData){
// we only pass the new cache as this function is called after clearing the router cache
// and filling in the new page data from the server. Meaning the existing cache is actually the cache that's
// just been created & has been written to, but hasn't been "committed" yet.
(0, _applyflightdata.applyFlightData)(updatedCache, updatedCache, flightDataPath);
}
} else {
// When flightData is a string, it suggests that the server response should have triggered an MPA navigation
// I'm not 100% sure of this decision, but it seems unlikely that we'd want to introduce a redirect side effect
// when refreshing on-screen data, so handling this has been ommitted.
}
});
fetchPromises.push(fetchPromise);
}
for(const key in parallelRoutes){
const parallelFetchPromise = refreshInactiveParallelSegmentsImpl({
state,
updatedTree: parallelRoutes[key],
updatedCache,
includeNextUrl,
fetchedSegments,
rootTree,
canonicalUrl
});
fetchPromises.push(parallelFetchPromise);
}
await Promise.all(fetchPromises);
}
function addRefreshMarkerToActiveParallelSegments(tree, path) {
const [segment, parallelRoutes, , refetchMarker] = tree;
// a page segment might also contain concatenated search params, so we do a partial match on the key
if (segment.includes(_segment.PAGE_SEGMENT_KEY) && refetchMarker !== "refresh") {
tree[2] = path;
tree[3] = "refresh";
}
for(const key in parallelRoutes){
addRefreshMarkerToActiveParallelSegments(parallelRoutes[key], path);
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=refetch-inactive-parallel-segments.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/refetch-inactive-parallel-segments.ts"],"names":["addRefreshMarkerToActiveParallelSegments","refreshInactiveParallelSegments","options","fetchedSegments","Set","refreshInactiveParallelSegmentsImpl","rootTree","updatedTree","state","updatedCache","includeNextUrl","canonicalUrl","parallelRoutes","refetchPath","refetchMarker","fetchPromises","has","add","fetchPromise","fetchServerResponse","URL","location","origin","nextUrl","buildId","then","fetchResponse","flightData","flightDataPath","applyFlightData","push","key","parallelFetchPromise","Promise","all","tree","path","segment","includes","PAGE_SEGMENT_KEY"],"mappings":";;;;;;;;;;;;;;;IAiHgBA,wCAAwC;eAAxCA;;IAvFMC,+BAA+B;eAA/BA;;;iCAvBU;qCACI;yBACH;AAqB1B,eAAeA,gCACpBC,OAAwC;IAExC,MAAMC,kBAAkB,IAAIC;IAC5B,MAAMC,oCAAoC;QACxC,GAAGH,OAAO;QACVI,UAAUJ,QAAQK,WAAW;QAC7BJ;IACF;AACF;AAEA,eAAeE,oCAAoC,KAWlD;IAXkD,IAAA,EACjDG,KAAK,EACLD,WAAW,EACXE,YAAY,EACZC,cAAc,EACdP,eAAe,EACfG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IAAIE,QAAQC,QAAQ,CAACC,yBAAgB,KAAKzB,kBAAkB,WAAW;QACrEqB,IAAI,CAAC,EAAE,GAAGC;QACVD,IAAI,CAAC,EAAE,GAAG;IACZ;IAEA,IAAK,MAAMJ,OAAOnB,eAAgB;QAChCZ,yCAAyCY,cAAc,CAACmB,IAAI,EAAEK;IAChE;AACF"}

View File

@ -0,0 +1,229 @@
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime';
import type { FlightRouterState, FlightSegmentPath } from '../../../server/app-render/types';
import type { FetchServerResponseResult } from './fetch-server-response';
export declare const ACTION_REFRESH = "refresh";
export declare const ACTION_NAVIGATE = "navigate";
export declare const ACTION_RESTORE = "restore";
export declare const ACTION_SERVER_PATCH = "server-patch";
export declare const ACTION_PREFETCH = "prefetch";
export declare const ACTION_FAST_REFRESH = "fast-refresh";
export declare const ACTION_SERVER_ACTION = "server-action";
export type RouterChangeByServerResponse = ({ previousTree, serverResponse, }: {
previousTree: FlightRouterState;
serverResponse: FetchServerResponseResult;
}) => void;
export type RouterNavigate = (href: string, navigateType: 'push' | 'replace', shouldScroll: boolean) => void;
export interface Mutable {
mpaNavigation?: boolean;
patchedTree?: FlightRouterState;
canonicalUrl?: string;
scrollableSegments?: FlightSegmentPath[];
pendingPush?: boolean;
cache?: CacheNode;
prefetchCache?: AppRouterState['prefetchCache'];
hashFragment?: string;
shouldScroll?: boolean;
preserveCustomHistoryState?: boolean;
}
export interface ServerActionMutable extends Mutable {
inFlightServerAction?: Promise<any> | null;
}
/**
* Refresh triggers a refresh of the full page data.
* - fetches the Flight data and fills rsc at the root of the cache.
* - The router state is updated at the root.
*/
export interface RefreshAction {
type: typeof ACTION_REFRESH;
origin: Location['origin'];
}
export interface FastRefreshAction {
type: typeof ACTION_FAST_REFRESH;
origin: Location['origin'];
}
export type ServerActionDispatcher = (args: Omit<ServerActionAction, 'type' | 'mutable' | 'navigate' | 'changeByServerResponse' | 'cache'>) => void;
export interface ServerActionAction {
type: typeof ACTION_SERVER_ACTION;
actionId: string;
actionArgs: any[];
resolve: (value: any) => void;
reject: (reason?: any) => void;
}
/**
* Navigate triggers a navigation to the provided url. It supports two types: `push` and `replace`.
*
* `navigateType`:
* - `push` - pushes a new history entry in the browser history
* - `replace` - replaces the current history entry in the browser history
*
* Navigate has multiple cache heuristics:
* - page was prefetched
* - Apply router state tree from prefetch
* - Apply Flight data from prefetch to the cache
* - If Flight data is a string, it's a redirect and the state is updated to trigger a redirect
* - Check if hard navigation is needed
* - Hard navigation happens when a dynamic parameter below the common layout changed
* - When hard navigation is needed the cache is invalidated below the flightSegmentPath
* - The missing cache nodes of the page will be fetched in layout-router and trigger the SERVER_PATCH action
* - If hard navigation is not needed
* - The cache is reused
* - If any cache nodes are missing they'll be fetched in layout-router and trigger the SERVER_PATCH action
* - page was not prefetched
* - The navigate was called from `next/router` (`router.push()` / `router.replace()`) / `next/link` without prefetched data available (e.g. the prefetch didn't come back from the server before clicking the link)
* - Flight data is fetched in the reducer (suspends the reducer)
* - Router state tree is created based on Flight data
* - Cache is filled based on the Flight data
*
* Above steps explain 3 cases:
* - `soft` - Reuses the existing cache and fetches missing nodes in layout-router.
* - `hard` - Creates a new cache where cache nodes are removed below the common layout and fetches missing nodes in layout-router.
* - `optimistic` (explicit no prefetch) - Creates a new cache and kicks off the data fetch in the reducer. The data fetch is awaited in the layout-router.
*/
export interface NavigateAction {
type: typeof ACTION_NAVIGATE;
url: URL;
isExternalUrl: boolean;
locationSearch: Location['search'];
navigateType: 'push' | 'replace';
shouldScroll: boolean;
}
/**
* Restore applies the provided router state.
* - Used for `popstate` (back/forward navigation) where a known router state has to be applied.
* - Also used when syncing the router state with `pushState`/`replaceState` calls.
* - Router state is applied as-is from the history state, if available.
* - If the history state does not contain the router state, the existing router state is used.
* - If any cache node is missing it will be fetched in layout-router during rendering and the server-patch case.
* - If existing cache nodes match these are used.
*/
export interface RestoreAction {
type: typeof ACTION_RESTORE;
url: URL;
tree: FlightRouterState | undefined;
}
/**
* Server-patch applies the provided Flight data to the cache and router tree.
* - Only triggered in layout-router.
* - Creates a new cache and router state with the Flight data applied.
*/
export interface ServerPatchAction {
type: typeof ACTION_SERVER_PATCH;
serverResponse: FetchServerResponseResult;
previousTree: FlightRouterState;
}
/**
* PrefetchKind defines the type of prefetching that should be done.
* - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully.
* - `full` - prefetch the page data fully.
* - `temporary` - a temporary prefetch entry is added to the cache, this is used when prefetch={false} is used in next/link or when you push a route programmatically.
*/
export declare enum PrefetchKind {
AUTO = "auto",
FULL = "full",
TEMPORARY = "temporary"
}
/**
* Prefetch adds the provided FlightData to the prefetch cache
* - Creates the router state tree based on the patch in FlightData
* - Adds the FlightData to the prefetch cache
* - In ACTION_NAVIGATE the prefetch cache is checked and the router state tree and FlightData are applied.
*/
export interface PrefetchAction {
type: typeof ACTION_PREFETCH;
url: URL;
kind: PrefetchKind;
}
export interface PushRef {
/**
* If the app-router should push a new history entry in app-router's useEffect()
*/
pendingPush: boolean;
/**
* Multi-page navigation through location.href.
*/
mpaNavigation: boolean;
/**
* Skip applying the router state to the browser history state.
*/
preserveCustomHistoryState: boolean;
}
export type FocusAndScrollRef = {
/**
* If focus and scroll should be set in the layout-router's useEffect()
*/
apply: boolean;
/**
* The hash fragment that should be scrolled to.
*/
hashFragment: string | null;
/**
* The paths of the segments that should be focused.
*/
segmentPaths: FlightSegmentPath[];
/**
* If only the URLs hash fragment changed
*/
onlyHashChange: boolean;
};
export type PrefetchCacheEntry = {
treeAtTimeOfPrefetch: FlightRouterState;
data: Promise<FetchServerResponseResult>;
kind: PrefetchKind;
prefetchTime: number;
lastUsedTime: number | null;
key: string;
status: PrefetchCacheEntryStatus;
};
export declare enum PrefetchCacheEntryStatus {
fresh = "fresh",
reusable = "reusable",
expired = "expired",
stale = "stale"
}
/**
* Handles keeping the state of app-router.
*/
export type AppRouterState = {
/**
* The buildId is used to do a mpaNavigation when the server returns a different buildId.
* It is used to avoid issues where an older version of the app is loaded in the browser while the server has a new version.
*/
buildId: string;
/**
* The router state, this is written into the history state in app-router using replaceState/pushState.
* - Has to be serializable as it is written into the history state.
* - Holds which segments and parallel routes are shown on the screen.
*/
tree: FlightRouterState;
/**
* The cache holds React nodes for every segment that is shown on screen as well as previously shown segments.
* It also holds in-progress data requests.
* Prefetched data is stored separately in `prefetchCache`, that is applied during ACTION_NAVIGATE.
*/
cache: CacheNode;
/**
* Cache that holds prefetched Flight responses keyed by url.
*/
prefetchCache: Map<string, PrefetchCacheEntry>;
/**
* Decides if the update should create a new history entry and if the navigation has to trigger a browser navigation.
*/
pushRef: PushRef;
/**
* Decides if the update should apply scroll and focus management.
*/
focusAndScrollRef: FocusAndScrollRef;
/**
* The canonical url that is pushed/replaced.
* - This is the url you see in the browser.
*/
canonicalUrl: string;
/**
* The underlying "url" representing the UI state, which is used for intercepting routes.
*/
nextUrl: string | null;
};
export type ReadonlyReducerState = Readonly<AppRouterState>;
export type ReducerState = Promise<AppRouterState> | AppRouterState;
export type ReducerActions = Readonly<RefreshAction | NavigateAction | RestoreAction | ServerPatchAction | PrefetchAction | FastRefreshAction | ServerActionAction>;
export declare function isThenable(value: any): value is Promise<AppRouterState>;

View File

@ -0,0 +1,89 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ACTION_FAST_REFRESH: null,
ACTION_NAVIGATE: null,
ACTION_PREFETCH: null,
ACTION_REFRESH: null,
ACTION_RESTORE: null,
ACTION_SERVER_ACTION: null,
ACTION_SERVER_PATCH: null,
PrefetchCacheEntryStatus: null,
PrefetchKind: null,
isThenable: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ACTION_FAST_REFRESH: function() {
return ACTION_FAST_REFRESH;
},
ACTION_NAVIGATE: function() {
return ACTION_NAVIGATE;
},
ACTION_PREFETCH: function() {
return ACTION_PREFETCH;
},
ACTION_REFRESH: function() {
return ACTION_REFRESH;
},
ACTION_RESTORE: function() {
return ACTION_RESTORE;
},
ACTION_SERVER_ACTION: function() {
return ACTION_SERVER_ACTION;
},
ACTION_SERVER_PATCH: function() {
return ACTION_SERVER_PATCH;
},
PrefetchCacheEntryStatus: function() {
return PrefetchCacheEntryStatus;
},
PrefetchKind: function() {
return PrefetchKind;
},
isThenable: function() {
return isThenable;
}
});
const ACTION_REFRESH = "refresh";
const ACTION_NAVIGATE = "navigate";
const ACTION_RESTORE = "restore";
const ACTION_SERVER_PATCH = "server-patch";
const ACTION_PREFETCH = "prefetch";
const ACTION_FAST_REFRESH = "fast-refresh";
const ACTION_SERVER_ACTION = "server-action";
var PrefetchKind;
(function(PrefetchKind) {
PrefetchKind["AUTO"] = "auto";
PrefetchKind["FULL"] = "full";
PrefetchKind["TEMPORARY"] = "temporary";
})(PrefetchKind || (PrefetchKind = {}));
var PrefetchCacheEntryStatus;
(function(PrefetchCacheEntryStatus) {
PrefetchCacheEntryStatus["fresh"] = "fresh";
PrefetchCacheEntryStatus["reusable"] = "reusable";
PrefetchCacheEntryStatus["expired"] = "expired";
PrefetchCacheEntryStatus["stale"] = "stale";
})(PrefetchCacheEntryStatus || (PrefetchCacheEntryStatus = {}));
function isThenable(value) {
// TODO: We don't gain anything from this abstraction. It's unsound, and only
// makes sense in the specific places where we use it. So it's better to keep
// the type coercion inline, instead of leaking this to other places in
// the codebase.
return value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=router-reducer-types.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/router-reducer/router-reducer-types.ts"],"names":["ACTION_FAST_REFRESH","ACTION_NAVIGATE","ACTION_PREFETCH","ACTION_REFRESH","ACTION_RESTORE","ACTION_SERVER_ACTION","ACTION_SERVER_PATCH","isThenable","PrefetchKind","PrefetchCacheEntryStatus","value","then"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;IAYaA,mBAAmB;eAAnBA;;IAJAC,eAAe;eAAfA;;IAGAC,eAAe;eAAfA;;IAJAC,cAAc;eAAdA;;IAEAC,cAAc;eAAdA;;IAIAC,oBAAoB;eAApBA;;IAHAC,mBAAmB;eAAnBA;;;;;;;;IAuQGC,UAAU;eAAVA;;;AA1QT,MAAMJ,iBAAiB;AACvB,MAAMF,kBAAkB;AACxB,MAAMG,iBAAiB;AACvB,MAAME,sBAAsB;AAC5B,MAAMJ,kBAAkB;AACxB,MAAMF,sBAAsB;AAC5B,MAAMK,uBAAuB;;UAuIxBG;;;;GAAAA,iBAAAA;;UA8DAC;;;;;GAAAA,6BAAAA;AA+DL,SAASF,WAAWG,KAAU;IACnC,6EAA6E;IAC7E,6EAA6E;IAC7E,uEAAuE;IACvE,gBAAgB;IAChB,OACEA,SACC,CAAA,OAAOA,UAAU,YAAY,OAAOA,UAAU,UAAS,KACxD,OAAOA,MAAMC,IAAI,KAAK;AAE1B"}

Some files were not shown because too many files have changed in this diff Show More