UNPKG

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