@tanstack/react-router 0.0.1-beta.7 → 0.0.1-beta.71

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.
@@ -1,2524 +0,0 @@
1
- /**
2
- * react-router
3
- *
4
- * Copyright (c) TanStack
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
- /**
16
- * router-core
17
- *
18
- * Copyright (c) TanStack
19
- *
20
- * This source code is licensed under the MIT license found in the
21
- * LICENSE.md file in the root directory of this source tree.
22
- *
23
- * @license MIT
24
- */
25
- function _extends$1() {
26
- _extends$1 = Object.assign ? Object.assign.bind() : function (target) {
27
- for (var i = 1; i < arguments.length; i++) {
28
- var source = arguments[i];
29
-
30
- for (var key in source) {
31
- if (Object.prototype.hasOwnProperty.call(source, key)) {
32
- target[key] = source[key];
33
- }
34
- }
35
- }
36
-
37
- return target;
38
- };
39
- return _extends$1.apply(this, arguments);
40
- }
41
-
42
- /**
43
- * Actions represent the type of change to a location value.
44
- *
45
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#action
46
- */
47
- var Action;
48
-
49
- (function (Action) {
50
- /**
51
- * A POP indicates a change to an arbitrary index in the history stack, such
52
- * as a back or forward navigation. It does not describe the direction of the
53
- * navigation, only that the current index changed.
54
- *
55
- * Note: This is the default action for newly created history objects.
56
- */
57
- Action["Pop"] = "POP";
58
- /**
59
- * A PUSH indicates a new entry being added to the history stack, such as when
60
- * a link is clicked and a new page loads. When this happens, all subsequent
61
- * entries in the stack are lost.
62
- */
63
-
64
- Action["Push"] = "PUSH";
65
- /**
66
- * A REPLACE indicates the entry at the current index in the history stack
67
- * being replaced by a new one.
68
- */
69
-
70
- Action["Replace"] = "REPLACE";
71
- })(Action || (Action = {}));
72
-
73
- var readOnly = process.env.NODE_ENV !== "production" ? function (obj) {
74
- return Object.freeze(obj);
75
- } : function (obj) {
76
- return obj;
77
- };
78
-
79
- function warning$1(cond, message) {
80
- if (!cond) {
81
- // eslint-disable-next-line no-console
82
- if (typeof console !== 'undefined') console.warn(message);
83
-
84
- try {
85
- // Welcome to debugging history!
86
- //
87
- // This error is thrown as a convenience so you can more easily
88
- // find the source for a warning that appears in the console by
89
- // enabling "pause on exceptions" in your JavaScript debugger.
90
- throw new Error(message); // eslint-disable-next-line no-empty
91
- } catch (e) {}
92
- }
93
- }
94
-
95
- var BeforeUnloadEventType = 'beforeunload';
96
- var HashChangeEventType = 'hashchange';
97
- var PopStateEventType = 'popstate';
98
- /**
99
- * Browser history stores the location in regular URLs. This is the standard for
100
- * most web apps, but it requires some configuration on the server to ensure you
101
- * serve the same app at multiple URLs.
102
- *
103
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
104
- */
105
-
106
- function createBrowserHistory(options) {
107
- if (options === void 0) {
108
- options = {};
109
- }
110
-
111
- var _options = options,
112
- _options$window = _options.window,
113
- window = _options$window === void 0 ? document.defaultView : _options$window;
114
- var globalHistory = window.history;
115
-
116
- function getIndexAndLocation() {
117
- var _window$location = window.location,
118
- pathname = _window$location.pathname,
119
- search = _window$location.search,
120
- hash = _window$location.hash;
121
- var state = globalHistory.state || {};
122
- return [state.idx, readOnly({
123
- pathname: pathname,
124
- search: search,
125
- hash: hash,
126
- state: state.usr || null,
127
- key: state.key || 'default'
128
- })];
129
- }
130
-
131
- var blockedPopTx = null;
132
-
133
- function handlePop() {
134
- if (blockedPopTx) {
135
- blockers.call(blockedPopTx);
136
- blockedPopTx = null;
137
- } else {
138
- var nextAction = Action.Pop;
139
-
140
- var _getIndexAndLocation = getIndexAndLocation(),
141
- nextIndex = _getIndexAndLocation[0],
142
- nextLocation = _getIndexAndLocation[1];
143
-
144
- if (blockers.length) {
145
- if (nextIndex != null) {
146
- var delta = index - nextIndex;
147
-
148
- if (delta) {
149
- // Revert the POP
150
- blockedPopTx = {
151
- action: nextAction,
152
- location: nextLocation,
153
- retry: function retry() {
154
- go(delta * -1);
155
- }
156
- };
157
- go(delta);
158
- }
159
- } else {
160
- // Trying to POP to a location with no index. We did not create
161
- // this location, so we can't effectively block the navigation.
162
- process.env.NODE_ENV !== "production" ? warning$1(false, // TODO: Write up a doc that explains our blocking strategy in
163
- // detail and link to it here so people can understand better what
164
- // is going on and how to avoid it.
165
- "You are trying to block a POP navigation to a location that was not " + "created by the history library. The block will fail silently in " + "production, but in general you should do all navigation with the " + "history library (instead of using window.history.pushState directly) " + "to avoid this situation.") : void 0;
166
- }
167
- } else {
168
- applyTx(nextAction);
169
- }
170
- }
171
- }
172
-
173
- window.addEventListener(PopStateEventType, handlePop);
174
- var action = Action.Pop;
175
-
176
- var _getIndexAndLocation2 = getIndexAndLocation(),
177
- index = _getIndexAndLocation2[0],
178
- location = _getIndexAndLocation2[1];
179
-
180
- var listeners = createEvents();
181
- var blockers = createEvents();
182
-
183
- if (index == null) {
184
- index = 0;
185
- globalHistory.replaceState(_extends$1({}, globalHistory.state, {
186
- idx: index
187
- }), '');
188
- }
189
-
190
- function createHref(to) {
191
- return typeof to === 'string' ? to : createPath(to);
192
- } // state defaults to `null` because `window.history.state` does
193
-
194
-
195
- function getNextLocation(to, state) {
196
- if (state === void 0) {
197
- state = null;
198
- }
199
-
200
- return readOnly(_extends$1({
201
- pathname: location.pathname,
202
- hash: '',
203
- search: ''
204
- }, typeof to === 'string' ? parsePath(to) : to, {
205
- state: state,
206
- key: createKey()
207
- }));
208
- }
209
-
210
- function getHistoryStateAndUrl(nextLocation, index) {
211
- return [{
212
- usr: nextLocation.state,
213
- key: nextLocation.key,
214
- idx: index
215
- }, createHref(nextLocation)];
216
- }
217
-
218
- function allowTx(action, location, retry) {
219
- return !blockers.length || (blockers.call({
220
- action: action,
221
- location: location,
222
- retry: retry
223
- }), false);
224
- }
225
-
226
- function applyTx(nextAction) {
227
- action = nextAction;
228
-
229
- var _getIndexAndLocation3 = getIndexAndLocation();
230
-
231
- index = _getIndexAndLocation3[0];
232
- location = _getIndexAndLocation3[1];
233
- listeners.call({
234
- action: action,
235
- location: location
236
- });
237
- }
238
-
239
- function push(to, state) {
240
- var nextAction = Action.Push;
241
- var nextLocation = getNextLocation(to, state);
242
-
243
- function retry() {
244
- push(to, state);
245
- }
246
-
247
- if (allowTx(nextAction, nextLocation, retry)) {
248
- var _getHistoryStateAndUr = getHistoryStateAndUrl(nextLocation, index + 1),
249
- historyState = _getHistoryStateAndUr[0],
250
- url = _getHistoryStateAndUr[1]; // TODO: Support forced reloading
251
- // try...catch because iOS limits us to 100 pushState calls :/
252
-
253
-
254
- try {
255
- globalHistory.pushState(historyState, '', url);
256
- } catch (error) {
257
- // They are going to lose state here, but there is no real
258
- // way to warn them about it since the page will refresh...
259
- window.location.assign(url);
260
- }
261
-
262
- applyTx(nextAction);
263
- }
264
- }
265
-
266
- function replace(to, state) {
267
- var nextAction = Action.Replace;
268
- var nextLocation = getNextLocation(to, state);
269
-
270
- function retry() {
271
- replace(to, state);
272
- }
273
-
274
- if (allowTx(nextAction, nextLocation, retry)) {
275
- var _getHistoryStateAndUr2 = getHistoryStateAndUrl(nextLocation, index),
276
- historyState = _getHistoryStateAndUr2[0],
277
- url = _getHistoryStateAndUr2[1]; // TODO: Support forced reloading
278
-
279
-
280
- globalHistory.replaceState(historyState, '', url);
281
- applyTx(nextAction);
282
- }
283
- }
284
-
285
- function go(delta) {
286
- globalHistory.go(delta);
287
- }
288
-
289
- var history = {
290
- get action() {
291
- return action;
292
- },
293
-
294
- get location() {
295
- return location;
296
- },
297
-
298
- createHref: createHref,
299
- push: push,
300
- replace: replace,
301
- go: go,
302
- back: function back() {
303
- go(-1);
304
- },
305
- forward: function forward() {
306
- go(1);
307
- },
308
- listen: function listen(listener) {
309
- return listeners.push(listener);
310
- },
311
- block: function block(blocker) {
312
- var unblock = blockers.push(blocker);
313
-
314
- if (blockers.length === 1) {
315
- window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);
316
- }
317
-
318
- return function () {
319
- unblock(); // Remove the beforeunload listener so the document may
320
- // still be salvageable in the pagehide event.
321
- // See https://html.spec.whatwg.org/#unloading-documents
322
-
323
- if (!blockers.length) {
324
- window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);
325
- }
326
- };
327
- }
328
- };
329
- return history;
330
- }
331
- /**
332
- * Hash history stores the location in window.location.hash. This makes it ideal
333
- * for situations where you don't want to send the location to the server for
334
- * some reason, either because you do cannot configure it or the URL space is
335
- * reserved for something else.
336
- *
337
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
338
- */
339
-
340
- function createHashHistory(options) {
341
- if (options === void 0) {
342
- options = {};
343
- }
344
-
345
- var _options2 = options,
346
- _options2$window = _options2.window,
347
- window = _options2$window === void 0 ? document.defaultView : _options2$window;
348
- var globalHistory = window.history;
349
-
350
- function getIndexAndLocation() {
351
- var _parsePath = parsePath(window.location.hash.substr(1)),
352
- _parsePath$pathname = _parsePath.pathname,
353
- pathname = _parsePath$pathname === void 0 ? '/' : _parsePath$pathname,
354
- _parsePath$search = _parsePath.search,
355
- search = _parsePath$search === void 0 ? '' : _parsePath$search,
356
- _parsePath$hash = _parsePath.hash,
357
- hash = _parsePath$hash === void 0 ? '' : _parsePath$hash;
358
-
359
- var state = globalHistory.state || {};
360
- return [state.idx, readOnly({
361
- pathname: pathname,
362
- search: search,
363
- hash: hash,
364
- state: state.usr || null,
365
- key: state.key || 'default'
366
- })];
367
- }
368
-
369
- var blockedPopTx = null;
370
-
371
- function handlePop() {
372
- if (blockedPopTx) {
373
- blockers.call(blockedPopTx);
374
- blockedPopTx = null;
375
- } else {
376
- var nextAction = Action.Pop;
377
-
378
- var _getIndexAndLocation4 = getIndexAndLocation(),
379
- nextIndex = _getIndexAndLocation4[0],
380
- nextLocation = _getIndexAndLocation4[1];
381
-
382
- if (blockers.length) {
383
- if (nextIndex != null) {
384
- var delta = index - nextIndex;
385
-
386
- if (delta) {
387
- // Revert the POP
388
- blockedPopTx = {
389
- action: nextAction,
390
- location: nextLocation,
391
- retry: function retry() {
392
- go(delta * -1);
393
- }
394
- };
395
- go(delta);
396
- }
397
- } else {
398
- // Trying to POP to a location with no index. We did not create
399
- // this location, so we can't effectively block the navigation.
400
- process.env.NODE_ENV !== "production" ? warning$1(false, // TODO: Write up a doc that explains our blocking strategy in
401
- // detail and link to it here so people can understand better
402
- // what is going on and how to avoid it.
403
- "You are trying to block a POP navigation to a location that was not " + "created by the history library. The block will fail silently in " + "production, but in general you should do all navigation with the " + "history library (instead of using window.history.pushState directly) " + "to avoid this situation.") : void 0;
404
- }
405
- } else {
406
- applyTx(nextAction);
407
- }
408
- }
409
- }
410
-
411
- window.addEventListener(PopStateEventType, handlePop); // popstate does not fire on hashchange in IE 11 and old (trident) Edge
412
- // https://developer.mozilla.org/de/docs/Web/API/Window/popstate_event
413
-
414
- window.addEventListener(HashChangeEventType, function () {
415
- var _getIndexAndLocation5 = getIndexAndLocation(),
416
- nextLocation = _getIndexAndLocation5[1]; // Ignore extraneous hashchange events.
417
-
418
-
419
- if (createPath(nextLocation) !== createPath(location)) {
420
- handlePop();
421
- }
422
- });
423
- var action = Action.Pop;
424
-
425
- var _getIndexAndLocation6 = getIndexAndLocation(),
426
- index = _getIndexAndLocation6[0],
427
- location = _getIndexAndLocation6[1];
428
-
429
- var listeners = createEvents();
430
- var blockers = createEvents();
431
-
432
- if (index == null) {
433
- index = 0;
434
- globalHistory.replaceState(_extends$1({}, globalHistory.state, {
435
- idx: index
436
- }), '');
437
- }
438
-
439
- function getBaseHref() {
440
- var base = document.querySelector('base');
441
- var href = '';
442
-
443
- if (base && base.getAttribute('href')) {
444
- var url = window.location.href;
445
- var hashIndex = url.indexOf('#');
446
- href = hashIndex === -1 ? url : url.slice(0, hashIndex);
447
- }
448
-
449
- return href;
450
- }
451
-
452
- function createHref(to) {
453
- return getBaseHref() + '#' + (typeof to === 'string' ? to : createPath(to));
454
- }
455
-
456
- function getNextLocation(to, state) {
457
- if (state === void 0) {
458
- state = null;
459
- }
460
-
461
- return readOnly(_extends$1({
462
- pathname: location.pathname,
463
- hash: '',
464
- search: ''
465
- }, typeof to === 'string' ? parsePath(to) : to, {
466
- state: state,
467
- key: createKey()
468
- }));
469
- }
470
-
471
- function getHistoryStateAndUrl(nextLocation, index) {
472
- return [{
473
- usr: nextLocation.state,
474
- key: nextLocation.key,
475
- idx: index
476
- }, createHref(nextLocation)];
477
- }
478
-
479
- function allowTx(action, location, retry) {
480
- return !blockers.length || (blockers.call({
481
- action: action,
482
- location: location,
483
- retry: retry
484
- }), false);
485
- }
486
-
487
- function applyTx(nextAction) {
488
- action = nextAction;
489
-
490
- var _getIndexAndLocation7 = getIndexAndLocation();
491
-
492
- index = _getIndexAndLocation7[0];
493
- location = _getIndexAndLocation7[1];
494
- listeners.call({
495
- action: action,
496
- location: location
497
- });
498
- }
499
-
500
- function push(to, state) {
501
- var nextAction = Action.Push;
502
- var nextLocation = getNextLocation(to, state);
503
-
504
- function retry() {
505
- push(to, state);
506
- }
507
-
508
- process.env.NODE_ENV !== "production" ? warning$1(nextLocation.pathname.charAt(0) === '/', "Relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")") : void 0;
509
-
510
- if (allowTx(nextAction, nextLocation, retry)) {
511
- var _getHistoryStateAndUr3 = getHistoryStateAndUrl(nextLocation, index + 1),
512
- historyState = _getHistoryStateAndUr3[0],
513
- url = _getHistoryStateAndUr3[1]; // TODO: Support forced reloading
514
- // try...catch because iOS limits us to 100 pushState calls :/
515
-
516
-
517
- try {
518
- globalHistory.pushState(historyState, '', url);
519
- } catch (error) {
520
- // They are going to lose state here, but there is no real
521
- // way to warn them about it since the page will refresh...
522
- window.location.assign(url);
523
- }
524
-
525
- applyTx(nextAction);
526
- }
527
- }
528
-
529
- function replace(to, state) {
530
- var nextAction = Action.Replace;
531
- var nextLocation = getNextLocation(to, state);
532
-
533
- function retry() {
534
- replace(to, state);
535
- }
536
-
537
- process.env.NODE_ENV !== "production" ? warning$1(nextLocation.pathname.charAt(0) === '/', "Relative pathnames are not supported in hash history.replace(" + JSON.stringify(to) + ")") : void 0;
538
-
539
- if (allowTx(nextAction, nextLocation, retry)) {
540
- var _getHistoryStateAndUr4 = getHistoryStateAndUrl(nextLocation, index),
541
- historyState = _getHistoryStateAndUr4[0],
542
- url = _getHistoryStateAndUr4[1]; // TODO: Support forced reloading
543
-
544
-
545
- globalHistory.replaceState(historyState, '', url);
546
- applyTx(nextAction);
547
- }
548
- }
549
-
550
- function go(delta) {
551
- globalHistory.go(delta);
552
- }
553
-
554
- var history = {
555
- get action() {
556
- return action;
557
- },
558
-
559
- get location() {
560
- return location;
561
- },
562
-
563
- createHref: createHref,
564
- push: push,
565
- replace: replace,
566
- go: go,
567
- back: function back() {
568
- go(-1);
569
- },
570
- forward: function forward() {
571
- go(1);
572
- },
573
- listen: function listen(listener) {
574
- return listeners.push(listener);
575
- },
576
- block: function block(blocker) {
577
- var unblock = blockers.push(blocker);
578
-
579
- if (blockers.length === 1) {
580
- window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);
581
- }
582
-
583
- return function () {
584
- unblock(); // Remove the beforeunload listener so the document may
585
- // still be salvageable in the pagehide event.
586
- // See https://html.spec.whatwg.org/#unloading-documents
587
-
588
- if (!blockers.length) {
589
- window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);
590
- }
591
- };
592
- }
593
- };
594
- return history;
595
- }
596
- /**
597
- * Memory history stores the current location in memory. It is designed for use
598
- * in stateful non-browser environments like tests and React Native.
599
- *
600
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#creatememoryhistory
601
- */
602
-
603
- function createMemoryHistory(options) {
604
- if (options === void 0) {
605
- options = {};
606
- }
607
-
608
- var _options3 = options,
609
- _options3$initialEntr = _options3.initialEntries,
610
- initialEntries = _options3$initialEntr === void 0 ? ['/'] : _options3$initialEntr,
611
- initialIndex = _options3.initialIndex;
612
- var entries = initialEntries.map(function (entry) {
613
- var location = readOnly(_extends$1({
614
- pathname: '/',
615
- search: '',
616
- hash: '',
617
- state: null,
618
- key: createKey()
619
- }, typeof entry === 'string' ? parsePath(entry) : entry));
620
- process.env.NODE_ENV !== "production" ? warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in createMemoryHistory({ initialEntries }) (invalid entry: " + JSON.stringify(entry) + ")") : void 0;
621
- return location;
622
- });
623
- var index = clamp(initialIndex == null ? entries.length - 1 : initialIndex, 0, entries.length - 1);
624
- var action = Action.Pop;
625
- var location = entries[index];
626
- var listeners = createEvents();
627
- var blockers = createEvents();
628
-
629
- function createHref(to) {
630
- return typeof to === 'string' ? to : createPath(to);
631
- }
632
-
633
- function getNextLocation(to, state) {
634
- if (state === void 0) {
635
- state = null;
636
- }
637
-
638
- return readOnly(_extends$1({
639
- pathname: location.pathname,
640
- search: '',
641
- hash: ''
642
- }, typeof to === 'string' ? parsePath(to) : to, {
643
- state: state,
644
- key: createKey()
645
- }));
646
- }
647
-
648
- function allowTx(action, location, retry) {
649
- return !blockers.length || (blockers.call({
650
- action: action,
651
- location: location,
652
- retry: retry
653
- }), false);
654
- }
655
-
656
- function applyTx(nextAction, nextLocation) {
657
- action = nextAction;
658
- location = nextLocation;
659
- listeners.call({
660
- action: action,
661
- location: location
662
- });
663
- }
664
-
665
- function push(to, state) {
666
- var nextAction = Action.Push;
667
- var nextLocation = getNextLocation(to, state);
668
-
669
- function retry() {
670
- push(to, state);
671
- }
672
-
673
- process.env.NODE_ENV !== "production" ? warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in memory history.push(" + JSON.stringify(to) + ")") : void 0;
674
-
675
- if (allowTx(nextAction, nextLocation, retry)) {
676
- index += 1;
677
- entries.splice(index, entries.length, nextLocation);
678
- applyTx(nextAction, nextLocation);
679
- }
680
- }
681
-
682
- function replace(to, state) {
683
- var nextAction = Action.Replace;
684
- var nextLocation = getNextLocation(to, state);
685
-
686
- function retry() {
687
- replace(to, state);
688
- }
689
-
690
- process.env.NODE_ENV !== "production" ? warning$1(location.pathname.charAt(0) === '/', "Relative pathnames are not supported in memory history.replace(" + JSON.stringify(to) + ")") : void 0;
691
-
692
- if (allowTx(nextAction, nextLocation, retry)) {
693
- entries[index] = nextLocation;
694
- applyTx(nextAction, nextLocation);
695
- }
696
- }
697
-
698
- function go(delta) {
699
- var nextIndex = clamp(index + delta, 0, entries.length - 1);
700
- var nextAction = Action.Pop;
701
- var nextLocation = entries[nextIndex];
702
-
703
- function retry() {
704
- go(delta);
705
- }
706
-
707
- if (allowTx(nextAction, nextLocation, retry)) {
708
- index = nextIndex;
709
- applyTx(nextAction, nextLocation);
710
- }
711
- }
712
-
713
- var history = {
714
- get index() {
715
- return index;
716
- },
717
-
718
- get action() {
719
- return action;
720
- },
721
-
722
- get location() {
723
- return location;
724
- },
725
-
726
- createHref: createHref,
727
- push: push,
728
- replace: replace,
729
- go: go,
730
- back: function back() {
731
- go(-1);
732
- },
733
- forward: function forward() {
734
- go(1);
735
- },
736
- listen: function listen(listener) {
737
- return listeners.push(listener);
738
- },
739
- block: function block(blocker) {
740
- return blockers.push(blocker);
741
- }
742
- };
743
- return history;
744
- } ////////////////////////////////////////////////////////////////////////////////
745
- // UTILS
746
- ////////////////////////////////////////////////////////////////////////////////
747
-
748
- function clamp(n, lowerBound, upperBound) {
749
- return Math.min(Math.max(n, lowerBound), upperBound);
750
- }
751
-
752
- function promptBeforeUnload(event) {
753
- // Cancel the event.
754
- event.preventDefault(); // Chrome (and legacy IE) requires returnValue to be set.
755
-
756
- event.returnValue = '';
757
- }
758
-
759
- function createEvents() {
760
- var handlers = [];
761
- return {
762
- get length() {
763
- return handlers.length;
764
- },
765
-
766
- push: function push(fn) {
767
- handlers.push(fn);
768
- return function () {
769
- handlers = handlers.filter(function (handler) {
770
- return handler !== fn;
771
- });
772
- };
773
- },
774
- call: function call(arg) {
775
- handlers.forEach(function (fn) {
776
- return fn && fn(arg);
777
- });
778
- }
779
- };
780
- }
781
-
782
- function createKey() {
783
- return Math.random().toString(36).substr(2, 8);
784
- }
785
- /**
786
- * Creates a string URL path from the given pathname, search, and hash components.
787
- *
788
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createpath
789
- */
790
-
791
-
792
- function createPath(_ref) {
793
- var _ref$pathname = _ref.pathname,
794
- pathname = _ref$pathname === void 0 ? '/' : _ref$pathname,
795
- _ref$search = _ref.search,
796
- search = _ref$search === void 0 ? '' : _ref$search,
797
- _ref$hash = _ref.hash,
798
- hash = _ref$hash === void 0 ? '' : _ref$hash;
799
- if (search && search !== '?') pathname += search.charAt(0) === '?' ? search : '?' + search;
800
- if (hash && hash !== '#') pathname += hash.charAt(0) === '#' ? hash : '#' + hash;
801
- return pathname;
802
- }
803
- /**
804
- * Parses a string URL path into its separate pathname, search, and hash components.
805
- *
806
- * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#parsepath
807
- */
808
-
809
- function parsePath(path) {
810
- var parsedPath = {};
811
-
812
- if (path) {
813
- var hashIndex = path.indexOf('#');
814
-
815
- if (hashIndex >= 0) {
816
- parsedPath.hash = path.substr(hashIndex);
817
- path = path.substr(0, hashIndex);
818
- }
819
-
820
- var searchIndex = path.indexOf('?');
821
-
822
- if (searchIndex >= 0) {
823
- parsedPath.search = path.substr(searchIndex);
824
- path = path.substr(0, searchIndex);
825
- }
826
-
827
- if (path) {
828
- parsedPath.pathname = path;
829
- }
830
- }
831
-
832
- return parsedPath;
833
- }
834
-
835
- var isProduction = process.env.NODE_ENV === 'production';
836
- var prefix = 'Invariant failed';
837
- function invariant(condition, message) {
838
- if (condition) {
839
- return;
840
- }
841
- if (isProduction) {
842
- throw new Error(prefix);
843
- }
844
- var provided = typeof message === 'function' ? message() : message;
845
- var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix;
846
- throw new Error(value);
847
- }
848
-
849
- // type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
850
- // k: infer I,
851
- // ) => any
852
- // ? I
853
- // : never
854
-
855
- /**
856
- * This function returns `a` if `b` is deeply equal.
857
- * If not, it will replace any deeply equal children of `b` with those of `a`.
858
- * This can be used for structural sharing between JSON values for example.
859
- */
860
- function replaceEqualDeep(prev, next) {
861
- if (prev === next) {
862
- return prev;
863
- }
864
-
865
- const array = Array.isArray(prev) && Array.isArray(next);
866
-
867
- if (array || isPlainObject(prev) && isPlainObject(next)) {
868
- const aSize = array ? prev.length : Object.keys(prev).length;
869
- const bItems = array ? next : Object.keys(next);
870
- const bSize = bItems.length;
871
- const copy = array ? [] : {};
872
- let equalItems = 0;
873
-
874
- for (let i = 0; i < bSize; i++) {
875
- const key = array ? i : bItems[i];
876
- copy[key] = replaceEqualDeep(prev[key], next[key]);
877
-
878
- if (copy[key] === prev[key]) {
879
- equalItems++;
880
- }
881
- }
882
-
883
- return aSize === bSize && equalItems === aSize ? prev : copy;
884
- }
885
-
886
- return next;
887
- } // Copied from: https://github.com/jonschlinkert/is-plain-object
888
-
889
- function isPlainObject(o) {
890
- if (!hasObjectPrototype(o)) {
891
- return false;
892
- } // If has modified constructor
893
-
894
-
895
- const ctor = o.constructor;
896
-
897
- if (typeof ctor === 'undefined') {
898
- return true;
899
- } // If has modified prototype
900
-
901
-
902
- const prot = ctor.prototype;
903
-
904
- if (!hasObjectPrototype(prot)) {
905
- return false;
906
- } // If constructor does not have an Object-specific method
907
-
908
-
909
- if (!prot.hasOwnProperty('isPrototypeOf')) {
910
- return false;
911
- } // Most likely a plain Object
912
-
913
-
914
- return true;
915
- }
916
-
917
- function hasObjectPrototype(o) {
918
- return Object.prototype.toString.call(o) === '[object Object]';
919
- }
920
-
921
- function last(arr) {
922
- return arr[arr.length - 1];
923
- }
924
- function warning(cond, message) {
925
- if (cond) {
926
- if (typeof console !== 'undefined') console.warn(message);
927
-
928
- try {
929
- throw new Error(message);
930
- } catch (_unused) {}
931
- }
932
-
933
- return true;
934
- }
935
-
936
- function isFunction(d) {
937
- return typeof d === 'function';
938
- }
939
-
940
- function functionalUpdate(updater, previous) {
941
- if (isFunction(updater)) {
942
- return updater(previous);
943
- }
944
-
945
- return updater;
946
- }
947
- function pick(parent, keys) {
948
- return keys.reduce((obj, key) => {
949
- obj[key] = parent[key];
950
- return obj;
951
- }, {});
952
- }
953
-
954
- function joinPaths(paths) {
955
- return cleanPath(paths.filter(Boolean).join('/'));
956
- }
957
- function cleanPath(path) {
958
- // remove double slashes
959
- return path.replace(/\/{2,}/g, '/');
960
- }
961
- function trimPathLeft(path) {
962
- return path === '/' ? path : path.replace(/^\/{1,}/, '');
963
- }
964
- function trimPathRight(path) {
965
- return path === '/' ? path : path.replace(/\/{1,}$/, '');
966
- }
967
- function trimPath(path) {
968
- return trimPathRight(trimPathLeft(path));
969
- }
970
- function resolvePath(basepath, base, to) {
971
- base = base.replace(new RegExp("^" + basepath), '/');
972
- to = to.replace(new RegExp("^" + basepath), '/');
973
- let baseSegments = parsePathname(base);
974
- const toSegments = parsePathname(to);
975
- toSegments.forEach((toSegment, index) => {
976
- if (toSegment.value === '/') {
977
- if (!index) {
978
- // Leading slash
979
- baseSegments = [toSegment];
980
- } else if (index === toSegments.length - 1) {
981
- // Trailing Slash
982
- baseSegments.push(toSegment);
983
- } else ;
984
- } else if (toSegment.value === '..') {
985
- var _last;
986
-
987
- // Extra trailing slash? pop it off
988
- if (baseSegments.length > 1 && ((_last = last(baseSegments)) == null ? void 0 : _last.value) === '/') {
989
- baseSegments.pop();
990
- }
991
-
992
- baseSegments.pop();
993
- } else if (toSegment.value === '.') {
994
- return;
995
- } else {
996
- baseSegments.push(toSegment);
997
- }
998
- });
999
- const joined = joinPaths([basepath, ...baseSegments.map(d => d.value)]);
1000
- return cleanPath(joined);
1001
- }
1002
- function parsePathname(pathname) {
1003
- if (!pathname) {
1004
- return [];
1005
- }
1006
-
1007
- pathname = cleanPath(pathname);
1008
- const segments = [];
1009
-
1010
- if (pathname.slice(0, 1) === '/') {
1011
- pathname = pathname.substring(1);
1012
- segments.push({
1013
- type: 'pathname',
1014
- value: '/'
1015
- });
1016
- }
1017
-
1018
- if (!pathname) {
1019
- return segments;
1020
- } // Remove empty segments and '.' segments
1021
-
1022
-
1023
- const split = pathname.split('/').filter(Boolean);
1024
- segments.push(...split.map(part => {
1025
- if (part.startsWith('*')) {
1026
- return {
1027
- type: 'wildcard',
1028
- value: part
1029
- };
1030
- }
1031
-
1032
- if (part.charAt(0) === ':') {
1033
- return {
1034
- type: 'param',
1035
- value: part
1036
- };
1037
- }
1038
-
1039
- return {
1040
- type: 'pathname',
1041
- value: part
1042
- };
1043
- }));
1044
-
1045
- if (pathname.slice(-1) === '/') {
1046
- pathname = pathname.substring(1);
1047
- segments.push({
1048
- type: 'pathname',
1049
- value: '/'
1050
- });
1051
- }
1052
-
1053
- return segments;
1054
- }
1055
- function interpolatePath(path, params, leaveWildcard) {
1056
- const interpolatedPathSegments = parsePathname(path);
1057
- return joinPaths(interpolatedPathSegments.map(segment => {
1058
- if (segment.value === '*' && !leaveWildcard) {
1059
- return '';
1060
- }
1061
-
1062
- if (segment.type === 'param') {
1063
- var _segment$value$substr;
1064
-
1065
- return (_segment$value$substr = params[segment.value.substring(1)]) != null ? _segment$value$substr : '';
1066
- }
1067
-
1068
- return segment.value;
1069
- }));
1070
- }
1071
- function matchPathname(currentPathname, matchLocation) {
1072
- const pathParams = matchByPath(currentPathname, matchLocation); // const searchMatched = matchBySearch(currentLocation.search, matchLocation)
1073
-
1074
- if (matchLocation.to && !pathParams) {
1075
- return;
1076
- } // if (matchLocation.search && !searchMatched) {
1077
- // return
1078
- // }
1079
-
1080
-
1081
- return pathParams != null ? pathParams : {};
1082
- }
1083
- function matchByPath(from, matchLocation) {
1084
- var _matchLocation$to;
1085
-
1086
- const baseSegments = parsePathname(from);
1087
- const routeSegments = parsePathname("" + ((_matchLocation$to = matchLocation.to) != null ? _matchLocation$to : '*'));
1088
- const params = {};
1089
-
1090
- let isMatch = (() => {
1091
- for (let i = 0; i < Math.max(baseSegments.length, routeSegments.length); i++) {
1092
- const baseSegment = baseSegments[i];
1093
- const routeSegment = routeSegments[i];
1094
- const isLastRouteSegment = i === routeSegments.length - 1;
1095
- const isLastBaseSegment = i === baseSegments.length - 1;
1096
-
1097
- if (routeSegment) {
1098
- if (routeSegment.type === 'wildcard') {
1099
- if (baseSegment != null && baseSegment.value) {
1100
- params['*'] = joinPaths(baseSegments.slice(i).map(d => d.value));
1101
- return true;
1102
- }
1103
-
1104
- return false;
1105
- }
1106
-
1107
- if (routeSegment.type === 'pathname') {
1108
- if (routeSegment.value === '/' && !(baseSegment != null && baseSegment.value)) {
1109
- return true;
1110
- }
1111
-
1112
- if (baseSegment) {
1113
- if (matchLocation.caseSensitive) {
1114
- if (routeSegment.value !== baseSegment.value) {
1115
- return false;
1116
- }
1117
- } else if (routeSegment.value.toLowerCase() !== baseSegment.value.toLowerCase()) {
1118
- return false;
1119
- }
1120
- }
1121
- }
1122
-
1123
- if (!baseSegment) {
1124
- return false;
1125
- }
1126
-
1127
- if (routeSegment.type === 'param') {
1128
- if ((baseSegment == null ? void 0 : baseSegment.value) === '/') {
1129
- return false;
1130
- }
1131
-
1132
- if (!baseSegment.value.startsWith(':')) {
1133
- params[routeSegment.value.substring(1)] = baseSegment.value;
1134
- }
1135
- }
1136
- }
1137
-
1138
- if (isLastRouteSegment && !isLastBaseSegment) {
1139
- return !!matchLocation.fuzzy;
1140
- }
1141
- }
1142
-
1143
- return true;
1144
- })();
1145
-
1146
- return isMatch ? params : undefined;
1147
- }
1148
-
1149
- // @ts-nocheck
1150
- // qss has been slightly modified and inlined here for our use cases (and compression's sake). We've included it as a hard dependency for MIT license attribution.
1151
- function encode(obj, pfx) {
1152
- var k,
1153
- i,
1154
- tmp,
1155
- str = '';
1156
-
1157
- for (k in obj) {
1158
- if ((tmp = obj[k]) !== void 0) {
1159
- if (Array.isArray(tmp)) {
1160
- for (i = 0; i < tmp.length; i++) {
1161
- str && (str += '&');
1162
- str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp[i]);
1163
- }
1164
- } else {
1165
- str && (str += '&');
1166
- str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp);
1167
- }
1168
- }
1169
- }
1170
-
1171
- return (pfx || '') + str;
1172
- }
1173
-
1174
- function toValue(mix) {
1175
- if (!mix) return '';
1176
- var str = decodeURIComponent(mix);
1177
- if (str === 'false') return false;
1178
- if (str === 'true') return true;
1179
- if (str.charAt(0) === '0') return str;
1180
- return +str * 0 === 0 ? +str : str;
1181
- }
1182
-
1183
- function decode(str) {
1184
- var tmp,
1185
- k,
1186
- out = {},
1187
- arr = str.split('&');
1188
-
1189
- while (tmp = arr.shift()) {
1190
- tmp = tmp.split('=');
1191
- k = tmp.shift();
1192
-
1193
- if (out[k] !== void 0) {
1194
- out[k] = [].concat(out[k], toValue(tmp.shift()));
1195
- } else {
1196
- out[k] = toValue(tmp.shift());
1197
- }
1198
- }
1199
-
1200
- return out;
1201
- }
1202
-
1203
- function _extends() {
1204
- _extends = Object.assign ? Object.assign.bind() : function (target) {
1205
- for (var i = 1; i < arguments.length; i++) {
1206
- var source = arguments[i];
1207
-
1208
- for (var key in source) {
1209
- if (Object.prototype.hasOwnProperty.call(source, key)) {
1210
- target[key] = source[key];
1211
- }
1212
- }
1213
- }
1214
-
1215
- return target;
1216
- };
1217
- return _extends.apply(this, arguments);
1218
- }
1219
-
1220
- function createRoute(routeConfig, options, parent, router) {
1221
- const {
1222
- id,
1223
- routeId,
1224
- path: routePath,
1225
- fullPath
1226
- } = routeConfig;
1227
-
1228
- const action = router.state.actions[id] || (() => {
1229
- router.state.actions[id] = {
1230
- pending: [],
1231
- submit: async (submission, actionOpts) => {
1232
- var _actionOpts$invalidat;
1233
-
1234
- if (!route) {
1235
- return;
1236
- }
1237
-
1238
- const invalidate = (_actionOpts$invalidat = actionOpts == null ? void 0 : actionOpts.invalidate) != null ? _actionOpts$invalidat : true;
1239
- const actionState = {
1240
- submittedAt: Date.now(),
1241
- status: 'pending',
1242
- submission
1243
- };
1244
- action.current = actionState;
1245
- action.latest = actionState;
1246
- action.pending.push(actionState);
1247
- router.state = _extends({}, router.state, {
1248
- currentAction: actionState,
1249
- latestAction: actionState
1250
- });
1251
- router.notify();
1252
-
1253
- try {
1254
- const res = await (route.options.action == null ? void 0 : route.options.action(submission));
1255
- actionState.data = res;
1256
-
1257
- if (invalidate) {
1258
- router.invalidateRoute({
1259
- to: '.',
1260
- fromCurrent: true
1261
- });
1262
- await router.reload();
1263
- }
1264
-
1265
- actionState.status = 'success';
1266
- return res;
1267
- } catch (err) {
1268
- console.error(err);
1269
- actionState.error = err;
1270
- actionState.status = 'error';
1271
- } finally {
1272
- action.pending = action.pending.filter(d => d !== actionState);
1273
- router.removeActionQueue.push({
1274
- action,
1275
- actionState
1276
- });
1277
- router.notify();
1278
- }
1279
- }
1280
- };
1281
- return router.state.actions[id];
1282
- })();
1283
-
1284
- const loader = router.state.loaders[id] || (() => {
1285
- router.state.loaders[id] = {
1286
- pending: [],
1287
- fetch: async loaderContext => {
1288
- if (!route) {
1289
- return;
1290
- }
1291
-
1292
- const loaderState = {
1293
- loadedAt: Date.now(),
1294
- loaderContext
1295
- };
1296
- loader.current = loaderState;
1297
- loader.latest = loaderState;
1298
- loader.pending.push(loaderState); // router.state = {
1299
- // ...router.state,
1300
- // currentAction: loaderState,
1301
- // latestAction: loaderState,
1302
- // }
1303
-
1304
- router.notify();
1305
-
1306
- try {
1307
- return await (route.options.loader == null ? void 0 : route.options.loader(loaderContext));
1308
- } finally {
1309
- loader.pending = loader.pending.filter(d => d !== loaderState); // router.removeActionQueue.push({ loader, loaderState })
1310
-
1311
- router.notify();
1312
- }
1313
- }
1314
- };
1315
- return router.state.loaders[id];
1316
- })();
1317
-
1318
- let route = {
1319
- routeId: id,
1320
- routeRouteId: routeId,
1321
- routePath,
1322
- fullPath,
1323
- options,
1324
- router,
1325
- childRoutes: undefined,
1326
- parentRoute: parent,
1327
- action,
1328
- loader: loader,
1329
- buildLink: options => {
1330
- return router.buildLink(_extends({}, options, {
1331
- from: fullPath
1332
- }));
1333
- },
1334
- navigate: options => {
1335
- return router.navigate(_extends({}, options, {
1336
- from: fullPath
1337
- }));
1338
- },
1339
- matchRoute: (matchLocation, opts) => {
1340
- return router.matchRoute(_extends({}, matchLocation, {
1341
- from: fullPath
1342
- }), opts);
1343
- }
1344
- };
1345
- router.options.createRoute == null ? void 0 : router.options.createRoute({
1346
- router,
1347
- route
1348
- });
1349
- return route;
1350
- }
1351
- function cascadeLoaderData(matches) {
1352
- matches.forEach((match, index) => {
1353
- const parent = matches[index - 1];
1354
-
1355
- if (parent) {
1356
- match.loaderData = replaceEqualDeep(match.loaderData, _extends({}, parent.loaderData, match.routeLoaderData));
1357
- }
1358
- });
1359
- }
1360
-
1361
- const rootRouteId = '__root__';
1362
- const createRouteConfig = function createRouteConfig(options, children, isRoot, parentId, parentPath) {
1363
- if (options === void 0) {
1364
- options = {};
1365
- }
1366
-
1367
- if (isRoot === void 0) {
1368
- isRoot = true;
1369
- }
1370
-
1371
- if (isRoot) {
1372
- options.path = rootRouteId;
1373
- } // Strip the root from parentIds
1374
-
1375
-
1376
- if (parentId === rootRouteId) {
1377
- parentId = '';
1378
- }
1379
-
1380
- let path = isRoot ? rootRouteId : options.path; // If the path is anything other than an index path, trim it up
1381
-
1382
- if (path && path !== '/') {
1383
- path = trimPath(path);
1384
- }
1385
-
1386
- const routeId = path || options.id;
1387
- let id = joinPaths([parentId, routeId]);
1388
-
1389
- if (path === rootRouteId) {
1390
- path = '/';
1391
- }
1392
-
1393
- if (id !== rootRouteId) {
1394
- id = joinPaths(['/', id]);
1395
- }
1396
-
1397
- const fullPath = id === rootRouteId ? '/' : trimPathRight(joinPaths([parentPath, path]));
1398
- return {
1399
- id: id,
1400
- routeId: routeId,
1401
- path: path,
1402
- fullPath: fullPath,
1403
- options: options,
1404
- children,
1405
- createChildren: cb => createRouteConfig(options, cb(childOptions => createRouteConfig(childOptions, undefined, false, id, fullPath)), false, parentId, parentPath),
1406
- addChildren: children => createRouteConfig(options, children, false, parentId, parentPath),
1407
- createRoute: childOptions => createRouteConfig(childOptions, undefined, false, id, fullPath)
1408
- };
1409
- };
1410
-
1411
- const elementTypes = ['element', 'errorElement', 'catchElement', 'pendingElement'];
1412
- function createRouteMatch(router, route, opts) {
1413
- const routeMatch = _extends({}, route, opts, {
1414
- router,
1415
- routeSearch: {},
1416
- search: {},
1417
- childMatches: [],
1418
- status: 'idle',
1419
- routeLoaderData: {},
1420
- loaderData: {},
1421
- isPending: false,
1422
- isFetching: false,
1423
- isInvalid: false,
1424
- invalidAt: Infinity,
1425
- getIsInvalid: () => {
1426
- const now = Date.now();
1427
- return routeMatch.isInvalid || routeMatch.invalidAt < now;
1428
- },
1429
- __: {
1430
- abortController: new AbortController(),
1431
- latestId: '',
1432
- resolve: () => {},
1433
- notify: () => {
1434
- routeMatch.__.resolve();
1435
-
1436
- routeMatch.router.notify();
1437
- },
1438
- startPending: () => {
1439
- var _routeMatch$options$p, _routeMatch$options$p2;
1440
-
1441
- const pendingMs = (_routeMatch$options$p = routeMatch.options.pendingMs) != null ? _routeMatch$options$p : router.options.defaultPendingMs;
1442
- const pendingMinMs = (_routeMatch$options$p2 = routeMatch.options.pendingMinMs) != null ? _routeMatch$options$p2 : router.options.defaultPendingMinMs;
1443
-
1444
- if (routeMatch.__.pendingTimeout || routeMatch.status !== 'loading' || typeof pendingMs === 'undefined') {
1445
- return;
1446
- }
1447
-
1448
- routeMatch.__.pendingTimeout = setTimeout(() => {
1449
- routeMatch.isPending = true;
1450
-
1451
- routeMatch.__.resolve();
1452
-
1453
- if (typeof pendingMinMs !== 'undefined') {
1454
- routeMatch.__.pendingMinPromise = new Promise(r => routeMatch.__.pendingMinTimeout = setTimeout(r, pendingMinMs));
1455
- }
1456
- }, pendingMs);
1457
- },
1458
- cancelPending: () => {
1459
- routeMatch.isPending = false;
1460
- clearTimeout(routeMatch.__.pendingTimeout);
1461
- clearTimeout(routeMatch.__.pendingMinTimeout);
1462
- delete routeMatch.__.pendingMinPromise;
1463
- },
1464
- // setParentMatch: (parentMatch?: RouteMatch) => {
1465
- // routeMatch.parentMatch = parentMatch
1466
- // },
1467
- // addChildMatch: (childMatch: RouteMatch) => {
1468
- // if (
1469
- // routeMatch.childMatches.find((d) => d.matchId === childMatch.matchId)
1470
- // ) {
1471
- // return
1472
- // }
1473
- // routeMatch.childMatches.push(childMatch)
1474
- // },
1475
- validate: () => {
1476
- var _routeMatch$parentMat, _routeMatch$parentMat2;
1477
-
1478
- // Validate the search params and stabilize them
1479
- const parentSearch = (_routeMatch$parentMat = (_routeMatch$parentMat2 = routeMatch.parentMatch) == null ? void 0 : _routeMatch$parentMat2.search) != null ? _routeMatch$parentMat : router.location.search;
1480
-
1481
- try {
1482
- const prevSearch = routeMatch.routeSearch;
1483
- const validator = typeof routeMatch.options.validateSearch === 'object' ? routeMatch.options.validateSearch.parse : routeMatch.options.validateSearch;
1484
- let nextSearch = replaceEqualDeep(prevSearch, validator == null ? void 0 : validator(parentSearch)); // Invalidate route matches when search param stability changes
1485
-
1486
- if (prevSearch !== nextSearch) {
1487
- routeMatch.isInvalid = true;
1488
- }
1489
-
1490
- routeMatch.routeSearch = nextSearch;
1491
- routeMatch.search = replaceEqualDeep(parentSearch, _extends({}, parentSearch, nextSearch));
1492
- } catch (err) {
1493
- console.error(err);
1494
- const error = new Error('Invalid search params found', {
1495
- cause: err
1496
- });
1497
- error.code = 'INVALID_SEARCH_PARAMS';
1498
- routeMatch.status = 'error';
1499
- routeMatch.error = error; // Do not proceed with loading the route
1500
-
1501
- return;
1502
- }
1503
- }
1504
- },
1505
- cancel: () => {
1506
- var _routeMatch$__$abortC;
1507
-
1508
- (_routeMatch$__$abortC = routeMatch.__.abortController) == null ? void 0 : _routeMatch$__$abortC.abort();
1509
-
1510
- routeMatch.__.cancelPending();
1511
- },
1512
- invalidate: () => {
1513
- routeMatch.isInvalid = true;
1514
- },
1515
- hasLoaders: () => {
1516
- return !!(route.options.loader || elementTypes.some(d => typeof route.options[d] === 'function'));
1517
- },
1518
- load: async loaderOpts => {
1519
- const now = Date.now();
1520
- const minMaxAge = loaderOpts != null && loaderOpts.preload ? Math.max(loaderOpts == null ? void 0 : loaderOpts.maxAge, loaderOpts == null ? void 0 : loaderOpts.gcMaxAge) : 0; // If this is a preload, add it to the preload cache
1521
-
1522
- if (loaderOpts != null && loaderOpts.preload && minMaxAge > 0) {
1523
- // If the match is currently active, don't preload it
1524
- if (router.state.matches.find(d => d.matchId === routeMatch.matchId)) {
1525
- return;
1526
- }
1527
-
1528
- router.matchCache[routeMatch.matchId] = {
1529
- gc: now + loaderOpts.gcMaxAge,
1530
- match: routeMatch
1531
- };
1532
- } // If the match is invalid, errored or idle, trigger it to load
1533
-
1534
-
1535
- if (routeMatch.status === 'success' && routeMatch.getIsInvalid() || routeMatch.status === 'error' || routeMatch.status === 'idle') {
1536
- const maxAge = loaderOpts != null && loaderOpts.preload ? loaderOpts == null ? void 0 : loaderOpts.maxAge : undefined;
1537
- routeMatch.fetch({
1538
- maxAge
1539
- });
1540
- }
1541
- },
1542
- fetch: async opts => {
1543
- const id = '' + Date.now() + Math.random();
1544
- routeMatch.__.latestId = id; // If the match was in an error state, set it
1545
- // to a loading state again. Otherwise, keep it
1546
- // as loading or resolved
1547
-
1548
- if (routeMatch.status === 'idle') {
1549
- routeMatch.status = 'loading';
1550
- } // We started loading the route, so it's no longer invalid
1551
-
1552
-
1553
- routeMatch.isInvalid = false;
1554
- routeMatch.__.loadPromise = new Promise(async resolve => {
1555
- // We are now fetching, even if it's in the background of a
1556
- // resolved state
1557
- routeMatch.isFetching = true;
1558
- routeMatch.__.resolve = resolve;
1559
-
1560
- const loaderPromise = (async () => {
1561
- // Load the elements and data in parallel
1562
- routeMatch.__.elementsPromise = (async () => {
1563
- // then run all element and data loaders in parallel
1564
- // For each element type, potentially load it asynchronously
1565
- await Promise.all(elementTypes.map(async type => {
1566
- const routeElement = routeMatch.options[type];
1567
-
1568
- if (routeMatch.__[type]) {
1569
- return;
1570
- }
1571
-
1572
- routeMatch.__[type] = await router.options.createElement(routeElement);
1573
- }));
1574
- })();
1575
-
1576
- routeMatch.__.dataPromise = Promise.resolve().then(async () => {
1577
- try {
1578
- var _ref, _ref2, _opts$maxAge;
1579
-
1580
- if (routeMatch.options.loader) {
1581
- const data = await routeMatch.options.loader({
1582
- params: routeMatch.params,
1583
- search: routeMatch.routeSearch,
1584
- signal: routeMatch.__.abortController.signal
1585
- });
1586
-
1587
- if (id !== routeMatch.__.latestId) {
1588
- return routeMatch.__.loaderPromise;
1589
- }
1590
-
1591
- routeMatch.routeLoaderData = replaceEqualDeep(routeMatch.routeLoaderData, data);
1592
- }
1593
-
1594
- routeMatch.error = undefined;
1595
- routeMatch.status = 'success';
1596
- routeMatch.updatedAt = Date.now();
1597
- routeMatch.invalidAt = routeMatch.updatedAt + ((_ref = (_ref2 = (_opts$maxAge = opts == null ? void 0 : opts.maxAge) != null ? _opts$maxAge : routeMatch.options.loaderMaxAge) != null ? _ref2 : router.options.defaultLoaderMaxAge) != null ? _ref : 0);
1598
- } catch (err) {
1599
- if (id !== routeMatch.__.latestId) {
1600
- return routeMatch.__.loaderPromise;
1601
- }
1602
-
1603
- if (process.env.NODE_ENV !== 'production') {
1604
- console.error(err);
1605
- }
1606
-
1607
- routeMatch.error = err;
1608
- routeMatch.status = 'error';
1609
- routeMatch.updatedAt = Date.now();
1610
- }
1611
- });
1612
-
1613
- try {
1614
- await Promise.all([routeMatch.__.elementsPromise, routeMatch.__.dataPromise]);
1615
-
1616
- if (id !== routeMatch.__.latestId) {
1617
- return routeMatch.__.loaderPromise;
1618
- }
1619
-
1620
- if (routeMatch.__.pendingMinPromise) {
1621
- await routeMatch.__.pendingMinPromise;
1622
- delete routeMatch.__.pendingMinPromise;
1623
- }
1624
- } finally {
1625
- if (id !== routeMatch.__.latestId) {
1626
- return routeMatch.__.loaderPromise;
1627
- }
1628
-
1629
- routeMatch.__.cancelPending();
1630
-
1631
- routeMatch.isPending = false;
1632
- routeMatch.isFetching = false;
1633
-
1634
- routeMatch.__.notify();
1635
- }
1636
- })();
1637
-
1638
- routeMatch.__.loaderPromise = loaderPromise;
1639
- await loaderPromise;
1640
-
1641
- if (id !== routeMatch.__.latestId) {
1642
- return routeMatch.__.loaderPromise;
1643
- }
1644
-
1645
- delete routeMatch.__.loaderPromise;
1646
- });
1647
- return await routeMatch.__.loadPromise;
1648
- }
1649
- });
1650
-
1651
- if (!routeMatch.hasLoaders()) {
1652
- routeMatch.status = 'success';
1653
- }
1654
-
1655
- return routeMatch;
1656
- }
1657
-
1658
- const defaultParseSearch = parseSearchWith(JSON.parse);
1659
- const defaultStringifySearch = stringifySearchWith(JSON.stringify);
1660
- function parseSearchWith(parser) {
1661
- return searchStr => {
1662
- if (searchStr.substring(0, 1) === '?') {
1663
- searchStr = searchStr.substring(1);
1664
- }
1665
-
1666
- let query = decode(searchStr); // Try to parse any query params that might be json
1667
-
1668
- for (let key in query) {
1669
- const value = query[key];
1670
-
1671
- if (typeof value === 'string') {
1672
- try {
1673
- query[key] = parser(value);
1674
- } catch (err) {//
1675
- }
1676
- }
1677
- }
1678
-
1679
- return query;
1680
- };
1681
- }
1682
- function stringifySearchWith(stringify) {
1683
- return search => {
1684
- search = _extends({}, search);
1685
-
1686
- if (search) {
1687
- Object.keys(search).forEach(key => {
1688
- const val = search[key];
1689
-
1690
- if (typeof val === 'undefined' || val === undefined) {
1691
- delete search[key];
1692
- } else if (val && typeof val === 'object' && val !== null) {
1693
- try {
1694
- search[key] = stringify(val);
1695
- } catch (err) {// silent
1696
- }
1697
- }
1698
- });
1699
- }
1700
-
1701
- const searchStr = encode(search).toString();
1702
- return searchStr ? "?" + searchStr : '';
1703
- };
1704
- }
1705
-
1706
- var _window$document;
1707
- // Detect if we're in the DOM
1708
- const isServer = typeof window === 'undefined' || !((_window$document = window.document) != null && _window$document.createElement); // This is the default history object if none is defined
1709
-
1710
- const createDefaultHistory = () => isServer ? createMemoryHistory() : createBrowserHistory();
1711
-
1712
- function createRouter(userOptions) {
1713
- var _userOptions$stringif, _userOptions$parseSea;
1714
-
1715
- const history = (userOptions == null ? void 0 : userOptions.history) || createDefaultHistory();
1716
-
1717
- const originalOptions = _extends({
1718
- defaultLoaderGcMaxAge: 5 * 60 * 1000,
1719
- defaultLoaderMaxAge: 0,
1720
- defaultPreloadMaxAge: 2000,
1721
- defaultPreloadDelay: 50
1722
- }, userOptions, {
1723
- stringifySearch: (_userOptions$stringif = userOptions == null ? void 0 : userOptions.stringifySearch) != null ? _userOptions$stringif : defaultStringifySearch,
1724
- parseSearch: (_userOptions$parseSea = userOptions == null ? void 0 : userOptions.parseSearch) != null ? _userOptions$parseSea : defaultParseSearch
1725
- });
1726
-
1727
- let router = {
1728
- history,
1729
- options: originalOptions,
1730
- listeners: [],
1731
- removeActionQueue: [],
1732
- // Resolved after construction
1733
- basepath: '',
1734
- routeTree: undefined,
1735
- routesById: {},
1736
- location: undefined,
1737
- allRouteInfo: undefined,
1738
- //
1739
- navigationPromise: Promise.resolve(),
1740
- resolveNavigation: () => {},
1741
- matchCache: {},
1742
- state: {
1743
- status: 'idle',
1744
- location: null,
1745
- matches: [],
1746
- actions: {},
1747
- loaders: {},
1748
- lastUpdated: Date.now(),
1749
- isFetching: false,
1750
- isPreloading: false
1751
- },
1752
- startedLoadingAt: Date.now(),
1753
- subscribe: listener => {
1754
- router.listeners.push(listener);
1755
- return () => {
1756
- router.listeners = router.listeners.filter(x => x !== listener);
1757
- };
1758
- },
1759
- getRoute: id => {
1760
- return router.routesById[id];
1761
- },
1762
- notify: () => {
1763
- router.state = _extends({}, router.state, {
1764
- isFetching: router.state.status === 'loading' || router.state.matches.some(d => d.isFetching),
1765
- isPreloading: Object.values(router.matchCache).some(d => d.match.isFetching && !router.state.matches.find(dd => dd.matchId === d.match.matchId))
1766
- });
1767
- cascadeLoaderData(router.state.matches);
1768
- router.listeners.forEach(listener => listener(router));
1769
- },
1770
- dehydrateState: () => {
1771
- return _extends({}, pick(router.state, ['status', 'location', 'lastUpdated']), {
1772
- matches: router.state.matches.map(match => pick(match, ['matchId', 'status', 'routeLoaderData', 'loaderData', 'isInvalid', 'invalidAt']))
1773
- });
1774
- },
1775
- hydrateState: dehydratedState => {
1776
- // Match the routes
1777
- const matches = router.matchRoutes(router.location.pathname, {
1778
- strictParseParams: true
1779
- });
1780
- router.state = _extends({}, router.state, dehydratedState, {
1781
- matches: matches.map(match => {
1782
- const dehydratedMatch = dehydratedState.matches.find(d => d.matchId === match.matchId);
1783
- invariant(dehydratedMatch, 'Oh no! Dehydrated route matches did not match the active state of the router 😬');
1784
- Object.assign(match, dehydratedMatch);
1785
- return match;
1786
- })
1787
- });
1788
- },
1789
- mount: () => {
1790
- const next = router.__.buildLocation({
1791
- to: '.',
1792
- search: true,
1793
- hash: true
1794
- }); // If the current location isn't updated, trigger a navigation
1795
- // to the current location. Otherwise, load the current location.
1796
-
1797
-
1798
- if (next.href !== router.location.href) {
1799
- router.__.commitLocation(next, true);
1800
- }
1801
-
1802
- router.loadLocation();
1803
- const unsub = router.history.listen(event => {
1804
- console.log(event.location);
1805
- router.loadLocation(router.__.parseLocation(event.location, router.location));
1806
- }); // addEventListener does not exist in React Native, but window does
1807
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1808
-
1809
- if (!isServer && window.addEventListener) {
1810
- // Listen to visibillitychange and focus
1811
- window.addEventListener('visibilitychange', router.onFocus, false);
1812
- window.addEventListener('focus', router.onFocus, false);
1813
- }
1814
-
1815
- return () => {
1816
- unsub(); // Be sure to unsubscribe if a new handler is set
1817
-
1818
- window.removeEventListener('visibilitychange', router.onFocus);
1819
- window.removeEventListener('focus', router.onFocus);
1820
- };
1821
- },
1822
- onFocus: () => {
1823
- router.loadLocation();
1824
- },
1825
- update: opts => {
1826
- const newHistory = (opts == null ? void 0 : opts.history) !== router.history;
1827
-
1828
- if (!router.location || newHistory) {
1829
- if (opts != null && opts.history) {
1830
- router.history = opts.history;
1831
- }
1832
-
1833
- router.location = router.__.parseLocation(router.history.location);
1834
- router.state.location = router.location;
1835
- }
1836
-
1837
- Object.assign(router.options, opts);
1838
- const {
1839
- basepath,
1840
- routeConfig
1841
- } = router.options;
1842
- router.basepath = cleanPath("/" + (basepath != null ? basepath : ''));
1843
-
1844
- if (routeConfig) {
1845
- router.routesById = {};
1846
- router.routeTree = router.__.buildRouteTree(routeConfig);
1847
- }
1848
-
1849
- return router;
1850
- },
1851
- cancelMatches: () => {
1852
- var _router$state$pending, _router$state$pending2;
1853
- [...router.state.matches, ...((_router$state$pending = (_router$state$pending2 = router.state.pending) == null ? void 0 : _router$state$pending2.matches) != null ? _router$state$pending : [])].forEach(match => {
1854
- match.cancel();
1855
- });
1856
- },
1857
- loadLocation: async next => {
1858
- const id = Math.random();
1859
- router.startedLoadingAt = id;
1860
-
1861
- if (next) {
1862
- // Ingest the new location
1863
- router.location = next;
1864
- } // Clear out old actions
1865
-
1866
-
1867
- router.removeActionQueue.forEach(_ref => {
1868
- let {
1869
- action,
1870
- actionState
1871
- } = _ref;
1872
-
1873
- if (router.state.currentAction === actionState) {
1874
- router.state.currentAction = undefined;
1875
- }
1876
-
1877
- if (action.current === actionState) {
1878
- action.current = undefined;
1879
- }
1880
- });
1881
- router.removeActionQueue = []; // Cancel any pending matches
1882
-
1883
- router.cancelMatches(); // Match the routes
1884
-
1885
- const matches = router.matchRoutes(router.location.pathname, {
1886
- strictParseParams: true
1887
- });
1888
- router.state = _extends({}, router.state, {
1889
- pending: {
1890
- matches: matches,
1891
- location: router.location
1892
- },
1893
- status: 'loading'
1894
- });
1895
- router.notify(); // Load the matches
1896
-
1897
- await router.loadMatches(matches, {
1898
- withPending: true
1899
- });
1900
-
1901
- if (router.startedLoadingAt !== id) {
1902
- // Ignore side-effects of match loading
1903
- return router.navigationPromise;
1904
- }
1905
-
1906
- const previousMatches = router.state.matches;
1907
- const exiting = [],
1908
- staying = [];
1909
- previousMatches.forEach(d => {
1910
- if (matches.find(dd => dd.matchId === d.matchId)) {
1911
- staying.push(d);
1912
- } else {
1913
- exiting.push(d);
1914
- }
1915
- });
1916
- const now = Date.now();
1917
- exiting.forEach(d => {
1918
- var _ref2, _d$options$loaderGcMa, _ref3, _d$options$loaderMaxA;
1919
-
1920
- d.__.onExit == null ? void 0 : d.__.onExit({
1921
- params: d.params,
1922
- search: d.routeSearch
1923
- }); // Clear idle error states when match leaves
1924
-
1925
- if (d.status === 'error' && !d.isFetching) {
1926
- d.status = 'idle';
1927
- d.error = undefined;
1928
- }
1929
-
1930
- const gc = Math.max((_ref2 = (_d$options$loaderGcMa = d.options.loaderGcMaxAge) != null ? _d$options$loaderGcMa : router.options.defaultLoaderGcMaxAge) != null ? _ref2 : 0, (_ref3 = (_d$options$loaderMaxA = d.options.loaderMaxAge) != null ? _d$options$loaderMaxA : router.options.defaultLoaderMaxAge) != null ? _ref3 : 0);
1931
-
1932
- if (gc > 0) {
1933
- router.matchCache[d.matchId] = {
1934
- gc: gc == Infinity ? Number.MAX_SAFE_INTEGER : now + gc,
1935
- match: d
1936
- };
1937
- }
1938
- });
1939
- staying.forEach(d => {
1940
- d.options.onTransition == null ? void 0 : d.options.onTransition({
1941
- params: d.params,
1942
- search: d.routeSearch
1943
- });
1944
- });
1945
- const entering = matches.filter(d => {
1946
- return !previousMatches.find(dd => dd.matchId === d.matchId);
1947
- });
1948
- entering.forEach(d => {
1949
- d.__.onExit = d.options.onMatch == null ? void 0 : d.options.onMatch({
1950
- params: d.params,
1951
- search: d.search
1952
- });
1953
- delete router.matchCache[d.matchId];
1954
- });
1955
-
1956
- if (matches.some(d => d.status === 'loading')) {
1957
- router.notify();
1958
- await Promise.all(matches.map(d => d.__.loaderPromise || Promise.resolve()));
1959
- }
1960
-
1961
- if (router.startedLoadingAt !== id) {
1962
- // Ignore side-effects of match loading
1963
- return;
1964
- }
1965
-
1966
- router.state = _extends({}, router.state, {
1967
- location: router.location,
1968
- matches,
1969
- pending: undefined,
1970
- status: 'idle'
1971
- });
1972
- router.notify();
1973
- router.resolveNavigation();
1974
- },
1975
- cleanMatchCache: () => {
1976
- const now = Date.now();
1977
- Object.keys(router.matchCache).forEach(matchId => {
1978
- const entry = router.matchCache[matchId]; // Don't remove loading matches
1979
-
1980
- if (entry.match.status === 'loading') {
1981
- return;
1982
- } // Do not remove successful matches that are still valid
1983
-
1984
-
1985
- if (entry.gc > 0 && entry.gc > now) {
1986
- return;
1987
- } // Everything else gets removed
1988
-
1989
-
1990
- delete router.matchCache[matchId];
1991
- });
1992
- },
1993
- loadRoute: async function loadRoute(navigateOpts) {
1994
- if (navigateOpts === void 0) {
1995
- navigateOpts = router.location;
1996
- }
1997
-
1998
- const next = router.buildNext(navigateOpts);
1999
- const matches = router.matchRoutes(next.pathname, {
2000
- strictParseParams: true
2001
- });
2002
- await router.loadMatches(matches);
2003
- return matches;
2004
- },
2005
- preloadRoute: async function preloadRoute(navigateOpts, loaderOpts) {
2006
- var _ref4, _ref5, _loaderOpts$maxAge, _ref6, _ref7, _loaderOpts$gcMaxAge;
2007
-
2008
- if (navigateOpts === void 0) {
2009
- navigateOpts = router.location;
2010
- }
2011
-
2012
- const next = router.buildNext(navigateOpts);
2013
- const matches = router.matchRoutes(next.pathname, {
2014
- strictParseParams: true
2015
- });
2016
- await router.loadMatches(matches, {
2017
- preload: true,
2018
- maxAge: (_ref4 = (_ref5 = (_loaderOpts$maxAge = loaderOpts.maxAge) != null ? _loaderOpts$maxAge : router.options.defaultPreloadMaxAge) != null ? _ref5 : router.options.defaultLoaderMaxAge) != null ? _ref4 : 0,
2019
- gcMaxAge: (_ref6 = (_ref7 = (_loaderOpts$gcMaxAge = loaderOpts.gcMaxAge) != null ? _loaderOpts$gcMaxAge : router.options.defaultPreloadGcMaxAge) != null ? _ref7 : router.options.defaultLoaderGcMaxAge) != null ? _ref6 : 0
2020
- });
2021
- return matches;
2022
- },
2023
- matchRoutes: (pathname, opts) => {
2024
- var _router$state$pending3, _router$state$pending4;
2025
-
2026
- router.cleanMatchCache();
2027
- const matches = [];
2028
-
2029
- if (!router.routeTree) {
2030
- return matches;
2031
- }
2032
-
2033
- const existingMatches = [...router.state.matches, ...((_router$state$pending3 = (_router$state$pending4 = router.state.pending) == null ? void 0 : _router$state$pending4.matches) != null ? _router$state$pending3 : [])];
2034
-
2035
- const recurse = async routes => {
2036
- var _parentMatch$params, _router$options$filte, _foundRoute$childRout;
2037
-
2038
- const parentMatch = last(matches);
2039
- let params = (_parentMatch$params = parentMatch == null ? void 0 : parentMatch.params) != null ? _parentMatch$params : {};
2040
- const filteredRoutes = (_router$options$filte = router.options.filterRoutes == null ? void 0 : router.options.filterRoutes(routes)) != null ? _router$options$filte : routes;
2041
- let foundRoutes = [];
2042
-
2043
- const findMatchInRoutes = (parentRoutes, routes) => {
2044
- routes.some(route => {
2045
- var _route$childRoutes, _route$childRoutes2, _route$options$caseSe;
2046
-
2047
- if (!route.routePath && (_route$childRoutes = route.childRoutes) != null && _route$childRoutes.length) {
2048
- return findMatchInRoutes([...foundRoutes, route], route.childRoutes);
2049
- }
2050
-
2051
- const fuzzy = !!(route.routePath !== '/' || (_route$childRoutes2 = route.childRoutes) != null && _route$childRoutes2.length);
2052
- const matchParams = matchPathname(pathname, {
2053
- to: route.fullPath,
2054
- fuzzy,
2055
- caseSensitive: (_route$options$caseSe = route.options.caseSensitive) != null ? _route$options$caseSe : router.options.caseSensitive
2056
- });
2057
-
2058
- if (matchParams) {
2059
- let parsedParams;
2060
-
2061
- try {
2062
- var _route$options$parseP;
2063
-
2064
- parsedParams = (_route$options$parseP = route.options.parseParams == null ? void 0 : route.options.parseParams(matchParams)) != null ? _route$options$parseP : matchParams;
2065
- } catch (err) {
2066
- if (opts != null && opts.strictParseParams) {
2067
- throw err;
2068
- }
2069
- }
2070
-
2071
- params = _extends({}, params, parsedParams);
2072
- }
2073
-
2074
- if (!!matchParams) {
2075
- foundRoutes = [...parentRoutes, route];
2076
- }
2077
-
2078
- return !!foundRoutes.length;
2079
- });
2080
- return !!foundRoutes.length;
2081
- };
2082
-
2083
- findMatchInRoutes([], filteredRoutes);
2084
-
2085
- if (!foundRoutes.length) {
2086
- return;
2087
- }
2088
-
2089
- foundRoutes.forEach(foundRoute => {
2090
- var _router$matchCache$ma;
2091
-
2092
- const interpolatedPath = interpolatePath(foundRoute.routePath, params);
2093
- const matchId = interpolatePath(foundRoute.routeId, params, true);
2094
- const match = existingMatches.find(d => d.matchId === matchId) || ((_router$matchCache$ma = router.matchCache[matchId]) == null ? void 0 : _router$matchCache$ma.match) || createRouteMatch(router, foundRoute, {
2095
- matchId,
2096
- params,
2097
- pathname: joinPaths([pathname, interpolatedPath])
2098
- });
2099
- matches.push(match);
2100
- });
2101
- const foundRoute = last(foundRoutes);
2102
-
2103
- if ((_foundRoute$childRout = foundRoute.childRoutes) != null && _foundRoute$childRout.length) {
2104
- recurse(foundRoute.childRoutes);
2105
- }
2106
- };
2107
-
2108
- recurse([router.routeTree]);
2109
- cascadeLoaderData(matches);
2110
- return matches;
2111
- },
2112
- loadMatches: async (resolvedMatches, loaderOpts) => {
2113
- const matchPromises = resolvedMatches.map(async match => {
2114
- // Validate the match (loads search params etc)
2115
- match.__.validate();
2116
-
2117
- match.load(loaderOpts);
2118
-
2119
- if (match.status === 'loading') {
2120
- // If requested, start the pending timers
2121
- if (loaderOpts != null && loaderOpts.withPending) match.__.startPending(); // Wait for the first sign of activity from the match
2122
- // This might be completion, error, or a pending state
2123
-
2124
- await match.__.loadPromise;
2125
- }
2126
- });
2127
- router.notify();
2128
- await Promise.all(matchPromises);
2129
- },
2130
- invalidateRoute: opts => {
2131
- var _router$state$pending5, _router$state$pending6;
2132
-
2133
- const next = router.buildNext(opts);
2134
- const unloadedMatchIds = router.matchRoutes(next.pathname).map(d => d.matchId);
2135
- [...router.state.matches, ...((_router$state$pending5 = (_router$state$pending6 = router.state.pending) == null ? void 0 : _router$state$pending6.matches) != null ? _router$state$pending5 : [])].forEach(match => {
2136
- if (unloadedMatchIds.includes(match.matchId)) {
2137
- match.invalidate();
2138
- }
2139
- });
2140
- },
2141
- reload: () => router.__.navigate({
2142
- fromCurrent: true,
2143
- replace: true,
2144
- search: true
2145
- }),
2146
- resolvePath: (from, path) => {
2147
- return resolvePath(router.basepath, from, cleanPath(path));
2148
- },
2149
- matchRoute: (location, opts) => {
2150
- var _location$from;
2151
-
2152
- // const location = router.buildNext(opts)
2153
- location = _extends({}, location, {
2154
- to: location.to ? router.resolvePath((_location$from = location.from) != null ? _location$from : '', location.to) : undefined
2155
- });
2156
- const next = router.buildNext(location);
2157
-
2158
- if (opts != null && opts.pending) {
2159
- var _router$state$pending7;
2160
-
2161
- if (!((_router$state$pending7 = router.state.pending) != null && _router$state$pending7.location)) {
2162
- return false;
2163
- }
2164
-
2165
- return !!matchPathname(router.state.pending.location.pathname, _extends({}, opts, {
2166
- to: next.pathname
2167
- }));
2168
- }
2169
-
2170
- return !!matchPathname(router.state.location.pathname, _extends({}, opts, {
2171
- to: next.pathname
2172
- }));
2173
- },
2174
- navigate: async _ref8 => {
2175
- let {
2176
- from,
2177
- to = '.',
2178
- search,
2179
- hash,
2180
- replace,
2181
- params
2182
- } = _ref8;
2183
- // If this link simply reloads the current route,
2184
- // make sure it has a new key so it will trigger a data refresh
2185
- // If this `to` is a valid external URL, return
2186
- // null for LinkUtils
2187
- const toString = String(to);
2188
- const fromString = String(from);
2189
- let isExternal;
2190
-
2191
- try {
2192
- new URL("" + toString);
2193
- isExternal = true;
2194
- } catch (e) {}
2195
-
2196
- invariant(!isExternal, 'Attempting to navigate to external url with router.navigate!');
2197
- return router.__.navigate({
2198
- from: fromString,
2199
- to: toString,
2200
- search,
2201
- hash,
2202
- replace,
2203
- params
2204
- });
2205
- },
2206
- buildLink: _ref9 => {
2207
- var _preload, _ref10;
2208
-
2209
- let {
2210
- from,
2211
- to = '.',
2212
- search,
2213
- params,
2214
- hash,
2215
- target,
2216
- replace,
2217
- activeOptions,
2218
- preload,
2219
- preloadMaxAge: userPreloadMaxAge,
2220
- preloadGcMaxAge: userPreloadGcMaxAge,
2221
- preloadDelay: userPreloadDelay,
2222
- disabled
2223
- } = _ref9;
2224
-
2225
- // If this link simply reloads the current route,
2226
- // make sure it has a new key so it will trigger a data refresh
2227
- // If this `to` is a valid external URL, return
2228
- // null for LinkUtils
2229
- try {
2230
- new URL("" + to);
2231
- return {
2232
- type: 'external',
2233
- href: to
2234
- };
2235
- } catch (e) {}
2236
-
2237
- const nextOpts = {
2238
- from,
2239
- to,
2240
- search,
2241
- params,
2242
- hash,
2243
- replace
2244
- };
2245
- const next = router.buildNext(nextOpts);
2246
- preload = (_preload = preload) != null ? _preload : router.options.defaultPreload;
2247
- const preloadDelay = (_ref10 = userPreloadDelay != null ? userPreloadDelay : router.options.defaultPreloadDelay) != null ? _ref10 : 0; // Compare path/hash for matches
2248
-
2249
- const pathIsEqual = router.state.location.pathname === next.pathname;
2250
- const currentPathSplit = router.state.location.pathname.split('/');
2251
- const nextPathSplit = next.pathname.split('/');
2252
- const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
2253
- const hashIsEqual = router.state.location.hash === next.hash; // Combine the matches based on user options
2254
-
2255
- const pathTest = activeOptions != null && activeOptions.exact ? pathIsEqual : pathIsFuzzyEqual;
2256
- const hashTest = activeOptions != null && activeOptions.includeHash ? hashIsEqual : true; // The final "active" test
2257
-
2258
- const isActive = pathTest && hashTest; // The click handler
2259
-
2260
- const handleClick = e => {
2261
- if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
2262
- e.preventDefault();
2263
-
2264
- if (pathIsEqual && !search && !hash) {
2265
- router.invalidateRoute(nextOpts);
2266
- } // All is well? Navigate!)
2267
-
2268
-
2269
- router.__.navigate(nextOpts);
2270
- }
2271
- }; // The click handler
2272
-
2273
-
2274
- const handleFocus = e => {
2275
- if (preload) {
2276
- router.preloadRoute(nextOpts, {
2277
- maxAge: userPreloadMaxAge,
2278
- gcMaxAge: userPreloadGcMaxAge
2279
- });
2280
- }
2281
- };
2282
-
2283
- const handleEnter = e => {
2284
- const target = e.target || {};
2285
-
2286
- if (preload) {
2287
- if (target.preloadTimeout) {
2288
- return;
2289
- }
2290
-
2291
- target.preloadTimeout = setTimeout(() => {
2292
- target.preloadTimeout = null;
2293
- router.preloadRoute(nextOpts, {
2294
- maxAge: userPreloadMaxAge,
2295
- gcMaxAge: userPreloadGcMaxAge
2296
- });
2297
- }, preloadDelay);
2298
- }
2299
- };
2300
-
2301
- const handleLeave = e => {
2302
- const target = e.target || {};
2303
-
2304
- if (target.preloadTimeout) {
2305
- clearTimeout(target.preloadTimeout);
2306
- target.preloadTimeout = null;
2307
- }
2308
- };
2309
-
2310
- return {
2311
- type: 'internal',
2312
- next,
2313
- handleFocus,
2314
- handleClick,
2315
- handleEnter,
2316
- handleLeave,
2317
- isActive,
2318
- disabled
2319
- };
2320
- },
2321
- buildNext: opts => {
2322
- const next = router.__.buildLocation(opts);
2323
-
2324
- const matches = router.matchRoutes(next.pathname);
2325
-
2326
- const __preSearchFilters = matches.map(match => {
2327
- var _match$options$preSea;
2328
-
2329
- return (_match$options$preSea = match.options.preSearchFilters) != null ? _match$options$preSea : [];
2330
- }).flat().filter(Boolean);
2331
-
2332
- const __postSearchFilters = matches.map(match => {
2333
- var _match$options$postSe;
2334
-
2335
- return (_match$options$postSe = match.options.postSearchFilters) != null ? _match$options$postSe : [];
2336
- }).flat().filter(Boolean);
2337
-
2338
- return router.__.buildLocation(_extends({}, opts, {
2339
- __preSearchFilters,
2340
- __postSearchFilters
2341
- }));
2342
- },
2343
- __: {
2344
- buildRouteTree: rootRouteConfig => {
2345
- const recurseRoutes = (routeConfigs, parent) => {
2346
- return routeConfigs.map(routeConfig => {
2347
- const routeOptions = routeConfig.options;
2348
- const route = createRoute(routeConfig, routeOptions, parent, router);
2349
- const existingRoute = router.routesById[route.routeId];
2350
-
2351
- if (existingRoute) {
2352
- if (process.env.NODE_ENV !== 'production') {
2353
- console.warn("Duplicate routes found with id: " + String(route.routeId), router.routesById, route);
2354
- }
2355
-
2356
- throw new Error();
2357
- }
2358
- router.routesById[route.routeId] = route;
2359
- const children = routeConfig.children;
2360
- route.childRoutes = children != null && children.length ? recurseRoutes(children, route) : undefined;
2361
- return route;
2362
- });
2363
- };
2364
-
2365
- const routes = recurseRoutes([rootRouteConfig]);
2366
- return routes[0];
2367
- },
2368
- parseLocation: (location, previousLocation) => {
2369
- var _location$hash$split$;
2370
-
2371
- const parsedSearch = router.options.parseSearch(location.search);
2372
- return {
2373
- pathname: location.pathname,
2374
- searchStr: location.search,
2375
- search: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
2376
- hash: (_location$hash$split$ = location.hash.split('#').reverse()[0]) != null ? _location$hash$split$ : '',
2377
- href: "" + location.pathname + location.search + location.hash,
2378
- state: location.state,
2379
- key: location.key
2380
- };
2381
- },
2382
- navigate: location => {
2383
- const next = router.buildNext(location);
2384
- return router.__.commitLocation(next, location.replace);
2385
- },
2386
- buildLocation: function buildLocation(dest) {
2387
- var _dest$from, _router$basepath, _dest$to, _last, _dest$params, _dest$__preSearchFilt, _functionalUpdate, _dest$__preSearchFilt2, _dest$__postSearchFil;
2388
-
2389
- if (dest === void 0) {
2390
- dest = {};
2391
- }
2392
-
2393
- // const resolvedFrom: Location = {
2394
- // ...router.location,
2395
- const fromPathname = dest.fromCurrent ? router.location.pathname : (_dest$from = dest.from) != null ? _dest$from : router.location.pathname;
2396
-
2397
- let pathname = resolvePath((_router$basepath = router.basepath) != null ? _router$basepath : '/', fromPathname, "" + ((_dest$to = dest.to) != null ? _dest$to : '.'));
2398
-
2399
- const fromMatches = router.matchRoutes(router.location.pathname, {
2400
- strictParseParams: true
2401
- });
2402
- const toMatches = router.matchRoutes(pathname);
2403
-
2404
- const prevParams = _extends({}, (_last = last(fromMatches)) == null ? void 0 : _last.params);
2405
-
2406
- let nextParams = ((_dest$params = dest.params) != null ? _dest$params : true) === true ? prevParams : functionalUpdate(dest.params, prevParams);
2407
-
2408
- if (nextParams) {
2409
- toMatches.map(d => d.options.stringifyParams).filter(Boolean).forEach(fn => {
2410
- Object.assign({}, nextParams, fn(nextParams));
2411
- });
2412
- }
2413
-
2414
- pathname = interpolatePath(pathname, nextParams != null ? nextParams : {}); // Pre filters first
2415
-
2416
- const preFilteredSearch = (_dest$__preSearchFilt = dest.__preSearchFilters) != null && _dest$__preSearchFilt.length ? dest.__preSearchFilters.reduce((prev, next) => next(prev), router.location.search) : router.location.search; // Then the link/navigate function
2417
-
2418
- const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
2419
- : dest.search ? (_functionalUpdate = functionalUpdate(dest.search, preFilteredSearch)) != null ? _functionalUpdate : {} // Updater
2420
- : (_dest$__preSearchFilt2 = dest.__preSearchFilters) != null && _dest$__preSearchFilt2.length ? preFilteredSearch // Preserve resolvedFrom filters
2421
- : {}; // Then post filters
2422
-
2423
- const postFilteredSearch = (_dest$__postSearchFil = dest.__postSearchFilters) != null && _dest$__postSearchFil.length ? dest.__postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
2424
- const search = replaceEqualDeep(router.location.search, postFilteredSearch);
2425
- const searchStr = router.options.stringifySearch(search);
2426
- let hash = dest.hash === true ? router.location.hash : functionalUpdate(dest.hash, router.location.hash);
2427
- hash = hash ? "#" + hash : '';
2428
- return {
2429
- pathname,
2430
- search,
2431
- searchStr,
2432
- state: router.location.state,
2433
- hash,
2434
- href: "" + pathname + searchStr + hash,
2435
- key: dest.key
2436
- };
2437
- },
2438
- commitLocation: (next, replace) => {
2439
- const id = '' + Date.now() + Math.random();
2440
- if (router.navigateTimeout) clearTimeout(router.navigateTimeout);
2441
- let nextAction = 'replace';
2442
-
2443
- if (!replace) {
2444
- nextAction = 'push';
2445
- }
2446
-
2447
- const isSameUrl = router.__.parseLocation(history.location).href === next.href;
2448
-
2449
- if (isSameUrl && !next.key) {
2450
- nextAction = 'replace';
2451
- }
2452
-
2453
- if (nextAction === 'replace') {
2454
- history.replace({
2455
- pathname: next.pathname,
2456
- hash: next.hash,
2457
- search: next.searchStr
2458
- }, {
2459
- id
2460
- });
2461
- } else {
2462
- history.push({
2463
- pathname: next.pathname,
2464
- hash: next.hash,
2465
- search: next.searchStr
2466
- }, {
2467
- id
2468
- });
2469
- }
2470
-
2471
- router.navigationPromise = new Promise(resolve => {
2472
- const previousNavigationResolve = router.resolveNavigation;
2473
-
2474
- router.resolveNavigation = () => {
2475
- previousNavigationResolve();
2476
- resolve();
2477
- };
2478
- });
2479
- return router.navigationPromise;
2480
- }
2481
- }
2482
- };
2483
- router.update(userOptions); // Allow frameworks to hook into the router creation
2484
-
2485
- router.options.createRouter == null ? void 0 : router.options.createRouter(router);
2486
- return router;
2487
- }
2488
-
2489
- function isCtrlEvent(e) {
2490
- return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
2491
- }
2492
-
2493
- exports.cascadeLoaderData = cascadeLoaderData;
2494
- exports.cleanPath = cleanPath;
2495
- exports.createBrowserHistory = createBrowserHistory;
2496
- exports.createHashHistory = createHashHistory;
2497
- exports.createMemoryHistory = createMemoryHistory;
2498
- exports.createRoute = createRoute;
2499
- exports.createRouteConfig = createRouteConfig;
2500
- exports.createRouteMatch = createRouteMatch;
2501
- exports.createRouter = createRouter;
2502
- exports.decode = decode;
2503
- exports.defaultParseSearch = defaultParseSearch;
2504
- exports.defaultStringifySearch = defaultStringifySearch;
2505
- exports.encode = encode;
2506
- exports.functionalUpdate = functionalUpdate;
2507
- exports.interpolatePath = interpolatePath;
2508
- exports.invariant = invariant;
2509
- exports.joinPaths = joinPaths;
2510
- exports.last = last;
2511
- exports.matchByPath = matchByPath;
2512
- exports.matchPathname = matchPathname;
2513
- exports.parsePathname = parsePathname;
2514
- exports.parseSearchWith = parseSearchWith;
2515
- exports.pick = pick;
2516
- exports.replaceEqualDeep = replaceEqualDeep;
2517
- exports.resolvePath = resolvePath;
2518
- exports.rootRouteId = rootRouteId;
2519
- exports.stringifySearchWith = stringifySearchWith;
2520
- exports.trimPath = trimPath;
2521
- exports.trimPathLeft = trimPathLeft;
2522
- exports.trimPathRight = trimPathRight;
2523
- exports.warning = warning;
2524
- //# sourceMappingURL=index.js.map