source: imaps-frontend/node_modules/@remix-run/router/dist/router.umd.js@ 0c6b92a

main
Last change on this file since 0c6b92a was 0c6b92a, checked in by stefan toskovski <stefantoska84@…>, 5 weeks ago

Pred finalna verzija

  • Property mode set to 100644
File size: 210.8 KB
Line 
1/**
2 * @remix-run/router v1.21.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(function (global, factory) {
12 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
13 typeof define === 'function' && define.amd ? define(['exports'], factory) :
14 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.RemixRouter = {}));
15})(this, (function (exports) { 'use strict';
16
17 function _extends() {
18 _extends = Object.assign ? Object.assign.bind() : function (target) {
19 for (var i = 1; i < arguments.length; i++) {
20 var source = arguments[i];
21 for (var key in source) {
22 if (Object.prototype.hasOwnProperty.call(source, key)) {
23 target[key] = source[key];
24 }
25 }
26 }
27 return target;
28 };
29 return _extends.apply(this, arguments);
30 }
31
32 ////////////////////////////////////////////////////////////////////////////////
33 //#region Types and Constants
34 ////////////////////////////////////////////////////////////////////////////////
35
36 /**
37 * Actions represent the type of change to a location value.
38 */
39 let Action = /*#__PURE__*/function (Action) {
40 Action["Pop"] = "POP";
41 Action["Push"] = "PUSH";
42 Action["Replace"] = "REPLACE";
43 return Action;
44 }({});
45
46 /**
47 * The pathname, search, and hash values of a URL.
48 */
49
50 // TODO: (v7) Change the Location generic default from `any` to `unknown` and
51 // remove Remix `useLocation` wrapper.
52 /**
53 * An entry in a history stack. A location contains information about the
54 * URL path, as well as possibly some arbitrary state and a key.
55 */
56 /**
57 * A change to the current location.
58 */
59 /**
60 * A function that receives notifications about location changes.
61 */
62 /**
63 * Describes a location that is the destination of some navigation, either via
64 * `history.push` or `history.replace`. This may be either a URL or the pieces
65 * of a URL path.
66 */
67 /**
68 * A history is an interface to the navigation stack. The history serves as the
69 * source of truth for the current location, as well as provides a set of
70 * methods that may be used to change it.
71 *
72 * It is similar to the DOM's `window.history` object, but with a smaller, more
73 * focused API.
74 */
75 const PopStateEventType = "popstate";
76 //#endregion
77
78 ////////////////////////////////////////////////////////////////////////////////
79 //#region Memory History
80 ////////////////////////////////////////////////////////////////////////////////
81
82 /**
83 * A user-supplied object that describes a location. Used when providing
84 * entries to `createMemoryHistory` via its `initialEntries` option.
85 */
86 /**
87 * A memory history stores locations in memory. This is useful in stateful
88 * environments where there is no web browser, such as node tests or React
89 * Native.
90 */
91 /**
92 * Memory history stores the current location in memory. It is designed for use
93 * in stateful non-browser environments like tests and React Native.
94 */
95 function createMemoryHistory(options) {
96 if (options === void 0) {
97 options = {};
98 }
99 let {
100 initialEntries = ["/"],
101 initialIndex,
102 v5Compat = false
103 } = options;
104 let entries; // Declare so we can access from createMemoryLocation
105 entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined));
106 let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
107 let action = Action.Pop;
108 let listener = null;
109 function clampIndex(n) {
110 return Math.min(Math.max(n, 0), entries.length - 1);
111 }
112 function getCurrentLocation() {
113 return entries[index];
114 }
115 function createMemoryLocation(to, state, key) {
116 if (state === void 0) {
117 state = null;
118 }
119 let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key);
120 warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
121 return location;
122 }
123 function createHref(to) {
124 return typeof to === "string" ? to : createPath(to);
125 }
126 let history = {
127 get index() {
128 return index;
129 },
130 get action() {
131 return action;
132 },
133 get location() {
134 return getCurrentLocation();
135 },
136 createHref,
137 createURL(to) {
138 return new URL(createHref(to), "http://localhost");
139 },
140 encodeLocation(to) {
141 let path = typeof to === "string" ? parsePath(to) : to;
142 return {
143 pathname: path.pathname || "",
144 search: path.search || "",
145 hash: path.hash || ""
146 };
147 },
148 push(to, state) {
149 action = Action.Push;
150 let nextLocation = createMemoryLocation(to, state);
151 index += 1;
152 entries.splice(index, entries.length, nextLocation);
153 if (v5Compat && listener) {
154 listener({
155 action,
156 location: nextLocation,
157 delta: 1
158 });
159 }
160 },
161 replace(to, state) {
162 action = Action.Replace;
163 let nextLocation = createMemoryLocation(to, state);
164 entries[index] = nextLocation;
165 if (v5Compat && listener) {
166 listener({
167 action,
168 location: nextLocation,
169 delta: 0
170 });
171 }
172 },
173 go(delta) {
174 action = Action.Pop;
175 let nextIndex = clampIndex(index + delta);
176 let nextLocation = entries[nextIndex];
177 index = nextIndex;
178 if (listener) {
179 listener({
180 action,
181 location: nextLocation,
182 delta
183 });
184 }
185 },
186 listen(fn) {
187 listener = fn;
188 return () => {
189 listener = null;
190 };
191 }
192 };
193 return history;
194 }
195 //#endregion
196
197 ////////////////////////////////////////////////////////////////////////////////
198 //#region Browser History
199 ////////////////////////////////////////////////////////////////////////////////
200
201 /**
202 * A browser history stores the current location in regular URLs in a web
203 * browser environment. This is the standard for most web apps and provides the
204 * cleanest URLs the browser's address bar.
205 *
206 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
207 */
208 /**
209 * Browser history stores the location in regular URLs. This is the standard for
210 * most web apps, but it requires some configuration on the server to ensure you
211 * serve the same app at multiple URLs.
212 *
213 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
214 */
215 function createBrowserHistory(options) {
216 if (options === void 0) {
217 options = {};
218 }
219 function createBrowserLocation(window, globalHistory) {
220 let {
221 pathname,
222 search,
223 hash
224 } = window.location;
225 return createLocation("", {
226 pathname,
227 search,
228 hash
229 },
230 // state defaults to `null` because `window.history.state` does
231 globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
232 }
233 function createBrowserHref(window, to) {
234 return typeof to === "string" ? to : createPath(to);
235 }
236 return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
237 }
238 //#endregion
239
240 ////////////////////////////////////////////////////////////////////////////////
241 //#region Hash History
242 ////////////////////////////////////////////////////////////////////////////////
243
244 /**
245 * A hash history stores the current location in the fragment identifier portion
246 * of the URL in a web browser environment.
247 *
248 * This is ideal for apps that do not control the server for some reason
249 * (because the fragment identifier is never sent to the server), including some
250 * shared hosting environments that do not provide fine-grained controls over
251 * which pages are served at which URLs.
252 *
253 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
254 */
255 /**
256 * Hash history stores the location in window.location.hash. This makes it ideal
257 * for situations where you don't want to send the location to the server for
258 * some reason, either because you do cannot configure it or the URL space is
259 * reserved for something else.
260 *
261 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
262 */
263 function createHashHistory(options) {
264 if (options === void 0) {
265 options = {};
266 }
267 function createHashLocation(window, globalHistory) {
268 let {
269 pathname = "/",
270 search = "",
271 hash = ""
272 } = parsePath(window.location.hash.substr(1));
273
274 // Hash URL should always have a leading / just like window.location.pathname
275 // does, so if an app ends up at a route like /#something then we add a
276 // leading slash so all of our path-matching behaves the same as if it would
277 // in a browser router. This is particularly important when there exists a
278 // root splat route (<Route path="*">) since that matches internally against
279 // "/*" and we'd expect /#something to 404 in a hash router app.
280 if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
281 pathname = "/" + pathname;
282 }
283 return createLocation("", {
284 pathname,
285 search,
286 hash
287 },
288 // state defaults to `null` because `window.history.state` does
289 globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
290 }
291 function createHashHref(window, to) {
292 let base = window.document.querySelector("base");
293 let href = "";
294 if (base && base.getAttribute("href")) {
295 let url = window.location.href;
296 let hashIndex = url.indexOf("#");
297 href = hashIndex === -1 ? url : url.slice(0, hashIndex);
298 }
299 return href + "#" + (typeof to === "string" ? to : createPath(to));
300 }
301 function validateHashLocation(location, to) {
302 warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
303 }
304 return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
305 }
306 //#endregion
307
308 ////////////////////////////////////////////////////////////////////////////////
309 //#region UTILS
310 ////////////////////////////////////////////////////////////////////////////////
311
312 /**
313 * @private
314 */
315 function invariant(value, message) {
316 if (value === false || value === null || typeof value === "undefined") {
317 throw new Error(message);
318 }
319 }
320 function warning(cond, message) {
321 if (!cond) {
322 // eslint-disable-next-line no-console
323 if (typeof console !== "undefined") console.warn(message);
324 try {
325 // Welcome to debugging history!
326 //
327 // This error is thrown as a convenience, so you can more easily
328 // find the source for a warning that appears in the console by
329 // enabling "pause on exceptions" in your JavaScript debugger.
330 throw new Error(message);
331 // eslint-disable-next-line no-empty
332 } catch (e) {}
333 }
334 }
335 function createKey() {
336 return Math.random().toString(36).substr(2, 8);
337 }
338
339 /**
340 * For browser-based histories, we combine the state and key into an object
341 */
342 function getHistoryState(location, index) {
343 return {
344 usr: location.state,
345 key: location.key,
346 idx: index
347 };
348 }
349
350 /**
351 * Creates a Location object with a unique key from the given Path
352 */
353 function createLocation(current, to, state, key) {
354 if (state === void 0) {
355 state = null;
356 }
357 let location = _extends({
358 pathname: typeof current === "string" ? current : current.pathname,
359 search: "",
360 hash: ""
361 }, typeof to === "string" ? parsePath(to) : to, {
362 state,
363 // TODO: This could be cleaned up. push/replace should probably just take
364 // full Locations now and avoid the need to run through this flow at all
365 // But that's a pretty big refactor to the current test suite so going to
366 // keep as is for the time being and just let any incoming keys take precedence
367 key: to && to.key || key || createKey()
368 });
369 return location;
370 }
371
372 /**
373 * Creates a string URL path from the given pathname, search, and hash components.
374 */
375 function createPath(_ref) {
376 let {
377 pathname = "/",
378 search = "",
379 hash = ""
380 } = _ref;
381 if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
382 if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
383 return pathname;
384 }
385
386 /**
387 * Parses a string URL path into its separate pathname, search, and hash components.
388 */
389 function parsePath(path) {
390 let parsedPath = {};
391 if (path) {
392 let hashIndex = path.indexOf("#");
393 if (hashIndex >= 0) {
394 parsedPath.hash = path.substr(hashIndex);
395 path = path.substr(0, hashIndex);
396 }
397 let searchIndex = path.indexOf("?");
398 if (searchIndex >= 0) {
399 parsedPath.search = path.substr(searchIndex);
400 path = path.substr(0, searchIndex);
401 }
402 if (path) {
403 parsedPath.pathname = path;
404 }
405 }
406 return parsedPath;
407 }
408 function getUrlBasedHistory(getLocation, createHref, validateLocation, options) {
409 if (options === void 0) {
410 options = {};
411 }
412 let {
413 window = document.defaultView,
414 v5Compat = false
415 } = options;
416 let globalHistory = window.history;
417 let action = Action.Pop;
418 let listener = null;
419 let index = getIndex();
420 // Index should only be null when we initialize. If not, it's because the
421 // user called history.pushState or history.replaceState directly, in which
422 // case we should log a warning as it will result in bugs.
423 if (index == null) {
424 index = 0;
425 globalHistory.replaceState(_extends({}, globalHistory.state, {
426 idx: index
427 }), "");
428 }
429 function getIndex() {
430 let state = globalHistory.state || {
431 idx: null
432 };
433 return state.idx;
434 }
435 function handlePop() {
436 action = Action.Pop;
437 let nextIndex = getIndex();
438 let delta = nextIndex == null ? null : nextIndex - index;
439 index = nextIndex;
440 if (listener) {
441 listener({
442 action,
443 location: history.location,
444 delta
445 });
446 }
447 }
448 function push(to, state) {
449 action = Action.Push;
450 let location = createLocation(history.location, to, state);
451 if (validateLocation) validateLocation(location, to);
452 index = getIndex() + 1;
453 let historyState = getHistoryState(location, index);
454 let url = history.createHref(location);
455
456 // try...catch because iOS limits us to 100 pushState calls :/
457 try {
458 globalHistory.pushState(historyState, "", url);
459 } catch (error) {
460 // If the exception is because `state` can't be serialized, let that throw
461 // outwards just like a replace call would so the dev knows the cause
462 // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps
463 // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
464 if (error instanceof DOMException && error.name === "DataCloneError") {
465 throw error;
466 }
467 // They are going to lose state here, but there is no real
468 // way to warn them about it since the page will refresh...
469 window.location.assign(url);
470 }
471 if (v5Compat && listener) {
472 listener({
473 action,
474 location: history.location,
475 delta: 1
476 });
477 }
478 }
479 function replace(to, state) {
480 action = Action.Replace;
481 let location = createLocation(history.location, to, state);
482 if (validateLocation) validateLocation(location, to);
483 index = getIndex();
484 let historyState = getHistoryState(location, index);
485 let url = history.createHref(location);
486 globalHistory.replaceState(historyState, "", url);
487 if (v5Compat && listener) {
488 listener({
489 action,
490 location: history.location,
491 delta: 0
492 });
493 }
494 }
495 function createURL(to) {
496 // window.location.origin is "null" (the literal string value) in Firefox
497 // under certain conditions, notably when serving from a local HTML file
498 // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
499 let base = window.location.origin !== "null" ? window.location.origin : window.location.href;
500 let href = typeof to === "string" ? to : createPath(to);
501 // Treating this as a full URL will strip any trailing spaces so we need to
502 // pre-encode them since they might be part of a matching splat param from
503 // an ancestor route
504 href = href.replace(/ $/, "%20");
505 invariant(base, "No window.location.(origin|href) available to create URL for href: " + href);
506 return new URL(href, base);
507 }
508 let history = {
509 get action() {
510 return action;
511 },
512 get location() {
513 return getLocation(window, globalHistory);
514 },
515 listen(fn) {
516 if (listener) {
517 throw new Error("A history only accepts one active listener");
518 }
519 window.addEventListener(PopStateEventType, handlePop);
520 listener = fn;
521 return () => {
522 window.removeEventListener(PopStateEventType, handlePop);
523 listener = null;
524 };
525 },
526 createHref(to) {
527 return createHref(window, to);
528 },
529 createURL,
530 encodeLocation(to) {
531 // Encode a Location the same way window.location would
532 let url = createURL(to);
533 return {
534 pathname: url.pathname,
535 search: url.search,
536 hash: url.hash
537 };
538 },
539 push,
540 replace,
541 go(n) {
542 return globalHistory.go(n);
543 }
544 };
545 return history;
546 }
547
548 //#endregion
549
550 /**
551 * Map of routeId -> data returned from a loader/action/error
552 */
553
554 let ResultType = /*#__PURE__*/function (ResultType) {
555 ResultType["data"] = "data";
556 ResultType["deferred"] = "deferred";
557 ResultType["redirect"] = "redirect";
558 ResultType["error"] = "error";
559 return ResultType;
560 }({});
561
562 /**
563 * Successful result from a loader or action
564 */
565
566 /**
567 * Successful defer() result from a loader or action
568 */
569
570 /**
571 * Redirect result from a loader or action
572 */
573
574 /**
575 * Unsuccessful result from a loader or action
576 */
577
578 /**
579 * Result from a loader or action - potentially successful or unsuccessful
580 */
581
582 /**
583 * Users can specify either lowercase or uppercase form methods on `<Form>`,
584 * useSubmit(), `<fetcher.Form>`, etc.
585 */
586
587 /**
588 * Active navigation/fetcher form methods are exposed in lowercase on the
589 * RouterState
590 */
591
592 /**
593 * In v7, active navigation/fetcher form methods are exposed in uppercase on the
594 * RouterState. This is to align with the normalization done via fetch().
595 */
596
597 // Thanks https://github.com/sindresorhus/type-fest!
598
599 /**
600 * @private
601 * Internal interface to pass around for action submissions, not intended for
602 * external consumption
603 */
604
605 /**
606 * @private
607 * Arguments passed to route loader/action functions. Same for now but we keep
608 * this as a private implementation detail in case they diverge in the future.
609 */
610
611 // TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:
612 // ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs
613 // Also, make them a type alias instead of an interface
614 /**
615 * Arguments passed to loader functions
616 */
617 /**
618 * Arguments passed to action functions
619 */
620 /**
621 * Loaders and actions can return anything except `undefined` (`null` is a
622 * valid return value if there is no data to return). Responses are preferred
623 * and will ease any future migration to Remix
624 */
625 /**
626 * Route loader function signature
627 */
628 /**
629 * Route action function signature
630 */
631 /**
632 * Arguments passed to shouldRevalidate function
633 */
634 /**
635 * Route shouldRevalidate function signature. This runs after any submission
636 * (navigation or fetcher), so we flatten the navigation/fetcher submission
637 * onto the arguments. It shouldn't matter whether it came from a navigation
638 * or a fetcher, what really matters is the URLs and the formData since loaders
639 * have to re-run based on the data models that were potentially mutated.
640 */
641 /**
642 * Function provided by the framework-aware layers to set `hasErrorBoundary`
643 * from the framework-aware `errorElement` prop
644 *
645 * @deprecated Use `mapRouteProperties` instead
646 */
647 /**
648 * Result from a loader or action called via dataStrategy
649 */
650 /**
651 * Function provided by the framework-aware layers to set any framework-specific
652 * properties from framework-agnostic properties
653 */
654 /**
655 * Keys we cannot change from within a lazy() function. We spread all other keys
656 * onto the route. Either they're meaningful to the router, or they'll get
657 * ignored.
658 */
659 const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]);
660
661 /**
662 * lazy() function to load a route definition, which can add non-matching
663 * related properties to a route
664 */
665
666 /**
667 * Base RouteObject with common props shared by all types of routes
668 */
669
670 /**
671 * Index routes must not have children
672 */
673
674 /**
675 * Non-index routes may have children, but cannot have index
676 */
677
678 /**
679 * A route object represents a logical route, with (optionally) its child
680 * routes organized in a tree-like structure.
681 */
682
683 /**
684 * A data route object, which is just a RouteObject with a required unique ID
685 */
686
687 // Recursive helper for finding path parameters in the absence of wildcards
688
689 /**
690 * Examples:
691 * "/a/b/*" -> "*"
692 * ":a" -> "a"
693 * "/a/:b" -> "b"
694 * "/a/blahblahblah:b" -> "b"
695 * "/:a/:b" -> "a" | "b"
696 * "/:a/b/:c/*" -> "a" | "c" | "*"
697 */
698
699 // Attempt to parse the given string segment. If it fails, then just return the
700 // plain string type as a default fallback. Otherwise, return the union of the
701 // parsed string literals that were referenced as dynamic segments in the route.
702 /**
703 * The parameters that were parsed from the URL path.
704 */
705 /**
706 * A RouteMatch contains info about how a route matched a URL.
707 */
708 function isIndexRoute(route) {
709 return route.index === true;
710 }
711
712 // Walk the route tree generating unique IDs where necessary, so we are working
713 // solely with AgnosticDataRouteObject's within the Router
714 function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {
715 if (parentPath === void 0) {
716 parentPath = [];
717 }
718 if (manifest === void 0) {
719 manifest = {};
720 }
721 return routes.map((route, index) => {
722 let treePath = [...parentPath, String(index)];
723 let id = typeof route.id === "string" ? route.id : treePath.join("-");
724 invariant(route.index !== true || !route.children, "Cannot specify children on an index route");
725 invariant(!manifest[id], "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages");
726 if (isIndexRoute(route)) {
727 let indexRoute = _extends({}, route, mapRouteProperties(route), {
728 id
729 });
730 manifest[id] = indexRoute;
731 return indexRoute;
732 } else {
733 let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), {
734 id,
735 children: undefined
736 });
737 manifest[id] = pathOrLayoutRoute;
738 if (route.children) {
739 pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);
740 }
741 return pathOrLayoutRoute;
742 }
743 });
744 }
745
746 /**
747 * Matches the given routes to a location and returns the match data.
748 *
749 * @see https://reactrouter.com/v6/utils/match-routes
750 */
751 function matchRoutes(routes, locationArg, basename) {
752 if (basename === void 0) {
753 basename = "/";
754 }
755 return matchRoutesImpl(routes, locationArg, basename, false);
756 }
757 function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
758 let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
759 let pathname = stripBasename(location.pathname || "/", basename);
760 if (pathname == null) {
761 return null;
762 }
763 let branches = flattenRoutes(routes);
764 rankRouteBranches(branches);
765 let matches = null;
766 for (let i = 0; matches == null && i < branches.length; ++i) {
767 // Incoming pathnames are generally encoded from either window.location
768 // or from router.navigate, but we want to match against the unencoded
769 // paths in the route definitions. Memory router locations won't be
770 // encoded here but there also shouldn't be anything to decode so this
771 // should be a safe operation. This avoids needing matchRoutes to be
772 // history-aware.
773 let decoded = decodePath(pathname);
774 matches = matchRouteBranch(branches[i], decoded, allowPartial);
775 }
776 return matches;
777 }
778 function convertRouteMatchToUiMatch(match, loaderData) {
779 let {
780 route,
781 pathname,
782 params
783 } = match;
784 return {
785 id: route.id,
786 pathname,
787 params,
788 data: loaderData[route.id],
789 handle: route.handle
790 };
791 }
792 function flattenRoutes(routes, branches, parentsMeta, parentPath) {
793 if (branches === void 0) {
794 branches = [];
795 }
796 if (parentsMeta === void 0) {
797 parentsMeta = [];
798 }
799 if (parentPath === void 0) {
800 parentPath = "";
801 }
802 let flattenRoute = (route, index, relativePath) => {
803 let meta = {
804 relativePath: relativePath === undefined ? route.path || "" : relativePath,
805 caseSensitive: route.caseSensitive === true,
806 childrenIndex: index,
807 route
808 };
809 if (meta.relativePath.startsWith("/")) {
810 invariant(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes.");
811 meta.relativePath = meta.relativePath.slice(parentPath.length);
812 }
813 let path = joinPaths([parentPath, meta.relativePath]);
814 let routesMeta = parentsMeta.concat(meta);
815
816 // Add the children before adding this route to the array, so we traverse the
817 // route tree depth-first and child routes appear before their parents in
818 // the "flattened" version.
819 if (route.children && route.children.length > 0) {
820 invariant(
821 // Our types know better, but runtime JS may not!
822 // @ts-expect-error
823 route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\"."));
824 flattenRoutes(route.children, branches, routesMeta, path);
825 }
826
827 // Routes without a path shouldn't ever match by themselves unless they are
828 // index routes, so don't add them to the list of possible branches.
829 if (route.path == null && !route.index) {
830 return;
831 }
832 branches.push({
833 path,
834 score: computeScore(path, route.index),
835 routesMeta
836 });
837 };
838 routes.forEach((route, index) => {
839 var _route$path;
840 // coarse-grain check for optional params
841 if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) {
842 flattenRoute(route, index);
843 } else {
844 for (let exploded of explodeOptionalSegments(route.path)) {
845 flattenRoute(route, index, exploded);
846 }
847 }
848 });
849 return branches;
850 }
851
852 /**
853 * Computes all combinations of optional path segments for a given path,
854 * excluding combinations that are ambiguous and of lower priority.
855 *
856 * For example, `/one/:two?/three/:four?/:five?` explodes to:
857 * - `/one/three`
858 * - `/one/:two/three`
859 * - `/one/three/:four`
860 * - `/one/three/:five`
861 * - `/one/:two/three/:four`
862 * - `/one/:two/three/:five`
863 * - `/one/three/:four/:five`
864 * - `/one/:two/three/:four/:five`
865 */
866 function explodeOptionalSegments(path) {
867 let segments = path.split("/");
868 if (segments.length === 0) return [];
869 let [first, ...rest] = segments;
870
871 // Optional path segments are denoted by a trailing `?`
872 let isOptional = first.endsWith("?");
873 // Compute the corresponding required segment: `foo?` -> `foo`
874 let required = first.replace(/\?$/, "");
875 if (rest.length === 0) {
876 // Intepret empty string as omitting an optional segment
877 // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`
878 return isOptional ? [required, ""] : [required];
879 }
880 let restExploded = explodeOptionalSegments(rest.join("/"));
881 let result = [];
882
883 // All child paths with the prefix. Do this for all children before the
884 // optional version for all children, so we get consistent ordering where the
885 // parent optional aspect is preferred as required. Otherwise, we can get
886 // child sections interspersed where deeper optional segments are higher than
887 // parent optional segments, where for example, /:two would explode _earlier_
888 // then /:one. By always including the parent as required _for all children_
889 // first, we avoid this issue
890 result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/")));
891
892 // Then, if this is an optional value, add all child versions without
893 if (isOptional) {
894 result.push(...restExploded);
895 }
896
897 // for absolute paths, ensure `/` instead of empty segment
898 return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded);
899 }
900 function rankRouteBranches(branches) {
901 branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
902 : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
903 }
904 const paramRe = /^:[\w-]+$/;
905 const dynamicSegmentValue = 3;
906 const indexRouteValue = 2;
907 const emptySegmentValue = 1;
908 const staticSegmentValue = 10;
909 const splatPenalty = -2;
910 const isSplat = s => s === "*";
911 function computeScore(path, index) {
912 let segments = path.split("/");
913 let initialScore = segments.length;
914 if (segments.some(isSplat)) {
915 initialScore += splatPenalty;
916 }
917 if (index) {
918 initialScore += indexRouteValue;
919 }
920 return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
921 }
922 function compareIndexes(a, b) {
923 let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
924 return siblings ?
925 // If two routes are siblings, we should try to match the earlier sibling
926 // first. This allows people to have fine-grained control over the matching
927 // behavior by simply putting routes with identical paths in the order they
928 // want them tried.
929 a[a.length - 1] - b[b.length - 1] :
930 // Otherwise, it doesn't really make sense to rank non-siblings by index,
931 // so they sort equally.
932 0;
933 }
934 function matchRouteBranch(branch, pathname, allowPartial) {
935 if (allowPartial === void 0) {
936 allowPartial = false;
937 }
938 let {
939 routesMeta
940 } = branch;
941 let matchedParams = {};
942 let matchedPathname = "/";
943 let matches = [];
944 for (let i = 0; i < routesMeta.length; ++i) {
945 let meta = routesMeta[i];
946 let end = i === routesMeta.length - 1;
947 let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
948 let match = matchPath({
949 path: meta.relativePath,
950 caseSensitive: meta.caseSensitive,
951 end
952 }, remainingPathname);
953 let route = meta.route;
954 if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
955 match = matchPath({
956 path: meta.relativePath,
957 caseSensitive: meta.caseSensitive,
958 end: false
959 }, remainingPathname);
960 }
961 if (!match) {
962 return null;
963 }
964 Object.assign(matchedParams, match.params);
965 matches.push({
966 // TODO: Can this as be avoided?
967 params: matchedParams,
968 pathname: joinPaths([matchedPathname, match.pathname]),
969 pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
970 route
971 });
972 if (match.pathnameBase !== "/") {
973 matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
974 }
975 }
976 return matches;
977 }
978
979 /**
980 * Returns a path with params interpolated.
981 *
982 * @see https://reactrouter.com/v6/utils/generate-path
983 */
984 function generatePath(originalPath, params) {
985 if (params === void 0) {
986 params = {};
987 }
988 let path = originalPath;
989 if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
990 warning(false, "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\"."));
991 path = path.replace(/\*$/, "/*");
992 }
993
994 // ensure `/` is added at the beginning if the path is absolute
995 const prefix = path.startsWith("/") ? "/" : "";
996 const stringify = p => p == null ? "" : typeof p === "string" ? p : String(p);
997 const segments = path.split(/\/+/).map((segment, index, array) => {
998 const isLastSegment = index === array.length - 1;
999
1000 // only apply the splat if it's the last segment
1001 if (isLastSegment && segment === "*") {
1002 const star = "*";
1003 // Apply the splat
1004 return stringify(params[star]);
1005 }
1006 const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
1007 if (keyMatch) {
1008 const [, key, optional] = keyMatch;
1009 let param = params[key];
1010 invariant(optional === "?" || param != null, "Missing \":" + key + "\" param");
1011 return stringify(param);
1012 }
1013
1014 // Remove any optional markers from optional static segments
1015 return segment.replace(/\?$/g, "");
1016 })
1017 // Remove empty segments
1018 .filter(segment => !!segment);
1019 return prefix + segments.join("/");
1020 }
1021
1022 /**
1023 * A PathPattern is used to match on some portion of a URL pathname.
1024 */
1025
1026 /**
1027 * A PathMatch contains info about how a PathPattern matched on a URL pathname.
1028 */
1029
1030 /**
1031 * Performs pattern matching on a URL pathname and returns information about
1032 * the match.
1033 *
1034 * @see https://reactrouter.com/v6/utils/match-path
1035 */
1036 function matchPath(pattern, pathname) {
1037 if (typeof pattern === "string") {
1038 pattern = {
1039 path: pattern,
1040 caseSensitive: false,
1041 end: true
1042 };
1043 }
1044 let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
1045 let match = pathname.match(matcher);
1046 if (!match) return null;
1047 let matchedPathname = match[0];
1048 let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
1049 let captureGroups = match.slice(1);
1050 let params = compiledParams.reduce((memo, _ref, index) => {
1051 let {
1052 paramName,
1053 isOptional
1054 } = _ref;
1055 // We need to compute the pathnameBase here using the raw splat value
1056 // instead of using params["*"] later because it will be decoded then
1057 if (paramName === "*") {
1058 let splatValue = captureGroups[index] || "";
1059 pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
1060 }
1061 const value = captureGroups[index];
1062 if (isOptional && !value) {
1063 memo[paramName] = undefined;
1064 } else {
1065 memo[paramName] = (value || "").replace(/%2F/g, "/");
1066 }
1067 return memo;
1068 }, {});
1069 return {
1070 params,
1071 pathname: matchedPathname,
1072 pathnameBase,
1073 pattern
1074 };
1075 }
1076 function compilePath(path, caseSensitive, end) {
1077 if (caseSensitive === void 0) {
1078 caseSensitive = false;
1079 }
1080 if (end === void 0) {
1081 end = true;
1082 }
1083 warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\"."));
1084 let params = [];
1085 let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
1086 .replace(/^\/*/, "/") // Make sure it has a leading /
1087 .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars
1088 .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => {
1089 params.push({
1090 paramName,
1091 isOptional: isOptional != null
1092 });
1093 return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
1094 });
1095 if (path.endsWith("*")) {
1096 params.push({
1097 paramName: "*"
1098 });
1099 regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
1100 : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
1101 } else if (end) {
1102 // When matching to the end, ignore trailing slashes
1103 regexpSource += "\\/*$";
1104 } else if (path !== "" && path !== "/") {
1105 // If our path is non-empty and contains anything beyond an initial slash,
1106 // then we have _some_ form of path in our regex, so we should expect to
1107 // match only if we find the end of this path segment. Look for an optional
1108 // non-captured trailing slash (to match a portion of the URL) or the end
1109 // of the path (if we've matched to the end). We used to do this with a
1110 // word boundary but that gives false positives on routes like
1111 // /user-preferences since `-` counts as a word boundary.
1112 regexpSource += "(?:(?=\\/|$))";
1113 } else ;
1114 let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
1115 return [matcher, params];
1116 }
1117 function decodePath(value) {
1118 try {
1119 return value.split("/").map(v => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
1120 } catch (error) {
1121 warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ")."));
1122 return value;
1123 }
1124 }
1125
1126 /**
1127 * @private
1128 */
1129 function stripBasename(pathname, basename) {
1130 if (basename === "/") return pathname;
1131 if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
1132 return null;
1133 }
1134
1135 // We want to leave trailing slash behavior in the user's control, so if they
1136 // specify a basename with a trailing slash, we should support it
1137 let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
1138 let nextChar = pathname.charAt(startIndex);
1139 if (nextChar && nextChar !== "/") {
1140 // pathname does not start with basename/
1141 return null;
1142 }
1143 return pathname.slice(startIndex) || "/";
1144 }
1145
1146 /**
1147 * Returns a resolved path object relative to the given pathname.
1148 *
1149 * @see https://reactrouter.com/v6/utils/resolve-path
1150 */
1151 function resolvePath(to, fromPathname) {
1152 if (fromPathname === void 0) {
1153 fromPathname = "/";
1154 }
1155 let {
1156 pathname: toPathname,
1157 search = "",
1158 hash = ""
1159 } = typeof to === "string" ? parsePath(to) : to;
1160 let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
1161 return {
1162 pathname,
1163 search: normalizeSearch(search),
1164 hash: normalizeHash(hash)
1165 };
1166 }
1167 function resolvePathname(relativePath, fromPathname) {
1168 let segments = fromPathname.replace(/\/+$/, "").split("/");
1169 let relativeSegments = relativePath.split("/");
1170 relativeSegments.forEach(segment => {
1171 if (segment === "..") {
1172 // Keep the root "" segment so the pathname starts at /
1173 if (segments.length > 1) segments.pop();
1174 } else if (segment !== ".") {
1175 segments.push(segment);
1176 }
1177 });
1178 return segments.length > 1 ? segments.join("/") : "/";
1179 }
1180 function getInvalidPathError(char, field, dest, path) {
1181 return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + "a string in <Link to=\"...\"> and the router will parse it for you.";
1182 }
1183
1184 /**
1185 * @private
1186 *
1187 * When processing relative navigation we want to ignore ancestor routes that
1188 * do not contribute to the path, such that index/pathless layout routes don't
1189 * interfere.
1190 *
1191 * For example, when moving a route element into an index route and/or a
1192 * pathless layout route, relative link behavior contained within should stay
1193 * the same. Both of the following examples should link back to the root:
1194 *
1195 * <Route path="/">
1196 * <Route path="accounts" element={<Link to=".."}>
1197 * </Route>
1198 *
1199 * <Route path="/">
1200 * <Route path="accounts">
1201 * <Route element={<AccountsLayout />}> // <-- Does not contribute
1202 * <Route index element={<Link to=".."} /> // <-- Does not contribute
1203 * </Route
1204 * </Route>
1205 * </Route>
1206 */
1207 function getPathContributingMatches(matches) {
1208 return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
1209 }
1210
1211 // Return the array of pathnames for the current route matches - used to
1212 // generate the routePathnames input for resolveTo()
1213 function getResolveToMatches(matches, v7_relativeSplatPath) {
1214 let pathMatches = getPathContributingMatches(matches);
1215
1216 // When v7_relativeSplatPath is enabled, use the full pathname for the leaf
1217 // match so we include splat values for "." links. See:
1218 // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329
1219 if (v7_relativeSplatPath) {
1220 return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
1221 }
1222 return pathMatches.map(match => match.pathnameBase);
1223 }
1224
1225 /**
1226 * @private
1227 */
1228 function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {
1229 if (isPathRelative === void 0) {
1230 isPathRelative = false;
1231 }
1232 let to;
1233 if (typeof toArg === "string") {
1234 to = parsePath(toArg);
1235 } else {
1236 to = _extends({}, toArg);
1237 invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
1238 invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
1239 invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
1240 }
1241 let isEmptyPath = toArg === "" || to.pathname === "";
1242 let toPathname = isEmptyPath ? "/" : to.pathname;
1243 let from;
1244
1245 // Routing is relative to the current pathname if explicitly requested.
1246 //
1247 // If a pathname is explicitly provided in `to`, it should be relative to the
1248 // route context. This is explained in `Note on `<Link to>` values` in our
1249 // migration guide from v5 as a means of disambiguation between `to` values
1250 // that begin with `/` and those that do not. However, this is problematic for
1251 // `to` values that do not provide a pathname. `to` can simply be a search or
1252 // hash string, in which case we should assume that the navigation is relative
1253 // to the current location's pathname and *not* the route pathname.
1254 if (toPathname == null) {
1255 from = locationPathname;
1256 } else {
1257 let routePathnameIndex = routePathnames.length - 1;
1258
1259 // With relative="route" (the default), each leading .. segment means
1260 // "go up one route" instead of "go up one URL segment". This is a key
1261 // difference from how <a href> works and a major reason we call this a
1262 // "to" value instead of a "href".
1263 if (!isPathRelative && toPathname.startsWith("..")) {
1264 let toSegments = toPathname.split("/");
1265 while (toSegments[0] === "..") {
1266 toSegments.shift();
1267 routePathnameIndex -= 1;
1268 }
1269 to.pathname = toSegments.join("/");
1270 }
1271 from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
1272 }
1273 let path = resolvePath(to, from);
1274
1275 // Ensure the pathname has a trailing slash if the original "to" had one
1276 let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
1277 // Or if this was a link to the current path which has a trailing slash
1278 let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
1279 if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
1280 path.pathname += "/";
1281 }
1282 return path;
1283 }
1284
1285 /**
1286 * @private
1287 */
1288 function getToPathname(to) {
1289 // Empty strings should be treated the same as / paths
1290 return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
1291 }
1292
1293 /**
1294 * @private
1295 */
1296 const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
1297
1298 /**
1299 * @private
1300 */
1301 const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
1302
1303 /**
1304 * @private
1305 */
1306 const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
1307
1308 /**
1309 * @private
1310 */
1311 const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
1312 /**
1313 * This is a shortcut for creating `application/json` responses. Converts `data`
1314 * to JSON and sets the `Content-Type` header.
1315 *
1316 * @deprecated The `json` method is deprecated in favor of returning raw objects.
1317 * This method will be removed in v7.
1318 */
1319 const json = function json(data, init) {
1320 if (init === void 0) {
1321 init = {};
1322 }
1323 let responseInit = typeof init === "number" ? {
1324 status: init
1325 } : init;
1326 let headers = new Headers(responseInit.headers);
1327 if (!headers.has("Content-Type")) {
1328 headers.set("Content-Type", "application/json; charset=utf-8");
1329 }
1330 return new Response(JSON.stringify(data), _extends({}, responseInit, {
1331 headers
1332 }));
1333 };
1334 class DataWithResponseInit {
1335 constructor(data, init) {
1336 this.type = "DataWithResponseInit";
1337 this.data = data;
1338 this.init = init || null;
1339 }
1340 }
1341
1342 /**
1343 * Create "responses" that contain `status`/`headers` without forcing
1344 * serialization into an actual `Response` - used by Remix single fetch
1345 */
1346 function data(data, init) {
1347 return new DataWithResponseInit(data, typeof init === "number" ? {
1348 status: init
1349 } : init);
1350 }
1351 class AbortedDeferredError extends Error {}
1352 class DeferredData {
1353 constructor(data, responseInit) {
1354 this.pendingKeysSet = new Set();
1355 this.subscribers = new Set();
1356 this.deferredKeys = [];
1357 invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects");
1358
1359 // Set up an AbortController + Promise we can race against to exit early
1360 // cancellation
1361 let reject;
1362 this.abortPromise = new Promise((_, r) => reject = r);
1363 this.controller = new AbortController();
1364 let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted"));
1365 this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort);
1366 this.controller.signal.addEventListener("abort", onAbort);
1367 this.data = Object.entries(data).reduce((acc, _ref2) => {
1368 let [key, value] = _ref2;
1369 return Object.assign(acc, {
1370 [key]: this.trackPromise(key, value)
1371 });
1372 }, {});
1373 if (this.done) {
1374 // All incoming values were resolved
1375 this.unlistenAbortSignal();
1376 }
1377 this.init = responseInit;
1378 }
1379 trackPromise(key, value) {
1380 if (!(value instanceof Promise)) {
1381 return value;
1382 }
1383 this.deferredKeys.push(key);
1384 this.pendingKeysSet.add(key);
1385
1386 // We store a little wrapper promise that will be extended with
1387 // _data/_error props upon resolve/reject
1388 let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));
1389
1390 // Register rejection listeners to avoid uncaught promise rejections on
1391 // errors or aborted deferred values
1392 promise.catch(() => {});
1393 Object.defineProperty(promise, "_tracked", {
1394 get: () => true
1395 });
1396 return promise;
1397 }
1398 onSettle(promise, key, error, data) {
1399 if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {
1400 this.unlistenAbortSignal();
1401 Object.defineProperty(promise, "_error", {
1402 get: () => error
1403 });
1404 return Promise.reject(error);
1405 }
1406 this.pendingKeysSet.delete(key);
1407 if (this.done) {
1408 // Nothing left to abort!
1409 this.unlistenAbortSignal();
1410 }
1411
1412 // If the promise was resolved/rejected with undefined, we'll throw an error as you
1413 // should always resolve with a value or null
1414 if (error === undefined && data === undefined) {
1415 let undefinedError = new Error("Deferred data for key \"" + key + "\" resolved/rejected with `undefined`, " + "you must resolve/reject with a value or `null`.");
1416 Object.defineProperty(promise, "_error", {
1417 get: () => undefinedError
1418 });
1419 this.emit(false, key);
1420 return Promise.reject(undefinedError);
1421 }
1422 if (data === undefined) {
1423 Object.defineProperty(promise, "_error", {
1424 get: () => error
1425 });
1426 this.emit(false, key);
1427 return Promise.reject(error);
1428 }
1429 Object.defineProperty(promise, "_data", {
1430 get: () => data
1431 });
1432 this.emit(false, key);
1433 return data;
1434 }
1435 emit(aborted, settledKey) {
1436 this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));
1437 }
1438 subscribe(fn) {
1439 this.subscribers.add(fn);
1440 return () => this.subscribers.delete(fn);
1441 }
1442 cancel() {
1443 this.controller.abort();
1444 this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));
1445 this.emit(true);
1446 }
1447 async resolveData(signal) {
1448 let aborted = false;
1449 if (!this.done) {
1450 let onAbort = () => this.cancel();
1451 signal.addEventListener("abort", onAbort);
1452 aborted = await new Promise(resolve => {
1453 this.subscribe(aborted => {
1454 signal.removeEventListener("abort", onAbort);
1455 if (aborted || this.done) {
1456 resolve(aborted);
1457 }
1458 });
1459 });
1460 }
1461 return aborted;
1462 }
1463 get done() {
1464 return this.pendingKeysSet.size === 0;
1465 }
1466 get unwrappedData() {
1467 invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds");
1468 return Object.entries(this.data).reduce((acc, _ref3) => {
1469 let [key, value] = _ref3;
1470 return Object.assign(acc, {
1471 [key]: unwrapTrackedPromise(value)
1472 });
1473 }, {});
1474 }
1475 get pendingKeys() {
1476 return Array.from(this.pendingKeysSet);
1477 }
1478 }
1479 function isTrackedPromise(value) {
1480 return value instanceof Promise && value._tracked === true;
1481 }
1482 function unwrapTrackedPromise(value) {
1483 if (!isTrackedPromise(value)) {
1484 return value;
1485 }
1486 if (value._error) {
1487 throw value._error;
1488 }
1489 return value._data;
1490 }
1491 /**
1492 * @deprecated The `defer` method is deprecated in favor of returning raw
1493 * objects. This method will be removed in v7.
1494 */
1495 const defer = function defer(data, init) {
1496 if (init === void 0) {
1497 init = {};
1498 }
1499 let responseInit = typeof init === "number" ? {
1500 status: init
1501 } : init;
1502 return new DeferredData(data, responseInit);
1503 };
1504 /**
1505 * A redirect response. Sets the status code and the `Location` header.
1506 * Defaults to "302 Found".
1507 */
1508 const redirect = function redirect(url, init) {
1509 if (init === void 0) {
1510 init = 302;
1511 }
1512 let responseInit = init;
1513 if (typeof responseInit === "number") {
1514 responseInit = {
1515 status: responseInit
1516 };
1517 } else if (typeof responseInit.status === "undefined") {
1518 responseInit.status = 302;
1519 }
1520 let headers = new Headers(responseInit.headers);
1521 headers.set("Location", url);
1522 return new Response(null, _extends({}, responseInit, {
1523 headers
1524 }));
1525 };
1526
1527 /**
1528 * A redirect response that will force a document reload to the new location.
1529 * Sets the status code and the `Location` header.
1530 * Defaults to "302 Found".
1531 */
1532 const redirectDocument = (url, init) => {
1533 let response = redirect(url, init);
1534 response.headers.set("X-Remix-Reload-Document", "true");
1535 return response;
1536 };
1537
1538 /**
1539 * A redirect response that will perform a `history.replaceState` instead of a
1540 * `history.pushState` for client-side navigation redirects.
1541 * Sets the status code and the `Location` header.
1542 * Defaults to "302 Found".
1543 */
1544 const replace = (url, init) => {
1545 let response = redirect(url, init);
1546 response.headers.set("X-Remix-Replace", "true");
1547 return response;
1548 };
1549 /**
1550 * @private
1551 * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
1552 *
1553 * We don't export the class for public use since it's an implementation
1554 * detail, but we export the interface above so folks can build their own
1555 * abstractions around instances via isRouteErrorResponse()
1556 */
1557 class ErrorResponseImpl {
1558 constructor(status, statusText, data, internal) {
1559 if (internal === void 0) {
1560 internal = false;
1561 }
1562 this.status = status;
1563 this.statusText = statusText || "";
1564 this.internal = internal;
1565 if (data instanceof Error) {
1566 this.data = data.toString();
1567 this.error = data;
1568 } else {
1569 this.data = data;
1570 }
1571 }
1572 }
1573
1574 /**
1575 * Check if the given error is an ErrorResponse generated from a 4xx/5xx
1576 * Response thrown from an action/loader
1577 */
1578 function isRouteErrorResponse(error) {
1579 return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
1580 }
1581
1582 ////////////////////////////////////////////////////////////////////////////////
1583 //#region Types and Constants
1584 ////////////////////////////////////////////////////////////////////////////////
1585
1586 /**
1587 * A Router instance manages all navigation and data loading/mutations
1588 */
1589 /**
1590 * State maintained internally by the router. During a navigation, all states
1591 * reflect the the "old" location unless otherwise noted.
1592 */
1593 /**
1594 * Data that can be passed into hydrate a Router from SSR
1595 */
1596 /**
1597 * Future flags to toggle new feature behavior
1598 */
1599 /**
1600 * Initialization options for createRouter
1601 */
1602 /**
1603 * State returned from a server-side query() call
1604 */
1605 /**
1606 * A StaticHandler instance manages a singular SSR navigation/fetch event
1607 */
1608 /**
1609 * Subscriber function signature for changes to router state
1610 */
1611 /**
1612 * Function signature for determining the key to be used in scroll restoration
1613 * for a given location
1614 */
1615 /**
1616 * Function signature for determining the current scroll position
1617 */
1618 // Allowed for any navigation or fetch
1619 // Only allowed for navigations
1620 // Only allowed for submission navigations
1621 /**
1622 * Options for a navigate() call for a normal (non-submission) navigation
1623 */
1624 /**
1625 * Options for a navigate() call for a submission navigation
1626 */
1627 /**
1628 * Options to pass to navigate() for a navigation
1629 */
1630 /**
1631 * Options for a fetch() load
1632 */
1633 /**
1634 * Options for a fetch() submission
1635 */
1636 /**
1637 * Options to pass to fetch()
1638 */
1639 /**
1640 * Potential states for state.navigation
1641 */
1642 /**
1643 * Potential states for fetchers
1644 */
1645 /**
1646 * Cached info for active fetcher.load() instances so they can participate
1647 * in revalidation
1648 */
1649 /**
1650 * Identified fetcher.load() calls that need to be revalidated
1651 */
1652 const validMutationMethodsArr = ["post", "put", "patch", "delete"];
1653 const validMutationMethods = new Set(validMutationMethodsArr);
1654 const validRequestMethodsArr = ["get", ...validMutationMethodsArr];
1655 const validRequestMethods = new Set(validRequestMethodsArr);
1656 const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
1657 const redirectPreserveMethodStatusCodes = new Set([307, 308]);
1658 const IDLE_NAVIGATION = {
1659 state: "idle",
1660 location: undefined,
1661 formMethod: undefined,
1662 formAction: undefined,
1663 formEncType: undefined,
1664 formData: undefined,
1665 json: undefined,
1666 text: undefined
1667 };
1668 const IDLE_FETCHER = {
1669 state: "idle",
1670 data: undefined,
1671 formMethod: undefined,
1672 formAction: undefined,
1673 formEncType: undefined,
1674 formData: undefined,
1675 json: undefined,
1676 text: undefined
1677 };
1678 const IDLE_BLOCKER = {
1679 state: "unblocked",
1680 proceed: undefined,
1681 reset: undefined,
1682 location: undefined
1683 };
1684 const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
1685 const defaultMapRouteProperties = route => ({
1686 hasErrorBoundary: Boolean(route.hasErrorBoundary)
1687 });
1688 const TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
1689
1690 //#endregion
1691
1692 ////////////////////////////////////////////////////////////////////////////////
1693 //#region createRouter
1694 ////////////////////////////////////////////////////////////////////////////////
1695
1696 /**
1697 * Create a router and listen to history POP navigations
1698 */
1699 function createRouter(init) {
1700 const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined;
1701 const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
1702 const isServer = !isBrowser;
1703 invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
1704 let mapRouteProperties;
1705 if (init.mapRouteProperties) {
1706 mapRouteProperties = init.mapRouteProperties;
1707 } else if (init.detectErrorBoundary) {
1708 // If they are still using the deprecated version, wrap it with the new API
1709 let detectErrorBoundary = init.detectErrorBoundary;
1710 mapRouteProperties = route => ({
1711 hasErrorBoundary: detectErrorBoundary(route)
1712 });
1713 } else {
1714 mapRouteProperties = defaultMapRouteProperties;
1715 }
1716
1717 // Routes keyed by ID
1718 let manifest = {};
1719 // Routes in tree format for matching
1720 let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);
1721 let inFlightDataRoutes;
1722 let basename = init.basename || "/";
1723 let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;
1724 let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;
1725
1726 // Config driven behavior flags
1727 let future = _extends({
1728 v7_fetcherPersist: false,
1729 v7_normalizeFormMethod: false,
1730 v7_partialHydration: false,
1731 v7_prependBasename: false,
1732 v7_relativeSplatPath: false,
1733 v7_skipActionErrorRevalidation: false
1734 }, init.future);
1735 // Cleanup function for history
1736 let unlistenHistory = null;
1737 // Externally-provided functions to call on all state changes
1738 let subscribers = new Set();
1739 // Externally-provided object to hold scroll restoration locations during routing
1740 let savedScrollPositions = null;
1741 // Externally-provided function to get scroll restoration keys
1742 let getScrollRestorationKey = null;
1743 // Externally-provided function to get current scroll position
1744 let getScrollPosition = null;
1745 // One-time flag to control the initial hydration scroll restoration. Because
1746 // we don't get the saved positions from <ScrollRestoration /> until _after_
1747 // the initial render, we need to manually trigger a separate updateState to
1748 // send along the restoreScrollPosition
1749 // Set to true if we have `hydrationData` since we assume we were SSR'd and that
1750 // SSR did the initial scroll restoration.
1751 let initialScrollRestored = init.hydrationData != null;
1752 let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
1753 let initialErrors = null;
1754 if (initialMatches == null && !patchRoutesOnNavigationImpl) {
1755 // If we do not match a user-provided-route, fall back to the root
1756 // to allow the error boundary to take over
1757 let error = getInternalRouterError(404, {
1758 pathname: init.history.location.pathname
1759 });
1760 let {
1761 matches,
1762 route
1763 } = getShortCircuitMatches(dataRoutes);
1764 initialMatches = matches;
1765 initialErrors = {
1766 [route.id]: error
1767 };
1768 }
1769
1770 // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and
1771 // our initial match is a splat route, clear them out so we run through lazy
1772 // discovery on hydration in case there's a more accurate lazy route match.
1773 // In SSR apps (with `hydrationData`), we expect that the server will send
1774 // up the proper matched routes so we don't want to run lazy discovery on
1775 // initial hydration and want to hydrate into the splat route.
1776 if (initialMatches && !init.hydrationData) {
1777 let fogOfWar = checkFogOfWar(initialMatches, dataRoutes, init.history.location.pathname);
1778 if (fogOfWar.active) {
1779 initialMatches = null;
1780 }
1781 }
1782 let initialized;
1783 if (!initialMatches) {
1784 initialized = false;
1785 initialMatches = [];
1786
1787 // If partial hydration and fog of war is enabled, we will be running
1788 // `patchRoutesOnNavigation` during hydration so include any partial matches as
1789 // the initial matches so we can properly render `HydrateFallback`'s
1790 if (future.v7_partialHydration) {
1791 let fogOfWar = checkFogOfWar(null, dataRoutes, init.history.location.pathname);
1792 if (fogOfWar.active && fogOfWar.matches) {
1793 initialMatches = fogOfWar.matches;
1794 }
1795 }
1796 } else if (initialMatches.some(m => m.route.lazy)) {
1797 // All initialMatches need to be loaded before we're ready. If we have lazy
1798 // functions around still then we'll need to run them in initialize()
1799 initialized = false;
1800 } else if (!initialMatches.some(m => m.route.loader)) {
1801 // If we've got no loaders to run, then we're good to go
1802 initialized = true;
1803 } else if (future.v7_partialHydration) {
1804 // If partial hydration is enabled, we're initialized so long as we were
1805 // provided with hydrationData for every route with a loader, and no loaders
1806 // were marked for explicit hydration
1807 let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
1808 let errors = init.hydrationData ? init.hydrationData.errors : null;
1809 // If errors exist, don't consider routes below the boundary
1810 if (errors) {
1811 let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);
1812 initialized = initialMatches.slice(0, idx + 1).every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
1813 } else {
1814 initialized = initialMatches.every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
1815 }
1816 } else {
1817 // Without partial hydration - we're initialized if we were provided any
1818 // hydrationData - which is expected to be complete
1819 initialized = init.hydrationData != null;
1820 }
1821 let router;
1822 let state = {
1823 historyAction: init.history.action,
1824 location: init.history.location,
1825 matches: initialMatches,
1826 initialized,
1827 navigation: IDLE_NAVIGATION,
1828 // Don't restore on initial updateState() if we were SSR'd
1829 restoreScrollPosition: init.hydrationData != null ? false : null,
1830 preventScrollReset: false,
1831 revalidation: "idle",
1832 loaderData: init.hydrationData && init.hydrationData.loaderData || {},
1833 actionData: init.hydrationData && init.hydrationData.actionData || null,
1834 errors: init.hydrationData && init.hydrationData.errors || initialErrors,
1835 fetchers: new Map(),
1836 blockers: new Map()
1837 };
1838
1839 // -- Stateful internal variables to manage navigations --
1840 // Current navigation in progress (to be committed in completeNavigation)
1841 let pendingAction = Action.Pop;
1842
1843 // Should the current navigation prevent the scroll reset if scroll cannot
1844 // be restored?
1845 let pendingPreventScrollReset = false;
1846
1847 // AbortController for the active navigation
1848 let pendingNavigationController;
1849
1850 // Should the current navigation enable document.startViewTransition?
1851 let pendingViewTransitionEnabled = false;
1852
1853 // Store applied view transitions so we can apply them on POP
1854 let appliedViewTransitions = new Map();
1855
1856 // Cleanup function for persisting applied transitions to sessionStorage
1857 let removePageHideEventListener = null;
1858
1859 // We use this to avoid touching history in completeNavigation if a
1860 // revalidation is entirely uninterrupted
1861 let isUninterruptedRevalidation = false;
1862
1863 // Use this internal flag to force revalidation of all loaders:
1864 // - submissions (completed or interrupted)
1865 // - useRevalidator()
1866 // - X-Remix-Revalidate (from redirect)
1867 let isRevalidationRequired = false;
1868
1869 // Use this internal array to capture routes that require revalidation due
1870 // to a cancelled deferred on action submission
1871 let cancelledDeferredRoutes = [];
1872
1873 // Use this internal array to capture fetcher loads that were cancelled by an
1874 // action navigation and require revalidation
1875 let cancelledFetcherLoads = new Set();
1876
1877 // AbortControllers for any in-flight fetchers
1878 let fetchControllers = new Map();
1879
1880 // Track loads based on the order in which they started
1881 let incrementingLoadId = 0;
1882
1883 // Track the outstanding pending navigation data load to be compared against
1884 // the globally incrementing load when a fetcher load lands after a completed
1885 // navigation
1886 let pendingNavigationLoadId = -1;
1887
1888 // Fetchers that triggered data reloads as a result of their actions
1889 let fetchReloadIds = new Map();
1890
1891 // Fetchers that triggered redirect navigations
1892 let fetchRedirectIds = new Set();
1893
1894 // Most recent href/match for fetcher.load calls for fetchers
1895 let fetchLoadMatches = new Map();
1896
1897 // Ref-count mounted fetchers so we know when it's ok to clean them up
1898 let activeFetchers = new Map();
1899
1900 // Fetchers that have requested a delete when using v7_fetcherPersist,
1901 // they'll be officially removed after they return to idle
1902 let deletedFetchers = new Set();
1903
1904 // Store DeferredData instances for active route matches. When a
1905 // route loader returns defer() we stick one in here. Then, when a nested
1906 // promise resolves we update loaderData. If a new navigation starts we
1907 // cancel active deferreds for eliminated routes.
1908 let activeDeferreds = new Map();
1909
1910 // Store blocker functions in a separate Map outside of router state since
1911 // we don't need to update UI state if they change
1912 let blockerFunctions = new Map();
1913
1914 // Flag to ignore the next history update, so we can revert the URL change on
1915 // a POP navigation that was blocked by the user without touching router state
1916 let unblockBlockerHistoryUpdate = undefined;
1917
1918 // Initialize the router, all side effects should be kicked off from here.
1919 // Implemented as a Fluent API for ease of:
1920 // let router = createRouter(init).initialize();
1921 function initialize() {
1922 // If history informs us of a POP navigation, start the navigation but do not update
1923 // state. We'll update our own state once the navigation completes
1924 unlistenHistory = init.history.listen(_ref => {
1925 let {
1926 action: historyAction,
1927 location,
1928 delta
1929 } = _ref;
1930 // Ignore this event if it was just us resetting the URL from a
1931 // blocked POP navigation
1932 if (unblockBlockerHistoryUpdate) {
1933 unblockBlockerHistoryUpdate();
1934 unblockBlockerHistoryUpdate = undefined;
1935 return;
1936 }
1937 warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location " + "that was not created by @remix-run/router. This will fail silently in " + "production. This can happen if you are navigating outside the router " + "via `window.history.pushState`/`window.location.hash` instead of using " + "router navigation APIs. This can also happen if you are using " + "createHashRouter and the user manually changes the URL.");
1938 let blockerKey = shouldBlockNavigation({
1939 currentLocation: state.location,
1940 nextLocation: location,
1941 historyAction
1942 });
1943 if (blockerKey && delta != null) {
1944 // Restore the URL to match the current UI, but don't update router state
1945 let nextHistoryUpdatePromise = new Promise(resolve => {
1946 unblockBlockerHistoryUpdate = resolve;
1947 });
1948 init.history.go(delta * -1);
1949
1950 // Put the blocker into a blocked state
1951 updateBlocker(blockerKey, {
1952 state: "blocked",
1953 location,
1954 proceed() {
1955 updateBlocker(blockerKey, {
1956 state: "proceeding",
1957 proceed: undefined,
1958 reset: undefined,
1959 location
1960 });
1961 // Re-do the same POP navigation we just blocked, after the url
1962 // restoration is also complete. See:
1963 // https://github.com/remix-run/react-router/issues/11613
1964 nextHistoryUpdatePromise.then(() => init.history.go(delta));
1965 },
1966 reset() {
1967 let blockers = new Map(state.blockers);
1968 blockers.set(blockerKey, IDLE_BLOCKER);
1969 updateState({
1970 blockers
1971 });
1972 }
1973 });
1974 return;
1975 }
1976 return startNavigation(historyAction, location);
1977 });
1978 if (isBrowser) {
1979 // FIXME: This feels gross. How can we cleanup the lines between
1980 // scrollRestoration/appliedTransitions persistance?
1981 restoreAppliedTransitions(routerWindow, appliedViewTransitions);
1982 let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
1983 routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
1984 removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
1985 }
1986
1987 // Kick off initial data load if needed. Use Pop to avoid modifying history
1988 // Note we don't do any handling of lazy here. For SPA's it'll get handled
1989 // in the normal navigation flow. For SSR it's expected that lazy modules are
1990 // resolved prior to router creation since we can't go into a fallbackElement
1991 // UI for SSR'd apps
1992 if (!state.initialized) {
1993 startNavigation(Action.Pop, state.location, {
1994 initialHydration: true
1995 });
1996 }
1997 return router;
1998 }
1999
2000 // Clean up a router and it's side effects
2001 function dispose() {
2002 if (unlistenHistory) {
2003 unlistenHistory();
2004 }
2005 if (removePageHideEventListener) {
2006 removePageHideEventListener();
2007 }
2008 subscribers.clear();
2009 pendingNavigationController && pendingNavigationController.abort();
2010 state.fetchers.forEach((_, key) => deleteFetcher(key));
2011 state.blockers.forEach((_, key) => deleteBlocker(key));
2012 }
2013
2014 // Subscribe to state updates for the router
2015 function subscribe(fn) {
2016 subscribers.add(fn);
2017 return () => subscribers.delete(fn);
2018 }
2019
2020 // Update our state and notify the calling context of the change
2021 function updateState(newState, opts) {
2022 if (opts === void 0) {
2023 opts = {};
2024 }
2025 state = _extends({}, state, newState);
2026
2027 // Prep fetcher cleanup so we can tell the UI which fetcher data entries
2028 // can be removed
2029 let completedFetchers = [];
2030 let deletedFetchersKeys = [];
2031 if (future.v7_fetcherPersist) {
2032 state.fetchers.forEach((fetcher, key) => {
2033 if (fetcher.state === "idle") {
2034 if (deletedFetchers.has(key)) {
2035 // Unmounted from the UI and can be totally removed
2036 deletedFetchersKeys.push(key);
2037 } else {
2038 // Returned to idle but still mounted in the UI, so semi-remains for
2039 // revalidations and such
2040 completedFetchers.push(key);
2041 }
2042 }
2043 });
2044 }
2045
2046 // Iterate over a local copy so that if flushSync is used and we end up
2047 // removing and adding a new subscriber due to the useCallback dependencies,
2048 // we don't get ourselves into a loop calling the new subscriber immediately
2049 [...subscribers].forEach(subscriber => subscriber(state, {
2050 deletedFetchers: deletedFetchersKeys,
2051 viewTransitionOpts: opts.viewTransitionOpts,
2052 flushSync: opts.flushSync === true
2053 }));
2054
2055 // Remove idle fetchers from state since we only care about in-flight fetchers.
2056 if (future.v7_fetcherPersist) {
2057 completedFetchers.forEach(key => state.fetchers.delete(key));
2058 deletedFetchersKeys.forEach(key => deleteFetcher(key));
2059 }
2060 }
2061
2062 // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
2063 // and setting state.[historyAction/location/matches] to the new route.
2064 // - Location is a required param
2065 // - Navigation will always be set to IDLE_NAVIGATION
2066 // - Can pass any other state in newState
2067 function completeNavigation(location, newState, _temp) {
2068 var _location$state, _location$state2;
2069 let {
2070 flushSync
2071 } = _temp === void 0 ? {} : _temp;
2072 // Deduce if we're in a loading/actionReload state:
2073 // - We have committed actionData in the store
2074 // - The current navigation was a mutation submission
2075 // - We're past the submitting state and into the loading state
2076 // - The location being loaded is not the result of a redirect
2077 let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;
2078 let actionData;
2079 if (newState.actionData) {
2080 if (Object.keys(newState.actionData).length > 0) {
2081 actionData = newState.actionData;
2082 } else {
2083 // Empty actionData -> clear prior actionData due to an action error
2084 actionData = null;
2085 }
2086 } else if (isActionReload) {
2087 // Keep the current data if we're wrapping up the action reload
2088 actionData = state.actionData;
2089 } else {
2090 // Clear actionData on any other completed navigations
2091 actionData = null;
2092 }
2093
2094 // Always preserve any existing loaderData from re-used routes
2095 let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;
2096
2097 // On a successful navigation we can assume we got through all blockers
2098 // so we can start fresh
2099 let blockers = state.blockers;
2100 if (blockers.size > 0) {
2101 blockers = new Map(blockers);
2102 blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
2103 }
2104
2105 // Always respect the user flag. Otherwise don't reset on mutation
2106 // submission navigations unless they redirect
2107 let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;
2108
2109 // Commit any in-flight routes at the end of the HMR revalidation "navigation"
2110 if (inFlightDataRoutes) {
2111 dataRoutes = inFlightDataRoutes;
2112 inFlightDataRoutes = undefined;
2113 }
2114 if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) {
2115 init.history.push(location, location.state);
2116 } else if (pendingAction === Action.Replace) {
2117 init.history.replace(location, location.state);
2118 }
2119 let viewTransitionOpts;
2120
2121 // On POP, enable transitions if they were enabled on the original navigation
2122 if (pendingAction === Action.Pop) {
2123 // Forward takes precedence so they behave like the original navigation
2124 let priorPaths = appliedViewTransitions.get(state.location.pathname);
2125 if (priorPaths && priorPaths.has(location.pathname)) {
2126 viewTransitionOpts = {
2127 currentLocation: state.location,
2128 nextLocation: location
2129 };
2130 } else if (appliedViewTransitions.has(location.pathname)) {
2131 // If we don't have a previous forward nav, assume we're popping back to
2132 // the new location and enable if that location previously enabled
2133 viewTransitionOpts = {
2134 currentLocation: location,
2135 nextLocation: state.location
2136 };
2137 }
2138 } else if (pendingViewTransitionEnabled) {
2139 // Store the applied transition on PUSH/REPLACE
2140 let toPaths = appliedViewTransitions.get(state.location.pathname);
2141 if (toPaths) {
2142 toPaths.add(location.pathname);
2143 } else {
2144 toPaths = new Set([location.pathname]);
2145 appliedViewTransitions.set(state.location.pathname, toPaths);
2146 }
2147 viewTransitionOpts = {
2148 currentLocation: state.location,
2149 nextLocation: location
2150 };
2151 }
2152 updateState(_extends({}, newState, {
2153 // matches, errors, fetchers go through as-is
2154 actionData,
2155 loaderData,
2156 historyAction: pendingAction,
2157 location,
2158 initialized: true,
2159 navigation: IDLE_NAVIGATION,
2160 revalidation: "idle",
2161 restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),
2162 preventScrollReset,
2163 blockers
2164 }), {
2165 viewTransitionOpts,
2166 flushSync: flushSync === true
2167 });
2168
2169 // Reset stateful navigation vars
2170 pendingAction = Action.Pop;
2171 pendingPreventScrollReset = false;
2172 pendingViewTransitionEnabled = false;
2173 isUninterruptedRevalidation = false;
2174 isRevalidationRequired = false;
2175 cancelledDeferredRoutes = [];
2176 }
2177
2178 // Trigger a navigation event, which can either be a numerical POP or a PUSH
2179 // replace with an optional submission
2180 async function navigate(to, opts) {
2181 if (typeof to === "number") {
2182 init.history.go(to);
2183 return;
2184 }
2185 let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative);
2186 let {
2187 path,
2188 submission,
2189 error
2190 } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);
2191 let currentLocation = state.location;
2192 let nextLocation = createLocation(state.location, path, opts && opts.state);
2193
2194 // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded
2195 // URL from window.location, so we need to encode it here so the behavior
2196 // remains the same as POP and non-data-router usages. new URL() does all
2197 // the same encoding we'd get from a history.pushState/window.location read
2198 // without having to touch history
2199 nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));
2200 let userReplace = opts && opts.replace != null ? opts.replace : undefined;
2201 let historyAction = Action.Push;
2202 if (userReplace === true) {
2203 historyAction = Action.Replace;
2204 } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
2205 // By default on submissions to the current location we REPLACE so that
2206 // users don't have to double-click the back button to get to the prior
2207 // location. If the user redirects to a different location from the
2208 // action/loader this will be ignored and the redirect will be a PUSH
2209 historyAction = Action.Replace;
2210 }
2211 let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined;
2212 let flushSync = (opts && opts.flushSync) === true;
2213 let blockerKey = shouldBlockNavigation({
2214 currentLocation,
2215 nextLocation,
2216 historyAction
2217 });
2218 if (blockerKey) {
2219 // Put the blocker into a blocked state
2220 updateBlocker(blockerKey, {
2221 state: "blocked",
2222 location: nextLocation,
2223 proceed() {
2224 updateBlocker(blockerKey, {
2225 state: "proceeding",
2226 proceed: undefined,
2227 reset: undefined,
2228 location: nextLocation
2229 });
2230 // Send the same navigation through
2231 navigate(to, opts);
2232 },
2233 reset() {
2234 let blockers = new Map(state.blockers);
2235 blockers.set(blockerKey, IDLE_BLOCKER);
2236 updateState({
2237 blockers
2238 });
2239 }
2240 });
2241 return;
2242 }
2243 return await startNavigation(historyAction, nextLocation, {
2244 submission,
2245 // Send through the formData serialization error if we have one so we can
2246 // render at the right error boundary after we match routes
2247 pendingError: error,
2248 preventScrollReset,
2249 replace: opts && opts.replace,
2250 enableViewTransition: opts && opts.viewTransition,
2251 flushSync
2252 });
2253 }
2254
2255 // Revalidate all current loaders. If a navigation is in progress or if this
2256 // is interrupted by a navigation, allow this to "succeed" by calling all
2257 // loaders during the next loader round
2258 function revalidate() {
2259 interruptActiveLoads();
2260 updateState({
2261 revalidation: "loading"
2262 });
2263
2264 // If we're currently submitting an action, we don't need to start a new
2265 // navigation, we'll just let the follow up loader execution call all loaders
2266 if (state.navigation.state === "submitting") {
2267 return;
2268 }
2269
2270 // If we're currently in an idle state, start a new navigation for the current
2271 // action/location and mark it as uninterrupted, which will skip the history
2272 // update in completeNavigation
2273 if (state.navigation.state === "idle") {
2274 startNavigation(state.historyAction, state.location, {
2275 startUninterruptedRevalidation: true
2276 });
2277 return;
2278 }
2279
2280 // Otherwise, if we're currently in a loading state, just start a new
2281 // navigation to the navigation.location but do not trigger an uninterrupted
2282 // revalidation so that history correctly updates once the navigation completes
2283 startNavigation(pendingAction || state.historyAction, state.navigation.location, {
2284 overrideNavigation: state.navigation,
2285 // Proxy through any rending view transition
2286 enableViewTransition: pendingViewTransitionEnabled === true
2287 });
2288 }
2289
2290 // Start a navigation to the given action/location. Can optionally provide a
2291 // overrideNavigation which will override the normalLoad in the case of a redirect
2292 // navigation
2293 async function startNavigation(historyAction, location, opts) {
2294 // Abort any in-progress navigations and start a new one. Unset any ongoing
2295 // uninterrupted revalidations unless told otherwise, since we want this
2296 // new navigation to update history normally
2297 pendingNavigationController && pendingNavigationController.abort();
2298 pendingNavigationController = null;
2299 pendingAction = historyAction;
2300 isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
2301
2302 // Save the current scroll position every time we start a new navigation,
2303 // and track whether we should reset scroll on completion
2304 saveScrollPosition(state.location, state.matches);
2305 pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
2306 pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
2307 let routesToUse = inFlightDataRoutes || dataRoutes;
2308 let loadingNavigation = opts && opts.overrideNavigation;
2309 let matches = matchRoutes(routesToUse, location, basename);
2310 let flushSync = (opts && opts.flushSync) === true;
2311 let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
2312 if (fogOfWar.active && fogOfWar.matches) {
2313 matches = fogOfWar.matches;
2314 }
2315
2316 // Short circuit with a 404 on the root error boundary if we match nothing
2317 if (!matches) {
2318 let {
2319 error,
2320 notFoundMatches,
2321 route
2322 } = handleNavigational404(location.pathname);
2323 completeNavigation(location, {
2324 matches: notFoundMatches,
2325 loaderData: {},
2326 errors: {
2327 [route.id]: error
2328 }
2329 }, {
2330 flushSync
2331 });
2332 return;
2333 }
2334
2335 // Short circuit if it's only a hash change and not a revalidation or
2336 // mutation submission.
2337 //
2338 // Ignore on initial page loads because since the initial hydration will always
2339 // be "same hash". For example, on /page#hash and submit a <Form method="post">
2340 // which will default to a navigation to /page
2341 if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
2342 completeNavigation(location, {
2343 matches
2344 }, {
2345 flushSync
2346 });
2347 return;
2348 }
2349
2350 // Create a controller/Request for this navigation
2351 pendingNavigationController = new AbortController();
2352 let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
2353 let pendingActionResult;
2354 if (opts && opts.pendingError) {
2355 // If we have a pendingError, it means the user attempted a GET submission
2356 // with binary FormData so assign here and skip to handleLoaders. That
2357 // way we handle calling loaders above the boundary etc. It's not really
2358 // different from an actionError in that sense.
2359 pendingActionResult = [findNearestBoundary(matches).route.id, {
2360 type: ResultType.error,
2361 error: opts.pendingError
2362 }];
2363 } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
2364 // Call action if we received an action submission
2365 let actionResult = await handleAction(request, location, opts.submission, matches, fogOfWar.active, {
2366 replace: opts.replace,
2367 flushSync
2368 });
2369 if (actionResult.shortCircuited) {
2370 return;
2371 }
2372
2373 // If we received a 404 from handleAction, it's because we couldn't lazily
2374 // discover the destination route so we don't want to call loaders
2375 if (actionResult.pendingActionResult) {
2376 let [routeId, result] = actionResult.pendingActionResult;
2377 if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
2378 pendingNavigationController = null;
2379 completeNavigation(location, {
2380 matches: actionResult.matches,
2381 loaderData: {},
2382 errors: {
2383 [routeId]: result.error
2384 }
2385 });
2386 return;
2387 }
2388 }
2389 matches = actionResult.matches || matches;
2390 pendingActionResult = actionResult.pendingActionResult;
2391 loadingNavigation = getLoadingNavigation(location, opts.submission);
2392 flushSync = false;
2393 // No need to do fog of war matching again on loader execution
2394 fogOfWar.active = false;
2395
2396 // Create a GET request for the loaders
2397 request = createClientSideRequest(init.history, request.url, request.signal);
2398 }
2399
2400 // Call loaders
2401 let {
2402 shortCircuited,
2403 matches: updatedMatches,
2404 loaderData,
2405 errors
2406 } = await handleLoaders(request, location, matches, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult);
2407 if (shortCircuited) {
2408 return;
2409 }
2410
2411 // Clean up now that the action/loaders have completed. Don't clean up if
2412 // we short circuited because pendingNavigationController will have already
2413 // been assigned to a new controller for the next navigation
2414 pendingNavigationController = null;
2415 completeNavigation(location, _extends({
2416 matches: updatedMatches || matches
2417 }, getActionDataForCommit(pendingActionResult), {
2418 loaderData,
2419 errors
2420 }));
2421 }
2422
2423 // Call the action matched by the leaf route for this navigation and handle
2424 // redirects/errors
2425 async function handleAction(request, location, submission, matches, isFogOfWar, opts) {
2426 if (opts === void 0) {
2427 opts = {};
2428 }
2429 interruptActiveLoads();
2430
2431 // Put us in a submitting state
2432 let navigation = getSubmittingNavigation(location, submission);
2433 updateState({
2434 navigation
2435 }, {
2436 flushSync: opts.flushSync === true
2437 });
2438 if (isFogOfWar) {
2439 let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
2440 if (discoverResult.type === "aborted") {
2441 return {
2442 shortCircuited: true
2443 };
2444 } else if (discoverResult.type === "error") {
2445 let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
2446 return {
2447 matches: discoverResult.partialMatches,
2448 pendingActionResult: [boundaryId, {
2449 type: ResultType.error,
2450 error: discoverResult.error
2451 }]
2452 };
2453 } else if (!discoverResult.matches) {
2454 let {
2455 notFoundMatches,
2456 error,
2457 route
2458 } = handleNavigational404(location.pathname);
2459 return {
2460 matches: notFoundMatches,
2461 pendingActionResult: [route.id, {
2462 type: ResultType.error,
2463 error
2464 }]
2465 };
2466 } else {
2467 matches = discoverResult.matches;
2468 }
2469 }
2470
2471 // Call our action and get the result
2472 let result;
2473 let actionMatch = getTargetMatch(matches, location);
2474 if (!actionMatch.route.action && !actionMatch.route.lazy) {
2475 result = {
2476 type: ResultType.error,
2477 error: getInternalRouterError(405, {
2478 method: request.method,
2479 pathname: location.pathname,
2480 routeId: actionMatch.route.id
2481 })
2482 };
2483 } else {
2484 let results = await callDataStrategy("action", state, request, [actionMatch], matches, null);
2485 result = results[actionMatch.route.id];
2486 if (request.signal.aborted) {
2487 return {
2488 shortCircuited: true
2489 };
2490 }
2491 }
2492 if (isRedirectResult(result)) {
2493 let replace;
2494 if (opts && opts.replace != null) {
2495 replace = opts.replace;
2496 } else {
2497 // If the user didn't explicity indicate replace behavior, replace if
2498 // we redirected to the exact same location we're currently at to avoid
2499 // double back-buttons
2500 let location = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename);
2501 replace = location === state.location.pathname + state.location.search;
2502 }
2503 await startRedirectNavigation(request, result, true, {
2504 submission,
2505 replace
2506 });
2507 return {
2508 shortCircuited: true
2509 };
2510 }
2511 if (isDeferredResult(result)) {
2512 throw getInternalRouterError(400, {
2513 type: "defer-action"
2514 });
2515 }
2516 if (isErrorResult(result)) {
2517 // Store off the pending error - we use it to determine which loaders
2518 // to call and will commit it when we complete the navigation
2519 let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
2520
2521 // By default, all submissions to the current location are REPLACE
2522 // navigations, but if the action threw an error that'll be rendered in
2523 // an errorElement, we fall back to PUSH so that the user can use the
2524 // back button to get back to the pre-submission form location to try
2525 // again
2526 if ((opts && opts.replace) !== true) {
2527 pendingAction = Action.Push;
2528 }
2529 return {
2530 matches,
2531 pendingActionResult: [boundaryMatch.route.id, result]
2532 };
2533 }
2534 return {
2535 matches,
2536 pendingActionResult: [actionMatch.route.id, result]
2537 };
2538 }
2539
2540 // Call all applicable loaders for the given matches, handling redirects,
2541 // errors, etc.
2542 async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) {
2543 // Figure out the right navigation we want to use for data loading
2544 let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
2545
2546 // If this was a redirect from an action we don't have a "submission" but
2547 // we have it on the loading navigation so use that if available
2548 let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
2549
2550 // If this is an uninterrupted revalidation, we remain in our current idle
2551 // state. If not, we need to switch to our loading state and load data,
2552 // preserving any new action data or existing action data (in the case of
2553 // a revalidation interrupting an actionReload)
2554 // If we have partialHydration enabled, then don't update the state for the
2555 // initial data load since it's not a "navigation"
2556 let shouldUpdateNavigationState = !isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration);
2557
2558 // When fog of war is enabled, we enter our `loading` state earlier so we
2559 // can discover new routes during the `loading` state. We skip this if
2560 // we've already run actions since we would have done our matching already.
2561 // If the children() function threw then, we want to proceed with the
2562 // partial matches it discovered.
2563 if (isFogOfWar) {
2564 if (shouldUpdateNavigationState) {
2565 let actionData = getUpdatedActionData(pendingActionResult);
2566 updateState(_extends({
2567 navigation: loadingNavigation
2568 }, actionData !== undefined ? {
2569 actionData
2570 } : {}), {
2571 flushSync
2572 });
2573 }
2574 let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
2575 if (discoverResult.type === "aborted") {
2576 return {
2577 shortCircuited: true
2578 };
2579 } else if (discoverResult.type === "error") {
2580 let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
2581 return {
2582 matches: discoverResult.partialMatches,
2583 loaderData: {},
2584 errors: {
2585 [boundaryId]: discoverResult.error
2586 }
2587 };
2588 } else if (!discoverResult.matches) {
2589 let {
2590 error,
2591 notFoundMatches,
2592 route
2593 } = handleNavigational404(location.pathname);
2594 return {
2595 matches: notFoundMatches,
2596 loaderData: {},
2597 errors: {
2598 [route.id]: error
2599 }
2600 };
2601 } else {
2602 matches = discoverResult.matches;
2603 }
2604 }
2605 let routesToUse = inFlightDataRoutes || dataRoutes;
2606 let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult);
2607
2608 // Cancel pending deferreds for no-longer-matched routes or routes we're
2609 // about to reload. Note that if this is an action reload we would have
2610 // already cancelled all pending deferreds so this would be a no-op
2611 cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId));
2612 pendingNavigationLoadId = ++incrementingLoadId;
2613
2614 // Short circuit if we have no loaders to run
2615 if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
2616 let updatedFetchers = markFetchRedirectsDone();
2617 completeNavigation(location, _extends({
2618 matches,
2619 loaderData: {},
2620 // Commit pending error if we're short circuiting
2621 errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
2622 [pendingActionResult[0]]: pendingActionResult[1].error
2623 } : null
2624 }, getActionDataForCommit(pendingActionResult), updatedFetchers ? {
2625 fetchers: new Map(state.fetchers)
2626 } : {}), {
2627 flushSync
2628 });
2629 return {
2630 shortCircuited: true
2631 };
2632 }
2633 if (shouldUpdateNavigationState) {
2634 let updates = {};
2635 if (!isFogOfWar) {
2636 // Only update navigation/actionNData if we didn't already do it above
2637 updates.navigation = loadingNavigation;
2638 let actionData = getUpdatedActionData(pendingActionResult);
2639 if (actionData !== undefined) {
2640 updates.actionData = actionData;
2641 }
2642 }
2643 if (revalidatingFetchers.length > 0) {
2644 updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
2645 }
2646 updateState(updates, {
2647 flushSync
2648 });
2649 }
2650 revalidatingFetchers.forEach(rf => {
2651 abortFetcher(rf.key);
2652 if (rf.controller) {
2653 // Fetchers use an independent AbortController so that aborting a fetcher
2654 // (via deleteFetcher) does not abort the triggering navigation that
2655 // triggered the revalidation
2656 fetchControllers.set(rf.key, rf.controller);
2657 }
2658 });
2659
2660 // Proxy navigation abort through to revalidation fetchers
2661 let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key));
2662 if (pendingNavigationController) {
2663 pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations);
2664 }
2665 let {
2666 loaderResults,
2667 fetcherResults
2668 } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, request);
2669 if (request.signal.aborted) {
2670 return {
2671 shortCircuited: true
2672 };
2673 }
2674
2675 // Clean up _after_ loaders have completed. Don't clean up if we short
2676 // circuited because fetchControllers would have been aborted and
2677 // reassigned to new controllers for the next navigation
2678 if (pendingNavigationController) {
2679 pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
2680 }
2681 revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key));
2682
2683 // If any loaders returned a redirect Response, start a new REPLACE navigation
2684 let redirect = findRedirect(loaderResults);
2685 if (redirect) {
2686 await startRedirectNavigation(request, redirect.result, true, {
2687 replace
2688 });
2689 return {
2690 shortCircuited: true
2691 };
2692 }
2693 redirect = findRedirect(fetcherResults);
2694 if (redirect) {
2695 // If this redirect came from a fetcher make sure we mark it in
2696 // fetchRedirectIds so it doesn't get revalidated on the next set of
2697 // loader executions
2698 fetchRedirectIds.add(redirect.key);
2699 await startRedirectNavigation(request, redirect.result, true, {
2700 replace
2701 });
2702 return {
2703 shortCircuited: true
2704 };
2705 }
2706
2707 // Process and commit output from loaders
2708 let {
2709 loaderData,
2710 errors
2711 } = processLoaderData(state, matches, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds);
2712
2713 // Wire up subscribers to update loaderData as promises settle
2714 activeDeferreds.forEach((deferredData, routeId) => {
2715 deferredData.subscribe(aborted => {
2716 // Note: No need to updateState here since the TrackedPromise on
2717 // loaderData is stable across resolve/reject
2718 // Remove this instance if we were aborted or if promises have settled
2719 if (aborted || deferredData.done) {
2720 activeDeferreds.delete(routeId);
2721 }
2722 });
2723 });
2724
2725 // Preserve SSR errors during partial hydration
2726 if (future.v7_partialHydration && initialHydration && state.errors) {
2727 errors = _extends({}, state.errors, errors);
2728 }
2729 let updatedFetchers = markFetchRedirectsDone();
2730 let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
2731 let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
2732 return _extends({
2733 matches,
2734 loaderData,
2735 errors
2736 }, shouldUpdateFetchers ? {
2737 fetchers: new Map(state.fetchers)
2738 } : {});
2739 }
2740 function getUpdatedActionData(pendingActionResult) {
2741 if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
2742 // This is cast to `any` currently because `RouteData`uses any and it
2743 // would be a breaking change to use any.
2744 // TODO: v7 - change `RouteData` to use `unknown` instead of `any`
2745 return {
2746 [pendingActionResult[0]]: pendingActionResult[1].data
2747 };
2748 } else if (state.actionData) {
2749 if (Object.keys(state.actionData).length === 0) {
2750 return null;
2751 } else {
2752 return state.actionData;
2753 }
2754 }
2755 }
2756 function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
2757 revalidatingFetchers.forEach(rf => {
2758 let fetcher = state.fetchers.get(rf.key);
2759 let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined);
2760 state.fetchers.set(rf.key, revalidatingFetcher);
2761 });
2762 return new Map(state.fetchers);
2763 }
2764
2765 // Trigger a fetcher load/submit for the given fetcher key
2766 function fetch(key, routeId, href, opts) {
2767 if (isServer) {
2768 throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback.");
2769 }
2770 abortFetcher(key);
2771 let flushSync = (opts && opts.flushSync) === true;
2772 let routesToUse = inFlightDataRoutes || dataRoutes;
2773 let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative);
2774 let matches = matchRoutes(routesToUse, normalizedPath, basename);
2775 let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
2776 if (fogOfWar.active && fogOfWar.matches) {
2777 matches = fogOfWar.matches;
2778 }
2779 if (!matches) {
2780 setFetcherError(key, routeId, getInternalRouterError(404, {
2781 pathname: normalizedPath
2782 }), {
2783 flushSync
2784 });
2785 return;
2786 }
2787 let {
2788 path,
2789 submission,
2790 error
2791 } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);
2792 if (error) {
2793 setFetcherError(key, routeId, error, {
2794 flushSync
2795 });
2796 return;
2797 }
2798 let match = getTargetMatch(matches, path);
2799 let preventScrollReset = (opts && opts.preventScrollReset) === true;
2800 if (submission && isMutationMethod(submission.formMethod)) {
2801 handleFetcherAction(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
2802 return;
2803 }
2804
2805 // Store off the match so we can call it's shouldRevalidate on subsequent
2806 // revalidations
2807 fetchLoadMatches.set(key, {
2808 routeId,
2809 path
2810 });
2811 handleFetcherLoader(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
2812 }
2813
2814 // Call the action for the matched fetcher.submit(), and then handle redirects,
2815 // errors, and revalidation
2816 async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync, preventScrollReset, submission) {
2817 interruptActiveLoads();
2818 fetchLoadMatches.delete(key);
2819 function detectAndHandle405Error(m) {
2820 if (!m.route.action && !m.route.lazy) {
2821 let error = getInternalRouterError(405, {
2822 method: submission.formMethod,
2823 pathname: path,
2824 routeId: routeId
2825 });
2826 setFetcherError(key, routeId, error, {
2827 flushSync
2828 });
2829 return true;
2830 }
2831 return false;
2832 }
2833 if (!isFogOfWar && detectAndHandle405Error(match)) {
2834 return;
2835 }
2836
2837 // Put this fetcher into it's submitting state
2838 let existingFetcher = state.fetchers.get(key);
2839 updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
2840 flushSync
2841 });
2842 let abortController = new AbortController();
2843 let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
2844 if (isFogOfWar) {
2845 let discoverResult = await discoverRoutes(requestMatches, path, fetchRequest.signal);
2846 if (discoverResult.type === "aborted") {
2847 return;
2848 } else if (discoverResult.type === "error") {
2849 setFetcherError(key, routeId, discoverResult.error, {
2850 flushSync
2851 });
2852 return;
2853 } else if (!discoverResult.matches) {
2854 setFetcherError(key, routeId, getInternalRouterError(404, {
2855 pathname: path
2856 }), {
2857 flushSync
2858 });
2859 return;
2860 } else {
2861 requestMatches = discoverResult.matches;
2862 match = getTargetMatch(requestMatches, path);
2863 if (detectAndHandle405Error(match)) {
2864 return;
2865 }
2866 }
2867 }
2868
2869 // Call the action for the fetcher
2870 fetchControllers.set(key, abortController);
2871 let originatingLoadId = incrementingLoadId;
2872 let actionResults = await callDataStrategy("action", state, fetchRequest, [match], requestMatches, key);
2873 let actionResult = actionResults[match.route.id];
2874 if (fetchRequest.signal.aborted) {
2875 // We can delete this so long as we weren't aborted by our own fetcher
2876 // re-submit which would have put _new_ controller is in fetchControllers
2877 if (fetchControllers.get(key) === abortController) {
2878 fetchControllers.delete(key);
2879 }
2880 return;
2881 }
2882
2883 // When using v7_fetcherPersist, we don't want errors bubbling up to the UI
2884 // or redirects processed for unmounted fetchers so we just revert them to
2885 // idle
2886 if (future.v7_fetcherPersist && deletedFetchers.has(key)) {
2887 if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
2888 updateFetcherState(key, getDoneFetcher(undefined));
2889 return;
2890 }
2891 // Let SuccessResult's fall through for revalidation
2892 } else {
2893 if (isRedirectResult(actionResult)) {
2894 fetchControllers.delete(key);
2895 if (pendingNavigationLoadId > originatingLoadId) {
2896 // A new navigation was kicked off after our action started, so that
2897 // should take precedence over this redirect navigation. We already
2898 // set isRevalidationRequired so all loaders for the new route should
2899 // fire unless opted out via shouldRevalidate
2900 updateFetcherState(key, getDoneFetcher(undefined));
2901 return;
2902 } else {
2903 fetchRedirectIds.add(key);
2904 updateFetcherState(key, getLoadingFetcher(submission));
2905 return startRedirectNavigation(fetchRequest, actionResult, false, {
2906 fetcherSubmission: submission,
2907 preventScrollReset
2908 });
2909 }
2910 }
2911
2912 // Process any non-redirect errors thrown
2913 if (isErrorResult(actionResult)) {
2914 setFetcherError(key, routeId, actionResult.error);
2915 return;
2916 }
2917 }
2918 if (isDeferredResult(actionResult)) {
2919 throw getInternalRouterError(400, {
2920 type: "defer-action"
2921 });
2922 }
2923
2924 // Start the data load for current matches, or the next location if we're
2925 // in the middle of a navigation
2926 let nextLocation = state.navigation.location || state.location;
2927 let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);
2928 let routesToUse = inFlightDataRoutes || dataRoutes;
2929 let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;
2930 invariant(matches, "Didn't find any matches after fetcher action");
2931 let loadId = ++incrementingLoadId;
2932 fetchReloadIds.set(key, loadId);
2933 let loadFetcher = getLoadingFetcher(submission, actionResult.data);
2934 state.fetchers.set(key, loadFetcher);
2935 let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]);
2936
2937 // Put all revalidating fetchers into the loading state, except for the
2938 // current fetcher which we want to keep in it's current loading state which
2939 // contains it's action submission info + action data
2940 revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {
2941 let staleKey = rf.key;
2942 let existingFetcher = state.fetchers.get(staleKey);
2943 let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined);
2944 state.fetchers.set(staleKey, revalidatingFetcher);
2945 abortFetcher(staleKey);
2946 if (rf.controller) {
2947 fetchControllers.set(staleKey, rf.controller);
2948 }
2949 });
2950 updateState({
2951 fetchers: new Map(state.fetchers)
2952 });
2953 let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key));
2954 abortController.signal.addEventListener("abort", abortPendingFetchRevalidations);
2955 let {
2956 loaderResults,
2957 fetcherResults
2958 } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
2959 if (abortController.signal.aborted) {
2960 return;
2961 }
2962 abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
2963 fetchReloadIds.delete(key);
2964 fetchControllers.delete(key);
2965 revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));
2966 let redirect = findRedirect(loaderResults);
2967 if (redirect) {
2968 return startRedirectNavigation(revalidationRequest, redirect.result, false, {
2969 preventScrollReset
2970 });
2971 }
2972 redirect = findRedirect(fetcherResults);
2973 if (redirect) {
2974 // If this redirect came from a fetcher make sure we mark it in
2975 // fetchRedirectIds so it doesn't get revalidated on the next set of
2976 // loader executions
2977 fetchRedirectIds.add(redirect.key);
2978 return startRedirectNavigation(revalidationRequest, redirect.result, false, {
2979 preventScrollReset
2980 });
2981 }
2982
2983 // Process and commit output from loaders
2984 let {
2985 loaderData,
2986 errors
2987 } = processLoaderData(state, matches, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);
2988
2989 // Since we let revalidations complete even if the submitting fetcher was
2990 // deleted, only put it back to idle if it hasn't been deleted
2991 if (state.fetchers.has(key)) {
2992 let doneFetcher = getDoneFetcher(actionResult.data);
2993 state.fetchers.set(key, doneFetcher);
2994 }
2995 abortStaleFetchLoads(loadId);
2996
2997 // If we are currently in a navigation loading state and this fetcher is
2998 // more recent than the navigation, we want the newer data so abort the
2999 // navigation and complete it with the fetcher data
3000 if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
3001 invariant(pendingAction, "Expected pending action");
3002 pendingNavigationController && pendingNavigationController.abort();
3003 completeNavigation(state.navigation.location, {
3004 matches,
3005 loaderData,
3006 errors,
3007 fetchers: new Map(state.fetchers)
3008 });
3009 } else {
3010 // otherwise just update with the fetcher data, preserving any existing
3011 // loaderData for loaders that did not need to reload. We have to
3012 // manually merge here since we aren't going through completeNavigation
3013 updateState({
3014 errors,
3015 loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),
3016 fetchers: new Map(state.fetchers)
3017 });
3018 isRevalidationRequired = false;
3019 }
3020 }
3021
3022 // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
3023 async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync, preventScrollReset, submission) {
3024 let existingFetcher = state.fetchers.get(key);
3025 updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), {
3026 flushSync
3027 });
3028 let abortController = new AbortController();
3029 let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
3030 if (isFogOfWar) {
3031 let discoverResult = await discoverRoutes(matches, path, fetchRequest.signal);
3032 if (discoverResult.type === "aborted") {
3033 return;
3034 } else if (discoverResult.type === "error") {
3035 setFetcherError(key, routeId, discoverResult.error, {
3036 flushSync
3037 });
3038 return;
3039 } else if (!discoverResult.matches) {
3040 setFetcherError(key, routeId, getInternalRouterError(404, {
3041 pathname: path
3042 }), {
3043 flushSync
3044 });
3045 return;
3046 } else {
3047 matches = discoverResult.matches;
3048 match = getTargetMatch(matches, path);
3049 }
3050 }
3051
3052 // Call the loader for this fetcher route match
3053 fetchControllers.set(key, abortController);
3054 let originatingLoadId = incrementingLoadId;
3055 let results = await callDataStrategy("loader", state, fetchRequest, [match], matches, key);
3056 let result = results[match.route.id];
3057
3058 // Deferred isn't supported for fetcher loads, await everything and treat it
3059 // as a normal load. resolveDeferredData will return undefined if this
3060 // fetcher gets aborted, so we just leave result untouched and short circuit
3061 // below if that happens
3062 if (isDeferredResult(result)) {
3063 result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;
3064 }
3065
3066 // We can delete this so long as we weren't aborted by our our own fetcher
3067 // re-load which would have put _new_ controller is in fetchControllers
3068 if (fetchControllers.get(key) === abortController) {
3069 fetchControllers.delete(key);
3070 }
3071 if (fetchRequest.signal.aborted) {
3072 return;
3073 }
3074
3075 // We don't want errors bubbling up or redirects followed for unmounted
3076 // fetchers, so short circuit here if it was removed from the UI
3077 if (deletedFetchers.has(key)) {
3078 updateFetcherState(key, getDoneFetcher(undefined));
3079 return;
3080 }
3081
3082 // If the loader threw a redirect Response, start a new REPLACE navigation
3083 if (isRedirectResult(result)) {
3084 if (pendingNavigationLoadId > originatingLoadId) {
3085 // A new navigation was kicked off after our loader started, so that
3086 // should take precedence over this redirect navigation
3087 updateFetcherState(key, getDoneFetcher(undefined));
3088 return;
3089 } else {
3090 fetchRedirectIds.add(key);
3091 await startRedirectNavigation(fetchRequest, result, false, {
3092 preventScrollReset
3093 });
3094 return;
3095 }
3096 }
3097
3098 // Process any non-redirect errors thrown
3099 if (isErrorResult(result)) {
3100 setFetcherError(key, routeId, result.error);
3101 return;
3102 }
3103 invariant(!isDeferredResult(result), "Unhandled fetcher deferred data");
3104
3105 // Put the fetcher back into an idle state
3106 updateFetcherState(key, getDoneFetcher(result.data));
3107 }
3108
3109 /**
3110 * Utility function to handle redirects returned from an action or loader.
3111 * Normally, a redirect "replaces" the navigation that triggered it. So, for
3112 * example:
3113 *
3114 * - user is on /a
3115 * - user clicks a link to /b
3116 * - loader for /b redirects to /c
3117 *
3118 * In a non-JS app the browser would track the in-flight navigation to /b and
3119 * then replace it with /c when it encountered the redirect response. In
3120 * the end it would only ever update the URL bar with /c.
3121 *
3122 * In client-side routing using pushState/replaceState, we aim to emulate
3123 * this behavior and we also do not update history until the end of the
3124 * navigation (including processed redirects). This means that we never
3125 * actually touch history until we've processed redirects, so we just use
3126 * the history action from the original navigation (PUSH or REPLACE).
3127 */
3128 async function startRedirectNavigation(request, redirect, isNavigation, _temp2) {
3129 let {
3130 submission,
3131 fetcherSubmission,
3132 preventScrollReset,
3133 replace
3134 } = _temp2 === void 0 ? {} : _temp2;
3135 if (redirect.response.headers.has("X-Remix-Revalidate")) {
3136 isRevalidationRequired = true;
3137 }
3138 let location = redirect.response.headers.get("Location");
3139 invariant(location, "Expected a Location header on the redirect Response");
3140 location = normalizeRedirectLocation(location, new URL(request.url), basename);
3141 let redirectLocation = createLocation(state.location, location, {
3142 _isRedirect: true
3143 });
3144 if (isBrowser) {
3145 let isDocumentReload = false;
3146 if (redirect.response.headers.has("X-Remix-Reload-Document")) {
3147 // Hard reload if the response contained X-Remix-Reload-Document
3148 isDocumentReload = true;
3149 } else if (ABSOLUTE_URL_REGEX.test(location)) {
3150 const url = init.history.createURL(location);
3151 isDocumentReload =
3152 // Hard reload if it's an absolute URL to a new origin
3153 url.origin !== routerWindow.location.origin ||
3154 // Hard reload if it's an absolute URL that does not match our basename
3155 stripBasename(url.pathname, basename) == null;
3156 }
3157 if (isDocumentReload) {
3158 if (replace) {
3159 routerWindow.location.replace(location);
3160 } else {
3161 routerWindow.location.assign(location);
3162 }
3163 return;
3164 }
3165 }
3166
3167 // There's no need to abort on redirects, since we don't detect the
3168 // redirect until the action/loaders have settled
3169 pendingNavigationController = null;
3170 let redirectHistoryAction = replace === true || redirect.response.headers.has("X-Remix-Replace") ? Action.Replace : Action.Push;
3171
3172 // Use the incoming submission if provided, fallback on the active one in
3173 // state.navigation
3174 let {
3175 formMethod,
3176 formAction,
3177 formEncType
3178 } = state.navigation;
3179 if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
3180 submission = getSubmissionFromNavigation(state.navigation);
3181 }
3182
3183 // If this was a 307/308 submission we want to preserve the HTTP method and
3184 // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the
3185 // redirected location
3186 let activeSubmission = submission || fetcherSubmission;
3187 if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
3188 await startNavigation(redirectHistoryAction, redirectLocation, {
3189 submission: _extends({}, activeSubmission, {
3190 formAction: location
3191 }),
3192 // Preserve these flags across redirects
3193 preventScrollReset: preventScrollReset || pendingPreventScrollReset,
3194 enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
3195 });
3196 } else {
3197 // If we have a navigation submission, we will preserve it through the
3198 // redirect navigation
3199 let overrideNavigation = getLoadingNavigation(redirectLocation, submission);
3200 await startNavigation(redirectHistoryAction, redirectLocation, {
3201 overrideNavigation,
3202 // Send fetcher submissions through for shouldRevalidate
3203 fetcherSubmission,
3204 // Preserve these flags across redirects
3205 preventScrollReset: preventScrollReset || pendingPreventScrollReset,
3206 enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
3207 });
3208 }
3209 }
3210
3211 // Utility wrapper for calling dataStrategy client-side without having to
3212 // pass around the manifest, mapRouteProperties, etc.
3213 async function callDataStrategy(type, state, request, matchesToLoad, matches, fetcherKey) {
3214 let results;
3215 let dataResults = {};
3216 try {
3217 results = await callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties);
3218 } catch (e) {
3219 // If the outer dataStrategy method throws, just return the error for all
3220 // matches - and it'll naturally bubble to the root
3221 matchesToLoad.forEach(m => {
3222 dataResults[m.route.id] = {
3223 type: ResultType.error,
3224 error: e
3225 };
3226 });
3227 return dataResults;
3228 }
3229 for (let [routeId, result] of Object.entries(results)) {
3230 if (isRedirectDataStrategyResultResult(result)) {
3231 let response = result.result;
3232 dataResults[routeId] = {
3233 type: ResultType.redirect,
3234 response: normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, future.v7_relativeSplatPath)
3235 };
3236 } else {
3237 dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
3238 }
3239 }
3240 return dataResults;
3241 }
3242 async function callLoadersAndMaybeResolveData(state, matches, matchesToLoad, fetchersToLoad, request) {
3243 let currentMatches = state.matches;
3244
3245 // Kick off loaders and fetchers in parallel
3246 let loaderResultsPromise = callDataStrategy("loader", state, request, matchesToLoad, matches, null);
3247 let fetcherResultsPromise = Promise.all(fetchersToLoad.map(async f => {
3248 if (f.matches && f.match && f.controller) {
3249 let results = await callDataStrategy("loader", state, createClientSideRequest(init.history, f.path, f.controller.signal), [f.match], f.matches, f.key);
3250 let result = results[f.match.route.id];
3251 // Fetcher results are keyed by fetcher key from here on out, not routeId
3252 return {
3253 [f.key]: result
3254 };
3255 } else {
3256 return Promise.resolve({
3257 [f.key]: {
3258 type: ResultType.error,
3259 error: getInternalRouterError(404, {
3260 pathname: f.path
3261 })
3262 }
3263 });
3264 }
3265 }));
3266 let loaderResults = await loaderResultsPromise;
3267 let fetcherResults = (await fetcherResultsPromise).reduce((acc, r) => Object.assign(acc, r), {});
3268 await Promise.all([resolveNavigationDeferredResults(matches, loaderResults, request.signal, currentMatches, state.loaderData), resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad)]);
3269 return {
3270 loaderResults,
3271 fetcherResults
3272 };
3273 }
3274 function interruptActiveLoads() {
3275 // Every interruption triggers a revalidation
3276 isRevalidationRequired = true;
3277
3278 // Cancel pending route-level deferreds and mark cancelled routes for
3279 // revalidation
3280 cancelledDeferredRoutes.push(...cancelActiveDeferreds());
3281
3282 // Abort in-flight fetcher loads
3283 fetchLoadMatches.forEach((_, key) => {
3284 if (fetchControllers.has(key)) {
3285 cancelledFetcherLoads.add(key);
3286 }
3287 abortFetcher(key);
3288 });
3289 }
3290 function updateFetcherState(key, fetcher, opts) {
3291 if (opts === void 0) {
3292 opts = {};
3293 }
3294 state.fetchers.set(key, fetcher);
3295 updateState({
3296 fetchers: new Map(state.fetchers)
3297 }, {
3298 flushSync: (opts && opts.flushSync) === true
3299 });
3300 }
3301 function setFetcherError(key, routeId, error, opts) {
3302 if (opts === void 0) {
3303 opts = {};
3304 }
3305 let boundaryMatch = findNearestBoundary(state.matches, routeId);
3306 deleteFetcher(key);
3307 updateState({
3308 errors: {
3309 [boundaryMatch.route.id]: error
3310 },
3311 fetchers: new Map(state.fetchers)
3312 }, {
3313 flushSync: (opts && opts.flushSync) === true
3314 });
3315 }
3316 function getFetcher(key) {
3317 if (future.v7_fetcherPersist) {
3318 activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
3319 // If this fetcher was previously marked for deletion, unmark it since we
3320 // have a new instance
3321 if (deletedFetchers.has(key)) {
3322 deletedFetchers.delete(key);
3323 }
3324 }
3325 return state.fetchers.get(key) || IDLE_FETCHER;
3326 }
3327 function deleteFetcher(key) {
3328 let fetcher = state.fetchers.get(key);
3329 // Don't abort the controller if this is a deletion of a fetcher.submit()
3330 // in it's loading phase since - we don't want to abort the corresponding
3331 // revalidation and want them to complete and land
3332 if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
3333 abortFetcher(key);
3334 }
3335 fetchLoadMatches.delete(key);
3336 fetchReloadIds.delete(key);
3337 fetchRedirectIds.delete(key);
3338 deletedFetchers.delete(key);
3339 cancelledFetcherLoads.delete(key);
3340 state.fetchers.delete(key);
3341 }
3342 function deleteFetcherAndUpdateState(key) {
3343 if (future.v7_fetcherPersist) {
3344 let count = (activeFetchers.get(key) || 0) - 1;
3345 if (count <= 0) {
3346 activeFetchers.delete(key);
3347 deletedFetchers.add(key);
3348 } else {
3349 activeFetchers.set(key, count);
3350 }
3351 } else {
3352 deleteFetcher(key);
3353 }
3354 updateState({
3355 fetchers: new Map(state.fetchers)
3356 });
3357 }
3358 function abortFetcher(key) {
3359 let controller = fetchControllers.get(key);
3360 if (controller) {
3361 controller.abort();
3362 fetchControllers.delete(key);
3363 }
3364 }
3365 function markFetchersDone(keys) {
3366 for (let key of keys) {
3367 let fetcher = getFetcher(key);
3368 let doneFetcher = getDoneFetcher(fetcher.data);
3369 state.fetchers.set(key, doneFetcher);
3370 }
3371 }
3372 function markFetchRedirectsDone() {
3373 let doneKeys = [];
3374 let updatedFetchers = false;
3375 for (let key of fetchRedirectIds) {
3376 let fetcher = state.fetchers.get(key);
3377 invariant(fetcher, "Expected fetcher: " + key);
3378 if (fetcher.state === "loading") {
3379 fetchRedirectIds.delete(key);
3380 doneKeys.push(key);
3381 updatedFetchers = true;
3382 }
3383 }
3384 markFetchersDone(doneKeys);
3385 return updatedFetchers;
3386 }
3387 function abortStaleFetchLoads(landedId) {
3388 let yeetedKeys = [];
3389 for (let [key, id] of fetchReloadIds) {
3390 if (id < landedId) {
3391 let fetcher = state.fetchers.get(key);
3392 invariant(fetcher, "Expected fetcher: " + key);
3393 if (fetcher.state === "loading") {
3394 abortFetcher(key);
3395 fetchReloadIds.delete(key);
3396 yeetedKeys.push(key);
3397 }
3398 }
3399 }
3400 markFetchersDone(yeetedKeys);
3401 return yeetedKeys.length > 0;
3402 }
3403 function getBlocker(key, fn) {
3404 let blocker = state.blockers.get(key) || IDLE_BLOCKER;
3405 if (blockerFunctions.get(key) !== fn) {
3406 blockerFunctions.set(key, fn);
3407 }
3408 return blocker;
3409 }
3410 function deleteBlocker(key) {
3411 state.blockers.delete(key);
3412 blockerFunctions.delete(key);
3413 }
3414
3415 // Utility function to update blockers, ensuring valid state transitions
3416 function updateBlocker(key, newBlocker) {
3417 let blocker = state.blockers.get(key) || IDLE_BLOCKER;
3418
3419 // Poor mans state machine :)
3420 // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM
3421 invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state);
3422 let blockers = new Map(state.blockers);
3423 blockers.set(key, newBlocker);
3424 updateState({
3425 blockers
3426 });
3427 }
3428 function shouldBlockNavigation(_ref2) {
3429 let {
3430 currentLocation,
3431 nextLocation,
3432 historyAction
3433 } = _ref2;
3434 if (blockerFunctions.size === 0) {
3435 return;
3436 }
3437
3438 // We ony support a single active blocker at the moment since we don't have
3439 // any compelling use cases for multi-blocker yet
3440 if (blockerFunctions.size > 1) {
3441 warning(false, "A router only supports one blocker at a time");
3442 }
3443 let entries = Array.from(blockerFunctions.entries());
3444 let [blockerKey, blockerFunction] = entries[entries.length - 1];
3445 let blocker = state.blockers.get(blockerKey);
3446 if (blocker && blocker.state === "proceeding") {
3447 // If the blocker is currently proceeding, we don't need to re-check
3448 // it and can let this navigation continue
3449 return;
3450 }
3451
3452 // At this point, we know we're unblocked/blocked so we need to check the
3453 // user-provided blocker function
3454 if (blockerFunction({
3455 currentLocation,
3456 nextLocation,
3457 historyAction
3458 })) {
3459 return blockerKey;
3460 }
3461 }
3462 function handleNavigational404(pathname) {
3463 let error = getInternalRouterError(404, {
3464 pathname
3465 });
3466 let routesToUse = inFlightDataRoutes || dataRoutes;
3467 let {
3468 matches,
3469 route
3470 } = getShortCircuitMatches(routesToUse);
3471
3472 // Cancel all pending deferred on 404s since we don't keep any routes
3473 cancelActiveDeferreds();
3474 return {
3475 notFoundMatches: matches,
3476 route,
3477 error
3478 };
3479 }
3480 function cancelActiveDeferreds(predicate) {
3481 let cancelledRouteIds = [];
3482 activeDeferreds.forEach((dfd, routeId) => {
3483 if (!predicate || predicate(routeId)) {
3484 // Cancel the deferred - but do not remove from activeDeferreds here -
3485 // we rely on the subscribers to do that so our tests can assert proper
3486 // cleanup via _internalActiveDeferreds
3487 dfd.cancel();
3488 cancelledRouteIds.push(routeId);
3489 activeDeferreds.delete(routeId);
3490 }
3491 });
3492 return cancelledRouteIds;
3493 }
3494
3495 // Opt in to capturing and reporting scroll positions during navigations,
3496 // used by the <ScrollRestoration> component
3497 function enableScrollRestoration(positions, getPosition, getKey) {
3498 savedScrollPositions = positions;
3499 getScrollPosition = getPosition;
3500 getScrollRestorationKey = getKey || null;
3501
3502 // Perform initial hydration scroll restoration, since we miss the boat on
3503 // the initial updateState() because we've not yet rendered <ScrollRestoration/>
3504 // and therefore have no savedScrollPositions available
3505 if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
3506 initialScrollRestored = true;
3507 let y = getSavedScrollPosition(state.location, state.matches);
3508 if (y != null) {
3509 updateState({
3510 restoreScrollPosition: y
3511 });
3512 }
3513 }
3514 return () => {
3515 savedScrollPositions = null;
3516 getScrollPosition = null;
3517 getScrollRestorationKey = null;
3518 };
3519 }
3520 function getScrollKey(location, matches) {
3521 if (getScrollRestorationKey) {
3522 let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData)));
3523 return key || location.key;
3524 }
3525 return location.key;
3526 }
3527 function saveScrollPosition(location, matches) {
3528 if (savedScrollPositions && getScrollPosition) {
3529 let key = getScrollKey(location, matches);
3530 savedScrollPositions[key] = getScrollPosition();
3531 }
3532 }
3533 function getSavedScrollPosition(location, matches) {
3534 if (savedScrollPositions) {
3535 let key = getScrollKey(location, matches);
3536 let y = savedScrollPositions[key];
3537 if (typeof y === "number") {
3538 return y;
3539 }
3540 }
3541 return null;
3542 }
3543 function checkFogOfWar(matches, routesToUse, pathname) {
3544 if (patchRoutesOnNavigationImpl) {
3545 if (!matches) {
3546 let fogMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
3547 return {
3548 active: true,
3549 matches: fogMatches || []
3550 };
3551 } else {
3552 if (Object.keys(matches[0].params).length > 0) {
3553 // If we matched a dynamic param or a splat, it might only be because
3554 // we haven't yet discovered other routes that would match with a
3555 // higher score. Call patchRoutesOnNavigation just to be sure
3556 let partialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
3557 return {
3558 active: true,
3559 matches: partialMatches
3560 };
3561 }
3562 }
3563 }
3564 return {
3565 active: false,
3566 matches: null
3567 };
3568 }
3569 async function discoverRoutes(matches, pathname, signal) {
3570 if (!patchRoutesOnNavigationImpl) {
3571 return {
3572 type: "success",
3573 matches
3574 };
3575 }
3576 let partialMatches = matches;
3577 while (true) {
3578 let isNonHMR = inFlightDataRoutes == null;
3579 let routesToUse = inFlightDataRoutes || dataRoutes;
3580 let localManifest = manifest;
3581 try {
3582 await patchRoutesOnNavigationImpl({
3583 path: pathname,
3584 matches: partialMatches,
3585 patch: (routeId, children) => {
3586 if (signal.aborted) return;
3587 patchRoutesImpl(routeId, children, routesToUse, localManifest, mapRouteProperties);
3588 }
3589 });
3590 } catch (e) {
3591 return {
3592 type: "error",
3593 error: e,
3594 partialMatches
3595 };
3596 } finally {
3597 // If we are not in the middle of an HMR revalidation and we changed the
3598 // routes, provide a new identity so when we `updateState` at the end of
3599 // this navigation/fetch `router.routes` will be a new identity and
3600 // trigger a re-run of memoized `router.routes` dependencies.
3601 // HMR will already update the identity and reflow when it lands
3602 // `inFlightDataRoutes` in `completeNavigation`
3603 if (isNonHMR && !signal.aborted) {
3604 dataRoutes = [...dataRoutes];
3605 }
3606 }
3607 if (signal.aborted) {
3608 return {
3609 type: "aborted"
3610 };
3611 }
3612 let newMatches = matchRoutes(routesToUse, pathname, basename);
3613 if (newMatches) {
3614 return {
3615 type: "success",
3616 matches: newMatches
3617 };
3618 }
3619 let newPartialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
3620
3621 // Avoid loops if the second pass results in the same partial matches
3622 if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every((m, i) => m.route.id === newPartialMatches[i].route.id)) {
3623 return {
3624 type: "success",
3625 matches: null
3626 };
3627 }
3628 partialMatches = newPartialMatches;
3629 }
3630 }
3631 function _internalSetRoutes(newRoutes) {
3632 manifest = {};
3633 inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest);
3634 }
3635 function patchRoutes(routeId, children) {
3636 let isNonHMR = inFlightDataRoutes == null;
3637 let routesToUse = inFlightDataRoutes || dataRoutes;
3638 patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties);
3639
3640 // If we are not in the middle of an HMR revalidation and we changed the
3641 // routes, provide a new identity and trigger a reflow via `updateState`
3642 // to re-run memoized `router.routes` dependencies.
3643 // HMR will already update the identity and reflow when it lands
3644 // `inFlightDataRoutes` in `completeNavigation`
3645 if (isNonHMR) {
3646 dataRoutes = [...dataRoutes];
3647 updateState({});
3648 }
3649 }
3650 router = {
3651 get basename() {
3652 return basename;
3653 },
3654 get future() {
3655 return future;
3656 },
3657 get state() {
3658 return state;
3659 },
3660 get routes() {
3661 return dataRoutes;
3662 },
3663 get window() {
3664 return routerWindow;
3665 },
3666 initialize,
3667 subscribe,
3668 enableScrollRestoration,
3669 navigate,
3670 fetch,
3671 revalidate,
3672 // Passthrough to history-aware createHref used by useHref so we get proper
3673 // hash-aware URLs in DOM paths
3674 createHref: to => init.history.createHref(to),
3675 encodeLocation: to => init.history.encodeLocation(to),
3676 getFetcher,
3677 deleteFetcher: deleteFetcherAndUpdateState,
3678 dispose,
3679 getBlocker,
3680 deleteBlocker,
3681 patchRoutes,
3682 _internalFetchControllers: fetchControllers,
3683 _internalActiveDeferreds: activeDeferreds,
3684 // TODO: Remove setRoutes, it's temporary to avoid dealing with
3685 // updating the tree while validating the update algorithm.
3686 _internalSetRoutes
3687 };
3688 return router;
3689 }
3690 //#endregion
3691
3692 ////////////////////////////////////////////////////////////////////////////////
3693 //#region createStaticHandler
3694 ////////////////////////////////////////////////////////////////////////////////
3695
3696 const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
3697
3698 /**
3699 * Future flags to toggle new feature behavior
3700 */
3701
3702 function createStaticHandler(routes, opts) {
3703 invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
3704 let manifest = {};
3705 let basename = (opts ? opts.basename : null) || "/";
3706 let mapRouteProperties;
3707 if (opts != null && opts.mapRouteProperties) {
3708 mapRouteProperties = opts.mapRouteProperties;
3709 } else if (opts != null && opts.detectErrorBoundary) {
3710 // If they are still using the deprecated version, wrap it with the new API
3711 let detectErrorBoundary = opts.detectErrorBoundary;
3712 mapRouteProperties = route => ({
3713 hasErrorBoundary: detectErrorBoundary(route)
3714 });
3715 } else {
3716 mapRouteProperties = defaultMapRouteProperties;
3717 }
3718 // Config driven behavior flags
3719 let future = _extends({
3720 v7_relativeSplatPath: false,
3721 v7_throwAbortReason: false
3722 }, opts ? opts.future : null);
3723 let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest);
3724
3725 /**
3726 * The query() method is intended for document requests, in which we want to
3727 * call an optional action and potentially multiple loaders for all nested
3728 * routes. It returns a StaticHandlerContext object, which is very similar
3729 * to the router state (location, loaderData, actionData, errors, etc.) and
3730 * also adds SSR-specific information such as the statusCode and headers
3731 * from action/loaders Responses.
3732 *
3733 * It _should_ never throw and should report all errors through the
3734 * returned context.errors object, properly associating errors to their error
3735 * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be
3736 * used to emulate React error boundaries during SSr by performing a second
3737 * pass only down to the boundaryId.
3738 *
3739 * The one exception where we do not return a StaticHandlerContext is when a
3740 * redirect response is returned or thrown from any action/loader. We
3741 * propagate that out and return the raw Response so the HTTP server can
3742 * return it directly.
3743 *
3744 * - `opts.requestContext` is an optional server context that will be passed
3745 * to actions/loaders in the `context` parameter
3746 * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent
3747 * the bubbling of errors which allows single-fetch-type implementations
3748 * where the client will handle the bubbling and we may need to return data
3749 * for the handling route
3750 */
3751 async function query(request, _temp3) {
3752 let {
3753 requestContext,
3754 skipLoaderErrorBubbling,
3755 dataStrategy
3756 } = _temp3 === void 0 ? {} : _temp3;
3757 let url = new URL(request.url);
3758 let method = request.method;
3759 let location = createLocation("", createPath(url), null, "default");
3760 let matches = matchRoutes(dataRoutes, location, basename);
3761
3762 // SSR supports HEAD requests while SPA doesn't
3763 if (!isValidMethod(method) && method !== "HEAD") {
3764 let error = getInternalRouterError(405, {
3765 method
3766 });
3767 let {
3768 matches: methodNotAllowedMatches,
3769 route
3770 } = getShortCircuitMatches(dataRoutes);
3771 return {
3772 basename,
3773 location,
3774 matches: methodNotAllowedMatches,
3775 loaderData: {},
3776 actionData: null,
3777 errors: {
3778 [route.id]: error
3779 },
3780 statusCode: error.status,
3781 loaderHeaders: {},
3782 actionHeaders: {},
3783 activeDeferreds: null
3784 };
3785 } else if (!matches) {
3786 let error = getInternalRouterError(404, {
3787 pathname: location.pathname
3788 });
3789 let {
3790 matches: notFoundMatches,
3791 route
3792 } = getShortCircuitMatches(dataRoutes);
3793 return {
3794 basename,
3795 location,
3796 matches: notFoundMatches,
3797 loaderData: {},
3798 actionData: null,
3799 errors: {
3800 [route.id]: error
3801 },
3802 statusCode: error.status,
3803 loaderHeaders: {},
3804 actionHeaders: {},
3805 activeDeferreds: null
3806 };
3807 }
3808 let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null);
3809 if (isResponse(result)) {
3810 return result;
3811 }
3812
3813 // When returning StaticHandlerContext, we patch back in the location here
3814 // since we need it for React Context. But this helps keep our submit and
3815 // loadRouteData operating on a Request instead of a Location
3816 return _extends({
3817 location,
3818 basename
3819 }, result);
3820 }
3821
3822 /**
3823 * The queryRoute() method is intended for targeted route requests, either
3824 * for fetch ?_data requests or resource route requests. In this case, we
3825 * are only ever calling a single action or loader, and we are returning the
3826 * returned value directly. In most cases, this will be a Response returned
3827 * from the action/loader, but it may be a primitive or other value as well -
3828 * and in such cases the calling context should handle that accordingly.
3829 *
3830 * We do respect the throw/return differentiation, so if an action/loader
3831 * throws, then this method will throw the value. This is important so we
3832 * can do proper boundary identification in Remix where a thrown Response
3833 * must go to the Catch Boundary but a returned Response is happy-path.
3834 *
3835 * One thing to note is that any Router-initiated Errors that make sense
3836 * to associate with a status code will be thrown as an ErrorResponse
3837 * instance which include the raw Error, such that the calling context can
3838 * serialize the error as they see fit while including the proper response
3839 * code. Examples here are 404 and 405 errors that occur prior to reaching
3840 * any user-defined loaders.
3841 *
3842 * - `opts.routeId` allows you to specify the specific route handler to call.
3843 * If not provided the handler will determine the proper route by matching
3844 * against `request.url`
3845 * - `opts.requestContext` is an optional server context that will be passed
3846 * to actions/loaders in the `context` parameter
3847 */
3848 async function queryRoute(request, _temp4) {
3849 let {
3850 routeId,
3851 requestContext,
3852 dataStrategy
3853 } = _temp4 === void 0 ? {} : _temp4;
3854 let url = new URL(request.url);
3855 let method = request.method;
3856 let location = createLocation("", createPath(url), null, "default");
3857 let matches = matchRoutes(dataRoutes, location, basename);
3858
3859 // SSR supports HEAD requests while SPA doesn't
3860 if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
3861 throw getInternalRouterError(405, {
3862 method
3863 });
3864 } else if (!matches) {
3865 throw getInternalRouterError(404, {
3866 pathname: location.pathname
3867 });
3868 }
3869 let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);
3870 if (routeId && !match) {
3871 throw getInternalRouterError(403, {
3872 pathname: location.pathname,
3873 routeId
3874 });
3875 } else if (!match) {
3876 // This should never hit I don't think?
3877 throw getInternalRouterError(404, {
3878 pathname: location.pathname
3879 });
3880 }
3881 let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match);
3882 if (isResponse(result)) {
3883 return result;
3884 }
3885 let error = result.errors ? Object.values(result.errors)[0] : undefined;
3886 if (error !== undefined) {
3887 // If we got back result.errors, that means the loader/action threw
3888 // _something_ that wasn't a Response, but it's not guaranteed/required
3889 // to be an `instanceof Error` either, so we have to use throw here to
3890 // preserve the "error" state outside of queryImpl.
3891 throw error;
3892 }
3893
3894 // Pick off the right state value to return
3895 if (result.actionData) {
3896 return Object.values(result.actionData)[0];
3897 }
3898 if (result.loaderData) {
3899 var _result$activeDeferre;
3900 let data = Object.values(result.loaderData)[0];
3901 if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {
3902 data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];
3903 }
3904 return data;
3905 }
3906 return undefined;
3907 }
3908 async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch) {
3909 invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
3910 try {
3911 if (isMutationMethod(request.method.toLowerCase())) {
3912 let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null);
3913 return result;
3914 }
3915 let result = await loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch);
3916 return isResponse(result) ? result : _extends({}, result, {
3917 actionData: null,
3918 actionHeaders: {}
3919 });
3920 } catch (e) {
3921 // If the user threw/returned a Response in callLoaderOrAction for a
3922 // `queryRoute` call, we throw the `DataStrategyResult` to bail out early
3923 // and then return or throw the raw Response here accordingly
3924 if (isDataStrategyResult(e) && isResponse(e.result)) {
3925 if (e.type === ResultType.error) {
3926 throw e.result;
3927 }
3928 return e.result;
3929 }
3930 // Redirects are always returned since they don't propagate to catch
3931 // boundaries
3932 if (isRedirectResponse(e)) {
3933 return e;
3934 }
3935 throw e;
3936 }
3937 }
3938 async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {
3939 let result;
3940 if (!actionMatch.route.action && !actionMatch.route.lazy) {
3941 let error = getInternalRouterError(405, {
3942 method: request.method,
3943 pathname: new URL(request.url).pathname,
3944 routeId: actionMatch.route.id
3945 });
3946 if (isRouteRequest) {
3947 throw error;
3948 }
3949 result = {
3950 type: ResultType.error,
3951 error
3952 };
3953 } else {
3954 let results = await callDataStrategy("action", request, [actionMatch], matches, isRouteRequest, requestContext, dataStrategy);
3955 result = results[actionMatch.route.id];
3956 if (request.signal.aborted) {
3957 throwStaticHandlerAbortedError(request, isRouteRequest, future);
3958 }
3959 }
3960 if (isRedirectResult(result)) {
3961 // Uhhhh - this should never happen, we should always throw these from
3962 // callLoaderOrAction, but the type narrowing here keeps TS happy and we
3963 // can get back on the "throw all redirect responses" train here should
3964 // this ever happen :/
3965 throw new Response(null, {
3966 status: result.response.status,
3967 headers: {
3968 Location: result.response.headers.get("Location")
3969 }
3970 });
3971 }
3972 if (isDeferredResult(result)) {
3973 let error = getInternalRouterError(400, {
3974 type: "defer-action"
3975 });
3976 if (isRouteRequest) {
3977 throw error;
3978 }
3979 result = {
3980 type: ResultType.error,
3981 error
3982 };
3983 }
3984 if (isRouteRequest) {
3985 // Note: This should only be non-Response values if we get here, since
3986 // isRouteRequest should throw any Response received in callLoaderOrAction
3987 if (isErrorResult(result)) {
3988 throw result.error;
3989 }
3990 return {
3991 matches: [actionMatch],
3992 loaderData: {},
3993 actionData: {
3994 [actionMatch.route.id]: result.data
3995 },
3996 errors: null,
3997 // Note: statusCode + headers are unused here since queryRoute will
3998 // return the raw Response or value
3999 statusCode: 200,
4000 loaderHeaders: {},
4001 actionHeaders: {},
4002 activeDeferreds: null
4003 };
4004 }
4005
4006 // Create a GET request for the loaders
4007 let loaderRequest = new Request(request.url, {
4008 headers: request.headers,
4009 redirect: request.redirect,
4010 signal: request.signal
4011 });
4012 if (isErrorResult(result)) {
4013 // Store off the pending error - we use it to determine which loaders
4014 // to call and will commit it when we complete the navigation
4015 let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
4016 let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]);
4017
4018 // action status codes take precedence over loader status codes
4019 return _extends({}, context, {
4020 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
4021 actionData: null,
4022 actionHeaders: _extends({}, result.headers ? {
4023 [actionMatch.route.id]: result.headers
4024 } : {})
4025 });
4026 }
4027 let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null);
4028 return _extends({}, context, {
4029 actionData: {
4030 [actionMatch.route.id]: result.data
4031 }
4032 }, result.statusCode ? {
4033 statusCode: result.statusCode
4034 } : {}, {
4035 actionHeaders: result.headers ? {
4036 [actionMatch.route.id]: result.headers
4037 } : {}
4038 });
4039 }
4040 async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {
4041 let isRouteRequest = routeMatch != null;
4042
4043 // Short circuit if we have no loaders to run (queryRoute())
4044 if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {
4045 throw getInternalRouterError(400, {
4046 method: request.method,
4047 pathname: new URL(request.url).pathname,
4048 routeId: routeMatch == null ? void 0 : routeMatch.route.id
4049 });
4050 }
4051 let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;
4052 let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy);
4053
4054 // Short circuit if we have no loaders to run (query())
4055 if (matchesToLoad.length === 0) {
4056 return {
4057 matches,
4058 // Add a null for all matched routes for proper revalidation on the client
4059 loaderData: matches.reduce((acc, m) => Object.assign(acc, {
4060 [m.route.id]: null
4061 }), {}),
4062 errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
4063 [pendingActionResult[0]]: pendingActionResult[1].error
4064 } : null,
4065 statusCode: 200,
4066 loaderHeaders: {},
4067 activeDeferreds: null
4068 };
4069 }
4070 let results = await callDataStrategy("loader", request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy);
4071 if (request.signal.aborted) {
4072 throwStaticHandlerAbortedError(request, isRouteRequest, future);
4073 }
4074
4075 // Process and commit output from loaders
4076 let activeDeferreds = new Map();
4077 let context = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling);
4078
4079 // Add a null for any non-loader matches for proper revalidation on the client
4080 let executedLoaders = new Set(matchesToLoad.map(match => match.route.id));
4081 matches.forEach(match => {
4082 if (!executedLoaders.has(match.route.id)) {
4083 context.loaderData[match.route.id] = null;
4084 }
4085 });
4086 return _extends({}, context, {
4087 matches,
4088 activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null
4089 });
4090 }
4091
4092 // Utility wrapper for calling dataStrategy server-side without having to
4093 // pass around the manifest, mapRouteProperties, etc.
4094 async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy) {
4095 let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, type, null, request, matchesToLoad, matches, null, manifest, mapRouteProperties, requestContext);
4096 let dataResults = {};
4097 await Promise.all(matches.map(async match => {
4098 if (!(match.route.id in results)) {
4099 return;
4100 }
4101 let result = results[match.route.id];
4102 if (isRedirectDataStrategyResultResult(result)) {
4103 let response = result.result;
4104 // Throw redirects and let the server handle them with an HTTP redirect
4105 throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename, future.v7_relativeSplatPath);
4106 }
4107 if (isResponse(result.result) && isRouteRequest) {
4108 // For SSR single-route requests, we want to hand Responses back
4109 // directly without unwrapping
4110 throw result;
4111 }
4112 dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
4113 }));
4114 return dataResults;
4115 }
4116 return {
4117 dataRoutes,
4118 query,
4119 queryRoute
4120 };
4121 }
4122
4123 //#endregion
4124
4125 ////////////////////////////////////////////////////////////////////////////////
4126 //#region Helpers
4127 ////////////////////////////////////////////////////////////////////////////////
4128
4129 /**
4130 * Given an existing StaticHandlerContext and an error thrown at render time,
4131 * provide an updated StaticHandlerContext suitable for a second SSR render
4132 */
4133 function getStaticContextFromError(routes, context, error) {
4134 let newContext = _extends({}, context, {
4135 statusCode: isRouteErrorResponse(error) ? error.status : 500,
4136 errors: {
4137 [context._deepestRenderedBoundaryId || routes[0].id]: error
4138 }
4139 });
4140 return newContext;
4141 }
4142 function throwStaticHandlerAbortedError(request, isRouteRequest, future) {
4143 if (future.v7_throwAbortReason && request.signal.reason !== undefined) {
4144 throw request.signal.reason;
4145 }
4146 let method = isRouteRequest ? "queryRoute" : "query";
4147 throw new Error(method + "() call aborted: " + request.method + " " + request.url);
4148 }
4149 function isSubmissionNavigation(opts) {
4150 return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== undefined);
4151 }
4152 function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {
4153 let contextualMatches;
4154 let activeRouteMatch;
4155 if (fromRouteId) {
4156 // Grab matches up to the calling route so our route-relative logic is
4157 // relative to the correct source route
4158 contextualMatches = [];
4159 for (let match of matches) {
4160 contextualMatches.push(match);
4161 if (match.route.id === fromRouteId) {
4162 activeRouteMatch = match;
4163 break;
4164 }
4165 }
4166 } else {
4167 contextualMatches = matches;
4168 activeRouteMatch = matches[matches.length - 1];
4169 }
4170
4171 // Resolve the relative path
4172 let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path");
4173
4174 // When `to` is not specified we inherit search/hash from the current
4175 // location, unlike when to="." and we just inherit the path.
4176 // See https://github.com/remix-run/remix/issues/927
4177 if (to == null) {
4178 path.search = location.search;
4179 path.hash = location.hash;
4180 }
4181
4182 // Account for `?index` params when routing to the current location
4183 if ((to == null || to === "" || to === ".") && activeRouteMatch) {
4184 let nakedIndex = hasNakedIndexQuery(path.search);
4185 if (activeRouteMatch.route.index && !nakedIndex) {
4186 // Add one when we're targeting an index route
4187 path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
4188 } else if (!activeRouteMatch.route.index && nakedIndex) {
4189 // Remove existing ones when we're not
4190 let params = new URLSearchParams(path.search);
4191 let indexValues = params.getAll("index");
4192 params.delete("index");
4193 indexValues.filter(v => v).forEach(v => params.append("index", v));
4194 let qs = params.toString();
4195 path.search = qs ? "?" + qs : "";
4196 }
4197 }
4198
4199 // If we're operating within a basename, prepend it to the pathname. If
4200 // this is a root navigation, then just use the raw basename which allows
4201 // the basename to have full control over the presence of a trailing slash
4202 // on root actions
4203 if (prependBasename && basename !== "/") {
4204 path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
4205 }
4206 return createPath(path);
4207 }
4208
4209 // Normalize navigation options by converting formMethod=GET formData objects to
4210 // URLSearchParams so they behave identically to links with query params
4211 function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {
4212 // Return location verbatim on non-submission navigations
4213 if (!opts || !isSubmissionNavigation(opts)) {
4214 return {
4215 path
4216 };
4217 }
4218 if (opts.formMethod && !isValidMethod(opts.formMethod)) {
4219 return {
4220 path,
4221 error: getInternalRouterError(405, {
4222 method: opts.formMethod
4223 })
4224 };
4225 }
4226 let getInvalidBodyError = () => ({
4227 path,
4228 error: getInternalRouterError(400, {
4229 type: "invalid-body"
4230 })
4231 });
4232
4233 // Create a Submission on non-GET navigations
4234 let rawFormMethod = opts.formMethod || "get";
4235 let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();
4236 let formAction = stripHashFromPath(path);
4237 if (opts.body !== undefined) {
4238 if (opts.formEncType === "text/plain") {
4239 // text only support POST/PUT/PATCH/DELETE submissions
4240 if (!isMutationMethod(formMethod)) {
4241 return getInvalidBodyError();
4242 }
4243 let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ?
4244 // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
4245 Array.from(opts.body.entries()).reduce((acc, _ref3) => {
4246 let [name, value] = _ref3;
4247 return "" + acc + name + "=" + value + "\n";
4248 }, "") : String(opts.body);
4249 return {
4250 path,
4251 submission: {
4252 formMethod,
4253 formAction,
4254 formEncType: opts.formEncType,
4255 formData: undefined,
4256 json: undefined,
4257 text
4258 }
4259 };
4260 } else if (opts.formEncType === "application/json") {
4261 // json only supports POST/PUT/PATCH/DELETE submissions
4262 if (!isMutationMethod(formMethod)) {
4263 return getInvalidBodyError();
4264 }
4265 try {
4266 let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
4267 return {
4268 path,
4269 submission: {
4270 formMethod,
4271 formAction,
4272 formEncType: opts.formEncType,
4273 formData: undefined,
4274 json,
4275 text: undefined
4276 }
4277 };
4278 } catch (e) {
4279 return getInvalidBodyError();
4280 }
4281 }
4282 }
4283 invariant(typeof FormData === "function", "FormData is not available in this environment");
4284 let searchParams;
4285 let formData;
4286 if (opts.formData) {
4287 searchParams = convertFormDataToSearchParams(opts.formData);
4288 formData = opts.formData;
4289 } else if (opts.body instanceof FormData) {
4290 searchParams = convertFormDataToSearchParams(opts.body);
4291 formData = opts.body;
4292 } else if (opts.body instanceof URLSearchParams) {
4293 searchParams = opts.body;
4294 formData = convertSearchParamsToFormData(searchParams);
4295 } else if (opts.body == null) {
4296 searchParams = new URLSearchParams();
4297 formData = new FormData();
4298 } else {
4299 try {
4300 searchParams = new URLSearchParams(opts.body);
4301 formData = convertSearchParamsToFormData(searchParams);
4302 } catch (e) {
4303 return getInvalidBodyError();
4304 }
4305 }
4306 let submission = {
4307 formMethod,
4308 formAction,
4309 formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
4310 formData,
4311 json: undefined,
4312 text: undefined
4313 };
4314 if (isMutationMethod(submission.formMethod)) {
4315 return {
4316 path,
4317 submission
4318 };
4319 }
4320
4321 // Flatten submission onto URLSearchParams for GET submissions
4322 let parsedPath = parsePath(path);
4323 // On GET navigation submissions we can drop the ?index param from the
4324 // resulting location since all loaders will run. But fetcher GET submissions
4325 // only run a single loader so we need to preserve any incoming ?index params
4326 if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
4327 searchParams.append("index", "");
4328 }
4329 parsedPath.search = "?" + searchParams;
4330 return {
4331 path: createPath(parsedPath),
4332 submission
4333 };
4334 }
4335
4336 // Filter out all routes at/below any caught error as they aren't going to
4337 // render so we don't need to load them
4338 function getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary) {
4339 if (includeBoundary === void 0) {
4340 includeBoundary = false;
4341 }
4342 let index = matches.findIndex(m => m.route.id === boundaryId);
4343 if (index >= 0) {
4344 return matches.slice(0, includeBoundary ? index + 1 : index);
4345 }
4346 return matches;
4347 }
4348 function getMatchesToLoad(history, state, matches, submission, location, initialHydration, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {
4349 let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined;
4350 let currentUrl = history.createURL(state.location);
4351 let nextUrl = history.createURL(location);
4352
4353 // Pick navigation matches that are net-new or qualify for revalidation
4354 let boundaryMatches = matches;
4355 if (initialHydration && state.errors) {
4356 // On initial hydration, only consider matches up to _and including_ the boundary.
4357 // This is inclusive to handle cases where a server loader ran successfully,
4358 // a child server loader bubbled up to this route, but this route has
4359 // `clientLoader.hydrate` so we want to still run the `clientLoader` so that
4360 // we have a complete version of `loaderData`
4361 boundaryMatches = getLoaderMatchesUntilBoundary(matches, Object.keys(state.errors)[0], true);
4362 } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
4363 // If an action threw an error, we call loaders up to, but not including the
4364 // boundary
4365 boundaryMatches = getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]);
4366 }
4367
4368 // Don't revalidate loaders by default after action 4xx/5xx responses
4369 // when the flag is enabled. They can still opt-into revalidation via
4370 // `shouldRevalidate` via `actionResult`
4371 let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined;
4372 let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400;
4373 let navigationMatches = boundaryMatches.filter((match, index) => {
4374 let {
4375 route
4376 } = match;
4377 if (route.lazy) {
4378 // We haven't loaded this route yet so we don't know if it's got a loader!
4379 return true;
4380 }
4381 if (route.loader == null) {
4382 return false;
4383 }
4384 if (initialHydration) {
4385 return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);
4386 }
4387
4388 // Always call the loader on new route instances and pending defer cancellations
4389 if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {
4390 return true;
4391 }
4392
4393 // This is the default implementation for when we revalidate. If the route
4394 // provides it's own implementation, then we give them full control but
4395 // provide this value so they can leverage it if needed after they check
4396 // their own specific use cases
4397 let currentRouteMatch = state.matches[index];
4398 let nextRouteMatch = match;
4399 return shouldRevalidateLoader(match, _extends({
4400 currentUrl,
4401 currentParams: currentRouteMatch.params,
4402 nextUrl,
4403 nextParams: nextRouteMatch.params
4404 }, submission, {
4405 actionResult,
4406 actionStatus,
4407 defaultShouldRevalidate: shouldSkipRevalidation ? false :
4408 // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
4409 isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search ||
4410 // Search params affect all loaders
4411 currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
4412 }));
4413 });
4414
4415 // Pick fetcher.loads that need to be revalidated
4416 let revalidatingFetchers = [];
4417 fetchLoadMatches.forEach((f, key) => {
4418 // Don't revalidate:
4419 // - on initial hydration (shouldn't be any fetchers then anyway)
4420 // - if fetcher won't be present in the subsequent render
4421 // - no longer matches the URL (v7_fetcherPersist=false)
4422 // - was unmounted but persisted due to v7_fetcherPersist=true
4423 if (initialHydration || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) {
4424 return;
4425 }
4426 let fetcherMatches = matchRoutes(routesToUse, f.path, basename);
4427
4428 // If the fetcher path no longer matches, push it in with null matches so
4429 // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is
4430 // currently only a use-case for Remix HMR where the route tree can change
4431 // at runtime and remove a route previously loaded via a fetcher
4432 if (!fetcherMatches) {
4433 revalidatingFetchers.push({
4434 key,
4435 routeId: f.routeId,
4436 path: f.path,
4437 matches: null,
4438 match: null,
4439 controller: null
4440 });
4441 return;
4442 }
4443
4444 // Revalidating fetchers are decoupled from the route matches since they
4445 // load from a static href. They revalidate based on explicit revalidation
4446 // (submission, useRevalidator, or X-Remix-Revalidate)
4447 let fetcher = state.fetchers.get(key);
4448 let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
4449 let shouldRevalidate = false;
4450 if (fetchRedirectIds.has(key)) {
4451 // Never trigger a revalidation of an actively redirecting fetcher
4452 shouldRevalidate = false;
4453 } else if (cancelledFetcherLoads.has(key)) {
4454 // Always mark for revalidation if the fetcher was cancelled
4455 cancelledFetcherLoads.delete(key);
4456 shouldRevalidate = true;
4457 } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) {
4458 // If the fetcher hasn't ever completed loading yet, then this isn't a
4459 // revalidation, it would just be a brand new load if an explicit
4460 // revalidation is required
4461 shouldRevalidate = isRevalidationRequired;
4462 } else {
4463 // Otherwise fall back on any user-defined shouldRevalidate, defaulting
4464 // to explicit revalidations only
4465 shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({
4466 currentUrl,
4467 currentParams: state.matches[state.matches.length - 1].params,
4468 nextUrl,
4469 nextParams: matches[matches.length - 1].params
4470 }, submission, {
4471 actionResult,
4472 actionStatus,
4473 defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
4474 }));
4475 }
4476 if (shouldRevalidate) {
4477 revalidatingFetchers.push({
4478 key,
4479 routeId: f.routeId,
4480 path: f.path,
4481 matches: fetcherMatches,
4482 match: fetcherMatch,
4483 controller: new AbortController()
4484 });
4485 }
4486 });
4487 return [navigationMatches, revalidatingFetchers];
4488 }
4489 function shouldLoadRouteOnHydration(route, loaderData, errors) {
4490 // We dunno if we have a loader - gotta find out!
4491 if (route.lazy) {
4492 return true;
4493 }
4494
4495 // No loader, nothing to initialize
4496 if (!route.loader) {
4497 return false;
4498 }
4499 let hasData = loaderData != null && loaderData[route.id] !== undefined;
4500 let hasError = errors != null && errors[route.id] !== undefined;
4501
4502 // Don't run if we error'd during SSR
4503 if (!hasData && hasError) {
4504 return false;
4505 }
4506
4507 // Explicitly opting-in to running on hydration
4508 if (typeof route.loader === "function" && route.loader.hydrate === true) {
4509 return true;
4510 }
4511
4512 // Otherwise, run if we're not yet initialized with anything
4513 return !hasData && !hasError;
4514 }
4515 function isNewLoader(currentLoaderData, currentMatch, match) {
4516 let isNew =
4517 // [a] -> [a, b]
4518 !currentMatch ||
4519 // [a, b] -> [a, c]
4520 match.route.id !== currentMatch.route.id;
4521
4522 // Handle the case that we don't have data for a re-used route, potentially
4523 // from a prior error or from a cancelled pending deferred
4524 let isMissingData = currentLoaderData[match.route.id] === undefined;
4525
4526 // Always load if this is a net-new route or we don't yet have data
4527 return isNew || isMissingData;
4528 }
4529 function isNewRouteInstance(currentMatch, match) {
4530 let currentPath = currentMatch.route.path;
4531 return (
4532 // param change for this match, /users/123 -> /users/456
4533 currentMatch.pathname !== match.pathname ||
4534 // splat param changed, which is not present in match.path
4535 // e.g. /files/images/avatar.jpg -> files/finances.xls
4536 currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
4537 );
4538 }
4539 function shouldRevalidateLoader(loaderMatch, arg) {
4540 if (loaderMatch.route.shouldRevalidate) {
4541 let routeChoice = loaderMatch.route.shouldRevalidate(arg);
4542 if (typeof routeChoice === "boolean") {
4543 return routeChoice;
4544 }
4545 }
4546 return arg.defaultShouldRevalidate;
4547 }
4548 function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties) {
4549 var _childrenToPatch;
4550 let childrenToPatch;
4551 if (routeId) {
4552 let route = manifest[routeId];
4553 invariant(route, "No route found to patch children into: routeId = " + routeId);
4554 if (!route.children) {
4555 route.children = [];
4556 }
4557 childrenToPatch = route.children;
4558 } else {
4559 childrenToPatch = routesToUse;
4560 }
4561
4562 // Don't patch in routes we already know about so that `patch` is idempotent
4563 // to simplify user-land code. This is useful because we re-call the
4564 // `patchRoutesOnNavigation` function for matched routes with params.
4565 let uniqueChildren = children.filter(newRoute => !childrenToPatch.some(existingRoute => isSameRoute(newRoute, existingRoute)));
4566 let newRoutes = convertRoutesToDataRoutes(uniqueChildren, mapRouteProperties, [routeId || "_", "patch", String(((_childrenToPatch = childrenToPatch) == null ? void 0 : _childrenToPatch.length) || "0")], manifest);
4567 childrenToPatch.push(...newRoutes);
4568 }
4569 function isSameRoute(newRoute, existingRoute) {
4570 // Most optimal check is by id
4571 if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
4572 return true;
4573 }
4574
4575 // Second is by pathing differences
4576 if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
4577 return false;
4578 }
4579
4580 // Pathless layout routes are trickier since we need to check children.
4581 // If they have no children then they're the same as far as we can tell
4582 if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
4583 return true;
4584 }
4585
4586 // Otherwise, we look to see if every child in the new route is already
4587 // represented in the existing route's children
4588 return newRoute.children.every((aChild, i) => {
4589 var _existingRoute$childr;
4590 return (_existingRoute$childr = existingRoute.children) == null ? void 0 : _existingRoute$childr.some(bChild => isSameRoute(aChild, bChild));
4591 });
4592 }
4593
4594 /**
4595 * Execute route.lazy() methods to lazily load route modules (loader, action,
4596 * shouldRevalidate) and update the routeManifest in place which shares objects
4597 * with dataRoutes so those get updated as well.
4598 */
4599 async function loadLazyRouteModule(route, mapRouteProperties, manifest) {
4600 if (!route.lazy) {
4601 return;
4602 }
4603 let lazyRoute = await route.lazy();
4604
4605 // If the lazy route function was executed and removed by another parallel
4606 // call then we can return - first lazy() to finish wins because the return
4607 // value of lazy is expected to be static
4608 if (!route.lazy) {
4609 return;
4610 }
4611 let routeToUpdate = manifest[route.id];
4612 invariant(routeToUpdate, "No route found in manifest");
4613
4614 // Update the route in place. This should be safe because there's no way
4615 // we could yet be sitting on this route as we can't get there without
4616 // resolving lazy() first.
4617 //
4618 // This is different than the HMR "update" use-case where we may actively be
4619 // on the route being updated. The main concern boils down to "does this
4620 // mutation affect any ongoing navigations or any current state.matches
4621 // values?". If not, it should be safe to update in place.
4622 let routeUpdates = {};
4623 for (let lazyRouteProperty in lazyRoute) {
4624 let staticRouteValue = routeToUpdate[lazyRouteProperty];
4625 let isPropertyStaticallyDefined = staticRouteValue !== undefined &&
4626 // This property isn't static since it should always be updated based
4627 // on the route updates
4628 lazyRouteProperty !== "hasErrorBoundary";
4629 warning(!isPropertyStaticallyDefined, "Route \"" + routeToUpdate.id + "\" has a static property \"" + lazyRouteProperty + "\" " + "defined but its lazy function is also returning a value for this property. " + ("The lazy route property \"" + lazyRouteProperty + "\" will be ignored."));
4630 if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {
4631 routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];
4632 }
4633 }
4634
4635 // Mutate the route with the provided updates. Do this first so we pass
4636 // the updated version to mapRouteProperties
4637 Object.assign(routeToUpdate, routeUpdates);
4638
4639 // Mutate the `hasErrorBoundary` property on the route based on the route
4640 // updates and remove the `lazy` function so we don't resolve the lazy
4641 // route again.
4642 Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), {
4643 lazy: undefined
4644 }));
4645 }
4646
4647 // Default implementation of `dataStrategy` which fetches all loaders in parallel
4648 async function defaultDataStrategy(_ref4) {
4649 let {
4650 matches
4651 } = _ref4;
4652 let matchesToLoad = matches.filter(m => m.shouldLoad);
4653 let results = await Promise.all(matchesToLoad.map(m => m.resolve()));
4654 return results.reduce((acc, result, i) => Object.assign(acc, {
4655 [matchesToLoad[i].route.id]: result
4656 }), {});
4657 }
4658 async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties, requestContext) {
4659 let loadRouteDefinitionsPromises = matches.map(m => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties, manifest) : undefined);
4660 let dsMatches = matches.map((match, i) => {
4661 let loadRoutePromise = loadRouteDefinitionsPromises[i];
4662 let shouldLoad = matchesToLoad.some(m => m.route.id === match.route.id);
4663 // `resolve` encapsulates route.lazy(), executing the loader/action,
4664 // and mapping return values/thrown errors to a `DataStrategyResult`. Users
4665 // can pass a callback to take fine-grained control over the execution
4666 // of the loader/action
4667 let resolve = async handlerOverride => {
4668 if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) {
4669 shouldLoad = true;
4670 }
4671 return shouldLoad ? callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, requestContext) : Promise.resolve({
4672 type: ResultType.data,
4673 result: undefined
4674 });
4675 };
4676 return _extends({}, match, {
4677 shouldLoad,
4678 resolve
4679 });
4680 });
4681
4682 // Send all matches here to allow for a middleware-type implementation.
4683 // handler will be a no-op for unneeded routes and we filter those results
4684 // back out below.
4685 let results = await dataStrategyImpl({
4686 matches: dsMatches,
4687 request,
4688 params: matches[0].params,
4689 fetcherKey,
4690 context: requestContext
4691 });
4692
4693 // Wait for all routes to load here but 'swallow the error since we want
4694 // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -
4695 // called from `match.resolve()`
4696 try {
4697 await Promise.all(loadRouteDefinitionsPromises);
4698 } catch (e) {
4699 // No-op
4700 }
4701 return results;
4702 }
4703
4704 // Default logic for calling a loader/action is the user has no specified a dataStrategy
4705 async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {
4706 let result;
4707 let onReject;
4708 let runHandler = handler => {
4709 // Setup a promise we can race against so that abort signals short circuit
4710 let reject;
4711 // This will never resolve so safe to type it as Promise<DataStrategyResult> to
4712 // satisfy the function return value
4713 let abortPromise = new Promise((_, r) => reject = r);
4714 onReject = () => reject();
4715 request.signal.addEventListener("abort", onReject);
4716 let actualHandler = ctx => {
4717 if (typeof handler !== "function") {
4718 return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ("\"" + type + "\" [routeId: " + match.route.id + "]")));
4719 }
4720 return handler({
4721 request,
4722 params: match.params,
4723 context: staticContext
4724 }, ...(ctx !== undefined ? [ctx] : []));
4725 };
4726 let handlerPromise = (async () => {
4727 try {
4728 let val = await (handlerOverride ? handlerOverride(ctx => actualHandler(ctx)) : actualHandler());
4729 return {
4730 type: "data",
4731 result: val
4732 };
4733 } catch (e) {
4734 return {
4735 type: "error",
4736 result: e
4737 };
4738 }
4739 })();
4740 return Promise.race([handlerPromise, abortPromise]);
4741 };
4742 try {
4743 let handler = match.route[type];
4744
4745 // If we have a route.lazy promise, await that first
4746 if (loadRoutePromise) {
4747 if (handler) {
4748 // Run statically defined handler in parallel with lazy()
4749 let handlerError;
4750 let [value] = await Promise.all([
4751 // If the handler throws, don't let it immediately bubble out,
4752 // since we need to let the lazy() execution finish so we know if this
4753 // route has a boundary that can handle the error
4754 runHandler(handler).catch(e => {
4755 handlerError = e;
4756 }), loadRoutePromise]);
4757 if (handlerError !== undefined) {
4758 throw handlerError;
4759 }
4760 result = value;
4761 } else {
4762 // Load lazy route module, then run any returned handler
4763 await loadRoutePromise;
4764 handler = match.route[type];
4765 if (handler) {
4766 // Handler still runs even if we got interrupted to maintain consistency
4767 // with un-abortable behavior of handler execution on non-lazy or
4768 // previously-lazy-loaded routes
4769 result = await runHandler(handler);
4770 } else if (type === "action") {
4771 let url = new URL(request.url);
4772 let pathname = url.pathname + url.search;
4773 throw getInternalRouterError(405, {
4774 method: request.method,
4775 pathname,
4776 routeId: match.route.id
4777 });
4778 } else {
4779 // lazy() route has no loader to run. Short circuit here so we don't
4780 // hit the invariant below that errors on returning undefined.
4781 return {
4782 type: ResultType.data,
4783 result: undefined
4784 };
4785 }
4786 }
4787 } else if (!handler) {
4788 let url = new URL(request.url);
4789 let pathname = url.pathname + url.search;
4790 throw getInternalRouterError(404, {
4791 pathname
4792 });
4793 } else {
4794 result = await runHandler(handler);
4795 }
4796 invariant(result.result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`.");
4797 } catch (e) {
4798 // We should already be catching and converting normal handler executions to
4799 // DataStrategyResults and returning them, so anything that throws here is an
4800 // unexpected error we still need to wrap
4801 return {
4802 type: ResultType.error,
4803 result: e
4804 };
4805 } finally {
4806 if (onReject) {
4807 request.signal.removeEventListener("abort", onReject);
4808 }
4809 }
4810 return result;
4811 }
4812 async function convertDataStrategyResultToDataResult(dataStrategyResult) {
4813 let {
4814 result,
4815 type
4816 } = dataStrategyResult;
4817 if (isResponse(result)) {
4818 let data;
4819 try {
4820 let contentType = result.headers.get("Content-Type");
4821 // Check between word boundaries instead of startsWith() due to the last
4822 // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type
4823 if (contentType && /\bapplication\/json\b/.test(contentType)) {
4824 if (result.body == null) {
4825 data = null;
4826 } else {
4827 data = await result.json();
4828 }
4829 } else {
4830 data = await result.text();
4831 }
4832 } catch (e) {
4833 return {
4834 type: ResultType.error,
4835 error: e
4836 };
4837 }
4838 if (type === ResultType.error) {
4839 return {
4840 type: ResultType.error,
4841 error: new ErrorResponseImpl(result.status, result.statusText, data),
4842 statusCode: result.status,
4843 headers: result.headers
4844 };
4845 }
4846 return {
4847 type: ResultType.data,
4848 data,
4849 statusCode: result.status,
4850 headers: result.headers
4851 };
4852 }
4853 if (type === ResultType.error) {
4854 if (isDataWithResponseInit(result)) {
4855 var _result$init2;
4856 if (result.data instanceof Error) {
4857 var _result$init;
4858 return {
4859 type: ResultType.error,
4860 error: result.data,
4861 statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status
4862 };
4863 }
4864
4865 // Convert thrown data() to ErrorResponse instances
4866 result = new ErrorResponseImpl(((_result$init2 = result.init) == null ? void 0 : _result$init2.status) || 500, undefined, result.data);
4867 }
4868 return {
4869 type: ResultType.error,
4870 error: result,
4871 statusCode: isRouteErrorResponse(result) ? result.status : undefined
4872 };
4873 }
4874 if (isDeferredData(result)) {
4875 var _result$init3, _result$init4;
4876 return {
4877 type: ResultType.deferred,
4878 deferredData: result,
4879 statusCode: (_result$init3 = result.init) == null ? void 0 : _result$init3.status,
4880 headers: ((_result$init4 = result.init) == null ? void 0 : _result$init4.headers) && new Headers(result.init.headers)
4881 };
4882 }
4883 if (isDataWithResponseInit(result)) {
4884 var _result$init5, _result$init6;
4885 return {
4886 type: ResultType.data,
4887 data: result.data,
4888 statusCode: (_result$init5 = result.init) == null ? void 0 : _result$init5.status,
4889 headers: (_result$init6 = result.init) != null && _result$init6.headers ? new Headers(result.init.headers) : undefined
4890 };
4891 }
4892 return {
4893 type: ResultType.data,
4894 data: result
4895 };
4896 }
4897
4898 // Support relative routing in internal redirects
4899 function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) {
4900 let location = response.headers.get("Location");
4901 invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header");
4902 if (!ABSOLUTE_URL_REGEX.test(location)) {
4903 let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1);
4904 location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath);
4905 response.headers.set("Location", location);
4906 }
4907 return response;
4908 }
4909 function normalizeRedirectLocation(location, currentUrl, basename) {
4910 if (ABSOLUTE_URL_REGEX.test(location)) {
4911 // Strip off the protocol+origin for same-origin + same-basename absolute redirects
4912 let normalizedLocation = location;
4913 let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
4914 let isSameBasename = stripBasename(url.pathname, basename) != null;
4915 if (url.origin === currentUrl.origin && isSameBasename) {
4916 return url.pathname + url.search + url.hash;
4917 }
4918 }
4919 return location;
4920 }
4921
4922 // Utility method for creating the Request instances for loaders/actions during
4923 // client-side navigations and fetches. During SSR we will always have a
4924 // Request instance from the static handler (query/queryRoute)
4925 function createClientSideRequest(history, location, signal, submission) {
4926 let url = history.createURL(stripHashFromPath(location)).toString();
4927 let init = {
4928 signal
4929 };
4930 if (submission && isMutationMethod(submission.formMethod)) {
4931 let {
4932 formMethod,
4933 formEncType
4934 } = submission;
4935 // Didn't think we needed this but it turns out unlike other methods, patch
4936 // won't be properly normalized to uppercase and results in a 405 error.
4937 // See: https://fetch.spec.whatwg.org/#concept-method
4938 init.method = formMethod.toUpperCase();
4939 if (formEncType === "application/json") {
4940 init.headers = new Headers({
4941 "Content-Type": formEncType
4942 });
4943 init.body = JSON.stringify(submission.json);
4944 } else if (formEncType === "text/plain") {
4945 // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
4946 init.body = submission.text;
4947 } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
4948 // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
4949 init.body = convertFormDataToSearchParams(submission.formData);
4950 } else {
4951 // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
4952 init.body = submission.formData;
4953 }
4954 }
4955 return new Request(url, init);
4956 }
4957 function convertFormDataToSearchParams(formData) {
4958 let searchParams = new URLSearchParams();
4959 for (let [key, value] of formData.entries()) {
4960 // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs
4961 searchParams.append(key, typeof value === "string" ? value : value.name);
4962 }
4963 return searchParams;
4964 }
4965 function convertSearchParamsToFormData(searchParams) {
4966 let formData = new FormData();
4967 for (let [key, value] of searchParams.entries()) {
4968 formData.append(key, value);
4969 }
4970 return formData;
4971 }
4972 function processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {
4973 // Fill in loaderData/errors from our loaders
4974 let loaderData = {};
4975 let errors = null;
4976 let statusCode;
4977 let foundError = false;
4978 let loaderHeaders = {};
4979 let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined;
4980
4981 // Process loader results into state.loaderData/state.errors
4982 matches.forEach(match => {
4983 if (!(match.route.id in results)) {
4984 return;
4985 }
4986 let id = match.route.id;
4987 let result = results[id];
4988 invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
4989 if (isErrorResult(result)) {
4990 let error = result.error;
4991 // If we have a pending action error, we report it at the highest-route
4992 // that throws a loader error, and then clear it out to indicate that
4993 // it was consumed
4994 if (pendingError !== undefined) {
4995 error = pendingError;
4996 pendingError = undefined;
4997 }
4998 errors = errors || {};
4999 if (skipLoaderErrorBubbling) {
5000 errors[id] = error;
5001 } else {
5002 // Look upwards from the matched route for the closest ancestor error
5003 // boundary, defaulting to the root match. Prefer higher error values
5004 // if lower errors bubble to the same boundary
5005 let boundaryMatch = findNearestBoundary(matches, id);
5006 if (errors[boundaryMatch.route.id] == null) {
5007 errors[boundaryMatch.route.id] = error;
5008 }
5009 }
5010
5011 // Clear our any prior loaderData for the throwing route
5012 loaderData[id] = undefined;
5013
5014 // Once we find our first (highest) error, we set the status code and
5015 // prevent deeper status codes from overriding
5016 if (!foundError) {
5017 foundError = true;
5018 statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
5019 }
5020 if (result.headers) {
5021 loaderHeaders[id] = result.headers;
5022 }
5023 } else {
5024 if (isDeferredResult(result)) {
5025 activeDeferreds.set(id, result.deferredData);
5026 loaderData[id] = result.deferredData.data;
5027 // Error status codes always override success status codes, but if all
5028 // loaders are successful we take the deepest status code.
5029 if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
5030 statusCode = result.statusCode;
5031 }
5032 if (result.headers) {
5033 loaderHeaders[id] = result.headers;
5034 }
5035 } else {
5036 loaderData[id] = result.data;
5037 // Error status codes always override success status codes, but if all
5038 // loaders are successful we take the deepest status code.
5039 if (result.statusCode && result.statusCode !== 200 && !foundError) {
5040 statusCode = result.statusCode;
5041 }
5042 if (result.headers) {
5043 loaderHeaders[id] = result.headers;
5044 }
5045 }
5046 }
5047 });
5048
5049 // If we didn't consume the pending action error (i.e., all loaders
5050 // resolved), then consume it here. Also clear out any loaderData for the
5051 // throwing route
5052 if (pendingError !== undefined && pendingActionResult) {
5053 errors = {
5054 [pendingActionResult[0]]: pendingError
5055 };
5056 loaderData[pendingActionResult[0]] = undefined;
5057 }
5058 return {
5059 loaderData,
5060 errors,
5061 statusCode: statusCode || 200,
5062 loaderHeaders
5063 };
5064 }
5065 function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) {
5066 let {
5067 loaderData,
5068 errors
5069 } = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble
5070 );
5071
5072 // Process results from our revalidating fetchers
5073 revalidatingFetchers.forEach(rf => {
5074 let {
5075 key,
5076 match,
5077 controller
5078 } = rf;
5079 let result = fetcherResults[key];
5080 invariant(result, "Did not find corresponding fetcher result");
5081
5082 // Process fetcher non-redirect errors
5083 if (controller && controller.signal.aborted) {
5084 // Nothing to do for aborted fetchers
5085 return;
5086 } else if (isErrorResult(result)) {
5087 let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id);
5088 if (!(errors && errors[boundaryMatch.route.id])) {
5089 errors = _extends({}, errors, {
5090 [boundaryMatch.route.id]: result.error
5091 });
5092 }
5093 state.fetchers.delete(key);
5094 } else if (isRedirectResult(result)) {
5095 // Should never get here, redirects should get processed above, but we
5096 // keep this to type narrow to a success result in the else
5097 invariant(false, "Unhandled fetcher revalidation redirect");
5098 } else if (isDeferredResult(result)) {
5099 // Should never get here, deferred data should be awaited for fetchers
5100 // in resolveDeferredResults
5101 invariant(false, "Unhandled fetcher deferred data");
5102 } else {
5103 let doneFetcher = getDoneFetcher(result.data);
5104 state.fetchers.set(key, doneFetcher);
5105 }
5106 });
5107 return {
5108 loaderData,
5109 errors
5110 };
5111 }
5112 function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
5113 let mergedLoaderData = _extends({}, newLoaderData);
5114 for (let match of matches) {
5115 let id = match.route.id;
5116 if (newLoaderData.hasOwnProperty(id)) {
5117 if (newLoaderData[id] !== undefined) {
5118 mergedLoaderData[id] = newLoaderData[id];
5119 }
5120 } else if (loaderData[id] !== undefined && match.route.loader) {
5121 // Preserve existing keys not included in newLoaderData and where a loader
5122 // wasn't removed by HMR
5123 mergedLoaderData[id] = loaderData[id];
5124 }
5125 if (errors && errors.hasOwnProperty(id)) {
5126 // Don't keep any loader data below the boundary
5127 break;
5128 }
5129 }
5130 return mergedLoaderData;
5131 }
5132 function getActionDataForCommit(pendingActionResult) {
5133 if (!pendingActionResult) {
5134 return {};
5135 }
5136 return isErrorResult(pendingActionResult[1]) ? {
5137 // Clear out prior actionData on errors
5138 actionData: {}
5139 } : {
5140 actionData: {
5141 [pendingActionResult[0]]: pendingActionResult[1].data
5142 }
5143 };
5144 }
5145
5146 // Find the nearest error boundary, looking upwards from the leaf route (or the
5147 // route specified by routeId) for the closest ancestor error boundary,
5148 // defaulting to the root match
5149 function findNearestBoundary(matches, routeId) {
5150 let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];
5151 return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];
5152 }
5153 function getShortCircuitMatches(routes) {
5154 // Prefer a root layout route if present, otherwise shim in a route object
5155 let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || {
5156 id: "__shim-error-route__"
5157 };
5158 return {
5159 matches: [{
5160 params: {},
5161 pathname: "",
5162 pathnameBase: "",
5163 route
5164 }],
5165 route
5166 };
5167 }
5168 function getInternalRouterError(status, _temp5) {
5169 let {
5170 pathname,
5171 routeId,
5172 method,
5173 type,
5174 message
5175 } = _temp5 === void 0 ? {} : _temp5;
5176 let statusText = "Unknown Server Error";
5177 let errorMessage = "Unknown @remix-run/router error";
5178 if (status === 400) {
5179 statusText = "Bad Request";
5180 if (method && pathname && routeId) {
5181 errorMessage = "You made a " + method + " request to \"" + pathname + "\" but " + ("did not provide a `loader` for route \"" + routeId + "\", ") + "so there is no way to handle the request.";
5182 } else if (type === "defer-action") {
5183 errorMessage = "defer() is not supported in actions";
5184 } else if (type === "invalid-body") {
5185 errorMessage = "Unable to encode submission body";
5186 }
5187 } else if (status === 403) {
5188 statusText = "Forbidden";
5189 errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\"";
5190 } else if (status === 404) {
5191 statusText = "Not Found";
5192 errorMessage = "No route matches URL \"" + pathname + "\"";
5193 } else if (status === 405) {
5194 statusText = "Method Not Allowed";
5195 if (method && pathname && routeId) {
5196 errorMessage = "You made a " + method.toUpperCase() + " request to \"" + pathname + "\" but " + ("did not provide an `action` for route \"" + routeId + "\", ") + "so there is no way to handle the request.";
5197 } else if (method) {
5198 errorMessage = "Invalid request method \"" + method.toUpperCase() + "\"";
5199 }
5200 }
5201 return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);
5202 }
5203
5204 // Find any returned redirect errors, starting from the lowest match
5205 function findRedirect(results) {
5206 let entries = Object.entries(results);
5207 for (let i = entries.length - 1; i >= 0; i--) {
5208 let [key, result] = entries[i];
5209 if (isRedirectResult(result)) {
5210 return {
5211 key,
5212 result
5213 };
5214 }
5215 }
5216 }
5217 function stripHashFromPath(path) {
5218 let parsedPath = typeof path === "string" ? parsePath(path) : path;
5219 return createPath(_extends({}, parsedPath, {
5220 hash: ""
5221 }));
5222 }
5223 function isHashChangeOnly(a, b) {
5224 if (a.pathname !== b.pathname || a.search !== b.search) {
5225 return false;
5226 }
5227 if (a.hash === "") {
5228 // /page -> /page#hash
5229 return b.hash !== "";
5230 } else if (a.hash === b.hash) {
5231 // /page#hash -> /page#hash
5232 return true;
5233 } else if (b.hash !== "") {
5234 // /page#hash -> /page#other
5235 return true;
5236 }
5237
5238 // If the hash is removed the browser will re-perform a request to the server
5239 // /page#hash -> /page
5240 return false;
5241 }
5242 function isDataStrategyResult(result) {
5243 return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === ResultType.data || result.type === ResultType.error);
5244 }
5245 function isRedirectDataStrategyResultResult(result) {
5246 return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
5247 }
5248 function isDeferredResult(result) {
5249 return result.type === ResultType.deferred;
5250 }
5251 function isErrorResult(result) {
5252 return result.type === ResultType.error;
5253 }
5254 function isRedirectResult(result) {
5255 return (result && result.type) === ResultType.redirect;
5256 }
5257 function isDataWithResponseInit(value) {
5258 return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
5259 }
5260 function isDeferredData(value) {
5261 let deferred = value;
5262 return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
5263 }
5264 function isResponse(value) {
5265 return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
5266 }
5267 function isRedirectResponse(result) {
5268 if (!isResponse(result)) {
5269 return false;
5270 }
5271 let status = result.status;
5272 let location = result.headers.get("Location");
5273 return status >= 300 && status <= 399 && location != null;
5274 }
5275 function isValidMethod(method) {
5276 return validRequestMethods.has(method.toLowerCase());
5277 }
5278 function isMutationMethod(method) {
5279 return validMutationMethods.has(method.toLowerCase());
5280 }
5281 async function resolveNavigationDeferredResults(matches, results, signal, currentMatches, currentLoaderData) {
5282 let entries = Object.entries(results);
5283 for (let index = 0; index < entries.length; index++) {
5284 let [routeId, result] = entries[index];
5285 let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
5286 // If we don't have a match, then we can have a deferred result to do
5287 // anything with. This is for revalidating fetchers where the route was
5288 // removed during HMR
5289 if (!match) {
5290 continue;
5291 }
5292 let currentMatch = currentMatches.find(m => m.route.id === match.route.id);
5293 let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;
5294 if (isDeferredResult(result) && isRevalidatingLoader) {
5295 // Note: we do not have to touch activeDeferreds here since we race them
5296 // against the signal in resolveDeferredData and they'll get aborted
5297 // there if needed
5298 await resolveDeferredData(result, signal, false).then(result => {
5299 if (result) {
5300 results[routeId] = result;
5301 }
5302 });
5303 }
5304 }
5305 }
5306 async function resolveFetcherDeferredResults(matches, results, revalidatingFetchers) {
5307 for (let index = 0; index < revalidatingFetchers.length; index++) {
5308 let {
5309 key,
5310 routeId,
5311 controller
5312 } = revalidatingFetchers[index];
5313 let result = results[key];
5314 let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
5315 // If we don't have a match, then we can have a deferred result to do
5316 // anything with. This is for revalidating fetchers where the route was
5317 // removed during HMR
5318 if (!match) {
5319 continue;
5320 }
5321 if (isDeferredResult(result)) {
5322 // Note: we do not have to touch activeDeferreds here since we race them
5323 // against the signal in resolveDeferredData and they'll get aborted
5324 // there if needed
5325 invariant(controller, "Expected an AbortController for revalidating fetcher deferred result");
5326 await resolveDeferredData(result, controller.signal, true).then(result => {
5327 if (result) {
5328 results[key] = result;
5329 }
5330 });
5331 }
5332 }
5333 }
5334 async function resolveDeferredData(result, signal, unwrap) {
5335 if (unwrap === void 0) {
5336 unwrap = false;
5337 }
5338 let aborted = await result.deferredData.resolveData(signal);
5339 if (aborted) {
5340 return;
5341 }
5342 if (unwrap) {
5343 try {
5344 return {
5345 type: ResultType.data,
5346 data: result.deferredData.unwrappedData
5347 };
5348 } catch (e) {
5349 // Handle any TrackedPromise._error values encountered while unwrapping
5350 return {
5351 type: ResultType.error,
5352 error: e
5353 };
5354 }
5355 }
5356 return {
5357 type: ResultType.data,
5358 data: result.deferredData.data
5359 };
5360 }
5361 function hasNakedIndexQuery(search) {
5362 return new URLSearchParams(search).getAll("index").some(v => v === "");
5363 }
5364 function getTargetMatch(matches, location) {
5365 let search = typeof location === "string" ? parsePath(location).search : location.search;
5366 if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
5367 // Return the leaf index route when index is present
5368 return matches[matches.length - 1];
5369 }
5370 // Otherwise grab the deepest "path contributing" match (ignoring index and
5371 // pathless layout routes)
5372 let pathMatches = getPathContributingMatches(matches);
5373 return pathMatches[pathMatches.length - 1];
5374 }
5375 function getSubmissionFromNavigation(navigation) {
5376 let {
5377 formMethod,
5378 formAction,
5379 formEncType,
5380 text,
5381 formData,
5382 json
5383 } = navigation;
5384 if (!formMethod || !formAction || !formEncType) {
5385 return;
5386 }
5387 if (text != null) {
5388 return {
5389 formMethod,
5390 formAction,
5391 formEncType,
5392 formData: undefined,
5393 json: undefined,
5394 text
5395 };
5396 } else if (formData != null) {
5397 return {
5398 formMethod,
5399 formAction,
5400 formEncType,
5401 formData,
5402 json: undefined,
5403 text: undefined
5404 };
5405 } else if (json !== undefined) {
5406 return {
5407 formMethod,
5408 formAction,
5409 formEncType,
5410 formData: undefined,
5411 json,
5412 text: undefined
5413 };
5414 }
5415 }
5416 function getLoadingNavigation(location, submission) {
5417 if (submission) {
5418 let navigation = {
5419 state: "loading",
5420 location,
5421 formMethod: submission.formMethod,
5422 formAction: submission.formAction,
5423 formEncType: submission.formEncType,
5424 formData: submission.formData,
5425 json: submission.json,
5426 text: submission.text
5427 };
5428 return navigation;
5429 } else {
5430 let navigation = {
5431 state: "loading",
5432 location,
5433 formMethod: undefined,
5434 formAction: undefined,
5435 formEncType: undefined,
5436 formData: undefined,
5437 json: undefined,
5438 text: undefined
5439 };
5440 return navigation;
5441 }
5442 }
5443 function getSubmittingNavigation(location, submission) {
5444 let navigation = {
5445 state: "submitting",
5446 location,
5447 formMethod: submission.formMethod,
5448 formAction: submission.formAction,
5449 formEncType: submission.formEncType,
5450 formData: submission.formData,
5451 json: submission.json,
5452 text: submission.text
5453 };
5454 return navigation;
5455 }
5456 function getLoadingFetcher(submission, data) {
5457 if (submission) {
5458 let fetcher = {
5459 state: "loading",
5460 formMethod: submission.formMethod,
5461 formAction: submission.formAction,
5462 formEncType: submission.formEncType,
5463 formData: submission.formData,
5464 json: submission.json,
5465 text: submission.text,
5466 data
5467 };
5468 return fetcher;
5469 } else {
5470 let fetcher = {
5471 state: "loading",
5472 formMethod: undefined,
5473 formAction: undefined,
5474 formEncType: undefined,
5475 formData: undefined,
5476 json: undefined,
5477 text: undefined,
5478 data
5479 };
5480 return fetcher;
5481 }
5482 }
5483 function getSubmittingFetcher(submission, existingFetcher) {
5484 let fetcher = {
5485 state: "submitting",
5486 formMethod: submission.formMethod,
5487 formAction: submission.formAction,
5488 formEncType: submission.formEncType,
5489 formData: submission.formData,
5490 json: submission.json,
5491 text: submission.text,
5492 data: existingFetcher ? existingFetcher.data : undefined
5493 };
5494 return fetcher;
5495 }
5496 function getDoneFetcher(data) {
5497 let fetcher = {
5498 state: "idle",
5499 formMethod: undefined,
5500 formAction: undefined,
5501 formEncType: undefined,
5502 formData: undefined,
5503 json: undefined,
5504 text: undefined,
5505 data
5506 };
5507 return fetcher;
5508 }
5509 function restoreAppliedTransitions(_window, transitions) {
5510 try {
5511 let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);
5512 if (sessionPositions) {
5513 let json = JSON.parse(sessionPositions);
5514 for (let [k, v] of Object.entries(json || {})) {
5515 if (v && Array.isArray(v)) {
5516 transitions.set(k, new Set(v || []));
5517 }
5518 }
5519 }
5520 } catch (e) {
5521 // no-op, use default empty object
5522 }
5523 }
5524 function persistAppliedTransitions(_window, transitions) {
5525 if (transitions.size > 0) {
5526 let json = {};
5527 for (let [k, v] of transitions) {
5528 json[k] = [...v];
5529 }
5530 try {
5531 _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));
5532 } catch (error) {
5533 warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ").");
5534 }
5535 }
5536 }
5537 //#endregion
5538
5539 exports.AbortedDeferredError = AbortedDeferredError;
5540 exports.Action = Action;
5541 exports.IDLE_BLOCKER = IDLE_BLOCKER;
5542 exports.IDLE_FETCHER = IDLE_FETCHER;
5543 exports.IDLE_NAVIGATION = IDLE_NAVIGATION;
5544 exports.UNSAFE_DEFERRED_SYMBOL = UNSAFE_DEFERRED_SYMBOL;
5545 exports.UNSAFE_DeferredData = DeferredData;
5546 exports.UNSAFE_ErrorResponseImpl = ErrorResponseImpl;
5547 exports.UNSAFE_convertRouteMatchToUiMatch = convertRouteMatchToUiMatch;
5548 exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes;
5549 exports.UNSAFE_decodePath = decodePath;
5550 exports.UNSAFE_getResolveToMatches = getResolveToMatches;
5551 exports.UNSAFE_invariant = invariant;
5552 exports.UNSAFE_warning = warning;
5553 exports.createBrowserHistory = createBrowserHistory;
5554 exports.createHashHistory = createHashHistory;
5555 exports.createMemoryHistory = createMemoryHistory;
5556 exports.createPath = createPath;
5557 exports.createRouter = createRouter;
5558 exports.createStaticHandler = createStaticHandler;
5559 exports.data = data;
5560 exports.defer = defer;
5561 exports.generatePath = generatePath;
5562 exports.getStaticContextFromError = getStaticContextFromError;
5563 exports.getToPathname = getToPathname;
5564 exports.isDataWithResponseInit = isDataWithResponseInit;
5565 exports.isDeferredData = isDeferredData;
5566 exports.isRouteErrorResponse = isRouteErrorResponse;
5567 exports.joinPaths = joinPaths;
5568 exports.json = json;
5569 exports.matchPath = matchPath;
5570 exports.matchRoutes = matchRoutes;
5571 exports.normalizePathname = normalizePathname;
5572 exports.parsePath = parsePath;
5573 exports.redirect = redirect;
5574 exports.redirectDocument = redirectDocument;
5575 exports.replace = replace;
5576 exports.resolvePath = resolvePath;
5577 exports.resolveTo = resolveTo;
5578 exports.stripBasename = stripBasename;
5579
5580 Object.defineProperty(exports, '__esModule', { value: true });
5581
5582}));
5583//# sourceMappingURL=router.umd.js.map
Note: See TracBrowser for help on using the repository browser.