next
Version:
The React Framework
174 lines (172 loc) • 11 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createInitialRouterState", {
enumerable: true,
get: function() {
return createInitialRouterState;
}
});
const _createhreffromurl = require("./create-href-from-url");
const _computechangedpath = require("./compute-changed-path");
const _rsctransport = require("../../../shared/lib/rsc-transport");
const _rendertree = require("../render-tree");
const _cache = require("../segment-cache/cache");
const _decodeserverresponse = require("../segment-cache/decode-server-response");
const _bfcache = require("../segment-cache/bfcache");
const _fetchserverresponse = require("./fetch-server-response");
const _optimisticroutes = require("../segment-cache/optimistic-routes");
function createInitialRouterState({ navigatedAt, initialRSCPayload, initialFlightStreamForCache, location }) {
const { c: initialCanonicalUrlParts, t: initialTransportData, q: initialRenderedSearch, i: initialCouldBeIntercepted, S: initialSupportsPerSegmentPrefetching, s: initialStaleTime, l: initialStaticStageByteLength, r: initialRootVaryParams, p: initialRuntimePrefetchStream, d: initialDynamicStaleTimeSeconds } = initialRSCPayload;
// 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 = initialCanonicalUrlParts.join('/');
// The initial router state tree, derived from the transport tree.
const initialTree = (0, _rsctransport.transportNodeToFlightRouterState)(initialTransportData.t, initialRenderedSearch);
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;
// Decode the initial transport data into the RouteTree type, with the
// payload's render output embedded on each node and the head as its own
// one-node tree. (discoverKnownRoute below stores the route tree in the
// route cache, which strips the data on write — see stripDataFromRouteTree.)
//
// For statically-generated-at-build-time HTML pages, the tree baked into
// the initial RSC payload won't have the correct segment inlining hints
// because those are computed after the pre-render. The server marks these
// trees with InliningHintsStale, which causes the route cache entry to be
// immediately expired. The next prefetch will re-fetch the tree with
// correct hints from the /_tree response.
const initialSeed = (0, _decodeserverresponse.createNavigationSeed)(navigatedAt, // There's no base tree to overlay onto; the initial payload is a full
// render from the root.
null, initialTransportData, // The initial payload may still be streaming in while we hydrate, so its
// vary params can't be drained here; they decode as null. The
// segment-cache write below re-decodes the transport data with the
// payload's root params once the stale time has resolved.
null, // Same for partiality: only segment-cache writes consume it, and the
// write below re-decodes with the payload's actual response-level value.
// Pass the conservative value here.
true, // The initial payload always includes the param values in the tree
// (fallback shells are patched with the parsed values before this runs —
// see createInitialRSCPayloadFromFallbackPrerender), so there's no
// pathname to parse them from.
null, initialRenderedSearch, null, initialDynamicStaleTimeSeconds ?? _bfcache.UnknownDynamicStaleTime);
const initialRoot = initialSeed.root;
const initialNavigation = (0, _rendertree.createInitialRenderTreeForHydration)(navigatedAt, initialRoot, initialSeed.dynamicStaleAt);
// The following only applies in the browser (location !== null) since neither
// route learning nor segment cache state persists from SSR to client.
if (location !== null) {
// Learn the route pattern so we can predict it for future navigations.
(0, _optimisticroutes.discoverKnownRoute)(Date.now(), location.pathname, location.search, null, null, initialRoot, initialCouldBeIntercepted, canonicalUrl, initialSeed.renderedSearch, initialSupportsPerSegmentPrefetching, false // hasDynamicRewrite
);
// TODO: Implement Shell extraction as part of Cached Navigations.
// Intentionally holding off on doing this until we decide how the Cached
// Navigations behavior should work in combination with App Shells.
// Write the initial payload's segment data into the segment cache so
// subsequent navigations to the initial page can serve cached
// segments instantly.
if (initialStaleTime !== undefined) {
if (initialStaticStageByteLength !== undefined && initialFlightStreamForCache != null) {
// Partially static page — truncate the cloned Flight stream at the
// static stage byte boundary, decode, and cache the static subset.
// Promise.resolve wraps the Flight-deserialized thenable into a
// native Promise so we can chain `.then` on it safely.
Promise.resolve(initialStaticStageByteLength).then(async (byteLength)=>{
if (byteLength === 0) {
initialFlightStreamForCache.cancel();
return;
}
const staticStageResponse = await (0, _fetchserverresponse.decodeStageUntilBoundary)(initialFlightStreamForCache, byteLength, undefined);
if (staticStageResponse === null) {
return;
}
(0, _cache.spawnStaticStageCacheWrite)(Date.now(), staticStageResponse, true, null, initialTree, initialRenderedSearch, _cache // hydration writes are bound to the shared map
.segmentCacheMap);
}).catch(()=>{
// The static stage processing failed. Not fatal — the page
// rendered normally, we just won't write into the cache.
});
} else {
// Fully static page — cache the initial payload's segment data as-is.
// We're not using the initial response here (which would allow us to
// combine the two branches) to avoid unnecessary decoding of the
// Flight data, since we can just take the segment data that we
// already decoded during hydration and write it into the
// cache directly.
(0, _cache.spawnStaticStageCacheWrite)(Date.now(), // The transport subset of the initial payload, already decoded
// during hydration. `u` (the runtime-data verdict) is deliberately
// omitted from this synthesized subset — its writes record their
// strategy unrefined — while the truncated branch above forwards
// the decoded payload's own `u`.
{
t: initialTransportData,
r: initialRootVaryParams,
s: initialStaleTime
}, false, null, initialTree, initialRenderedSearch, _cache // hydration writes are bound to the shared map
.segmentCacheMap);
// Cancel the stream clone — fully static path doesn't need it.
initialFlightStreamForCache?.cancel();
}
} else {
// No caching — cancel the unused stream clone.
initialFlightStreamForCache?.cancel();
}
// If the initial RSC payload includes an embedded runtime prefetch stream,
// decode it and write the runtime data into the segment cache. This allows
// subsequent navigations to serve runtime-prefetchable content from cache
// without a separate prefetch request.
if (initialRuntimePrefetchStream != null) {
(0, _cache.writeRuntimePrefetchStreamIntoCache)(Date.now(), initialRuntimePrefetchStream, initialTree, initialRenderedSearch, _cache // hydration writes are bound to the shared map
.segmentCacheMap).catch(()=>{
// Runtime prefetch cache write failed. Not fatal — the page rendered
// normally, we just won't cache runtime data.
});
}
}
// NOTE: We intentionally don't check if any data needs to be fetched from the
// server. We assume the initial hydration payload is sufficient to render
// the page.
//
// The completeness of the initial data is an important property that we rely
// on as a last-ditch mechanism for recovering the app; we must always be able
// to reload a fresh HTML document to get to a consistent state.
//
// In the future, there may be cases where the server intentionally sends
// partial data and expects the client to fill in the rest, in which case this
// logic may change. (There already is a similar case where the server sends
// _no_ hydration data in the HTML document at all, and the client fetches it
// separately, but that's different because we still end up hydrating with a
// complete tree.)
const initialState = {
tree: initialNavigation.tree.route,
root: (0, _cache.createRootRouteTree)(initialNavigation.tree.node, initialNavigation.head.node),
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
},
scrollRef: {
scrollRef: null,
forceScroll: false,
onlyHashChange: false,
hashFragment: null
},
canonicalUrl,
renderedSearch: initialRenderedSearch,
// the || operator is intentional, the pathname can be an empty string
nextUrl: ((0, _computechangedpath.extractPathFromFlightRouterState)(initialTree) || location?.pathname) ?? null,
previousNextUrl: null,
debugInfo: null
};
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