UNPKG

24.9 kBJavaScriptView Raw
1/**
2 * react-router v8.5.2
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 { PROTOCOL_RELATIVE_URL_REGEX } from "../router/url.js";
12import { createBrowserHistory, createPath, invariant } from "../router/history.js";
13import { validateNavigationTarget } from "../router/navigation.js";
14import { ErrorResponseImpl, createContext, resolvePath } from "../router/utils.js";
15import { createRouter, hasInvalidProtocol, isMutationMethod } from "../router/router.js";
16import { RSCRouterContext } from "../context.js";
17import { createRequestInit } from "../dom/ssr/data.js";
18import { getSingleFetchDataStrategyImpl, singleFetchUrl, stripIndexParam } from "../dom/ssr/single-fetch.js";
19import { noActionDefinedError, shouldHydrateRouteLoader } from "../dom/ssr/routes.js";
20import { getManifestPathsParam, getPathsWithAncestors, handleClientVersionMismatch } from "../dom/ssr/fog-of-war.js";
21import { FrameworkContext, setIsHydrated } from "../dom/ssr/components.js";
22import { RouterProvider } from "../components.js";
23import { RSCRouterGlobalErrorBoundary } from "./errorBoundaries.js";
24import { populateRSCRouteModules } from "./route-modules.js";
25import { getHydrationData } from "../dom/ssr/hydration.js";
26import * as React$1 from "react";
27import * as ReactDOM from "react-dom";
28//#region lib/rsc/browser.tsx
29const defaultManifestPath = "/__manifest";
30/**
31* Create a React `callServer` implementation for React Router.
32*
33* @example
34* import {
35* createFromReadableStream,
36* createTemporaryReferenceSet,
37* encodeReply,
38* setServerCallback,
39* } from "@vitejs/plugin-rsc/browser";
40* import { unstable_createCallServer as createCallServer } from "react-router";
41*
42* setServerCallback(
43* createCallServer({
44* createFromReadableStream,
45* createTemporaryReferenceSet,
46* encodeReply,
47* })
48* );
49*
50* @name unstable_createCallServer
51* @public
52* @category RSC
53* @mode data
54* @param opts Options
55* @param opts.createFromReadableStream Your `react-server-dom-xyz/client`'s
56* `createFromReadableStream`. Used to decode payloads from the server.
57* @param opts.createTemporaryReferenceSet A function that creates a temporary
58* reference set for the [RSC](https://react.dev/reference/rsc/server-components)
59* payload.
60* @param opts.encodeReply Your `react-server-dom-xyz/client`'s `encodeReply`.
61* Used when sending payloads to the server.
62* @param opts.fetch Optional [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
63* implementation. Defaults to global [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch).
64* @returns A function that can be used to call server actions.
65*/
66function createCallServer({ createFromReadableStream, createTemporaryReferenceSet, encodeReply, fetch: fetchImplementation = fetch }) {
67 const globalVar = window;
68 let landedActionId = 0;
69 return async (id, args) => {
70 let actionId = globalVar.__routerActionID = (globalVar.__routerActionID ??= 0) + 1;
71 const temporaryReferences = createTemporaryReferenceSet();
72 const payloadPromise = fetchImplementation(new Request(location.href, {
73 body: await encodeReply(args, { temporaryReferences }),
74 method: "POST",
75 headers: {
76 Accept: "text/x-component",
77 "rsc-action-id": id
78 }
79 })).then((response) => {
80 if (!response.body) throw new Error("No response body");
81 return createFromReadableStream(response.body, { temporaryReferences });
82 });
83 React$1.startTransition(() => Promise.resolve(payloadPromise).then(async (payload) => {
84 if (payload.type === "redirect") {
85 let location = normalizeRedirectLocation(payload.location);
86 validateNavigationTarget(payload.location, location, new URL(window.location.href), "allow-explicit");
87 if (payload.reload || isExternalLocation(location)) {
88 if (hasInvalidProtocol(location)) throw new Error("Invalid redirect location");
89 window.location.href = location;
90 return;
91 }
92 React$1.startTransition(() => {
93 globalVar.__reactRouterDataRouter.navigate(location, { replace: payload.replace });
94 });
95 return;
96 }
97 if (payload.type !== "action") throw new Error("Unexpected payload type");
98 const rerender = await payload.rerender;
99 if (rerender && landedActionId < actionId && globalVar.__routerActionID <= actionId) {
100 if (rerender.type === "redirect") {
101 let location = normalizeRedirectLocation(rerender.location);
102 validateNavigationTarget(rerender.location, location, new URL(window.location.href), "allow-explicit");
103 if (rerender.reload || isExternalLocation(location)) {
104 if (hasInvalidProtocol(location)) throw new Error("Invalid redirect location");
105 window.location.href = location;
106 return;
107 }
108 React$1.startTransition(() => {
109 globalVar.__reactRouterDataRouter.navigate(location, { replace: rerender.replace });
110 });
111 return;
112 }
113 React$1.startTransition(() => {
114 let lastMatch;
115 for (const match of rerender.matches) {
116 globalVar.__reactRouterDataRouter.patchRoutes(lastMatch?.id ?? null, [createRouteFromServerManifest(match)], true);
117 lastMatch = match;
118 }
119 window.__reactRouterDataRouter._internalSetStateDoNotUseOrYouWillBreakYourApp({
120 loaderData: Object.assign({}, globalVar.__reactRouterDataRouter.state.loaderData, rerender.loaderData),
121 errors: rerender.errors ? Object.assign({}, globalVar.__reactRouterDataRouter.state.errors, rerender.errors) : null
122 });
123 });
124 }
125 }).catch(() => {}));
126 return payloadPromise.then((payload) => {
127 if (payload.type !== "action" && payload.type !== "redirect") throw new Error("Unexpected payload type");
128 return payload.actionResult;
129 });
130 };
131}
132function createRouterFromPayload({ fetchImplementation, createFromReadableStream, getContext, payload }) {
133 const globalVar = window;
134 if (globalVar.__reactRouterDataRouter && globalVar.__reactRouterRouteModules) return {
135 router: globalVar.__reactRouterDataRouter,
136 routeModules: globalVar.__reactRouterRouteModules
137 };
138 if (payload.type !== "render") throw new Error("Invalid payload type");
139 let { clientVersion } = payload;
140 globalVar.__reactRouterRouteModules = globalVar.__reactRouterRouteModules ?? {};
141 populateRSCRouteModules(globalVar.__reactRouterRouteModules, payload.matches);
142 let routes = payload.matches.reduceRight((previous, match) => {
143 const route = createRouteFromServerManifest(match, payload);
144 if (previous.length > 0) route.children = previous;
145 else if (!route.index) route.children = [];
146 return [route];
147 }, []);
148 let applyPatchesPromise;
149 globalVar.__reactRouterDataRouter = createRouter({
150 routes,
151 getContext,
152 basename: payload.basename,
153 history: createBrowserHistory(),
154 hydrationData: getHydrationData({
155 state: {
156 loaderData: payload.loaderData,
157 actionData: payload.actionData,
158 errors: payload.errors
159 },
160 routes,
161 getRouteInfo: (routeId) => {
162 let match = payload.matches.find((m) => m.id === routeId);
163 invariant(match, "Route not found in payload");
164 return {
165 clientLoader: match.clientLoader,
166 clientMiddleware: match.clientMiddleware,
167 hasLoader: match.hasLoader,
168 hasHydrateFallback: match.hydrateFallbackElement != null
169 };
170 },
171 location: payload.location,
172 basename: payload.basename,
173 future: {},
174 isSpaMode: false
175 }),
176 async patchRoutesOnNavigation({ path, signal, fetcherKey }) {
177 if (payload.routeDiscovery.mode === "initial") {
178 if (!applyPatchesPromise) applyPatchesPromise = (async () => {
179 if (!payload.patches) return;
180 let patches = await payload.patches;
181 React$1.startTransition(() => {
182 patches.forEach((p) => {
183 window.__reactRouterDataRouter.patchRoutes(p.parentId ?? null, [createRouteFromServerManifest(p)]);
184 });
185 });
186 })();
187 await applyPatchesPromise;
188 return;
189 }
190 if (discoveredPaths.has(path)) return;
191 let { state } = globalVar.__reactRouterDataRouter;
192 await fetchAndApplyManifestPatches([path], createFromReadableStream, fetchImplementation, clientVersion, fetcherKey ? window.location.href : createPath(state.navigation.location || state.location), signal);
193 },
194 dataStrategy: getRSCSingleFetchDataStrategy(() => globalVar.__reactRouterDataRouter, true, createFromReadableStream, fetchImplementation, clientVersion)
195 });
196 if (globalVar.__reactRouterDataRouter.state.initialized) {
197 globalVar.__routerInitialized = true;
198 globalVar.__reactRouterDataRouter.initialize();
199 } else globalVar.__routerInitialized = false;
200 let lastLoaderData = void 0;
201 globalVar.__reactRouterDataRouter.subscribe(({ loaderData, actionData }) => {
202 if (lastLoaderData !== loaderData) globalVar.__routerActionID = (globalVar.__routerActionID ??= 0) + 1;
203 });
204 globalVar.__reactRouterDataRouter._updateRoutesForHMR = (routeUpdateByRouteId) => {
205 const oldRoutes = window.__reactRouterDataRouter.routes;
206 const newRoutes = [];
207 function walkRoutes(routes, parentId) {
208 return routes.map((route) => {
209 const routeUpdate = routeUpdateByRouteId.get(route.id);
210 if (routeUpdate) {
211 const { routeModule, hasAction, hasComponent, hasLoader, hasClientMiddleware } = routeUpdate;
212 const newRoute = createRouteFromServerManifest({
213 clientAction: routeModule.clientAction,
214 clientLoader: routeModule.clientLoader,
215 clientMiddleware: hasClientMiddleware ? routeModule.clientMiddleware ?? route.middleware : void 0,
216 element: route.element,
217 errorElement: route.errorElement,
218 handle: route.handle,
219 hasAction,
220 hasComponent,
221 hasLoader,
222 hydrateFallbackElement: route.hydrateFallbackElement,
223 id: route.id,
224 index: route.index,
225 links: routeModule.links,
226 meta: routeModule.meta,
227 parentId,
228 path: route.path,
229 shouldRevalidate: routeModule.shouldRevalidate
230 });
231 if (route.children) newRoute.children = walkRoutes(route.children, route.id);
232 return newRoute;
233 }
234 const updatedRoute = { ...route };
235 if (route.children) updatedRoute.children = walkRoutes(route.children, route.id);
236 return updatedRoute;
237 });
238 }
239 newRoutes.push(...walkRoutes(oldRoutes, void 0));
240 window.__reactRouterDataRouter._internalSetRoutes(newRoutes);
241 };
242 return {
243 router: globalVar.__reactRouterDataRouter,
244 routeModules: globalVar.__reactRouterRouteModules
245 };
246}
247const renderedRoutesContext = createContext();
248function getRSCSingleFetchDataStrategy(getRouter, ssr, createFromReadableStream, fetchImplementation, clientVersion) {
249 let dataStrategy = getSingleFetchDataStrategyImpl(getRouter, (match) => {
250 let M = match;
251 return {
252 hasLoader: M.route.hasLoader,
253 hasClientLoader: M.route.hasClientLoader
254 };
255 }, getFetchAndDecodeViaRSC(getRouter, createFromReadableStream, fetchImplementation, clientVersion), ssr, (match) => {
256 let M = match;
257 return !M.route.hasComponent || M.route.element != null;
258 });
259 return async (args) => args.runClientMiddleware(async () => {
260 args.context.set(renderedRoutesContext, []);
261 let results = await dataStrategy(args);
262 const renderedRoutesById = /* @__PURE__ */ new Map();
263 for (const route of args.context.get(renderedRoutesContext)) {
264 if (!renderedRoutesById.has(route.id)) renderedRoutesById.set(route.id, []);
265 renderedRoutesById.get(route.id).push(route);
266 }
267 React$1.startTransition(() => {
268 for (const match of args.matches) {
269 const renderedRoutes = renderedRoutesById.get(match.route.id);
270 if (renderedRoutes) for (const rendered of renderedRoutes) window.__reactRouterDataRouter.patchRoutes(rendered.parentId ?? null, [createRouteFromServerManifest(rendered)], true);
271 }
272 });
273 return results;
274 });
275}
276function getFetchAndDecodeViaRSC(getRouter, createFromReadableStream, fetchImplementation, clientVersion) {
277 return async (args, targetRoutes) => {
278 let { request, context } = args;
279 let url = singleFetchUrl(request.url, "rsc");
280 if (request.method === "GET") {
281 url = stripIndexParam(url);
282 if (targetRoutes) url.searchParams.set("_routes", targetRoutes.join(","));
283 }
284 let res = await fetchImplementation(new Request(url, await createRequestInit(request)));
285 if (res.status >= 400 && !res.headers.has("X-Remix-Response")) throw new ErrorResponseImpl(res.status, res.statusText, await res.text());
286 invariant(res.body, "No response body to decode");
287 try {
288 const payload = await createFromReadableStream(res.body, { temporaryReferences: void 0 });
289 if (payload.type === "redirect") return {
290 status: res.status,
291 data: { redirect: {
292 redirect: payload.location,
293 reload: payload.reload,
294 replace: payload.replace,
295 revalidate: false,
296 status: payload.status
297 } }
298 };
299 if (payload.type !== "render") throw new Error("Unexpected payload type");
300 if (clientVersion !== void 0 && await handleClientVersionMismatch(payload.clientVersion !== clientVersion, clientVersion, createPath(getRouter().state.navigation.location || getRouter().state.location))) return new Promise(() => {});
301 context.get(renderedRoutesContext).push(...payload.matches);
302 let results = { routes: {} };
303 const dataKey = isMutationMethod(request.method) ? "actionData" : "loaderData";
304 for (let [routeId, data] of Object.entries(payload[dataKey] || {})) results.routes[routeId] = { data };
305 if (payload.errors) for (let [routeId, error] of Object.entries(payload.errors)) results.routes[routeId] = { error };
306 return {
307 status: res.status,
308 data: results
309 };
310 } catch (cause) {
311 throw new Error("Unable to decode RSC response", { cause });
312 }
313 };
314}
315/**
316* Hydrates a server rendered {@link unstable_RSCPayload} in the browser.
317*
318* @example
319* import { startTransition, StrictMode } from "react";
320* import { hydrateRoot } from "react-dom/client";
321* import {
322* unstable_getRSCStream as getRSCStream,
323* unstable_RSCHydratedRouter as RSCHydratedRouter,
324* } from "react-router";
325* import type { unstable_RSCPayload as RSCPayload } from "react-router";
326*
327* createFromReadableStream(getRSCStream()).then((payload) =>
328* startTransition(async () => {
329* hydrateRoot(
330* document,
331* <StrictMode>
332* <RSCHydratedRouter
333* createFromReadableStream={createFromReadableStream}
334* payload={payload}
335* />
336* </StrictMode>,
337* { formState: await getFormState(payload) },
338* );
339* }),
340* );
341*
342* @name unstable_RSCHydratedRouter
343* @public
344* @category RSC
345* @mode data
346* @param props Props
347* @param {unstable_RSCHydratedRouterProps.createFromReadableStream} props.createFromReadableStream n/a
348* @param {unstable_RSCHydratedRouterProps.fetch} props.fetch n/a
349* @param {unstable_RSCHydratedRouterProps.getContext} props.getContext n/a
350* @param {unstable_RSCHydratedRouterProps.payload} props.payload n/a
351* @returns A hydrated {@link DataRouter} that can be used to navigate and
352* render routes.
353*/
354function RSCHydratedRouter({ createFromReadableStream, fetch: fetchImplementation = fetch, payload, getContext }) {
355 if (payload.type !== "render") throw new Error("Invalid payload type");
356 let { routeDiscovery, clientVersion } = payload;
357 let { router, routeModules } = React$1.useMemo(() => createRouterFromPayload({
358 payload,
359 fetchImplementation,
360 getContext,
361 createFromReadableStream
362 }), [
363 createFromReadableStream,
364 payload,
365 fetchImplementation,
366 getContext
367 ]);
368 React$1.useEffect(() => {
369 setIsHydrated();
370 }, []);
371 React$1.useLayoutEffect(() => {
372 const globalVar = window;
373 if (!globalVar.__routerInitialized) {
374 globalVar.__routerInitialized = true;
375 globalVar.__reactRouterDataRouter.initialize();
376 }
377 }, []);
378 let [{ routes, state }, setState] = React$1.useState(() => ({
379 routes: cloneRoutes(router.routes),
380 state: router.state
381 }));
382 React$1.useLayoutEffect(() => router.subscribe((newState) => {
383 if (diffRoutes(router.routes, routes)) React$1.startTransition(() => {
384 setState({
385 routes: cloneRoutes(router.routes),
386 state: newState
387 });
388 });
389 }), [
390 router.subscribe,
391 routes,
392 router
393 ]);
394 React$1.useLayoutEffect(() => {
395 if (state.initialized) return;
396 let unsubscribe = () => {};
397 unsubscribe = router.subscribe((newState) => {
398 if (newState.initialized) {
399 unsubscribe();
400 React$1.startTransition(() => {
401 setState((current) => current.state.initialized ? current : {
402 ...current,
403 state: newState
404 });
405 });
406 }
407 });
408 return unsubscribe;
409 }, [
410 router.subscribe,
411 router,
412 state.initialized
413 ]);
414 const transitionEnabledRouter = React$1.useMemo(() => ({
415 ...router,
416 state,
417 routes
418 }), [
419 router,
420 routes,
421 state
422 ]);
423 React$1.useEffect(() => {
424 if (routeDiscovery.mode === "initial" || window.navigator?.connection?.saveData === true) return;
425 function registerElement(el) {
426 let path = el.tagName === "FORM" ? el.getAttribute("action") : el.getAttribute("href");
427 if (!path) return;
428 let pathname = el.tagName === "A" ? el.pathname : new URL(path, window.location.origin).pathname;
429 if (!discoveredPaths.has(pathname)) nextPaths.add(pathname);
430 }
431 async function fetchPatches() {
432 document.querySelectorAll("a[data-discover], form[data-discover]").forEach(registerElement);
433 let paths = Array.from(nextPaths.keys()).filter((path) => {
434 if (discoveredPaths.has(path)) {
435 nextPaths.delete(path);
436 return false;
437 }
438 return true;
439 });
440 if (paths.length === 0) return;
441 try {
442 await fetchAndApplyManifestPatches(paths, createFromReadableStream, fetchImplementation, clientVersion, null);
443 } catch (e) {
444 console.error("Failed to fetch manifest patches", e);
445 }
446 }
447 let debouncedFetchPatches = debounce(fetchPatches, 100);
448 fetchPatches();
449 new MutationObserver(() => debouncedFetchPatches()).observe(document.documentElement, {
450 subtree: true,
451 childList: true,
452 attributes: true,
453 attributeFilter: [
454 "data-discover",
455 "href",
456 "action"
457 ]
458 });
459 }, [
460 routeDiscovery,
461 createFromReadableStream,
462 fetchImplementation,
463 clientVersion
464 ]);
465 const frameworkContext = {
466 future: {},
467 isSpaMode: false,
468 ssr: true,
469 criticalCss: "",
470 manifest: {
471 routes: {},
472 version: "1",
473 url: "",
474 entry: {
475 module: "",
476 imports: []
477 }
478 },
479 routeDiscovery: payload.routeDiscovery.mode === "initial" ? {
480 mode: "initial",
481 manifestPath: defaultManifestPath
482 } : {
483 mode: "lazy",
484 manifestPath: payload.routeDiscovery.manifestPath || defaultManifestPath
485 },
486 routeModules
487 };
488 return /* @__PURE__ */ React$1.createElement(RSCRouterContext.Provider, { value: true }, /* @__PURE__ */ React$1.createElement(RSCRouterGlobalErrorBoundary, { location: state.location }, /* @__PURE__ */ React$1.createElement(FrameworkContext.Provider, { value: frameworkContext }, /* @__PURE__ */ React$1.createElement(RouterProvider, {
489 router: transitionEnabledRouter,
490 flushSync: ReactDOM.flushSync
491 }))));
492}
493function createRouteFromServerManifest(match, payload) {
494 let hasInitialData = payload && match.id in payload.loaderData;
495 let initialData = payload?.loaderData[match.id];
496 let hasInitialError = payload?.errors && match.id in payload.errors;
497 let initialError = payload?.errors?.[match.id];
498 let isHydrationRequest = match.clientLoader?.hydrate === true || !match.hasLoader || match.hasComponent && !match.element;
499 invariant(window.__reactRouterRouteModules);
500 populateRSCRouteModules(window.__reactRouterRouteModules, match);
501 let dataRoute = {
502 id: match.id,
503 element: match.element,
504 errorElement: match.errorElement,
505 handle: match.handle,
506 hydrateFallbackElement: match.hydrateFallbackElement,
507 index: match.index,
508 loader: match.clientLoader ? async (args, singleFetch) => {
509 let _isHydrationRequest = isHydrationRequest;
510 isHydrationRequest = false;
511 return await match.clientLoader({
512 ...args,
513 serverLoader: () => {
514 preventInvalidServerHandlerCall("loader", match.id, match.hasLoader);
515 if (_isHydrationRequest) {
516 if (hasInitialData) return initialData;
517 if (hasInitialError) throw initialError;
518 }
519 return callSingleFetch(singleFetch);
520 }
521 });
522 } : (_, singleFetch) => callSingleFetch(singleFetch),
523 action: match.clientAction ? (args, singleFetch) => match.clientAction({
524 ...args,
525 serverAction: async () => {
526 preventInvalidServerHandlerCall("action", match.id, match.hasLoader);
527 return await callSingleFetch(singleFetch);
528 }
529 }) : match.hasAction ? (_, singleFetch) => callSingleFetch(singleFetch) : () => {
530 throw noActionDefinedError("action", match.id);
531 },
532 path: match.path,
533 middleware: match.clientMiddleware,
534 shouldRevalidate: match.shouldRevalidate,
535 hasLoader: true,
536 hasClientLoader: match.clientLoader != null,
537 hasComponent: match.hasComponent,
538 hasAction: match.hasAction,
539 hasClientAction: match.clientAction != null
540 };
541 if (typeof dataRoute.loader === "function") dataRoute.loader.hydrate = shouldHydrateRouteLoader(match.id, match.clientLoader, match.hasLoader, false);
542 return dataRoute;
543}
544function callSingleFetch(singleFetch) {
545 invariant(typeof singleFetch === "function", "Invalid singleFetch parameter");
546 return singleFetch();
547}
548function preventInvalidServerHandlerCall(type, routeId, hasHandler) {
549 if (!hasHandler) {
550 let msg = `You are trying to call ${type === "action" ? "serverAction()" : "serverLoader()"} on a route that does not have a server ${type} (routeId: "${routeId}")`;
551 console.error(msg);
552 throw new ErrorResponseImpl(400, "Bad Request", new Error(msg), true);
553 }
554}
555const nextPaths = /* @__PURE__ */ new Set();
556const discoveredPathsMaxSize = 1e3;
557const discoveredPaths = /* @__PURE__ */ new Set();
558function getManifestUrl(paths, clientVersion) {
559 if (paths.length === 0) return null;
560 let url;
561 if (paths.length === 1) url = new URL(`${paths[0]}.manifest`, window.location.origin);
562 else {
563 let basename = (window.__reactRouterDataRouter.basename ?? "").replace(/^\/|\/$/g, "");
564 url = new URL(`${basename}/.manifest`, window.location.origin);
565 url.searchParams.set("paths", getManifestPathsParam(paths));
566 }
567 if (clientVersion !== void 0) url.searchParams.set("version", clientVersion);
568 return url;
569}
570async function fetchAndApplyManifestPatches(paths, createFromReadableStream, fetchImplementation, clientVersion, errorReloadPath, signal) {
571 paths = getPathsWithAncestors(paths);
572 let url = getManifestUrl(paths, clientVersion);
573 if (url == null) return;
574 if (url.toString().length > 7680) {
575 nextPaths.clear();
576 return;
577 }
578 let response = await fetchImplementation(new Request(url, { signal }));
579 if (clientVersion !== void 0 && response.status === 204 && response.headers.has("X-Remix-Reload-Document")) {
580 await handleClientVersionMismatch(true, clientVersion, errorReloadPath);
581 return;
582 }
583 if (!response.body || response.status < 200 || response.status >= 300) throw new Error("Unable to fetch new route matches from the server");
584 let payload = await createFromReadableStream(response.body, { temporaryReferences: void 0 });
585 if (payload.type !== "manifest") throw new Error("Failed to patch routes");
586 paths.forEach((p) => addToFifoQueue(p, discoveredPaths));
587 let patches = await payload.patches;
588 React$1.startTransition(() => {
589 patches.forEach((p) => {
590 window.__reactRouterDataRouter.patchRoutes(p.parentId ?? null, [createRouteFromServerManifest(p)]);
591 });
592 });
593}
594function addToFifoQueue(path, queue) {
595 if (queue.size >= discoveredPathsMaxSize) {
596 let first = queue.values().next().value;
597 if (typeof first === "string") queue.delete(first);
598 }
599 queue.add(path);
600}
601function debounce(callback, wait) {
602 let timeoutId;
603 return (...args) => {
604 window.clearTimeout(timeoutId);
605 timeoutId = window.setTimeout(() => callback(...args), wait);
606 };
607}
608function isExternalLocation(location) {
609 return new URL(location, window.location.href).origin !== window.location.origin;
610}
611function normalizeRedirectLocation(location) {
612 if (PROTOCOL_RELATIVE_URL_REGEX.test(location)) {
613 let path = resolvePath(location);
614 return path.pathname + path.search + path.hash;
615 }
616 return location;
617}
618function cloneRoutes(routes) {
619 if (!routes) return void 0;
620 return routes.map((route) => ({
621 ...route,
622 children: cloneRoutes(route.children)
623 }));
624}
625function diffRoutes(a, b) {
626 if (a.length !== b.length) return true;
627 return a.some((route, index) => {
628 if (route.element !== b[index].element) return true;
629 if (route.errorElement !== b[index].errorElement) return true;
630 if (route.hydrateFallbackElement !== b[index].hydrateFallbackElement) return true;
631 if (route.hasLoader !== b[index].hasLoader) return true;
632 if (route.hasClientLoader !== b[index].hasClientLoader) return true;
633 if (route.hasAction !== b[index].hasAction) return true;
634 if (route.hasClientAction !== b[index].hasClientAction) return true;
635 return diffRoutes(route.children || [], b[index].children || []);
636 });
637}
638//#endregion
639export { RSCHydratedRouter, createCallServer };