@tanstack/react-router 0.0.1-beta.6 → 0.0.1-beta.60

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