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

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 +1143 -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 +2213 -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 +2793 -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 +1748 -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,1748 @@
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
+ const abortController = new AbortController()
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
+
1014
+ const handleErrorAndRedirect = (err: any, code: string) => {
1015
+ err.routerCode = code
1016
+ firstBadMatchIndex = firstBadMatchIndex ?? index
1017
+
1018
+ if (isRedirect(err)) {
1019
+ throw err
1020
+ }
1021
+
1022
+ try {
1023
+ route.options.onError?.(err)
1024
+ } catch (errorHandlerErr) {
1025
+ err = errorHandlerErr
1026
+
1027
+ if (isRedirect(errorHandlerErr)) {
1028
+ throw errorHandlerErr
1029
+ }
1030
+ }
1031
+
1032
+ matches[index] = match = {
1033
+ ...match,
1034
+ error: err,
1035
+ status: 'error',
1036
+ updatedAt: Date.now(),
1037
+ abortController,
1038
+ }
1039
+ }
1040
+
1041
+ try {
1042
+ if (match.paramsError) {
1043
+ handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS')
1044
+ }
1045
+
1046
+ if (match.searchError) {
1047
+ handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH')
1048
+ }
1049
+
1050
+ const parentContext =
1051
+ parentMatch?.context ?? this.options.context ?? {}
1052
+
1053
+ const beforeLoadContext =
1054
+ (await route.options.beforeLoad?.({
1055
+ search: match.search,
1056
+ abortController: match.abortController,
1057
+ params: match.params,
1058
+ preload: !!preload,
1059
+ context: parentContext,
1060
+ location: this.state.location,
1061
+ // TOOD: just expose state and router, etc
1062
+ navigate: (opts) =>
1063
+ this.navigate({ ...opts, from: match.pathname } as any),
1064
+ buildLocation: this.buildLocation,
1065
+ cause: match.cause,
1066
+ })) ?? ({} as any)
1067
+
1068
+ if (isRedirect(beforeLoadContext)) {
1069
+ throw beforeLoadContext
1070
+ }
1071
+
1072
+ const context = {
1073
+ ...parentContext,
1074
+ ...beforeLoadContext,
1075
+ }
1076
+
1077
+ matches[index] = match = {
1078
+ ...match,
1079
+ context: replaceEqualDeep(match.context, context),
1080
+ }
1081
+ } catch (err) {
1082
+ handleErrorAndRedirect(err, 'BEFORE_LOAD')
1083
+ break
1084
+ }
1085
+ }
1086
+ } catch (err) {
1087
+ if (isRedirect(err)) {
1088
+ if (!preload) this.navigate(err as any)
1089
+ return matches
1090
+ }
1091
+
1092
+ throw err
1093
+ }
1094
+
1095
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex)
1096
+ const matchPromises: Promise<any>[] = []
1097
+
1098
+ validResolvedMatches.forEach((match, index) => {
1099
+ matchPromises.push(
1100
+ (async () => {
1101
+ const parentMatchPromise = matchPromises[index - 1]
1102
+ const route = this.looseRoutesById[match.routeId]!
1103
+
1104
+ const handleErrorAndRedirect = (err: any) => {
1105
+ if (isRedirect(err)) {
1106
+ if (!preload) {
1107
+ this.navigate(err as any)
1108
+ }
1109
+ return true
1110
+ }
1111
+ return false
1112
+ }
1113
+
1114
+ let loadPromise: Promise<void> | undefined
1115
+
1116
+ matches[index] = match = {
1117
+ ...match,
1118
+ fetchedAt: Date.now(),
1119
+ invalid: false,
1120
+ showPending: false,
1121
+ }
1122
+
1123
+ const pendingMs =
1124
+ route.options.pendingMs ?? this.options.defaultPendingMs
1125
+
1126
+ let pendingPromise: Promise<void> | undefined
1127
+
1128
+ if (
1129
+ !preload &&
1130
+ pendingMs &&
1131
+ (route.options.pendingComponent ??
1132
+ this.options.defaultPendingComponent)
1133
+ ) {
1134
+ pendingPromise = new Promise((r) => setTimeout(r, pendingMs))
1135
+ }
1136
+
1137
+ if (match.isFetching) {
1138
+ loadPromise = getRouteMatch(this.state, match.id)?.loadPromise
1139
+ } else {
1140
+ const loaderContext: LoaderFnContext = {
1141
+ params: match.params,
1142
+ search: match.search,
1143
+ preload: !!preload,
1144
+ parentMatchPromise,
1145
+ abortController: match.abortController,
1146
+ context: match.context,
1147
+ location: this.state.location,
1148
+ navigate: (opts) =>
1149
+ this.navigate({ ...opts, from: match.pathname } as any),
1150
+ cause: match.cause,
1151
+ }
1152
+
1153
+ // Default to reloading the route all the time
1154
+ let shouldReload = true
1155
+
1156
+ let shouldReloadDeps =
1157
+ typeof route.options.shouldReload === 'function'
1158
+ ? route.options.shouldReload?.(loaderContext)
1159
+ : !!(route.options.shouldReload ?? true)
1160
+
1161
+ if (match.cause === 'enter' || invalidate) {
1162
+ match.shouldReloadDeps = shouldReloadDeps
1163
+ } else if (match.cause === 'stay') {
1164
+ if (typeof shouldReloadDeps === 'object') {
1165
+ // compare the deps to see if they've changed
1166
+ shouldReload = !deepEqual(
1167
+ shouldReloadDeps,
1168
+ match.shouldReloadDeps,
1169
+ )
1170
+
1171
+ match.shouldReloadDeps = shouldReloadDeps
1172
+ } else {
1173
+ shouldReload = !!shouldReloadDeps
1174
+ }
1175
+ }
1176
+
1177
+ // If the user doesn't want the route to reload, just
1178
+ // resolve with the existing loader data
1179
+
1180
+ if (!shouldReload) {
1181
+ loadPromise = Promise.resolve(match.loaderData)
1182
+ } else {
1183
+ // Otherwise, load the route
1184
+ matches[index] = match = {
1185
+ ...match,
1186
+ isFetching: true,
1187
+ }
1188
+
1189
+ const componentsPromise = Promise.all(
1190
+ componentTypes.map(async (type) => {
1191
+ const component = route.options[type]
1192
+
1193
+ if ((component as any)?.preload) {
1194
+ await (component as any).preload()
1195
+ }
1196
+ }),
1197
+ )
1198
+
1199
+ const loaderPromise = route.options.loader?.(loaderContext)
1200
+
1201
+ loadPromise = Promise.all([
1202
+ componentsPromise,
1203
+ loaderPromise,
1204
+ ]).then((d) => d[1])
1205
+ }
1206
+ }
1207
+
1208
+ matches[index] = match = {
1209
+ ...match,
1210
+ loadPromise,
1211
+ }
1212
+
1213
+ if (!preload) {
1214
+ updatePendingMatch(match)
1215
+ }
1216
+
1217
+ let didShowPending = false
1218
+ const pendingMinMs =
1219
+ route.options.pendingMinMs ?? this.options.defaultPendingMinMs
1220
+
1221
+ await new Promise<void>(async (resolve) => {
1222
+ // If the route has a pending component and a pendingMs option,
1223
+ // forcefully show the pending component
1224
+ if (pendingPromise) {
1225
+ pendingPromise.then(() => {
1226
+ if ((latestPromise = checkLatest())) return
1227
+
1228
+ didShowPending = true
1229
+ matches[index] = match = {
1230
+ ...match,
1231
+ showPending: true,
1232
+ }
1233
+
1234
+ updatePendingMatch(match)
1235
+ resolve()
1236
+ })
1237
+ }
1238
+
1239
+ try {
1240
+ const loaderData = await loadPromise
1241
+ if ((latestPromise = checkLatest())) return await latestPromise
1242
+
1243
+ if (isRedirect(loaderData)) {
1244
+ if (handleErrorAndRedirect(loaderData)) return
1245
+ }
1246
+
1247
+ if (didShowPending && pendingMinMs) {
1248
+ await new Promise((r) => setTimeout(r, pendingMinMs))
1249
+ }
1250
+
1251
+ if ((latestPromise = checkLatest())) return await latestPromise
1252
+
1253
+ matches[index] = match = {
1254
+ ...match,
1255
+ error: undefined,
1256
+ status: 'success',
1257
+ isFetching: false,
1258
+ updatedAt: Date.now(),
1259
+ loaderData,
1260
+ loadPromise: undefined,
1261
+ }
1262
+ } catch (error) {
1263
+ if ((latestPromise = checkLatest())) return await latestPromise
1264
+ if (handleErrorAndRedirect(error)) return
1265
+
1266
+ try {
1267
+ route.options.onError?.(error)
1268
+ } catch (onErrorError) {
1269
+ error = onErrorError
1270
+ if (handleErrorAndRedirect(onErrorError)) return
1271
+ }
1272
+
1273
+ matches[index] = match = {
1274
+ ...match,
1275
+ error,
1276
+ status: 'error',
1277
+ isFetching: false,
1278
+ updatedAt: Date.now(),
1279
+ }
1280
+ } finally {
1281
+ // If we showed the pending component, that means
1282
+ // we already moved the pendingMatches to the matches
1283
+ // state, so we need to update that specific match
1284
+ if (didShowPending && pendingMinMs && match.showPending) {
1285
+ this.__store.setState((s) => ({
1286
+ ...s,
1287
+ matches: s.matches?.map((d) =>
1288
+ d.id === match.id ? match : d,
1289
+ ),
1290
+ }))
1291
+ }
1292
+ }
1293
+
1294
+ if (!preload) {
1295
+ updatePendingMatch(match)
1296
+ }
1297
+
1298
+ resolve()
1299
+ })
1300
+ })(),
1301
+ )
1302
+ })
1303
+
1304
+ await Promise.all(matchPromises)
1305
+ return matches
1306
+ }
1307
+
1308
+ invalidate = () =>
1309
+ this.load({
1310
+ invalidate: true,
1311
+ })
1312
+
1313
+ load = async (opts?: { invalidate?: boolean }): Promise<void> => {
1314
+ const promise = new Promise<void>(async (resolve, reject) => {
1315
+ const next = this.latestLocation
1316
+ const prevLocation = this.state.resolvedLocation
1317
+ const pathDidChange = prevLocation!.href !== next.href
1318
+ let latestPromise: Promise<void> | undefined | null
1319
+
1320
+ // Cancel any pending matches
1321
+ this.cancelMatches()
1322
+
1323
+ this.emit({
1324
+ type: 'onBeforeLoad',
1325
+ fromLocation: prevLocation,
1326
+ toLocation: next,
1327
+ pathChanged: pathDidChange,
1328
+ })
1329
+
1330
+ // Match the routes
1331
+ let pendingMatches: RouteMatch<any, any>[] = this.matchRoutes(
1332
+ next.pathname,
1333
+ next.search,
1334
+ {
1335
+ debug: true,
1336
+ },
1337
+ )
1338
+
1339
+ const previousMatches = this.state.matches
1340
+
1341
+ // Ingest the new matches
1342
+ this.__store.setState((s) => ({
1343
+ ...s,
1344
+ isLoading: true,
1345
+ location: next,
1346
+ pendingMatches,
1347
+ }))
1348
+
1349
+ try {
1350
+ try {
1351
+ // Load the matches
1352
+ await this.loadMatches({
1353
+ matches: pendingMatches,
1354
+ checkLatest: () => this.checkLatest(promise),
1355
+ invalidate: opts?.invalidate,
1356
+ })
1357
+ } catch (err) {
1358
+ // swallow this error, since we'll display the
1359
+ // errors on the route components
1360
+ }
1361
+
1362
+ // Only apply the latest transition
1363
+ if ((latestPromise = this.checkLatest(promise))) {
1364
+ return latestPromise
1365
+ }
1366
+
1367
+ const exitingMatchIds = previousMatches.filter(
1368
+ (id) => !this.pendingMatches.includes(id),
1369
+ )
1370
+ const enteringMatchIds = this.pendingMatches.filter(
1371
+ (id) => !previousMatches.includes(id),
1372
+ )
1373
+ const stayingMatchIds = previousMatches.filter((id) =>
1374
+ this.pendingMatches.includes(id),
1375
+ )
1376
+
1377
+ this.__store.setState((s) => ({
1378
+ ...s,
1379
+ isLoading: false,
1380
+ matches: pendingMatches,
1381
+ pendingMatches: undefined,
1382
+ }))
1383
+
1384
+ //
1385
+ ;(
1386
+ [
1387
+ [exitingMatchIds, 'onLeave'],
1388
+ [enteringMatchIds, 'onEnter'],
1389
+ [stayingMatchIds, 'onTransition'],
1390
+ ] as const
1391
+ ).forEach(([matches, hook]) => {
1392
+ matches.forEach((match) => {
1393
+ this.looseRoutesById[match.routeId]!.options[hook]?.(match)
1394
+ })
1395
+ })
1396
+
1397
+ this.emit({
1398
+ type: 'onLoad',
1399
+ fromLocation: prevLocation,
1400
+ toLocation: next,
1401
+ pathChanged: pathDidChange,
1402
+ })
1403
+
1404
+ resolve()
1405
+ } catch (err) {
1406
+ // Only apply the latest transition
1407
+ if ((latestPromise = this.checkLatest(promise))) {
1408
+ return latestPromise
1409
+ }
1410
+
1411
+ reject(err)
1412
+ }
1413
+ })
1414
+
1415
+ this.latestLoadPromise = promise
1416
+
1417
+ return this.latestLoadPromise
1418
+ }
1419
+
1420
+ preloadRoute = async (
1421
+ navigateOpts: BuildNextOptions = this.state.location,
1422
+ ) => {
1423
+ let next = this.buildLocation(navigateOpts)
1424
+
1425
+ let matches = this.matchRoutes(next.pathname, next.search, {
1426
+ throwOnError: true,
1427
+ })
1428
+
1429
+ matches = await this.loadMatches({
1430
+ matches,
1431
+ preload: true,
1432
+ checkLatest: () => undefined,
1433
+ })
1434
+
1435
+ return matches
1436
+ }
1437
+
1438
+ buildLink: BuildLinkFn<TRouteTree> = (dest) => {
1439
+ // If this link simply reloads the current route,
1440
+ // make sure it has a new key so it will trigger a data refresh
1441
+
1442
+ // If this `to` is a valid external URL, return
1443
+ // null for LinkUtils
1444
+
1445
+ const {
1446
+ to,
1447
+ preload: userPreload,
1448
+ preloadDelay: userPreloadDelay,
1449
+ activeOptions,
1450
+ disabled,
1451
+ target,
1452
+ replace,
1453
+ resetScroll,
1454
+ startTransition,
1455
+ } = dest
1456
+
1457
+ try {
1458
+ new URL(`${to}`)
1459
+ return {
1460
+ type: 'external',
1461
+ href: to as any,
1462
+ }
1463
+ } catch (e) {}
1464
+
1465
+ const nextOpts = dest
1466
+ const next = this.buildLocation(nextOpts as any)
1467
+
1468
+ const preload = userPreload ?? this.options.defaultPreload
1469
+ const preloadDelay =
1470
+ userPreloadDelay ?? this.options.defaultPreloadDelay ?? 0
1471
+
1472
+ // Compare path/hash for matches
1473
+ const currentPathSplit = this.latestLocation.pathname.split('/')
1474
+ const nextPathSplit = next.pathname.split('/')
1475
+ const pathIsFuzzyEqual = nextPathSplit.every(
1476
+ (d, i) => d === currentPathSplit[i],
1477
+ )
1478
+ // Combine the matches based on user this.options
1479
+ const pathTest = activeOptions?.exact
1480
+ ? this.latestLocation.pathname === next.pathname
1481
+ : pathIsFuzzyEqual
1482
+ const hashTest = activeOptions?.includeHash
1483
+ ? this.latestLocation.hash === next.hash
1484
+ : true
1485
+ const searchTest =
1486
+ activeOptions?.includeSearch ?? true
1487
+ ? deepEqual(this.latestLocation.search, next.search, true)
1488
+ : true
1489
+
1490
+ // The final "active" test
1491
+ const isActive = pathTest && hashTest && searchTest
1492
+
1493
+ // The click handler
1494
+ const handleClick = (e: MouseEvent) => {
1495
+ if (
1496
+ !disabled &&
1497
+ !isCtrlEvent(e) &&
1498
+ !e.defaultPrevented &&
1499
+ (!target || target === '_self') &&
1500
+ e.button === 0
1501
+ ) {
1502
+ e.preventDefault()
1503
+
1504
+ // All is well? Navigate!
1505
+ this.commitLocation({ ...next, replace, resetScroll, startTransition })
1506
+ }
1507
+ }
1508
+
1509
+ // The click handler
1510
+ const handleFocus = (e: MouseEvent) => {
1511
+ if (preload) {
1512
+ this.preloadRoute(nextOpts as any).catch((err) => {
1513
+ console.warn(err)
1514
+ console.warn(preloadWarning)
1515
+ })
1516
+ }
1517
+ }
1518
+
1519
+ const handleTouchStart = (e: TouchEvent) => {
1520
+ if (preload) {
1521
+ this.preloadRoute(nextOpts as any).catch((err) => {
1522
+ console.warn(err)
1523
+ console.warn(preloadWarning)
1524
+ })
1525
+ }
1526
+ }
1527
+
1528
+ const handleEnter = (e: MouseEvent) => {
1529
+ const target = (e.target || {}) as LinkCurrentTargetElement
1530
+
1531
+ if (preload) {
1532
+ if (target.preloadTimeout) {
1533
+ return
1534
+ }
1535
+
1536
+ target.preloadTimeout = setTimeout(() => {
1537
+ target.preloadTimeout = null
1538
+ this.preloadRoute(nextOpts as any).catch((err) => {
1539
+ console.warn(err)
1540
+ console.warn(preloadWarning)
1541
+ })
1542
+ }, preloadDelay)
1543
+ }
1544
+ }
1545
+
1546
+ const handleLeave = (e: MouseEvent) => {
1547
+ const target = (e.target || {}) as LinkCurrentTargetElement
1548
+
1549
+ if (target.preloadTimeout) {
1550
+ clearTimeout(target.preloadTimeout)
1551
+ target.preloadTimeout = null
1552
+ }
1553
+ }
1554
+
1555
+ return {
1556
+ type: 'internal',
1557
+ next,
1558
+ handleFocus,
1559
+ handleClick,
1560
+ handleEnter,
1561
+ handleLeave,
1562
+ handleTouchStart,
1563
+ isActive,
1564
+ disabled,
1565
+ }
1566
+ }
1567
+
1568
+ matchRoute: MatchRouteFn<TRouteTree> = (location, opts) => {
1569
+ location = {
1570
+ ...location,
1571
+ to: location.to
1572
+ ? this.resolvePathWithBase((location.from || '') as string, location.to)
1573
+ : undefined,
1574
+ } as any
1575
+
1576
+ const next = this.buildLocation(location as any)
1577
+
1578
+ if (opts?.pending && this.state.status !== 'pending') {
1579
+ return false
1580
+ }
1581
+
1582
+ const baseLocation = opts?.pending
1583
+ ? this.latestLocation
1584
+ : this.state.resolvedLocation
1585
+
1586
+ if (!baseLocation) {
1587
+ return false
1588
+ }
1589
+
1590
+ const match = matchPathname(this.basepath, baseLocation.pathname, {
1591
+ ...opts,
1592
+ to: next.pathname,
1593
+ }) as any
1594
+
1595
+ if (!match) {
1596
+ return false
1597
+ }
1598
+
1599
+ if (match && (opts?.includeSearch ?? true)) {
1600
+ return deepEqual(baseLocation.search, next.search, true) ? match : false
1601
+ }
1602
+
1603
+ return match
1604
+ }
1605
+
1606
+ injectHtml = async (html: string | (() => Promise<string> | string)) => {
1607
+ this.injectedHtml.push(html)
1608
+ }
1609
+
1610
+ dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {
1611
+ if (typeof document === 'undefined') {
1612
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key)
1613
+
1614
+ this.injectHtml(async () => {
1615
+ const id = `__TSR_DEHYDRATED__${strKey}`
1616
+ const data =
1617
+ typeof getData === 'function' ? await (getData as any)() : getData
1618
+ return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${escapeJSON(
1619
+ strKey,
1620
+ )}"] = ${JSON.stringify(data)}
1621
+ ;(() => {
1622
+ var el = document.getElementById('${id}')
1623
+ el.parentElement.removeChild(el)
1624
+ })()
1625
+ </script>`
1626
+ })
1627
+
1628
+ return () => this.hydrateData<T>(key)
1629
+ }
1630
+
1631
+ return () => undefined
1632
+ }
1633
+
1634
+ hydrateData = <T extends any = unknown>(key: any) => {
1635
+ if (typeof document !== 'undefined') {
1636
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key)
1637
+
1638
+ return window[`__TSR_DEHYDRATED__${strKey}` as any] as T
1639
+ }
1640
+
1641
+ return undefined
1642
+ }
1643
+
1644
+ dehydrate = (): DehydratedRouter => {
1645
+ return {
1646
+ state: {
1647
+ dehydratedMatches: this.state.matches.map((d) =>
1648
+ pick(d, [
1649
+ 'fetchedAt',
1650
+ 'invalid',
1651
+ 'id',
1652
+ 'status',
1653
+ 'updatedAt',
1654
+ 'loaderData',
1655
+ ]),
1656
+ ),
1657
+ },
1658
+ }
1659
+ }
1660
+
1661
+ hydrate = async (__do_not_use_server_ctx?: HydrationCtx) => {
1662
+ let _ctx = __do_not_use_server_ctx
1663
+ // Client hydrates from window
1664
+ if (typeof document !== 'undefined') {
1665
+ _ctx = window.__TSR_DEHYDRATED__
1666
+ }
1667
+
1668
+ invariant(
1669
+ _ctx,
1670
+ 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',
1671
+ )
1672
+
1673
+ const ctx = _ctx
1674
+ this.dehydratedData = ctx.payload as any
1675
+ this.options.hydrate?.(ctx.payload as any)
1676
+ const dehydratedState = ctx.router.state
1677
+
1678
+ let matches = this.matchRoutes(
1679
+ this.state.location.pathname,
1680
+ this.state.location.search,
1681
+ ).map((match) => {
1682
+ const dehydratedMatch = dehydratedState.dehydratedMatches.find(
1683
+ (d) => d.id === match.id,
1684
+ )
1685
+
1686
+ invariant(
1687
+ dehydratedMatch,
1688
+ `Could not find a client-side match for dehydrated match with id: ${match.id}!`,
1689
+ )
1690
+
1691
+ if (dehydratedMatch) {
1692
+ return {
1693
+ ...match,
1694
+ ...dehydratedMatch,
1695
+ }
1696
+ }
1697
+ return match
1698
+ })
1699
+
1700
+ this.__store.setState((s) => {
1701
+ return {
1702
+ ...s,
1703
+ matches: matches as any,
1704
+ }
1705
+ })
1706
+ }
1707
+
1708
+ // resolveMatchPromise = (matchId: string, key: string, value: any) => {
1709
+ // state.matches
1710
+ // .find((d) => d.id === matchId)
1711
+ // ?.__promisesByKey[key]?.resolve(value)
1712
+ // }
1713
+ }
1714
+
1715
+ // A function that takes an import() argument which is a function and returns a new function that will
1716
+ // proxy arguments from the caller to the imported function, retaining all type
1717
+ // information along the way
1718
+ export function lazyFn<
1719
+ T extends Record<string, (...args: any[]) => any>,
1720
+ TKey extends keyof T = 'default',
1721
+ >(fn: () => Promise<T>, key?: TKey) {
1722
+ return async (...args: Parameters<T[TKey]>): Promise<ReturnType<T[TKey]>> => {
1723
+ const imported = await fn()
1724
+ return imported[key || 'default'](...args)
1725
+ }
1726
+ }
1727
+
1728
+ function isCtrlEvent(e: MouseEvent) {
1729
+ return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
1730
+ }
1731
+ export class SearchParamError extends Error {}
1732
+
1733
+ export class PathParamError extends Error {}
1734
+
1735
+ export function getInitialRouterState(
1736
+ location: ParsedLocation,
1737
+ ): RouterState<any> {
1738
+ return {
1739
+ isLoading: false,
1740
+ isTransitioning: false,
1741
+ status: 'idle',
1742
+ resolvedLocation: { ...location },
1743
+ location,
1744
+ matches: [],
1745
+ pendingMatches: [],
1746
+ lastUpdated: Date.now(),
1747
+ }
1748
+ }