UNPKG

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