UNPKG

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