UNPKG

7.18 kBJavaScriptView Raw
1/**
2 * react-router v8.3.0
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11import { createPath } from "../../router/history.js";
12import { joinPaths, matchRoutesImpl } from "../../router/utils.js";
13import { createClientRoutes } from "./routes.js";
14import * as React$1 from "react";
15//#region lib/dom/ssr/fog-of-war.ts
16const nextPaths = /* @__PURE__ */ new Set();
17const discoveredPathsMaxSize = 1e3;
18const discoveredPaths = /* @__PURE__ */ new Set();
19const URL_LIMIT = 7680;
20function getPathsWithAncestors(paths) {
21 let result = /* @__PURE__ */ new Set();
22 paths.forEach((path) => {
23 if (!path.startsWith("/")) path = `/${path}`;
24 for (let i = 1; i < path.length; i++) if (path[i] === "/") result.add(path.slice(0, i));
25 result.add(path);
26 });
27 return Array.from(result);
28}
29function isFogOfWarEnabled(routeDiscovery, ssr) {
30 return routeDiscovery.mode === "lazy" && ssr === true;
31}
32function getPartialManifest({ sri, ...manifest }, router) {
33 let routeIds = new Set(router.state.matches.map((m) => m.route.id));
34 let segments = router.state.location.pathname.split("/").filter(Boolean);
35 let paths = ["/"];
36 segments.pop();
37 while (segments.length > 0) {
38 paths.push(`/${segments.join("/")}`);
39 segments.pop();
40 }
41 paths.forEach((path) => {
42 let matches = matchRoutesImpl(router.routes, path, router.basename || "/", false, router.branches);
43 if (matches) matches.forEach((m) => routeIds.add(m.route.id));
44 });
45 let initialRoutes = [...routeIds].reduce((acc, id) => Object.assign(acc, { [id]: manifest.routes[id] }), {});
46 return {
47 ...manifest,
48 routes: initialRoutes,
49 sri: sri ? true : void 0
50 };
51}
52function getPatchRoutesOnNavigationFunction(getRouter, manifest, routeModules, ssr, routeDiscovery, isSpaMode, basename) {
53 if (!isFogOfWarEnabled(routeDiscovery, ssr)) return;
54 return async ({ path, patch, signal, fetcherKey }) => {
55 if (discoveredPaths.has(path)) return;
56 let { state } = getRouter();
57 await fetchAndApplyManifestPatches([path], fetcherKey ? window.location.href : createPath(state.navigation.location || state.location), manifest, routeModules, ssr, isSpaMode, basename, routeDiscovery.manifestPath, patch, signal);
58 };
59}
60function useFogOFWarDiscovery(router, manifest, routeModules, ssr, routeDiscovery, isSpaMode) {
61 React$1.useEffect(() => {
62 if (!isFogOfWarEnabled(routeDiscovery, ssr) || window.navigator?.connection?.saveData === true) return;
63 function registerElement(el) {
64 let path = el.tagName === "FORM" ? el.getAttribute("action") : el.getAttribute("href");
65 if (!path) return;
66 let pathname = el.tagName === "A" ? el.pathname : new URL(path, window.location.origin).pathname;
67 if (!discoveredPaths.has(pathname)) nextPaths.add(pathname);
68 }
69 async function fetchPatches() {
70 document.querySelectorAll("a[data-discover], form[data-discover]").forEach(registerElement);
71 let lazyPaths = Array.from(nextPaths.keys()).filter((path) => {
72 if (discoveredPaths.has(path)) {
73 nextPaths.delete(path);
74 return false;
75 }
76 return true;
77 });
78 if (lazyPaths.length === 0) return;
79 try {
80 await fetchAndApplyManifestPatches(lazyPaths, null, manifest, routeModules, ssr, isSpaMode, router.basename, routeDiscovery.manifestPath, router.patchRoutes);
81 } catch (e) {
82 console.error("Failed to fetch manifest patches", e);
83 }
84 }
85 let debouncedFetchPatches = debounce(fetchPatches, 100);
86 fetchPatches();
87 let observer = new MutationObserver(() => debouncedFetchPatches());
88 observer.observe(document.documentElement, {
89 subtree: true,
90 childList: true,
91 attributes: true,
92 attributeFilter: [
93 "data-discover",
94 "href",
95 "action"
96 ]
97 });
98 return () => observer.disconnect();
99 }, [
100 ssr,
101 isSpaMode,
102 manifest,
103 routeModules,
104 router,
105 routeDiscovery
106 ]);
107}
108function getManifestPath(_manifestPath, basename) {
109 let manifestPath = _manifestPath || "/__manifest";
110 return basename == null ? manifestPath : joinPaths([basename, manifestPath]);
111}
112const MANIFEST_VERSION_STORAGE_KEY = "react-router-manifest-version";
113async function handleClientVersionMismatch(needsReload, version, errorReloadPath) {
114 if (!needsReload) {
115 try {
116 sessionStorage.removeItem(MANIFEST_VERSION_STORAGE_KEY);
117 } catch {}
118 return false;
119 }
120 if (!errorReloadPath) {
121 console.warn("Detected a manifest version mismatch during eager route discovery. The next navigation/fetch to an undiscovered route will result in a new document navigation to sync up with the latest manifest.");
122 return true;
123 }
124 try {
125 if (sessionStorage.getItem(MANIFEST_VERSION_STORAGE_KEY) === version) {
126 console.error("Unable to discover routes due to manifest version mismatch.");
127 return true;
128 }
129 sessionStorage.setItem(MANIFEST_VERSION_STORAGE_KEY, version);
130 } catch {}
131 window.location.href = errorReloadPath;
132 console.warn("Detected manifest version mismatch, reloading...");
133 await new Promise(() => {});
134 return true;
135}
136async function fetchAndApplyManifestPatches(paths, errorReloadPath, manifest, routeModules, ssr, isSpaMode, basename, manifestPath, patchRoutes, signal) {
137 paths = getPathsWithAncestors(paths);
138 const searchParams = new URLSearchParams();
139 searchParams.set("paths", paths.sort().join(","));
140 searchParams.set("version", manifest.version);
141 let url = new URL(getManifestPath(manifestPath, basename), window.location.origin);
142 url.search = searchParams.toString();
143 if (url.toString().length > 7680) {
144 nextPaths.clear();
145 return;
146 }
147 let serverPatches;
148 try {
149 let res = await fetch(url, { signal });
150 if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
151 if (await handleClientVersionMismatch(res.status === 204 && res.headers.has("X-Remix-Reload-Document"), manifest.version, errorReloadPath)) return;
152 serverPatches = await res.json();
153 } catch (e) {
154 if (signal?.aborted) return;
155 throw e;
156 }
157 let knownRoutes = new Set(Object.keys(manifest.routes));
158 let patches = Object.values(serverPatches).reduce((acc, route) => {
159 if (route && !knownRoutes.has(route.id)) acc[route.id] = route;
160 return acc;
161 }, {});
162 Object.assign(manifest.routes, patches);
163 paths.forEach((p) => addToFifoQueue(p, discoveredPaths));
164 let parentIds = /* @__PURE__ */ new Set();
165 Object.values(patches).forEach((patch) => {
166 if (patch && (!patch.parentId || !patches[patch.parentId])) parentIds.add(patch.parentId);
167 });
168 parentIds.forEach((parentId) => patchRoutes(parentId || null, createClientRoutes(patches, routeModules, null, ssr, isSpaMode, parentId)));
169}
170function addToFifoQueue(path, queue) {
171 if (queue.size >= discoveredPathsMaxSize) {
172 let first = queue.values().next().value;
173 if (first !== void 0) queue.delete(first);
174 }
175 queue.add(path);
176}
177function debounce(callback, wait) {
178 let timeoutId;
179 return (...args) => {
180 window.clearTimeout(timeoutId);
181 timeoutId = window.setTimeout(() => callback(...args), wait);
182 };
183}
184//#endregion
185export { URL_LIMIT, getManifestPath, getPartialManifest, getPatchRoutesOnNavigationFunction, getPathsWithAncestors, handleClientVersionMismatch, isFogOfWarEnabled, useFogOFWarDiscovery };