UNPKG

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