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

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 +1067 -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 +2282 -2580
  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 +63 -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 +283 -0
  65. package/build/types/routeInfo.d.ts +22 -0
  66. package/build/types/router.d.ts +185 -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 +2873 -2545
  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 +422 -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 +882 -0
  94. package/src/routeInfo.ts +70 -0
  95. package/src/router.ts +1651 -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,1067 @@
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
+ invalid: false
361
+ };
362
+
363
+ // Regardless of whether we're reusing an existing match or creating
364
+ // a new one, we need to update the match's search params
365
+ match.search = utils.replaceEqualDeep(match.search, preMatchSearch);
366
+ // And also update the searchError if there is one
367
+ match.searchError = searchError;
368
+ matches.push(match);
369
+ });
370
+ return matches;
371
+ };
372
+ cancelMatch = id => {
373
+ RouterProvider.getRouteMatch(this.state, id)?.abortController?.abort();
374
+ };
375
+ cancelMatches = () => {
376
+ this.state.pendingMatches?.forEach(match => {
377
+ this.cancelMatch(match.id);
378
+ });
379
+ };
380
+ buildLocation = opts => {
381
+ const build = (dest = {}, matches) => {
382
+ const from = this.latestLocation;
383
+ const fromSearch = (this.state.pendingMatches || this.state.matches).at(-1)?.search || from.search;
384
+ const fromPathname = dest.from ?? from.pathname;
385
+ let pathname = this.resolvePathWithBase(fromPathname, `${dest.to ?? ''}`);
386
+ const fromMatches = this.matchRoutes(fromPathname, fromSearch);
387
+ const stayingMatches = matches?.filter(d => fromMatches?.find(e => e.routeId === d.routeId));
388
+ const prevParams = {
389
+ ...utils.last(fromMatches)?.params
390
+ };
391
+ let nextParams = (dest.params ?? true) === true ? prevParams : utils.functionalUpdate(dest.params, prevParams);
392
+ if (nextParams) {
393
+ matches?.map(d => this.looseRoutesById[d.routeId].options.stringifyParams).filter(Boolean).forEach(fn => {
394
+ nextParams = {
395
+ ...nextParams,
396
+ ...fn(nextParams)
397
+ };
398
+ });
399
+ }
400
+ pathname = path.interpolatePath(pathname, nextParams ?? {});
401
+ const preSearchFilters = stayingMatches?.map(match => this.looseRoutesById[match.routeId].options.preSearchFilters ?? []).flat().filter(Boolean) ?? [];
402
+ const postSearchFilters = stayingMatches?.map(match => this.looseRoutesById[match.routeId].options.postSearchFilters ?? []).flat().filter(Boolean) ?? [];
403
+
404
+ // Pre filters first
405
+ const preFilteredSearch = preSearchFilters?.length ? preSearchFilters?.reduce((prev, next) => next(prev), fromSearch) : fromSearch;
406
+
407
+ // Then the link/navigate function
408
+ const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
409
+ : dest.search ? utils.functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
410
+ : preSearchFilters?.length ? preFilteredSearch // Preserve resolvedFrom filters
411
+ : {};
412
+
413
+ // Then post filters
414
+ const postFilteredSearch = postSearchFilters?.length ? postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
415
+ const search = utils.replaceEqualDeep(fromSearch, postFilteredSearch);
416
+ const searchStr = this.options.stringifySearch(search);
417
+ const hash = dest.hash === true ? from.hash : dest.hash ? utils.functionalUpdate(dest.hash, from.hash) : from.hash;
418
+ const hashStr = hash ? `#${hash}` : '';
419
+ let nextState = dest.state === true ? from.state : dest.state ? utils.functionalUpdate(dest.state, from.state) : from.state;
420
+ nextState = utils.replaceEqualDeep(from.state, nextState);
421
+ return {
422
+ pathname,
423
+ search,
424
+ searchStr,
425
+ state: nextState,
426
+ hash,
427
+ href: `${pathname}${searchStr}${hashStr}`,
428
+ unmaskOnReload: dest.unmaskOnReload
429
+ };
430
+ };
431
+ const buildWithMatches = (dest = {}, maskedDest) => {
432
+ let next = build(dest);
433
+ let maskedNext = maskedDest ? build(maskedDest) : undefined;
434
+ if (!maskedNext) {
435
+ let params = {};
436
+ let foundMask = this.options.routeMasks?.find(d => {
437
+ const match = path.matchPathname(this.basepath, next.pathname, {
438
+ to: d.from,
439
+ caseSensitive: false,
440
+ fuzzy: false
441
+ });
442
+ if (match) {
443
+ params = match;
444
+ return true;
445
+ }
446
+ return false;
447
+ });
448
+ if (foundMask) {
449
+ foundMask = {
450
+ ...foundMask,
451
+ from: path.interpolatePath(foundMask.from, params)
452
+ };
453
+ maskedDest = foundMask;
454
+ maskedNext = build(maskedDest);
455
+ }
456
+ }
457
+ const nextMatches = this.matchRoutes(next.pathname, next.search);
458
+ const maskedMatches = maskedNext ? this.matchRoutes(maskedNext.pathname, maskedNext.search) : undefined;
459
+ const maskedFinal = maskedNext ? build(maskedDest, maskedMatches) : undefined;
460
+ const final = build(dest, nextMatches);
461
+ if (maskedFinal) {
462
+ final.maskedLocation = maskedFinal;
463
+ }
464
+ return final;
465
+ };
466
+ if (opts.mask) {
467
+ return buildWithMatches(opts, {
468
+ ...utils.pick(opts, ['from']),
469
+ ...opts.mask
470
+ });
471
+ }
472
+ return buildWithMatches(opts);
473
+ };
474
+ commitLocation = async ({
475
+ startTransition,
476
+ ...next
477
+ }) => {
478
+ if (this.navigateTimeout) clearTimeout(this.navigateTimeout);
479
+ const isSameUrl = this.latestLocation.href === next.href;
480
+
481
+ // If the next urls are the same and we're not replacing,
482
+ // do nothing
483
+ if (!isSameUrl || !next.replace) {
484
+ let {
485
+ maskedLocation,
486
+ ...nextHistory
487
+ } = next;
488
+ if (maskedLocation) {
489
+ nextHistory = {
490
+ ...maskedLocation,
491
+ state: {
492
+ ...maskedLocation.state,
493
+ __tempKey: undefined,
494
+ __tempLocation: {
495
+ ...nextHistory,
496
+ search: nextHistory.searchStr,
497
+ state: {
498
+ ...nextHistory.state,
499
+ __tempKey: undefined,
500
+ __tempLocation: undefined,
501
+ key: undefined
502
+ }
503
+ }
504
+ }
505
+ };
506
+ if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
507
+ nextHistory.state.__tempKey = this.tempLocationKey;
508
+ }
509
+ }
510
+ const apply = () => {
511
+ this.history[next.replace ? 'replace' : 'push'](nextHistory.href, nextHistory.state);
512
+ };
513
+ if (startTransition ?? true) {
514
+ this.startReactTransition(apply);
515
+ } else {
516
+ apply();
517
+ }
518
+ }
519
+ this.resetNextScroll = next.resetScroll ?? true;
520
+ return this.latestLoadPromise;
521
+ };
522
+ buildAndCommitLocation = ({
523
+ replace,
524
+ resetScroll,
525
+ startTransition,
526
+ ...rest
527
+ } = {}) => {
528
+ const location = this.buildLocation(rest);
529
+ return this.commitLocation({
530
+ ...location,
531
+ startTransition,
532
+ replace,
533
+ resetScroll
534
+ });
535
+ };
536
+ navigate = ({
537
+ from,
538
+ to = '',
539
+ ...rest
540
+ }) => {
541
+ // If this link simply reloads the current route,
542
+ // make sure it has a new key so it will trigger a data refresh
543
+
544
+ // If this `to` is a valid external URL, return
545
+ // null for LinkUtils
546
+ const toString = String(to);
547
+ const fromString = typeof from === 'undefined' ? from : String(from);
548
+ let isExternal;
549
+ try {
550
+ new URL(`${toString}`);
551
+ isExternal = true;
552
+ } catch (e) {}
553
+ invariant(!isExternal, 'Attempting to navigate to external url with this.navigate!');
554
+ return this.buildAndCommitLocation({
555
+ ...rest,
556
+ from: fromString,
557
+ to: toString
558
+ });
559
+ };
560
+ loadMatches = async ({
561
+ checkLatest,
562
+ matches,
563
+ preload
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 loaderContext = {
679
+ params: match.params,
680
+ deps: match.loaderDeps,
681
+ preload: !!preload,
682
+ parentMatchPromise,
683
+ abortController: match.abortController,
684
+ context: match.context,
685
+ location: this.state.location,
686
+ navigate: opts => this.navigate({
687
+ ...opts,
688
+ from: match.pathname
689
+ }),
690
+ cause: preload ? 'preload' : match.cause
691
+ };
692
+ const fetch = async () => {
693
+ if (match.isFetching) {
694
+ loadPromise = RouterProvider.getRouteMatch(this.state, match.id)?.loadPromise;
695
+ } else {
696
+ // If the user doesn't want the route to reload, just
697
+ // resolve with the existing loader data
698
+
699
+ if (match.fetchCount && match.status === 'success') {
700
+ resolve();
701
+ }
702
+
703
+ // Otherwise, load the route
704
+ matches[index] = match = {
705
+ ...match,
706
+ isFetching: true,
707
+ fetchCount: match.fetchCount + 1
708
+ };
709
+ const componentsPromise = Promise.all(componentTypes.map(async type => {
710
+ const component = route.options[type];
711
+ if (component?.preload) {
712
+ await component.preload();
713
+ }
714
+ }));
715
+ const loaderPromise = route.options.loader?.(loaderContext);
716
+ loadPromise = Promise.all([componentsPromise, loaderPromise]).then(d => d[1]);
717
+ }
718
+ matches[index] = match = {
719
+ ...match,
720
+ loadPromise
721
+ };
722
+ updateMatch(match);
723
+ try {
724
+ const loaderData = await loadPromise;
725
+ if (latestPromise = checkLatest()) return await latestPromise;
726
+ if (redirects.isRedirect(loaderData)) {
727
+ if (handleErrorAndRedirect(loaderData)) return;
728
+ }
729
+ if (didShowPending && pendingMinMs) {
730
+ await new Promise(r => setTimeout(r, pendingMinMs));
731
+ }
732
+ if (latestPromise = checkLatest()) return await latestPromise;
733
+ matches[index] = match = {
734
+ ...match,
735
+ error: undefined,
736
+ status: 'success',
737
+ isFetching: false,
738
+ updatedAt: Date.now(),
739
+ loaderData,
740
+ loadPromise: undefined
741
+ };
742
+ } catch (error) {
743
+ if (latestPromise = checkLatest()) return await latestPromise;
744
+ if (handleErrorAndRedirect(error)) return;
745
+ try {
746
+ route.options.onError?.(error);
747
+ } catch (onErrorError) {
748
+ error = onErrorError;
749
+ if (handleErrorAndRedirect(onErrorError)) return;
750
+ }
751
+ matches[index] = match = {
752
+ ...match,
753
+ error,
754
+ status: 'error',
755
+ isFetching: false
756
+ };
757
+ }
758
+ updateMatch(match);
759
+ };
760
+
761
+ // This is where all of the stale-while-revalidate magic happens
762
+ const age = Date.now() - match.updatedAt;
763
+ let staleAge = preload ? route.options.preloadStaleTime ?? this.options.defaultPreloadStaleTime ?? 30_000 // 30 seconds for preloads by default
764
+ : route.options.staleTime ?? this.options.defaultStaleTime ?? 0;
765
+
766
+ // Default to reloading the route all the time
767
+ let shouldReload;
768
+ const shouldReloadOption = route.options.shouldReload;
769
+
770
+ // Allow shouldReload to get the last say,
771
+ // if provided.
772
+ shouldReload = typeof shouldReloadOption === 'function' ? shouldReloadOption(loaderContext) : shouldReloadOption;
773
+ if (match.status !== 'success') {
774
+ // If we need to potentially show the pending component,
775
+ // start a timer to show it after the pendingMs
776
+ if (shouldPending) {
777
+ new Promise(r => setTimeout(r, pendingMs)).then(async () => {
778
+ if (latestPromise = checkLatest()) return latestPromise;
779
+ didShowPending = true;
780
+ matches[index] = match = {
781
+ ...match,
782
+ showPending: true
783
+ };
784
+ updateMatch(match);
785
+ resolve();
786
+ });
787
+ }
788
+
789
+ // Critical Fetching, we need to await
790
+ await fetch();
791
+ } else if (match.invalid || (shouldReload ?? age > staleAge)) {
792
+ // Background Fetching, no need to wait
793
+ fetch();
794
+ }
795
+ resolve();
796
+ }));
797
+ });
798
+ await Promise.all(matchPromises);
799
+ return matches;
800
+ };
801
+ invalidate = () => {
802
+ const invalidate = d => ({
803
+ ...d,
804
+ invalid: true
805
+ });
806
+ this.__store.setState(s => ({
807
+ ...s,
808
+ matches: s.matches.map(invalidate),
809
+ cachedMatches: s.cachedMatches.map(invalidate),
810
+ pendingMatches: s.pendingMatches?.map(invalidate)
811
+ }));
812
+ this.load();
813
+ };
814
+ load = async () => {
815
+ const promise = new Promise(async (resolve, reject) => {
816
+ const next = this.latestLocation;
817
+ const prevLocation = this.state.resolvedLocation;
818
+ const pathDidChange = prevLocation.href !== next.href;
819
+ let latestPromise;
820
+
821
+ // Cancel any pending matches
822
+ this.cancelMatches();
823
+ this.emit({
824
+ type: 'onBeforeLoad',
825
+ fromLocation: prevLocation,
826
+ toLocation: next,
827
+ pathChanged: pathDidChange
828
+ });
829
+ let pendingMatches;
830
+ const previousMatches = this.state.matches;
831
+ this.__store.batch(() => {
832
+ // This is where all of the garbage collection magic happens
833
+ this.__store.setState(s => {
834
+ return {
835
+ ...s,
836
+ cachedMatches: s.cachedMatches.filter(d => {
837
+ const route = this.looseRoutesById[d.routeId];
838
+ return d.status !== 'error' && Date.now() - d.updatedAt < (route.options.gcTime ?? this.options.defaultGcTime ?? 5 * 60 * 1000);
839
+ })
840
+ };
841
+ });
842
+
843
+ // Match the routes
844
+ pendingMatches = this.matchRoutes(next.pathname, next.search, {
845
+ debug: true
846
+ });
847
+
848
+ // Ingest the new matches
849
+ // If a cached moved to pendingMatches, remove it from cachedMatches
850
+ this.__store.setState(s => ({
851
+ ...s,
852
+ isLoading: true,
853
+ location: next,
854
+ pendingMatches,
855
+ cachedMatches: s.cachedMatches.filter(d => {
856
+ return !pendingMatches.find(e => e.id === d.id);
857
+ })
858
+ }));
859
+ });
860
+ try {
861
+ try {
862
+ // Load the matches
863
+ await this.loadMatches({
864
+ matches: pendingMatches,
865
+ checkLatest: () => this.checkLatest(promise)
866
+ });
867
+ } catch (err) {
868
+ // swallow this error, since we'll display the
869
+ // errors on the route components
870
+ }
871
+
872
+ // Only apply the latest transition
873
+ if (latestPromise = this.checkLatest(promise)) {
874
+ return latestPromise;
875
+ }
876
+ const exitingMatches = previousMatches.filter(match => !pendingMatches.find(d => d.id === match.id));
877
+ const enteringMatches = pendingMatches.filter(match => !previousMatches.find(d => d.id === match.id));
878
+ const stayingMatches = previousMatches.filter(match => pendingMatches.find(d => d.id === match.id));
879
+
880
+ // Commit the pending matches. If a previous match was
881
+ // removed, place it in the cachedMatches
882
+ this.__store.setState(s => ({
883
+ ...s,
884
+ isLoading: false,
885
+ matches: pendingMatches,
886
+ pendingMatches: undefined,
887
+ cachedMatches: [...s.cachedMatches, ...exitingMatches.filter(d => d.status !== 'error')]
888
+ }))
889
+
890
+ //
891
+ ;
892
+ [[exitingMatches, 'onLeave'], [enteringMatches, 'onEnter'], [stayingMatches, 'onStay']].forEach(([matches, hook]) => {
893
+ matches.forEach(match => {
894
+ this.looseRoutesById[match.routeId].options[hook]?.(match);
895
+ });
896
+ });
897
+ this.emit({
898
+ type: 'onLoad',
899
+ fromLocation: prevLocation,
900
+ toLocation: next,
901
+ pathChanged: pathDidChange
902
+ });
903
+ resolve();
904
+ } catch (err) {
905
+ // Only apply the latest transition
906
+ if (latestPromise = this.checkLatest(promise)) {
907
+ return latestPromise;
908
+ }
909
+ reject(err);
910
+ }
911
+ });
912
+ this.latestLoadPromise = promise;
913
+ return this.latestLoadPromise;
914
+ };
915
+ preloadRoute = async (navigateOpts = this.state.location) => {
916
+ let next = this.buildLocation(navigateOpts);
917
+ let matches = this.matchRoutes(next.pathname, next.search, {
918
+ throwOnError: true
919
+ });
920
+ const loadedMatchIds = Object.fromEntries([...this.state.matches, ...(this.state.pendingMatches ?? []), ...this.state.cachedMatches]?.map(d => [d.id, true]));
921
+ this.__store.batch(() => {
922
+ matches.forEach(match => {
923
+ if (!loadedMatchIds[match.id]) {
924
+ this.__store.setState(s => ({
925
+ ...s,
926
+ cachedMatches: [...s.cachedMatches, match]
927
+ }));
928
+ }
929
+ });
930
+ });
931
+ matches = await this.loadMatches({
932
+ matches,
933
+ preload: true,
934
+ checkLatest: () => undefined
935
+ });
936
+ return matches;
937
+ };
938
+ matchRoute = (location, opts) => {
939
+ location = {
940
+ ...location,
941
+ to: location.to ? this.resolvePathWithBase(location.from || '', location.to) : undefined
942
+ };
943
+ const next = this.buildLocation(location);
944
+ if (opts?.pending && this.state.status !== 'pending') {
945
+ return false;
946
+ }
947
+ const baseLocation = opts?.pending ? this.latestLocation : this.state.resolvedLocation;
948
+ if (!baseLocation) {
949
+ return false;
950
+ }
951
+ const match = path.matchPathname(this.basepath, baseLocation.pathname, {
952
+ ...opts,
953
+ to: next.pathname
954
+ });
955
+ if (!match) {
956
+ return false;
957
+ }
958
+ if (match && (opts?.includeSearch ?? true)) {
959
+ return utils.deepEqual(baseLocation.search, next.search, true) ? match : false;
960
+ }
961
+ return match;
962
+ };
963
+ injectHtml = async html => {
964
+ this.injectedHtml.push(html);
965
+ };
966
+ dehydrateData = (key, getData) => {
967
+ if (typeof document === 'undefined') {
968
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key);
969
+ this.injectHtml(async () => {
970
+ const id = `__TSR_DEHYDRATED__${strKey}`;
971
+ const data = typeof getData === 'function' ? await getData() : getData;
972
+ return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${utils.escapeJSON(strKey)}"] = ${JSON.stringify(data)}
973
+ ;(() => {
974
+ var el = document.getElementById('${id}')
975
+ el.parentElement.removeChild(el)
976
+ })()
977
+ </script>`;
978
+ });
979
+ return () => this.hydrateData(key);
980
+ }
981
+ return () => undefined;
982
+ };
983
+ hydrateData = key => {
984
+ if (typeof document !== 'undefined') {
985
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key);
986
+ return window[`__TSR_DEHYDRATED__${strKey}`];
987
+ }
988
+ return undefined;
989
+ };
990
+ dehydrate = () => {
991
+ return {
992
+ state: {
993
+ dehydratedMatches: this.state.matches.map(d => utils.pick(d, ['id', 'status', 'updatedAt', 'loaderData']))
994
+ }
995
+ };
996
+ };
997
+ hydrate = async __do_not_use_server_ctx => {
998
+ let _ctx = __do_not_use_server_ctx;
999
+ // Client hydrates from window
1000
+ if (typeof document !== 'undefined') {
1001
+ _ctx = window.__TSR_DEHYDRATED__;
1002
+ }
1003
+ invariant(_ctx, 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?');
1004
+ const ctx = _ctx;
1005
+ this.dehydratedData = ctx.payload;
1006
+ this.options.hydrate?.(ctx.payload);
1007
+ const dehydratedState = ctx.router.state;
1008
+ let matches = this.matchRoutes(this.state.location.pathname, this.state.location.search).map(match => {
1009
+ const dehydratedMatch = dehydratedState.dehydratedMatches.find(d => d.id === match.id);
1010
+ invariant(dehydratedMatch, `Could not find a client-side match for dehydrated match with id: ${match.id}!`);
1011
+ if (dehydratedMatch) {
1012
+ return {
1013
+ ...match,
1014
+ ...dehydratedMatch
1015
+ };
1016
+ }
1017
+ return match;
1018
+ });
1019
+ this.__store.setState(s => {
1020
+ return {
1021
+ ...s,
1022
+ matches: matches
1023
+ };
1024
+ });
1025
+ };
1026
+
1027
+ // resolveMatchPromise = (matchId: string, key: string, value: any) => {
1028
+ // state.matches
1029
+ // .find((d) => d.id === matchId)
1030
+ // ?.__promisesByKey[key]?.resolve(value)
1031
+ // }
1032
+ }
1033
+
1034
+ // A function that takes an import() argument which is a function and returns a new function that will
1035
+ // proxy arguments from the caller to the imported function, retaining all type
1036
+ // information along the way
1037
+ function lazyFn(fn, key) {
1038
+ return async (...args) => {
1039
+ const imported = await fn();
1040
+ return imported[key || 'default'](...args);
1041
+ };
1042
+ }
1043
+ class SearchParamError extends Error {}
1044
+ class PathParamError extends Error {}
1045
+ function getInitialRouterState(location) {
1046
+ return {
1047
+ isLoading: false,
1048
+ isTransitioning: false,
1049
+ status: 'idle',
1050
+ resolvedLocation: {
1051
+ ...location
1052
+ },
1053
+ location,
1054
+ matches: [],
1055
+ pendingMatches: [],
1056
+ cachedMatches: [],
1057
+ lastUpdated: Date.now()
1058
+ };
1059
+ }
1060
+
1061
+ exports.PathParamError = PathParamError;
1062
+ exports.Router = Router;
1063
+ exports.SearchParamError = SearchParamError;
1064
+ exports.componentTypes = componentTypes;
1065
+ exports.getInitialRouterState = getInitialRouterState;
1066
+ exports.lazyFn = lazyFn;
1067
+ //# sourceMappingURL=router.js.map