@tanstack/react-router 0.0.1-alpha.0

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