@tanstack/react-router 0.0.1-beta.28 → 0.0.1-beta.280

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 (106) hide show
  1. package/LICENSE +21 -0
  2. package/build/cjs/CatchBoundary.js +128 -0
  3. package/build/cjs/CatchBoundary.js.map +1 -0
  4. package/build/cjs/Matches.js +233 -0
  5. package/build/cjs/Matches.js.map +1 -0
  6. package/build/cjs/RouterProvider.js +170 -0
  7. package/build/cjs/RouterProvider.js.map +1 -0
  8. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +2 -22
  9. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +1 -1
  10. package/build/cjs/awaited.js +43 -0
  11. package/build/cjs/awaited.js.map +1 -0
  12. package/build/cjs/defer.js +37 -0
  13. package/build/cjs/defer.js.map +1 -0
  14. package/build/cjs/fileRoute.js +27 -0
  15. package/build/cjs/fileRoute.js.map +1 -0
  16. package/build/cjs/index.js +130 -0
  17. package/build/cjs/index.js.map +1 -0
  18. package/build/cjs/lazyRouteComponent.js +54 -0
  19. package/build/cjs/lazyRouteComponent.js.map +1 -0
  20. package/build/cjs/link.js +223 -0
  21. package/build/cjs/link.js.map +1 -0
  22. package/build/cjs/path.js +214 -0
  23. package/build/cjs/path.js.map +1 -0
  24. package/build/cjs/qss.js +63 -0
  25. package/build/cjs/qss.js.map +1 -0
  26. package/build/cjs/redirects.js +28 -0
  27. package/build/cjs/redirects.js.map +1 -0
  28. package/build/cjs/route.js +191 -0
  29. package/build/cjs/route.js.map +1 -0
  30. package/build/cjs/router.js +1049 -0
  31. package/build/cjs/router.js.map +1 -0
  32. package/build/cjs/scroll-restoration.js +202 -0
  33. package/build/cjs/scroll-restoration.js.map +1 -0
  34. package/build/cjs/searchParams.js +81 -0
  35. package/build/cjs/searchParams.js.map +1 -0
  36. package/build/cjs/useBlocker.js +55 -0
  37. package/build/cjs/useBlocker.js.map +1 -0
  38. package/build/cjs/useNavigate.js +86 -0
  39. package/build/cjs/useNavigate.js.map +1 -0
  40. package/build/cjs/useParams.js +26 -0
  41. package/build/cjs/useParams.js.map +1 -0
  42. package/build/cjs/useSearch.js +25 -0
  43. package/build/cjs/useSearch.js.map +1 -0
  44. package/build/cjs/utils.js +239 -0
  45. package/build/cjs/utils.js.map +1 -0
  46. package/build/esm/index.js +2255 -2571
  47. package/build/esm/index.js.map +1 -1
  48. package/build/stats-html.html +3498 -2694
  49. package/build/stats-react.json +1204 -44
  50. package/build/types/CatchBoundary.d.ts +36 -0
  51. package/build/types/Matches.d.ts +62 -0
  52. package/build/types/RouterProvider.d.ts +35 -0
  53. package/build/types/awaited.d.ts +9 -0
  54. package/build/types/defer.d.ts +19 -0
  55. package/build/types/fileRoute.d.ts +38 -0
  56. package/build/types/history.d.ts +7 -0
  57. package/build/types/index.d.ts +27 -114
  58. package/build/types/lazyRouteComponent.d.ts +2 -0
  59. package/build/types/link.d.ts +91 -0
  60. package/build/types/location.d.ts +12 -0
  61. package/build/types/path.d.ts +17 -0
  62. package/build/types/qss.d.ts +2 -0
  63. package/build/types/redirects.d.ts +11 -0
  64. package/build/types/route.d.ts +282 -0
  65. package/build/types/routeInfo.d.ts +22 -0
  66. package/build/types/router.d.ts +188 -0
  67. package/build/types/scroll-restoration.d.ts +18 -0
  68. package/build/types/searchParams.d.ts +7 -0
  69. package/build/types/useBlocker.d.ts +9 -0
  70. package/build/types/useNavigate.d.ts +19 -0
  71. package/build/types/useParams.d.ts +7 -0
  72. package/build/types/useSearch.d.ts +7 -0
  73. package/build/types/utils.d.ts +66 -0
  74. package/build/umd/index.development.js +2858 -2548
  75. package/build/umd/index.development.js.map +1 -1
  76. package/build/umd/index.production.js +4 -4
  77. package/build/umd/index.production.js.map +1 -1
  78. package/package.json +11 -10
  79. package/src/CatchBoundary.tsx +101 -0
  80. package/src/Matches.tsx +421 -0
  81. package/src/RouterProvider.tsx +252 -0
  82. package/src/awaited.tsx +40 -0
  83. package/src/defer.ts +55 -0
  84. package/src/fileRoute.ts +152 -0
  85. package/src/history.ts +8 -0
  86. package/src/index.tsx +28 -761
  87. package/src/lazyRouteComponent.tsx +33 -0
  88. package/src/link.tsx +598 -0
  89. package/src/location.ts +13 -0
  90. package/src/path.ts +261 -0
  91. package/src/qss.ts +53 -0
  92. package/src/redirects.ts +39 -0
  93. package/src/route.ts +872 -0
  94. package/src/routeInfo.ts +70 -0
  95. package/src/router.ts +1630 -0
  96. package/src/scroll-restoration.tsx +230 -0
  97. package/src/searchParams.ts +79 -0
  98. package/src/useBlocker.tsx +27 -0
  99. package/src/useNavigate.tsx +111 -0
  100. package/src/useParams.tsx +25 -0
  101. package/src/useSearch.tsx +25 -0
  102. package/src/utils.ts +350 -0
  103. package/build/cjs/react-router/src/index.js +0 -508
  104. package/build/cjs/react-router/src/index.js.map +0 -1
  105. package/build/cjs/router-core/build/esm/index.js +0 -2530
  106. package/build/cjs/router-core/build/esm/index.js.map +0 -1
@@ -0,0 +1,1049 @@
1
+ /**
2
+ * @tanstack/react-router/src/index.tsx
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
+ var history = require('@tanstack/history');
14
+ var store = require('@tanstack/store');
15
+ var searchParams = require('./searchParams.js');
16
+ var utils = require('./utils.js');
17
+ var RouterProvider = require('./RouterProvider.js');
18
+ var path = require('./path.js');
19
+ var invariant = require('tiny-invariant');
20
+ var redirects = require('./redirects.js');
21
+
22
+ // import warning from 'tiny-warning'
23
+
24
+ //
25
+
26
+ const componentTypes = ['component', 'errorComponent', 'pendingComponent'];
27
+ class Router {
28
+ // Option-independent properties
29
+ tempLocationKey = `${Math.round(Math.random() * 10000000)}`;
30
+ resetNextScroll = true;
31
+ navigateTimeout = null;
32
+ latestLoadPromise = Promise.resolve();
33
+ subscribers = new Set();
34
+ injectedHtml = [];
35
+
36
+ // Must build in constructor
37
+
38
+ constructor(options) {
39
+ this.update({
40
+ defaultPreloadDelay: 50,
41
+ defaultPendingMs: 1000,
42
+ defaultPendingMinMs: 500,
43
+ context: undefined,
44
+ ...options,
45
+ stringifySearch: options?.stringifySearch ?? searchParams.defaultStringifySearch,
46
+ parseSearch: options?.parseSearch ?? searchParams.defaultParseSearch
47
+ });
48
+ }
49
+
50
+ // These are default implementations that can optionally be overridden
51
+ // by the router provider once rendered. We provide these so that the
52
+ // router can be used in a non-react environment if necessary
53
+ startReactTransition = fn => fn();
54
+ update = newOptions => {
55
+ this.options = {
56
+ ...this.options,
57
+ ...newOptions
58
+ };
59
+ this.basepath = `/${path.trimPath(newOptions.basepath ?? '') ?? ''}`;
60
+ if (!this.history || this.options.history && this.options.history !== this.history) {
61
+ this.history = this.options.history ?? (typeof document !== 'undefined' ? history.createBrowserHistory() : history.createMemoryHistory());
62
+ this.latestLocation = this.parseLocation();
63
+ }
64
+ if (this.options.routeTree !== this.routeTree) {
65
+ this.routeTree = this.options.routeTree;
66
+ this.buildRouteTree();
67
+ }
68
+ if (!this.__store) {
69
+ this.__store = new store.Store(getInitialRouterState(this.latestLocation), {
70
+ onUpdate: () => {
71
+ this.__store.state = {
72
+ ...this.state,
73
+ status: this.state.isTransitioning || this.state.isLoading ? 'pending' : 'idle'
74
+ };
75
+ }
76
+ });
77
+ }
78
+ };
79
+ get state() {
80
+ return this.__store.state;
81
+ }
82
+ buildRouteTree = () => {
83
+ this.routesById = {};
84
+ this.routesByPath = {};
85
+ const notFoundRoute = this.options.notFoundRoute;
86
+ if (notFoundRoute) {
87
+ notFoundRoute.init({
88
+ originalIndex: 99999999999
89
+ });
90
+ this.routesById[notFoundRoute.id] = notFoundRoute;
91
+ }
92
+ const recurseRoutes = childRoutes => {
93
+ childRoutes.forEach((childRoute, i) => {
94
+ childRoute.init({
95
+ originalIndex: i
96
+ });
97
+ const existingRoute = this.routesById[childRoute.id];
98
+ invariant(!existingRoute, `Duplicate routes found with id: ${String(childRoute.id)}`);
99
+ this.routesById[childRoute.id] = childRoute;
100
+ if (!childRoute.isRoot && childRoute.path) {
101
+ const trimmedFullPath = path.trimPathRight(childRoute.fullPath);
102
+ if (!this.routesByPath[trimmedFullPath] || childRoute.fullPath.endsWith('/')) {
103
+ this.routesByPath[trimmedFullPath] = childRoute;
104
+ }
105
+ }
106
+ const children = childRoute.children;
107
+ if (children?.length) {
108
+ recurseRoutes(children);
109
+ }
110
+ });
111
+ };
112
+ recurseRoutes([this.routeTree]);
113
+ const scoredRoutes = [];
114
+ Object.values(this.routesById).forEach((d, i) => {
115
+ if (d.isRoot || !d.path) {
116
+ return;
117
+ }
118
+ const trimmed = path.trimPathLeft(d.fullPath);
119
+ const parsed = path.parsePathname(trimmed);
120
+ while (parsed.length > 1 && parsed[0]?.value === '/') {
121
+ parsed.shift();
122
+ }
123
+ const scores = parsed.map(d => {
124
+ if (d.value === '/') {
125
+ return 0.75;
126
+ }
127
+ if (d.type === 'param') {
128
+ return 0.5;
129
+ }
130
+ if (d.type === 'wildcard') {
131
+ return 0.25;
132
+ }
133
+ return 1;
134
+ });
135
+ scoredRoutes.push({
136
+ child: d,
137
+ trimmed,
138
+ parsed,
139
+ index: i,
140
+ scores
141
+ });
142
+ });
143
+ this.flatRoutes = scoredRoutes.sort((a, b) => {
144
+ const minLength = Math.min(a.scores.length, b.scores.length);
145
+
146
+ // Sort by min available score
147
+ for (let i = 0; i < minLength; i++) {
148
+ if (a.scores[i] !== b.scores[i]) {
149
+ return b.scores[i] - a.scores[i];
150
+ }
151
+ }
152
+
153
+ // Sort by length of score
154
+ if (a.scores.length !== b.scores.length) {
155
+ return b.scores.length - a.scores.length;
156
+ }
157
+
158
+ // Sort by min available parsed value
159
+ for (let i = 0; i < minLength; i++) {
160
+ if (a.parsed[i].value !== b.parsed[i].value) {
161
+ return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
162
+ }
163
+ }
164
+
165
+ // Sort by original index
166
+ return a.index - b.index;
167
+ }).map((d, i) => {
168
+ d.child.rank = i;
169
+ return d.child;
170
+ });
171
+ };
172
+ subscribe = (eventType, fn) => {
173
+ const listener = {
174
+ eventType,
175
+ fn
176
+ };
177
+ this.subscribers.add(listener);
178
+ return () => {
179
+ this.subscribers.delete(listener);
180
+ };
181
+ };
182
+ emit = routerEvent => {
183
+ this.subscribers.forEach(listener => {
184
+ if (listener.eventType === routerEvent.type) {
185
+ listener.fn(routerEvent);
186
+ }
187
+ });
188
+ };
189
+ checkLatest = promise => {
190
+ return this.latestLoadPromise !== promise ? this.latestLoadPromise : undefined;
191
+ };
192
+ parseLocation = previousLocation => {
193
+ const parse = ({
194
+ pathname,
195
+ search,
196
+ hash,
197
+ state
198
+ }) => {
199
+ const parsedSearch = this.options.parseSearch(search);
200
+ return {
201
+ pathname: pathname,
202
+ searchStr: search,
203
+ search: utils.replaceEqualDeep(previousLocation?.search, parsedSearch),
204
+ hash: hash.split('#').reverse()[0] ?? '',
205
+ href: `${pathname}${search}${hash}`,
206
+ state: utils.replaceEqualDeep(previousLocation?.state, state)
207
+ };
208
+ };
209
+ const location = parse(this.history.location);
210
+ let {
211
+ __tempLocation,
212
+ __tempKey
213
+ } = location.state;
214
+ if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
215
+ // Sync up the location keys
216
+ const parsedTempLocation = parse(__tempLocation);
217
+ parsedTempLocation.state.key = location.state.key;
218
+ delete parsedTempLocation.state.__tempLocation;
219
+ return {
220
+ ...parsedTempLocation,
221
+ maskedLocation: location
222
+ };
223
+ }
224
+ return location;
225
+ };
226
+ resolvePathWithBase = (from, path$1) => {
227
+ return path.resolvePath(this.basepath, from, path.cleanPath(path$1));
228
+ };
229
+ get looseRoutesById() {
230
+ return this.routesById;
231
+ }
232
+ matchRoutes = (pathname, locationSearch, opts) => {
233
+ let routeParams = {};
234
+ let foundRoute = this.flatRoutes.find(route => {
235
+ const matchedParams = path.matchPathname(this.basepath, path.trimPathRight(pathname), {
236
+ to: route.fullPath,
237
+ caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive,
238
+ fuzzy: true
239
+ });
240
+ if (matchedParams) {
241
+ routeParams = matchedParams;
242
+ return true;
243
+ }
244
+ return false;
245
+ });
246
+ let routeCursor = foundRoute || this.routesById['__root__'];
247
+ let matchedRoutes = [routeCursor];
248
+
249
+ // Check to see if the route needs a 404 entry
250
+ if (
251
+ // If we found a route, and it's not an index route and we have left over path
252
+ (foundRoute ? foundRoute.path !== '/' && routeParams['**'] :
253
+ // Or if we didn't find a route and we have left over path
254
+ path.trimPathRight(pathname)) &&
255
+ // And we have a 404 route configured
256
+ this.options.notFoundRoute) {
257
+ matchedRoutes.push(this.options.notFoundRoute);
258
+ }
259
+ while (routeCursor?.parentRoute) {
260
+ routeCursor = routeCursor.parentRoute;
261
+ if (routeCursor) matchedRoutes.unshift(routeCursor);
262
+ }
263
+
264
+ // Existing matches are matches that are already loaded along with
265
+ // pending matches that are still loading
266
+
267
+ const parseErrors = matchedRoutes.map(route => {
268
+ let parsedParamsError;
269
+ if (route.options.parseParams) {
270
+ try {
271
+ const parsedParams = route.options.parseParams(routeParams);
272
+ // Add the parsed params to the accumulated params bag
273
+ Object.assign(routeParams, parsedParams);
274
+ } catch (err) {
275
+ parsedParamsError = new PathParamError(err.message, {
276
+ cause: err
277
+ });
278
+ if (opts?.throwOnError) {
279
+ throw parsedParamsError;
280
+ }
281
+ return parsedParamsError;
282
+ }
283
+ }
284
+ return;
285
+ });
286
+ const matches = [];
287
+ matchedRoutes.forEach((route, index) => {
288
+ // Take each matched route and resolve + validate its search params
289
+ // This has to happen serially because each route's search params
290
+ // can depend on the parent route's search params
291
+ // It must also happen before we create the match so that we can
292
+ // pass the search params to the route's potential key function
293
+ // which is used to uniquely identify the route match in state
294
+
295
+ const parentMatch = matches[index - 1];
296
+ const [preMatchSearch, searchError] = (() => {
297
+ // Validate the search params and stabilize them
298
+ const parentSearch = parentMatch?.search ?? locationSearch;
299
+ try {
300
+ const validator = typeof route.options.validateSearch === 'object' ? route.options.validateSearch.parse : route.options.validateSearch;
301
+ let search = validator?.(parentSearch) ?? {};
302
+ return [{
303
+ ...parentSearch,
304
+ ...search
305
+ }, undefined];
306
+ } catch (err) {
307
+ const searchError = new SearchParamError(err.message, {
308
+ cause: err
309
+ });
310
+ if (opts?.throwOnError) {
311
+ throw searchError;
312
+ }
313
+ return [parentSearch, searchError];
314
+ }
315
+ })();
316
+
317
+ // This is where we need to call route.options.loaderDeps() to get any additional
318
+ // deps that the route's loader function might need to run. We need to do this
319
+ // before we create the match so that we can pass the deps to the route's
320
+ // potential key function which is used to uniquely identify the route match in state
321
+
322
+ const loaderDeps = route.options.loaderDeps?.({
323
+ search: preMatchSearch
324
+ }) ?? '';
325
+ const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : '';
326
+ const interpolatedPath = path.interpolatePath(route.fullPath, routeParams);
327
+ const matchId = path.interpolatePath(route.id, routeParams, true) + loaderDepsHash;
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 = RouterProvider.getRouteMatch(this.state, matchId);
333
+ const cause = this.state.matches.find(d => d.id === matchId) ? 'stay' : 'enter';
334
+
335
+ // Create a fresh route match
336
+ const hasLoaders = !!(route.options.loader || componentTypes.some(d => route.options[d]?.preload));
337
+ const match = existingMatch ? {
338
+ ...existingMatch,
339
+ cause
340
+ } : {
341
+ id: matchId,
342
+ routeId: route.id,
343
+ params: routeParams,
344
+ pathname: path.joinPaths([this.basepath, interpolatedPath]),
345
+ updatedAt: Date.now(),
346
+ search: {},
347
+ searchError: undefined,
348
+ status: hasLoaders ? 'pending' : 'success',
349
+ showPending: false,
350
+ isFetching: false,
351
+ error: undefined,
352
+ paramsError: parseErrors[index],
353
+ loadPromise: Promise.resolve(),
354
+ routeContext: undefined,
355
+ context: undefined,
356
+ abortController: new AbortController(),
357
+ fetchCount: 0,
358
+ cause,
359
+ loaderDeps
360
+ };
361
+
362
+ // Regardless of whether we're reusing an existing match or creating
363
+ // a new one, we need to update the match's search params
364
+ match.search = utils.replaceEqualDeep(match.search, preMatchSearch);
365
+ // And also update the searchError if there is one
366
+ match.searchError = searchError;
367
+ matches.push(match);
368
+ });
369
+ return matches;
370
+ };
371
+ cancelMatch = id => {
372
+ RouterProvider.getRouteMatch(this.state, id)?.abortController?.abort();
373
+ };
374
+ cancelMatches = () => {
375
+ this.state.pendingMatches?.forEach(match => {
376
+ this.cancelMatch(match.id);
377
+ });
378
+ };
379
+ buildLocation = opts => {
380
+ const build = (dest = {}, matches) => {
381
+ const from = this.latestLocation;
382
+ const fromSearch = (this.state.pendingMatches || this.state.matches).at(-1)?.search || from.search;
383
+ const fromPathname = dest.from ?? from.pathname;
384
+ let pathname = this.resolvePathWithBase(fromPathname, `${dest.to ?? ''}`);
385
+ const fromMatches = this.matchRoutes(fromPathname, fromSearch);
386
+ const stayingMatches = matches?.filter(d => fromMatches?.find(e => e.routeId === d.routeId));
387
+ const prevParams = {
388
+ ...utils.last(fromMatches)?.params
389
+ };
390
+ let nextParams = (dest.params ?? true) === true ? prevParams : utils.functionalUpdate(dest.params, prevParams);
391
+ if (nextParams) {
392
+ matches?.map(d => this.looseRoutesById[d.routeId].options.stringifyParams).filter(Boolean).forEach(fn => {
393
+ nextParams = {
394
+ ...nextParams,
395
+ ...fn(nextParams)
396
+ };
397
+ });
398
+ }
399
+ pathname = path.interpolatePath(pathname, nextParams ?? {});
400
+ const preSearchFilters = stayingMatches?.map(match => this.looseRoutesById[match.routeId].options.preSearchFilters ?? []).flat().filter(Boolean) ?? [];
401
+ const postSearchFilters = stayingMatches?.map(match => this.looseRoutesById[match.routeId].options.postSearchFilters ?? []).flat().filter(Boolean) ?? [];
402
+
403
+ // Pre filters first
404
+ const preFilteredSearch = preSearchFilters?.length ? preSearchFilters?.reduce((prev, next) => next(prev), fromSearch) : fromSearch;
405
+
406
+ // Then the link/navigate function
407
+ const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
408
+ : dest.search ? utils.functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
409
+ : preSearchFilters?.length ? preFilteredSearch // Preserve resolvedFrom filters
410
+ : {};
411
+
412
+ // Then post filters
413
+ const postFilteredSearch = postSearchFilters?.length ? postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
414
+ const search = utils.replaceEqualDeep(fromSearch, postFilteredSearch);
415
+ const searchStr = this.options.stringifySearch(search);
416
+ const hash = dest.hash === true ? from.hash : dest.hash ? utils.functionalUpdate(dest.hash, from.hash) : from.hash;
417
+ const hashStr = hash ? `#${hash}` : '';
418
+ let nextState = dest.state === true ? from.state : dest.state ? utils.functionalUpdate(dest.state, from.state) : from.state;
419
+ nextState = utils.replaceEqualDeep(from.state, nextState);
420
+ return {
421
+ pathname,
422
+ search,
423
+ searchStr,
424
+ state: nextState,
425
+ hash,
426
+ href: `${pathname}${searchStr}${hashStr}`,
427
+ unmaskOnReload: dest.unmaskOnReload
428
+ };
429
+ };
430
+ const buildWithMatches = (dest = {}, maskedDest) => {
431
+ let next = build(dest);
432
+ let maskedNext = maskedDest ? build(maskedDest) : undefined;
433
+ if (!maskedNext) {
434
+ let params = {};
435
+ let foundMask = this.options.routeMasks?.find(d => {
436
+ const match = path.matchPathname(this.basepath, next.pathname, {
437
+ to: d.from,
438
+ caseSensitive: false,
439
+ fuzzy: false
440
+ });
441
+ if (match) {
442
+ params = match;
443
+ return true;
444
+ }
445
+ return false;
446
+ });
447
+ if (foundMask) {
448
+ foundMask = {
449
+ ...foundMask,
450
+ from: path.interpolatePath(foundMask.from, params)
451
+ };
452
+ maskedDest = foundMask;
453
+ maskedNext = build(maskedDest);
454
+ }
455
+ }
456
+ const nextMatches = this.matchRoutes(next.pathname, next.search);
457
+ const maskedMatches = maskedNext ? this.matchRoutes(maskedNext.pathname, maskedNext.search) : undefined;
458
+ const maskedFinal = maskedNext ? build(maskedDest, maskedMatches) : undefined;
459
+ const final = build(dest, nextMatches);
460
+ if (maskedFinal) {
461
+ final.maskedLocation = maskedFinal;
462
+ }
463
+ return final;
464
+ };
465
+ if (opts.mask) {
466
+ return buildWithMatches(opts, {
467
+ ...utils.pick(opts, ['from']),
468
+ ...opts.mask
469
+ });
470
+ }
471
+ return buildWithMatches(opts);
472
+ };
473
+ commitLocation = async ({
474
+ startTransition,
475
+ ...next
476
+ }) => {
477
+ if (this.navigateTimeout) clearTimeout(this.navigateTimeout);
478
+ const isSameUrl = this.latestLocation.href === next.href;
479
+
480
+ // If the next urls are the same and we're not replacing,
481
+ // do nothing
482
+ if (!isSameUrl || !next.replace) {
483
+ let {
484
+ maskedLocation,
485
+ ...nextHistory
486
+ } = next;
487
+ if (maskedLocation) {
488
+ nextHistory = {
489
+ ...maskedLocation,
490
+ state: {
491
+ ...maskedLocation.state,
492
+ __tempKey: undefined,
493
+ __tempLocation: {
494
+ ...nextHistory,
495
+ search: nextHistory.searchStr,
496
+ state: {
497
+ ...nextHistory.state,
498
+ __tempKey: undefined,
499
+ __tempLocation: undefined,
500
+ key: undefined
501
+ }
502
+ }
503
+ }
504
+ };
505
+ if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
506
+ nextHistory.state.__tempKey = this.tempLocationKey;
507
+ }
508
+ }
509
+ const apply = () => {
510
+ this.history[next.replace ? 'replace' : 'push'](nextHistory.href, nextHistory.state);
511
+ };
512
+ if (startTransition ?? true) {
513
+ this.startReactTransition(apply);
514
+ } else {
515
+ apply();
516
+ }
517
+ }
518
+ this.resetNextScroll = next.resetScroll ?? true;
519
+ return this.latestLoadPromise;
520
+ };
521
+ buildAndCommitLocation = ({
522
+ replace,
523
+ resetScroll,
524
+ startTransition,
525
+ ...rest
526
+ } = {}) => {
527
+ const location = this.buildLocation(rest);
528
+ return this.commitLocation({
529
+ ...location,
530
+ startTransition,
531
+ replace,
532
+ resetScroll
533
+ });
534
+ };
535
+ navigate = ({
536
+ from,
537
+ to = '',
538
+ ...rest
539
+ }) => {
540
+ // If this link simply reloads the current route,
541
+ // make sure it has a new key so it will trigger a data refresh
542
+
543
+ // If this `to` is a valid external URL, return
544
+ // null for LinkUtils
545
+ const toString = String(to);
546
+ const fromString = typeof from === 'undefined' ? from : String(from);
547
+ let isExternal;
548
+ try {
549
+ new URL(`${toString}`);
550
+ isExternal = true;
551
+ } catch (e) {}
552
+ invariant(!isExternal, 'Attempting to navigate to external url with this.navigate!');
553
+ return this.buildAndCommitLocation({
554
+ ...rest,
555
+ from: fromString,
556
+ to: toString
557
+ });
558
+ };
559
+ loadMatches = async ({
560
+ checkLatest,
561
+ matches,
562
+ preload,
563
+ invalidate
564
+ }) => {
565
+ let latestPromise;
566
+ let firstBadMatchIndex;
567
+ const updateMatch = match => {
568
+ // const isPreload = this.state.cachedMatches.find((d) => d.id === match.id)
569
+ const isPending = this.state.pendingMatches?.find(d => d.id === match.id);
570
+ const isMatched = this.state.matches.find(d => d.id === match.id);
571
+ const matchesKey = isPending ? 'pendingMatches' : isMatched ? 'matches' : 'cachedMatches';
572
+ this.__store.setState(s => ({
573
+ ...s,
574
+ [matchesKey]: s[matchesKey]?.map(d => d.id === match.id ? match : d)
575
+ }));
576
+ };
577
+
578
+ // Check each match middleware to see if the route can be accessed
579
+ try {
580
+ for (let [index, match] of matches.entries()) {
581
+ const parentMatch = matches[index - 1];
582
+ const route = this.looseRoutesById[match.routeId];
583
+ const abortController = new AbortController();
584
+ const handleErrorAndRedirect = (err, code) => {
585
+ err.routerCode = code;
586
+ firstBadMatchIndex = firstBadMatchIndex ?? index;
587
+ if (redirects.isRedirect(err)) {
588
+ throw err;
589
+ }
590
+ try {
591
+ route.options.onError?.(err);
592
+ } catch (errorHandlerErr) {
593
+ err = errorHandlerErr;
594
+ if (redirects.isRedirect(errorHandlerErr)) {
595
+ throw errorHandlerErr;
596
+ }
597
+ }
598
+ matches[index] = match = {
599
+ ...match,
600
+ error: err,
601
+ status: 'error',
602
+ updatedAt: Date.now(),
603
+ abortController: new AbortController()
604
+ };
605
+ };
606
+ try {
607
+ if (match.paramsError) {
608
+ handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS');
609
+ }
610
+ if (match.searchError) {
611
+ handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH');
612
+ }
613
+ const parentContext = parentMatch?.context ?? this.options.context ?? {};
614
+ const beforeLoadContext = (await route.options.beforeLoad?.({
615
+ search: match.search,
616
+ abortController,
617
+ params: match.params,
618
+ preload: !!preload,
619
+ context: parentContext,
620
+ location: this.state.location,
621
+ // TOOD: just expose state and router, etc
622
+ navigate: opts => this.navigate({
623
+ ...opts,
624
+ from: match.pathname
625
+ }),
626
+ buildLocation: this.buildLocation,
627
+ cause: preload ? 'preload' : match.cause
628
+ })) ?? {};
629
+ if (redirects.isRedirect(beforeLoadContext)) {
630
+ throw beforeLoadContext;
631
+ }
632
+ const context = {
633
+ ...parentContext,
634
+ ...beforeLoadContext
635
+ };
636
+ matches[index] = match = {
637
+ ...match,
638
+ routeContext: utils.replaceEqualDeep(match.routeContext, beforeLoadContext),
639
+ context: utils.replaceEqualDeep(match.context, context),
640
+ abortController
641
+ };
642
+ } catch (err) {
643
+ handleErrorAndRedirect(err, 'BEFORE_LOAD');
644
+ break;
645
+ }
646
+ }
647
+ } catch (err) {
648
+ if (redirects.isRedirect(err)) {
649
+ if (!preload) this.navigate(err);
650
+ return matches;
651
+ }
652
+ throw err;
653
+ }
654
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
655
+ const matchPromises = [];
656
+ validResolvedMatches.forEach((match, index) => {
657
+ matchPromises.push(new Promise(async resolve => {
658
+ const parentMatchPromise = matchPromises[index - 1];
659
+ const route = this.looseRoutesById[match.routeId];
660
+ const handleErrorAndRedirect = err => {
661
+ if (redirects.isRedirect(err)) {
662
+ if (!preload) {
663
+ this.navigate(err);
664
+ }
665
+ return true;
666
+ }
667
+ return false;
668
+ };
669
+ let loadPromise;
670
+ matches[index] = match = {
671
+ ...match,
672
+ showPending: false
673
+ };
674
+ let didShowPending = false;
675
+ const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
676
+ const pendingMinMs = route.options.pendingMinMs ?? this.options.defaultPendingMinMs;
677
+ const shouldPending = !preload && pendingMs && (route.options.pendingComponent ?? this.options.defaultPendingComponent);
678
+ const fetch = async () => {
679
+ if (match.isFetching) {
680
+ loadPromise = RouterProvider.getRouteMatch(this.state, match.id)?.loadPromise;
681
+ } else {
682
+ const loaderContext = {
683
+ params: match.params,
684
+ deps: match.loaderDeps,
685
+ preload: !!preload,
686
+ parentMatchPromise,
687
+ abortController: match.abortController,
688
+ context: match.context,
689
+ location: this.state.location,
690
+ navigate: opts => this.navigate({
691
+ ...opts,
692
+ from: match.pathname
693
+ }),
694
+ cause: preload ? 'preload' : match.cause
695
+ };
696
+ if (match.fetchCount && match.status === 'success') {
697
+ resolve();
698
+ }
699
+
700
+ // Otherwise, load the route
701
+ matches[index] = match = {
702
+ ...match,
703
+ isFetching: true,
704
+ fetchCount: match.fetchCount + 1
705
+ };
706
+ const componentsPromise = Promise.all(componentTypes.map(async type => {
707
+ const component = route.options[type];
708
+ if (component?.preload) {
709
+ await component.preload();
710
+ }
711
+ }));
712
+ const loaderPromise = route.options.loader?.(loaderContext);
713
+ loadPromise = Promise.all([componentsPromise, loaderPromise]).then(d => d[1]);
714
+ }
715
+ matches[index] = match = {
716
+ ...match,
717
+ loadPromise
718
+ };
719
+ updateMatch(match);
720
+ try {
721
+ const loaderData = await loadPromise;
722
+ if (latestPromise = checkLatest()) return await latestPromise;
723
+ if (redirects.isRedirect(loaderData)) {
724
+ if (handleErrorAndRedirect(loaderData)) return;
725
+ }
726
+ if (didShowPending && pendingMinMs) {
727
+ await new Promise(r => setTimeout(r, pendingMinMs));
728
+ }
729
+ if (latestPromise = checkLatest()) return await latestPromise;
730
+ matches[index] = match = {
731
+ ...match,
732
+ error: undefined,
733
+ status: 'success',
734
+ isFetching: false,
735
+ updatedAt: Date.now(),
736
+ loaderData,
737
+ loadPromise: undefined
738
+ };
739
+ } catch (error) {
740
+ if (latestPromise = checkLatest()) return await latestPromise;
741
+ if (handleErrorAndRedirect(error)) return;
742
+ try {
743
+ route.options.onError?.(error);
744
+ } catch (onErrorError) {
745
+ error = onErrorError;
746
+ if (handleErrorAndRedirect(onErrorError)) return;
747
+ }
748
+ matches[index] = match = {
749
+ ...match,
750
+ error,
751
+ status: 'error',
752
+ isFetching: false
753
+ };
754
+ }
755
+ updateMatch(match);
756
+ };
757
+
758
+ // This is where all of the stale-while-revalidate magic happens
759
+ const age = Date.now() - match.updatedAt;
760
+ let staleAge = preload ? route.options.preloadStaleTime ?? this.options.defaultPreloadStaleTime ?? 30_000 // 30 seconds for preloads by default
761
+ : route.options.staleTime ?? this.options.defaultStaleTime ?? 0;
762
+ if (match.status === 'success') {
763
+ // Background Fetching, no need to wait
764
+ if (age > staleAge) {
765
+ fetch();
766
+ }
767
+ } else {
768
+ // Critical Fetching, we need to await
769
+
770
+ // If we need to potentially show the pending component,
771
+ // start a timer to show it after the pendingMs
772
+ if (shouldPending) {
773
+ new Promise(r => setTimeout(r, pendingMs)).then(async () => {
774
+ if (latestPromise = checkLatest()) return latestPromise;
775
+ didShowPending = true;
776
+ matches[index] = match = {
777
+ ...match,
778
+ showPending: true
779
+ };
780
+ updateMatch(match);
781
+ resolve();
782
+ });
783
+ }
784
+ await fetch();
785
+ }
786
+ resolve();
787
+ }));
788
+ });
789
+ await Promise.all(matchPromises);
790
+ return matches;
791
+ };
792
+ invalidate = () => this.load({
793
+ invalidate: true
794
+ });
795
+ load = async opts => {
796
+ const promise = new Promise(async (resolve, reject) => {
797
+ const next = this.latestLocation;
798
+ const prevLocation = this.state.resolvedLocation;
799
+ const pathDidChange = prevLocation.href !== next.href;
800
+ let latestPromise;
801
+
802
+ // Cancel any pending matches
803
+ this.cancelMatches();
804
+ this.emit({
805
+ type: 'onBeforeLoad',
806
+ fromLocation: prevLocation,
807
+ toLocation: next,
808
+ pathChanged: pathDidChange
809
+ });
810
+ let pendingMatches;
811
+ const previousMatches = this.state.matches;
812
+ this.__store.batch(() => {
813
+ // This is where all of the garbage collection magic happens
814
+ this.__store.setState(s => {
815
+ return {
816
+ ...s,
817
+ cachedMatches: s.cachedMatches.filter(d => {
818
+ const route = this.looseRoutesById[d.routeId];
819
+ return d.status !== 'error' && Date.now() - d.updatedAt < (route.options.gcTime ?? this.options.defaultGcTime ?? 5 * 60 * 1000);
820
+ })
821
+ };
822
+ });
823
+
824
+ // Match the routes
825
+ pendingMatches = this.matchRoutes(next.pathname, next.search, {
826
+ debug: true
827
+ });
828
+
829
+ // Ingest the new matches
830
+ // If a cached moved to pendingMatches, remove it from cachedMatches
831
+ this.__store.setState(s => ({
832
+ ...s,
833
+ isLoading: true,
834
+ location: next,
835
+ pendingMatches,
836
+ cachedMatches: s.cachedMatches.filter(d => {
837
+ return !pendingMatches.find(e => e.id === d.id);
838
+ })
839
+ }));
840
+ });
841
+ try {
842
+ try {
843
+ // Load the matches
844
+ await this.loadMatches({
845
+ matches: pendingMatches,
846
+ checkLatest: () => this.checkLatest(promise),
847
+ invalidate: opts?.invalidate
848
+ });
849
+ } catch (err) {
850
+ // swallow this error, since we'll display the
851
+ // errors on the route components
852
+ }
853
+
854
+ // Only apply the latest transition
855
+ if (latestPromise = this.checkLatest(promise)) {
856
+ return latestPromise;
857
+ }
858
+ const exitingMatches = previousMatches.filter(match => !pendingMatches.find(d => d.id === match.id));
859
+ const enteringMatches = pendingMatches.filter(match => !previousMatches.find(d => d.id === match.id));
860
+ const stayingMatches = previousMatches.filter(match => pendingMatches.find(d => d.id === match.id));
861
+
862
+ // Commit the pending matches. If a previous match was
863
+ // removed, place it in the cachedMatches
864
+ this.__store.setState(s => ({
865
+ ...s,
866
+ isLoading: false,
867
+ matches: pendingMatches,
868
+ pendingMatches: undefined,
869
+ cachedMatches: [...s.cachedMatches, ...exitingMatches.filter(d => d.status !== 'error')]
870
+ }))
871
+
872
+ //
873
+ ;
874
+ [[exitingMatches, 'onLeave'], [enteringMatches, 'onEnter'], [stayingMatches, 'onStay']].forEach(([matches, hook]) => {
875
+ matches.forEach(match => {
876
+ this.looseRoutesById[match.routeId].options[hook]?.(match);
877
+ });
878
+ });
879
+ this.emit({
880
+ type: 'onLoad',
881
+ fromLocation: prevLocation,
882
+ toLocation: next,
883
+ pathChanged: pathDidChange
884
+ });
885
+ resolve();
886
+ } catch (err) {
887
+ // Only apply the latest transition
888
+ if (latestPromise = this.checkLatest(promise)) {
889
+ return latestPromise;
890
+ }
891
+ reject(err);
892
+ }
893
+ });
894
+ this.latestLoadPromise = promise;
895
+ return this.latestLoadPromise;
896
+ };
897
+ preloadRoute = async (navigateOpts = this.state.location) => {
898
+ let next = this.buildLocation(navigateOpts);
899
+ let matches = this.matchRoutes(next.pathname, next.search, {
900
+ throwOnError: true
901
+ });
902
+ const loadedMatchIds = Object.fromEntries([...this.state.matches, ...(this.state.pendingMatches ?? []), ...this.state.cachedMatches]?.map(d => [d.id, true]));
903
+ this.__store.batch(() => {
904
+ matches.forEach(match => {
905
+ if (!loadedMatchIds[match.id]) {
906
+ this.__store.setState(s => ({
907
+ ...s,
908
+ cachedMatches: [...s.cachedMatches, match]
909
+ }));
910
+ }
911
+ });
912
+ });
913
+ matches = await this.loadMatches({
914
+ matches,
915
+ preload: true,
916
+ checkLatest: () => undefined
917
+ });
918
+ return matches;
919
+ };
920
+ matchRoute = (location, opts) => {
921
+ location = {
922
+ ...location,
923
+ to: location.to ? this.resolvePathWithBase(location.from || '', location.to) : undefined
924
+ };
925
+ const next = this.buildLocation(location);
926
+ if (opts?.pending && this.state.status !== 'pending') {
927
+ return false;
928
+ }
929
+ const baseLocation = opts?.pending ? this.latestLocation : this.state.resolvedLocation;
930
+ if (!baseLocation) {
931
+ return false;
932
+ }
933
+ const match = path.matchPathname(this.basepath, baseLocation.pathname, {
934
+ ...opts,
935
+ to: next.pathname
936
+ });
937
+ if (!match) {
938
+ return false;
939
+ }
940
+ if (match && (opts?.includeSearch ?? true)) {
941
+ return utils.deepEqual(baseLocation.search, next.search, true) ? match : false;
942
+ }
943
+ return match;
944
+ };
945
+ injectHtml = async html => {
946
+ this.injectedHtml.push(html);
947
+ };
948
+ dehydrateData = (key, getData) => {
949
+ if (typeof document === 'undefined') {
950
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key);
951
+ this.injectHtml(async () => {
952
+ const id = `__TSR_DEHYDRATED__${strKey}`;
953
+ const data = typeof getData === 'function' ? await getData() : getData;
954
+ return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${utils.escapeJSON(strKey)}"] = ${JSON.stringify(data)}
955
+ ;(() => {
956
+ var el = document.getElementById('${id}')
957
+ el.parentElement.removeChild(el)
958
+ })()
959
+ </script>`;
960
+ });
961
+ return () => this.hydrateData(key);
962
+ }
963
+ return () => undefined;
964
+ };
965
+ hydrateData = key => {
966
+ if (typeof document !== 'undefined') {
967
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key);
968
+ return window[`__TSR_DEHYDRATED__${strKey}`];
969
+ }
970
+ return undefined;
971
+ };
972
+ dehydrate = () => {
973
+ return {
974
+ state: {
975
+ dehydratedMatches: this.state.matches.map(d => utils.pick(d, ['id', 'status', 'updatedAt', 'loaderData']))
976
+ }
977
+ };
978
+ };
979
+ hydrate = async __do_not_use_server_ctx => {
980
+ let _ctx = __do_not_use_server_ctx;
981
+ // Client hydrates from window
982
+ if (typeof document !== 'undefined') {
983
+ _ctx = window.__TSR_DEHYDRATED__;
984
+ }
985
+ invariant(_ctx, 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?');
986
+ const ctx = _ctx;
987
+ this.dehydratedData = ctx.payload;
988
+ this.options.hydrate?.(ctx.payload);
989
+ const dehydratedState = ctx.router.state;
990
+ let matches = this.matchRoutes(this.state.location.pathname, this.state.location.search).map(match => {
991
+ const dehydratedMatch = dehydratedState.dehydratedMatches.find(d => d.id === match.id);
992
+ invariant(dehydratedMatch, `Could not find a client-side match for dehydrated match with id: ${match.id}!`);
993
+ if (dehydratedMatch) {
994
+ return {
995
+ ...match,
996
+ ...dehydratedMatch
997
+ };
998
+ }
999
+ return match;
1000
+ });
1001
+ this.__store.setState(s => {
1002
+ return {
1003
+ ...s,
1004
+ matches: matches
1005
+ };
1006
+ });
1007
+ };
1008
+
1009
+ // resolveMatchPromise = (matchId: string, key: string, value: any) => {
1010
+ // state.matches
1011
+ // .find((d) => d.id === matchId)
1012
+ // ?.__promisesByKey[key]?.resolve(value)
1013
+ // }
1014
+ }
1015
+
1016
+ // A function that takes an import() argument which is a function and returns a new function that will
1017
+ // proxy arguments from the caller to the imported function, retaining all type
1018
+ // information along the way
1019
+ function lazyFn(fn, key) {
1020
+ return async (...args) => {
1021
+ const imported = await fn();
1022
+ return imported[key || 'default'](...args);
1023
+ };
1024
+ }
1025
+ class SearchParamError extends Error {}
1026
+ class PathParamError extends Error {}
1027
+ function getInitialRouterState(location) {
1028
+ return {
1029
+ isLoading: false,
1030
+ isTransitioning: false,
1031
+ status: 'idle',
1032
+ resolvedLocation: {
1033
+ ...location
1034
+ },
1035
+ location,
1036
+ matches: [],
1037
+ pendingMatches: [],
1038
+ cachedMatches: [],
1039
+ lastUpdated: Date.now()
1040
+ };
1041
+ }
1042
+
1043
+ exports.PathParamError = PathParamError;
1044
+ exports.Router = Router;
1045
+ exports.SearchParamError = SearchParamError;
1046
+ exports.componentTypes = componentTypes;
1047
+ exports.getInitialRouterState = getInitialRouterState;
1048
+ exports.lazyFn = lazyFn;
1049
+ //# sourceMappingURL=router.js.map