@tanstack/router-core 0.0.1-beta.2 → 0.0.1-beta.201

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