@tanstack/router-core 0.0.1-beta.15 → 0.0.1-beta.151

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/build/cjs/fileRoute.js +29 -0
  3. package/build/cjs/fileRoute.js.map +1 -0
  4. package/build/cjs/history.js +226 -0
  5. package/build/cjs/history.js.map +1 -0
  6. package/build/cjs/index.js +78 -0
  7. package/build/cjs/{packages/router-core/src/index.js.map → index.js.map} +1 -1
  8. package/build/cjs/{packages/router-core/src/path.js → path.js} +45 -56
  9. package/build/cjs/path.js.map +1 -0
  10. package/build/cjs/{packages/router-core/src/qss.js → qss.js} +10 -16
  11. package/build/cjs/qss.js.map +1 -0
  12. package/build/cjs/route.js +103 -0
  13. package/build/cjs/route.js.map +1 -0
  14. package/build/cjs/router.js +1113 -0
  15. package/build/cjs/router.js.map +1 -0
  16. package/build/cjs/{packages/router-core/src/searchParams.js → searchParams.js} +11 -13
  17. package/build/cjs/searchParams.js.map +1 -0
  18. package/build/cjs/{packages/router-core/src/utils.js → utils.js} +54 -64
  19. package/build/cjs/utils.js.map +1 -0
  20. package/build/esm/index.js +1417 -2105
  21. package/build/esm/index.js.map +1 -1
  22. package/build/stats-html.html +59 -49
  23. package/build/stats-react.json +203 -234
  24. package/build/types/index.d.ts +604 -426
  25. package/build/umd/index.development.js +1640 -2224
  26. package/build/umd/index.development.js.map +1 -1
  27. package/build/umd/index.production.js +13 -2
  28. package/build/umd/index.production.js.map +1 -1
  29. package/package.json +11 -7
  30. package/src/fileRoute.ts +120 -0
  31. package/src/history.ts +292 -0
  32. package/src/index.ts +3 -10
  33. package/src/link.ts +118 -113
  34. package/src/path.ts +37 -17
  35. package/src/qss.ts +1 -2
  36. package/src/route.ts +891 -218
  37. package/src/routeInfo.ts +121 -204
  38. package/src/router.ts +1494 -1017
  39. package/src/searchParams.ts +1 -1
  40. package/src/utils.ts +80 -49
  41. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +0 -33
  42. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +0 -1
  43. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js +0 -33
  44. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js.map +0 -1
  45. package/build/cjs/node_modules/history/index.js +0 -815
  46. package/build/cjs/node_modules/history/index.js.map +0 -1
  47. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js +0 -30
  48. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js.map +0 -1
  49. package/build/cjs/packages/router-core/src/index.js +0 -58
  50. package/build/cjs/packages/router-core/src/path.js.map +0 -1
  51. package/build/cjs/packages/router-core/src/qss.js.map +0 -1
  52. package/build/cjs/packages/router-core/src/route.js +0 -147
  53. package/build/cjs/packages/router-core/src/route.js.map +0 -1
  54. package/build/cjs/packages/router-core/src/routeConfig.js +0 -69
  55. package/build/cjs/packages/router-core/src/routeConfig.js.map +0 -1
  56. package/build/cjs/packages/router-core/src/routeMatch.js +0 -231
  57. package/build/cjs/packages/router-core/src/routeMatch.js.map +0 -1
  58. package/build/cjs/packages/router-core/src/router.js +0 -833
  59. package/build/cjs/packages/router-core/src/router.js.map +0 -1
  60. package/build/cjs/packages/router-core/src/searchParams.js.map +0 -1
  61. package/build/cjs/packages/router-core/src/utils.js.map +0 -1
  62. package/src/frameworks.ts +0 -11
  63. package/src/routeConfig.ts +0 -514
  64. package/src/routeMatch.ts +0 -319
@@ -0,0 +1,1113 @@
1
+ /**
2
+ * @tanstack/router-core/src/index.ts
3
+ *
4
+ * Copyright (c) TanStack
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE.md file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ 'use strict';
12
+
13
+ Object.defineProperty(exports, '__esModule', { value: true });
14
+
15
+ var reactStore = require('@tanstack/react-store');
16
+ var invariant = require('tiny-invariant');
17
+ var path = require('./path.js');
18
+ var searchParams = require('./searchParams.js');
19
+ var utils = require('./utils.js');
20
+ var history = require('./history.js');
21
+
22
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
23
+
24
+ var invariant__default = /*#__PURE__*/_interopDefaultLegacy(invariant);
25
+
26
+ //
27
+
28
+ const componentTypes = ['component', 'errorComponent', 'pendingComponent'];
29
+ class Router {
30
+ #unsubHistory;
31
+ constructor(options) {
32
+ this.options = {
33
+ defaultPreloadDelay: 50,
34
+ context: undefined,
35
+ ...options,
36
+ stringifySearch: options?.stringifySearch ?? searchParams.defaultStringifySearch,
37
+ parseSearch: options?.parseSearch ?? searchParams.defaultParseSearch
38
+ // fetchServerDataFn: options?.fetchServerDataFn ?? defaultFetchServerDataFn,
39
+ };
40
+
41
+ this.__store = new reactStore.Store(getInitialRouterState(), {
42
+ onUpdate: () => {
43
+ const prev = this.state;
44
+ this.state = this.__store.state;
45
+ const matchesByIdChanged = prev.matchesById !== this.state.matchesById;
46
+ let matchesChanged;
47
+ let pendingMatchesChanged;
48
+ if (!matchesByIdChanged) {
49
+ matchesChanged = prev.matchIds.length !== this.state.matchIds.length || prev.matchIds.some((d, i) => d !== this.state.matchIds[i]);
50
+ pendingMatchesChanged = prev.pendingMatchIds.length !== this.state.pendingMatchIds.length || prev.pendingMatchIds.some((d, i) => d !== this.state.pendingMatchIds[i]);
51
+ }
52
+ if (matchesByIdChanged || matchesChanged) {
53
+ this.state.matches = this.state.matchIds.map(id => {
54
+ return this.state.matchesById[id];
55
+ });
56
+ }
57
+ if (matchesByIdChanged || pendingMatchesChanged) {
58
+ this.state.pendingMatches = this.state.pendingMatchIds.map(id => {
59
+ return this.state.matchesById[id];
60
+ });
61
+ }
62
+ this.state.isFetching = [...this.state.matches, ...this.state.pendingMatches].some(d => d.isFetching);
63
+ },
64
+ defaultPriority: 'low'
65
+ });
66
+ this.state = this.__store.state;
67
+ this.update(options);
68
+ const next = this.buildNext({
69
+ hash: true,
70
+ fromCurrent: true,
71
+ search: true,
72
+ state: true
73
+ });
74
+ if (this.state.location.href !== next.href) {
75
+ this.#commitLocation({
76
+ ...next,
77
+ replace: true
78
+ });
79
+ }
80
+ }
81
+ reset = () => {
82
+ this.__store.setState(s => Object.assign(s, getInitialRouterState()));
83
+ };
84
+ mount = () => {
85
+ // If the router matches are empty, start loading the matches
86
+ // if (!this.state.matches.length) {
87
+ this.safeLoad();
88
+ // }
89
+ };
90
+
91
+ update = opts => {
92
+ this.options = {
93
+ ...this.options,
94
+ ...opts,
95
+ context: {
96
+ ...this.options.context,
97
+ ...opts?.context
98
+ }
99
+ };
100
+ if (!this.history || this.options.history && this.options.history !== this.history) {
101
+ if (this.#unsubHistory) {
102
+ this.#unsubHistory();
103
+ }
104
+ this.history = this.options.history ?? (isServer ? history.createMemoryHistory() : history.createBrowserHistory());
105
+ const parsedLocation = this.#parseLocation();
106
+ this.__store.setState(s => ({
107
+ ...s,
108
+ resolvedLocation: parsedLocation,
109
+ location: parsedLocation
110
+ }));
111
+ this.#unsubHistory = this.history.listen(() => {
112
+ this.safeLoad({
113
+ next: this.#parseLocation(this.state.location)
114
+ });
115
+ });
116
+ }
117
+ const {
118
+ basepath,
119
+ routeTree
120
+ } = this.options;
121
+ this.basepath = `/${path.trimPath(basepath ?? '') ?? ''}`;
122
+ if (routeTree && routeTree !== this.routeTree) {
123
+ this.#buildRouteTree(routeTree);
124
+ }
125
+ return this;
126
+ };
127
+ buildNext = opts => {
128
+ const next = this.#buildLocation(opts);
129
+ const __matches = this.matchRoutes(next.pathname, next.search);
130
+ return this.#buildLocation({
131
+ ...opts,
132
+ __matches
133
+ });
134
+ };
135
+ cancelMatches = () => {
136
+ this.state.matches.forEach(match => {
137
+ this.cancelMatch(match.id);
138
+ });
139
+ };
140
+ cancelMatch = id => {
141
+ this.getRouteMatch(id)?.abortController?.abort();
142
+ };
143
+ safeLoad = opts => {
144
+ return this.load(opts).catch(err => {
145
+ // console.warn(err)
146
+ // invariant(false, 'Encountered an error during router.load()! ☝️.')
147
+ });
148
+ };
149
+ latestLoadPromise = Promise.resolve();
150
+ load = async opts => {
151
+ const promise = new Promise(async (resolve, reject) => {
152
+ let latestPromise;
153
+ const checkLatest = () => {
154
+ return this.latestLoadPromise !== promise ? this.latestLoadPromise : undefined;
155
+ };
156
+
157
+ // Cancel any pending matches
158
+ // this.cancelMatches()
159
+
160
+ let pendingMatches;
161
+ this.__store.batch(() => {
162
+ if (opts?.next) {
163
+ // Ingest the new location
164
+ this.__store.setState(s => ({
165
+ ...s,
166
+ location: opts.next
167
+ }));
168
+ }
169
+
170
+ // Match the routes
171
+ pendingMatches = this.matchRoutes(this.state.location.pathname, this.state.location.search, {
172
+ throwOnError: opts?.throwOnError,
173
+ debug: true
174
+ });
175
+ this.__store.setState(s => ({
176
+ ...s,
177
+ status: 'pending',
178
+ pendingMatchIds: pendingMatches.map(d => d.id),
179
+ matchesById: this.#mergeMatches(s.matchesById, pendingMatches)
180
+ }));
181
+ });
182
+ try {
183
+ // Load the matches
184
+ await this.loadMatches(pendingMatches);
185
+
186
+ // Only apply the latest transition
187
+ if (latestPromise = checkLatest()) {
188
+ return await latestPromise;
189
+ }
190
+ const prevLocation = this.state.resolvedLocation;
191
+ this.__store.setState(s => ({
192
+ ...s,
193
+ status: 'idle',
194
+ resolvedLocation: s.location,
195
+ matchIds: s.pendingMatchIds,
196
+ pendingMatchIds: []
197
+ }));
198
+ if (prevLocation.href !== this.state.location.href) {
199
+ this.options.onRouteChange?.();
200
+ }
201
+ resolve();
202
+ } catch (err) {
203
+ // Only apply the latest transition
204
+ if (latestPromise = checkLatest()) {
205
+ return await latestPromise;
206
+ }
207
+ reject(err);
208
+ }
209
+ });
210
+ this.latestLoadPromise = promise;
211
+ return this.latestLoadPromise;
212
+ };
213
+ #mergeMatches = (prevMatchesById, nextMatches) => {
214
+ const nextMatchesById = {
215
+ ...prevMatchesById
216
+ };
217
+ let hadNew = false;
218
+ nextMatches.forEach(match => {
219
+ if (!nextMatchesById[match.id]) {
220
+ hadNew = true;
221
+ nextMatchesById[match.id] = match;
222
+ }
223
+ });
224
+ if (!hadNew) {
225
+ return prevMatchesById;
226
+ }
227
+ return nextMatchesById;
228
+ };
229
+ getRoute = id => {
230
+ const route = this.routesById[id];
231
+ invariant__default["default"](route, `Route with id "${id}" not found`);
232
+ return route;
233
+ };
234
+ preloadRoute = async (navigateOpts = this.state.location) => {
235
+ const next = this.buildNext(navigateOpts);
236
+ const matches = this.matchRoutes(next.pathname, next.search, {
237
+ throwOnError: true
238
+ });
239
+ this.__store.setState(s => {
240
+ return {
241
+ ...s,
242
+ matchesById: this.#mergeMatches(s.matchesById, matches)
243
+ };
244
+ });
245
+ await this.loadMatches(matches, {
246
+ preload: true,
247
+ maxAge: navigateOpts.maxAge
248
+ });
249
+ return matches;
250
+ };
251
+ cleanMatches = () => {
252
+ const now = Date.now();
253
+ const outdatedMatchIds = Object.values(this.state.matchesById).filter(match => {
254
+ const route = this.getRoute(match.routeId);
255
+ return !this.state.matchIds.includes(match.id) && !this.state.pendingMatchIds.includes(match.id) && match.preloadInvalidAt < now && (route.options.gcMaxAge ? match.updatedAt + route.options.gcMaxAge < now : true);
256
+ }).map(d => d.id);
257
+ if (outdatedMatchIds.length) {
258
+ this.__store.setState(s => {
259
+ const matchesById = {
260
+ ...s.matchesById
261
+ };
262
+ outdatedMatchIds.forEach(id => {
263
+ delete matchesById[id];
264
+ });
265
+ return {
266
+ ...s,
267
+ matchesById
268
+ };
269
+ });
270
+ }
271
+ };
272
+ matchRoutes = (pathname, locationSearch, opts) => {
273
+ let routeParams = {};
274
+ let foundRoute = this.flatRoutes.find(route => {
275
+ const matchedParams = path.matchPathname(this.basepath, path.trimPathRight(pathname), {
276
+ to: route.fullPath,
277
+ caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive
278
+ });
279
+ if (matchedParams) {
280
+ routeParams = matchedParams;
281
+ return true;
282
+ }
283
+ return false;
284
+ });
285
+ let routeCursor = foundRoute || this.routesById['__root__'];
286
+ let matchedRoutes = [routeCursor];
287
+ while (routeCursor?.parentRoute) {
288
+ routeCursor = routeCursor.parentRoute;
289
+ if (routeCursor) matchedRoutes.unshift(routeCursor);
290
+ }
291
+
292
+ // Alright, by now we should have all of our
293
+ // matching routes and their param pairs, let's
294
+ // Turn them into actual `Match` objects and
295
+ // accumulate the params into a single params bag
296
+ let allParams = {};
297
+
298
+ // Existing matches are matches that are already loaded along with
299
+ // pending matches that are still loading
300
+
301
+ const matches = matchedRoutes.map(route => {
302
+ let parsedParams;
303
+ let parsedParamsError;
304
+ try {
305
+ parsedParams = route.options.parseParams?.(routeParams) ?? routeParams;
306
+ // (typeof route.options.parseParams === 'object' &&
307
+ // route.options.parseParams.parse
308
+ // ? route.options.parseParams.parse(routeParams)
309
+ // : (route.options.parseParams as any)?.(routeParams!)) ?? routeParams
310
+ } catch (err) {
311
+ parsedParamsError = new PathParamError(err.message, {
312
+ cause: err
313
+ });
314
+ if (opts?.throwOnError) {
315
+ throw parsedParamsError;
316
+ }
317
+ }
318
+
319
+ // Add the parsed params to the accumulated params bag
320
+ Object.assign(allParams, parsedParams);
321
+ const interpolatedPath = path.interpolatePath(route.path, allParams);
322
+ const key = route.options.key ? route.options.key({
323
+ params: allParams,
324
+ search: locationSearch
325
+ }) ?? '' : '';
326
+ const stringifiedKey = key ? JSON.stringify(key) : '';
327
+ const matchId = path.interpolatePath(route.id, allParams, true) + stringifiedKey;
328
+
329
+ // Waste not, want not. If we already have a match for this route,
330
+ // reuse it. This is important for layout routes, which might stick
331
+ // around between navigation actions that only change leaf routes.
332
+ const existingMatch = this.getRouteMatch(matchId);
333
+ if (existingMatch) {
334
+ return {
335
+ ...existingMatch
336
+ };
337
+ }
338
+
339
+ // Create a fresh route match
340
+ const hasLoaders = !!(route.options.loader || componentTypes.some(d => route.options[d]?.preload));
341
+ const routeMatch = {
342
+ id: matchId,
343
+ key: stringifiedKey,
344
+ routeId: route.id,
345
+ params: allParams,
346
+ pathname: path.joinPaths([this.basepath, interpolatedPath]),
347
+ updatedAt: Date.now(),
348
+ invalidAt: Infinity,
349
+ preloadInvalidAt: Infinity,
350
+ routeSearch: {},
351
+ search: {},
352
+ status: hasLoaders ? 'idle' : 'success',
353
+ isFetching: false,
354
+ invalid: false,
355
+ error: undefined,
356
+ paramsError: parsedParamsError,
357
+ searchError: undefined,
358
+ loaderData: undefined,
359
+ loadPromise: Promise.resolve(),
360
+ routeContext: undefined,
361
+ context: undefined,
362
+ abortController: new AbortController(),
363
+ fetchedAt: 0
364
+ };
365
+ return routeMatch;
366
+ });
367
+
368
+ // Take each match and resolve its search params and context
369
+ // This has to happen after the matches are created or found
370
+ // so that we can use the parent match's search params and context
371
+ matches.forEach((match, i) => {
372
+ const parentMatch = matches[i - 1];
373
+ const route = this.getRoute(match.routeId);
374
+ const searchInfo = (() => {
375
+ // Validate the search params and stabilize them
376
+ const parentSearchInfo = {
377
+ search: parentMatch?.search ?? locationSearch,
378
+ routeSearch: parentMatch?.routeSearch ?? locationSearch
379
+ };
380
+ try {
381
+ const validator = typeof route.options.validateSearch === 'object' ? route.options.validateSearch.parse : route.options.validateSearch;
382
+ const routeSearch = validator?.(parentSearchInfo.search) ?? {};
383
+ const search = {
384
+ ...parentSearchInfo.search,
385
+ ...routeSearch
386
+ };
387
+ return {
388
+ routeSearch: utils.replaceEqualDeep(match.routeSearch, routeSearch),
389
+ search: utils.replaceEqualDeep(match.search, search)
390
+ };
391
+ } catch (err) {
392
+ match.searchError = new SearchParamError(err.message, {
393
+ cause: err
394
+ });
395
+ if (opts?.throwOnError) {
396
+ throw match.searchError;
397
+ }
398
+ return parentSearchInfo;
399
+ }
400
+ })();
401
+ Object.assign(match, {
402
+ ...searchInfo
403
+ });
404
+ const contextInfo = (() => {
405
+ try {
406
+ const routeContext = route.options.getContext?.({
407
+ parentContext: parentMatch?.routeContext ?? {},
408
+ context: parentMatch?.context ?? this?.options.context ?? {},
409
+ params: match.params,
410
+ search: match.search
411
+ }) || {};
412
+ const context = {
413
+ ...(parentMatch?.context ?? this?.options.context),
414
+ ...routeContext
415
+ };
416
+ return {
417
+ context,
418
+ routeContext
419
+ };
420
+ } catch (err) {
421
+ route.options.onError?.(err);
422
+ throw err;
423
+ }
424
+ })();
425
+ Object.assign(match, {
426
+ ...contextInfo
427
+ });
428
+ });
429
+ return matches;
430
+ };
431
+ loadMatches = async (resolvedMatches, opts) => {
432
+ this.cleanMatches();
433
+ if (!opts?.preload) {
434
+ resolvedMatches.forEach(match => {
435
+ // Update each match with its latest route data
436
+ this.setRouteMatch(match.id, s => ({
437
+ ...s,
438
+ routeSearch: match.routeSearch,
439
+ search: match.search,
440
+ routeContext: match.routeContext,
441
+ context: match.context,
442
+ error: match.error,
443
+ paramsError: match.paramsError,
444
+ searchError: match.searchError,
445
+ params: match.params
446
+ }));
447
+ });
448
+ }
449
+ let firstBadMatchIndex;
450
+
451
+ // Check each match middleware to see if the route can be accessed
452
+ try {
453
+ for (const [index, match] of resolvedMatches.entries()) {
454
+ const route = this.getRoute(match.routeId);
455
+ const handleError = (err, handler) => {
456
+ firstBadMatchIndex = firstBadMatchIndex ?? index;
457
+ handler = handler || route.options.onError;
458
+ if (isRedirect(err)) {
459
+ throw err;
460
+ }
461
+ try {
462
+ handler?.(err);
463
+ } catch (errorHandlerErr) {
464
+ err = errorHandlerErr;
465
+ if (isRedirect(errorHandlerErr)) {
466
+ throw errorHandlerErr;
467
+ }
468
+ }
469
+ this.setRouteMatch(match.id, s => ({
470
+ ...s,
471
+ error: err,
472
+ status: 'error',
473
+ updatedAt: Date.now()
474
+ }));
475
+ };
476
+ if (match.paramsError) {
477
+ handleError(match.paramsError, route.options.onParseParamsError);
478
+ }
479
+ if (match.searchError) {
480
+ handleError(match.searchError, route.options.onValidateSearchError);
481
+ }
482
+ let didError = false;
483
+ try {
484
+ await route.options.beforeLoad?.({
485
+ ...match,
486
+ preload: !!opts?.preload
487
+ });
488
+ } catch (err) {
489
+ handleError(err, route.options.onBeforeLoadError);
490
+ didError = true;
491
+ }
492
+
493
+ // If we errored, do not run the next matches' middleware
494
+ if (didError) {
495
+ break;
496
+ }
497
+ }
498
+ } catch (err) {
499
+ if (!opts?.preload) {
500
+ this.navigate(err);
501
+ }
502
+ throw err;
503
+ }
504
+ const validResolvedMatches = resolvedMatches.slice(0, firstBadMatchIndex);
505
+ const matchPromises = [];
506
+ validResolvedMatches.forEach((match, index) => {
507
+ matchPromises.push((async () => {
508
+ const parentMatchPromise = matchPromises[index - 1];
509
+ const route = this.getRoute(match.routeId);
510
+ if (match.isFetching || match.status === 'success' && !this.getIsInvalid({
511
+ matchId: match.id,
512
+ preload: opts?.preload
513
+ })) {
514
+ return this.getRouteMatch(match.id)?.loadPromise;
515
+ }
516
+ const fetchedAt = Date.now();
517
+ const checkLatest = () => {
518
+ const latest = this.getRouteMatch(match.id);
519
+ return latest && latest.fetchedAt !== fetchedAt ? latest.loadPromise : undefined;
520
+ };
521
+ const loadPromise = (async () => {
522
+ let latestPromise;
523
+ const componentsPromise = Promise.all(componentTypes.map(async type => {
524
+ const component = route.options[type];
525
+ if (component?.preload) {
526
+ await component.preload();
527
+ }
528
+ }));
529
+ const loaderPromise = route.options.loader?.({
530
+ ...match,
531
+ preload: !!opts?.preload,
532
+ parentMatchPromise
533
+ });
534
+ const handleError = err => {
535
+ if (isRedirect(err)) {
536
+ if (!opts?.preload) {
537
+ this.navigate(err);
538
+ }
539
+ return true;
540
+ }
541
+ return false;
542
+ };
543
+ try {
544
+ const [_, loader] = await Promise.all([componentsPromise, loaderPromise]);
545
+ if (latestPromise = checkLatest()) return await latestPromise;
546
+ this.setRouteMatchData(match.id, () => loader, opts);
547
+ } catch (err) {
548
+ if (latestPromise = checkLatest()) return await latestPromise;
549
+ if (handleError(err)) {
550
+ return;
551
+ }
552
+ const errorHandler = route.options.onLoadError ?? route.options.onError;
553
+ let caughtError = err;
554
+ try {
555
+ errorHandler?.(err);
556
+ } catch (errorHandlerErr) {
557
+ caughtError = errorHandlerErr;
558
+ if (handleError(errorHandlerErr)) {
559
+ return;
560
+ }
561
+ }
562
+ this.setRouteMatch(match.id, s => ({
563
+ ...s,
564
+ error: caughtError,
565
+ status: 'error',
566
+ isFetching: false,
567
+ updatedAt: Date.now()
568
+ }));
569
+ }
570
+ })();
571
+ this.setRouteMatch(match.id, s => ({
572
+ ...s,
573
+ status: s.status !== 'success' ? 'pending' : s.status,
574
+ isFetching: true,
575
+ loadPromise,
576
+ fetchedAt,
577
+ invalid: false
578
+ }));
579
+ await loadPromise;
580
+ })());
581
+ });
582
+ await Promise.all(matchPromises);
583
+ };
584
+ reload = () => {
585
+ return this.navigate({
586
+ fromCurrent: true,
587
+ replace: true,
588
+ search: true
589
+ });
590
+ };
591
+ resolvePath = (from, path$1) => {
592
+ return path.resolvePath(this.basepath, from, path.cleanPath(path$1));
593
+ };
594
+ navigate = async ({
595
+ from,
596
+ to = '',
597
+ search,
598
+ hash,
599
+ replace,
600
+ params
601
+ }) => {
602
+ // If this link simply reloads the current route,
603
+ // make sure it has a new key so it will trigger a data refresh
604
+
605
+ // If this `to` is a valid external URL, return
606
+ // null for LinkUtils
607
+ const toString = String(to);
608
+ const fromString = typeof from === 'undefined' ? from : String(from);
609
+ let isExternal;
610
+ try {
611
+ new URL(`${toString}`);
612
+ isExternal = true;
613
+ } catch (e) {}
614
+ invariant__default["default"](!isExternal, 'Attempting to navigate to external url with this.navigate!');
615
+ return this.#commitLocation({
616
+ from: fromString,
617
+ to: toString,
618
+ search,
619
+ hash,
620
+ replace,
621
+ params
622
+ });
623
+ };
624
+ matchRoute = (location, opts) => {
625
+ location = {
626
+ ...location,
627
+ to: location.to ? this.resolvePath(location.from ?? '', location.to) : undefined
628
+ };
629
+ const next = this.buildNext(location);
630
+ if (opts?.pending && this.state.status !== 'pending') {
631
+ return false;
632
+ }
633
+ const baseLocation = opts?.pending ? this.state.location : this.state.resolvedLocation;
634
+ if (!baseLocation) {
635
+ return false;
636
+ }
637
+ const match = path.matchPathname(this.basepath, baseLocation.pathname, {
638
+ ...opts,
639
+ to: next.pathname
640
+ });
641
+ if (!match) {
642
+ return false;
643
+ }
644
+ if (opts?.includeSearch ?? true) {
645
+ return utils.partialDeepEqual(baseLocation.search, next.search) ? match : false;
646
+ }
647
+ return match;
648
+ };
649
+ buildLink = ({
650
+ from,
651
+ to = '.',
652
+ search,
653
+ params,
654
+ hash,
655
+ target,
656
+ replace,
657
+ activeOptions,
658
+ preload,
659
+ preloadDelay: userPreloadDelay,
660
+ disabled
661
+ }) => {
662
+ // If this link simply reloads the current route,
663
+ // make sure it has a new key so it will trigger a data refresh
664
+
665
+ // If this `to` is a valid external URL, return
666
+ // null for LinkUtils
667
+
668
+ try {
669
+ new URL(`${to}`);
670
+ return {
671
+ type: 'external',
672
+ href: to
673
+ };
674
+ } catch (e) {}
675
+ const nextOpts = {
676
+ from,
677
+ to,
678
+ search,
679
+ params,
680
+ hash,
681
+ replace
682
+ };
683
+ const next = this.buildNext(nextOpts);
684
+ preload = preload ?? this.options.defaultPreload;
685
+ const preloadDelay = userPreloadDelay ?? this.options.defaultPreloadDelay ?? 0;
686
+
687
+ // Compare path/hash for matches
688
+ const currentPathSplit = this.state.location.pathname.split('/');
689
+ const nextPathSplit = next.pathname.split('/');
690
+ const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
691
+ // Combine the matches based on user options
692
+ const pathTest = activeOptions?.exact ? this.state.location.pathname === next.pathname : pathIsFuzzyEqual;
693
+ const hashTest = activeOptions?.includeHash ? this.state.location.hash === next.hash : true;
694
+ const searchTest = activeOptions?.includeSearch ?? true ? utils.partialDeepEqual(this.state.location.search, next.search) : true;
695
+
696
+ // The final "active" test
697
+ const isActive = pathTest && hashTest && searchTest;
698
+
699
+ // The click handler
700
+ const handleClick = e => {
701
+ if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
702
+ e.preventDefault();
703
+
704
+ // All is well? Navigate!
705
+ this.#commitLocation(nextOpts);
706
+ }
707
+ };
708
+
709
+ // The click handler
710
+ const handleFocus = e => {
711
+ if (preload) {
712
+ this.preloadRoute(nextOpts).catch(err => {
713
+ console.warn(err);
714
+ console.warn('Error preloading route! ☝️');
715
+ });
716
+ }
717
+ };
718
+ const handleTouchStart = e => {
719
+ this.preloadRoute(nextOpts).catch(err => {
720
+ console.warn(err);
721
+ console.warn('Error preloading route! ☝️');
722
+ });
723
+ };
724
+ const handleEnter = e => {
725
+ const target = e.target || {};
726
+ if (preload) {
727
+ if (target.preloadTimeout) {
728
+ return;
729
+ }
730
+ target.preloadTimeout = setTimeout(() => {
731
+ target.preloadTimeout = null;
732
+ this.preloadRoute(nextOpts).catch(err => {
733
+ console.warn(err);
734
+ console.warn('Error preloading route! ☝️');
735
+ });
736
+ }, preloadDelay);
737
+ }
738
+ };
739
+ const handleLeave = e => {
740
+ const target = e.target || {};
741
+ if (target.preloadTimeout) {
742
+ clearTimeout(target.preloadTimeout);
743
+ target.preloadTimeout = null;
744
+ }
745
+ };
746
+ return {
747
+ type: 'internal',
748
+ next,
749
+ handleFocus,
750
+ handleClick,
751
+ handleEnter,
752
+ handleLeave,
753
+ handleTouchStart,
754
+ isActive,
755
+ disabled
756
+ };
757
+ };
758
+ dehydrate = () => {
759
+ return {
760
+ state: utils.pick(this.state, ['location', 'status', 'lastUpdated'])
761
+ };
762
+ };
763
+ hydrate = async __do_not_use_server_ctx => {
764
+ let _ctx = __do_not_use_server_ctx;
765
+ // Client hydrates from window
766
+ if (typeof document !== 'undefined') {
767
+ _ctx = window.__TSR_DEHYDRATED__;
768
+ }
769
+ invariant__default["default"](_ctx, 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?');
770
+ const ctx = _ctx;
771
+ this.dehydratedData = ctx.payload;
772
+ this.options.hydrate?.(ctx.payload);
773
+ this.__store.setState(s => {
774
+ return {
775
+ ...s,
776
+ ...ctx.router.state,
777
+ resolvedLocation: ctx.router.state.location
778
+ };
779
+ });
780
+ await this.load();
781
+ return;
782
+ };
783
+ injectedHtml = [];
784
+ injectHtml = async html => {
785
+ this.injectedHtml.push(html);
786
+ };
787
+ dehydrateData = (key, getData) => {
788
+ if (typeof document === 'undefined') {
789
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key);
790
+ this.injectHtml(async () => {
791
+ const id = `__TSR_DEHYDRATED__${strKey}`;
792
+ const data = typeof getData === 'function' ? await getData() : getData;
793
+ return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${escapeJSON(strKey)}"] = ${JSON.stringify(data)}
794
+ ;(() => {
795
+ var el = document.getElementById('${id}')
796
+ el.parentElement.removeChild(el)
797
+ })()
798
+ </script>`;
799
+ });
800
+ return () => this.hydrateData(key);
801
+ }
802
+ return () => undefined;
803
+ };
804
+ hydrateData = key => {
805
+ if (typeof document !== 'undefined') {
806
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key);
807
+ return window[`__TSR_DEHYDRATED__${strKey}`];
808
+ }
809
+ return undefined;
810
+ };
811
+
812
+ // resolveMatchPromise = (matchId: string, key: string, value: any) => {
813
+ // this.state.matches
814
+ // .find((d) => d.id === matchId)
815
+ // ?.__promisesByKey[key]?.resolve(value)
816
+ // }
817
+
818
+ #buildRouteTree = routeTree => {
819
+ this.routeTree = routeTree;
820
+ this.routesById = {};
821
+ this.routesByPath = {};
822
+ this.flatRoutes = [];
823
+ const recurseRoutes = routes => {
824
+ routes.forEach((route, i) => {
825
+ route.init({
826
+ originalIndex: i,
827
+ router: this
828
+ });
829
+ const existingRoute = this.routesById[route.id];
830
+ invariant__default["default"](!existingRoute, `Duplicate routes found with id: ${String(route.id)}`);
831
+ this.routesById[route.id] = route;
832
+ if (!route.isRoot && route.path) {
833
+ const trimmedFullPath = path.trimPathRight(route.fullPath);
834
+ if (!this.routesByPath[trimmedFullPath] || route.fullPath.endsWith('/')) {
835
+ this.routesByPath[trimmedFullPath] = route;
836
+ }
837
+ }
838
+ const children = route.children;
839
+ if (children?.length) {
840
+ recurseRoutes(children);
841
+ }
842
+ });
843
+ };
844
+ recurseRoutes([routeTree]);
845
+ this.flatRoutes = Object.values(this.routesByPath).map((d, i) => {
846
+ const trimmed = path.trimPath(d.fullPath);
847
+ const parsed = path.parsePathname(trimmed);
848
+ while (parsed.length > 1 && parsed[0]?.value === '/') {
849
+ parsed.shift();
850
+ }
851
+ const score = parsed.map(d => {
852
+ if (d.type === 'param') {
853
+ return 0.5;
854
+ }
855
+ if (d.type === 'wildcard') {
856
+ return 0.25;
857
+ }
858
+ return 1;
859
+ });
860
+ return {
861
+ child: d,
862
+ trimmed,
863
+ parsed,
864
+ index: i,
865
+ score
866
+ };
867
+ }).sort((a, b) => {
868
+ let isIndex = a.trimmed === '/' ? 1 : b.trimmed === '/' ? -1 : 0;
869
+ if (isIndex !== 0) return isIndex;
870
+ const length = Math.min(a.score.length, b.score.length);
871
+
872
+ // Sort by length of score
873
+ if (a.score.length !== b.score.length) {
874
+ return b.score.length - a.score.length;
875
+ }
876
+
877
+ // Sort by min available score
878
+ for (let i = 0; i < length; i++) {
879
+ if (a.score[i] !== b.score[i]) {
880
+ return b.score[i] - a.score[i];
881
+ }
882
+ }
883
+
884
+ // Sort by min available parsed value
885
+ for (let i = 0; i < length; i++) {
886
+ if (a.parsed[i].value !== b.parsed[i].value) {
887
+ return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
888
+ }
889
+ }
890
+
891
+ // Sort by length of trimmed full path
892
+ if (a.trimmed !== b.trimmed) {
893
+ return a.trimmed > b.trimmed ? 1 : -1;
894
+ }
895
+
896
+ // Sort by original index
897
+ return a.index - b.index;
898
+ }).map((d, i) => {
899
+ d.child.rank = i;
900
+ return d.child;
901
+ });
902
+ };
903
+ #parseLocation = previousLocation => {
904
+ let {
905
+ pathname,
906
+ search,
907
+ hash,
908
+ state
909
+ } = this.history.location;
910
+ const parsedSearch = this.options.parseSearch(search);
911
+ return {
912
+ pathname: pathname,
913
+ searchStr: search,
914
+ search: utils.replaceEqualDeep(previousLocation?.search, parsedSearch),
915
+ hash: hash.split('#').reverse()[0] ?? '',
916
+ href: `${pathname}${search}${hash}`,
917
+ state: state,
918
+ key: state?.key || '__init__'
919
+ };
920
+ };
921
+ #buildLocation = (dest = {}) => {
922
+ dest.fromCurrent = dest.fromCurrent ?? dest.to === '';
923
+ const fromPathname = dest.fromCurrent ? this.state.location.pathname : dest.from ?? this.state.location.pathname;
924
+ let pathname = path.resolvePath(this.basepath ?? '/', fromPathname, `${dest.to ?? ''}`);
925
+ const fromMatches = this.matchRoutes(this.state.location.pathname, this.state.location.search);
926
+ const prevParams = {
927
+ ...utils.last(fromMatches)?.params
928
+ };
929
+ let nextParams = (dest.params ?? true) === true ? prevParams : utils.functionalUpdate(dest.params, prevParams);
930
+ if (nextParams) {
931
+ dest.__matches?.map(d => this.getRoute(d.routeId).options.stringifyParams).filter(Boolean).forEach(fn => {
932
+ nextParams = {
933
+ ...nextParams,
934
+ ...fn(nextParams)
935
+ };
936
+ });
937
+ }
938
+ pathname = path.interpolatePath(pathname, nextParams ?? {});
939
+ const preSearchFilters = dest.__matches?.map(match => this.getRoute(match.routeId).options.preSearchFilters ?? []).flat().filter(Boolean) ?? [];
940
+ const postSearchFilters = dest.__matches?.map(match => this.getRoute(match.routeId).options.postSearchFilters ?? []).flat().filter(Boolean) ?? [];
941
+
942
+ // Pre filters first
943
+ const preFilteredSearch = preSearchFilters?.length ? preSearchFilters?.reduce((prev, next) => next(prev), this.state.location.search) : this.state.location.search;
944
+
945
+ // Then the link/navigate function
946
+ const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
947
+ : dest.search ? utils.functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
948
+ : preSearchFilters?.length ? preFilteredSearch // Preserve resolvedFrom filters
949
+ : {};
950
+
951
+ // Then post filters
952
+ const postFilteredSearch = postSearchFilters?.length ? postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
953
+ const search = utils.replaceEqualDeep(this.state.location.search, postFilteredSearch);
954
+ const searchStr = this.options.stringifySearch(search);
955
+ const hash = dest.hash === true ? this.state.location.hash : utils.functionalUpdate(dest.hash, this.state.location.hash);
956
+ const hashStr = hash ? `#${hash}` : '';
957
+ const nextState = dest.state === true ? this.state.location.state : utils.functionalUpdate(dest.state, this.state.location.state);
958
+ return {
959
+ pathname,
960
+ search,
961
+ searchStr,
962
+ state: nextState,
963
+ hash,
964
+ href: this.history.createHref(`${pathname}${searchStr}${hashStr}`),
965
+ key: dest.key
966
+ };
967
+ };
968
+ #commitLocation = async location => {
969
+ const next = this.buildNext(location);
970
+ const id = '' + Date.now() + Math.random();
971
+ if (this.navigateTimeout) clearTimeout(this.navigateTimeout);
972
+ let nextAction = 'replace';
973
+ if (!location.replace) {
974
+ nextAction = 'push';
975
+ }
976
+ const isSameUrl = this.state.location.href === next.href;
977
+ if (isSameUrl && !next.key) {
978
+ nextAction = 'replace';
979
+ }
980
+ const href = `${next.pathname}${next.searchStr}${next.hash ? `#${next.hash}` : ''}`;
981
+ this.history[nextAction === 'push' ? 'push' : 'replace'](href, {
982
+ id,
983
+ ...next.state
984
+ });
985
+ return this.latestLoadPromise;
986
+ };
987
+ getRouteMatch = id => {
988
+ return this.state.matchesById[id];
989
+ };
990
+ setRouteMatch = (id, updater) => {
991
+ this.__store.setState(prev => ({
992
+ ...prev,
993
+ matchesById: {
994
+ ...prev.matchesById,
995
+ [id]: updater(prev.matchesById[id])
996
+ }
997
+ }));
998
+ };
999
+ setRouteMatchData = (id, updater, opts) => {
1000
+ const match = this.getRouteMatch(id);
1001
+ if (!match) return;
1002
+ const route = this.getRoute(match.routeId);
1003
+ const updatedAt = opts?.updatedAt ?? Date.now();
1004
+ const preloadInvalidAt = updatedAt + (opts?.maxAge ?? route.options.preloadMaxAge ?? this.options.defaultPreloadMaxAge ?? 5000);
1005
+ const invalidAt = updatedAt + (opts?.maxAge ?? route.options.maxAge ?? this.options.defaultMaxAge ?? Infinity);
1006
+ this.setRouteMatch(id, s => ({
1007
+ ...s,
1008
+ error: undefined,
1009
+ status: 'success',
1010
+ isFetching: false,
1011
+ updatedAt: Date.now(),
1012
+ loaderData: utils.functionalUpdate(updater, s.loaderData),
1013
+ preloadInvalidAt,
1014
+ invalidAt
1015
+ }));
1016
+ if (this.state.matches.find(d => d.id === id)) ;
1017
+ };
1018
+ invalidate = async opts => {
1019
+ if (opts?.matchId) {
1020
+ this.setRouteMatch(opts.matchId, s => ({
1021
+ ...s,
1022
+ invalid: true
1023
+ }));
1024
+ const matchIndex = this.state.matches.findIndex(d => d.id === opts.matchId);
1025
+ const childMatch = this.state.matches[matchIndex + 1];
1026
+ if (childMatch) {
1027
+ return this.invalidate({
1028
+ matchId: childMatch.id,
1029
+ reload: false
1030
+ });
1031
+ }
1032
+ } else {
1033
+ this.__store.batch(() => {
1034
+ Object.values(this.state.matchesById).forEach(match => {
1035
+ this.setRouteMatch(match.id, s => ({
1036
+ ...s,
1037
+ invalid: true
1038
+ }));
1039
+ });
1040
+ });
1041
+ }
1042
+ if (opts?.reload ?? true) {
1043
+ return this.reload();
1044
+ }
1045
+ };
1046
+ getIsInvalid = opts => {
1047
+ if (!opts?.matchId) {
1048
+ return !!this.state.matches.find(d => this.getIsInvalid({
1049
+ matchId: d.id,
1050
+ preload: opts?.preload
1051
+ }));
1052
+ }
1053
+ const match = this.getRouteMatch(opts?.matchId);
1054
+ if (!match) {
1055
+ return false;
1056
+ }
1057
+ const now = Date.now();
1058
+ return match.invalid || (opts?.preload ? match.preloadInvalidAt : match.invalidAt) < now;
1059
+ };
1060
+ }
1061
+
1062
+ // Detect if we're in the DOM
1063
+ const isServer = typeof window === 'undefined' || !window.document.createElement;
1064
+ function getInitialRouterState() {
1065
+ return {
1066
+ status: 'idle',
1067
+ isFetching: false,
1068
+ resolvedLocation: null,
1069
+ location: null,
1070
+ matchesById: {},
1071
+ matchIds: [],
1072
+ pendingMatchIds: [],
1073
+ matches: [],
1074
+ pendingMatches: [],
1075
+ lastUpdated: Date.now()
1076
+ };
1077
+ }
1078
+ function isCtrlEvent(e) {
1079
+ return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
1080
+ }
1081
+ function redirect(opts) {
1082
+ opts.isRedirect = true;
1083
+ return opts;
1084
+ }
1085
+ function isRedirect(obj) {
1086
+ return !!obj?.isRedirect;
1087
+ }
1088
+ class SearchParamError extends Error {}
1089
+ class PathParamError extends Error {}
1090
+ function escapeJSON(jsonString) {
1091
+ return jsonString.replace(/\\/g, '\\\\') // Escape backslashes
1092
+ .replace(/'/g, "\\'") // Escape single quotes
1093
+ .replace(/"/g, '\\"'); // Escape double quotes
1094
+ }
1095
+
1096
+ // A function that takes an import() argument which is a function and returns a new function that will
1097
+ // proxy arguments from the caller to the imported function, retaining all type
1098
+ // information along the way
1099
+ function lazyFn(fn, key) {
1100
+ return async (...args) => {
1101
+ const imported = await fn();
1102
+ return imported[key || 'default'](...args);
1103
+ };
1104
+ }
1105
+
1106
+ exports.PathParamError = PathParamError;
1107
+ exports.Router = Router;
1108
+ exports.SearchParamError = SearchParamError;
1109
+ exports.componentTypes = componentTypes;
1110
+ exports.isRedirect = isRedirect;
1111
+ exports.lazyFn = lazyFn;
1112
+ exports.redirect = redirect;
1113
+ //# sourceMappingURL=router.js.map