@remix-run/router 1.0.2 → 1.0.3-pre.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3411 @@
1
+ /**
2
+ * @remix-run/router v1.0.3-pre.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
+
22
+ for (var key in source) {
23
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
24
+ target[key] = source[key];
25
+ }
26
+ }
27
+ }
28
+
29
+ return target;
30
+ };
31
+ return _extends.apply(this, arguments);
32
+ }
33
+
34
+ ////////////////////////////////////////////////////////////////////////////////
35
+ //#region Types and Constants
36
+ ////////////////////////////////////////////////////////////////////////////////
37
+
38
+ /**
39
+ * Actions represent the type of change to a location value.
40
+ */
41
+ exports.Action = void 0;
42
+ /**
43
+ * The pathname, search, and hash values of a URL.
44
+ */
45
+
46
+ (function (Action) {
47
+ Action["Pop"] = "POP";
48
+ Action["Push"] = "PUSH";
49
+ Action["Replace"] = "REPLACE";
50
+ })(exports.Action || (exports.Action = {}));
51
+
52
+ const PopStateEventType = "popstate"; //#endregion
53
+ ////////////////////////////////////////////////////////////////////////////////
54
+ //#region Memory History
55
+ ////////////////////////////////////////////////////////////////////////////////
56
+
57
+ /**
58
+ * A user-supplied object that describes a location. Used when providing
59
+ * entries to `createMemoryHistory` via its `initialEntries` option.
60
+ */
61
+
62
+ /**
63
+ * Memory history stores the current location in memory. It is designed for use
64
+ * in stateful non-browser environments like tests and React Native.
65
+ */
66
+ function createMemoryHistory(options) {
67
+ if (options === void 0) {
68
+ options = {};
69
+ }
70
+
71
+ let {
72
+ initialEntries = ["/"],
73
+ initialIndex,
74
+ v5Compat = false
75
+ } = options;
76
+ let entries; // Declare so we can access from createMemoryLocation
77
+
78
+ entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined));
79
+ let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
80
+ let action = exports.Action.Pop;
81
+ let listener = null;
82
+
83
+ function clampIndex(n) {
84
+ return Math.min(Math.max(n, 0), entries.length - 1);
85
+ }
86
+
87
+ function getCurrentLocation() {
88
+ return entries[index];
89
+ }
90
+
91
+ function createMemoryLocation(to, state, key) {
92
+ if (state === void 0) {
93
+ state = null;
94
+ }
95
+
96
+ let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key);
97
+ warning$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
98
+ return location;
99
+ }
100
+
101
+ let history = {
102
+ get index() {
103
+ return index;
104
+ },
105
+
106
+ get action() {
107
+ return action;
108
+ },
109
+
110
+ get location() {
111
+ return getCurrentLocation();
112
+ },
113
+
114
+ createHref(to) {
115
+ return typeof to === "string" ? to : createPath(to);
116
+ },
117
+
118
+ push(to, state) {
119
+ action = exports.Action.Push;
120
+ let nextLocation = createMemoryLocation(to, state);
121
+ index += 1;
122
+ entries.splice(index, entries.length, nextLocation);
123
+
124
+ if (v5Compat && listener) {
125
+ listener({
126
+ action,
127
+ location: nextLocation
128
+ });
129
+ }
130
+ },
131
+
132
+ replace(to, state) {
133
+ action = exports.Action.Replace;
134
+ let nextLocation = createMemoryLocation(to, state);
135
+ entries[index] = nextLocation;
136
+
137
+ if (v5Compat && listener) {
138
+ listener({
139
+ action,
140
+ location: nextLocation
141
+ });
142
+ }
143
+ },
144
+
145
+ go(delta) {
146
+ action = exports.Action.Pop;
147
+ index = clampIndex(index + delta);
148
+
149
+ if (listener) {
150
+ listener({
151
+ action,
152
+ location: getCurrentLocation()
153
+ });
154
+ }
155
+ },
156
+
157
+ listen(fn) {
158
+ listener = fn;
159
+ return () => {
160
+ listener = null;
161
+ };
162
+ }
163
+
164
+ };
165
+ return history;
166
+ } //#endregion
167
+ ////////////////////////////////////////////////////////////////////////////////
168
+ //#region Browser History
169
+ ////////////////////////////////////////////////////////////////////////////////
170
+
171
+ /**
172
+ * A browser history stores the current location in regular URLs in a web
173
+ * browser environment. This is the standard for most web apps and provides the
174
+ * cleanest URLs the browser's address bar.
175
+ *
176
+ * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
177
+ */
178
+
179
+ /**
180
+ * Browser history stores the location in regular URLs. This is the standard for
181
+ * most web apps, but it requires some configuration on the server to ensure you
182
+ * serve the same app at multiple URLs.
183
+ *
184
+ * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
185
+ */
186
+ function createBrowserHistory(options) {
187
+ if (options === void 0) {
188
+ options = {};
189
+ }
190
+
191
+ function createBrowserLocation(window, globalHistory) {
192
+ let {
193
+ pathname,
194
+ search,
195
+ hash
196
+ } = window.location;
197
+ return createLocation("", {
198
+ pathname,
199
+ search,
200
+ hash
201
+ }, // state defaults to `null` because `window.history.state` does
202
+ globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
203
+ }
204
+
205
+ function createBrowserHref(window, to) {
206
+ return typeof to === "string" ? to : createPath(to);
207
+ }
208
+
209
+ return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
210
+ } //#endregion
211
+ ////////////////////////////////////////////////////////////////////////////////
212
+ //#region Hash History
213
+ ////////////////////////////////////////////////////////////////////////////////
214
+
215
+ /**
216
+ * A hash history stores the current location in the fragment identifier portion
217
+ * of the URL in a web browser environment.
218
+ *
219
+ * This is ideal for apps that do not control the server for some reason
220
+ * (because the fragment identifier is never sent to the server), including some
221
+ * shared hosting environments that do not provide fine-grained controls over
222
+ * which pages are served at which URLs.
223
+ *
224
+ * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
225
+ */
226
+
227
+ /**
228
+ * Hash history stores the location in window.location.hash. This makes it ideal
229
+ * for situations where you don't want to send the location to the server for
230
+ * some reason, either because you do cannot configure it or the URL space is
231
+ * reserved for something else.
232
+ *
233
+ * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
234
+ */
235
+ function createHashHistory(options) {
236
+ if (options === void 0) {
237
+ options = {};
238
+ }
239
+
240
+ function createHashLocation(window, globalHistory) {
241
+ let {
242
+ pathname = "/",
243
+ search = "",
244
+ hash = ""
245
+ } = parsePath(window.location.hash.substr(1));
246
+ return createLocation("", {
247
+ pathname,
248
+ search,
249
+ hash
250
+ }, // state defaults to `null` because `window.history.state` does
251
+ globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
252
+ }
253
+
254
+ function createHashHref(window, to) {
255
+ let base = window.document.querySelector("base");
256
+ let href = "";
257
+
258
+ if (base && base.getAttribute("href")) {
259
+ let url = window.location.href;
260
+ let hashIndex = url.indexOf("#");
261
+ href = hashIndex === -1 ? url : url.slice(0, hashIndex);
262
+ }
263
+
264
+ return href + "#" + (typeof to === "string" ? to : createPath(to));
265
+ }
266
+
267
+ function validateHashLocation(location, to) {
268
+ warning$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
269
+ }
270
+
271
+ return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
272
+ } //#endregion
273
+ ////////////////////////////////////////////////////////////////////////////////
274
+ //#region UTILS
275
+ ////////////////////////////////////////////////////////////////////////////////
276
+
277
+ function warning$1(cond, message) {
278
+ if (!cond) {
279
+ // eslint-disable-next-line no-console
280
+ if (typeof console !== "undefined") console.warn(message);
281
+
282
+ try {
283
+ // Welcome to debugging history!
284
+ //
285
+ // This error is thrown as a convenience so you can more easily
286
+ // find the source for a warning that appears in the console by
287
+ // enabling "pause on exceptions" in your JavaScript debugger.
288
+ throw new Error(message); // eslint-disable-next-line no-empty
289
+ } catch (e) {}
290
+ }
291
+ }
292
+
293
+ function createKey() {
294
+ return Math.random().toString(36).substr(2, 8);
295
+ }
296
+ /**
297
+ * For browser-based histories, we combine the state and key into an object
298
+ */
299
+
300
+
301
+ function getHistoryState(location) {
302
+ return {
303
+ usr: location.state,
304
+ key: location.key
305
+ };
306
+ }
307
+ /**
308
+ * Creates a Location object with a unique key from the given Path
309
+ */
310
+
311
+
312
+ function createLocation(current, to, state, key) {
313
+ if (state === void 0) {
314
+ state = null;
315
+ }
316
+
317
+ let location = _extends({
318
+ pathname: typeof current === "string" ? current : current.pathname,
319
+ search: "",
320
+ hash: ""
321
+ }, typeof to === "string" ? parsePath(to) : to, {
322
+ state,
323
+ // TODO: This could be cleaned up. push/replace should probably just take
324
+ // full Locations now and avoid the need to run through this flow at all
325
+ // But that's a pretty big refactor to the current test suite so going to
326
+ // keep as is for the time being and just let any incoming keys take precedence
327
+ key: to && to.key || key || createKey()
328
+ });
329
+
330
+ return location;
331
+ }
332
+ /**
333
+ * Creates a string URL path from the given pathname, search, and hash components.
334
+ */
335
+
336
+ function createPath(_ref) {
337
+ let {
338
+ pathname = "/",
339
+ search = "",
340
+ hash = ""
341
+ } = _ref;
342
+ if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
343
+ if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
344
+ return pathname;
345
+ }
346
+ /**
347
+ * Parses a string URL path into its separate pathname, search, and hash components.
348
+ */
349
+
350
+ function parsePath(path) {
351
+ let parsedPath = {};
352
+
353
+ if (path) {
354
+ let hashIndex = path.indexOf("#");
355
+
356
+ if (hashIndex >= 0) {
357
+ parsedPath.hash = path.substr(hashIndex);
358
+ path = path.substr(0, hashIndex);
359
+ }
360
+
361
+ let searchIndex = path.indexOf("?");
362
+
363
+ if (searchIndex >= 0) {
364
+ parsedPath.search = path.substr(searchIndex);
365
+ path = path.substr(0, searchIndex);
366
+ }
367
+
368
+ if (path) {
369
+ parsedPath.pathname = path;
370
+ }
371
+ }
372
+
373
+ return parsedPath;
374
+ }
375
+
376
+ function getUrlBasedHistory(getLocation, createHref, validateLocation, options) {
377
+ if (options === void 0) {
378
+ options = {};
379
+ }
380
+
381
+ let {
382
+ window = document.defaultView,
383
+ v5Compat = false
384
+ } = options;
385
+ let globalHistory = window.history;
386
+ let action = exports.Action.Pop;
387
+ let listener = null;
388
+
389
+ function handlePop() {
390
+ action = exports.Action.Pop;
391
+
392
+ if (listener) {
393
+ listener({
394
+ action,
395
+ location: history.location
396
+ });
397
+ }
398
+ }
399
+
400
+ function push(to, state) {
401
+ action = exports.Action.Push;
402
+ let location = createLocation(history.location, to, state);
403
+ if (validateLocation) validateLocation(location, to);
404
+ let historyState = getHistoryState(location);
405
+ let url = history.createHref(location); // try...catch because iOS limits us to 100 pushState calls :/
406
+
407
+ try {
408
+ globalHistory.pushState(historyState, "", url);
409
+ } catch (error) {
410
+ // They are going to lose state here, but there is no real
411
+ // way to warn them about it since the page will refresh...
412
+ window.location.assign(url);
413
+ }
414
+
415
+ if (v5Compat && listener) {
416
+ listener({
417
+ action,
418
+ location: history.location
419
+ });
420
+ }
421
+ }
422
+
423
+ function replace(to, state) {
424
+ action = exports.Action.Replace;
425
+ let location = createLocation(history.location, to, state);
426
+ if (validateLocation) validateLocation(location, to);
427
+ let historyState = getHistoryState(location);
428
+ let url = history.createHref(location);
429
+ globalHistory.replaceState(historyState, "", url);
430
+
431
+ if (v5Compat && listener) {
432
+ listener({
433
+ action,
434
+ location: history.location
435
+ });
436
+ }
437
+ }
438
+
439
+ let history = {
440
+ get action() {
441
+ return action;
442
+ },
443
+
444
+ get location() {
445
+ return getLocation(window, globalHistory);
446
+ },
447
+
448
+ listen(fn) {
449
+ if (listener) {
450
+ throw new Error("A history only accepts one active listener");
451
+ }
452
+
453
+ window.addEventListener(PopStateEventType, handlePop);
454
+ listener = fn;
455
+ return () => {
456
+ window.removeEventListener(PopStateEventType, handlePop);
457
+ listener = null;
458
+ };
459
+ },
460
+
461
+ createHref(to) {
462
+ return createHref(window, to);
463
+ },
464
+
465
+ push,
466
+ replace,
467
+
468
+ go(n) {
469
+ return globalHistory.go(n);
470
+ }
471
+
472
+ };
473
+ return history;
474
+ } //#endregion
475
+
476
+ /**
477
+ * Map of routeId -> data returned from a loader/action/error
478
+ */
479
+
480
+ let ResultType;
481
+ /**
482
+ * Successful result from a loader or action
483
+ */
484
+
485
+ (function (ResultType) {
486
+ ResultType["data"] = "data";
487
+ ResultType["deferred"] = "deferred";
488
+ ResultType["redirect"] = "redirect";
489
+ ResultType["error"] = "error";
490
+ })(ResultType || (ResultType = {}));
491
+
492
+ function isIndexRoute(route) {
493
+ return route.index === true;
494
+ } // Walk the route tree generating unique IDs where necessary so we are working
495
+ // solely with AgnosticDataRouteObject's within the Router
496
+
497
+
498
+ function convertRoutesToDataRoutes(routes, parentPath, allIds) {
499
+ if (parentPath === void 0) {
500
+ parentPath = [];
501
+ }
502
+
503
+ if (allIds === void 0) {
504
+ allIds = new Set();
505
+ }
506
+
507
+ return routes.map((route, index) => {
508
+ let treePath = [...parentPath, index];
509
+ let id = typeof route.id === "string" ? route.id : treePath.join("-");
510
+ invariant(route.index !== true || !route.children, "Cannot specify children on an index route");
511
+ invariant(!allIds.has(id), "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages");
512
+ allIds.add(id);
513
+
514
+ if (isIndexRoute(route)) {
515
+ let indexRoute = _extends({}, route, {
516
+ id
517
+ });
518
+
519
+ return indexRoute;
520
+ } else {
521
+ let pathOrLayoutRoute = _extends({}, route, {
522
+ id,
523
+ children: route.children ? convertRoutesToDataRoutes(route.children, treePath, allIds) : undefined
524
+ });
525
+
526
+ return pathOrLayoutRoute;
527
+ }
528
+ });
529
+ }
530
+ /**
531
+ * Matches the given routes to a location and returns the match data.
532
+ *
533
+ * @see https://reactrouter.com/docs/en/v6/utils/match-routes
534
+ */
535
+
536
+ function matchRoutes(routes, locationArg, basename) {
537
+ if (basename === void 0) {
538
+ basename = "/";
539
+ }
540
+
541
+ let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
542
+ let pathname = stripBasename(location.pathname || "/", basename);
543
+
544
+ if (pathname == null) {
545
+ return null;
546
+ }
547
+
548
+ let branches = flattenRoutes(routes);
549
+ rankRouteBranches(branches);
550
+ let matches = null;
551
+
552
+ for (let i = 0; matches == null && i < branches.length; ++i) {
553
+ matches = matchRouteBranch(branches[i], // incoming pathnames are always encoded from either window.location or
554
+ // from route.navigate, but we want to match against the unencoded paths
555
+ // in the route definitions
556
+ safelyDecodeURI(pathname));
557
+ }
558
+
559
+ return matches;
560
+ }
561
+
562
+ function flattenRoutes(routes, branches, parentsMeta, parentPath) {
563
+ if (branches === void 0) {
564
+ branches = [];
565
+ }
566
+
567
+ if (parentsMeta === void 0) {
568
+ parentsMeta = [];
569
+ }
570
+
571
+ if (parentPath === void 0) {
572
+ parentPath = "";
573
+ }
574
+
575
+ routes.forEach((route, index) => {
576
+ let meta = {
577
+ relativePath: route.path || "",
578
+ caseSensitive: route.caseSensitive === true,
579
+ childrenIndex: index,
580
+ route
581
+ };
582
+
583
+ if (meta.relativePath.startsWith("/")) {
584
+ 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.");
585
+ meta.relativePath = meta.relativePath.slice(parentPath.length);
586
+ }
587
+
588
+ let path = joinPaths([parentPath, meta.relativePath]);
589
+ let routesMeta = parentsMeta.concat(meta); // Add the children before adding this route to the array so we traverse the
590
+ // route tree depth-first and child routes appear before their parents in
591
+ // the "flattened" version.
592
+
593
+ if (route.children && route.children.length > 0) {
594
+ invariant( // Our types know better, but runtime JS may not!
595
+ // @ts-expect-error
596
+ route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\"."));
597
+ flattenRoutes(route.children, branches, routesMeta, path);
598
+ } // Routes without a path shouldn't ever match by themselves unless they are
599
+ // index routes, so don't add them to the list of possible branches.
600
+
601
+
602
+ if (route.path == null && !route.index) {
603
+ return;
604
+ }
605
+
606
+ branches.push({
607
+ path,
608
+ score: computeScore(path, route.index),
609
+ routesMeta
610
+ });
611
+ });
612
+ return branches;
613
+ }
614
+
615
+ function rankRouteBranches(branches) {
616
+ branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
617
+ : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
618
+ }
619
+
620
+ const paramRe = /^:\w+$/;
621
+ const dynamicSegmentValue = 3;
622
+ const indexRouteValue = 2;
623
+ const emptySegmentValue = 1;
624
+ const staticSegmentValue = 10;
625
+ const splatPenalty = -2;
626
+
627
+ const isSplat = s => s === "*";
628
+
629
+ function computeScore(path, index) {
630
+ let segments = path.split("/");
631
+ let initialScore = segments.length;
632
+
633
+ if (segments.some(isSplat)) {
634
+ initialScore += splatPenalty;
635
+ }
636
+
637
+ if (index) {
638
+ initialScore += indexRouteValue;
639
+ }
640
+
641
+ return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
642
+ }
643
+
644
+ function compareIndexes(a, b) {
645
+ let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
646
+ return siblings ? // If two routes are siblings, we should try to match the earlier sibling
647
+ // first. This allows people to have fine-grained control over the matching
648
+ // behavior by simply putting routes with identical paths in the order they
649
+ // want them tried.
650
+ a[a.length - 1] - b[b.length - 1] : // Otherwise, it doesn't really make sense to rank non-siblings by index,
651
+ // so they sort equally.
652
+ 0;
653
+ }
654
+
655
+ function matchRouteBranch(branch, pathname) {
656
+ let {
657
+ routesMeta
658
+ } = branch;
659
+ let matchedParams = {};
660
+ let matchedPathname = "/";
661
+ let matches = [];
662
+
663
+ for (let i = 0; i < routesMeta.length; ++i) {
664
+ let meta = routesMeta[i];
665
+ let end = i === routesMeta.length - 1;
666
+ let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
667
+ let match = matchPath({
668
+ path: meta.relativePath,
669
+ caseSensitive: meta.caseSensitive,
670
+ end
671
+ }, remainingPathname);
672
+ if (!match) return null;
673
+ Object.assign(matchedParams, match.params);
674
+ let route = meta.route;
675
+ matches.push({
676
+ // TODO: Can this as be avoided?
677
+ params: matchedParams,
678
+ pathname: joinPaths([matchedPathname, match.pathname]),
679
+ pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
680
+ route
681
+ });
682
+
683
+ if (match.pathnameBase !== "/") {
684
+ matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
685
+ }
686
+ }
687
+
688
+ return matches;
689
+ }
690
+ /**
691
+ * Returns a path with params interpolated.
692
+ *
693
+ * @see https://reactrouter.com/docs/en/v6/utils/generate-path
694
+ */
695
+
696
+
697
+ function generatePath(path, params) {
698
+ if (params === void 0) {
699
+ params = {};
700
+ }
701
+
702
+ return path.replace(/:(\w+)/g, (_, key) => {
703
+ invariant(params[key] != null, "Missing \":" + key + "\" param");
704
+ return params[key];
705
+ }).replace(/(\/?)\*/, (_, prefix, __, str) => {
706
+ const star = "*";
707
+
708
+ if (params[star] == null) {
709
+ // If no splat was provided, trim the trailing slash _unless_ it's
710
+ // the entire path
711
+ return str === "/*" ? "/" : "";
712
+ } // Apply the splat
713
+
714
+
715
+ return "" + prefix + params[star];
716
+ });
717
+ }
718
+ /**
719
+ * A PathPattern is used to match on some portion of a URL pathname.
720
+ */
721
+
722
+ /**
723
+ * Performs pattern matching on a URL pathname and returns information about
724
+ * the match.
725
+ *
726
+ * @see https://reactrouter.com/docs/en/v6/utils/match-path
727
+ */
728
+ function matchPath(pattern, pathname) {
729
+ if (typeof pattern === "string") {
730
+ pattern = {
731
+ path: pattern,
732
+ caseSensitive: false,
733
+ end: true
734
+ };
735
+ }
736
+
737
+ let [matcher, paramNames] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
738
+ let match = pathname.match(matcher);
739
+ if (!match) return null;
740
+ let matchedPathname = match[0];
741
+ let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
742
+ let captureGroups = match.slice(1);
743
+ let params = paramNames.reduce((memo, paramName, index) => {
744
+ // We need to compute the pathnameBase here using the raw splat value
745
+ // instead of using params["*"] later because it will be decoded then
746
+ if (paramName === "*") {
747
+ let splatValue = captureGroups[index] || "";
748
+ pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
749
+ }
750
+
751
+ memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || "", paramName);
752
+ return memo;
753
+ }, {});
754
+ return {
755
+ params,
756
+ pathname: matchedPathname,
757
+ pathnameBase,
758
+ pattern
759
+ };
760
+ }
761
+
762
+ function compilePath(path, caseSensitive, end) {
763
+ if (caseSensitive === void 0) {
764
+ caseSensitive = false;
765
+ }
766
+
767
+ if (end === void 0) {
768
+ end = true;
769
+ }
770
+
771
+ 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(/\*$/, "/*") + "\"."));
772
+ let paramNames = [];
773
+ let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
774
+ .replace(/^\/*/, "/") // Make sure it has a leading /
775
+ .replace(/[\\.*+^$?{}|()[\]]/g, "\\$&") // Escape special regex chars
776
+ .replace(/:(\w+)/g, (_, paramName) => {
777
+ paramNames.push(paramName);
778
+ return "([^\\/]+)";
779
+ });
780
+
781
+ if (path.endsWith("*")) {
782
+ paramNames.push("*");
783
+ regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
784
+ : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
785
+ } else if (end) {
786
+ // When matching to the end, ignore trailing slashes
787
+ regexpSource += "\\/*$";
788
+ } else if (path !== "" && path !== "/") {
789
+ // If our path is non-empty and contains anything beyond an initial slash,
790
+ // then we have _some_ form of path in our regex so we should expect to
791
+ // match only if we find the end of this path segment. Look for an optional
792
+ // non-captured trailing slash (to match a portion of the URL) or the end
793
+ // of the path (if we've matched to the end). We used to do this with a
794
+ // word boundary but that gives false positives on routes like
795
+ // /user-preferences since `-` counts as a word boundary.
796
+ regexpSource += "(?:(?=\\/|$))";
797
+ } else ;
798
+
799
+ let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
800
+ return [matcher, paramNames];
801
+ }
802
+
803
+ function safelyDecodeURI(value) {
804
+ try {
805
+ return decodeURI(value);
806
+ } catch (error) {
807
+ 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 + ")."));
808
+ return value;
809
+ }
810
+ }
811
+
812
+ function safelyDecodeURIComponent(value, paramName) {
813
+ try {
814
+ return decodeURIComponent(value);
815
+ } catch (error) {
816
+ warning(false, "The value for the URL param \"" + paramName + "\" will not be decoded because" + (" the string \"" + value + "\" is a malformed URL segment. This is probably") + (" due to a bad percent encoding (" + error + ")."));
817
+ return value;
818
+ }
819
+ }
820
+ /**
821
+ * @private
822
+ */
823
+
824
+
825
+ function stripBasename(pathname, basename) {
826
+ if (basename === "/") return pathname;
827
+
828
+ if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
829
+ return null;
830
+ } // We want to leave trailing slash behavior in the user's control, so if they
831
+ // specify a basename with a trailing slash, we should support it
832
+
833
+
834
+ let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
835
+ let nextChar = pathname.charAt(startIndex);
836
+
837
+ if (nextChar && nextChar !== "/") {
838
+ // pathname does not start with basename/
839
+ return null;
840
+ }
841
+
842
+ return pathname.slice(startIndex) || "/";
843
+ }
844
+ /**
845
+ * @private
846
+ */
847
+
848
+ function invariant(value, message) {
849
+ if (value === false || value === null || typeof value === "undefined") {
850
+ throw new Error(message);
851
+ }
852
+ }
853
+ /**
854
+ * @private
855
+ */
856
+
857
+ function warning(cond, message) {
858
+ if (!cond) {
859
+ // eslint-disable-next-line no-console
860
+ if (typeof console !== "undefined") console.warn(message);
861
+
862
+ try {
863
+ // Welcome to debugging React Router!
864
+ //
865
+ // This error is thrown as a convenience so you can more easily
866
+ // find the source for a warning that appears in the console by
867
+ // enabling "pause on exceptions" in your JavaScript debugger.
868
+ throw new Error(message); // eslint-disable-next-line no-empty
869
+ } catch (e) {}
870
+ }
871
+ }
872
+ /**
873
+ * Returns a resolved path object relative to the given pathname.
874
+ *
875
+ * @see https://reactrouter.com/docs/en/v6/utils/resolve-path
876
+ */
877
+
878
+ function resolvePath(to, fromPathname) {
879
+ if (fromPathname === void 0) {
880
+ fromPathname = "/";
881
+ }
882
+
883
+ let {
884
+ pathname: toPathname,
885
+ search = "",
886
+ hash = ""
887
+ } = typeof to === "string" ? parsePath(to) : to;
888
+ let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
889
+ return {
890
+ pathname,
891
+ search: normalizeSearch(search),
892
+ hash: normalizeHash(hash)
893
+ };
894
+ }
895
+
896
+ function resolvePathname(relativePath, fromPathname) {
897
+ let segments = fromPathname.replace(/\/+$/, "").split("/");
898
+ let relativeSegments = relativePath.split("/");
899
+ relativeSegments.forEach(segment => {
900
+ if (segment === "..") {
901
+ // Keep the root "" segment so the pathname starts at /
902
+ if (segments.length > 1) segments.pop();
903
+ } else if (segment !== ".") {
904
+ segments.push(segment);
905
+ }
906
+ });
907
+ return segments.length > 1 ? segments.join("/") : "/";
908
+ }
909
+
910
+ function getInvalidPathError(char, field, dest, path) {
911
+ 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.";
912
+ }
913
+ /**
914
+ * @private
915
+ *
916
+ * When processing relative navigation we want to ignore ancestor routes that
917
+ * do not contribute to the path, such that index/pathless layout routes don't
918
+ * interfere.
919
+ *
920
+ * For example, when moving a route element into an index route and/or a
921
+ * pathless layout route, relative link behavior contained within should stay
922
+ * the same. Both of the following examples should link back to the root:
923
+ *
924
+ * <Route path="/">
925
+ * <Route path="accounts" element={<Link to=".."}>
926
+ * </Route>
927
+ *
928
+ * <Route path="/">
929
+ * <Route path="accounts">
930
+ * <Route element={<AccountsLayout />}> // <-- Does not contribute
931
+ * <Route index element={<Link to=".."} /> // <-- Does not contribute
932
+ * </Route
933
+ * </Route>
934
+ * </Route>
935
+ */
936
+
937
+
938
+ function getPathContributingMatches(matches) {
939
+ return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
940
+ }
941
+ /**
942
+ * @private
943
+ */
944
+
945
+ function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {
946
+ if (isPathRelative === void 0) {
947
+ isPathRelative = false;
948
+ }
949
+
950
+ let to;
951
+
952
+ if (typeof toArg === "string") {
953
+ to = parsePath(toArg);
954
+ } else {
955
+ to = _extends({}, toArg);
956
+ invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
957
+ invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
958
+ invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
959
+ }
960
+
961
+ let isEmptyPath = toArg === "" || to.pathname === "";
962
+ let toPathname = isEmptyPath ? "/" : to.pathname;
963
+ let from; // Routing is relative to the current pathname if explicitly requested.
964
+ //
965
+ // If a pathname is explicitly provided in `to`, it should be relative to the
966
+ // route context. This is explained in `Note on `<Link to>` values` in our
967
+ // migration guide from v5 as a means of disambiguation between `to` values
968
+ // that begin with `/` and those that do not. However, this is problematic for
969
+ // `to` values that do not provide a pathname. `to` can simply be a search or
970
+ // hash string, in which case we should assume that the navigation is relative
971
+ // to the current location's pathname and *not* the route pathname.
972
+
973
+ if (isPathRelative || toPathname == null) {
974
+ from = locationPathname;
975
+ } else {
976
+ let routePathnameIndex = routePathnames.length - 1;
977
+
978
+ if (toPathname.startsWith("..")) {
979
+ let toSegments = toPathname.split("/"); // Each leading .. segment means "go up one route" instead of "go up one
980
+ // URL segment". This is a key difference from how <a href> works and a
981
+ // major reason we call this a "to" value instead of a "href".
982
+
983
+ while (toSegments[0] === "..") {
984
+ toSegments.shift();
985
+ routePathnameIndex -= 1;
986
+ }
987
+
988
+ to.pathname = toSegments.join("/");
989
+ } // If there are more ".." segments than parent routes, resolve relative to
990
+ // the root / URL.
991
+
992
+
993
+ from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
994
+ }
995
+
996
+ let path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original "to" had one
997
+
998
+ let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); // Or if this was a link to the current path which has a trailing slash
999
+
1000
+ let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
1001
+
1002
+ if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
1003
+ path.pathname += "/";
1004
+ }
1005
+
1006
+ return path;
1007
+ }
1008
+ /**
1009
+ * @private
1010
+ */
1011
+
1012
+ function getToPathname(to) {
1013
+ // Empty strings should be treated the same as / paths
1014
+ return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
1015
+ }
1016
+ /**
1017
+ * @private
1018
+ */
1019
+
1020
+ const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
1021
+ /**
1022
+ * @private
1023
+ */
1024
+
1025
+ const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
1026
+ /**
1027
+ * @private
1028
+ */
1029
+
1030
+ const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
1031
+ /**
1032
+ * @private
1033
+ */
1034
+
1035
+ const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
1036
+
1037
+ /**
1038
+ * This is a shortcut for creating `application/json` responses. Converts `data`
1039
+ * to JSON and sets the `Content-Type` header.
1040
+ */
1041
+ const json = function json(data, init) {
1042
+ if (init === void 0) {
1043
+ init = {};
1044
+ }
1045
+
1046
+ let responseInit = typeof init === "number" ? {
1047
+ status: init
1048
+ } : init;
1049
+ let headers = new Headers(responseInit.headers);
1050
+
1051
+ if (!headers.has("Content-Type")) {
1052
+ headers.set("Content-Type", "application/json; charset=utf-8");
1053
+ }
1054
+
1055
+ return new Response(JSON.stringify(data), _extends({}, responseInit, {
1056
+ headers
1057
+ }));
1058
+ };
1059
+ class AbortedDeferredError extends Error {}
1060
+ class DeferredData {
1061
+ constructor(data) {
1062
+ this.pendingKeys = new Set();
1063
+ this.subscriber = undefined;
1064
+ invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects"); // Set up an AbortController + Promise we can race against to exit early
1065
+ // cancellation
1066
+
1067
+ let reject;
1068
+ this.abortPromise = new Promise((_, r) => reject = r);
1069
+ this.controller = new AbortController();
1070
+
1071
+ let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted"));
1072
+
1073
+ this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort);
1074
+
1075
+ this.controller.signal.addEventListener("abort", onAbort);
1076
+ this.data = Object.entries(data).reduce((acc, _ref) => {
1077
+ let [key, value] = _ref;
1078
+ return Object.assign(acc, {
1079
+ [key]: this.trackPromise(key, value)
1080
+ });
1081
+ }, {});
1082
+ }
1083
+
1084
+ trackPromise(key, value) {
1085
+ if (!(value instanceof Promise)) {
1086
+ return value;
1087
+ }
1088
+
1089
+ this.pendingKeys.add(key); // We store a little wrapper promise that will be extended with
1090
+ // _data/_error props upon resolve/reject
1091
+
1092
+ let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, null, data), error => this.onSettle(promise, key, error)); // Register rejection listeners to avoid uncaught promise rejections on
1093
+ // errors or aborted deferred values
1094
+
1095
+ promise.catch(() => {});
1096
+ Object.defineProperty(promise, "_tracked", {
1097
+ get: () => true
1098
+ });
1099
+ return promise;
1100
+ }
1101
+
1102
+ onSettle(promise, key, error, data) {
1103
+ if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {
1104
+ this.unlistenAbortSignal();
1105
+ Object.defineProperty(promise, "_error", {
1106
+ get: () => error
1107
+ });
1108
+ return Promise.reject(error);
1109
+ }
1110
+
1111
+ this.pendingKeys.delete(key);
1112
+
1113
+ if (this.done) {
1114
+ // Nothing left to abort!
1115
+ this.unlistenAbortSignal();
1116
+ }
1117
+
1118
+ const subscriber = this.subscriber;
1119
+
1120
+ if (error) {
1121
+ Object.defineProperty(promise, "_error", {
1122
+ get: () => error
1123
+ });
1124
+ subscriber && subscriber(false);
1125
+ return Promise.reject(error);
1126
+ }
1127
+
1128
+ Object.defineProperty(promise, "_data", {
1129
+ get: () => data
1130
+ });
1131
+ subscriber && subscriber(false);
1132
+ return data;
1133
+ }
1134
+
1135
+ subscribe(fn) {
1136
+ this.subscriber = fn;
1137
+ }
1138
+
1139
+ cancel() {
1140
+ this.controller.abort();
1141
+ this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k));
1142
+ let subscriber = this.subscriber;
1143
+ subscriber && subscriber(true);
1144
+ }
1145
+
1146
+ async resolveData(signal) {
1147
+ let aborted = false;
1148
+
1149
+ if (!this.done) {
1150
+ let onAbort = () => this.cancel();
1151
+
1152
+ signal.addEventListener("abort", onAbort);
1153
+ aborted = await new Promise(resolve => {
1154
+ this.subscribe(aborted => {
1155
+ signal.removeEventListener("abort", onAbort);
1156
+
1157
+ if (aborted || this.done) {
1158
+ resolve(aborted);
1159
+ }
1160
+ });
1161
+ });
1162
+ }
1163
+
1164
+ return aborted;
1165
+ }
1166
+
1167
+ get done() {
1168
+ return this.pendingKeys.size === 0;
1169
+ }
1170
+
1171
+ get unwrappedData() {
1172
+ invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds");
1173
+ return Object.entries(this.data).reduce((acc, _ref2) => {
1174
+ let [key, value] = _ref2;
1175
+ return Object.assign(acc, {
1176
+ [key]: unwrapTrackedPromise(value)
1177
+ });
1178
+ }, {});
1179
+ }
1180
+
1181
+ }
1182
+
1183
+ function isTrackedPromise(value) {
1184
+ return value instanceof Promise && value._tracked === true;
1185
+ }
1186
+
1187
+ function unwrapTrackedPromise(value) {
1188
+ if (!isTrackedPromise(value)) {
1189
+ return value;
1190
+ }
1191
+
1192
+ if (value._error) {
1193
+ throw value._error;
1194
+ }
1195
+
1196
+ return value._data;
1197
+ }
1198
+
1199
+ function defer(data) {
1200
+ return new DeferredData(data);
1201
+ }
1202
+
1203
+ /**
1204
+ * A redirect response. Sets the status code and the `Location` header.
1205
+ * Defaults to "302 Found".
1206
+ */
1207
+ const redirect = function redirect(url, init) {
1208
+ if (init === void 0) {
1209
+ init = 302;
1210
+ }
1211
+
1212
+ let responseInit = init;
1213
+
1214
+ if (typeof responseInit === "number") {
1215
+ responseInit = {
1216
+ status: responseInit
1217
+ };
1218
+ } else if (typeof responseInit.status === "undefined") {
1219
+ responseInit.status = 302;
1220
+ }
1221
+
1222
+ let headers = new Headers(responseInit.headers);
1223
+ headers.set("Location", url);
1224
+ return new Response(null, _extends({}, responseInit, {
1225
+ headers
1226
+ }));
1227
+ };
1228
+ /**
1229
+ * @private
1230
+ * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
1231
+ */
1232
+
1233
+ class ErrorResponse {
1234
+ constructor(status, statusText, data) {
1235
+ this.status = status;
1236
+ this.statusText = statusText || "";
1237
+ this.data = data;
1238
+ }
1239
+
1240
+ }
1241
+ /**
1242
+ * Check if the given error is an ErrorResponse generated from a 4xx/5xx
1243
+ * Response throw from an action/loader
1244
+ */
1245
+
1246
+ function isRouteErrorResponse(e) {
1247
+ return e instanceof ErrorResponse;
1248
+ }
1249
+
1250
+ //#region Types and Constants
1251
+ ////////////////////////////////////////////////////////////////////////////////
1252
+
1253
+ /**
1254
+ * A Router instance manages all navigation and data loading/mutations
1255
+ */
1256
+
1257
+ const IDLE_NAVIGATION = {
1258
+ state: "idle",
1259
+ location: undefined,
1260
+ formMethod: undefined,
1261
+ formAction: undefined,
1262
+ formEncType: undefined,
1263
+ formData: undefined
1264
+ };
1265
+ const IDLE_FETCHER = {
1266
+ state: "idle",
1267
+ data: undefined,
1268
+ formMethod: undefined,
1269
+ formAction: undefined,
1270
+ formEncType: undefined,
1271
+ formData: undefined
1272
+ };
1273
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
1274
+ const isServer = !isBrowser; //#endregion
1275
+ ////////////////////////////////////////////////////////////////////////////////
1276
+ //#region createRouter
1277
+ ////////////////////////////////////////////////////////////////////////////////
1278
+
1279
+ /**
1280
+ * Create a router and listen to history POP navigations
1281
+ */
1282
+
1283
+ function createRouter(init) {
1284
+ invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
1285
+ let dataRoutes = convertRoutesToDataRoutes(init.routes); // Cleanup function for history
1286
+
1287
+ let unlistenHistory = null; // Externally-provided functions to call on all state changes
1288
+
1289
+ let subscribers = new Set(); // Externally-provided object to hold scroll restoration locations during routing
1290
+
1291
+ let savedScrollPositions = null; // Externally-provided function to get scroll restoration keys
1292
+
1293
+ let getScrollRestorationKey = null; // Externally-provided function to get current scroll position
1294
+
1295
+ let getScrollPosition = null; // One-time flag to control the initial hydration scroll restoration. Because
1296
+ // we don't get the saved positions from <ScrollRestoration /> until _after_
1297
+ // the initial render, we need to manually trigger a separate updateState to
1298
+ // send along the restoreScrollPosition
1299
+
1300
+ let initialScrollRestored = false;
1301
+ let initialMatches = matchRoutes(dataRoutes, init.history.location, init.basename);
1302
+ let initialErrors = null;
1303
+
1304
+ if (initialMatches == null) {
1305
+ // If we do not match a user-provided-route, fall back to the root
1306
+ // to allow the error boundary to take over
1307
+ let {
1308
+ matches,
1309
+ route,
1310
+ error
1311
+ } = getNotFoundMatches(dataRoutes);
1312
+ initialMatches = matches;
1313
+ initialErrors = {
1314
+ [route.id]: error
1315
+ };
1316
+ }
1317
+
1318
+ let initialized = !initialMatches.some(m => m.route.loader) || init.hydrationData != null;
1319
+ let router;
1320
+ let state = {
1321
+ historyAction: init.history.action,
1322
+ location: init.history.location,
1323
+ matches: initialMatches,
1324
+ initialized,
1325
+ navigation: IDLE_NAVIGATION,
1326
+ restoreScrollPosition: null,
1327
+ preventScrollReset: false,
1328
+ revalidation: "idle",
1329
+ loaderData: init.hydrationData && init.hydrationData.loaderData || {},
1330
+ actionData: init.hydrationData && init.hydrationData.actionData || null,
1331
+ errors: init.hydrationData && init.hydrationData.errors || initialErrors,
1332
+ fetchers: new Map()
1333
+ }; // -- Stateful internal variables to manage navigations --
1334
+ // Current navigation in progress (to be committed in completeNavigation)
1335
+
1336
+ let pendingAction = exports.Action.Pop; // Should the current navigation prevent the scroll reset if scroll cannot
1337
+ // be restored?
1338
+
1339
+ let pendingPreventScrollReset = false; // AbortController for the active navigation
1340
+
1341
+ let pendingNavigationController; // We use this to avoid touching history in completeNavigation if a
1342
+ // revalidation is entirely uninterrupted
1343
+
1344
+ let isUninterruptedRevalidation = false; // Use this internal flag to force revalidation of all loaders:
1345
+ // - submissions (completed or interrupted)
1346
+ // - useRevalidate()
1347
+ // - X-Remix-Revalidate (from redirect)
1348
+
1349
+ let isRevalidationRequired = false; // Use this internal array to capture routes that require revalidation due
1350
+ // to a cancelled deferred on action submission
1351
+
1352
+ let cancelledDeferredRoutes = []; // Use this internal array to capture fetcher loads that were cancelled by an
1353
+ // action navigation and require revalidation
1354
+
1355
+ let cancelledFetcherLoads = []; // AbortControllers for any in-flight fetchers
1356
+
1357
+ let fetchControllers = new Map(); // Track loads based on the order in which they started
1358
+
1359
+ let incrementingLoadId = 0; // Track the outstanding pending navigation data load to be compared against
1360
+ // the globally incrementing load when a fetcher load lands after a completed
1361
+ // navigation
1362
+
1363
+ let pendingNavigationLoadId = -1; // Fetchers that triggered data reloads as a result of their actions
1364
+
1365
+ let fetchReloadIds = new Map(); // Fetchers that triggered redirect navigations from their actions
1366
+
1367
+ let fetchRedirectIds = new Set(); // Most recent href/match for fetcher.load calls for fetchers
1368
+
1369
+ let fetchLoadMatches = new Map(); // Store DeferredData instances for active route matches. When a
1370
+ // route loader returns defer() we stick one in here. Then, when a nested
1371
+ // promise resolves we update loaderData. If a new navigation starts we
1372
+ // cancel active deferreds for eliminated routes.
1373
+
1374
+ let activeDeferreds = new Map(); // Initialize the router, all side effects should be kicked off from here.
1375
+ // Implemented as a Fluent API for ease of:
1376
+ // let router = createRouter(init).initialize();
1377
+
1378
+ function initialize() {
1379
+ // If history informs us of a POP navigation, start the navigation but do not update
1380
+ // state. We'll update our own state once the navigation completes
1381
+ unlistenHistory = init.history.listen(_ref => {
1382
+ let {
1383
+ action: historyAction,
1384
+ location
1385
+ } = _ref;
1386
+ return startNavigation(historyAction, location);
1387
+ }); // Kick off initial data load if needed. Use Pop to avoid modifying history
1388
+
1389
+ if (!state.initialized) {
1390
+ startNavigation(exports.Action.Pop, state.location);
1391
+ }
1392
+
1393
+ return router;
1394
+ } // Clean up a router and it's side effects
1395
+
1396
+
1397
+ function dispose() {
1398
+ if (unlistenHistory) {
1399
+ unlistenHistory();
1400
+ }
1401
+
1402
+ subscribers.clear();
1403
+ pendingNavigationController && pendingNavigationController.abort();
1404
+ state.fetchers.forEach((_, key) => deleteFetcher(key));
1405
+ } // Subscribe to state updates for the router
1406
+
1407
+
1408
+ function subscribe(fn) {
1409
+ subscribers.add(fn);
1410
+ return () => subscribers.delete(fn);
1411
+ } // Update our state and notify the calling context of the change
1412
+
1413
+
1414
+ function updateState(newState) {
1415
+ state = _extends({}, state, newState);
1416
+ subscribers.forEach(subscriber => subscriber(state));
1417
+ } // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
1418
+ // and setting state.[historyAction/location/matches] to the new route.
1419
+ // - Location is a required param
1420
+ // - Navigation will always be set to IDLE_NAVIGATION
1421
+ // - Can pass any other state in newState
1422
+
1423
+
1424
+ function completeNavigation(location, newState) {
1425
+ var _state$navigation$for;
1426
+
1427
+ // Deduce if we're in a loading/actionReload state:
1428
+ // - We have committed actionData in the store
1429
+ // - The current navigation was a submission
1430
+ // - We're past the submitting state and into the loading state
1431
+ // - The location we've finished loading is different from the submission
1432
+ // location, indicating we redirected from the action (avoids false
1433
+ // positives for loading/submissionRedirect when actionData returned
1434
+ // on a prior submission)
1435
+ let isActionReload = state.actionData != null && state.navigation.formMethod != null && state.navigation.state === "loading" && ((_state$navigation$for = state.navigation.formAction) == null ? void 0 : _state$navigation$for.split("?")[0]) === location.pathname; // Always preserve any existing loaderData from re-used routes
1436
+
1437
+ let newLoaderData = newState.loaderData ? {
1438
+ loaderData: mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [])
1439
+ } : {};
1440
+ updateState(_extends({}, isActionReload ? {} : {
1441
+ actionData: null
1442
+ }, newState, newLoaderData, {
1443
+ historyAction: pendingAction,
1444
+ location,
1445
+ initialized: true,
1446
+ navigation: IDLE_NAVIGATION,
1447
+ revalidation: "idle",
1448
+ // Don't restore on submission navigations
1449
+ restoreScrollPosition: state.navigation.formData ? false : getSavedScrollPosition(location, newState.matches || state.matches),
1450
+ preventScrollReset: pendingPreventScrollReset
1451
+ }));
1452
+
1453
+ if (isUninterruptedRevalidation) ; else if (pendingAction === exports.Action.Pop) ; else if (pendingAction === exports.Action.Push) {
1454
+ init.history.push(location, location.state);
1455
+ } else if (pendingAction === exports.Action.Replace) {
1456
+ init.history.replace(location, location.state);
1457
+ } // Reset stateful navigation vars
1458
+
1459
+
1460
+ pendingAction = exports.Action.Pop;
1461
+ pendingPreventScrollReset = false;
1462
+ isUninterruptedRevalidation = false;
1463
+ isRevalidationRequired = false;
1464
+ cancelledDeferredRoutes = [];
1465
+ cancelledFetcherLoads = [];
1466
+ } // Trigger a navigation event, which can either be a numerical POP or a PUSH
1467
+ // replace with an optional submission
1468
+
1469
+
1470
+ async function navigate(to, opts) {
1471
+ if (typeof to === "number") {
1472
+ init.history.go(to);
1473
+ return;
1474
+ }
1475
+
1476
+ let {
1477
+ path,
1478
+ submission,
1479
+ error
1480
+ } = normalizeNavigateOptions(to, opts);
1481
+ let location = createLocation(state.location, path, opts && opts.state); // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded
1482
+ // URL from window.location, so we need to encode it here so the behavior
1483
+ // remains the same as POP and non-data-router usages. new URL() does all
1484
+ // the same encoding we'd get from a history.pushState/window.location read
1485
+ // without having to touch history
1486
+
1487
+ let url = createURL(createPath(location));
1488
+ location = _extends({}, location, {
1489
+ pathname: url.pathname,
1490
+ search: url.search,
1491
+ hash: url.hash
1492
+ });
1493
+ let historyAction = (opts && opts.replace) === true || submission != null ? exports.Action.Replace : exports.Action.Push;
1494
+ let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined;
1495
+ return await startNavigation(historyAction, location, {
1496
+ submission,
1497
+ // Send through the formData serialization error if we have one so we can
1498
+ // render at the right error boundary after we match routes
1499
+ pendingError: error,
1500
+ preventScrollReset,
1501
+ replace: opts && opts.replace
1502
+ });
1503
+ } // Revalidate all current loaders. If a navigation is in progress or if this
1504
+ // is interrupted by a navigation, allow this to "succeed" by calling all
1505
+ // loaders during the next loader round
1506
+
1507
+
1508
+ function revalidate() {
1509
+ interruptActiveLoads();
1510
+ updateState({
1511
+ revalidation: "loading"
1512
+ }); // If we're currently submitting an action, we don't need to start a new
1513
+ // navigation, we'll just let the follow up loader execution call all loaders
1514
+
1515
+ if (state.navigation.state === "submitting") {
1516
+ return;
1517
+ } // If we're currently in an idle state, start a new navigation for the current
1518
+ // action/location and mark it as uninterrupted, which will skip the history
1519
+ // update in completeNavigation
1520
+
1521
+
1522
+ if (state.navigation.state === "idle") {
1523
+ startNavigation(state.historyAction, state.location, {
1524
+ startUninterruptedRevalidation: true
1525
+ });
1526
+ return;
1527
+ } // Otherwise, if we're currently in a loading state, just start a new
1528
+ // navigation to the navigation.location but do not trigger an uninterrupted
1529
+ // revalidation so that history correctly updates once the navigation completes
1530
+
1531
+
1532
+ startNavigation(pendingAction || state.historyAction, state.navigation.location, {
1533
+ overrideNavigation: state.navigation
1534
+ });
1535
+ } // Start a navigation to the given action/location. Can optionally provide a
1536
+ // overrideNavigation which will override the normalLoad in the case of a redirect
1537
+ // navigation
1538
+
1539
+
1540
+ async function startNavigation(historyAction, location, opts) {
1541
+ // Abort any in-progress navigations and start a new one. Unset any ongoing
1542
+ // uninterrupted revalidations unless told otherwise, since we want this
1543
+ // new navigation to update history normally
1544
+ pendingNavigationController && pendingNavigationController.abort();
1545
+ pendingNavigationController = null;
1546
+ pendingAction = historyAction;
1547
+ isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; // Save the current scroll position every time we start a new navigation,
1548
+ // and track whether we should reset scroll on completion
1549
+
1550
+ saveScrollPosition(state.location, state.matches);
1551
+ pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
1552
+ let loadingNavigation = opts && opts.overrideNavigation;
1553
+ let matches = matchRoutes(dataRoutes, location, init.basename); // Short circuit with a 404 on the root error boundary if we match nothing
1554
+
1555
+ if (!matches) {
1556
+ let {
1557
+ matches: notFoundMatches,
1558
+ route,
1559
+ error
1560
+ } = getNotFoundMatches(dataRoutes); // Cancel all pending deferred on 404s since we don't keep any routes
1561
+
1562
+ cancelActiveDeferreds();
1563
+ completeNavigation(location, {
1564
+ matches: notFoundMatches,
1565
+ loaderData: {},
1566
+ errors: {
1567
+ [route.id]: error
1568
+ }
1569
+ });
1570
+ return;
1571
+ } // Short circuit if it's only a hash change
1572
+
1573
+
1574
+ if (isHashChangeOnly(state.location, location)) {
1575
+ completeNavigation(location, {
1576
+ matches
1577
+ });
1578
+ return;
1579
+ } // Create a controller/Request for this navigation
1580
+
1581
+
1582
+ pendingNavigationController = new AbortController();
1583
+ let request = createRequest(location, pendingNavigationController.signal, opts && opts.submission);
1584
+ let pendingActionData;
1585
+ let pendingError;
1586
+
1587
+ if (opts && opts.pendingError) {
1588
+ // If we have a pendingError, it means the user attempted a GET submission
1589
+ // with binary FormData so assign here and skip to handleLoaders. That
1590
+ // way we handle calling loaders above the boundary etc. It's not really
1591
+ // different from an actionError in that sense.
1592
+ pendingError = {
1593
+ [findNearestBoundary(matches).route.id]: opts.pendingError
1594
+ };
1595
+ } else if (opts && opts.submission) {
1596
+ // Call action if we received an action submission
1597
+ let actionOutput = await handleAction(request, location, opts.submission, matches, {
1598
+ replace: opts.replace
1599
+ });
1600
+
1601
+ if (actionOutput.shortCircuited) {
1602
+ return;
1603
+ }
1604
+
1605
+ pendingActionData = actionOutput.pendingActionData;
1606
+ pendingError = actionOutput.pendingActionError;
1607
+
1608
+ let navigation = _extends({
1609
+ state: "loading",
1610
+ location
1611
+ }, opts.submission);
1612
+
1613
+ loadingNavigation = navigation;
1614
+ } // Call loaders
1615
+
1616
+
1617
+ let {
1618
+ shortCircuited,
1619
+ loaderData,
1620
+ errors
1621
+ } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.replace, pendingActionData, pendingError);
1622
+
1623
+ if (shortCircuited) {
1624
+ return;
1625
+ } // Clean up now that the action/loaders have completed. Don't clean up if
1626
+ // we short circuited because pendingNavigationController will have already
1627
+ // been assigned to a new controller for the next navigation
1628
+
1629
+
1630
+ pendingNavigationController = null;
1631
+ completeNavigation(location, {
1632
+ matches,
1633
+ loaderData,
1634
+ errors
1635
+ });
1636
+ } // Call the action matched by the leaf route for this navigation and handle
1637
+ // redirects/errors
1638
+
1639
+
1640
+ async function handleAction(request, location, submission, matches, opts) {
1641
+ interruptActiveLoads(); // Put us in a submitting state
1642
+
1643
+ let navigation = _extends({
1644
+ state: "submitting",
1645
+ location
1646
+ }, submission);
1647
+
1648
+ updateState({
1649
+ navigation
1650
+ }); // Call our action and get the result
1651
+
1652
+ let result;
1653
+ let actionMatch = getTargetMatch(matches, location);
1654
+
1655
+ if (!actionMatch.route.action) {
1656
+ result = getMethodNotAllowedResult(location);
1657
+ } else {
1658
+ result = await callLoaderOrAction("action", request, actionMatch, matches, router.basename);
1659
+
1660
+ if (request.signal.aborted) {
1661
+ return {
1662
+ shortCircuited: true
1663
+ };
1664
+ }
1665
+ }
1666
+
1667
+ if (isRedirectResult(result)) {
1668
+ let redirectNavigation = _extends({
1669
+ state: "loading",
1670
+ location: createLocation(state.location, result.location)
1671
+ }, submission);
1672
+
1673
+ await startRedirectNavigation(result, redirectNavigation, opts && opts.replace);
1674
+ return {
1675
+ shortCircuited: true
1676
+ };
1677
+ }
1678
+
1679
+ if (isErrorResult(result)) {
1680
+ // Store off the pending error - we use it to determine which loaders
1681
+ // to call and will commit it when we complete the navigation
1682
+ let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); // By default, all submissions are REPLACE navigations, but if the
1683
+ // action threw an error that'll be rendered in an errorElement, we fall
1684
+ // back to PUSH so that the user can use the back button to get back to
1685
+ // the pre-submission form location to try again
1686
+
1687
+ if ((opts && opts.replace) !== true) {
1688
+ pendingAction = exports.Action.Push;
1689
+ }
1690
+
1691
+ return {
1692
+ pendingActionError: {
1693
+ [boundaryMatch.route.id]: result.error
1694
+ }
1695
+ };
1696
+ }
1697
+
1698
+ if (isDeferredResult(result)) {
1699
+ throw new Error("defer() is not supported in actions");
1700
+ }
1701
+
1702
+ return {
1703
+ pendingActionData: {
1704
+ [actionMatch.route.id]: result.data
1705
+ }
1706
+ };
1707
+ } // Call all applicable loaders for the given matches, handling redirects,
1708
+ // errors, etc.
1709
+
1710
+
1711
+ async function handleLoaders(request, location, matches, overrideNavigation, submission, replace, pendingActionData, pendingError) {
1712
+ // Figure out the right navigation we want to use for data loading
1713
+ let loadingNavigation = overrideNavigation;
1714
+
1715
+ if (!loadingNavigation) {
1716
+ let navigation = {
1717
+ state: "loading",
1718
+ location,
1719
+ formMethod: undefined,
1720
+ formAction: undefined,
1721
+ formEncType: undefined,
1722
+ formData: undefined
1723
+ };
1724
+ loadingNavigation = navigation;
1725
+ }
1726
+
1727
+ let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches); // Cancel pending deferreds for no-longer-matched routes or routes we're
1728
+ // about to reload. Note that if this is an action reload we would have
1729
+ // already cancelled all pending deferreds so this would be a no-op
1730
+
1731
+ cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); // Short circuit if we have no loaders to run
1732
+
1733
+ if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
1734
+ completeNavigation(location, {
1735
+ matches,
1736
+ loaderData: mergeLoaderData(state.loaderData, {}, matches),
1737
+ // Commit pending error if we're short circuiting
1738
+ errors: pendingError || null,
1739
+ actionData: pendingActionData || null
1740
+ });
1741
+ return {
1742
+ shortCircuited: true
1743
+ };
1744
+ } // If this is an uninterrupted revalidation, we remain in our current idle
1745
+ // state. If not, we need to switch to our loading state and load data,
1746
+ // preserving any new action data or existing action data (in the case of
1747
+ // a revalidation interrupting an actionReload)
1748
+
1749
+
1750
+ if (!isUninterruptedRevalidation) {
1751
+ revalidatingFetchers.forEach(_ref2 => {
1752
+ let [key] = _ref2;
1753
+ let fetcher = state.fetchers.get(key);
1754
+ let revalidatingFetcher = {
1755
+ state: "loading",
1756
+ data: fetcher && fetcher.data,
1757
+ formMethod: undefined,
1758
+ formAction: undefined,
1759
+ formEncType: undefined,
1760
+ formData: undefined
1761
+ };
1762
+ state.fetchers.set(key, revalidatingFetcher);
1763
+ });
1764
+ updateState(_extends({
1765
+ navigation: loadingNavigation,
1766
+ actionData: pendingActionData || state.actionData || null
1767
+ }, revalidatingFetchers.length > 0 ? {
1768
+ fetchers: new Map(state.fetchers)
1769
+ } : {}));
1770
+ }
1771
+
1772
+ pendingNavigationLoadId = ++incrementingLoadId;
1773
+ revalidatingFetchers.forEach(_ref3 => {
1774
+ let [key] = _ref3;
1775
+ return fetchControllers.set(key, pendingNavigationController);
1776
+ });
1777
+ let {
1778
+ results,
1779
+ loaderResults,
1780
+ fetcherResults
1781
+ } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request);
1782
+
1783
+ if (request.signal.aborted) {
1784
+ return {
1785
+ shortCircuited: true
1786
+ };
1787
+ } // Clean up _after_ loaders have completed. Don't clean up if we short
1788
+ // circuited because fetchControllers would have been aborted and
1789
+ // reassigned to new controllers for the next navigation
1790
+
1791
+
1792
+ revalidatingFetchers.forEach(_ref4 => {
1793
+ let [key] = _ref4;
1794
+ return fetchControllers.delete(key);
1795
+ }); // If any loaders returned a redirect Response, start a new REPLACE navigation
1796
+
1797
+ let redirect = findRedirect(results);
1798
+
1799
+ if (redirect) {
1800
+ let redirectNavigation = getLoaderRedirect(state, redirect);
1801
+ await startRedirectNavigation(redirect, redirectNavigation, replace);
1802
+ return {
1803
+ shortCircuited: true
1804
+ };
1805
+ } // Process and commit output from loaders
1806
+
1807
+
1808
+ let {
1809
+ loaderData,
1810
+ errors
1811
+ } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds); // Wire up subscribers to update loaderData as promises settle
1812
+
1813
+ activeDeferreds.forEach((deferredData, routeId) => {
1814
+ deferredData.subscribe(aborted => {
1815
+ // Note: No need to updateState here since the TrackedPromise on
1816
+ // loaderData is stable across resolve/reject
1817
+ // Remove this instance if we were aborted or if promises have settled
1818
+ if (aborted || deferredData.done) {
1819
+ activeDeferreds.delete(routeId);
1820
+ }
1821
+ });
1822
+ });
1823
+ markFetchRedirectsDone();
1824
+ let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
1825
+ return _extends({
1826
+ loaderData,
1827
+ errors
1828
+ }, didAbortFetchLoads || revalidatingFetchers.length > 0 ? {
1829
+ fetchers: new Map(state.fetchers)
1830
+ } : {});
1831
+ }
1832
+
1833
+ function getFetcher(key) {
1834
+ return state.fetchers.get(key) || IDLE_FETCHER;
1835
+ } // Trigger a fetcher load/submit for the given fetcher key
1836
+
1837
+
1838
+ function fetch(key, routeId, href, opts) {
1839
+ if (isServer) {
1840
+ 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.");
1841
+ }
1842
+
1843
+ if (fetchControllers.has(key)) abortFetcher(key);
1844
+ let matches = matchRoutes(dataRoutes, href, init.basename);
1845
+
1846
+ if (!matches) {
1847
+ setFetcherError(key, routeId, new ErrorResponse(404, "Not Found", null));
1848
+ return;
1849
+ }
1850
+
1851
+ let {
1852
+ path,
1853
+ submission
1854
+ } = normalizeNavigateOptions(href, opts, true);
1855
+ let match = getTargetMatch(matches, path);
1856
+
1857
+ if (submission) {
1858
+ handleFetcherAction(key, routeId, path, match, matches, submission);
1859
+ return;
1860
+ } // Store off the match so we can call it's shouldRevalidate on subsequent
1861
+ // revalidations
1862
+
1863
+
1864
+ fetchLoadMatches.set(key, [path, match, matches]);
1865
+ handleFetcherLoader(key, routeId, path, match, matches);
1866
+ } // Call the action for the matched fetcher.submit(), and then handle redirects,
1867
+ // errors, and revalidation
1868
+
1869
+
1870
+ async function handleFetcherAction(key, routeId, path, match, requestMatches, submission) {
1871
+ interruptActiveLoads();
1872
+ fetchLoadMatches.delete(key);
1873
+
1874
+ if (!match.route.action) {
1875
+ let {
1876
+ error
1877
+ } = getMethodNotAllowedResult(path);
1878
+ setFetcherError(key, routeId, error);
1879
+ return;
1880
+ } // Put this fetcher into it's submitting state
1881
+
1882
+
1883
+ let existingFetcher = state.fetchers.get(key);
1884
+
1885
+ let fetcher = _extends({
1886
+ state: "submitting"
1887
+ }, submission, {
1888
+ data: existingFetcher && existingFetcher.data
1889
+ });
1890
+
1891
+ state.fetchers.set(key, fetcher);
1892
+ updateState({
1893
+ fetchers: new Map(state.fetchers)
1894
+ }); // Call the action for the fetcher
1895
+
1896
+ let abortController = new AbortController();
1897
+ let fetchRequest = createRequest(path, abortController.signal, submission);
1898
+ fetchControllers.set(key, abortController);
1899
+ let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, router.basename);
1900
+
1901
+ if (fetchRequest.signal.aborted) {
1902
+ // We can delete this so long as we weren't aborted by ou our own fetcher
1903
+ // re-submit which would have put _new_ controller is in fetchControllers
1904
+ if (fetchControllers.get(key) === abortController) {
1905
+ fetchControllers.delete(key);
1906
+ }
1907
+
1908
+ return;
1909
+ }
1910
+
1911
+ if (isRedirectResult(actionResult)) {
1912
+ fetchControllers.delete(key);
1913
+ fetchRedirectIds.add(key);
1914
+
1915
+ let loadingFetcher = _extends({
1916
+ state: "loading"
1917
+ }, submission, {
1918
+ data: undefined
1919
+ });
1920
+
1921
+ state.fetchers.set(key, loadingFetcher);
1922
+ updateState({
1923
+ fetchers: new Map(state.fetchers)
1924
+ });
1925
+
1926
+ let redirectNavigation = _extends({
1927
+ state: "loading",
1928
+ location: createLocation(state.location, actionResult.location)
1929
+ }, submission);
1930
+
1931
+ await startRedirectNavigation(actionResult, redirectNavigation);
1932
+ return;
1933
+ } // Process any non-redirect errors thrown
1934
+
1935
+
1936
+ if (isErrorResult(actionResult)) {
1937
+ setFetcherError(key, routeId, actionResult.error);
1938
+ return;
1939
+ }
1940
+
1941
+ if (isDeferredResult(actionResult)) {
1942
+ invariant(false, "defer() is not supported in actions");
1943
+ } // Start the data load for current matches, or the next location if we're
1944
+ // in the middle of a navigation
1945
+
1946
+
1947
+ let nextLocation = state.navigation.location || state.location;
1948
+ let revalidationRequest = createRequest(nextLocation, abortController.signal);
1949
+ let matches = state.navigation.state !== "idle" ? matchRoutes(dataRoutes, state.navigation.location, init.basename) : state.matches;
1950
+ invariant(matches, "Didn't find any matches after fetcher action");
1951
+ let loadId = ++incrementingLoadId;
1952
+ fetchReloadIds.set(key, loadId);
1953
+
1954
+ let loadFetcher = _extends({
1955
+ state: "loading",
1956
+ data: actionResult.data
1957
+ }, submission);
1958
+
1959
+ state.fetchers.set(key, loadFetcher);
1960
+ let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, {
1961
+ [match.route.id]: actionResult.data
1962
+ }, undefined, // No need to send through errors since we short circuit above
1963
+ fetchLoadMatches); // Put all revalidating fetchers into the loading state, except for the
1964
+ // current fetcher which we want to keep in it's current loading state which
1965
+ // contains it's action submission info + action data
1966
+
1967
+ revalidatingFetchers.filter(_ref5 => {
1968
+ let [staleKey] = _ref5;
1969
+ return staleKey !== key;
1970
+ }).forEach(_ref6 => {
1971
+ let [staleKey] = _ref6;
1972
+ let existingFetcher = state.fetchers.get(staleKey);
1973
+ let revalidatingFetcher = {
1974
+ state: "loading",
1975
+ data: existingFetcher && existingFetcher.data,
1976
+ formMethod: undefined,
1977
+ formAction: undefined,
1978
+ formEncType: undefined,
1979
+ formData: undefined
1980
+ };
1981
+ state.fetchers.set(staleKey, revalidatingFetcher);
1982
+ fetchControllers.set(staleKey, abortController);
1983
+ });
1984
+ updateState({
1985
+ fetchers: new Map(state.fetchers)
1986
+ });
1987
+ let {
1988
+ results,
1989
+ loaderResults,
1990
+ fetcherResults
1991
+ } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
1992
+
1993
+ if (abortController.signal.aborted) {
1994
+ return;
1995
+ }
1996
+
1997
+ fetchReloadIds.delete(key);
1998
+ fetchControllers.delete(key);
1999
+ revalidatingFetchers.forEach(_ref7 => {
2000
+ let [staleKey] = _ref7;
2001
+ return fetchControllers.delete(staleKey);
2002
+ });
2003
+ let redirect = findRedirect(results);
2004
+
2005
+ if (redirect) {
2006
+ let redirectNavigation = getLoaderRedirect(state, redirect);
2007
+ await startRedirectNavigation(redirect, redirectNavigation);
2008
+ return;
2009
+ } // Process and commit output from loaders
2010
+
2011
+
2012
+ let {
2013
+ loaderData,
2014
+ errors
2015
+ } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);
2016
+ let doneFetcher = {
2017
+ state: "idle",
2018
+ data: actionResult.data,
2019
+ formMethod: undefined,
2020
+ formAction: undefined,
2021
+ formEncType: undefined,
2022
+ formData: undefined
2023
+ };
2024
+ state.fetchers.set(key, doneFetcher);
2025
+ let didAbortFetchLoads = abortStaleFetchLoads(loadId); // If we are currently in a navigation loading state and this fetcher is
2026
+ // more recent than the navigation, we want the newer data so abort the
2027
+ // navigation and complete it with the fetcher data
2028
+
2029
+ if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
2030
+ invariant(pendingAction, "Expected pending action");
2031
+ pendingNavigationController && pendingNavigationController.abort();
2032
+ completeNavigation(state.navigation.location, {
2033
+ matches,
2034
+ loaderData,
2035
+ errors,
2036
+ fetchers: new Map(state.fetchers)
2037
+ });
2038
+ } else {
2039
+ // otherwise just update with the fetcher data, preserving any existing
2040
+ // loaderData for loaders that did not need to reload. We have to
2041
+ // manually merge here since we aren't going through completeNavigation
2042
+ updateState(_extends({
2043
+ errors,
2044
+ loaderData: mergeLoaderData(state.loaderData, loaderData, matches)
2045
+ }, didAbortFetchLoads ? {
2046
+ fetchers: new Map(state.fetchers)
2047
+ } : {}));
2048
+ isRevalidationRequired = false;
2049
+ }
2050
+ } // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
2051
+
2052
+
2053
+ async function handleFetcherLoader(key, routeId, path, match, matches) {
2054
+ let existingFetcher = state.fetchers.get(key); // Put this fetcher into it's loading state
2055
+
2056
+ let loadingFetcher = {
2057
+ state: "loading",
2058
+ formMethod: undefined,
2059
+ formAction: undefined,
2060
+ formEncType: undefined,
2061
+ formData: undefined,
2062
+ data: existingFetcher && existingFetcher.data
2063
+ };
2064
+ state.fetchers.set(key, loadingFetcher);
2065
+ updateState({
2066
+ fetchers: new Map(state.fetchers)
2067
+ }); // Call the loader for this fetcher route match
2068
+
2069
+ let abortController = new AbortController();
2070
+ let fetchRequest = createRequest(path, abortController.signal);
2071
+ fetchControllers.set(key, abortController);
2072
+ let result = await callLoaderOrAction("loader", fetchRequest, match, matches, router.basename); // Deferred isn't supported or fetcher loads, await everything and treat it
2073
+ // as a normal load. resolveDeferredData will return undefined if this
2074
+ // fetcher gets aborted, so we just leave result untouched and short circuit
2075
+ // below if that happens
2076
+
2077
+ if (isDeferredResult(result)) {
2078
+ result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;
2079
+ } // We can delete this so long as we weren't aborted by ou our own fetcher
2080
+ // re-load which would have put _new_ controller is in fetchControllers
2081
+
2082
+
2083
+ if (fetchControllers.get(key) === abortController) {
2084
+ fetchControllers.delete(key);
2085
+ }
2086
+
2087
+ if (fetchRequest.signal.aborted) {
2088
+ return;
2089
+ } // If the loader threw a redirect Response, start a new REPLACE navigation
2090
+
2091
+
2092
+ if (isRedirectResult(result)) {
2093
+ let redirectNavigation = getLoaderRedirect(state, result);
2094
+ await startRedirectNavigation(result, redirectNavigation);
2095
+ return;
2096
+ } // Process any non-redirect errors thrown
2097
+
2098
+
2099
+ if (isErrorResult(result)) {
2100
+ let boundaryMatch = findNearestBoundary(state.matches, routeId);
2101
+ state.fetchers.delete(key); // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -
2102
+ // do we need to behave any differently with our non-redirect errors?
2103
+ // What if it was a non-redirect Response?
2104
+
2105
+ updateState({
2106
+ fetchers: new Map(state.fetchers),
2107
+ errors: {
2108
+ [boundaryMatch.route.id]: result.error
2109
+ }
2110
+ });
2111
+ return;
2112
+ }
2113
+
2114
+ invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); // Put the fetcher back into an idle state
2115
+
2116
+ let doneFetcher = {
2117
+ state: "idle",
2118
+ data: result.data,
2119
+ formMethod: undefined,
2120
+ formAction: undefined,
2121
+ formEncType: undefined,
2122
+ formData: undefined
2123
+ };
2124
+ state.fetchers.set(key, doneFetcher);
2125
+ updateState({
2126
+ fetchers: new Map(state.fetchers)
2127
+ });
2128
+ }
2129
+ /**
2130
+ * Utility function to handle redirects returned from an action or loader.
2131
+ * Normally, a redirect "replaces" the navigation that triggered it. So, for
2132
+ * example:
2133
+ *
2134
+ * - user is on /a
2135
+ * - user clicks a link to /b
2136
+ * - loader for /b redirects to /c
2137
+ *
2138
+ * In a non-JS app the browser would track the in-flight navigation to /b and
2139
+ * then replace it with /c when it encountered the redirect response. In
2140
+ * the end it would only ever update the URL bar with /c.
2141
+ *
2142
+ * In client-side routing using pushState/replaceState, we aim to emulate
2143
+ * this behavior and we also do not update history until the end of the
2144
+ * navigation (including processed redirects). This means that we never
2145
+ * actually touch history until we've processed redirects, so we just use
2146
+ * the history action from the original navigation (PUSH or REPLACE).
2147
+ */
2148
+
2149
+
2150
+ async function startRedirectNavigation(redirect, navigation, replace) {
2151
+ if (redirect.revalidate) {
2152
+ isRevalidationRequired = true;
2153
+ }
2154
+
2155
+ invariant(navigation.location, "Expected a location on the redirect navigation"); // There's no need to abort on redirects, since we don't detect the
2156
+ // redirect until the action/loaders have settled
2157
+
2158
+ pendingNavigationController = null;
2159
+ let redirectHistoryAction = replace === true ? exports.Action.Replace : exports.Action.Push;
2160
+ await startNavigation(redirectHistoryAction, navigation.location, {
2161
+ overrideNavigation: navigation
2162
+ });
2163
+ }
2164
+
2165
+ async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) {
2166
+ // Call all navigation loaders and revalidating fetcher loaders in parallel,
2167
+ // then slice off the results into separate arrays so we can handle them
2168
+ // accordingly
2169
+ let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, router.basename)), ...fetchersToLoad.map(_ref8 => {
2170
+ let [, href, match, fetchMatches] = _ref8;
2171
+ return callLoaderOrAction("loader", createRequest(href, request.signal), match, fetchMatches, router.basename);
2172
+ })]);
2173
+ let loaderResults = results.slice(0, matchesToLoad.length);
2174
+ let fetcherResults = results.slice(matchesToLoad.length);
2175
+ await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, request.signal, false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(_ref9 => {
2176
+ let [,, match] = _ref9;
2177
+ return match;
2178
+ }), fetcherResults, request.signal, true)]);
2179
+ return {
2180
+ results,
2181
+ loaderResults,
2182
+ fetcherResults
2183
+ };
2184
+ }
2185
+
2186
+ function interruptActiveLoads() {
2187
+ // Every interruption triggers a revalidation
2188
+ isRevalidationRequired = true; // Cancel pending route-level deferreds and mark cancelled routes for
2189
+ // revalidation
2190
+
2191
+ cancelledDeferredRoutes.push(...cancelActiveDeferreds()); // Abort in-flight fetcher loads
2192
+
2193
+ fetchLoadMatches.forEach((_, key) => {
2194
+ if (fetchControllers.has(key)) {
2195
+ cancelledFetcherLoads.push(key);
2196
+ abortFetcher(key);
2197
+ }
2198
+ });
2199
+ }
2200
+
2201
+ function setFetcherError(key, routeId, error) {
2202
+ let boundaryMatch = findNearestBoundary(state.matches, routeId);
2203
+ deleteFetcher(key);
2204
+ updateState({
2205
+ errors: {
2206
+ [boundaryMatch.route.id]: error
2207
+ },
2208
+ fetchers: new Map(state.fetchers)
2209
+ });
2210
+ }
2211
+
2212
+ function deleteFetcher(key) {
2213
+ if (fetchControllers.has(key)) abortFetcher(key);
2214
+ fetchLoadMatches.delete(key);
2215
+ fetchReloadIds.delete(key);
2216
+ fetchRedirectIds.delete(key);
2217
+ state.fetchers.delete(key);
2218
+ }
2219
+
2220
+ function abortFetcher(key) {
2221
+ let controller = fetchControllers.get(key);
2222
+ invariant(controller, "Expected fetch controller: " + key);
2223
+ controller.abort();
2224
+ fetchControllers.delete(key);
2225
+ }
2226
+
2227
+ function markFetchersDone(keys) {
2228
+ for (let key of keys) {
2229
+ let fetcher = getFetcher(key);
2230
+ let doneFetcher = {
2231
+ state: "idle",
2232
+ data: fetcher.data,
2233
+ formMethod: undefined,
2234
+ formAction: undefined,
2235
+ formEncType: undefined,
2236
+ formData: undefined
2237
+ };
2238
+ state.fetchers.set(key, doneFetcher);
2239
+ }
2240
+ }
2241
+
2242
+ function markFetchRedirectsDone() {
2243
+ let doneKeys = [];
2244
+
2245
+ for (let key of fetchRedirectIds) {
2246
+ let fetcher = state.fetchers.get(key);
2247
+ invariant(fetcher, "Expected fetcher: " + key);
2248
+
2249
+ if (fetcher.state === "loading") {
2250
+ fetchRedirectIds.delete(key);
2251
+ doneKeys.push(key);
2252
+ }
2253
+ }
2254
+
2255
+ markFetchersDone(doneKeys);
2256
+ }
2257
+
2258
+ function abortStaleFetchLoads(landedId) {
2259
+ let yeetedKeys = [];
2260
+
2261
+ for (let [key, id] of fetchReloadIds) {
2262
+ if (id < landedId) {
2263
+ let fetcher = state.fetchers.get(key);
2264
+ invariant(fetcher, "Expected fetcher: " + key);
2265
+
2266
+ if (fetcher.state === "loading") {
2267
+ abortFetcher(key);
2268
+ fetchReloadIds.delete(key);
2269
+ yeetedKeys.push(key);
2270
+ }
2271
+ }
2272
+ }
2273
+
2274
+ markFetchersDone(yeetedKeys);
2275
+ return yeetedKeys.length > 0;
2276
+ }
2277
+
2278
+ function cancelActiveDeferreds(predicate) {
2279
+ let cancelledRouteIds = [];
2280
+ activeDeferreds.forEach((dfd, routeId) => {
2281
+ if (!predicate || predicate(routeId)) {
2282
+ // Cancel the deferred - but do not remove from activeDeferreds here -
2283
+ // we rely on the subscribers to do that so our tests can assert proper
2284
+ // cleanup via _internalActiveDeferreds
2285
+ dfd.cancel();
2286
+ cancelledRouteIds.push(routeId);
2287
+ activeDeferreds.delete(routeId);
2288
+ }
2289
+ });
2290
+ return cancelledRouteIds;
2291
+ } // Opt in to capturing and reporting scroll positions during navigations,
2292
+ // used by the <ScrollRestoration> component
2293
+
2294
+
2295
+ function enableScrollRestoration(positions, getPosition, getKey) {
2296
+ savedScrollPositions = positions;
2297
+ getScrollPosition = getPosition;
2298
+
2299
+ getScrollRestorationKey = getKey || (location => location.key); // Perform initial hydration scroll restoration, since we miss the boat on
2300
+ // the initial updateState() because we've not yet rendered <ScrollRestoration/>
2301
+ // and therefore have no savedScrollPositions available
2302
+
2303
+
2304
+ if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
2305
+ initialScrollRestored = true;
2306
+ let y = getSavedScrollPosition(state.location, state.matches);
2307
+
2308
+ if (y != null) {
2309
+ updateState({
2310
+ restoreScrollPosition: y
2311
+ });
2312
+ }
2313
+ }
2314
+
2315
+ return () => {
2316
+ savedScrollPositions = null;
2317
+ getScrollPosition = null;
2318
+ getScrollRestorationKey = null;
2319
+ };
2320
+ }
2321
+
2322
+ function saveScrollPosition(location, matches) {
2323
+ if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {
2324
+ let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));
2325
+ let key = getScrollRestorationKey(location, userMatches) || location.key;
2326
+ savedScrollPositions[key] = getScrollPosition();
2327
+ }
2328
+ }
2329
+
2330
+ function getSavedScrollPosition(location, matches) {
2331
+ if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {
2332
+ let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));
2333
+ let key = getScrollRestorationKey(location, userMatches) || location.key;
2334
+ let y = savedScrollPositions[key];
2335
+
2336
+ if (typeof y === "number") {
2337
+ return y;
2338
+ }
2339
+ }
2340
+
2341
+ return null;
2342
+ }
2343
+
2344
+ router = {
2345
+ get basename() {
2346
+ return init.basename;
2347
+ },
2348
+
2349
+ get state() {
2350
+ return state;
2351
+ },
2352
+
2353
+ get routes() {
2354
+ return dataRoutes;
2355
+ },
2356
+
2357
+ initialize,
2358
+ subscribe,
2359
+ enableScrollRestoration,
2360
+ navigate,
2361
+ fetch,
2362
+ revalidate,
2363
+ // Passthrough to history-aware createHref used by useHref so we get proper
2364
+ // hash-aware URLs in DOM paths
2365
+ createHref: to => init.history.createHref(to),
2366
+ getFetcher,
2367
+ deleteFetcher,
2368
+ dispose,
2369
+ _internalFetchControllers: fetchControllers,
2370
+ _internalActiveDeferreds: activeDeferreds
2371
+ };
2372
+ return router;
2373
+ } //#endregion
2374
+ ////////////////////////////////////////////////////////////////////////////////
2375
+ //#region createStaticHandler
2376
+ ////////////////////////////////////////////////////////////////////////////////
2377
+
2378
+ const validActionMethods = new Set(["POST", "PUT", "PATCH", "DELETE"]);
2379
+ const validRequestMethods = new Set(["GET", "HEAD", ...validActionMethods]);
2380
+ function unstable_createStaticHandler(routes) {
2381
+ invariant(routes.length > 0, "You must provide a non-empty routes array to unstable_createStaticHandler");
2382
+ let dataRoutes = convertRoutesToDataRoutes(routes);
2383
+ /**
2384
+ * The query() method is intended for document requests, in which we want to
2385
+ * call an optional action and potentially multiple loaders for all nested
2386
+ * routes. It returns a StaticHandlerContext object, which is very similar
2387
+ * to the router state (location, loaderData, actionData, errors, etc.) and
2388
+ * also adds SSR-specific information such as the statusCode and headers
2389
+ * from action/loaders Responses.
2390
+ *
2391
+ * It _should_ never throw and should report all errors through the
2392
+ * returned context.errors object, properly associating errors to their error
2393
+ * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be
2394
+ * used to emulate React error boundaries during SSr by performing a second
2395
+ * pass only down to the boundaryId.
2396
+ *
2397
+ * The one exception where we do not return a StaticHandlerContext is when a
2398
+ * redirect response is returned or thrown from any action/loader. We
2399
+ * propagate that out and return the raw Response so the HTTP server can
2400
+ * return it directly.
2401
+ */
2402
+
2403
+ async function query(request) {
2404
+ let url = new URL(request.url);
2405
+ let location = createLocation("", createPath(url), null, "default");
2406
+ let matches = matchRoutes(dataRoutes, location);
2407
+
2408
+ if (!validRequestMethods.has(request.method)) {
2409
+ let {
2410
+ matches: methodNotAllowedMatches,
2411
+ route,
2412
+ error
2413
+ } = getMethodNotAllowedMatches(dataRoutes);
2414
+ return {
2415
+ location,
2416
+ matches: methodNotAllowedMatches,
2417
+ loaderData: {},
2418
+ actionData: null,
2419
+ errors: {
2420
+ [route.id]: error
2421
+ },
2422
+ statusCode: error.status,
2423
+ loaderHeaders: {},
2424
+ actionHeaders: {}
2425
+ };
2426
+ } else if (!matches) {
2427
+ let {
2428
+ matches: notFoundMatches,
2429
+ route,
2430
+ error
2431
+ } = getNotFoundMatches(dataRoutes);
2432
+ return {
2433
+ location,
2434
+ matches: notFoundMatches,
2435
+ loaderData: {},
2436
+ actionData: null,
2437
+ errors: {
2438
+ [route.id]: error
2439
+ },
2440
+ statusCode: error.status,
2441
+ loaderHeaders: {},
2442
+ actionHeaders: {}
2443
+ };
2444
+ }
2445
+
2446
+ let result = await queryImpl(request, location, matches);
2447
+
2448
+ if (result instanceof Response) {
2449
+ return result;
2450
+ } // When returning StaticHandlerContext, we patch back in the location here
2451
+ // since we need it for React Context. But this helps keep our submit and
2452
+ // loadRouteData operating on a Request instead of a Location
2453
+
2454
+
2455
+ return _extends({
2456
+ location
2457
+ }, result);
2458
+ }
2459
+ /**
2460
+ * The queryRoute() method is intended for targeted route requests, either
2461
+ * for fetch ?_data requests or resource route requests. In this case, we
2462
+ * are only ever calling a single action or loader, and we are returning the
2463
+ * returned value directly. In most cases, this will be a Response returned
2464
+ * from the action/loader, but it may be a primitive or other value as well -
2465
+ * and in such cases the calling context should handle that accordingly.
2466
+ *
2467
+ * We do respect the throw/return differentiation, so if an action/loader
2468
+ * throws, then this method will throw the value. This is important so we
2469
+ * can do proper boundary identification in Remix where a thrown Response
2470
+ * must go to the Catch Boundary but a returned Response is happy-path.
2471
+ *
2472
+ * One thing to note is that any Router-initiated thrown Response (such as a
2473
+ * 404 or 405) will have a custom X-Remix-Router-Error: "yes" header on it
2474
+ * in order to differentiate from responses thrown from user actions/loaders.
2475
+ */
2476
+
2477
+
2478
+ async function queryRoute(request, routeId) {
2479
+ let url = new URL(request.url);
2480
+ let location = createLocation("", createPath(url), null, "default");
2481
+ let matches = matchRoutes(dataRoutes, location);
2482
+
2483
+ if (!validRequestMethods.has(request.method)) {
2484
+ throw createRouterErrorResponse(null, {
2485
+ status: 405,
2486
+ statusText: "Method Not Allowed"
2487
+ });
2488
+ } else if (!matches) {
2489
+ throw createRouterErrorResponse(null, {
2490
+ status: 404,
2491
+ statusText: "Not Found"
2492
+ });
2493
+ }
2494
+
2495
+ let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);
2496
+
2497
+ if (!match) {
2498
+ throw createRouterErrorResponse(null, {
2499
+ status: 404,
2500
+ statusText: "Not Found"
2501
+ });
2502
+ }
2503
+
2504
+ let result = await queryImpl(request, location, matches, match);
2505
+
2506
+ if (result instanceof Response) {
2507
+ return result;
2508
+ }
2509
+
2510
+ let error = result.errors ? Object.values(result.errors)[0] : undefined;
2511
+
2512
+ if (error !== undefined) {
2513
+ // If we got back result.errors, that means the loader/action threw
2514
+ // _something_ that wasn't a Response, but it's not guaranteed/required
2515
+ // to be an `instanceof Error` either, so we have to use throw here to
2516
+ // preserve the "error" state outside of queryImpl.
2517
+ throw error;
2518
+ } // Pick off the right state value to return
2519
+
2520
+
2521
+ let routeData = [result.actionData, result.loaderData].find(v => v);
2522
+ return Object.values(routeData || {})[0];
2523
+ }
2524
+
2525
+ async function queryImpl(request, location, matches, routeMatch) {
2526
+ invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
2527
+
2528
+ try {
2529
+ if (validActionMethods.has(request.method)) {
2530
+ let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), routeMatch != null);
2531
+ return result;
2532
+ }
2533
+
2534
+ let result = await loadRouteData(request, matches, routeMatch);
2535
+ return result instanceof Response ? result : _extends({}, result, {
2536
+ actionData: null,
2537
+ actionHeaders: {}
2538
+ });
2539
+ } catch (e) {
2540
+ // If the user threw/returned a Response in callLoaderOrAction, we throw
2541
+ // it to bail out and then return or throw here based on whether the user
2542
+ // returned or threw
2543
+ if (isQueryRouteResponse(e)) {
2544
+ if (e.type === ResultType.error && !isRedirectResponse(e.response)) {
2545
+ throw e.response;
2546
+ }
2547
+
2548
+ return e.response;
2549
+ } // Redirects are always returned since they don't propagate to catch
2550
+ // boundaries
2551
+
2552
+
2553
+ if (isRedirectResponse(e)) {
2554
+ return e;
2555
+ }
2556
+
2557
+ throw e;
2558
+ }
2559
+ }
2560
+
2561
+ async function submit(request, matches, actionMatch, isRouteRequest) {
2562
+ let result;
2563
+
2564
+ if (!actionMatch.route.action) {
2565
+ let href = createServerHref(new URL(request.url));
2566
+
2567
+ if (isRouteRequest) {
2568
+ throw createRouterErrorResponse(null, {
2569
+ status: 405,
2570
+ statusText: "Method Not Allowed"
2571
+ });
2572
+ }
2573
+
2574
+ result = getMethodNotAllowedResult(href);
2575
+ } else {
2576
+ result = await callLoaderOrAction("action", request, actionMatch, matches, undefined, // Basename not currently supported in static handlers
2577
+ true, isRouteRequest);
2578
+
2579
+ if (request.signal.aborted) {
2580
+ let method = isRouteRequest ? "queryRoute" : "query";
2581
+ throw new Error(method + "() call aborted");
2582
+ }
2583
+ }
2584
+
2585
+ if (isRedirectResult(result)) {
2586
+ // Uhhhh - this should never happen, we should always throw these from
2587
+ // callLoaderOrAction, but the type narrowing here keeps TS happy and we
2588
+ // can get back on the "throw all redirect responses" train here should
2589
+ // this ever happen :/
2590
+ throw new Response(null, {
2591
+ status: result.status,
2592
+ headers: {
2593
+ Location: result.location
2594
+ }
2595
+ });
2596
+ }
2597
+
2598
+ if (isDeferredResult(result)) {
2599
+ throw new Error("defer() is not supported in actions");
2600
+ }
2601
+
2602
+ if (isRouteRequest) {
2603
+ // Note: This should only be non-Response values if we get here, since
2604
+ // isRouteRequest should throw any Response received in callLoaderOrAction
2605
+ if (isErrorResult(result)) {
2606
+ let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
2607
+ return {
2608
+ matches: [actionMatch],
2609
+ loaderData: {},
2610
+ actionData: null,
2611
+ errors: {
2612
+ [boundaryMatch.route.id]: result.error
2613
+ },
2614
+ // Note: statusCode + headers are unused here since queryRoute will
2615
+ // return the raw Response or value
2616
+ statusCode: 500,
2617
+ loaderHeaders: {},
2618
+ actionHeaders: {}
2619
+ };
2620
+ }
2621
+
2622
+ return {
2623
+ matches: [actionMatch],
2624
+ loaderData: {},
2625
+ actionData: {
2626
+ [actionMatch.route.id]: result.data
2627
+ },
2628
+ errors: null,
2629
+ // Note: statusCode + headers are unused here since queryRoute will
2630
+ // return the raw Response or value
2631
+ statusCode: 200,
2632
+ loaderHeaders: {},
2633
+ actionHeaders: {}
2634
+ };
2635
+ }
2636
+
2637
+ if (isErrorResult(result)) {
2638
+ // Store off the pending error - we use it to determine which loaders
2639
+ // to call and will commit it when we complete the navigation
2640
+ let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
2641
+ let context = await loadRouteData(request, matches, undefined, {
2642
+ [boundaryMatch.route.id]: result.error
2643
+ }); // action status codes take precedence over loader status codes
2644
+
2645
+ return _extends({}, context, {
2646
+ statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500,
2647
+ actionData: null,
2648
+ actionHeaders: _extends({}, result.headers ? {
2649
+ [actionMatch.route.id]: result.headers
2650
+ } : {})
2651
+ });
2652
+ }
2653
+
2654
+ let context = await loadRouteData(request, matches);
2655
+ return _extends({}, context, result.statusCode ? {
2656
+ statusCode: result.statusCode
2657
+ } : {}, {
2658
+ actionData: {
2659
+ [actionMatch.route.id]: result.data
2660
+ },
2661
+ actionHeaders: _extends({}, result.headers ? {
2662
+ [actionMatch.route.id]: result.headers
2663
+ } : {})
2664
+ });
2665
+ }
2666
+
2667
+ async function loadRouteData(request, matches, routeMatch, pendingActionError) {
2668
+ let isRouteRequest = routeMatch != null;
2669
+ let requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]);
2670
+ let matchesToLoad = requestMatches.filter(m => m.route.loader); // Short circuit if we have no loaders to run
2671
+
2672
+ if (matchesToLoad.length === 0) {
2673
+ return {
2674
+ matches,
2675
+ loaderData: {},
2676
+ errors: pendingActionError || null,
2677
+ statusCode: 200,
2678
+ loaderHeaders: {}
2679
+ };
2680
+ }
2681
+
2682
+ let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, undefined, // Basename not currently supported in static handlers
2683
+ true, isRouteRequest))]);
2684
+
2685
+ if (request.signal.aborted) {
2686
+ let method = isRouteRequest ? "queryRoute" : "query";
2687
+ throw new Error(method + "() call aborted");
2688
+ } // Can't do anything with these without the Remix side of things, so just
2689
+ // cancel them for now
2690
+
2691
+
2692
+ results.forEach(result => {
2693
+ if (isDeferredResult(result)) {
2694
+ result.deferredData.cancel();
2695
+ }
2696
+ }); // Process and commit output from loaders
2697
+
2698
+ let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError);
2699
+ return _extends({}, context, {
2700
+ matches
2701
+ });
2702
+ }
2703
+
2704
+ function createRouterErrorResponse(body, init) {
2705
+ return new Response(body, _extends({}, init, {
2706
+ headers: _extends({}, init.headers, {
2707
+ "X-Remix-Router-Error": "yes"
2708
+ })
2709
+ }));
2710
+ }
2711
+
2712
+ return {
2713
+ dataRoutes,
2714
+ query,
2715
+ queryRoute
2716
+ };
2717
+ } //#endregion
2718
+ ////////////////////////////////////////////////////////////////////////////////
2719
+ //#region Helpers
2720
+ ////////////////////////////////////////////////////////////////////////////////
2721
+
2722
+ /**
2723
+ * Given an existing StaticHandlerContext and an error thrown at render time,
2724
+ * provide an updated StaticHandlerContext suitable for a second SSR render
2725
+ */
2726
+
2727
+ function getStaticContextFromError(routes, context, error) {
2728
+ let newContext = _extends({}, context, {
2729
+ statusCode: 500,
2730
+ errors: {
2731
+ [context._deepestRenderedBoundaryId || routes[0].id]: error
2732
+ }
2733
+ });
2734
+
2735
+ return newContext;
2736
+ } // Normalize navigation options by converting formMethod=GET formData objects to
2737
+ // URLSearchParams so they behave identically to links with query params
2738
+
2739
+ function normalizeNavigateOptions(to, opts, isFetcher) {
2740
+ if (isFetcher === void 0) {
2741
+ isFetcher = false;
2742
+ }
2743
+
2744
+ let path = typeof to === "string" ? to : createPath(to); // Return location verbatim on non-submission navigations
2745
+
2746
+ if (!opts || !("formMethod" in opts) && !("formData" in opts)) {
2747
+ return {
2748
+ path
2749
+ };
2750
+ } // Create a Submission on non-GET navigations
2751
+
2752
+
2753
+ if (opts.formMethod != null && opts.formMethod !== "get") {
2754
+ return {
2755
+ path,
2756
+ submission: {
2757
+ formMethod: opts.formMethod,
2758
+ formAction: createServerHref(parsePath(path)),
2759
+ formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
2760
+ formData: opts.formData
2761
+ }
2762
+ };
2763
+ } // No formData to flatten for GET submission
2764
+
2765
+
2766
+ if (!opts.formData) {
2767
+ return {
2768
+ path
2769
+ };
2770
+ } // Flatten submission onto URLSearchParams for GET submissions
2771
+
2772
+
2773
+ let parsedPath = parsePath(path);
2774
+
2775
+ try {
2776
+ let searchParams = convertFormDataToSearchParams(opts.formData); // Since fetcher GET submissions only run a single loader (as opposed to
2777
+ // navigation GET submissions which run all loaders), we need to preserve
2778
+ // any incoming ?index params
2779
+
2780
+ if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
2781
+ searchParams.append("index", "");
2782
+ }
2783
+
2784
+ parsedPath.search = "?" + searchParams;
2785
+ } catch (e) {
2786
+ return {
2787
+ path,
2788
+ error: new ErrorResponse(400, "Bad Request", "Cannot submit binary form data using GET")
2789
+ };
2790
+ }
2791
+
2792
+ return {
2793
+ path: createPath(parsedPath)
2794
+ };
2795
+ }
2796
+
2797
+ function getLoaderRedirect(state, redirect) {
2798
+ let {
2799
+ formMethod,
2800
+ formAction,
2801
+ formEncType,
2802
+ formData
2803
+ } = state.navigation;
2804
+ let navigation = {
2805
+ state: "loading",
2806
+ location: createLocation(state.location, redirect.location),
2807
+ formMethod: formMethod || undefined,
2808
+ formAction: formAction || undefined,
2809
+ formEncType: formEncType || undefined,
2810
+ formData: formData || undefined
2811
+ };
2812
+ return navigation;
2813
+ } // Filter out all routes below any caught error as they aren't going to
2814
+ // render so we don't need to load them
2815
+
2816
+
2817
+ function getLoaderMatchesUntilBoundary(matches, boundaryId) {
2818
+ let boundaryMatches = matches;
2819
+
2820
+ if (boundaryId) {
2821
+ let index = matches.findIndex(m => m.route.id === boundaryId);
2822
+
2823
+ if (index >= 0) {
2824
+ boundaryMatches = matches.slice(0, index);
2825
+ }
2826
+ }
2827
+
2828
+ return boundaryMatches;
2829
+ }
2830
+
2831
+ function getMatchesToLoad(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches) {
2832
+ let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : null; // Pick navigation matches that are net-new or qualify for revalidation
2833
+
2834
+ let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;
2835
+ let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);
2836
+ let navigationMatches = boundaryMatches.filter((match, index) => match.route.loader != null && (isNewLoader(state.loaderData, state.matches[index], match) || // If this route had a pending deferred cancelled it must be revalidated
2837
+ cancelledDeferredRoutes.some(id => id === match.route.id) || shouldRevalidateLoader(state.location, state.matches[index], submission, location, match, isRevalidationRequired, actionResult))); // Pick fetcher.loads that need to be revalidated
2838
+
2839
+ let revalidatingFetchers = [];
2840
+ fetchLoadMatches && fetchLoadMatches.forEach((_ref10, key) => {
2841
+ let [href, match, fetchMatches] = _ref10;
2842
+
2843
+ // This fetcher was cancelled from a prior action submission - force reload
2844
+ if (cancelledFetcherLoads.includes(key)) {
2845
+ revalidatingFetchers.push([key, href, match, fetchMatches]);
2846
+ } else if (isRevalidationRequired) {
2847
+ let shouldRevalidate = shouldRevalidateLoader(href, match, submission, href, match, isRevalidationRequired, actionResult);
2848
+
2849
+ if (shouldRevalidate) {
2850
+ revalidatingFetchers.push([key, href, match, fetchMatches]);
2851
+ }
2852
+ }
2853
+ });
2854
+ return [navigationMatches, revalidatingFetchers];
2855
+ }
2856
+
2857
+ function isNewLoader(currentLoaderData, currentMatch, match) {
2858
+ let isNew = // [a] -> [a, b]
2859
+ !currentMatch || // [a, b] -> [a, c]
2860
+ match.route.id !== currentMatch.route.id; // Handle the case that we don't have data for a re-used route, potentially
2861
+ // from a prior error or from a cancelled pending deferred
2862
+
2863
+ let isMissingData = currentLoaderData[match.route.id] === undefined; // Always load if this is a net-new route or we don't yet have data
2864
+
2865
+ return isNew || isMissingData;
2866
+ }
2867
+
2868
+ function isNewRouteInstance(currentMatch, match) {
2869
+ let currentPath = currentMatch.route.path;
2870
+ return (// param change for this match, /users/123 -> /users/456
2871
+ currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path
2872
+ // e.g. /files/images/avatar.jpg -> files/finances.xls
2873
+ currentPath && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
2874
+ );
2875
+ }
2876
+
2877
+ function shouldRevalidateLoader(currentLocation, currentMatch, submission, location, match, isRevalidationRequired, actionResult) {
2878
+ let currentUrl = createURL(currentLocation);
2879
+ let currentParams = currentMatch.params;
2880
+ let nextUrl = createURL(location);
2881
+ let nextParams = match.params; // This is the default implementation as to when we revalidate. If the route
2882
+ // provides it's own implementation, then we give them full control but
2883
+ // provide this value so they can leverage it if needed after they check
2884
+ // their own specific use cases
2885
+ // Note that fetchers always provide the same current/next locations so the
2886
+ // URL-based checks here don't apply to fetcher shouldRevalidate calls
2887
+
2888
+ let defaultShouldRevalidate = isNewRouteInstance(currentMatch, match) || // Clicked the same link, resubmitted a GET form
2889
+ currentUrl.toString() === nextUrl.toString() || // Search params affect all loaders
2890
+ currentUrl.search !== nextUrl.search || // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate
2891
+ isRevalidationRequired;
2892
+
2893
+ if (match.route.shouldRevalidate) {
2894
+ let routeChoice = match.route.shouldRevalidate(_extends({
2895
+ currentUrl,
2896
+ currentParams,
2897
+ nextUrl,
2898
+ nextParams
2899
+ }, submission, {
2900
+ actionResult,
2901
+ defaultShouldRevalidate
2902
+ }));
2903
+
2904
+ if (typeof routeChoice === "boolean") {
2905
+ return routeChoice;
2906
+ }
2907
+ }
2908
+
2909
+ return defaultShouldRevalidate;
2910
+ }
2911
+
2912
+ async function callLoaderOrAction(type, request, match, matches, basename, isStaticRequest, isRouteRequest) {
2913
+ if (isStaticRequest === void 0) {
2914
+ isStaticRequest = false;
2915
+ }
2916
+
2917
+ if (isRouteRequest === void 0) {
2918
+ isRouteRequest = false;
2919
+ }
2920
+
2921
+ let resultType;
2922
+ let result; // Setup a promise we can race against so that abort signals short circuit
2923
+
2924
+ let reject;
2925
+ let abortPromise = new Promise((_, r) => reject = r);
2926
+
2927
+ let onReject = () => reject();
2928
+
2929
+ request.signal.addEventListener("abort", onReject);
2930
+
2931
+ try {
2932
+ let handler = match.route[type];
2933
+ invariant(handler, "Could not find the " + type + " to run on the \"" + match.route.id + "\" route");
2934
+ result = await Promise.race([handler({
2935
+ request,
2936
+ params: match.params
2937
+ }), abortPromise]);
2938
+ } catch (e) {
2939
+ resultType = ResultType.error;
2940
+ result = e;
2941
+ } finally {
2942
+ request.signal.removeEventListener("abort", onReject);
2943
+ }
2944
+
2945
+ if (result instanceof Response) {
2946
+ let status = result.status; // Process redirects
2947
+
2948
+ if (status >= 300 && status <= 399) {
2949
+ let location = result.headers.get("Location");
2950
+ invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header"); // Support relative routing in redirects
2951
+
2952
+ let activeMatches = matches.slice(0, matches.indexOf(match) + 1);
2953
+ let routePathnames = getPathContributingMatches(activeMatches).map(match => match.pathnameBase);
2954
+ let requestPath = createURL(request.url).pathname;
2955
+ let resolvedLocation = resolveTo(location, routePathnames, requestPath);
2956
+ invariant(createPath(resolvedLocation), "Unable to resolve redirect location: " + result.headers.get("Location")); // Prepend the basename to the redirect location if we have one
2957
+
2958
+ if (basename) {
2959
+ let path = resolvedLocation.pathname;
2960
+ resolvedLocation.pathname = path === "/" ? basename : joinPaths([basename, path]);
2961
+ }
2962
+
2963
+ location = createPath(resolvedLocation); // Don't process redirects in the router during static requests requests.
2964
+ // Instead, throw the Response and let the server handle it with an HTTP
2965
+ // redirect. We also update the Location header in place in this flow so
2966
+ // basename and relative routing is taken into account
2967
+
2968
+ if (isStaticRequest) {
2969
+ result.headers.set("Location", location);
2970
+ throw result;
2971
+ }
2972
+
2973
+ return {
2974
+ type: ResultType.redirect,
2975
+ status,
2976
+ location,
2977
+ revalidate: result.headers.get("X-Remix-Revalidate") !== null
2978
+ };
2979
+ } // For SSR single-route requests, we want to hand Responses back directly
2980
+ // without unwrapping. We do this with the QueryRouteResponse wrapper
2981
+ // interface so we can know whether it was returned or thrown
2982
+
2983
+
2984
+ if (isRouteRequest) {
2985
+ // eslint-disable-next-line no-throw-literal
2986
+ throw {
2987
+ type: resultType || ResultType.data,
2988
+ response: result
2989
+ };
2990
+ }
2991
+
2992
+ let data;
2993
+ let contentType = result.headers.get("Content-Type");
2994
+
2995
+ if (contentType && contentType.startsWith("application/json")) {
2996
+ data = await result.json();
2997
+ } else {
2998
+ data = await result.text();
2999
+ }
3000
+
3001
+ if (resultType === ResultType.error) {
3002
+ return {
3003
+ type: resultType,
3004
+ error: new ErrorResponse(status, result.statusText, data),
3005
+ headers: result.headers
3006
+ };
3007
+ }
3008
+
3009
+ return {
3010
+ type: ResultType.data,
3011
+ data,
3012
+ statusCode: result.status,
3013
+ headers: result.headers
3014
+ };
3015
+ }
3016
+
3017
+ if (resultType === ResultType.error) {
3018
+ return {
3019
+ type: resultType,
3020
+ error: result
3021
+ };
3022
+ }
3023
+
3024
+ if (result instanceof DeferredData) {
3025
+ return {
3026
+ type: ResultType.deferred,
3027
+ deferredData: result
3028
+ };
3029
+ }
3030
+
3031
+ return {
3032
+ type: ResultType.data,
3033
+ data: result
3034
+ };
3035
+ }
3036
+
3037
+ function createRequest(location, signal, submission) {
3038
+ let url = createURL(location).toString();
3039
+ let init = {
3040
+ signal
3041
+ };
3042
+
3043
+ if (submission) {
3044
+ let {
3045
+ formMethod,
3046
+ formEncType,
3047
+ formData
3048
+ } = submission;
3049
+ init.method = formMethod.toUpperCase();
3050
+ init.body = formEncType === "application/x-www-form-urlencoded" ? convertFormDataToSearchParams(formData) : formData;
3051
+ } // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
3052
+
3053
+
3054
+ return new Request(url, init);
3055
+ }
3056
+
3057
+ function convertFormDataToSearchParams(formData) {
3058
+ let searchParams = new URLSearchParams();
3059
+
3060
+ for (let [key, value] of formData.entries()) {
3061
+ invariant(typeof value === "string", 'File inputs are not supported with encType "application/x-www-form-urlencoded", ' + 'please use "multipart/form-data" instead.');
3062
+ searchParams.append(key, value);
3063
+ }
3064
+
3065
+ return searchParams;
3066
+ }
3067
+
3068
+ function processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) {
3069
+ // Fill in loaderData/errors from our loaders
3070
+ let loaderData = {};
3071
+ let errors = null;
3072
+ let statusCode;
3073
+ let foundError = false;
3074
+ let loaderHeaders = {}; // Process loader results into state.loaderData/state.errors
3075
+
3076
+ results.forEach((result, index) => {
3077
+ let id = matchesToLoad[index].route.id;
3078
+ invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
3079
+
3080
+ if (isErrorResult(result)) {
3081
+ // Look upwards from the matched route for the closest ancestor
3082
+ // error boundary, defaulting to the root match
3083
+ let boundaryMatch = findNearestBoundary(matches, id);
3084
+ let error = result.error; // If we have a pending action error, we report it at the highest-route
3085
+ // that throws a loader error, and then clear it out to indicate that
3086
+ // it was consumed
3087
+
3088
+ if (pendingError) {
3089
+ error = Object.values(pendingError)[0];
3090
+ pendingError = undefined;
3091
+ }
3092
+
3093
+ errors = Object.assign(errors || {}, {
3094
+ [boundaryMatch.route.id]: error
3095
+ }); // Once we find our first (highest) error, we set the status code and
3096
+ // prevent deeper status codes from overriding
3097
+
3098
+ if (!foundError) {
3099
+ foundError = true;
3100
+ statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
3101
+ }
3102
+
3103
+ if (result.headers) {
3104
+ loaderHeaders[id] = result.headers;
3105
+ }
3106
+ } else if (isDeferredResult(result)) {
3107
+ activeDeferreds && activeDeferreds.set(id, result.deferredData);
3108
+ loaderData[id] = result.deferredData.data; // TODO: Add statusCode/headers once we wire up streaming in Remix
3109
+ } else {
3110
+ loaderData[id] = result.data; // Error status codes always override success status codes, but if all
3111
+ // loaders are successful we take the deepest status code.
3112
+
3113
+ if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
3114
+ statusCode = result.statusCode;
3115
+ }
3116
+
3117
+ if (result.headers) {
3118
+ loaderHeaders[id] = result.headers;
3119
+ }
3120
+ }
3121
+ }); // If we didn't consume the pending action error (i.e., all loaders
3122
+ // resolved), then consume it here
3123
+
3124
+ if (pendingError) {
3125
+ errors = pendingError;
3126
+ }
3127
+
3128
+ return {
3129
+ loaderData,
3130
+ errors,
3131
+ statusCode: statusCode || 200,
3132
+ loaderHeaders
3133
+ };
3134
+ }
3135
+
3136
+ function processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) {
3137
+ let {
3138
+ loaderData,
3139
+ errors
3140
+ } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds); // Process results from our revalidating fetchers
3141
+
3142
+ for (let index = 0; index < revalidatingFetchers.length; index++) {
3143
+ let [key,, match] = revalidatingFetchers[index];
3144
+ invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result");
3145
+ let result = fetcherResults[index]; // Process fetcher non-redirect errors
3146
+
3147
+ if (isErrorResult(result)) {
3148
+ let boundaryMatch = findNearestBoundary(state.matches, match.route.id);
3149
+
3150
+ if (!(errors && errors[boundaryMatch.route.id])) {
3151
+ errors = _extends({}, errors, {
3152
+ [boundaryMatch.route.id]: result.error
3153
+ });
3154
+ }
3155
+
3156
+ state.fetchers.delete(key);
3157
+ } else if (isRedirectResult(result)) {
3158
+ // Should never get here, redirects should get processed above, but we
3159
+ // keep this to type narrow to a success result in the else
3160
+ throw new Error("Unhandled fetcher revalidation redirect");
3161
+ } else if (isDeferredResult(result)) {
3162
+ // Should never get here, deferred data should be awaited for fetchers
3163
+ // in resolveDeferredResults
3164
+ throw new Error("Unhandled fetcher deferred data");
3165
+ } else {
3166
+ let doneFetcher = {
3167
+ state: "idle",
3168
+ data: result.data,
3169
+ formMethod: undefined,
3170
+ formAction: undefined,
3171
+ formEncType: undefined,
3172
+ formData: undefined
3173
+ };
3174
+ state.fetchers.set(key, doneFetcher);
3175
+ }
3176
+ }
3177
+
3178
+ return {
3179
+ loaderData,
3180
+ errors
3181
+ };
3182
+ }
3183
+
3184
+ function mergeLoaderData(loaderData, newLoaderData, matches) {
3185
+ let mergedLoaderData = _extends({}, newLoaderData);
3186
+
3187
+ matches.forEach(match => {
3188
+ let id = match.route.id;
3189
+
3190
+ if (newLoaderData[id] === undefined && loaderData[id] !== undefined) {
3191
+ mergedLoaderData[id] = loaderData[id];
3192
+ }
3193
+ });
3194
+ return mergedLoaderData;
3195
+ } // Find the nearest error boundary, looking upwards from the leaf route (or the
3196
+ // route specified by routeId) for the closest ancestor error boundary,
3197
+ // defaulting to the root match
3198
+
3199
+
3200
+ function findNearestBoundary(matches, routeId) {
3201
+ let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];
3202
+ return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];
3203
+ }
3204
+
3205
+ function getShortCircuitMatches(routes, status, statusText) {
3206
+ // Prefer a root layout route if present, otherwise shim in a route object
3207
+ let route = routes.find(r => r.index || !r.path || r.path === "/") || {
3208
+ id: "__shim-" + status + "-route__"
3209
+ };
3210
+ return {
3211
+ matches: [{
3212
+ params: {},
3213
+ pathname: "",
3214
+ pathnameBase: "",
3215
+ route
3216
+ }],
3217
+ route,
3218
+ error: new ErrorResponse(status, statusText, null)
3219
+ };
3220
+ }
3221
+
3222
+ function getNotFoundMatches(routes) {
3223
+ return getShortCircuitMatches(routes, 404, "Not Found");
3224
+ }
3225
+
3226
+ function getMethodNotAllowedMatches(routes) {
3227
+ return getShortCircuitMatches(routes, 405, "Method Not Allowed");
3228
+ }
3229
+
3230
+ function getMethodNotAllowedResult(path) {
3231
+ let href = typeof path === "string" ? path : createServerHref(path);
3232
+ console.warn("You're trying to submit to a route that does not have an action. To " + "fix this, please add an `action` function to the route for " + ("[" + href + "]"));
3233
+ return {
3234
+ type: ResultType.error,
3235
+ error: new ErrorResponse(405, "Method Not Allowed", "")
3236
+ };
3237
+ } // Find any returned redirect errors, starting from the lowest match
3238
+
3239
+
3240
+ function findRedirect(results) {
3241
+ for (let i = results.length - 1; i >= 0; i--) {
3242
+ let result = results[i];
3243
+
3244
+ if (isRedirectResult(result)) {
3245
+ return result;
3246
+ }
3247
+ }
3248
+ } // Create an href to represent a "server" URL without the hash
3249
+
3250
+
3251
+ function createServerHref(location) {
3252
+ return (location.pathname || "") + (location.search || "");
3253
+ }
3254
+
3255
+ function isHashChangeOnly(a, b) {
3256
+ return a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash;
3257
+ }
3258
+
3259
+ function isDeferredResult(result) {
3260
+ return result.type === ResultType.deferred;
3261
+ }
3262
+
3263
+ function isErrorResult(result) {
3264
+ return result.type === ResultType.error;
3265
+ }
3266
+
3267
+ function isRedirectResult(result) {
3268
+ return (result && result.type) === ResultType.redirect;
3269
+ }
3270
+
3271
+ function isRedirectResponse(result) {
3272
+ if (!(result instanceof Response)) {
3273
+ return false;
3274
+ }
3275
+
3276
+ let status = result.status;
3277
+ let location = result.headers.get("Location");
3278
+ return status >= 300 && status <= 399 && location != null;
3279
+ }
3280
+
3281
+ function isQueryRouteResponse(obj) {
3282
+ return obj && obj.response instanceof Response && (obj.type === ResultType.data || ResultType.error);
3283
+ }
3284
+
3285
+ async function resolveDeferredResults(currentMatches, matchesToLoad, results, signal, isFetcher, currentLoaderData) {
3286
+ for (let index = 0; index < results.length; index++) {
3287
+ let result = results[index];
3288
+ let match = matchesToLoad[index];
3289
+ let currentMatch = currentMatches.find(m => m.route.id === match.route.id);
3290
+ let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;
3291
+
3292
+ if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {
3293
+ // Note: we do not have to touch activeDeferreds here since we race them
3294
+ // against the signal in resolveDeferredData and they'll get aborted
3295
+ // there if needed
3296
+ await resolveDeferredData(result, signal, isFetcher).then(result => {
3297
+ if (result) {
3298
+ results[index] = result || results[index];
3299
+ }
3300
+ });
3301
+ }
3302
+ }
3303
+ }
3304
+
3305
+ async function resolveDeferredData(result, signal, unwrap) {
3306
+ if (unwrap === void 0) {
3307
+ unwrap = false;
3308
+ }
3309
+
3310
+ let aborted = await result.deferredData.resolveData(signal);
3311
+
3312
+ if (aborted) {
3313
+ return;
3314
+ }
3315
+
3316
+ if (unwrap) {
3317
+ try {
3318
+ return {
3319
+ type: ResultType.data,
3320
+ data: result.deferredData.unwrappedData
3321
+ };
3322
+ } catch (e) {
3323
+ // Handle any TrackedPromise._error values encountered while unwrapping
3324
+ return {
3325
+ type: ResultType.error,
3326
+ error: e
3327
+ };
3328
+ }
3329
+ }
3330
+
3331
+ return {
3332
+ type: ResultType.data,
3333
+ data: result.deferredData.data
3334
+ };
3335
+ }
3336
+
3337
+ function hasNakedIndexQuery(search) {
3338
+ return new URLSearchParams(search).getAll("index").some(v => v === "");
3339
+ } // Note: This should match the format exported by useMatches, so if you change
3340
+ // this please also change that :) Eventually we'll DRY this up
3341
+
3342
+
3343
+ function createUseMatchesMatch(match, loaderData) {
3344
+ let {
3345
+ route,
3346
+ pathname,
3347
+ params
3348
+ } = match;
3349
+ return {
3350
+ id: route.id,
3351
+ pathname,
3352
+ params,
3353
+ data: loaderData[route.id],
3354
+ handle: route.handle
3355
+ };
3356
+ }
3357
+
3358
+ function getTargetMatch(matches, location) {
3359
+ let search = typeof location === "string" ? parsePath(location).search : location.search;
3360
+
3361
+ if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
3362
+ // Return the leaf index route when index is present
3363
+ return matches[matches.length - 1];
3364
+ } // Otherwise grab the deepest "path contributing" match (ignoring index and
3365
+ // pathless layout routes)
3366
+
3367
+
3368
+ let pathMatches = getPathContributingMatches(matches);
3369
+ return pathMatches[pathMatches.length - 1];
3370
+ }
3371
+
3372
+ function createURL(location) {
3373
+ let base = typeof window !== "undefined" && typeof window.location !== "undefined" ? window.location.origin : "unknown://unknown";
3374
+ let href = typeof location === "string" ? location : createServerHref(location);
3375
+ return new URL(href, base);
3376
+ } //#endregion
3377
+
3378
+ exports.AbortedDeferredError = AbortedDeferredError;
3379
+ exports.ErrorResponse = ErrorResponse;
3380
+ exports.IDLE_FETCHER = IDLE_FETCHER;
3381
+ exports.IDLE_NAVIGATION = IDLE_NAVIGATION;
3382
+ exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes;
3383
+ exports.UNSAFE_getPathContributingMatches = getPathContributingMatches;
3384
+ exports.createBrowserHistory = createBrowserHistory;
3385
+ exports.createHashHistory = createHashHistory;
3386
+ exports.createMemoryHistory = createMemoryHistory;
3387
+ exports.createPath = createPath;
3388
+ exports.createRouter = createRouter;
3389
+ exports.defer = defer;
3390
+ exports.generatePath = generatePath;
3391
+ exports.getStaticContextFromError = getStaticContextFromError;
3392
+ exports.getToPathname = getToPathname;
3393
+ exports.invariant = invariant;
3394
+ exports.isRouteErrorResponse = isRouteErrorResponse;
3395
+ exports.joinPaths = joinPaths;
3396
+ exports.json = json;
3397
+ exports.matchPath = matchPath;
3398
+ exports.matchRoutes = matchRoutes;
3399
+ exports.normalizePathname = normalizePathname;
3400
+ exports.parsePath = parsePath;
3401
+ exports.redirect = redirect;
3402
+ exports.resolvePath = resolvePath;
3403
+ exports.resolveTo = resolveTo;
3404
+ exports.stripBasename = stripBasename;
3405
+ exports.unstable_createStaticHandler = unstable_createStaticHandler;
3406
+ exports.warning = warning;
3407
+
3408
+ Object.defineProperty(exports, '__esModule', { value: true });
3409
+
3410
+ }));
3411
+ //# sourceMappingURL=router.umd.js.map