@tanstack/react-router 0.0.1-beta.26 → 0.0.1-beta.261

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 +128 -0
  3. package/build/cjs/CatchBoundary.js.map +1 -0
  4. package/build/cjs/Matches.js +244 -0
  5. package/build/cjs/Matches.js.map +1 -0
  6. package/build/cjs/RouterProvider.js +166 -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 +125 -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 +149 -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 +140 -0
  29. package/build/cjs/route.js.map +1 -0
  30. package/build/cjs/router.js +1144 -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 +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 +2214 -2529
  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 +36 -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 +34 -0
  56. package/build/types/history.d.ts +7 -0
  57. package/build/types/index.d.ts +27 -114
  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 +17 -0
  63. package/build/types/qss.d.ts +2 -0
  64. package/build/types/redirects.d.ts +11 -0
  65. package/build/types/route.d.ts +279 -0
  66. package/build/types/routeInfo.d.ts +22 -0
  67. package/build/types/router.d.ts +183 -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 +2794 -2481
  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 +101 -0
  81. package/src/Matches.tsx +428 -0
  82. package/src/RouterProvider.tsx +254 -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 -714
  88. package/src/injectHtml.ts +28 -0
  89. package/src/lazyRouteComponent.tsx +33 -0
  90. package/src/link.tsx +509 -0
  91. package/src/location.ts +15 -0
  92. package/src/path.ts +261 -0
  93. package/src/qss.ts +53 -0
  94. package/src/redirects.ts +39 -0
  95. package/src/route.ts +915 -0
  96. package/src/routeInfo.ts +68 -0
  97. package/src/router.ts +1750 -0
  98. package/src/scroll-restoration.tsx +230 -0
  99. package/src/searchParams.ts +79 -0
  100. package/src/useBlocker.tsx +26 -0
  101. package/src/useNavigate.tsx +110 -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 -2530
  108. package/build/cjs/router-core/build/esm/index.js.map +0 -1
package/src/router.ts ADDED
@@ -0,0 +1,1750 @@
1
+ import {
2
+ HistoryLocation,
3
+ HistoryState,
4
+ RouterHistory,
5
+ createBrowserHistory,
6
+ createMemoryHistory,
7
+ } from '@tanstack/history'
8
+ import { Store } from '@tanstack/store'
9
+
10
+ //
11
+
12
+ import {
13
+ AnySearchSchema,
14
+ AnyRoute,
15
+ AnyContext,
16
+ AnyPathParams,
17
+ RouteMask,
18
+ Route,
19
+ LoaderFnContext,
20
+ } from './route'
21
+ import { FullSearchSchema, RoutesById, RoutesByPath } from './routeInfo'
22
+ import { defaultParseSearch, defaultStringifySearch } from './searchParams'
23
+ import {
24
+ PickAsRequired,
25
+ Updater,
26
+ NonNullableUpdater,
27
+ replaceEqualDeep,
28
+ deepEqual,
29
+ escapeJSON,
30
+ functionalUpdate,
31
+ last,
32
+ pick,
33
+ } from './utils'
34
+ import {
35
+ ErrorRouteComponent,
36
+ PendingRouteComponent,
37
+ RouteComponent,
38
+ } from './route'
39
+ import { AnyRouteMatch, RouteMatch } from './Matches'
40
+ import { ParsedLocation } from './location'
41
+ import { LocationState } from './location'
42
+ import { SearchSerializer, SearchParser } from './searchParams'
43
+ import {
44
+ BuildLinkFn,
45
+ BuildLocationFn,
46
+ CommitLocationOptions,
47
+ InjectedHtmlEntry,
48
+ MatchRouteFn,
49
+ NavigateFn,
50
+ getRouteMatch,
51
+ } from './RouterProvider'
52
+
53
+ import {
54
+ cleanPath,
55
+ interpolatePath,
56
+ joinPaths,
57
+ matchPathname,
58
+ parsePathname,
59
+ removeBasepath,
60
+ resolvePath,
61
+ trimPath,
62
+ trimPathLeft,
63
+ trimPathRight,
64
+ } from './path'
65
+ import invariant from 'tiny-invariant'
66
+ import { isRedirect } from './redirects'
67
+ // import warning from 'tiny-warning'
68
+
69
+ //
70
+
71
+ declare global {
72
+ interface Window {
73
+ __TSR_DEHYDRATED__?: HydrationCtx
74
+ __TSR_ROUTER_CONTEXT__?: React.Context<Router<any>>
75
+ }
76
+ }
77
+
78
+ export interface Register {
79
+ // router: Router
80
+ }
81
+
82
+ export type AnyRouter = Router<AnyRoute, any>
83
+
84
+ export type RegisteredRouter = Register extends {
85
+ router: infer TRouter extends AnyRouter
86
+ }
87
+ ? TRouter
88
+ : AnyRouter
89
+
90
+ export type HydrationCtx = {
91
+ router: DehydratedRouter
92
+ payload: Record<string, any>
93
+ }
94
+
95
+ export type RouterContextOptions<TRouteTree extends AnyRoute> =
96
+ AnyContext extends TRouteTree['types']['routerContext']
97
+ ? {
98
+ context?: TRouteTree['types']['routerContext']
99
+ }
100
+ : {
101
+ context: TRouteTree['types']['routerContext']
102
+ }
103
+
104
+ export interface RouterOptions<
105
+ TRouteTree extends AnyRoute,
106
+ TDehydrated extends Record<string, any> = Record<string, any>,
107
+ > {
108
+ history?: RouterHistory
109
+ stringifySearch?: SearchSerializer
110
+ parseSearch?: SearchParser
111
+ defaultPreload?: false | 'intent'
112
+ defaultPreloadDelay?: number
113
+ defaultComponent?: RouteComponent<AnySearchSchema, AnyPathParams, AnyContext>
114
+ defaultErrorComponent?: ErrorRouteComponent<
115
+ AnySearchSchema,
116
+ AnyPathParams,
117
+ AnyContext
118
+ >
119
+ defaultPendingComponent?: PendingRouteComponent<
120
+ AnySearchSchema,
121
+ AnyPathParams,
122
+ AnyContext
123
+ >
124
+ defaultPendingMs?: number
125
+ defaultPendingMinMs?: number
126
+ caseSensitive?: boolean
127
+ routeTree?: TRouteTree
128
+ basepath?: string
129
+ context?: TRouteTree['types']['routerContext']
130
+ dehydrate?: () => TDehydrated
131
+ hydrate?: (dehydrated: TDehydrated) => void
132
+ routeMasks?: RouteMask<TRouteTree>[]
133
+ unmaskOnReload?: boolean
134
+ Wrap?: (props: { children: any }) => JSX.Element
135
+ notFoundRoute?: AnyRoute
136
+ }
137
+
138
+ export interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {
139
+ status: 'pending' | 'idle'
140
+ isLoading: boolean
141
+ isTransitioning: boolean
142
+ matches: RouteMatch<TRouteTree>[]
143
+ pendingMatches?: RouteMatch<TRouteTree>[]
144
+ location: ParsedLocation<FullSearchSchema<TRouteTree>>
145
+ resolvedLocation: ParsedLocation<FullSearchSchema<TRouteTree>>
146
+ lastUpdated: number
147
+ }
148
+
149
+ export type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void
150
+
151
+ export interface BuildNextOptions {
152
+ to?: string | number | null
153
+ params?: true | Updater<unknown>
154
+ search?: true | Updater<unknown>
155
+ hash?: true | Updater<string>
156
+ state?: true | NonNullableUpdater<LocationState>
157
+ mask?: {
158
+ to?: string | number | null
159
+ params?: true | Updater<unknown>
160
+ search?: true | Updater<unknown>
161
+ hash?: true | Updater<string>
162
+ state?: true | NonNullableUpdater<LocationState>
163
+ unmaskOnReload?: boolean
164
+ }
165
+ from?: string
166
+ }
167
+
168
+ export interface DehydratedRouterState {
169
+ dehydratedMatches: DehydratedRouteMatch[]
170
+ }
171
+
172
+ export type DehydratedRouteMatch = Pick<
173
+ RouteMatch,
174
+ 'fetchedAt' | 'invalid' | 'id' | 'status' | 'updatedAt'
175
+ >
176
+
177
+ export interface DehydratedRouter {
178
+ state: DehydratedRouterState
179
+ }
180
+
181
+ export type RouterConstructorOptions<
182
+ TRouteTree extends AnyRoute,
183
+ TDehydrated extends Record<string, any>,
184
+ > = Omit<RouterOptions<TRouteTree, TDehydrated>, 'context'> &
185
+ RouterContextOptions<TRouteTree>
186
+
187
+ export const componentTypes = [
188
+ 'component',
189
+ 'errorComponent',
190
+ 'pendingComponent',
191
+ ] as const
192
+
193
+ export type RouterEvents = {
194
+ onBeforeLoad: {
195
+ type: 'onBeforeLoad'
196
+ fromLocation: ParsedLocation
197
+ toLocation: ParsedLocation
198
+ pathChanged: boolean
199
+ }
200
+ onLoad: {
201
+ type: 'onLoad'
202
+ fromLocation: ParsedLocation
203
+ toLocation: ParsedLocation
204
+ pathChanged: boolean
205
+ }
206
+ onResolved: {
207
+ type: 'onResolved'
208
+ fromLocation: ParsedLocation
209
+ toLocation: ParsedLocation
210
+ pathChanged: boolean
211
+ }
212
+ }
213
+
214
+ export type RouterEvent = RouterEvents[keyof RouterEvents]
215
+
216
+ export type RouterListener<TRouterEvent extends RouterEvent> = {
217
+ eventType: TRouterEvent['type']
218
+ fn: ListenerFn<TRouterEvent>
219
+ }
220
+
221
+ type LinkCurrentTargetElement = {
222
+ preloadTimeout?: null | ReturnType<typeof setTimeout>
223
+ }
224
+
225
+ const preloadWarning = 'Error preloading route! ☝️'
226
+
227
+ export class Router<
228
+ TRouteTree extends AnyRoute = AnyRoute,
229
+ TDehydrated extends Record<string, any> = Record<string, any>,
230
+ > {
231
+ // Option-independent properties
232
+ tempLocationKey: string | undefined = `${Math.round(
233
+ Math.random() * 10000000,
234
+ )}`
235
+ resetNextScroll: boolean = true
236
+ navigateTimeout: NodeJS.Timeout | null = null
237
+ latestLoadPromise: Promise<void> = Promise.resolve()
238
+ subscribers = new Set<RouterListener<RouterEvent>>()
239
+ pendingMatches: AnyRouteMatch[] = []
240
+ injectedHtml: InjectedHtmlEntry[] = []
241
+ dehydratedData?: TDehydrated
242
+
243
+ // Must build in constructor
244
+ __store!: Store<RouterState<TRouteTree>>
245
+ options!: PickAsRequired<
246
+ RouterOptions<TRouteTree, TDehydrated>,
247
+ 'stringifySearch' | 'parseSearch' | 'context'
248
+ >
249
+ history!: RouterHistory
250
+ latestLocation!: ParsedLocation
251
+ basepath!: string
252
+ routeTree!: TRouteTree
253
+ routesById!: RoutesById<TRouteTree>
254
+ routesByPath!: RoutesByPath<TRouteTree>
255
+ flatRoutes!: AnyRoute[]
256
+
257
+ constructor(options: RouterConstructorOptions<TRouteTree, TDehydrated>) {
258
+ this.update({
259
+ defaultPreloadDelay: 50,
260
+ defaultPendingMs: 1000,
261
+ defaultPendingMinMs: 500,
262
+ context: undefined!,
263
+ ...options,
264
+ stringifySearch: options?.stringifySearch ?? defaultStringifySearch,
265
+ parseSearch: options?.parseSearch ?? defaultParseSearch,
266
+ })
267
+ }
268
+
269
+ // These are default implementations that can optionally be overridden
270
+ // by the router provider once rendered. We provide these so that the
271
+ // router can be used in a non-react environment if necessary
272
+ startReactTransition: (fn: () => void) => void = (fn) => fn()
273
+
274
+ update = (newOptions: RouterConstructorOptions<TRouteTree, TDehydrated>) => {
275
+ this.options = {
276
+ ...this.options,
277
+ ...newOptions,
278
+ }
279
+
280
+ this.basepath = `/${trimPath(newOptions.basepath ?? '') ?? ''}`
281
+
282
+ if (
283
+ !this.history ||
284
+ (this.options.history && this.options.history !== this.history)
285
+ ) {
286
+ this.history =
287
+ this.options.history ??
288
+ (typeof document !== 'undefined'
289
+ ? createBrowserHistory()
290
+ : createMemoryHistory())
291
+ this.latestLocation = this.parseLocation()
292
+ }
293
+
294
+ if (this.options.routeTree !== this.routeTree) {
295
+ this.routeTree = this.options.routeTree as TRouteTree
296
+ this.buildRouteTree()
297
+ }
298
+
299
+ if (!this.__store) {
300
+ this.__store = new Store(getInitialRouterState(this.latestLocation), {
301
+ onUpdate: () => {
302
+ this.__store.state = {
303
+ ...this.state,
304
+ status:
305
+ this.state.isTransitioning || this.state.isLoading
306
+ ? 'pending'
307
+ : 'idle',
308
+ }
309
+ },
310
+ })
311
+ }
312
+ }
313
+
314
+ get state() {
315
+ return this.__store.state
316
+ }
317
+
318
+ buildRouteTree = () => {
319
+ this.routesById = {} as RoutesById<TRouteTree>
320
+ this.routesByPath = {} as RoutesByPath<TRouteTree>
321
+
322
+ const notFoundRoute = this.options.notFoundRoute
323
+ if (notFoundRoute) {
324
+ notFoundRoute.init({ originalIndex: 99999999999 })
325
+ ;(this.routesById as any)[notFoundRoute.id] = notFoundRoute
326
+ }
327
+
328
+ const recurseRoutes = (childRoutes: AnyRoute[]) => {
329
+ childRoutes.forEach((childRoute, i) => {
330
+ childRoute.init({ originalIndex: i })
331
+
332
+ const existingRoute = (this.routesById as any)[childRoute.id]
333
+
334
+ invariant(
335
+ !existingRoute,
336
+ `Duplicate routes found with id: ${String(childRoute.id)}`,
337
+ )
338
+ ;(this.routesById as any)[childRoute.id] = childRoute
339
+
340
+ if (!childRoute.isRoot && childRoute.path) {
341
+ const trimmedFullPath = trimPathRight(childRoute.fullPath)
342
+ if (
343
+ !(this.routesByPath as any)[trimmedFullPath] ||
344
+ childRoute.fullPath.endsWith('/')
345
+ ) {
346
+ ;(this.routesByPath as any)[trimmedFullPath] = childRoute
347
+ }
348
+ }
349
+
350
+ const children = childRoute.children as Route[]
351
+
352
+ if (children?.length) {
353
+ recurseRoutes(children)
354
+ }
355
+ })
356
+ }
357
+
358
+ recurseRoutes([this.routeTree])
359
+
360
+ const scoredRoutes: {
361
+ child: AnyRoute
362
+ trimmed: string
363
+ parsed: ReturnType<typeof parsePathname>
364
+ index: number
365
+ score: number[]
366
+ }[] = []
367
+
368
+ ;(Object.values(this.routesById) as AnyRoute[]).forEach((d, i) => {
369
+ if (d.isRoot || !d.path) {
370
+ return
371
+ }
372
+
373
+ const trimmed = trimPathLeft(d.fullPath)
374
+ const parsed = parsePathname(trimmed)
375
+
376
+ while (parsed.length > 1 && parsed[0]?.value === '/') {
377
+ parsed.shift()
378
+ }
379
+
380
+ const score = parsed.map((d) => {
381
+ if (d.type === 'param') {
382
+ return 0.5
383
+ }
384
+
385
+ if (d.type === 'wildcard') {
386
+ return 0.25
387
+ }
388
+
389
+ return 1
390
+ })
391
+
392
+ scoredRoutes.push({ child: d, trimmed, parsed, index: i, score })
393
+ })
394
+
395
+ this.flatRoutes = scoredRoutes
396
+ .sort((a, b) => {
397
+ let isIndex = a.trimmed === '/' ? 1 : b.trimmed === '/' ? -1 : 0
398
+
399
+ if (isIndex !== 0) return isIndex
400
+
401
+ const length = Math.min(a.score.length, b.score.length)
402
+
403
+ // Sort by length of score
404
+ if (a.score.length !== b.score.length) {
405
+ return b.score.length - a.score.length
406
+ }
407
+
408
+ // Sort by min available score
409
+ for (let i = 0; i < length; i++) {
410
+ if (a.score[i] !== b.score[i]) {
411
+ return b.score[i]! - a.score[i]!
412
+ }
413
+ }
414
+
415
+ // Sort by min available parsed value
416
+ for (let i = 0; i < length; i++) {
417
+ if (a.parsed[i]!.value !== b.parsed[i]!.value) {
418
+ return a.parsed[i]!.value! > b.parsed[i]!.value! ? 1 : -1
419
+ }
420
+ }
421
+
422
+ // Sort by length of trimmed full path
423
+ if (a.trimmed !== b.trimmed) {
424
+ return a.trimmed > b.trimmed ? 1 : -1
425
+ }
426
+
427
+ // Sort by original index
428
+ return a.index - b.index
429
+ })
430
+ .map((d, i) => {
431
+ d.child.rank = i
432
+ return d.child
433
+ })
434
+ }
435
+
436
+ subscribe = <TType extends keyof RouterEvents>(
437
+ eventType: TType,
438
+ fn: ListenerFn<RouterEvents[TType]>,
439
+ ) => {
440
+ const listener: RouterListener<any> = {
441
+ eventType,
442
+ fn,
443
+ }
444
+
445
+ this.subscribers.add(listener)
446
+
447
+ return () => {
448
+ this.subscribers.delete(listener)
449
+ }
450
+ }
451
+
452
+ emit = (routerEvent: RouterEvent) => {
453
+ this.subscribers.forEach((listener) => {
454
+ if (listener.eventType === routerEvent.type) {
455
+ listener.fn(routerEvent)
456
+ }
457
+ })
458
+ }
459
+
460
+ checkLatest = (promise: Promise<void>): undefined | Promise<void> => {
461
+ return this.latestLoadPromise !== promise
462
+ ? this.latestLoadPromise
463
+ : undefined
464
+ }
465
+
466
+ parseLocation = (
467
+ previousLocation?: ParsedLocation,
468
+ ): ParsedLocation<FullSearchSchema<TRouteTree>> => {
469
+ const parse = ({
470
+ pathname,
471
+ search,
472
+ hash,
473
+ state,
474
+ }: HistoryLocation): ParsedLocation<FullSearchSchema<TRouteTree>> => {
475
+ const parsedSearch = this.options.parseSearch(search)
476
+
477
+ return {
478
+ pathname: pathname,
479
+ searchStr: search,
480
+ search: replaceEqualDeep(previousLocation?.search, parsedSearch) as any,
481
+ hash: hash.split('#').reverse()[0] ?? '',
482
+ href: `${pathname}${search}${hash}`,
483
+ state: replaceEqualDeep(previousLocation?.state, state) as HistoryState,
484
+ }
485
+ }
486
+
487
+ const location = parse(this.history.location)
488
+
489
+ let { __tempLocation, __tempKey } = location.state
490
+
491
+ if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
492
+ // Sync up the location keys
493
+ const parsedTempLocation = parse(__tempLocation) as any
494
+ parsedTempLocation.state.key = location.state.key
495
+
496
+ delete parsedTempLocation.state.__tempLocation
497
+
498
+ return {
499
+ ...parsedTempLocation,
500
+ maskedLocation: location,
501
+ }
502
+ }
503
+
504
+ return location
505
+ }
506
+
507
+ resolvePathWithBase = (from: string, path: string) => {
508
+ return resolvePath(this.basepath!, from, cleanPath(path))
509
+ }
510
+
511
+ get looseRoutesById() {
512
+ return this.routesById as Record<string, AnyRoute>
513
+ }
514
+
515
+ matchRoutes = <TRouteTree extends AnyRoute>(
516
+ pathname: string,
517
+ locationSearch: AnySearchSchema,
518
+ opts?: { throwOnError?: boolean; debug?: boolean },
519
+ ): RouteMatch<TRouteTree>[] => {
520
+ let routeParams: Record<string, string> = {}
521
+
522
+ let foundRoute = this.flatRoutes.find((route) => {
523
+ const matchedParams = matchPathname(
524
+ this.basepath,
525
+ trimPathRight(pathname),
526
+ {
527
+ to: route.fullPath,
528
+ caseSensitive:
529
+ route.options.caseSensitive ?? this.options.caseSensitive,
530
+ fuzzy: true,
531
+ },
532
+ )
533
+
534
+ if (matchedParams) {
535
+ routeParams = matchedParams
536
+ return true
537
+ }
538
+
539
+ return false
540
+ })
541
+
542
+ let routeCursor: AnyRoute =
543
+ foundRoute || (this.routesById as any)['__root__']
544
+
545
+ let matchedRoutes: AnyRoute[] = [routeCursor]
546
+
547
+ // Check to see if the route needs a 404 entry
548
+ if (
549
+ // If we found a route, and it's not an index route and we have left over path
550
+ (foundRoute
551
+ ? foundRoute.path !== '/' && routeParams['**']
552
+ : // Or if we didn't find a route and we have left over path
553
+ trimPathRight(pathname)) &&
554
+ // And we have a 404 route configured
555
+ this.options.notFoundRoute
556
+ ) {
557
+ matchedRoutes.push(this.options.notFoundRoute)
558
+ }
559
+
560
+ while (routeCursor?.parentRoute) {
561
+ routeCursor = routeCursor.parentRoute
562
+ if (routeCursor) matchedRoutes.unshift(routeCursor)
563
+ }
564
+
565
+ // Existing matches are matches that are already loaded along with
566
+ // pending matches that are still loading
567
+
568
+ const parseErrors = matchedRoutes.map((route) => {
569
+ let parsedParamsError
570
+
571
+ if (route.options.parseParams) {
572
+ try {
573
+ const parsedParams = route.options.parseParams(routeParams)
574
+ // Add the parsed params to the accumulated params bag
575
+ Object.assign(routeParams, parsedParams)
576
+ } catch (err: any) {
577
+ parsedParamsError = new PathParamError(err.message, {
578
+ cause: err,
579
+ })
580
+
581
+ if (opts?.throwOnError) {
582
+ throw parsedParamsError
583
+ }
584
+
585
+ return parsedParamsError
586
+ }
587
+ }
588
+
589
+ return
590
+ })
591
+
592
+ const matches: AnyRouteMatch[] = []
593
+
594
+ matchedRoutes.forEach((route, index) => {
595
+ // Take each matched route and resolve + validate its search params
596
+ // This has to happen serially because each route's search params
597
+ // can depend on the parent route's search params
598
+ // It must also happen before we create the match so that we can
599
+ // pass the search params to the route's potential key function
600
+ // which is used to uniquely identify the route match in state
601
+
602
+ const parentMatch = matches[index - 1]
603
+
604
+ const [preMatchSearch, searchError]: [Record<string, any>, any] = (() => {
605
+ // Validate the search params and stabilize them
606
+ const parentSearch = parentMatch?.search ?? locationSearch
607
+
608
+ try {
609
+ const validator =
610
+ typeof route.options.validateSearch === 'object'
611
+ ? route.options.validateSearch.parse
612
+ : route.options.validateSearch
613
+
614
+ let search = validator?.(parentSearch) ?? {}
615
+
616
+ return [
617
+ {
618
+ ...parentSearch,
619
+ ...search,
620
+ },
621
+ undefined,
622
+ ]
623
+ } catch (err: any) {
624
+ const searchError = new SearchParamError(err.message, {
625
+ cause: err,
626
+ })
627
+
628
+ if (opts?.throwOnError) {
629
+ throw searchError
630
+ }
631
+
632
+ return [parentSearch, searchError]
633
+ }
634
+ })()
635
+
636
+ const interpolatedPath = interpolatePath(route.fullPath, routeParams)
637
+ const matchId =
638
+ interpolatePath(route.id, routeParams, true) +
639
+ (route.options.key?.({
640
+ search: preMatchSearch,
641
+ location: this.state.location,
642
+ }) ?? '')
643
+
644
+ // Waste not, want not. If we already have a match for this route,
645
+ // reuse it. This is important for layout routes, which might stick
646
+ // around between navigation actions that only change leaf routes.
647
+ const existingMatch = getRouteMatch(this.state, matchId)
648
+
649
+ const cause = this.state.matches.find((d) => d.id === matchId)
650
+ ? 'stay'
651
+ : 'enter'
652
+
653
+ // Create a fresh route match
654
+ const hasLoaders = !!(
655
+ route.options.loader ||
656
+ componentTypes.some((d) => (route.options[d] as any)?.preload)
657
+ )
658
+
659
+ const match: AnyRouteMatch = existingMatch
660
+ ? { ...existingMatch, cause }
661
+ : {
662
+ id: matchId,
663
+ routeId: route.id,
664
+ params: routeParams,
665
+ pathname: joinPaths([this.basepath, interpolatedPath]),
666
+ updatedAt: Date.now(),
667
+ search: {} as any,
668
+ searchError: undefined,
669
+ status: hasLoaders ? 'pending' : 'success',
670
+ showPending: false,
671
+ isFetching: false,
672
+ invalid: false,
673
+ error: undefined,
674
+ paramsError: parseErrors[index],
675
+ loadPromise: Promise.resolve(),
676
+ context: undefined!,
677
+ abortController: new AbortController(),
678
+ shouldReloadDeps: undefined,
679
+ fetchedAt: 0,
680
+ cause,
681
+ }
682
+
683
+ // Regardless of whether we're reusing an existing match or creating
684
+ // a new one, we need to update the match's search params
685
+ match.search = replaceEqualDeep(match.search, preMatchSearch)
686
+ // And also update the searchError if there is one
687
+ match.searchError = searchError
688
+
689
+ matches.push(match)
690
+ })
691
+
692
+ return matches as any
693
+ }
694
+
695
+ cancelMatch = (id: string) => {
696
+ getRouteMatch(this.state, id)?.abortController?.abort()
697
+ }
698
+
699
+ cancelMatches = () => {
700
+ this.state.pendingMatches?.forEach((match) => {
701
+ this.cancelMatch(match.id)
702
+ })
703
+ }
704
+
705
+ buildLocation: BuildLocationFn<TRouteTree> = (opts) => {
706
+ const build = (
707
+ dest: BuildNextOptions & {
708
+ unmaskOnReload?: boolean
709
+ } = {},
710
+ matches?: AnyRouteMatch[],
711
+ ): ParsedLocation => {
712
+ const from = this.latestLocation
713
+ const fromSearch =
714
+ (this.state.pendingMatches || this.state.matches).at(-1)?.search ||
715
+ from.search
716
+ const fromPathname = dest.from ?? from.pathname
717
+
718
+ let pathname = this.resolvePathWithBase(fromPathname, `${dest.to ?? ''}`)
719
+
720
+ const fromMatches = this.matchRoutes(fromPathname, fromSearch)
721
+ const stayingMatches = matches?.filter(
722
+ (d) => fromMatches?.find((e) => e.routeId === d.routeId),
723
+ )
724
+
725
+ const prevParams = { ...last(fromMatches)?.params }
726
+
727
+ let nextParams =
728
+ (dest.params ?? true) === true
729
+ ? prevParams
730
+ : functionalUpdate(dest.params!, prevParams)
731
+
732
+ if (nextParams) {
733
+ matches
734
+ ?.map((d) => this.looseRoutesById[d.routeId]!.options.stringifyParams)
735
+ .filter(Boolean)
736
+ .forEach((fn) => {
737
+ nextParams = { ...nextParams!, ...fn!(nextParams!) }
738
+ })
739
+ }
740
+
741
+ pathname = interpolatePath(pathname, nextParams ?? {})
742
+
743
+ const preSearchFilters =
744
+ stayingMatches
745
+ ?.map(
746
+ (match) =>
747
+ this.looseRoutesById[match.routeId]!.options.preSearchFilters ??
748
+ [],
749
+ )
750
+ .flat()
751
+ .filter(Boolean) ?? []
752
+
753
+ const postSearchFilters =
754
+ stayingMatches
755
+ ?.map(
756
+ (match) =>
757
+ this.looseRoutesById[match.routeId]!.options.postSearchFilters ??
758
+ [],
759
+ )
760
+ .flat()
761
+ .filter(Boolean) ?? []
762
+
763
+ // Pre filters first
764
+ const preFilteredSearch = preSearchFilters?.length
765
+ ? preSearchFilters?.reduce(
766
+ (prev, next) => next(prev) as any,
767
+ fromSearch,
768
+ )
769
+ : fromSearch
770
+
771
+ // Then the link/navigate function
772
+ const destSearch =
773
+ dest.search === true
774
+ ? preFilteredSearch // Preserve resolvedFrom true
775
+ : dest.search
776
+ ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
777
+ : preSearchFilters?.length
778
+ ? preFilteredSearch // Preserve resolvedFrom filters
779
+ : {}
780
+
781
+ // Then post filters
782
+ const postFilteredSearch = postSearchFilters?.length
783
+ ? postSearchFilters.reduce((prev, next) => next(prev), destSearch)
784
+ : destSearch
785
+
786
+ const search = replaceEqualDeep(fromSearch, postFilteredSearch)
787
+
788
+ const searchStr = this.options.stringifySearch(search)
789
+
790
+ const hash =
791
+ dest.hash === true
792
+ ? from.hash
793
+ : dest.hash
794
+ ? functionalUpdate(dest.hash!, from.hash)
795
+ : from.hash
796
+
797
+ const hashStr = hash ? `#${hash}` : ''
798
+
799
+ let nextState =
800
+ dest.state === true
801
+ ? from.state
802
+ : dest.state
803
+ ? functionalUpdate(dest.state, from.state)
804
+ : from.state
805
+
806
+ nextState = replaceEqualDeep(from.state, nextState)
807
+
808
+ return {
809
+ pathname,
810
+ search,
811
+ searchStr,
812
+ state: nextState as any,
813
+ hash,
814
+ href: `${pathname}${searchStr}${hashStr}`,
815
+ unmaskOnReload: dest.unmaskOnReload,
816
+ }
817
+ }
818
+
819
+ const buildWithMatches = (
820
+ dest: BuildNextOptions = {},
821
+ maskedDest?: BuildNextOptions,
822
+ ) => {
823
+ let next = build(dest)
824
+ let maskedNext = maskedDest ? build(maskedDest) : undefined
825
+
826
+ if (!maskedNext) {
827
+ let params = {}
828
+
829
+ let foundMask = this.options.routeMasks?.find((d) => {
830
+ const match = matchPathname(this.basepath, next.pathname, {
831
+ to: d.from,
832
+ caseSensitive: false,
833
+ fuzzy: false,
834
+ })
835
+
836
+ if (match) {
837
+ params = match
838
+ return true
839
+ }
840
+
841
+ return false
842
+ })
843
+
844
+ if (foundMask) {
845
+ foundMask = {
846
+ ...foundMask,
847
+ from: interpolatePath(foundMask.from, params) as any,
848
+ }
849
+ maskedDest = foundMask
850
+ maskedNext = build(maskedDest)
851
+ }
852
+ }
853
+
854
+ const nextMatches = this.matchRoutes(next.pathname, next.search)
855
+ const maskedMatches = maskedNext
856
+ ? this.matchRoutes(maskedNext.pathname, maskedNext.search)
857
+ : undefined
858
+ const maskedFinal = maskedNext
859
+ ? build(maskedDest, maskedMatches)
860
+ : undefined
861
+
862
+ const final = build(dest, nextMatches)
863
+
864
+ if (maskedFinal) {
865
+ final.maskedLocation = maskedFinal
866
+ }
867
+
868
+ return final
869
+ }
870
+
871
+ if (opts.mask) {
872
+ return buildWithMatches(opts, {
873
+ ...pick(opts, ['from']),
874
+ ...opts.mask,
875
+ })
876
+ }
877
+
878
+ return buildWithMatches(opts)
879
+ }
880
+
881
+ commitLocation = async ({
882
+ startTransition,
883
+ ...next
884
+ }: ParsedLocation & CommitLocationOptions) => {
885
+ if (this.navigateTimeout) clearTimeout(this.navigateTimeout)
886
+
887
+ const isSameUrl = this.latestLocation.href === next.href
888
+
889
+ // If the next urls are the same and we're not replacing,
890
+ // do nothing
891
+ if (!isSameUrl || !next.replace) {
892
+ let { maskedLocation, ...nextHistory } = next
893
+
894
+ if (maskedLocation) {
895
+ nextHistory = {
896
+ ...maskedLocation,
897
+ state: {
898
+ ...maskedLocation.state,
899
+ __tempKey: undefined,
900
+ __tempLocation: {
901
+ ...nextHistory,
902
+ search: nextHistory.searchStr,
903
+ state: {
904
+ ...nextHistory.state,
905
+ __tempKey: undefined!,
906
+ __tempLocation: undefined!,
907
+ key: undefined!,
908
+ },
909
+ },
910
+ },
911
+ }
912
+
913
+ if (
914
+ nextHistory.unmaskOnReload ??
915
+ this.options.unmaskOnReload ??
916
+ false
917
+ ) {
918
+ nextHistory.state.__tempKey = this.tempLocationKey
919
+ }
920
+ }
921
+
922
+ const apply = () => {
923
+ this.history[next.replace ? 'replace' : 'push'](
924
+ nextHistory.href,
925
+ nextHistory.state,
926
+ )
927
+ }
928
+
929
+ if (startTransition ?? true) {
930
+ this.startReactTransition(apply)
931
+ } else {
932
+ apply()
933
+ }
934
+ }
935
+
936
+ this.resetNextScroll = next.resetScroll ?? true
937
+
938
+ return this.latestLoadPromise
939
+ }
940
+
941
+ buildAndCommitLocation = ({
942
+ replace,
943
+ resetScroll,
944
+ startTransition,
945
+ ...rest
946
+ }: BuildNextOptions & CommitLocationOptions = {}) => {
947
+ const location = this.buildLocation(rest)
948
+ return this.commitLocation({
949
+ ...location,
950
+ startTransition,
951
+ replace,
952
+ resetScroll,
953
+ })
954
+ }
955
+
956
+ navigate: NavigateFn<TRouteTree> = ({ from, to = '', ...rest }) => {
957
+ // If this link simply reloads the current route,
958
+ // make sure it has a new key so it will trigger a data refresh
959
+
960
+ // If this `to` is a valid external URL, return
961
+ // null for LinkUtils
962
+ const toString = String(to)
963
+ const fromString = typeof from === 'undefined' ? from : String(from)
964
+ let isExternal
965
+
966
+ try {
967
+ new URL(`${toString}`)
968
+ isExternal = true
969
+ } catch (e) {}
970
+
971
+ invariant(
972
+ !isExternal,
973
+ 'Attempting to navigate to external url with this.navigate!',
974
+ )
975
+
976
+ return this.buildAndCommitLocation({
977
+ ...rest,
978
+ from: fromString,
979
+ to: toString,
980
+ })
981
+ }
982
+
983
+ loadMatches = async ({
984
+ checkLatest,
985
+ matches,
986
+ preload,
987
+ invalidate,
988
+ }: {
989
+ checkLatest: () => Promise<void> | undefined
990
+ matches: AnyRouteMatch[]
991
+ preload?: boolean
992
+ invalidate?: boolean
993
+ }): Promise<RouteMatch[]> => {
994
+ let latestPromise
995
+ let firstBadMatchIndex: number | undefined
996
+
997
+ const updatePendingMatch = (match: AnyRouteMatch) => {
998
+ this.__store.setState((s) => ({
999
+ ...s,
1000
+ pendingMatches: s.pendingMatches?.map((d) =>
1001
+ d.id === match.id ? match : d,
1002
+ ),
1003
+ }))
1004
+ }
1005
+
1006
+
1007
+
1008
+ // Check each match middleware to see if the route can be accessed
1009
+ try {
1010
+ for (let [index, match] of matches.entries()) {
1011
+ const parentMatch = matches[index - 1]
1012
+ const route = this.looseRoutesById[match.routeId]!
1013
+ const abortController = new AbortController()
1014
+
1015
+ const handleErrorAndRedirect = (err: any, code: string) => {
1016
+ err.routerCode = code
1017
+ firstBadMatchIndex = firstBadMatchIndex ?? index
1018
+
1019
+ if (isRedirect(err)) {
1020
+ throw err
1021
+ }
1022
+
1023
+ try {
1024
+ route.options.onError?.(err)
1025
+ } catch (errorHandlerErr) {
1026
+ err = errorHandlerErr
1027
+
1028
+ if (isRedirect(errorHandlerErr)) {
1029
+ throw errorHandlerErr
1030
+ }
1031
+ }
1032
+
1033
+ matches[index] = match = {
1034
+ ...match,
1035
+ error: err,
1036
+ status: 'error',
1037
+ updatedAt: Date.now(),
1038
+ abortController: new AbortController(),
1039
+ }
1040
+ }
1041
+
1042
+ try {
1043
+ if (match.paramsError) {
1044
+ handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS')
1045
+ }
1046
+
1047
+ if (match.searchError) {
1048
+ handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH')
1049
+ }
1050
+
1051
+ const parentContext =
1052
+ parentMatch?.context ?? this.options.context ?? {}
1053
+
1054
+ const beforeLoadContext =
1055
+ (await route.options.beforeLoad?.({
1056
+ search: match.search,
1057
+ abortController,
1058
+ params: match.params,
1059
+ preload: !!preload,
1060
+ context: parentContext,
1061
+ location: this.state.location,
1062
+ // TOOD: just expose state and router, etc
1063
+ navigate: (opts) =>
1064
+ this.navigate({ ...opts, from: match.pathname } as any),
1065
+ buildLocation: this.buildLocation,
1066
+ cause: match.cause,
1067
+ })) ?? ({} as any)
1068
+
1069
+ if (isRedirect(beforeLoadContext)) {
1070
+ throw beforeLoadContext
1071
+ }
1072
+
1073
+ const context = {
1074
+ ...parentContext,
1075
+ ...beforeLoadContext,
1076
+ }
1077
+
1078
+ matches[index] = match = {
1079
+ ...match,
1080
+ context: replaceEqualDeep(match.context, context),
1081
+ abortController,
1082
+ }
1083
+ } catch (err) {
1084
+ handleErrorAndRedirect(err, 'BEFORE_LOAD')
1085
+ break
1086
+ }
1087
+ }
1088
+ } catch (err) {
1089
+ if (isRedirect(err)) {
1090
+ if (!preload) this.navigate(err as any)
1091
+ return matches
1092
+ }
1093
+
1094
+ throw err
1095
+ }
1096
+
1097
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex)
1098
+ const matchPromises: Promise<any>[] = []
1099
+
1100
+ validResolvedMatches.forEach((match, index) => {
1101
+ matchPromises.push(
1102
+ (async () => {
1103
+ const parentMatchPromise = matchPromises[index - 1]
1104
+ const route = this.looseRoutesById[match.routeId]!
1105
+
1106
+ const handleErrorAndRedirect = (err: any) => {
1107
+ if (isRedirect(err)) {
1108
+ if (!preload) {
1109
+ this.navigate(err as any)
1110
+ }
1111
+ return true
1112
+ }
1113
+ return false
1114
+ }
1115
+
1116
+ let loadPromise: Promise<void> | undefined
1117
+
1118
+ matches[index] = match = {
1119
+ ...match,
1120
+ fetchedAt: Date.now(),
1121
+ invalid: false,
1122
+ showPending: false,
1123
+ }
1124
+
1125
+ const pendingMs =
1126
+ route.options.pendingMs ?? this.options.defaultPendingMs
1127
+
1128
+ let pendingPromise: Promise<void> | undefined
1129
+
1130
+ if (
1131
+ !preload &&
1132
+ pendingMs &&
1133
+ (route.options.pendingComponent ??
1134
+ this.options.defaultPendingComponent)
1135
+ ) {
1136
+ pendingPromise = new Promise((r) => setTimeout(r, pendingMs))
1137
+ }
1138
+
1139
+ if (match.isFetching) {
1140
+ loadPromise = getRouteMatch(this.state, match.id)?.loadPromise
1141
+ } else {
1142
+ const loaderContext: LoaderFnContext = {
1143
+ params: match.params,
1144
+ search: match.search,
1145
+ preload: !!preload,
1146
+ parentMatchPromise,
1147
+ abortController: match.abortController,
1148
+ context: match.context,
1149
+ location: this.state.location,
1150
+ navigate: (opts) =>
1151
+ this.navigate({ ...opts, from: match.pathname } as any),
1152
+ cause: match.cause,
1153
+ }
1154
+
1155
+ // Default to reloading the route all the time
1156
+ let shouldReload = true
1157
+
1158
+ let shouldReloadDeps =
1159
+ typeof route.options.shouldReload === 'function'
1160
+ ? route.options.shouldReload?.(loaderContext)
1161
+ : !!(route.options.shouldReload ?? true)
1162
+
1163
+ if (match.cause === 'enter' || invalidate) {
1164
+ match.shouldReloadDeps = shouldReloadDeps
1165
+ } else if (match.cause === 'stay') {
1166
+ if (typeof shouldReloadDeps === 'object') {
1167
+ // compare the deps to see if they've changed
1168
+ shouldReload = !deepEqual(
1169
+ shouldReloadDeps,
1170
+ match.shouldReloadDeps,
1171
+ )
1172
+
1173
+ match.shouldReloadDeps = shouldReloadDeps
1174
+ } else {
1175
+ shouldReload = !!shouldReloadDeps
1176
+ }
1177
+ }
1178
+
1179
+ // If the user doesn't want the route to reload, just
1180
+ // resolve with the existing loader data
1181
+
1182
+ if (!shouldReload) {
1183
+ loadPromise = Promise.resolve(match.loaderData)
1184
+ } else {
1185
+ // Otherwise, load the route
1186
+ matches[index] = match = {
1187
+ ...match,
1188
+ isFetching: true,
1189
+ }
1190
+
1191
+ const componentsPromise = Promise.all(
1192
+ componentTypes.map(async (type) => {
1193
+ const component = route.options[type]
1194
+
1195
+ if ((component as any)?.preload) {
1196
+ await (component as any).preload()
1197
+ }
1198
+ }),
1199
+ )
1200
+
1201
+ const loaderPromise = route.options.loader?.(loaderContext)
1202
+
1203
+ loadPromise = Promise.all([
1204
+ componentsPromise,
1205
+ loaderPromise,
1206
+ ]).then((d) => d[1])
1207
+ }
1208
+ }
1209
+
1210
+ matches[index] = match = {
1211
+ ...match,
1212
+ loadPromise,
1213
+ }
1214
+
1215
+ if (!preload) {
1216
+ updatePendingMatch(match)
1217
+ }
1218
+
1219
+ let didShowPending = false
1220
+ const pendingMinMs =
1221
+ route.options.pendingMinMs ?? this.options.defaultPendingMinMs
1222
+
1223
+ await new Promise<void>(async (resolve) => {
1224
+ // If the route has a pending component and a pendingMs option,
1225
+ // forcefully show the pending component
1226
+ if (pendingPromise) {
1227
+ pendingPromise.then(() => {
1228
+ if ((latestPromise = checkLatest())) return
1229
+
1230
+ didShowPending = true
1231
+ matches[index] = match = {
1232
+ ...match,
1233
+ showPending: true,
1234
+ }
1235
+
1236
+ updatePendingMatch(match)
1237
+ resolve()
1238
+ })
1239
+ }
1240
+
1241
+ try {
1242
+ const loaderData = await loadPromise
1243
+ if ((latestPromise = checkLatest())) return await latestPromise
1244
+
1245
+ if (isRedirect(loaderData)) {
1246
+ if (handleErrorAndRedirect(loaderData)) return
1247
+ }
1248
+
1249
+ if (didShowPending && pendingMinMs) {
1250
+ await new Promise((r) => setTimeout(r, pendingMinMs))
1251
+ }
1252
+
1253
+ if ((latestPromise = checkLatest())) return await latestPromise
1254
+
1255
+ matches[index] = match = {
1256
+ ...match,
1257
+ error: undefined,
1258
+ status: 'success',
1259
+ isFetching: false,
1260
+ updatedAt: Date.now(),
1261
+ loaderData,
1262
+ loadPromise: undefined,
1263
+ }
1264
+ } catch (error) {
1265
+ if ((latestPromise = checkLatest())) return await latestPromise
1266
+ if (handleErrorAndRedirect(error)) return
1267
+
1268
+ try {
1269
+ route.options.onError?.(error)
1270
+ } catch (onErrorError) {
1271
+ error = onErrorError
1272
+ if (handleErrorAndRedirect(onErrorError)) return
1273
+ }
1274
+
1275
+ matches[index] = match = {
1276
+ ...match,
1277
+ error,
1278
+ status: 'error',
1279
+ isFetching: false,
1280
+ updatedAt: Date.now(),
1281
+ }
1282
+ } finally {
1283
+ // If we showed the pending component, that means
1284
+ // we already moved the pendingMatches to the matches
1285
+ // state, so we need to update that specific match
1286
+ if (didShowPending && pendingMinMs && match.showPending) {
1287
+ this.__store.setState((s) => ({
1288
+ ...s,
1289
+ matches: s.matches?.map((d) =>
1290
+ d.id === match.id ? match : d,
1291
+ ),
1292
+ }))
1293
+ }
1294
+ }
1295
+
1296
+ if (!preload) {
1297
+ updatePendingMatch(match)
1298
+ }
1299
+
1300
+ resolve()
1301
+ })
1302
+ })(),
1303
+ )
1304
+ })
1305
+
1306
+ await Promise.all(matchPromises)
1307
+ return matches
1308
+ }
1309
+
1310
+ invalidate = () =>
1311
+ this.load({
1312
+ invalidate: true,
1313
+ })
1314
+
1315
+ load = async (opts?: { invalidate?: boolean }): Promise<void> => {
1316
+ const promise = new Promise<void>(async (resolve, reject) => {
1317
+ const next = this.latestLocation
1318
+ const prevLocation = this.state.resolvedLocation
1319
+ const pathDidChange = prevLocation!.href !== next.href
1320
+ let latestPromise: Promise<void> | undefined | null
1321
+
1322
+ // Cancel any pending matches
1323
+ this.cancelMatches()
1324
+
1325
+ this.emit({
1326
+ type: 'onBeforeLoad',
1327
+ fromLocation: prevLocation,
1328
+ toLocation: next,
1329
+ pathChanged: pathDidChange,
1330
+ })
1331
+
1332
+ // Match the routes
1333
+ let pendingMatches: RouteMatch<any, any>[] = this.matchRoutes(
1334
+ next.pathname,
1335
+ next.search,
1336
+ {
1337
+ debug: true,
1338
+ },
1339
+ )
1340
+
1341
+ const previousMatches = this.state.matches
1342
+
1343
+ // Ingest the new matches
1344
+ this.__store.setState((s) => ({
1345
+ ...s,
1346
+ isLoading: true,
1347
+ location: next,
1348
+ pendingMatches,
1349
+ }))
1350
+
1351
+ try {
1352
+ try {
1353
+ // Load the matches
1354
+ await this.loadMatches({
1355
+ matches: pendingMatches,
1356
+ checkLatest: () => this.checkLatest(promise),
1357
+ invalidate: opts?.invalidate,
1358
+ })
1359
+ } catch (err) {
1360
+ // swallow this error, since we'll display the
1361
+ // errors on the route components
1362
+ }
1363
+
1364
+ // Only apply the latest transition
1365
+ if ((latestPromise = this.checkLatest(promise))) {
1366
+ return latestPromise
1367
+ }
1368
+
1369
+ const exitingMatchIds = previousMatches.filter(
1370
+ (id) => !this.pendingMatches.includes(id),
1371
+ )
1372
+ const enteringMatchIds = this.pendingMatches.filter(
1373
+ (id) => !previousMatches.includes(id),
1374
+ )
1375
+ const stayingMatchIds = previousMatches.filter((id) =>
1376
+ this.pendingMatches.includes(id),
1377
+ )
1378
+
1379
+ this.__store.setState((s) => ({
1380
+ ...s,
1381
+ isLoading: false,
1382
+ matches: pendingMatches,
1383
+ pendingMatches: undefined,
1384
+ }))
1385
+
1386
+ //
1387
+ ;(
1388
+ [
1389
+ [exitingMatchIds, 'onLeave'],
1390
+ [enteringMatchIds, 'onEnter'],
1391
+ [stayingMatchIds, 'onTransition'],
1392
+ ] as const
1393
+ ).forEach(([matches, hook]) => {
1394
+ matches.forEach((match) => {
1395
+ this.looseRoutesById[match.routeId]!.options[hook]?.(match)
1396
+ })
1397
+ })
1398
+
1399
+ this.emit({
1400
+ type: 'onLoad',
1401
+ fromLocation: prevLocation,
1402
+ toLocation: next,
1403
+ pathChanged: pathDidChange,
1404
+ })
1405
+
1406
+ resolve()
1407
+ } catch (err) {
1408
+ // Only apply the latest transition
1409
+ if ((latestPromise = this.checkLatest(promise))) {
1410
+ return latestPromise
1411
+ }
1412
+
1413
+ reject(err)
1414
+ }
1415
+ })
1416
+
1417
+ this.latestLoadPromise = promise
1418
+
1419
+ return this.latestLoadPromise
1420
+ }
1421
+
1422
+ preloadRoute = async (
1423
+ navigateOpts: BuildNextOptions = this.state.location,
1424
+ ) => {
1425
+ let next = this.buildLocation(navigateOpts)
1426
+
1427
+ let matches = this.matchRoutes(next.pathname, next.search, {
1428
+ throwOnError: true,
1429
+ })
1430
+
1431
+ matches = await this.loadMatches({
1432
+ matches,
1433
+ preload: true,
1434
+ checkLatest: () => undefined,
1435
+ })
1436
+
1437
+ return matches
1438
+ }
1439
+
1440
+ buildLink: BuildLinkFn<TRouteTree> = (dest) => {
1441
+ // If this link simply reloads the current route,
1442
+ // make sure it has a new key so it will trigger a data refresh
1443
+
1444
+ // If this `to` is a valid external URL, return
1445
+ // null for LinkUtils
1446
+
1447
+ const {
1448
+ to,
1449
+ preload: userPreload,
1450
+ preloadDelay: userPreloadDelay,
1451
+ activeOptions,
1452
+ disabled,
1453
+ target,
1454
+ replace,
1455
+ resetScroll,
1456
+ startTransition,
1457
+ } = dest
1458
+
1459
+ try {
1460
+ new URL(`${to}`)
1461
+ return {
1462
+ type: 'external',
1463
+ href: to as any,
1464
+ }
1465
+ } catch (e) {}
1466
+
1467
+ const nextOpts = dest
1468
+ const next = this.buildLocation(nextOpts as any)
1469
+
1470
+ const preload = userPreload ?? this.options.defaultPreload
1471
+ const preloadDelay =
1472
+ userPreloadDelay ?? this.options.defaultPreloadDelay ?? 0
1473
+
1474
+ // Compare path/hash for matches
1475
+ const currentPathSplit = this.latestLocation.pathname.split('/')
1476
+ const nextPathSplit = next.pathname.split('/')
1477
+ const pathIsFuzzyEqual = nextPathSplit.every(
1478
+ (d, i) => d === currentPathSplit[i],
1479
+ )
1480
+ // Combine the matches based on user this.options
1481
+ const pathTest = activeOptions?.exact
1482
+ ? this.latestLocation.pathname === next.pathname
1483
+ : pathIsFuzzyEqual
1484
+ const hashTest = activeOptions?.includeHash
1485
+ ? this.latestLocation.hash === next.hash
1486
+ : true
1487
+ const searchTest =
1488
+ activeOptions?.includeSearch ?? true
1489
+ ? deepEqual(this.latestLocation.search, next.search, true)
1490
+ : true
1491
+
1492
+ // The final "active" test
1493
+ const isActive = pathTest && hashTest && searchTest
1494
+
1495
+ // The click handler
1496
+ const handleClick = (e: MouseEvent) => {
1497
+ if (
1498
+ !disabled &&
1499
+ !isCtrlEvent(e) &&
1500
+ !e.defaultPrevented &&
1501
+ (!target || target === '_self') &&
1502
+ e.button === 0
1503
+ ) {
1504
+ e.preventDefault()
1505
+
1506
+ // All is well? Navigate!
1507
+ this.commitLocation({ ...next, replace, resetScroll, startTransition })
1508
+ }
1509
+ }
1510
+
1511
+ // The click handler
1512
+ const handleFocus = (e: MouseEvent) => {
1513
+ if (preload) {
1514
+ this.preloadRoute(nextOpts as any).catch((err) => {
1515
+ console.warn(err)
1516
+ console.warn(preloadWarning)
1517
+ })
1518
+ }
1519
+ }
1520
+
1521
+ const handleTouchStart = (e: TouchEvent) => {
1522
+ if (preload) {
1523
+ this.preloadRoute(nextOpts as any).catch((err) => {
1524
+ console.warn(err)
1525
+ console.warn(preloadWarning)
1526
+ })
1527
+ }
1528
+ }
1529
+
1530
+ const handleEnter = (e: MouseEvent) => {
1531
+ const target = (e.target || {}) as LinkCurrentTargetElement
1532
+
1533
+ if (preload) {
1534
+ if (target.preloadTimeout) {
1535
+ return
1536
+ }
1537
+
1538
+ target.preloadTimeout = setTimeout(() => {
1539
+ target.preloadTimeout = null
1540
+ this.preloadRoute(nextOpts as any).catch((err) => {
1541
+ console.warn(err)
1542
+ console.warn(preloadWarning)
1543
+ })
1544
+ }, preloadDelay)
1545
+ }
1546
+ }
1547
+
1548
+ const handleLeave = (e: MouseEvent) => {
1549
+ const target = (e.target || {}) as LinkCurrentTargetElement
1550
+
1551
+ if (target.preloadTimeout) {
1552
+ clearTimeout(target.preloadTimeout)
1553
+ target.preloadTimeout = null
1554
+ }
1555
+ }
1556
+
1557
+ return {
1558
+ type: 'internal',
1559
+ next,
1560
+ handleFocus,
1561
+ handleClick,
1562
+ handleEnter,
1563
+ handleLeave,
1564
+ handleTouchStart,
1565
+ isActive,
1566
+ disabled,
1567
+ }
1568
+ }
1569
+
1570
+ matchRoute: MatchRouteFn<TRouteTree> = (location, opts) => {
1571
+ location = {
1572
+ ...location,
1573
+ to: location.to
1574
+ ? this.resolvePathWithBase((location.from || '') as string, location.to)
1575
+ : undefined,
1576
+ } as any
1577
+
1578
+ const next = this.buildLocation(location as any)
1579
+
1580
+ if (opts?.pending && this.state.status !== 'pending') {
1581
+ return false
1582
+ }
1583
+
1584
+ const baseLocation = opts?.pending
1585
+ ? this.latestLocation
1586
+ : this.state.resolvedLocation
1587
+
1588
+ if (!baseLocation) {
1589
+ return false
1590
+ }
1591
+
1592
+ const match = matchPathname(this.basepath, baseLocation.pathname, {
1593
+ ...opts,
1594
+ to: next.pathname,
1595
+ }) as any
1596
+
1597
+ if (!match) {
1598
+ return false
1599
+ }
1600
+
1601
+ if (match && (opts?.includeSearch ?? true)) {
1602
+ return deepEqual(baseLocation.search, next.search, true) ? match : false
1603
+ }
1604
+
1605
+ return match
1606
+ }
1607
+
1608
+ injectHtml = async (html: string | (() => Promise<string> | string)) => {
1609
+ this.injectedHtml.push(html)
1610
+ }
1611
+
1612
+ dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {
1613
+ if (typeof document === 'undefined') {
1614
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key)
1615
+
1616
+ this.injectHtml(async () => {
1617
+ const id = `__TSR_DEHYDRATED__${strKey}`
1618
+ const data =
1619
+ typeof getData === 'function' ? await (getData as any)() : getData
1620
+ return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${escapeJSON(
1621
+ strKey,
1622
+ )}"] = ${JSON.stringify(data)}
1623
+ ;(() => {
1624
+ var el = document.getElementById('${id}')
1625
+ el.parentElement.removeChild(el)
1626
+ })()
1627
+ </script>`
1628
+ })
1629
+
1630
+ return () => this.hydrateData<T>(key)
1631
+ }
1632
+
1633
+ return () => undefined
1634
+ }
1635
+
1636
+ hydrateData = <T extends any = unknown>(key: any) => {
1637
+ if (typeof document !== 'undefined') {
1638
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key)
1639
+
1640
+ return window[`__TSR_DEHYDRATED__${strKey}` as any] as T
1641
+ }
1642
+
1643
+ return undefined
1644
+ }
1645
+
1646
+ dehydrate = (): DehydratedRouter => {
1647
+ return {
1648
+ state: {
1649
+ dehydratedMatches: this.state.matches.map((d) =>
1650
+ pick(d, [
1651
+ 'fetchedAt',
1652
+ 'invalid',
1653
+ 'id',
1654
+ 'status',
1655
+ 'updatedAt',
1656
+ 'loaderData',
1657
+ ]),
1658
+ ),
1659
+ },
1660
+ }
1661
+ }
1662
+
1663
+ hydrate = async (__do_not_use_server_ctx?: HydrationCtx) => {
1664
+ let _ctx = __do_not_use_server_ctx
1665
+ // Client hydrates from window
1666
+ if (typeof document !== 'undefined') {
1667
+ _ctx = window.__TSR_DEHYDRATED__
1668
+ }
1669
+
1670
+ invariant(
1671
+ _ctx,
1672
+ 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',
1673
+ )
1674
+
1675
+ const ctx = _ctx
1676
+ this.dehydratedData = ctx.payload as any
1677
+ this.options.hydrate?.(ctx.payload as any)
1678
+ const dehydratedState = ctx.router.state
1679
+
1680
+ let matches = this.matchRoutes(
1681
+ this.state.location.pathname,
1682
+ this.state.location.search,
1683
+ ).map((match) => {
1684
+ const dehydratedMatch = dehydratedState.dehydratedMatches.find(
1685
+ (d) => d.id === match.id,
1686
+ )
1687
+
1688
+ invariant(
1689
+ dehydratedMatch,
1690
+ `Could not find a client-side match for dehydrated match with id: ${match.id}!`,
1691
+ )
1692
+
1693
+ if (dehydratedMatch) {
1694
+ return {
1695
+ ...match,
1696
+ ...dehydratedMatch,
1697
+ }
1698
+ }
1699
+ return match
1700
+ })
1701
+
1702
+ this.__store.setState((s) => {
1703
+ return {
1704
+ ...s,
1705
+ matches: matches as any,
1706
+ }
1707
+ })
1708
+ }
1709
+
1710
+ // resolveMatchPromise = (matchId: string, key: string, value: any) => {
1711
+ // state.matches
1712
+ // .find((d) => d.id === matchId)
1713
+ // ?.__promisesByKey[key]?.resolve(value)
1714
+ // }
1715
+ }
1716
+
1717
+ // A function that takes an import() argument which is a function and returns a new function that will
1718
+ // proxy arguments from the caller to the imported function, retaining all type
1719
+ // information along the way
1720
+ export function lazyFn<
1721
+ T extends Record<string, (...args: any[]) => any>,
1722
+ TKey extends keyof T = 'default',
1723
+ >(fn: () => Promise<T>, key?: TKey) {
1724
+ return async (...args: Parameters<T[TKey]>): Promise<ReturnType<T[TKey]>> => {
1725
+ const imported = await fn()
1726
+ return imported[key || 'default'](...args)
1727
+ }
1728
+ }
1729
+
1730
+ function isCtrlEvent(e: MouseEvent) {
1731
+ return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
1732
+ }
1733
+ export class SearchParamError extends Error {}
1734
+
1735
+ export class PathParamError extends Error {}
1736
+
1737
+ export function getInitialRouterState(
1738
+ location: ParsedLocation,
1739
+ ): RouterState<any> {
1740
+ return {
1741
+ isLoading: false,
1742
+ isTransitioning: false,
1743
+ status: 'idle',
1744
+ resolvedLocation: { ...location },
1745
+ location,
1746
+ matches: [],
1747
+ pendingMatches: [],
1748
+ lastUpdated: Date.now(),
1749
+ }
1750
+ }