INDIE UNPKG

8.39 kBJavaScriptView Raw
1/**
2 * react-router v8.5.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 } 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;
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 = router.match(path);
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, fetchImplementation = (request) => fetch(request), serverOrigin, isApiOnly = false) {
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, fetchImplementation, serverOrigin, isApiOnly);
58 };
59}
60function useFogOFWarDiscovery(router, manifest, routeModules, ssr, routeDiscovery, isSpaMode, fetchImplementation = (request) => fetch(request), serverOrigin, isApiOnly = false) {
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, void 0, fetchImplementation, serverOrigin, isApiOnly);
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 fetchImplementation,
107 serverOrigin,
108 isApiOnly
109 ]);
110}
111function getManifestPath(_manifestPath, basename) {
112 let manifestPath = _manifestPath || "/__manifest";
113 return basename == null ? manifestPath : joinPaths([basename, manifestPath]);
114}
115const MANIFEST_VERSION_STORAGE_KEY = "react-router-manifest-version";
116const MANIFEST_RELOAD_TIMEOUT = 5e3;
117let pendingManifestReload;
118async function handleClientVersionMismatch(needsReload, version, errorReloadPath) {
119 if (pendingManifestReload) return pendingManifestReload;
120 if (!needsReload) {
121 try {
122 sessionStorage.removeItem(MANIFEST_VERSION_STORAGE_KEY);
123 } catch {}
124 return false;
125 }
126 if (!errorReloadPath) {
127 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.");
128 return true;
129 }
130 let alreadyReloaded = false;
131 try {
132 alreadyReloaded = sessionStorage.getItem(MANIFEST_VERSION_STORAGE_KEY) === version;
133 if (!alreadyReloaded) sessionStorage.setItem(MANIFEST_VERSION_STORAGE_KEY, version);
134 } catch {}
135 if (alreadyReloaded) throw new Error("Unable to discover routes due to manifest version mismatch.");
136 let rejectReload;
137 let reloadPromise = new Promise((_, reject) => {
138 rejectReload = reject;
139 });
140 pendingManifestReload = reloadPromise;
141 let failReload = () => {
142 clearTimeout(timeout);
143 window.removeEventListener("pageshow", onPageShow);
144 pendingManifestReload = void 0;
145 rejectReload(/* @__PURE__ */ new Error("Unable to discover routes due to manifest version mismatch."));
146 };
147 let timeout = setTimeout(failReload, MANIFEST_RELOAD_TIMEOUT);
148 let onPageShow = (event) => {
149 if (event.persisted) failReload();
150 };
151 window.addEventListener("pageshow", onPageShow);
152 try {
153 window.location.href = errorReloadPath;
154 console.warn("Detected manifest version mismatch, reloading...");
155 } catch {
156 failReload();
157 }
158 return reloadPromise;
159}
160async function fetchAndApplyManifestPatches(paths, errorReloadPath, manifest, routeModules, ssr, isSpaMode, basename, manifestPath, patchRoutes, signal, fetchImplementation = (request) => fetch(request), serverOrigin, isApiOnly = false) {
161 paths = getPathsWithAncestors(paths);
162 const searchParams = new URLSearchParams();
163 searchParams.set("paths", paths.sort().join(","));
164 searchParams.set("version", manifest.version);
165 let url = new URL(getManifestPath(manifestPath, basename), serverOrigin ?? window.location.origin);
166 url.search = searchParams.toString();
167 if (url.toString().length > 7680) {
168 nextPaths.clear();
169 return;
170 }
171 let serverPatches;
172 try {
173 let res = await fetchImplementation(new Request(url, { signal }), { type: "manifest" });
174 if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
175 if (await handleClientVersionMismatch(res.status === 204 && res.headers.has("X-Remix-Reload-Document"), manifest.version, errorReloadPath)) return;
176 serverPatches = await res.json();
177 } catch (e) {
178 if (signal?.aborted) return;
179 throw e;
180 }
181 if (signal?.aborted) return;
182 let knownRoutes = new Set(Object.keys(manifest.routes));
183 let patches = Object.values(serverPatches).reduce((acc, route) => {
184 if (route && !knownRoutes.has(route.id)) acc[route.id] = route;
185 return acc;
186 }, {});
187 Object.assign(manifest.routes, patches);
188 paths.forEach((p) => addToFifoQueue(p, discoveredPaths));
189 let parentIds = /* @__PURE__ */ new Set();
190 Object.values(patches).forEach((patch) => {
191 if (patch && (!patch.parentId || !patches[patch.parentId])) parentIds.add(patch.parentId);
192 });
193 parentIds.forEach((parentId) => patchRoutes(parentId || null, createClientRoutes(patches, routeModules, null, ssr, isSpaMode, parentId, void 0, void 0, isApiOnly)));
194}
195function addToFifoQueue(path, queue) {
196 if (queue.size >= discoveredPathsMaxSize) {
197 let first = queue.values().next().value;
198 if (first !== void 0) queue.delete(first);
199 }
200 queue.add(path);
201}
202function debounce(callback, wait) {
203 let timeoutId;
204 return (...args) => {
205 window.clearTimeout(timeoutId);
206 timeoutId = window.setTimeout(() => callback(...args), wait);
207 };
208}
209//#endregion
210export { URL_LIMIT, getManifestPath, getPartialManifest, getPatchRoutesOnNavigationFunction, getPathsWithAncestors, handleClientVersionMismatch, isFogOfWarEnabled, useFogOFWarDiscovery };