@remix-run/router 0.0.0-experimental-48058118

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