@tanstack/react-router 0.0.1-beta.27 → 0.0.1-beta.270

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