UNPKG

50.8 kBJavaScriptView Raw
1/**
2 * React Router v6.7.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 */
11import { invariant, joinPaths, matchPath, UNSAFE_getPathContributingMatches, warning, resolveTo, parsePath, matchRoutes, Action, isRouteErrorResponse, createMemoryHistory, stripBasename, AbortedDeferredError, createRouter } from '@remix-run/router';
12export { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, resolvePath } from '@remix-run/router';
13import * as React from 'react';
14
15function _extends() {
16 _extends = Object.assign ? Object.assign.bind() : function (target) {
17 for (var i = 1; i < arguments.length; i++) {
18 var source = arguments[i];
19
20 for (var key in source) {
21 if (Object.prototype.hasOwnProperty.call(source, key)) {
22 target[key] = source[key];
23 }
24 }
25 }
26
27 return target;
28 };
29 return _extends.apply(this, arguments);
30}
31
32/**
33 * Copyright (c) Facebook, Inc. and its affiliates.
34 *
35 * This source code is licensed under the MIT license found in the
36 * LICENSE file in the root directory of this source tree.
37 */
38/**
39 * inlined Object.is polyfill to avoid requiring consumers ship their own
40 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
41 */
42
43function isPolyfill(x, y) {
44 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
45 ;
46}
47
48const is = typeof Object.is === "function" ? Object.is : isPolyfill; // Intentionally not using named imports because Rollup uses dynamic
49// dispatch for CommonJS interop named imports.
50
51const {
52 useState,
53 useEffect,
54 useLayoutEffect,
55 useDebugValue
56} = React;
57let didWarnOld18Alpha = false;
58let didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
59// because of a very particular set of implementation details and assumptions
60// -- change any one of them and it will break. The most important assumption
61// is that updates are always synchronous, because concurrent rendering is
62// only available in versions of React that also have a built-in
63// useSyncExternalStore API. And we only use this shim when the built-in API
64// does not exist.
65//
66// Do not assume that the clever hacks used by this hook also work in general.
67// The point of this shim is to replace the need for hacks by other libraries.
68
69function useSyncExternalStore$2(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
70// React do not expose a way to check if we're hydrating. So users of the shim
71// will need to track that themselves and return the correct value
72// from `getSnapshot`.
73getServerSnapshot) {
74 if (process.env.NODE_ENV !== "production") {
75 if (!didWarnOld18Alpha) {
76 if ("startTransition" in React) {
77 didWarnOld18Alpha = true;
78 console.error("You are using an outdated, pre-release alpha of React 18 that " + "does not support useSyncExternalStore. The " + "use-sync-external-store shim will not work correctly. Upgrade " + "to a newer pre-release.");
79 }
80 }
81 } // Read the current snapshot from the store on every render. Again, this
82 // breaks the rules of React, and only works here because of specific
83 // implementation details, most importantly that updates are
84 // always synchronous.
85
86
87 const value = getSnapshot();
88
89 if (process.env.NODE_ENV !== "production") {
90 if (!didWarnUncachedGetSnapshot) {
91 const cachedValue = getSnapshot();
92
93 if (!is(value, cachedValue)) {
94 console.error("The result of getSnapshot should be cached to avoid an infinite loop");
95 didWarnUncachedGetSnapshot = true;
96 }
97 }
98 } // Because updates are synchronous, we don't queue them. Instead we force a
99 // re-render whenever the subscribed state changes by updating an some
100 // arbitrary useState hook. Then, during render, we call getSnapshot to read
101 // the current value.
102 //
103 // Because we don't actually use the state returned by the useState hook, we
104 // can save a bit of memory by storing other stuff in that slot.
105 //
106 // To implement the early bailout, we need to track some things on a mutable
107 // object. Usually, we would put that in a useRef hook, but we can stash it in
108 // our useState hook instead.
109 //
110 // To force a re-render, we call forceUpdate({inst}). That works because the
111 // new object always fails an equality check.
112
113
114 const [{
115 inst
116 }, forceUpdate] = useState({
117 inst: {
118 value,
119 getSnapshot
120 }
121 }); // Track the latest getSnapshot function with a ref. This needs to be updated
122 // in the layout phase so we can access it during the tearing check that
123 // happens on subscribe.
124
125 useLayoutEffect(() => {
126 inst.value = value;
127 inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
128 // commit phase if there was an interleaved mutation. In concurrent mode
129 // this can happen all the time, but even in synchronous mode, an earlier
130 // effect may have mutated the store.
131
132 if (checkIfSnapshotChanged(inst)) {
133 // Force a re-render.
134 forceUpdate({
135 inst
136 });
137 } // eslint-disable-next-line react-hooks/exhaustive-deps
138
139 }, [subscribe, value, getSnapshot]);
140 useEffect(() => {
141 // Check for changes right before subscribing. Subsequent changes will be
142 // detected in the subscription handler.
143 if (checkIfSnapshotChanged(inst)) {
144 // Force a re-render.
145 forceUpdate({
146 inst
147 });
148 }
149
150 const handleStoreChange = () => {
151 // TODO: Because there is no cross-renderer API for batching updates, it's
152 // up to the consumer of this library to wrap their subscription event
153 // with unstable_batchedUpdates. Should we try to detect when this isn't
154 // the case and print a warning in development?
155 // The store changed. Check if the snapshot changed since the last time we
156 // read from the store.
157 if (checkIfSnapshotChanged(inst)) {
158 // Force a re-render.
159 forceUpdate({
160 inst
161 });
162 }
163 }; // Subscribe to the store and return a clean-up function.
164
165
166 return subscribe(handleStoreChange); // eslint-disable-next-line react-hooks/exhaustive-deps
167 }, [subscribe]);
168 useDebugValue(value);
169 return value;
170}
171
172function checkIfSnapshotChanged(inst) {
173 const latestGetSnapshot = inst.getSnapshot;
174 const prevValue = inst.value;
175
176 try {
177 const nextValue = latestGetSnapshot();
178 return !is(prevValue, nextValue);
179 } catch (error) {
180 return true;
181 }
182}
183
184/**
185 * Copyright (c) Facebook, Inc. and its affiliates.
186 *
187 * This source code is licensed under the MIT license found in the
188 * LICENSE file in the root directory of this source tree.
189 *
190 * @flow
191 */
192function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
193 // Note: The shim does not use getServerSnapshot, because pre-18 versions of
194 // React do not expose a way to check if we're hydrating. So users of the shim
195 // will need to track that themselves and return the correct value
196 // from `getSnapshot`.
197 return getSnapshot();
198}
199
200/**
201 * Inlined into the react-router repo since use-sync-external-store does not
202 * provide a UMD-compatible package, so we need this to be able to distribute
203 * UMD react-router bundles
204 */
205const canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
206const isServerEnvironment = !canUseDOM;
207const shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore$2;
208const useSyncExternalStore = "useSyncExternalStore" in React ? (module => module.useSyncExternalStore)(React) : shim;
209
210const DataRouterContext = /*#__PURE__*/React.createContext(null);
211
212if (process.env.NODE_ENV !== "production") {
213 DataRouterContext.displayName = "DataRouter";
214}
215
216const DataRouterStateContext = /*#__PURE__*/React.createContext(null);
217
218if (process.env.NODE_ENV !== "production") {
219 DataRouterStateContext.displayName = "DataRouterState";
220}
221
222const AwaitContext = /*#__PURE__*/React.createContext(null);
223
224if (process.env.NODE_ENV !== "production") {
225 AwaitContext.displayName = "Await";
226}
227
228const NavigationContext = /*#__PURE__*/React.createContext(null);
229
230if (process.env.NODE_ENV !== "production") {
231 NavigationContext.displayName = "Navigation";
232}
233
234const LocationContext = /*#__PURE__*/React.createContext(null);
235
236if (process.env.NODE_ENV !== "production") {
237 LocationContext.displayName = "Location";
238}
239
240const RouteContext = /*#__PURE__*/React.createContext({
241 outlet: null,
242 matches: []
243});
244
245if (process.env.NODE_ENV !== "production") {
246 RouteContext.displayName = "Route";
247}
248
249const RouteErrorContext = /*#__PURE__*/React.createContext(null);
250
251if (process.env.NODE_ENV !== "production") {
252 RouteErrorContext.displayName = "RouteError";
253}
254
255/**
256 * Returns the full href for the given "to" value. This is useful for building
257 * custom links that are also accessible and preserve right-click behavior.
258 *
259 * @see https://reactrouter.com/hooks/use-href
260 */
261
262function useHref(to, _temp) {
263 let {
264 relative
265 } = _temp === void 0 ? {} : _temp;
266 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
267 // router loaded. We can help them understand how to avoid that.
268 "useHref() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
269 let {
270 basename,
271 navigator
272 } = React.useContext(NavigationContext);
273 let {
274 hash,
275 pathname,
276 search
277 } = useResolvedPath(to, {
278 relative
279 });
280 let joinedPathname = pathname; // If we're operating within a basename, prepend it to the pathname prior
281 // to creating the href. If this is a root navigation, then just use the raw
282 // basename which allows the basename to have full control over the presence
283 // of a trailing slash on root links
284
285 if (basename !== "/") {
286 joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
287 }
288
289 return navigator.createHref({
290 pathname: joinedPathname,
291 search,
292 hash
293 });
294}
295/**
296 * Returns true if this component is a descendant of a <Router>.
297 *
298 * @see https://reactrouter.com/hooks/use-in-router-context
299 */
300
301function useInRouterContext() {
302 return React.useContext(LocationContext) != null;
303}
304/**
305 * Returns the current location object, which represents the current URL in web
306 * browsers.
307 *
308 * Note: If you're using this it may mean you're doing some of your own
309 * "routing" in your app, and we'd like to know what your use case is. We may
310 * be able to provide something higher-level to better suit your needs.
311 *
312 * @see https://reactrouter.com/hooks/use-location
313 */
314
315function useLocation() {
316 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
317 // router loaded. We can help them understand how to avoid that.
318 "useLocation() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
319 return React.useContext(LocationContext).location;
320}
321/**
322 * Returns the current navigation action which describes how the router came to
323 * the current location, either by a pop, push, or replace on the history stack.
324 *
325 * @see https://reactrouter.com/hooks/use-navigation-type
326 */
327
328function useNavigationType() {
329 return React.useContext(LocationContext).navigationType;
330}
331/**
332 * Returns a PathMatch object if the given pattern matches the current URL.
333 * This is useful for components that need to know "active" state, e.g.
334 * <NavLink>.
335 *
336 * @see https://reactrouter.com/hooks/use-match
337 */
338
339function useMatch(pattern) {
340 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
341 // router loaded. We can help them understand how to avoid that.
342 "useMatch() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
343 let {
344 pathname
345 } = useLocation();
346 return React.useMemo(() => matchPath(pattern, pathname), [pathname, pattern]);
347}
348/**
349 * The interface for the navigate() function returned from useNavigate().
350 */
351
352/**
353 * Returns an imperative method for changing the location. Used by <Link>s, but
354 * may also be used by other elements to change the location.
355 *
356 * @see https://reactrouter.com/hooks/use-navigate
357 */
358function useNavigate() {
359 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
360 // router loaded. We can help them understand how to avoid that.
361 "useNavigate() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
362 let {
363 basename,
364 navigator
365 } = React.useContext(NavigationContext);
366 let {
367 matches
368 } = React.useContext(RouteContext);
369 let {
370 pathname: locationPathname
371 } = useLocation();
372 let routePathnamesJson = JSON.stringify(UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
373 let activeRef = React.useRef(false);
374 React.useEffect(() => {
375 activeRef.current = true;
376 });
377 let navigate = React.useCallback(function (to, options) {
378 if (options === void 0) {
379 options = {};
380 }
381
382 process.env.NODE_ENV !== "production" ? warning(activeRef.current, "You should call navigate() in a React.useEffect(), not when " + "your component is first rendered.") : void 0;
383 if (!activeRef.current) return;
384
385 if (typeof to === "number") {
386 navigator.go(to);
387 return;
388 }
389
390 let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path"); // If we're operating within a basename, prepend it to the pathname prior
391 // to handing off to history. If this is a root navigation, then we
392 // navigate to the raw basename which allows the basename to have full
393 // control over the presence of a trailing slash on root links
394
395 if (basename !== "/") {
396 path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
397 }
398
399 (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
400 }, [basename, navigator, routePathnamesJson, locationPathname]);
401 return navigate;
402}
403const OutletContext = /*#__PURE__*/React.createContext(null);
404/**
405 * Returns the context (if provided) for the child route at this level of the route
406 * hierarchy.
407 * @see https://reactrouter.com/hooks/use-outlet-context
408 */
409
410function useOutletContext() {
411 return React.useContext(OutletContext);
412}
413/**
414 * Returns the element for the child route at this level of the route
415 * hierarchy. Used internally by <Outlet> to render child routes.
416 *
417 * @see https://reactrouter.com/hooks/use-outlet
418 */
419
420function useOutlet(context) {
421 let outlet = React.useContext(RouteContext).outlet;
422
423 if (outlet) {
424 return /*#__PURE__*/React.createElement(OutletContext.Provider, {
425 value: context
426 }, outlet);
427 }
428
429 return outlet;
430}
431/**
432 * Returns an object of key/value pairs of the dynamic params from the current
433 * URL that were matched by the route path.
434 *
435 * @see https://reactrouter.com/hooks/use-params
436 */
437
438function useParams() {
439 let {
440 matches
441 } = React.useContext(RouteContext);
442 let routeMatch = matches[matches.length - 1];
443 return routeMatch ? routeMatch.params : {};
444}
445/**
446 * Resolves the pathname of the given `to` value against the current location.
447 *
448 * @see https://reactrouter.com/hooks/use-resolved-path
449 */
450
451function useResolvedPath(to, _temp2) {
452 let {
453 relative
454 } = _temp2 === void 0 ? {} : _temp2;
455 let {
456 matches
457 } = React.useContext(RouteContext);
458 let {
459 pathname: locationPathname
460 } = useLocation();
461 let routePathnamesJson = JSON.stringify(UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
462 return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
463}
464/**
465 * Returns the element of the route that matched the current location, prepared
466 * with the correct context to render the remainder of the route tree. Route
467 * elements in the tree must render an <Outlet> to render their child route's
468 * element.
469 *
470 * @see https://reactrouter.com/hooks/use-routes
471 */
472
473function useRoutes(routes, locationArg) {
474 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
475 // router loaded. We can help them understand how to avoid that.
476 "useRoutes() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
477 let {
478 navigator
479 } = React.useContext(NavigationContext);
480 let dataRouterStateContext = React.useContext(DataRouterStateContext);
481 let {
482 matches: parentMatches
483 } = React.useContext(RouteContext);
484 let routeMatch = parentMatches[parentMatches.length - 1];
485 let parentParams = routeMatch ? routeMatch.params : {};
486 let parentPathname = routeMatch ? routeMatch.pathname : "/";
487 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
488 let parentRoute = routeMatch && routeMatch.route;
489
490 if (process.env.NODE_ENV !== "production") {
491 // You won't get a warning about 2 different <Routes> under a <Route>
492 // without a trailing *, but this is a best-effort warning anyway since we
493 // cannot even give the warning unless they land at the parent route.
494 //
495 // Example:
496 //
497 // <Routes>
498 // {/* This route path MUST end with /* because otherwise
499 // it will never match /blog/post/123 */}
500 // <Route path="blog" element={<Blog />} />
501 // <Route path="blog/feed" element={<BlogFeed />} />
502 // </Routes>
503 //
504 // function Blog() {
505 // return (
506 // <Routes>
507 // <Route path="post/:id" element={<Post />} />
508 // </Routes>
509 // );
510 // }
511 let parentPath = parentRoute && parentRoute.path || "";
512 warningOnce(parentPathname, !parentRoute || parentPath.endsWith("*"), "You rendered descendant <Routes> (or called `useRoutes()`) at " + ("\"" + parentPathname + "\" (under <Route path=\"" + parentPath + "\">) but the ") + "parent route path has no trailing \"*\". This means if you navigate " + "deeper, the parent won't match anymore and therefore the child " + "routes will never render.\n\n" + ("Please change the parent <Route path=\"" + parentPath + "\"> to <Route ") + ("path=\"" + (parentPath === "/" ? "*" : parentPath + "/*") + "\">."));
513 }
514
515 let locationFromContext = useLocation();
516 let location;
517
518 if (locationArg) {
519 var _parsedLocationArg$pa;
520
521 let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
522 !(parentPathnameBase === "/" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? process.env.NODE_ENV !== "production" ? invariant(false, "When overriding the location using `<Routes location>` or `useRoutes(routes, location)`, " + "the location pathname must begin with the portion of the URL pathname that was " + ("matched by all parent routes. The current pathname base is \"" + parentPathnameBase + "\" ") + ("but pathname \"" + parsedLocationArg.pathname + "\" was given in the `location` prop.")) : invariant(false) : void 0;
523 location = parsedLocationArg;
524 } else {
525 location = locationFromContext;
526 }
527
528 let pathname = location.pathname || "/";
529 let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
530 let matches = matchRoutes(routes, {
531 pathname: remainingPathname
532 });
533
534 if (process.env.NODE_ENV !== "production") {
535 process.env.NODE_ENV !== "production" ? warning(parentRoute || matches != null, "No routes matched location \"" + location.pathname + location.search + location.hash + "\" ") : void 0;
536 process.env.NODE_ENV !== "production" ? warning(matches == null || matches[matches.length - 1].route.element !== undefined, "Matched leaf route at location \"" + location.pathname + location.search + location.hash + "\" does not have an element. " + "This means it will render an <Outlet /> with a null value by default resulting in an \"empty\" page.") : void 0;
537 }
538
539 let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
540 params: Object.assign({}, parentParams, match.params),
541 pathname: joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
542 navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
543 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
544 navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
545 })), parentMatches, dataRouterStateContext || undefined); // When a user passes in a `locationArg`, the associated routes need to
546 // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
547 // to use the scoped location instead of the global location.
548
549
550 if (locationArg && renderedMatches) {
551 return /*#__PURE__*/React.createElement(LocationContext.Provider, {
552 value: {
553 location: _extends({
554 pathname: "/",
555 search: "",
556 hash: "",
557 state: null,
558 key: "default"
559 }, location),
560 navigationType: Action.Pop
561 }
562 }, renderedMatches);
563 }
564
565 return renderedMatches;
566}
567
568function DefaultErrorElement() {
569 let error = useRouteError();
570 let message = isRouteErrorResponse(error) ? error.status + " " + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);
571 let stack = error instanceof Error ? error.stack : null;
572 let lightgrey = "rgba(200,200,200, 0.5)";
573 let preStyles = {
574 padding: "0.5rem",
575 backgroundColor: lightgrey
576 };
577 let codeStyles = {
578 padding: "2px 4px",
579 backgroundColor: lightgrey
580 };
581 return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h2", null, "Unhandled Thrown Error!"), /*#__PURE__*/React.createElement("h3", {
582 style: {
583 fontStyle: "italic"
584 }
585 }, message), stack ? /*#__PURE__*/React.createElement("pre", {
586 style: preStyles
587 }, stack) : null, /*#__PURE__*/React.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), /*#__PURE__*/React.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own\xA0", /*#__PURE__*/React.createElement("code", {
588 style: codeStyles
589 }, "errorElement"), " props on\xA0", /*#__PURE__*/React.createElement("code", {
590 style: codeStyles
591 }, "<Route>")));
592}
593
594class RenderErrorBoundary extends React.Component {
595 constructor(props) {
596 super(props);
597 this.state = {
598 location: props.location,
599 error: props.error
600 };
601 }
602
603 static getDerivedStateFromError(error) {
604 return {
605 error: error
606 };
607 }
608
609 static getDerivedStateFromProps(props, state) {
610 // When we get into an error state, the user will likely click "back" to the
611 // previous page that didn't have an error. Because this wraps the entire
612 // application, that will have no effect--the error page continues to display.
613 // This gives us a mechanism to recover from the error when the location changes.
614 //
615 // Whether we're in an error state or not, we update the location in state
616 // so that when we are in an error state, it gets reset when a new location
617 // comes in and the user recovers from the error.
618 if (state.location !== props.location) {
619 return {
620 error: props.error,
621 location: props.location
622 };
623 } // If we're not changing locations, preserve the location but still surface
624 // any new errors that may come through. We retain the existing error, we do
625 // this because the error provided from the app state may be cleared without
626 // the location changing.
627
628
629 return {
630 error: props.error || state.error,
631 location: state.location
632 };
633 }
634
635 componentDidCatch(error, errorInfo) {
636 console.error("React Router caught the following error during render", error, errorInfo);
637 }
638
639 render() {
640 return this.state.error ? /*#__PURE__*/React.createElement(RouteContext.Provider, {
641 value: this.props.routeContext
642 }, /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {
643 value: this.state.error,
644 children: this.props.component
645 })) : this.props.children;
646 }
647
648}
649
650function RenderedRoute(_ref) {
651 let {
652 routeContext,
653 match,
654 children
655 } = _ref;
656 let dataRouterContext = React.useContext(DataRouterContext); // Track how deep we got in our render pass to emulate SSR componentDidCatch
657 // in a DataStaticRouter
658
659 if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && match.route.errorElement) {
660 dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
661 }
662
663 return /*#__PURE__*/React.createElement(RouteContext.Provider, {
664 value: routeContext
665 }, children);
666}
667
668function _renderMatches(matches, parentMatches, dataRouterState) {
669 if (parentMatches === void 0) {
670 parentMatches = [];
671 }
672
673 if (matches == null) {
674 if (dataRouterState != null && dataRouterState.errors) {
675 // Don't bail if we have data router errors so we can render them in the
676 // boundary. Use the pre-matched (or shimmed) matches
677 matches = dataRouterState.matches;
678 } else {
679 return null;
680 }
681 }
682
683 let renderedMatches = matches; // If we have data errors, trim matches to the highest error boundary
684
685 let errors = dataRouterState == null ? void 0 : dataRouterState.errors;
686
687 if (errors != null) {
688 let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]));
689 !(errorIndex >= 0) ? process.env.NODE_ENV !== "production" ? invariant(false, "Could not find a matching route for the current errors: " + errors) : invariant(false) : void 0;
690 renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
691 }
692
693 return renderedMatches.reduceRight((outlet, match, index) => {
694 let error = match.route.id ? errors == null ? void 0 : errors[match.route.id] : null; // Only data routers handle errors
695
696 let errorElement = dataRouterState ? match.route.errorElement || /*#__PURE__*/React.createElement(DefaultErrorElement, null) : null;
697 let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
698
699 let getChildren = () => /*#__PURE__*/React.createElement(RenderedRoute, {
700 match: match,
701 routeContext: {
702 outlet,
703 matches
704 }
705 }, error ? errorElement : match.route.element !== undefined ? match.route.element : outlet); // Only wrap in an error boundary within data router usages when we have an
706 // errorElement on this route. Otherwise let it bubble up to an ancestor
707 // errorElement
708
709
710 return dataRouterState && (match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {
711 location: dataRouterState.location,
712 component: errorElement,
713 error: error,
714 children: getChildren(),
715 routeContext: {
716 outlet: null,
717 matches
718 }
719 }) : getChildren();
720 }, null);
721}
722var DataRouterHook;
723
724(function (DataRouterHook) {
725 DataRouterHook["UseBlocker"] = "useBlocker";
726 DataRouterHook["UseRevalidator"] = "useRevalidator";
727})(DataRouterHook || (DataRouterHook = {}));
728
729var DataRouterStateHook;
730
731(function (DataRouterStateHook) {
732 DataRouterStateHook["UseLoaderData"] = "useLoaderData";
733 DataRouterStateHook["UseActionData"] = "useActionData";
734 DataRouterStateHook["UseRouteError"] = "useRouteError";
735 DataRouterStateHook["UseNavigation"] = "useNavigation";
736 DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
737 DataRouterStateHook["UseMatches"] = "useMatches";
738 DataRouterStateHook["UseRevalidator"] = "useRevalidator";
739})(DataRouterStateHook || (DataRouterStateHook = {}));
740
741function getDataRouterConsoleError(hookName) {
742 return hookName + " must be used within a data router. See https://reactrouter.com/routers/picking-a-router.";
743}
744
745function useDataRouterContext(hookName) {
746 let ctx = React.useContext(DataRouterContext);
747 !ctx ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
748 return ctx;
749}
750
751function useDataRouterState(hookName) {
752 let state = React.useContext(DataRouterStateContext);
753 !state ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
754 return state;
755}
756
757function useRouteContext(hookName) {
758 let route = React.useContext(RouteContext);
759 !route ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
760 return route;
761}
762
763function useCurrentRouteId(hookName) {
764 let route = useRouteContext(hookName);
765 let thisRoute = route.matches[route.matches.length - 1];
766 !thisRoute.route.id ? process.env.NODE_ENV !== "production" ? invariant(false, hookName + " can only be used on routes that contain a unique \"id\"") : invariant(false) : void 0;
767 return thisRoute.route.id;
768}
769/**
770 * Returns the current navigation, defaulting to an "idle" navigation when
771 * no navigation is in progress
772 */
773
774
775function useNavigation() {
776 let state = useDataRouterState(DataRouterStateHook.UseNavigation);
777 return state.navigation;
778}
779/**
780 * Returns a revalidate function for manually triggering revalidation, as well
781 * as the current state of any manual revalidations
782 */
783
784function useRevalidator() {
785 let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
786 let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
787 return {
788 revalidate: dataRouterContext.router.revalidate,
789 state: state.revalidation
790 };
791}
792/**
793 * Returns the active route matches, useful for accessing loaderData for
794 * parent/child routes or the route "handle" property
795 */
796
797function useMatches() {
798 let {
799 matches,
800 loaderData
801 } = useDataRouterState(DataRouterStateHook.UseMatches);
802 return React.useMemo(() => matches.map(match => {
803 let {
804 pathname,
805 params
806 } = match; // Note: This structure matches that created by createUseMatchesMatch
807 // in the @remix-run/router , so if you change this please also change
808 // that :) Eventually we'll DRY this up
809
810 return {
811 id: match.route.id,
812 pathname,
813 params,
814 data: loaderData[match.route.id],
815 handle: match.route.handle
816 };
817 }), [matches, loaderData]);
818}
819/**
820 * Returns the loader data for the nearest ancestor Route loader
821 */
822
823function useLoaderData() {
824 let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
825 let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
826
827 if (state.errors && state.errors[routeId] != null) {
828 console.error("You cannot `useLoaderData` in an errorElement (routeId: " + routeId + ")");
829 return undefined;
830 }
831
832 return state.loaderData[routeId];
833}
834/**
835 * Returns the loaderData for the given routeId
836 */
837
838function useRouteLoaderData(routeId) {
839 let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
840 return state.loaderData[routeId];
841}
842/**
843 * Returns the action data for the nearest ancestor Route action
844 */
845
846function useActionData() {
847 let state = useDataRouterState(DataRouterStateHook.UseActionData);
848 let route = React.useContext(RouteContext);
849 !route ? process.env.NODE_ENV !== "production" ? invariant(false, "useActionData must be used inside a RouteContext") : invariant(false) : void 0;
850 return Object.values((state == null ? void 0 : state.actionData) || {})[0];
851}
852/**
853 * Returns the nearest ancestor Route error, which could be a loader/action
854 * error or a render error. This is intended to be called from your
855 * errorElement to display a proper error message.
856 */
857
858function useRouteError() {
859 var _state$errors;
860
861 let error = React.useContext(RouteErrorContext);
862 let state = useDataRouterState(DataRouterStateHook.UseRouteError);
863 let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError); // If this was a render error, we put it in a RouteError context inside
864 // of RenderErrorBoundary
865
866 if (error) {
867 return error;
868 } // Otherwise look for errors from our data router state
869
870
871 return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];
872}
873/**
874 * Returns the happy-path data from the nearest ancestor <Await /> value
875 */
876
877function useAsyncValue() {
878 let value = React.useContext(AwaitContext);
879 return value == null ? void 0 : value._data;
880}
881/**
882 * Returns the error from the nearest ancestor <Await /> value
883 */
884
885function useAsyncError() {
886 let value = React.useContext(AwaitContext);
887 return value == null ? void 0 : value._error;
888} // useBlocker() is a singleton for now since we don't have any compelling use
889// cases for multi-blocker yet
890
891let blockerKey = "blocker-singleton";
892/**
893 * Allow the application to block navigations within the SPA and present the
894 * user a confirmation dialog to confirm the navigation. Mostly used to avoid
895 * using half-filled form data. This does not handle hard-reloads or
896 * cross-origin navigations.
897 */
898
899function useBlocker(shouldBlock) {
900 let {
901 router
902 } = useDataRouterContext(DataRouterHook.UseBlocker);
903 let blockerFunction = React.useCallback(args => {
904 return typeof shouldBlock === "function" ? !!shouldBlock(args) : !!shouldBlock;
905 }, [shouldBlock]);
906 let blocker = router.getBlocker(blockerKey, blockerFunction); // Cleanup on unmount
907
908 React.useEffect(() => () => router.deleteBlocker(blockerKey), [router]);
909 return blocker;
910}
911const alreadyWarned = {};
912
913function warningOnce(key, cond, message) {
914 if (!cond && !alreadyWarned[key]) {
915 alreadyWarned[key] = true;
916 process.env.NODE_ENV !== "production" ? warning(false, message) : void 0;
917 }
918}
919
920/**
921 * Given a Remix Router instance, render the appropriate UI
922 */
923function RouterProvider(_ref) {
924 let {
925 fallbackElement,
926 router
927 } = _ref;
928 // Sync router state to our component state to force re-renders
929 let state = useSyncExternalStore(router.subscribe, () => router.state, // We have to provide this so React@18 doesn't complain during hydration,
930 // but we pass our serialized hydration data into the router so state here
931 // is already synced with what the server saw
932 () => router.state);
933 let navigator = React.useMemo(() => {
934 return {
935 createHref: router.createHref,
936 encodeLocation: router.encodeLocation,
937 go: n => router.navigate(n),
938 push: (to, state, opts) => router.navigate(to, {
939 state,
940 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
941 }),
942 replace: (to, state, opts) => router.navigate(to, {
943 replace: true,
944 state,
945 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
946 })
947 };
948 }, [router]);
949 let basename = router.basename || "/"; // The fragment and {null} here are important! We need them to keep React 18's
950 // useId happy when we are server-rendering since we may have a <script> here
951 // containing the hydrated server-side staticContext (from StaticRouterProvider).
952 // useId relies on the component tree structure to generate deterministic id's
953 // so we need to ensure it remains the same on the client even though
954 // we don't need the <script> tag
955
956 return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataRouterContext.Provider, {
957 value: {
958 router,
959 navigator,
960 static: false,
961 // Do we need this?
962 basename
963 }
964 }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {
965 value: state
966 }, /*#__PURE__*/React.createElement(Router, {
967 basename: router.basename,
968 location: router.state.location,
969 navigationType: router.state.historyAction,
970 navigator: navigator
971 }, router.state.initialized ? /*#__PURE__*/React.createElement(Routes, null) : fallbackElement))), null);
972}
973
974/**
975 * A <Router> that stores all entries in memory.
976 *
977 * @see https://reactrouter.com/router-components/memory-router
978 */
979function MemoryRouter(_ref2) {
980 let {
981 basename,
982 children,
983 initialEntries,
984 initialIndex
985 } = _ref2;
986 let historyRef = React.useRef();
987
988 if (historyRef.current == null) {
989 historyRef.current = createMemoryHistory({
990 initialEntries,
991 initialIndex,
992 v5Compat: true
993 });
994 }
995
996 let history = historyRef.current;
997 let [state, setState] = React.useState({
998 action: history.action,
999 location: history.location
1000 });
1001 React.useLayoutEffect(() => history.listen(setState), [history]);
1002 return /*#__PURE__*/React.createElement(Router, {
1003 basename: basename,
1004 children: children,
1005 location: state.location,
1006 navigationType: state.action,
1007 navigator: history
1008 });
1009}
1010
1011/**
1012 * Changes the current location.
1013 *
1014 * Note: This API is mostly useful in React.Component subclasses that are not
1015 * able to use hooks. In functional components, we recommend you use the
1016 * `useNavigate` hook instead.
1017 *
1018 * @see https://reactrouter.com/components/navigate
1019 */
1020function Navigate(_ref3) {
1021 let {
1022 to,
1023 replace,
1024 state,
1025 relative
1026 } = _ref3;
1027 !useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of
1028 // the router loaded. We can help them understand how to avoid that.
1029 "<Navigate> may be used only in the context of a <Router> component.") : invariant(false) : void 0;
1030 process.env.NODE_ENV !== "production" ? warning(!React.useContext(NavigationContext).static, "<Navigate> must not be used on the initial render in a <StaticRouter>. " + "This is a no-op, but you should modify your code so the <Navigate> is " + "only ever rendered in response to some user interaction or state change.") : void 0;
1031 let dataRouterState = React.useContext(DataRouterStateContext);
1032 let navigate = useNavigate();
1033 React.useEffect(() => {
1034 // Avoid kicking off multiple navigations if we're in the middle of a
1035 // data-router navigation, since components get re-rendered when we enter
1036 // a submitting/loading state
1037 if (dataRouterState && dataRouterState.navigation.state !== "idle") {
1038 return;
1039 }
1040
1041 navigate(to, {
1042 replace,
1043 state,
1044 relative
1045 });
1046 });
1047 return null;
1048}
1049
1050/**
1051 * Renders the child route's element, if there is one.
1052 *
1053 * @see https://reactrouter.com/components/outlet
1054 */
1055function Outlet(props) {
1056 return useOutlet(props.context);
1057}
1058
1059/**
1060 * Declares an element that should be rendered at a certain URL path.
1061 *
1062 * @see https://reactrouter.com/components/route
1063 */
1064function Route(_props) {
1065 process.env.NODE_ENV !== "production" ? invariant(false, "A <Route> is only ever to be used as the child of <Routes> element, " + "never rendered directly. Please wrap your <Route> in a <Routes>.") : invariant(false) ;
1066}
1067
1068/**
1069 * Provides location context for the rest of the app.
1070 *
1071 * Note: You usually won't render a <Router> directly. Instead, you'll render a
1072 * router that is more specific to your environment such as a <BrowserRouter>
1073 * in web browsers or a <StaticRouter> for server rendering.
1074 *
1075 * @see https://reactrouter.com/router-components/router
1076 */
1077function Router(_ref4) {
1078 let {
1079 basename: basenameProp = "/",
1080 children = null,
1081 location: locationProp,
1082 navigationType = Action.Pop,
1083 navigator,
1084 static: staticProp = false
1085 } = _ref4;
1086 !!useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, "You cannot render a <Router> inside another <Router>." + " You should never have more than one in your app.") : invariant(false) : void 0; // Preserve trailing slashes on basename, so we can let the user control
1087 // the enforcement of trailing slashes throughout the app
1088
1089 let basename = basenameProp.replace(/^\/*/, "/");
1090 let navigationContext = React.useMemo(() => ({
1091 basename,
1092 navigator,
1093 static: staticProp
1094 }), [basename, navigator, staticProp]);
1095
1096 if (typeof locationProp === "string") {
1097 locationProp = parsePath(locationProp);
1098 }
1099
1100 let {
1101 pathname = "/",
1102 search = "",
1103 hash = "",
1104 state = null,
1105 key = "default"
1106 } = locationProp;
1107 let location = React.useMemo(() => {
1108 let trailingPathname = stripBasename(pathname, basename);
1109
1110 if (trailingPathname == null) {
1111 return null;
1112 }
1113
1114 return {
1115 pathname: trailingPathname,
1116 search,
1117 hash,
1118 state,
1119 key
1120 };
1121 }, [basename, pathname, search, hash, state, key]);
1122 process.env.NODE_ENV !== "production" ? warning(location != null, "<Router basename=\"" + basename + "\"> is not able to match the URL " + ("\"" + pathname + search + hash + "\" because it does not start with the ") + "basename, so the <Router> won't render anything.") : void 0;
1123
1124 if (location == null) {
1125 return null;
1126 }
1127
1128 return /*#__PURE__*/React.createElement(NavigationContext.Provider, {
1129 value: navigationContext
1130 }, /*#__PURE__*/React.createElement(LocationContext.Provider, {
1131 children: children,
1132 value: {
1133 location,
1134 navigationType
1135 }
1136 }));
1137}
1138
1139/**
1140 * A container for a nested tree of <Route> elements that renders the branch
1141 * that best matches the current location.
1142 *
1143 * @see https://reactrouter.com/components/routes
1144 */
1145function Routes(_ref5) {
1146 let {
1147 children,
1148 location
1149 } = _ref5;
1150 let dataRouterContext = React.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes
1151 // directly. If we have children, then we're in a descendant tree and we
1152 // need to use child routes.
1153
1154 let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);
1155 return useRoutes(routes, location);
1156}
1157
1158/**
1159 * Component to use for rendering lazily loaded data from returning defer()
1160 * in a loader function
1161 */
1162function Await(_ref6) {
1163 let {
1164 children,
1165 errorElement,
1166 resolve
1167 } = _ref6;
1168 return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {
1169 resolve: resolve,
1170 errorElement: errorElement
1171 }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));
1172}
1173var AwaitRenderStatus;
1174
1175(function (AwaitRenderStatus) {
1176 AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
1177 AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
1178 AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
1179})(AwaitRenderStatus || (AwaitRenderStatus = {}));
1180
1181const neverSettledPromise = new Promise(() => {});
1182
1183class AwaitErrorBoundary extends React.Component {
1184 constructor(props) {
1185 super(props);
1186 this.state = {
1187 error: null
1188 };
1189 }
1190
1191 static getDerivedStateFromError(error) {
1192 return {
1193 error
1194 };
1195 }
1196
1197 componentDidCatch(error, errorInfo) {
1198 console.error("<Await> caught the following error during render", error, errorInfo);
1199 }
1200
1201 render() {
1202 let {
1203 children,
1204 errorElement,
1205 resolve
1206 } = this.props;
1207 let promise = null;
1208 let status = AwaitRenderStatus.pending;
1209
1210 if (!(resolve instanceof Promise)) {
1211 // Didn't get a promise - provide as a resolved promise
1212 status = AwaitRenderStatus.success;
1213 promise = Promise.resolve();
1214 Object.defineProperty(promise, "_tracked", {
1215 get: () => true
1216 });
1217 Object.defineProperty(promise, "_data", {
1218 get: () => resolve
1219 });
1220 } else if (this.state.error) {
1221 // Caught a render error, provide it as a rejected promise
1222 status = AwaitRenderStatus.error;
1223 let renderError = this.state.error;
1224 promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
1225
1226 Object.defineProperty(promise, "_tracked", {
1227 get: () => true
1228 });
1229 Object.defineProperty(promise, "_error", {
1230 get: () => renderError
1231 });
1232 } else if (resolve._tracked) {
1233 // Already tracked promise - check contents
1234 promise = resolve;
1235 status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
1236 } else {
1237 // Raw (untracked) promise - track it
1238 status = AwaitRenderStatus.pending;
1239 Object.defineProperty(resolve, "_tracked", {
1240 get: () => true
1241 });
1242 promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
1243 get: () => data
1244 }), error => Object.defineProperty(resolve, "_error", {
1245 get: () => error
1246 }));
1247 }
1248
1249 if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
1250 // Freeze the UI by throwing a never resolved promise
1251 throw neverSettledPromise;
1252 }
1253
1254 if (status === AwaitRenderStatus.error && !errorElement) {
1255 // No errorElement, throw to the nearest route-level error boundary
1256 throw promise._error;
1257 }
1258
1259 if (status === AwaitRenderStatus.error) {
1260 // Render via our errorElement
1261 return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
1262 value: promise,
1263 children: errorElement
1264 });
1265 }
1266
1267 if (status === AwaitRenderStatus.success) {
1268 // Render children with resolved value
1269 return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
1270 value: promise,
1271 children: children
1272 });
1273 } // Throw to the suspense boundary
1274
1275
1276 throw promise;
1277 }
1278
1279}
1280/**
1281 * @private
1282 * Indirection to leverage useAsyncValue for a render-prop API on <Await>
1283 */
1284
1285
1286function ResolveAwait(_ref7) {
1287 let {
1288 children
1289 } = _ref7;
1290 let data = useAsyncValue();
1291 let toRender = typeof children === "function" ? children(data) : children;
1292 return /*#__PURE__*/React.createElement(React.Fragment, null, toRender);
1293} ///////////////////////////////////////////////////////////////////////////////
1294// UTILS
1295///////////////////////////////////////////////////////////////////////////////
1296
1297/**
1298 * Creates a route config from a React "children" object, which is usually
1299 * either a `<Route>` element or an array of them. Used internally by
1300 * `<Routes>` to create a route config from its children.
1301 *
1302 * @see https://reactrouter.com/utils/create-routes-from-children
1303 */
1304
1305
1306function createRoutesFromChildren(children, parentPath) {
1307 if (parentPath === void 0) {
1308 parentPath = [];
1309 }
1310
1311 let routes = [];
1312 React.Children.forEach(children, (element, index) => {
1313 if (! /*#__PURE__*/React.isValidElement(element)) {
1314 // Ignore non-elements. This allows people to more easily inline
1315 // conditionals in their route config.
1316 return;
1317 }
1318
1319 if (element.type === React.Fragment) {
1320 // Transparently support React.Fragment and its children.
1321 routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath));
1322 return;
1323 }
1324
1325 !(element.type === Route) ? process.env.NODE_ENV !== "production" ? invariant(false, "[" + (typeof element.type === "string" ? element.type : element.type.name) + "] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>") : invariant(false) : void 0;
1326 !(!element.props.index || !element.props.children) ? process.env.NODE_ENV !== "production" ? invariant(false, "An index route cannot have child routes.") : invariant(false) : void 0;
1327 let treePath = [...parentPath, index];
1328 let route = {
1329 id: element.props.id || treePath.join("-"),
1330 caseSensitive: element.props.caseSensitive,
1331 element: element.props.element,
1332 index: element.props.index,
1333 path: element.props.path,
1334 loader: element.props.loader,
1335 action: element.props.action,
1336 errorElement: element.props.errorElement,
1337 hasErrorBoundary: element.props.errorElement != null,
1338 shouldRevalidate: element.props.shouldRevalidate,
1339 handle: element.props.handle
1340 };
1341
1342 if (element.props.children) {
1343 route.children = createRoutesFromChildren(element.props.children, treePath);
1344 }
1345
1346 routes.push(route);
1347 });
1348 return routes;
1349}
1350/**
1351 * Renders the result of `matchRoutes()` into a React element.
1352 */
1353
1354function renderMatches(matches) {
1355 return _renderMatches(matches);
1356}
1357/**
1358 * @private
1359 * Walk the route tree and add hasErrorBoundary if it's not provided, so that
1360 * users providing manual route arrays can just specify errorElement
1361 */
1362
1363function enhanceManualRouteObjects(routes) {
1364 return routes.map(route => {
1365 let routeClone = _extends({}, route);
1366
1367 if (routeClone.hasErrorBoundary == null) {
1368 routeClone.hasErrorBoundary = routeClone.errorElement != null;
1369 }
1370
1371 if (routeClone.children) {
1372 routeClone.children = enhanceManualRouteObjects(routeClone.children);
1373 }
1374
1375 return routeClone;
1376 });
1377}
1378
1379function createMemoryRouter(routes, opts) {
1380 return createRouter({
1381 basename: opts == null ? void 0 : opts.basename,
1382 history: createMemoryHistory({
1383 initialEntries: opts == null ? void 0 : opts.initialEntries,
1384 initialIndex: opts == null ? void 0 : opts.initialIndex
1385 }),
1386 hydrationData: opts == null ? void 0 : opts.hydrationData,
1387 routes: enhanceManualRouteObjects(routes)
1388 }).initialize();
1389} ///////////////////////////////////////////////////////////////////////////////
1390
1391export { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, enhanceManualRouteObjects as UNSAFE_enhanceManualRouteObjects, createMemoryRouter, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, renderMatches, useBlocker as unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };
1392//# sourceMappingURL=index.js.map