@tanstack/react-router 0.0.1-beta.4 → 0.0.1-beta.41

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