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,79 @@
import { fetchServerResponse } from "../fetch-server-response";
import { createHrefFromUrl } from "../create-href-from-url";
import { applyRouterStatePatchToTree } from "../apply-router-state-patch-to-tree";
import { isNavigatingToNewRootLayout } from "../is-navigating-to-new-root-layout";
import { handleExternalUrl } from "./navigate-reducer";
import { handleMutable } from "../handle-mutable";
import { applyFlightData } from "../apply-flight-data";
import { createEmptyCacheNode } from "../../app-router";
import { handleSegmentMismatch } from "../handle-segment-mismatch";
import { hasInterceptionRouteInCurrentTree } from "./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 = 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 = hasInterceptionRouteInCurrentTree(state.tree);
// TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree.
cache.lazyData = 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 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 = applyRouterStatePatchToTree(// TODO-APP: remove ''
[
""
], currentTree, treePatch, state.canonicalUrl);
if (newTree === null) {
return handleSegmentMismatch(state, action, treePatch);
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, state.pushRef.pendingPush);
}
const canonicalUrlOverrideHref = canonicalUrlOverride ? createHrefFromUrl(canonicalUrlOverride) : undefined;
if (canonicalUrlOverride) {
mutable.canonicalUrl = canonicalUrlOverrideHref;
}
const applied = applyFlightData(currentCache, cache, flightDataPath);
if (applied) {
mutable.cache = cache;
currentCache = cache;
}
mutable.patchedTree = newTree;
mutable.canonicalUrl = href;
currentTree = newTree;
}
return handleMutable(state, mutable);
}, ()=>state);
}
function fastRefreshReducerNoop(state, _action) {
return state;
}
export const fastRefreshReducer = process.env.NODE_ENV === "production" ? fastRefreshReducerNoop : fastRefreshReducerImpl;
//# 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":["fetchServerResponse","createHrefFromUrl","applyRouterStatePatchToTree","isNavigatingToNewRootLayout","handleExternalUrl","handleMutable","applyFlightData","createEmptyCacheNode","handleSegmentMismatch","hasInterceptionRouteInCurrentTree","fastRefreshReducerImpl","state","action","origin","mutable","href","canonicalUrl","preserveCustomHistoryState","cache","includeNextUrl","tree","lazyData","URL","nextUrl","buildId","then","flightData","canonicalUrlOverride","pushRef","pendingPush","currentTree","currentCache","flightDataPath","length","console","log","treePatch","newTree","canonicalUrlOverrideHref","undefined","applied","patchedTree","fastRefreshReducerNoop","_action","fastRefreshReducer","process","env","NODE_ENV"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,iBAAiB,QAAQ,0BAAyB;AAC3D,SAASC,2BAA2B,QAAQ,sCAAqC;AACjF,SAASC,2BAA2B,QAAQ,sCAAqC;AAOjF,SAASC,iBAAiB,QAAQ,qBAAoB;AACtD,SAASC,aAAa,QAAQ,oB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AsB;YACtB;gBAAC;aAAG,EACJ4B,aACAM,WACAzB,MAAMK,YAAY;YAGpB,IAAIqB,YAAY,MAAM;gBACpB,OAAO7B,sBAAsBG,OAAOC,QAAQwB;YAC9C;YAEA,IAAIjC,4BAA4B2B,aAAaO,UAAU;gBACrD,OAAOjC,kBACLO,OACAG,SACAC,MACAJ,MAAMiB,OAAO,CAACC,WAAW;YAE7B;YAEA,MAAMS,2BAA2BX,uBAC7B1B,kBAAkB0B,wBAClBY;YAEJ,IAAIZ,sBAAsB;gBACxBb,QAAQE,YAAY,GAAGsB;YACzB;YACA,MAAME,UAAUlC,gBAAgByB,cAAcb,OAAOc;YAErD,IAAIQ,SAAS;gBACX1B,QAAQI,KAAK,GAAGA;gBAChBa,eAAeb;YACjB;YAEAJ,QAAQ2B,WAAW,GAAGJ;YACtBvB,QAAQE,YAAY,GAAGD;YAEvBe,cAAcO;QAChB;QACA,OAAOhC,cAAcM,OAAOG;IAC9B,GACA,IAAMH;AAEV;AAEA,SAAS+B,uBACP/B,KAA2B,EAC3BgC,OAA0B;IAE1B,OAAOhC;AACT;AAEA,OAAO,MAAMiC,qBACXC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eACrBL,yBACAhC,uBAAsB"}

View File

@ -0,0 +1,33 @@
import { createRouterCacheKey } from "../create-router-cache-key";
export 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 = createRouterCacheKey(segment);
const cacheNode = childSegmentMap.get(cacheKey);
if (!cacheNode) {
continue;
}
const item = findHeadInCacheImpl(cacheNode, childParallelRoutes, keyPrefix + "/" + cacheKey);
if (item) {
return item;
}
}
return null;
}
//# 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":["createRouterCacheKey","findHeadInCache","cache","parallelRoutes","findHeadInCacheImpl","keyPrefix","isLastItem","Object","keys","length","key","segment","childParallelRoutes","childSegmentMap","get","cacheKey","cacheNode","item"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,6BAA4B;AAEjE,OAAO,SAASC,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,WAAWf,qBAAqBW;QAEtC,MAAMK,YAAYH,gBAAgBC,GAAG,CAACC;QACtC,IAAI,CAACC,WAAW;YACd;QACF;QAEA,MAAMC,OAAOb,oBACXY,WACAJ,qBACAP,YAAY,MAAMU;QAEpB,IAAIE,MAAM;YACR,OAAOA;QACT;IACF;IAEA,OAAO;AACT"}

View File

@ -0,0 +1,5 @@
export function getSegmentValue(segment) {
return Array.isArray(segment) ? segment[1] : segment;
}
//# 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":"AAEA,OAAO,SAASA,gBAAgBC,OAAgB;IAC9C,OAAOC,MAAMC,OAAO,CAACF,WAAWA,OAAO,CAAC,EAAE,GAAGA;AAC/C"}

View File

@ -0,0 +1,23 @@
import { isInterceptionRouteAppPath } from "../../../../server/future/helpers/interception-routes";
export 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" && 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;
}
//# 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":["isInterceptionRouteAppPath","hasInterceptionRouteInCurrentTree","segment","parallelRoutes","Array","isArray","key"],"mappings":"AACA,SAASA,0BAA0B,QAAQ,wDAAuD;AAElG,OAAO,SAASC,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,YAAYF,2BAA2BE,UAAU;QACtE,OAAO;IACT;IAEA,+CAA+C;IAC/C,IAAIC,gBAAgB;QAClB,IAAK,MAAMG,OAAOH,eAAgB;YAChC,IAAIF,kCAAkCE,cAAc,CAACG,IAAI,GAAG;gBAC1D,OAAO;YACT;QACF;IACF;IAEA,OAAO;AACT"}

View File

@ -0,0 +1,365 @@
import { fetchServerResponse } from "../fetch-server-response";
import { createHrefFromUrl } from "../create-href-from-url";
import { invalidateCacheBelowFlightSegmentPath } from "../invalidate-cache-below-flight-segmentpath";
import { applyRouterStatePatchToTree } from "../apply-router-state-patch-to-tree";
import { shouldHardNavigate } from "../should-hard-navigate";
import { isNavigatingToNewRootLayout } from "../is-navigating-to-new-root-layout";
import { PrefetchCacheEntryStatus } from "../router-reducer-types";
import { handleMutable } from "../handle-mutable";
import { applyFlightData } from "../apply-flight-data";
import { prefetchQueue } from "./prefetch-reducer";
import { createEmptyCacheNode } from "../../app-router";
import { DEFAULT_SEGMENT_KEY } from "../../../../shared/lib/segment";
import { listenForDynamicRequest, updateCacheNodeOnNavigation } from "../ppr-navigations";
import { getOrCreatePrefetchCacheEntry, prunePrefetchCache } from "../prefetch-cache-utils";
import { clearCacheNodeDataForSegmentPath } from "../clear-cache-node-data-for-segment-path";
export function handleExternalUrl(state, mutable, url, pendingPush) {
mutable.mpaNavigation = true;
mutable.canonicalUrl = url;
mutable.pendingPush = pendingPush;
mutable.scrollableSegments = undefined;
return 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){
clearCacheNodeDataForSegmentPath(newCache, currentCache, segmentPaths);
appliedPatch = true;
}
return appliedPatch;
}
// These implementations are expected to diverge significantly, so I've forked
// the entire function. The one that's disabled should be dead code eliminated
// because the check here is statically inlined at build time.
export 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 = createHrefFromUrl(url);
const pendingPush = navigateType === "push";
// we want to prune the prefetch cache on every navigation to avoid it growing too large
prunePrefetchCache(state.prefetchCache);
mutable.preserveCustomHistoryState = false;
if (isExternalUrl) {
return handleExternalUrl(state, mutable, url.toString(), pendingPush);
}
const prefetchValues = getOrCreatePrefetchCacheEntry({
url,
nextUrl: state.nextUrl,
tree: state.tree,
buildId: state.buildId,
prefetchCache: state.prefetchCache
});
const { treeAtTimeOfPrefetch, data } = prefetchValues;
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 = 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 = applyRouterStatePatchToTree(// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, treeAtTimeOfPrefetch, treePatch, href);
}
if (newTree !== null) {
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush);
}
const cache = createEmptyCacheNode();
let applied = false;
if (prefetchValues.status === 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 = applyFlightData(currentCache, cache, flightDataPath, prefetchValues);
}
const hardNavigate = 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;
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] !== DEFAULT_SEGMENT_KEY) {
scrollableSegments.push(scrollableSegmentPath);
}
}
}
}
mutable.patchedTree = currentTree;
mutable.canonicalUrl = canonicalUrlOverride ? createHrefFromUrl(canonicalUrlOverride) : href;
mutable.pendingPush = pendingPush;
mutable.scrollableSegments = scrollableSegments;
mutable.hashFragment = hash;
mutable.shouldScroll = shouldScroll;
return 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 = createHrefFromUrl(url);
const pendingPush = navigateType === "push";
// we want to prune the prefetch cache on every navigation to avoid it growing too large
prunePrefetchCache(state.prefetchCache);
mutable.preserveCustomHistoryState = false;
if (isExternalUrl) {
return handleExternalUrl(state, mutable, url.toString(), pendingPush);
}
const prefetchValues = getOrCreatePrefetchCacheEntry({
url,
nextUrl: state.nextUrl,
tree: state.tree,
buildId: state.buildId,
prefetchCache: state.prefetchCache
});
const { treeAtTimeOfPrefetch, data } = prefetchValues;
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 = 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 = applyRouterStatePatchToTree(// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, treeAtTimeOfPrefetch, treePatch, href);
}
if (newTree !== null) {
if (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 = 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.)
listenForDynamicRequest(task, 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 = createEmptyCacheNode();
let applied = false;
if (prefetchValues.status === 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 = applyFlightData(currentCache, cache, flightDataPath, prefetchValues);
}
const hardNavigate = 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;
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] !== DEFAULT_SEGMENT_KEY) {
scrollableSegments.push(scrollableSegmentPath);
}
}
}
}
mutable.patchedTree = currentTree;
mutable.canonicalUrl = canonicalUrlOverride ? createHrefFromUrl(canonicalUrlOverride) : href;
mutable.pendingPush = pendingPush;
mutable.scrollableSegments = scrollableSegments;
mutable.hashFragment = hash;
mutable.shouldScroll = shouldScroll;
return handleMutable(state, mutable);
}, ()=>state);
}
//# sourceMappingURL=navigate-reducer.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,21 @@
import { NEXT_RSC_UNION_QUERY } from "../../app-router-headers";
import { PromiseQueue } from "../../promise-queue";
import { getOrCreatePrefetchCacheEntry, prunePrefetchCache } from "../prefetch-cache-utils";
export const prefetchQueue = new PromiseQueue(5);
export function prefetchReducer(state, action) {
// let's prune the prefetch cache before we do anything else
prunePrefetchCache(state.prefetchCache);
const { url } = action;
url.searchParams.delete(NEXT_RSC_UNION_QUERY);
getOrCreatePrefetchCacheEntry({
url,
nextUrl: state.nextUrl,
prefetchCache: state.prefetchCache,
kind: action.kind,
tree: state.tree,
buildId: state.buildId
});
return state;
}
//# sourceMappingURL=prefetch-reducer.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/prefetch-reducer.ts"],"names":["NEXT_RSC_UNION_QUERY","PromiseQueue","getOrCreatePrefetchCacheEntry","prunePrefetchCache","prefetchQueue","prefetchReducer","state","action","prefetchCache","url","searchParams","delete","nextUrl","kind","tree","buildId"],"mappings":"AAKA,SAASA,oBAAoB,QAAQ,2BAA0B;AAC/D,SAASC,YAAY,QAAQ,sBAAqB;AAClD,SACEC,6BAA6B,EAC7BC,kBAAkB,QACb,0BAAyB;AAEhC,OAAO,MAAMC,gBAAgB,IAAIH,aAAa,GAAE;AAEhD,OAAO,SAASI,gBACdC,KAA2B,EAC3BC,MAAsB;IAEtB,4DAA4D;IAC5DJ,mBAAmBG,MAAME,aAAa;IAEtC,MAAM,EAAEC,GAAG,EAAE,GAAGF;IAChBE,IAAIC,YAAY,CAACC,MAAM,CAACX;IAExBE,8BAA8B;QAC5BO;QACAG,SAASN,MAAMM,OAAO;QACtBJ,eAAeF,MAAME,aAAa;QAClCK,MAAMN,OAAOM,IAAI;QACjBC,MAAMR,MAAMQ,IAAI;QAChBC,SAAST,MAAMS,OAAO;IACxB;IAEA,OAAOT;AACT"}

View File

@ -0,0 +1,88 @@
import { fetchServerResponse } from "../fetch-server-response";
import { createHrefFromUrl } from "../create-href-from-url";
import { applyRouterStatePatchToTree } from "../apply-router-state-patch-to-tree";
import { isNavigatingToNewRootLayout } from "../is-navigating-to-new-root-layout";
import { handleExternalUrl } from "./navigate-reducer";
import { handleMutable } from "../handle-mutable";
import { fillLazyItemsTillLeafWithHead } from "../fill-lazy-items-till-leaf-with-head";
import { createEmptyCacheNode } from "../../app-router";
import { handleSegmentMismatch } from "../handle-segment-mismatch";
import { hasInterceptionRouteInCurrentTree } from "./has-interception-route-in-current-tree";
import { refreshInactiveParallelSegments } from "../refetch-inactive-parallel-segments";
export function refreshReducer(state, action) {
const { origin } = action;
const mutable = {};
const href = state.canonicalUrl;
let currentTree = state.tree;
mutable.preserveCustomHistoryState = false;
const cache = 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 = hasInterceptionRouteInCurrentTree(state.tree);
// TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree.
cache.lazyData = 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 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 = applyRouterStatePatchToTree(// TODO-APP: remove ''
[
""
], currentTree, treePatch, state.canonicalUrl);
if (newTree === null) {
return handleSegmentMismatch(state, action, treePatch);
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, state.pushRef.pendingPush);
}
const canonicalUrlOverrideHref = canonicalUrlOverride ? 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;
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 refreshInactiveParallelSegments({
state,
updatedTree: newTree,
updatedCache: cache,
includeNextUrl,
canonicalUrl: mutable.canonicalUrl || state.canonicalUrl
});
mutable.cache = cache;
mutable.patchedTree = newTree;
mutable.canonicalUrl = href;
currentTree = newTree;
}
return handleMutable(state, mutable);
}, ()=>state);
}
//# sourceMappingURL=refresh-reducer.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/refresh-reducer.ts"],"names":["fetchServerResponse","createHrefFromUrl","applyRouterStatePatchToTree","isNavigatingToNewRootLayout","handleExternalUrl","handleMutable","fillLazyItemsTillLeafWithHead","createEmptyCacheNode","handleSegmentMismatch","hasInterceptionRouteInCurrentTree","refreshInactiveParallelSegments","refreshReducer","state","action","origin","mutable","href","canonicalUrl","currentTree","tree","preserveCustomHistoryState","cache","includeNextUrl","lazyData","URL","nextUrl","buildId","then","flightData","canonicalUrlOverride","pushRef","pendingPush","flightDataPath","length","console","log","treePatch","newTree","canonicalUrlOverrideHref","undefined","cacheNodeSeedData","head","slice","rsc","prefetchRsc","prefetchCache","Map","updatedTree","updatedCache","patchedTree"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,iBAAiB,QAAQ,0BAAyB;AAC3D,SAASC,2BAA2B,QAAQ,sCAAqC;AACjF,SAASC,2BAA2B,QAAQ,sCAAqC;AAOjF,SAASC,iBAAiB,QAAQ,qBAAoB;AACtD,SAASC,aAAa,QAAQ,oBAAmB;AAEjD,SAASC,6BAA6B,QAAQ,yCAAwC;AACtF,SAASC,oBAAoB,QAAQ,mBAAkB;AACvD,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,iCAAiC,QAAQ,2CAA0C;AAC5F,SAASC,+BAA+B,QAAQ,wCAAuC;AAEvF,OAAO,SAASC,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,QAAmBd;IAEzB,sFAAsF;IACtF,sHAAsH;IACtH,MAAMe,iBAAiBb,kCAAkCG,MAAMO,IAAI;IAEnE,uDAAuD;IACvD,wCAAwC;IACxCE,MAAME,QAAQ,GAAGvB,oBACf,IAAIwB,IAAIR,MAAMF,SACd;QAACI,WAAW,CAAC,EAAE;QAAEA,WAAW,CAAC,EAAE;QAAEA,WAAW,CAAC,EAAE;QAAE;KAAU,EAC3DI,iBAAiBV,MAAMa,OAAO,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aAAaV;gBACbW,cAAc3B;gBACdC;gBACAL,cAAcF,QAAQE,YAAY,IAAIL,MAAMK,YAAY;YAC1D;YAEAF,QAAQM,KAAK,GAAGA;YAChBN,QAAQkC,WAAW,GAAGZ;YACtBtB,QAAQE,YAAY,GAAGD;YAEvBE,cAAcmB;QAChB;QAEA,OAAOhC,cAAcO,OAAOG;IAC9B,GACA,IAAMH;AAEV"}

View File

@ -0,0 +1,39 @@
import { createHrefFromUrl } from "../create-href-from-url";
import { extractPathFromFlightRouterState } from "../compute-changed-path";
import { updateCacheNodeOnPopstateRestoration } from "../ppr-navigations";
export function restoreReducer(state, action) {
const { url, tree } = action;
const href = 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.
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 = extractPathFromFlightRouterState(treeToRestore)) != null ? _extractPathFromFlightRouterState : url.pathname
};
}
//# sourceMappingURL=restore-reducer.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/restore-reducer.ts"],"names":["createHrefFromUrl","extractPathFromFlightRouterState","updateCacheNodeOnPopstateRestoration","restoreReducer","state","action","url","tree","href","treeToRestore","oldCache","cache","newCache","process","env","__NEXT_PPR","buildId","canonicalUrl","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","prefetchCache","nextUrl","pathname"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,0BAAyB;AAM3D,SAASC,gCAAgC,QAAQ,0BAAyB;AAC1E,SAASC,oCAAoC,QAAQ,qBAAoB;AAEzE,OAAO,SAASC,eACdC,KAA2B,EAC3BC,MAAqB;IAErB,MAAM,EAAEC,GAAG,EAAEC,IAAI,EAAE,GAAGF;IACtB,MAAMG,OAAOR,kBAAkBM;IAC/B,0EAA0E;IAC1E,4FAA4F;IAC5F,gGAAgG;IAChG,6FAA6F;IAC7F,8DAA8D;IAC9D,yGAAyG;IACzG,MAAMG,gBAAgBF,QAAQH,MAAMG,IAAI;IAExC,MAAMG,WAAWN,MAAMO,KAAK;IAC5B,MAAMC,WAAWC,QAAQC,GAAG,CAACC,UAAU,GAEnC,qEAAqE;IACrE,2DAA2D;IAC3D,2BAA2B;IAC3Bb,qCAAqCQ,UAAUD,iBAC/CC;QAiBOT;IAfX,OAAO;QACLe,SAASZ,MAAMY,OAAO;QACtB,oBAAoB;QACpBC,cAAcT;QACdU,SAAS;YACPC,aAAa;YACbC,eAAe;YACf,6FAA6F;YAC7FC,4BAA4B;QAC9B;QACAC,mBAAmBlB,MAAMkB,iBAAiB;QAC1CX,OAAOC;QACPW,eAAenB,MAAMmB,aAAa;QAClC,wBAAwB;QACxBhB,MAAME;QACNe,SAASvB,CAAAA,oCAAAA,iCAAiCQ,0BAAjCR,oCAAmDK,IAAImB,QAAQ;IAC1E;AACF"}

View File

@ -0,0 +1,175 @@
import { callServer } from "../../../app-call-server";
import { ACTION, NEXT_ROUTER_STATE_TREE, NEXT_URL, RSC_CONTENT_TYPE_HEADER } from "../../app-router-headers";
// // 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");
import { addBasePath } from "../../../add-base-path";
import { createHrefFromUrl } from "../create-href-from-url";
import { handleExternalUrl } from "./navigate-reducer";
import { applyRouterStatePatchToTree } from "../apply-router-state-patch-to-tree";
import { isNavigatingToNewRootLayout } from "../is-navigating-to-new-root-layout";
import { handleMutable } from "../handle-mutable";
import { fillLazyItemsTillLeafWithHead } from "../fill-lazy-items-till-leaf-with-head";
import { createEmptyCacheNode } from "../../app-router";
import { hasInterceptionRouteInCurrentTree } from "./has-interception-route-in-current-tree";
import { handleSegmentMismatch } from "../handle-segment-mismatch";
import { refreshInactiveParallelSegments } from "../refetch-inactive-parallel-segments";
async function fetchServerAction(state, nextUrl, param) {
let { actionId, actionArgs } = param;
const body = await encodeReply(actionArgs);
const res = await fetch("", {
method: "POST",
headers: {
Accept: RSC_CONTENT_TYPE_HEADER,
[ACTION]: actionId,
[NEXT_ROUTER_STATE_TREE]: encodeURIComponent(JSON.stringify(state.tree)),
...process.env.NEXT_DEPLOYMENT_ID ? {
"x-deployment-id": process.env.NEXT_DEPLOYMENT_ID
} : {},
...nextUrl ? {
[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(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") === RSC_CONTENT_TYPE_HEADER;
if (isFlightResponse) {
const response = await createFromFetch(Promise.resolve(res), {
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
};
}
/*
* This reducer is responsible for calling the server action and processing any side-effects from the server action.
* It does not mutate the state by itself but rather delegates to other reducers to do the actual mutation.
*/ export 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 && 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 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 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 = 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 = applyRouterStatePatchToTree(// TODO-APP: remove ''
[
""
], currentTree, treePatch, redirectLocation ? createHrefFromUrl(redirectLocation) : state.canonicalUrl);
if (newTree === null) {
return handleSegmentMismatch(state, action, treePatch);
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return 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 = createEmptyCacheNode();
cache.rsc = rsc;
cache.prefetchRsc = null;
fillLazyItemsTillLeafWithHead(cache, // Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined, treePatch, cacheNodeSeedData, head);
await 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 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;
});
}
//# sourceMappingURL=server-action-reducer.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,49 @@
import { createHrefFromUrl } from "../create-href-from-url";
import { applyRouterStatePatchToTree } from "../apply-router-state-patch-to-tree";
import { isNavigatingToNewRootLayout } from "../is-navigating-to-new-root-layout";
import { handleExternalUrl } from "./navigate-reducer";
import { applyFlightData } from "../apply-flight-data";
import { handleMutable } from "../handle-mutable";
import { createEmptyCacheNode } from "../../app-router";
import { handleSegmentMismatch } from "../handle-segment-mismatch";
export 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 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 = applyRouterStatePatchToTree(// TODO-APP: remove ''
[
"",
...flightSegmentPath
], currentTree, treePatch, state.canonicalUrl);
if (newTree === null) {
return handleSegmentMismatch(state, action, treePatch);
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, state.canonicalUrl, state.pushRef.pendingPush);
}
const canonicalUrlOverrideHref = overrideCanonicalUrl ? createHrefFromUrl(overrideCanonicalUrl) : undefined;
if (canonicalUrlOverrideHref) {
mutable.canonicalUrl = canonicalUrlOverrideHref;
}
const cache = createEmptyCacheNode();
applyFlightData(currentCache, cache, flightDataPath);
mutable.patchedTree = newTree;
mutable.cache = cache;
currentCache = cache;
currentTree = newTree;
}
return handleMutable(state, mutable);
}
//# 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":["createHrefFromUrl","applyRouterStatePatchToTree","isNavigatingToNewRootLayout","handleExternalUrl","applyFlightData","handleMutable","createEmptyCacheNode","handleSegmentMismatch","serverPatchReducer","state","action","serverResponse","flightData","overrideCanonicalUrl","mutable","preserveCustomHistoryState","pushRef","pendingPush","currentTree","tree","currentCache","cache","flightDataPath","flightSegmentPath","slice","treePatch","newTree","canonicalUrl","canonicalUrlOverrideHref","undefined","patchedTree"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,0BAAyB;AAC3D,SAASC,2BAA2B,QAAQ,sCAAqC;AACjF,SAASC,2BAA2B,QAAQ,s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