UNPKG

33.2 kBJavaScriptView Raw
1/**
2 * react-router v7.15.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 */
11"use client";
12import {
13 RSCRouterGlobalErrorBoundary,
14 deserializeErrors,
15 getHydrationData,
16 populateRSCRouteModules
17} from "./chunk-RMD3H4O3.mjs";
18import {
19 CRITICAL_CSS_DATA_ATTRIBUTE,
20 ErrorResponseImpl,
21 FrameworkContext,
22 RSCRouterContext,
23 RemixErrorBoundary,
24 RouterProvider,
25 URL_LIMIT,
26 createBrowserHistory,
27 createClientRoutes,
28 createClientRoutesWithHMRRevalidationOptOut,
29 createContext,
30 createRequestInit,
31 createRouter,
32 decodeViaTurboStream,
33 getPatchRoutesOnNavigationFunction,
34 getSingleFetchDataStrategyImpl,
35 getTurboStreamSingleFetchDataStrategy,
36 hydrationRouteProperties,
37 invalidProtocols,
38 invariant,
39 isMutationMethod,
40 mapRouteProperties,
41 noActionDefinedError,
42 setIsHydrated,
43 shouldHydrateRouteLoader,
44 singleFetchUrl,
45 stripIndexParam,
46 useFogOFWarDiscovery
47} from "./chunk-5KNZJZUH.mjs";
48
49// lib/dom-export/dom-router-provider.tsx
50import * as React from "react";
51import * as ReactDOM from "react-dom";
52function RouterProvider2(props) {
53 return /* @__PURE__ */ React.createElement(RouterProvider, { flushSync: ReactDOM.flushSync, ...props });
54}
55
56// lib/dom-export/hydrated-router.tsx
57import * as React2 from "react";
58var ssrInfo = null;
59var router = null;
60function initSsrInfo() {
61 if (!ssrInfo && window.__reactRouterContext && window.__reactRouterManifest && window.__reactRouterRouteModules) {
62 if (window.__reactRouterManifest.sri === true) {
63 const importMap = document.querySelector("script[rr-importmap]");
64 if (importMap?.textContent) {
65 try {
66 window.__reactRouterManifest.sri = JSON.parse(
67 importMap.textContent
68 ).integrity;
69 } catch (err) {
70 console.error("Failed to parse import map", err);
71 }
72 }
73 }
74 ssrInfo = {
75 context: window.__reactRouterContext,
76 manifest: window.__reactRouterManifest,
77 routeModules: window.__reactRouterRouteModules,
78 stateDecodingPromise: void 0,
79 router: void 0,
80 routerInitialized: false
81 };
82 }
83}
84function createHydratedRouter({
85 getContext,
86 instrumentations
87}) {
88 initSsrInfo();
89 if (!ssrInfo) {
90 throw new Error(
91 "You must be using the SSR features of React Router in order to skip passing a `router` prop to `<RouterProvider>`"
92 );
93 }
94 let localSsrInfo = ssrInfo;
95 if (!ssrInfo.stateDecodingPromise) {
96 let stream = ssrInfo.context.stream;
97 invariant(stream, "No stream found for single fetch decoding");
98 ssrInfo.context.stream = void 0;
99 ssrInfo.stateDecodingPromise = decodeViaTurboStream(stream, window).then((value) => {
100 ssrInfo.context.state = value.value;
101 localSsrInfo.stateDecodingPromise.value = true;
102 }).catch((e) => {
103 localSsrInfo.stateDecodingPromise.error = e;
104 });
105 }
106 if (ssrInfo.stateDecodingPromise.error) {
107 throw ssrInfo.stateDecodingPromise.error;
108 }
109 if (!ssrInfo.stateDecodingPromise.value) {
110 throw ssrInfo.stateDecodingPromise;
111 }
112 let routes = createClientRoutes(
113 ssrInfo.manifest.routes,
114 ssrInfo.routeModules,
115 ssrInfo.context.state,
116 ssrInfo.context.ssr,
117 ssrInfo.context.isSpaMode
118 );
119 let hydrationData = void 0;
120 if (ssrInfo.context.isSpaMode) {
121 let { loaderData } = ssrInfo.context.state;
122 if (ssrInfo.manifest.routes.root?.hasLoader && loaderData && "root" in loaderData) {
123 hydrationData = {
124 loaderData: {
125 root: loaderData.root
126 }
127 };
128 }
129 } else {
130 hydrationData = getHydrationData({
131 state: ssrInfo.context.state,
132 routes,
133 getRouteInfo: (routeId) => ({
134 clientLoader: ssrInfo.routeModules[routeId]?.clientLoader,
135 hasLoader: ssrInfo.manifest.routes[routeId]?.hasLoader === true,
136 hasHydrateFallback: ssrInfo.routeModules[routeId]?.HydrateFallback != null
137 }),
138 location: window.location,
139 basename: window.__reactRouterContext?.basename,
140 isSpaMode: ssrInfo.context.isSpaMode
141 });
142 if (hydrationData && hydrationData.errors) {
143 hydrationData.errors = deserializeErrors(hydrationData.errors);
144 }
145 }
146 if (window.history.state && window.history.state.masked) {
147 window.history.replaceState(
148 { ...window.history.state, masked: void 0 },
149 ""
150 );
151 }
152 let router2 = createRouter({
153 routes,
154 history: createBrowserHistory(),
155 basename: ssrInfo.context.basename,
156 getContext,
157 hydrationData,
158 hydrationRouteProperties,
159 instrumentations,
160 mapRouteProperties,
161 future: {
162 v8_passThroughRequests: ssrInfo.context.future.v8_passThroughRequests
163 },
164 dataStrategy: getTurboStreamSingleFetchDataStrategy(
165 () => router2,
166 ssrInfo.manifest,
167 ssrInfo.routeModules,
168 ssrInfo.context.ssr,
169 ssrInfo.context.basename,
170 ssrInfo.context.future.unstable_trailingSlashAwareDataRequests
171 ),
172 patchRoutesOnNavigation: getPatchRoutesOnNavigationFunction(
173 () => router2,
174 ssrInfo.manifest,
175 ssrInfo.routeModules,
176 ssrInfo.context.ssr,
177 ssrInfo.context.routeDiscovery,
178 ssrInfo.context.isSpaMode,
179 ssrInfo.context.basename
180 )
181 });
182 ssrInfo.router = router2;
183 if (router2.state.initialized) {
184 ssrInfo.routerInitialized = true;
185 router2.initialize();
186 }
187 router2.createRoutesForHMR = /* spacer so ts-ignore does not affect the right hand of the assignment */
188 createClientRoutesWithHMRRevalidationOptOut;
189 window.__reactRouterDataRouter = router2;
190 return router2;
191}
192function HydratedRouter(props) {
193 if (!router) {
194 router = createHydratedRouter({
195 getContext: props.getContext,
196 instrumentations: props.instrumentations
197 });
198 }
199 let [criticalCss, setCriticalCss] = React2.useState(
200 process.env.NODE_ENV === "development" ? ssrInfo?.context.criticalCss : void 0
201 );
202 React2.useEffect(() => {
203 if (process.env.NODE_ENV === "development") {
204 setCriticalCss(void 0);
205 }
206 }, []);
207 React2.useEffect(() => {
208 if (process.env.NODE_ENV === "development" && criticalCss === void 0) {
209 document.querySelectorAll(`[${CRITICAL_CSS_DATA_ATTRIBUTE}]`).forEach((element) => element.remove());
210 }
211 }, [criticalCss]);
212 let [location2, setLocation] = React2.useState(router.state.location);
213 React2.useLayoutEffect(() => {
214 if (ssrInfo && ssrInfo.router && !ssrInfo.routerInitialized) {
215 ssrInfo.routerInitialized = true;
216 ssrInfo.router.initialize();
217 }
218 }, []);
219 React2.useLayoutEffect(() => {
220 if (ssrInfo && ssrInfo.router) {
221 return ssrInfo.router.subscribe((newState) => {
222 if (newState.location !== location2) {
223 setLocation(newState.location);
224 }
225 });
226 }
227 }, [location2]);
228 invariant(ssrInfo, "ssrInfo unavailable for HydratedRouter");
229 useFogOFWarDiscovery(
230 router,
231 ssrInfo.manifest,
232 ssrInfo.routeModules,
233 ssrInfo.context.ssr,
234 ssrInfo.context.routeDiscovery,
235 ssrInfo.context.isSpaMode
236 );
237 return (
238 // This fragment is important to ensure we match the <ServerRouter> JSX
239 // structure so that useId values hydrate correctly
240 /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement(
241 FrameworkContext.Provider,
242 {
243 value: {
244 manifest: ssrInfo.manifest,
245 routeModules: ssrInfo.routeModules,
246 future: ssrInfo.context.future,
247 criticalCss,
248 ssr: ssrInfo.context.ssr,
249 isSpaMode: ssrInfo.context.isSpaMode,
250 routeDiscovery: ssrInfo.context.routeDiscovery
251 }
252 },
253 /* @__PURE__ */ React2.createElement(RemixErrorBoundary, { location: location2 }, /* @__PURE__ */ React2.createElement(
254 RouterProvider2,
255 {
256 router,
257 useTransitions: props.useTransitions,
258 onError: props.onError
259 }
260 ))
261 ), /* @__PURE__ */ React2.createElement(React2.Fragment, null))
262 );
263}
264
265// lib/rsc/browser.tsx
266import * as React3 from "react";
267import * as ReactDOM2 from "react-dom";
268var defaultManifestPath = "/__manifest";
269function createCallServer({
270 createFromReadableStream,
271 createTemporaryReferenceSet,
272 encodeReply,
273 fetch: fetchImplementation = fetch
274}) {
275 const globalVar = window;
276 let landedActionId = 0;
277 return async (id, args) => {
278 let actionId = globalVar.__routerActionID = (globalVar.__routerActionID ?? (globalVar.__routerActionID = 0)) + 1;
279 const temporaryReferences = createTemporaryReferenceSet();
280 const payloadPromise = fetchImplementation(
281 new Request(location.href, {
282 body: await encodeReply(args, { temporaryReferences }),
283 method: "POST",
284 headers: {
285 Accept: "text/x-component",
286 "rsc-action-id": id
287 }
288 })
289 ).then((response) => {
290 if (!response.body) {
291 throw new Error("No response body");
292 }
293 return createFromReadableStream(response.body, {
294 temporaryReferences
295 });
296 });
297 React3.startTransition(
298 () => (
299 // @ts-expect-error - Needs React 19 types
300 Promise.resolve(payloadPromise).then(async (payload) => {
301 if (payload.type === "redirect") {
302 if (payload.reload || isExternalLocation(payload.location)) {
303 if (hasInvalidProtocol(payload.location)) {
304 throw new Error("Invalid redirect location");
305 }
306 window.location.href = payload.location;
307 return;
308 }
309 React3.startTransition(() => {
310 globalVar.__reactRouterDataRouter.navigate(payload.location, {
311 replace: payload.replace
312 });
313 });
314 return;
315 }
316 if (payload.type !== "action") {
317 throw new Error("Unexpected payload type");
318 }
319 const rerender = await payload.rerender;
320 if (rerender && landedActionId < actionId && globalVar.__routerActionID <= actionId) {
321 if (rerender.type === "redirect") {
322 if (rerender.reload || isExternalLocation(rerender.location)) {
323 if (hasInvalidProtocol(rerender.location)) {
324 throw new Error("Invalid redirect location");
325 }
326 window.location.href = rerender.location;
327 return;
328 }
329 React3.startTransition(() => {
330 globalVar.__reactRouterDataRouter.navigate(rerender.location, {
331 replace: rerender.replace
332 });
333 });
334 return;
335 }
336 React3.startTransition(() => {
337 let lastMatch;
338 for (const match of rerender.matches) {
339 globalVar.__reactRouterDataRouter.patchRoutes(
340 lastMatch?.id ?? null,
341 [createRouteFromServerManifest(match)],
342 true
343 );
344 lastMatch = match;
345 }
346 window.__reactRouterDataRouter._internalSetStateDoNotUseOrYouWillBreakYourApp(
347 {
348 loaderData: Object.assign(
349 {},
350 globalVar.__reactRouterDataRouter.state.loaderData,
351 rerender.loaderData
352 ),
353 errors: rerender.errors ? Object.assign(
354 {},
355 globalVar.__reactRouterDataRouter.state.errors,
356 rerender.errors
357 ) : null
358 }
359 );
360 });
361 }
362 }).catch(() => {
363 })
364 )
365 );
366 return payloadPromise.then((payload) => {
367 if (payload.type !== "action" && payload.type !== "redirect") {
368 throw new Error("Unexpected payload type");
369 }
370 return payload.actionResult;
371 });
372 };
373}
374function createRouterFromPayload({
375 fetchImplementation,
376 createFromReadableStream,
377 getContext,
378 payload
379}) {
380 const globalVar = window;
381 if (globalVar.__reactRouterDataRouter && globalVar.__reactRouterRouteModules)
382 return {
383 router: globalVar.__reactRouterDataRouter,
384 routeModules: globalVar.__reactRouterRouteModules
385 };
386 if (payload.type !== "render") throw new Error("Invalid payload type");
387 globalVar.__reactRouterRouteModules = globalVar.__reactRouterRouteModules ?? {};
388 populateRSCRouteModules(globalVar.__reactRouterRouteModules, payload.matches);
389 let routes = payload.matches.reduceRight((previous, match) => {
390 const route = createRouteFromServerManifest(
391 match,
392 payload
393 );
394 if (previous.length > 0) {
395 route.children = previous;
396 } else if (!route.index) {
397 route.children = [];
398 }
399 return [route];
400 }, []);
401 let applyPatchesPromise;
402 globalVar.__reactRouterDataRouter = createRouter({
403 routes,
404 getContext,
405 basename: payload.basename,
406 history: createBrowserHistory(),
407 hydrationData: getHydrationData({
408 state: {
409 loaderData: payload.loaderData,
410 actionData: payload.actionData,
411 errors: payload.errors
412 },
413 routes,
414 getRouteInfo: (routeId) => {
415 let match = payload.matches.find((m) => m.id === routeId);
416 invariant(match, "Route not found in payload");
417 return {
418 clientLoader: match.clientLoader,
419 hasLoader: match.hasLoader,
420 hasHydrateFallback: match.hydrateFallbackElement != null
421 };
422 },
423 location: payload.location,
424 basename: payload.basename,
425 isSpaMode: false
426 }),
427 async patchRoutesOnNavigation({ path, signal }) {
428 if (payload.routeDiscovery.mode === "initial") {
429 if (!applyPatchesPromise) {
430 applyPatchesPromise = (async () => {
431 if (!payload.patches) return;
432 let patches = await payload.patches;
433 React3.startTransition(() => {
434 patches.forEach((p) => {
435 window.__reactRouterDataRouter.patchRoutes(p.parentId ?? null, [
436 createRouteFromServerManifest(p)
437 ]);
438 });
439 });
440 })();
441 }
442 await applyPatchesPromise;
443 return;
444 }
445 if (discoveredPaths.has(path)) {
446 return;
447 }
448 await fetchAndApplyManifestPatches(
449 [path],
450 createFromReadableStream,
451 fetchImplementation,
452 signal
453 );
454 },
455 // FIXME: Pass `build.ssr` into this function
456 dataStrategy: getRSCSingleFetchDataStrategy(
457 () => globalVar.__reactRouterDataRouter,
458 true,
459 payload.basename,
460 createFromReadableStream,
461 fetchImplementation
462 )
463 });
464 if (globalVar.__reactRouterDataRouter.state.initialized) {
465 globalVar.__routerInitialized = true;
466 globalVar.__reactRouterDataRouter.initialize();
467 } else {
468 globalVar.__routerInitialized = false;
469 }
470 let lastLoaderData = void 0;
471 globalVar.__reactRouterDataRouter.subscribe(({ loaderData, actionData }) => {
472 if (lastLoaderData !== loaderData) {
473 globalVar.__routerActionID = (globalVar.__routerActionID ?? (globalVar.__routerActionID = 0)) + 1;
474 }
475 });
476 globalVar.__reactRouterDataRouter._updateRoutesForHMR = (routeUpdateByRouteId) => {
477 const oldRoutes = window.__reactRouterDataRouter.routes;
478 const newRoutes = [];
479 function walkRoutes(routes2, parentId) {
480 return routes2.map((route) => {
481 const routeUpdate = routeUpdateByRouteId.get(route.id);
482 if (routeUpdate) {
483 const {
484 routeModule,
485 hasAction,
486 hasComponent,
487 hasErrorBoundary,
488 hasLoader
489 } = routeUpdate;
490 const newRoute = createRouteFromServerManifest({
491 clientAction: routeModule.clientAction,
492 clientLoader: routeModule.clientLoader,
493 element: route.element,
494 errorElement: route.errorElement,
495 handle: route.handle,
496 hasAction,
497 hasComponent,
498 hasErrorBoundary,
499 hasLoader,
500 hydrateFallbackElement: route.hydrateFallbackElement,
501 id: route.id,
502 index: route.index,
503 links: routeModule.links,
504 meta: routeModule.meta,
505 parentId,
506 path: route.path,
507 shouldRevalidate: routeModule.shouldRevalidate
508 });
509 if (route.children) {
510 newRoute.children = walkRoutes(route.children, route.id);
511 }
512 return newRoute;
513 }
514 const updatedRoute = { ...route };
515 if (route.children) {
516 updatedRoute.children = walkRoutes(route.children, route.id);
517 }
518 return updatedRoute;
519 });
520 }
521 newRoutes.push(
522 ...walkRoutes(oldRoutes, void 0)
523 );
524 window.__reactRouterDataRouter._internalSetRoutes(newRoutes);
525 };
526 return {
527 router: globalVar.__reactRouterDataRouter,
528 routeModules: globalVar.__reactRouterRouteModules
529 };
530}
531var renderedRoutesContext = createContext();
532function getRSCSingleFetchDataStrategy(getRouter, ssr, basename, createFromReadableStream, fetchImplementation) {
533 let dataStrategy = getSingleFetchDataStrategyImpl(
534 getRouter,
535 (match) => {
536 let M = match;
537 return {
538 hasLoader: M.route.hasLoader,
539 hasClientLoader: M.route.hasClientLoader,
540 hasComponent: M.route.hasComponent,
541 hasAction: M.route.hasAction,
542 hasClientAction: M.route.hasClientAction
543 };
544 },
545 // pass map into fetchAndDecode so it can add payloads
546 getFetchAndDecodeViaRSC(createFromReadableStream, fetchImplementation),
547 ssr,
548 basename,
549 // .rsc requests are always trailing slash aware
550 true,
551 // If the route has a component but we don't have an element, we need to hit
552 // the server loader flow regardless of whether the client loader calls
553 // `serverLoader` or not, otherwise we'll have nothing to render.
554 (match) => {
555 let M = match;
556 return M.route.hasComponent && !M.route.element;
557 }
558 );
559 return async (args) => args.runClientMiddleware(async () => {
560 let context = args.context;
561 context.set(renderedRoutesContext, []);
562 let results = await dataStrategy(args);
563 const renderedRoutesById = /* @__PURE__ */ new Map();
564 for (const route of context.get(renderedRoutesContext)) {
565 if (!renderedRoutesById.has(route.id)) {
566 renderedRoutesById.set(route.id, []);
567 }
568 renderedRoutesById.get(route.id).push(route);
569 }
570 React3.startTransition(() => {
571 for (const match of args.matches) {
572 const renderedRoutes = renderedRoutesById.get(match.route.id);
573 if (renderedRoutes) {
574 for (const rendered of renderedRoutes) {
575 window.__reactRouterDataRouter.patchRoutes(
576 rendered.parentId ?? null,
577 [createRouteFromServerManifest(rendered)],
578 true
579 );
580 }
581 }
582 }
583 });
584 return results;
585 });
586}
587function getFetchAndDecodeViaRSC(createFromReadableStream, fetchImplementation) {
588 return async (args, basename, trailingSlashAware, targetRoutes) => {
589 let { request, context } = args;
590 let url = singleFetchUrl(request.url, basename, trailingSlashAware, "rsc");
591 if (request.method === "GET") {
592 url = stripIndexParam(url);
593 if (targetRoutes) {
594 url.searchParams.set("_routes", targetRoutes.join(","));
595 }
596 }
597 let res = await fetchImplementation(
598 new Request(url, await createRequestInit(request))
599 );
600 if (res.status >= 400 && !res.headers.has("X-Remix-Response")) {
601 throw new ErrorResponseImpl(res.status, res.statusText, await res.text());
602 }
603 invariant(res.body, "No response body to decode");
604 try {
605 const payload = await createFromReadableStream(res.body, {
606 temporaryReferences: void 0
607 });
608 if (payload.type === "redirect") {
609 return {
610 status: res.status,
611 data: {
612 redirect: {
613 redirect: payload.location,
614 reload: payload.reload,
615 replace: payload.replace,
616 revalidate: false,
617 status: payload.status
618 }
619 }
620 };
621 }
622 if (payload.type !== "render") {
623 throw new Error("Unexpected payload type");
624 }
625 context.get(renderedRoutesContext).push(...payload.matches);
626 let results = { routes: {} };
627 const dataKey = isMutationMethod(request.method) ? "actionData" : "loaderData";
628 for (let [routeId, data] of Object.entries(payload[dataKey] || {})) {
629 results.routes[routeId] = { data };
630 }
631 if (payload.errors) {
632 for (let [routeId, error] of Object.entries(payload.errors)) {
633 results.routes[routeId] = { error };
634 }
635 }
636 return { status: res.status, data: results };
637 } catch (cause) {
638 throw new Error("Unable to decode RSC response", { cause });
639 }
640 };
641}
642function RSCHydratedRouter({
643 createFromReadableStream,
644 fetch: fetchImplementation = fetch,
645 payload,
646 getContext
647}) {
648 if (payload.type !== "render") throw new Error("Invalid payload type");
649 let { routeDiscovery } = payload;
650 let { router: router2, routeModules } = React3.useMemo(
651 () => createRouterFromPayload({
652 payload,
653 fetchImplementation,
654 getContext,
655 createFromReadableStream
656 }),
657 [createFromReadableStream, payload, fetchImplementation, getContext]
658 );
659 React3.useEffect(() => {
660 setIsHydrated();
661 }, []);
662 React3.useLayoutEffect(() => {
663 const globalVar = window;
664 if (!globalVar.__routerInitialized) {
665 globalVar.__routerInitialized = true;
666 globalVar.__reactRouterDataRouter.initialize();
667 }
668 }, []);
669 let [{ routes, state }, setState] = React3.useState(() => ({
670 routes: cloneRoutes(router2.routes),
671 state: router2.state
672 }));
673 React3.useLayoutEffect(
674 () => router2.subscribe((newState) => {
675 if (diffRoutes(router2.routes, routes))
676 React3.startTransition(() => {
677 setState({
678 routes: cloneRoutes(router2.routes),
679 state: newState
680 });
681 });
682 }),
683 [router2.subscribe, routes, router2]
684 );
685 const transitionEnabledRouter = React3.useMemo(
686 () => ({
687 ...router2,
688 state,
689 routes
690 }),
691 [router2, routes, state]
692 );
693 React3.useEffect(() => {
694 if (routeDiscovery.mode === "initial" || // @ts-expect-error - TS doesn't know about this yet
695 window.navigator?.connection?.saveData === true) {
696 return;
697 }
698 function registerElement(el) {
699 let path = el.tagName === "FORM" ? el.getAttribute("action") : el.getAttribute("href");
700 if (!path) {
701 return;
702 }
703 let pathname = el.tagName === "A" ? el.pathname : new URL(path, window.location.origin).pathname;
704 if (!discoveredPaths.has(pathname)) {
705 nextPaths.add(pathname);
706 }
707 }
708 async function fetchPatches() {
709 document.querySelectorAll("a[data-discover], form[data-discover]").forEach(registerElement);
710 let paths = Array.from(nextPaths.keys()).filter((path) => {
711 if (discoveredPaths.has(path)) {
712 nextPaths.delete(path);
713 return false;
714 }
715 return true;
716 });
717 if (paths.length === 0) {
718 return;
719 }
720 try {
721 await fetchAndApplyManifestPatches(
722 paths,
723 createFromReadableStream,
724 fetchImplementation
725 );
726 } catch (e) {
727 console.error("Failed to fetch manifest patches", e);
728 }
729 }
730 let debouncedFetchPatches = debounce(fetchPatches, 100);
731 fetchPatches();
732 let observer = new MutationObserver(() => debouncedFetchPatches());
733 observer.observe(document.documentElement, {
734 subtree: true,
735 childList: true,
736 attributes: true,
737 attributeFilter: ["data-discover", "href", "action"]
738 });
739 }, [routeDiscovery, createFromReadableStream, fetchImplementation]);
740 const frameworkContext = {
741 future: {
742 // These flags have no runtime impact so can always be false. If we add
743 // flags that drive runtime behavior they'll need to be proxied through.
744 v8_middleware: false,
745 unstable_trailingSlashAwareDataRequests: true,
746 // always on for RSC
747 v8_passThroughRequests: true
748 // always on for RSC
749 },
750 isSpaMode: false,
751 ssr: true,
752 criticalCss: "",
753 manifest: {
754 routes: {},
755 version: "1",
756 url: "",
757 entry: {
758 module: "",
759 imports: []
760 }
761 },
762 routeDiscovery: payload.routeDiscovery.mode === "initial" ? { mode: "initial", manifestPath: defaultManifestPath } : {
763 mode: "lazy",
764 manifestPath: payload.routeDiscovery.manifestPath || defaultManifestPath
765 },
766 routeModules
767 };
768 return /* @__PURE__ */ React3.createElement(RSCRouterContext.Provider, { value: true }, /* @__PURE__ */ React3.createElement(RSCRouterGlobalErrorBoundary, { location: state.location }, /* @__PURE__ */ React3.createElement(FrameworkContext.Provider, { value: frameworkContext }, /* @__PURE__ */ React3.createElement(
769 RouterProvider,
770 {
771 router: transitionEnabledRouter,
772 flushSync: ReactDOM2.flushSync
773 }
774 ))));
775}
776function createRouteFromServerManifest(match, payload) {
777 let hasInitialData = payload && match.id in payload.loaderData;
778 let initialData = payload?.loaderData[match.id];
779 let hasInitialError = payload?.errors && match.id in payload.errors;
780 let initialError = payload?.errors?.[match.id];
781 let isHydrationRequest = match.clientLoader?.hydrate === true || !match.hasLoader || // If the route has a component but we don't have an element, we need to hit
782 // the server loader flow regardless of whether the client loader calls
783 // `serverLoader` or not, otherwise we'll have nothing to render.
784 match.hasComponent && !match.element;
785 invariant(window.__reactRouterRouteModules);
786 populateRSCRouteModules(window.__reactRouterRouteModules, match);
787 let dataRoute = {
788 id: match.id,
789 element: match.element,
790 errorElement: match.errorElement,
791 handle: match.handle,
792 hasErrorBoundary: match.hasErrorBoundary,
793 hydrateFallbackElement: match.hydrateFallbackElement,
794 index: match.index,
795 loader: match.clientLoader ? async (args, singleFetch) => {
796 try {
797 let result = await match.clientLoader({
798 ...args,
799 serverLoader: () => {
800 preventInvalidServerHandlerCall(
801 "loader",
802 match.id,
803 match.hasLoader
804 );
805 if (isHydrationRequest) {
806 if (hasInitialData) {
807 return initialData;
808 }
809 if (hasInitialError) {
810 throw initialError;
811 }
812 }
813 return callSingleFetch(singleFetch);
814 }
815 });
816 return result;
817 } finally {
818 isHydrationRequest = false;
819 }
820 } : (
821 // We always make the call in this RSC world since even if we don't
822 // have a `loader` we may need to get the `element` implementation
823 (_, singleFetch) => callSingleFetch(singleFetch)
824 ),
825 action: match.clientAction ? (args, singleFetch) => match.clientAction({
826 ...args,
827 serverAction: async () => {
828 preventInvalidServerHandlerCall(
829 "action",
830 match.id,
831 match.hasLoader
832 );
833 return await callSingleFetch(singleFetch);
834 }
835 }) : match.hasAction ? (_, singleFetch) => callSingleFetch(singleFetch) : () => {
836 throw noActionDefinedError("action", match.id);
837 },
838 path: match.path,
839 shouldRevalidate: match.shouldRevalidate,
840 // We always have a "loader" in this RSC world since even if we don't
841 // have a `loader` we may need to get the `element` implementation
842 hasLoader: true,
843 hasClientLoader: match.clientLoader != null,
844 hasAction: match.hasAction,
845 hasClientAction: match.clientAction != null
846 };
847 if (typeof dataRoute.loader === "function") {
848 dataRoute.loader.hydrate = shouldHydrateRouteLoader(
849 match.id,
850 match.clientLoader,
851 match.hasLoader,
852 false
853 );
854 }
855 return dataRoute;
856}
857function callSingleFetch(singleFetch) {
858 invariant(typeof singleFetch === "function", "Invalid singleFetch parameter");
859 return singleFetch();
860}
861function preventInvalidServerHandlerCall(type, routeId, hasHandler) {
862 if (!hasHandler) {
863 let fn = type === "action" ? "serverAction()" : "serverLoader()";
864 let msg = `You are trying to call ${fn} on a route that does not have a server ${type} (routeId: "${routeId}")`;
865 console.error(msg);
866 throw new ErrorResponseImpl(400, "Bad Request", new Error(msg), true);
867 }
868}
869var nextPaths = /* @__PURE__ */ new Set();
870var discoveredPathsMaxSize = 1e3;
871var discoveredPaths = /* @__PURE__ */ new Set();
872function getManifestUrl(paths) {
873 if (paths.length === 0) {
874 return null;
875 }
876 if (paths.length === 1) {
877 return new URL(`${paths[0]}.manifest`, window.location.origin);
878 }
879 const globalVar = window;
880 let basename = (globalVar.__reactRouterDataRouter.basename ?? "").replace(
881 /^\/|\/$/g,
882 ""
883 );
884 let url = new URL(`${basename}/.manifest`, window.location.origin);
885 url.searchParams.set("paths", paths.sort().join(","));
886 return url;
887}
888async function fetchAndApplyManifestPatches(paths, createFromReadableStream, fetchImplementation, signal) {
889 let url = getManifestUrl(paths);
890 if (url == null) {
891 return;
892 }
893 if (url.toString().length > URL_LIMIT) {
894 nextPaths.clear();
895 return;
896 }
897 let response = await fetchImplementation(new Request(url, { signal }));
898 if (!response.body || response.status < 200 || response.status >= 300) {
899 throw new Error("Unable to fetch new route matches from the server");
900 }
901 let payload = await createFromReadableStream(response.body, {
902 temporaryReferences: void 0
903 });
904 if (payload.type !== "manifest") {
905 throw new Error("Failed to patch routes");
906 }
907 paths.forEach((p) => addToFifoQueue(p, discoveredPaths));
908 let patches = await payload.patches;
909 React3.startTransition(() => {
910 patches.forEach((p) => {
911 window.__reactRouterDataRouter.patchRoutes(
912 p.parentId ?? null,
913 [createRouteFromServerManifest(p)]
914 );
915 });
916 });
917}
918function addToFifoQueue(path, queue) {
919 if (queue.size >= discoveredPathsMaxSize) {
920 let first = queue.values().next().value;
921 if (typeof first === "string") queue.delete(first);
922 }
923 queue.add(path);
924}
925function debounce(callback, wait) {
926 let timeoutId;
927 return (...args) => {
928 window.clearTimeout(timeoutId);
929 timeoutId = window.setTimeout(() => callback(...args), wait);
930 };
931}
932function isExternalLocation(location2) {
933 const newLocation = new URL(location2, window.location.href);
934 return newLocation.origin !== window.location.origin;
935}
936function hasInvalidProtocol(location2) {
937 try {
938 return invalidProtocols.includes(new URL(location2).protocol);
939 } catch {
940 return false;
941 }
942}
943function cloneRoutes(routes) {
944 if (!routes) return void 0;
945 return routes.map((route) => ({
946 ...route,
947 children: cloneRoutes(route.children)
948 }));
949}
950function diffRoutes(a, b) {
951 if (a.length !== b.length) return true;
952 return a.some((route, index) => {
953 if (route.element !== b[index].element) return true;
954 if (route.errorElement !== b[index].errorElement)
955 return true;
956 if (route.hydrateFallbackElement !== b[index].hydrateFallbackElement)
957 return true;
958 if (route.hasErrorBoundary !== b[index].hasErrorBoundary)
959 return true;
960 if (route.hasLoader !== b[index].hasLoader) return true;
961 if (route.hasClientLoader !== b[index].hasClientLoader)
962 return true;
963 if (route.hasAction !== b[index].hasAction) return true;
964 if (route.hasClientAction !== b[index].hasClientAction)
965 return true;
966 return diffRoutes(route.children || [], b[index].children || []);
967 });
968}
969
970// lib/rsc/html-stream/browser.ts
971function getRSCStream() {
972 let encoder = new TextEncoder();
973 let streamController = null;
974 let rscStream = new ReadableStream({
975 start(controller) {
976 if (typeof window === "undefined") {
977 return;
978 }
979 let handleChunk = (chunk) => {
980 if (typeof chunk === "string") {
981 controller.enqueue(encoder.encode(chunk));
982 } else {
983 controller.enqueue(chunk);
984 }
985 };
986 window.__FLIGHT_DATA || (window.__FLIGHT_DATA = []);
987 window.__FLIGHT_DATA.forEach(handleChunk);
988 window.__FLIGHT_DATA.push = (chunk) => {
989 handleChunk(chunk);
990 return 0;
991 };
992 streamController = controller;
993 }
994 });
995 if (typeof document !== "undefined" && document.readyState === "loading") {
996 document.addEventListener("DOMContentLoaded", () => {
997 streamController?.close();
998 });
999 } else {
1000 streamController?.close();
1001 }
1002 return rscStream;
1003}
1004export {
1005 HydratedRouter,
1006 RouterProvider2 as RouterProvider,
1007 RSCHydratedRouter as unstable_RSCHydratedRouter,
1008 createCallServer as unstable_createCallServer,
1009 getRSCStream as unstable_getRSCStream
1010};