@tanstack/react-router 0.0.1-beta.24 → 0.0.1-beta.241

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