@tanstack/react-router 0.0.1-beta.25 → 0.0.1-beta.250

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 +159 -0
  7. package/build/cjs/RouterProvider.js.map +1 -0
  8. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +2 -22
  9. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +1 -1
  10. package/build/cjs/awaited.js +43 -0
  11. package/build/cjs/awaited.js.map +1 -0
  12. package/build/cjs/defer.js +37 -0
  13. package/build/cjs/defer.js.map +1 -0
  14. package/build/cjs/fileRoute.js +27 -0
  15. package/build/cjs/fileRoute.js.map +1 -0
  16. package/build/cjs/index.js +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 +25 -0
  27. package/build/cjs/redirects.js.map +1 -0
  28. package/build/cjs/route.js +139 -0
  29. package/build/cjs/route.js.map +1 -0
  30. package/build/cjs/router.js +1134 -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 +76 -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 +2202 -2536
  47. package/build/esm/index.js.map +1 -1
  48. package/build/stats-html.html +3498 -2694
  49. package/build/stats-react.json +1216 -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 +10 -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 +2774 -2484
  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 +241 -0
  83. package/src/awaited.tsx +40 -0
  84. package/src/defer.ts +55 -0
  85. package/src/fileRoute.ts +154 -0
  86. package/src/history.ts +8 -0
  87. package/src/index.tsx +28 -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 +31 -0
  95. package/src/route.ts +911 -0
  96. package/src/routeInfo.ts +68 -0
  97. package/src/router.ts +1734 -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 -2528
  108. package/build/cjs/router-core/build/esm/index.js.map +0 -1
package/src/router.ts ADDED
@@ -0,0 +1,1734 @@
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 fromPathname = dest.from ?? from.pathname
714
+
715
+ let pathname = this.resolvePathWithBase(fromPathname, `${dest.to ?? ''}`)
716
+
717
+ const fromMatches = this.matchRoutes(fromPathname, from.search)
718
+ const stayingMatches = matches?.filter(
719
+ (d) => fromMatches?.find((e) => e.routeId === d.routeId),
720
+ )
721
+
722
+ const prevParams = { ...last(fromMatches)?.params }
723
+
724
+ let nextParams =
725
+ (dest.params ?? true) === true
726
+ ? prevParams
727
+ : functionalUpdate(dest.params!, prevParams)
728
+
729
+ if (nextParams) {
730
+ matches
731
+ ?.map((d) => this.looseRoutesById[d.routeId]!.options.stringifyParams)
732
+ .filter(Boolean)
733
+ .forEach((fn) => {
734
+ nextParams = { ...nextParams!, ...fn!(nextParams!) }
735
+ })
736
+ }
737
+
738
+ pathname = interpolatePath(pathname, nextParams ?? {})
739
+
740
+ const preSearchFilters =
741
+ stayingMatches
742
+ ?.map(
743
+ (match) =>
744
+ this.looseRoutesById[match.routeId]!.options.preSearchFilters ??
745
+ [],
746
+ )
747
+ .flat()
748
+ .filter(Boolean) ?? []
749
+
750
+ const postSearchFilters =
751
+ stayingMatches
752
+ ?.map(
753
+ (match) =>
754
+ this.looseRoutesById[match.routeId]!.options.postSearchFilters ??
755
+ [],
756
+ )
757
+ .flat()
758
+ .filter(Boolean) ?? []
759
+
760
+ // Pre filters first
761
+ const preFilteredSearch = preSearchFilters?.length
762
+ ? preSearchFilters?.reduce(
763
+ (prev, next) => next(prev) as any,
764
+ from.search,
765
+ )
766
+ : from.search
767
+
768
+ // Then the link/navigate function
769
+ const destSearch =
770
+ dest.search === true
771
+ ? preFilteredSearch // Preserve resolvedFrom true
772
+ : dest.search
773
+ ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
774
+ : preSearchFilters?.length
775
+ ? preFilteredSearch // Preserve resolvedFrom filters
776
+ : {}
777
+
778
+ // Then post filters
779
+ const postFilteredSearch = postSearchFilters?.length
780
+ ? postSearchFilters.reduce((prev, next) => next(prev), destSearch)
781
+ : destSearch
782
+
783
+ const search = replaceEqualDeep(from.search, postFilteredSearch)
784
+
785
+ const searchStr = this.options.stringifySearch(search)
786
+
787
+ const hash =
788
+ dest.hash === true
789
+ ? from.hash
790
+ : dest.hash
791
+ ? functionalUpdate(dest.hash!, from.hash)
792
+ : from.hash
793
+
794
+ const hashStr = hash ? `#${hash}` : ''
795
+
796
+ let nextState =
797
+ dest.state === true
798
+ ? from.state
799
+ : dest.state
800
+ ? functionalUpdate(dest.state, from.state)
801
+ : from.state
802
+
803
+ nextState = replaceEqualDeep(from.state, nextState)
804
+
805
+ return {
806
+ pathname,
807
+ search,
808
+ searchStr,
809
+ state: nextState as any,
810
+ hash,
811
+ href: this.history.createHref(`${pathname}${searchStr}${hashStr}`),
812
+ unmaskOnReload: dest.unmaskOnReload,
813
+ }
814
+ }
815
+
816
+ const buildWithMatches = (
817
+ dest: BuildNextOptions = {},
818
+ maskedDest?: BuildNextOptions,
819
+ ) => {
820
+ let next = build(dest)
821
+ let maskedNext = maskedDest ? build(maskedDest) : undefined
822
+
823
+ if (!maskedNext) {
824
+ let params = {}
825
+
826
+ let foundMask = this.options.routeMasks?.find((d) => {
827
+ const match = matchPathname(this.basepath, next.pathname, {
828
+ to: d.from,
829
+ caseSensitive: false,
830
+ fuzzy: false,
831
+ })
832
+
833
+ if (match) {
834
+ params = match
835
+ return true
836
+ }
837
+
838
+ return false
839
+ })
840
+
841
+ if (foundMask) {
842
+ foundMask = {
843
+ ...foundMask,
844
+ from: interpolatePath(foundMask.from, params) as any,
845
+ }
846
+ maskedDest = foundMask
847
+ maskedNext = build(maskedDest)
848
+ }
849
+ }
850
+
851
+ const nextMatches = this.matchRoutes(next.pathname, next.search)
852
+ const maskedMatches = maskedNext
853
+ ? this.matchRoutes(maskedNext.pathname, maskedNext.search)
854
+ : undefined
855
+ const maskedFinal = maskedNext
856
+ ? build(maskedDest, maskedMatches)
857
+ : undefined
858
+
859
+ const final = build(dest, nextMatches)
860
+
861
+ if (maskedFinal) {
862
+ final.maskedLocation = maskedFinal
863
+ }
864
+
865
+ return final
866
+ }
867
+
868
+ if (opts.mask) {
869
+ return buildWithMatches(opts, {
870
+ ...pick(opts, ['from']),
871
+ ...opts.mask,
872
+ })
873
+ }
874
+
875
+ return buildWithMatches(opts)
876
+ }
877
+
878
+ commitLocation = async ({
879
+ startTransition,
880
+ ...next
881
+ }: ParsedLocation & CommitLocationOptions) => {
882
+ if (this.navigateTimeout) clearTimeout(this.navigateTimeout)
883
+
884
+ const isSameUrl = this.latestLocation.href === next.href
885
+
886
+ // If the next urls are the same and we're not replacing,
887
+ // do nothing
888
+ if (!isSameUrl || !next.replace) {
889
+ let { maskedLocation, ...nextHistory } = next
890
+
891
+ if (maskedLocation) {
892
+ nextHistory = {
893
+ ...maskedLocation,
894
+ state: {
895
+ ...maskedLocation.state,
896
+ __tempKey: undefined,
897
+ __tempLocation: {
898
+ ...nextHistory,
899
+ search: nextHistory.searchStr,
900
+ state: {
901
+ ...nextHistory.state,
902
+ __tempKey: undefined!,
903
+ __tempLocation: undefined!,
904
+ key: undefined!,
905
+ },
906
+ },
907
+ },
908
+ }
909
+
910
+ if (
911
+ nextHistory.unmaskOnReload ??
912
+ this.options.unmaskOnReload ??
913
+ false
914
+ ) {
915
+ nextHistory.state.__tempKey = this.tempLocationKey
916
+ }
917
+ }
918
+
919
+ const apply = () => {
920
+ this.history[next.replace ? 'replace' : 'push'](
921
+ nextHistory.href,
922
+ nextHistory.state,
923
+ )
924
+ }
925
+
926
+ if (startTransition ?? true) {
927
+ this.startReactTransition(apply)
928
+ } else {
929
+ apply()
930
+ }
931
+ }
932
+
933
+ this.resetNextScroll = next.resetScroll ?? true
934
+
935
+ return this.latestLoadPromise
936
+ }
937
+
938
+ buildAndCommitLocation = ({
939
+ replace,
940
+ resetScroll,
941
+ startTransition,
942
+ ...rest
943
+ }: BuildNextOptions & CommitLocationOptions = {}) => {
944
+ const location = this.buildLocation(rest)
945
+ return this.commitLocation({
946
+ ...location,
947
+ startTransition,
948
+ replace,
949
+ resetScroll,
950
+ })
951
+ }
952
+
953
+ navigate: NavigateFn<TRouteTree> = ({ from, to = '', ...rest }) => {
954
+ // If this link simply reloads the current route,
955
+ // make sure it has a new key so it will trigger a data refresh
956
+
957
+ // If this `to` is a valid external URL, return
958
+ // null for LinkUtils
959
+ const toString = String(to)
960
+ const fromString = typeof from === 'undefined' ? from : String(from)
961
+ let isExternal
962
+
963
+ try {
964
+ new URL(`${toString}`)
965
+ isExternal = true
966
+ } catch (e) {}
967
+
968
+ invariant(
969
+ !isExternal,
970
+ 'Attempting to navigate to external url with this.navigate!',
971
+ )
972
+
973
+ return this.buildAndCommitLocation({
974
+ ...rest,
975
+ from: fromString,
976
+ to: toString,
977
+ })
978
+ }
979
+
980
+ loadMatches = async ({
981
+ checkLatest,
982
+ matches,
983
+ preload,
984
+ invalidate,
985
+ }: {
986
+ checkLatest: () => Promise<void> | undefined
987
+ matches: AnyRouteMatch[]
988
+ preload?: boolean
989
+ invalidate?: boolean
990
+ }): Promise<RouteMatch[]> => {
991
+ let latestPromise
992
+ let firstBadMatchIndex: number | undefined
993
+
994
+ const updatePendingMatch = (match: AnyRouteMatch) => {
995
+ this.__store.setState((s) => ({
996
+ ...s,
997
+ pendingMatches: s.pendingMatches?.map((d) =>
998
+ d.id === match.id ? match : d,
999
+ ),
1000
+ }))
1001
+ }
1002
+
1003
+ // Check each match middleware to see if the route can be accessed
1004
+ try {
1005
+ for (let [index, match] of matches.entries()) {
1006
+ const parentMatch = matches[index - 1]
1007
+ const route = this.looseRoutesById[match.routeId]!
1008
+
1009
+ const handleError = (err: any, code: string) => {
1010
+ err.routerCode = code
1011
+ firstBadMatchIndex = firstBadMatchIndex ?? index
1012
+
1013
+ if (isRedirect(err)) {
1014
+ throw err
1015
+ }
1016
+
1017
+ try {
1018
+ route.options.onError?.(err)
1019
+ } catch (errorHandlerErr) {
1020
+ err = errorHandlerErr
1021
+
1022
+ if (isRedirect(errorHandlerErr)) {
1023
+ throw errorHandlerErr
1024
+ }
1025
+ }
1026
+
1027
+ matches[index] = match = {
1028
+ ...match,
1029
+ error: err,
1030
+ status: 'error',
1031
+ updatedAt: Date.now(),
1032
+ }
1033
+ }
1034
+
1035
+ try {
1036
+ if (match.paramsError) {
1037
+ handleError(match.paramsError, 'PARSE_PARAMS')
1038
+ }
1039
+
1040
+ if (match.searchError) {
1041
+ handleError(match.searchError, 'VALIDATE_SEARCH')
1042
+ }
1043
+
1044
+ const parentContext =
1045
+ parentMatch?.context ?? this.options.context ?? {}
1046
+
1047
+ const beforeLoadContext =
1048
+ (await route.options.beforeLoad?.({
1049
+ search: match.search,
1050
+ abortController: match.abortController,
1051
+ params: match.params,
1052
+ preload: !!preload,
1053
+ context: parentContext,
1054
+ location: this.state.location,
1055
+ // TOOD: just expose state and router, etc
1056
+ navigate: (opts) =>
1057
+ this.navigate({ ...opts, from: match.pathname } as any),
1058
+ buildLocation: this.buildLocation,
1059
+ cause: match.cause,
1060
+ })) ?? ({} as any)
1061
+
1062
+ const context = {
1063
+ ...parentContext,
1064
+ ...beforeLoadContext,
1065
+ }
1066
+
1067
+ matches[index] = match = {
1068
+ ...match,
1069
+ context: replaceEqualDeep(match.context, context),
1070
+ }
1071
+ } catch (err) {
1072
+ handleError(err, 'BEFORE_LOAD')
1073
+ break
1074
+ }
1075
+ }
1076
+ } catch (err) {
1077
+ if (isRedirect(err)) {
1078
+ if (!preload) this.navigate(err as any)
1079
+ return matches
1080
+ }
1081
+
1082
+ throw err
1083
+ }
1084
+
1085
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex)
1086
+ const matchPromises: Promise<any>[] = []
1087
+
1088
+ validResolvedMatches.forEach((match, index) => {
1089
+ matchPromises.push(
1090
+ (async () => {
1091
+ const parentMatchPromise = matchPromises[index - 1]
1092
+ const route = this.looseRoutesById[match.routeId]!
1093
+
1094
+ const handleIfRedirect = (err: any) => {
1095
+ if (isRedirect(err)) {
1096
+ if (!preload) {
1097
+ this.navigate(err as any)
1098
+ }
1099
+ return true
1100
+ }
1101
+ return false
1102
+ }
1103
+
1104
+ let loadPromise: Promise<void> | undefined
1105
+
1106
+ matches[index] = match = {
1107
+ ...match,
1108
+ fetchedAt: Date.now(),
1109
+ invalid: false,
1110
+ showPending: false,
1111
+ }
1112
+
1113
+ const pendingMs =
1114
+ route.options.pendingMs ?? this.options.defaultPendingMs
1115
+
1116
+ let pendingPromise: Promise<void> | undefined
1117
+
1118
+ if (
1119
+ !preload &&
1120
+ pendingMs &&
1121
+ (route.options.pendingComponent ??
1122
+ this.options.defaultPendingComponent)
1123
+ ) {
1124
+ pendingPromise = new Promise((r) => setTimeout(r, pendingMs))
1125
+ }
1126
+
1127
+ if (match.isFetching) {
1128
+ loadPromise = getRouteMatch(this.state, match.id)?.loadPromise
1129
+ } else {
1130
+ const loaderContext: LoaderFnContext = {
1131
+ params: match.params,
1132
+ search: match.search,
1133
+ preload: !!preload,
1134
+ parentMatchPromise,
1135
+ abortController: match.abortController,
1136
+ context: match.context,
1137
+ location: this.state.location,
1138
+ navigate: (opts) =>
1139
+ this.navigate({ ...opts, from: match.pathname } as any),
1140
+ cause: match.cause,
1141
+ }
1142
+
1143
+ // Default to reloading the route all the time
1144
+ let shouldReload = true
1145
+
1146
+ let shouldReloadDeps =
1147
+ typeof route.options.shouldReload === 'function'
1148
+ ? route.options.shouldReload?.(loaderContext)
1149
+ : !!(route.options.shouldReload ?? true)
1150
+
1151
+ if (match.cause === 'enter' || invalidate) {
1152
+ match.shouldReloadDeps = shouldReloadDeps
1153
+ } else if (match.cause === 'stay') {
1154
+ if (typeof shouldReloadDeps === 'object') {
1155
+ // compare the deps to see if they've changed
1156
+ shouldReload = !deepEqual(
1157
+ shouldReloadDeps,
1158
+ match.shouldReloadDeps,
1159
+ )
1160
+
1161
+ match.shouldReloadDeps = shouldReloadDeps
1162
+ } else {
1163
+ shouldReload = !!shouldReloadDeps
1164
+ }
1165
+ }
1166
+
1167
+ // If the user doesn't want the route to reload, just
1168
+ // resolve with the existing loader data
1169
+
1170
+ if (!shouldReload) {
1171
+ loadPromise = Promise.resolve(match.loaderData)
1172
+ } else {
1173
+ // Otherwise, load the route
1174
+ matches[index] = match = {
1175
+ ...match,
1176
+ isFetching: true,
1177
+ }
1178
+
1179
+ const componentsPromise = Promise.all(
1180
+ componentTypes.map(async (type) => {
1181
+ const component = route.options[type]
1182
+
1183
+ if ((component as any)?.preload) {
1184
+ await (component as any).preload()
1185
+ }
1186
+ }),
1187
+ )
1188
+
1189
+ const loaderPromise = route.options.loader?.(loaderContext)
1190
+
1191
+ loadPromise = Promise.all([
1192
+ componentsPromise,
1193
+ loaderPromise,
1194
+ ]).then((d) => d[1])
1195
+ }
1196
+ }
1197
+
1198
+ matches[index] = match = {
1199
+ ...match,
1200
+ loadPromise,
1201
+ }
1202
+
1203
+ if (!preload) {
1204
+ updatePendingMatch(match)
1205
+ }
1206
+
1207
+ let didShowPending = false
1208
+ const pendingMinMs =
1209
+ route.options.pendingMinMs ?? this.options.defaultPendingMinMs
1210
+
1211
+ await new Promise<void>(async (resolve) => {
1212
+ // If the route has a pending component and a pendingMs option,
1213
+ // forcefully show the pending component
1214
+ if (pendingPromise) {
1215
+ pendingPromise.then(() => {
1216
+ if ((latestPromise = checkLatest())) return
1217
+
1218
+ didShowPending = true
1219
+ matches[index] = match = {
1220
+ ...match,
1221
+ showPending: true,
1222
+ }
1223
+
1224
+ updatePendingMatch(match)
1225
+ resolve()
1226
+ })
1227
+ }
1228
+
1229
+ try {
1230
+ const loaderData = await loadPromise
1231
+ if ((latestPromise = checkLatest())) return await latestPromise
1232
+
1233
+ if (didShowPending && pendingMinMs) {
1234
+ await new Promise((r) => setTimeout(r, pendingMinMs))
1235
+ }
1236
+
1237
+ if ((latestPromise = checkLatest())) return await latestPromise
1238
+
1239
+ matches[index] = match = {
1240
+ ...match,
1241
+ error: undefined,
1242
+ status: 'success',
1243
+ isFetching: false,
1244
+ updatedAt: Date.now(),
1245
+ loaderData,
1246
+ loadPromise: undefined,
1247
+ }
1248
+ } catch (error) {
1249
+ if ((latestPromise = checkLatest())) return await latestPromise
1250
+ if (handleIfRedirect(error)) return
1251
+
1252
+ try {
1253
+ route.options.onError?.(error)
1254
+ } catch (onErrorError) {
1255
+ error = onErrorError
1256
+ if (handleIfRedirect(onErrorError)) return
1257
+ }
1258
+
1259
+ matches[index] = match = {
1260
+ ...match,
1261
+ error,
1262
+ status: 'error',
1263
+ isFetching: false,
1264
+ updatedAt: Date.now(),
1265
+ }
1266
+ } finally {
1267
+ // If we showed the pending component, that means
1268
+ // we already moved the pendingMatches to the matches
1269
+ // state, so we need to update that specific match
1270
+ if (didShowPending && pendingMinMs && match.showPending) {
1271
+ this.__store.setState((s) => ({
1272
+ ...s,
1273
+ matches: s.matches?.map((d) =>
1274
+ d.id === match.id ? match : d,
1275
+ ),
1276
+ }))
1277
+ }
1278
+ }
1279
+
1280
+ if (!preload) {
1281
+ updatePendingMatch(match)
1282
+ }
1283
+
1284
+ resolve()
1285
+ })
1286
+ })(),
1287
+ )
1288
+ })
1289
+
1290
+ await Promise.all(matchPromises)
1291
+ return matches
1292
+ }
1293
+
1294
+ invalidate = () =>
1295
+ this.load({
1296
+ invalidate: true,
1297
+ })
1298
+
1299
+ load = async (opts?: { invalidate?: boolean }): Promise<void> => {
1300
+ const promise = new Promise<void>(async (resolve, reject) => {
1301
+ const next = this.latestLocation
1302
+ const prevLocation = this.state.resolvedLocation
1303
+ const pathDidChange = prevLocation!.href !== next.href
1304
+ let latestPromise: Promise<void> | undefined | null
1305
+
1306
+ // Cancel any pending matches
1307
+ this.cancelMatches()
1308
+
1309
+ this.emit({
1310
+ type: 'onBeforeLoad',
1311
+ fromLocation: prevLocation,
1312
+ toLocation: next,
1313
+ pathChanged: pathDidChange,
1314
+ })
1315
+
1316
+ // Match the routes
1317
+ let pendingMatches: RouteMatch<any, any>[] = this.matchRoutes(
1318
+ next.pathname,
1319
+ next.search,
1320
+ {
1321
+ debug: true,
1322
+ },
1323
+ )
1324
+
1325
+ const previousMatches = this.state.matches
1326
+
1327
+ // Ingest the new matches
1328
+ this.__store.setState((s) => ({
1329
+ ...s,
1330
+ isLoading: true,
1331
+ location: next,
1332
+ pendingMatches,
1333
+ }))
1334
+
1335
+ try {
1336
+ try {
1337
+ // Load the matches
1338
+ await this.loadMatches({
1339
+ matches: pendingMatches,
1340
+ checkLatest: () => this.checkLatest(promise),
1341
+ invalidate: opts?.invalidate,
1342
+ })
1343
+ } catch (err) {
1344
+ // swallow this error, since we'll display the
1345
+ // errors on the route components
1346
+ }
1347
+
1348
+ // Only apply the latest transition
1349
+ if ((latestPromise = this.checkLatest(promise))) {
1350
+ return latestPromise
1351
+ }
1352
+
1353
+ const exitingMatchIds = previousMatches.filter(
1354
+ (id) => !this.pendingMatches.includes(id),
1355
+ )
1356
+ const enteringMatchIds = this.pendingMatches.filter(
1357
+ (id) => !previousMatches.includes(id),
1358
+ )
1359
+ const stayingMatchIds = previousMatches.filter((id) =>
1360
+ this.pendingMatches.includes(id),
1361
+ )
1362
+
1363
+ this.__store.setState((s) => ({
1364
+ ...s,
1365
+ isLoading: false,
1366
+ matches: pendingMatches,
1367
+ pendingMatches: undefined,
1368
+ }))
1369
+
1370
+ //
1371
+ ;(
1372
+ [
1373
+ [exitingMatchIds, 'onLeave'],
1374
+ [enteringMatchIds, 'onEnter'],
1375
+ [stayingMatchIds, 'onTransition'],
1376
+ ] as const
1377
+ ).forEach(([matches, hook]) => {
1378
+ matches.forEach((match) => {
1379
+ this.looseRoutesById[match.routeId]!.options[hook]?.(match)
1380
+ })
1381
+ })
1382
+
1383
+ this.emit({
1384
+ type: 'onLoad',
1385
+ fromLocation: prevLocation,
1386
+ toLocation: next,
1387
+ pathChanged: pathDidChange,
1388
+ })
1389
+
1390
+ resolve()
1391
+ } catch (err) {
1392
+ // Only apply the latest transition
1393
+ if ((latestPromise = this.checkLatest(promise))) {
1394
+ return latestPromise
1395
+ }
1396
+
1397
+ reject(err)
1398
+ }
1399
+ })
1400
+
1401
+ this.latestLoadPromise = promise
1402
+
1403
+ return this.latestLoadPromise
1404
+ }
1405
+
1406
+ preloadRoute = async (
1407
+ navigateOpts: BuildNextOptions = this.state.location,
1408
+ ) => {
1409
+ let next = this.buildLocation(navigateOpts)
1410
+
1411
+ let matches = this.matchRoutes(next.pathname, next.search, {
1412
+ throwOnError: true,
1413
+ })
1414
+
1415
+ matches = await this.loadMatches({
1416
+ matches,
1417
+ preload: true,
1418
+ checkLatest: () => undefined,
1419
+ })
1420
+
1421
+ return matches
1422
+ }
1423
+
1424
+ buildLink: BuildLinkFn<TRouteTree> = (dest) => {
1425
+ // If this link simply reloads the current route,
1426
+ // make sure it has a new key so it will trigger a data refresh
1427
+
1428
+ // If this `to` is a valid external URL, return
1429
+ // null for LinkUtils
1430
+
1431
+ const {
1432
+ to,
1433
+ preload: userPreload,
1434
+ preloadDelay: userPreloadDelay,
1435
+ activeOptions,
1436
+ disabled,
1437
+ target,
1438
+ replace,
1439
+ resetScroll,
1440
+ startTransition,
1441
+ } = dest
1442
+
1443
+ try {
1444
+ new URL(`${to}`)
1445
+ return {
1446
+ type: 'external',
1447
+ href: to as any,
1448
+ }
1449
+ } catch (e) {}
1450
+
1451
+ const nextOpts = dest
1452
+ const next = this.buildLocation(nextOpts as any)
1453
+
1454
+ const preload = userPreload ?? this.options.defaultPreload
1455
+ const preloadDelay =
1456
+ userPreloadDelay ?? this.options.defaultPreloadDelay ?? 0
1457
+
1458
+ // Compare path/hash for matches
1459
+ const currentPathSplit = this.latestLocation.pathname.split('/')
1460
+ const nextPathSplit = next.pathname.split('/')
1461
+ const pathIsFuzzyEqual = nextPathSplit.every(
1462
+ (d, i) => d === currentPathSplit[i],
1463
+ )
1464
+ // Combine the matches based on user this.options
1465
+ const pathTest = activeOptions?.exact
1466
+ ? this.latestLocation.pathname === next.pathname
1467
+ : pathIsFuzzyEqual
1468
+ const hashTest = activeOptions?.includeHash
1469
+ ? this.latestLocation.hash === next.hash
1470
+ : true
1471
+ const searchTest =
1472
+ activeOptions?.includeSearch ?? true
1473
+ ? deepEqual(this.latestLocation.search, next.search, true)
1474
+ : true
1475
+
1476
+ // The final "active" test
1477
+ const isActive = pathTest && hashTest && searchTest
1478
+
1479
+ // The click handler
1480
+ const handleClick = (e: MouseEvent) => {
1481
+ if (
1482
+ !disabled &&
1483
+ !isCtrlEvent(e) &&
1484
+ !e.defaultPrevented &&
1485
+ (!target || target === '_self') &&
1486
+ e.button === 0
1487
+ ) {
1488
+ e.preventDefault()
1489
+
1490
+ // All is well? Navigate!
1491
+ this.commitLocation({ ...next, replace, resetScroll, startTransition })
1492
+ }
1493
+ }
1494
+
1495
+ // The click handler
1496
+ const handleFocus = (e: MouseEvent) => {
1497
+ if (preload) {
1498
+ this.preloadRoute(nextOpts as any).catch((err) => {
1499
+ console.warn(err)
1500
+ console.warn(preloadWarning)
1501
+ })
1502
+ }
1503
+ }
1504
+
1505
+ const handleTouchStart = (e: TouchEvent) => {
1506
+ if (preload) {
1507
+ this.preloadRoute(nextOpts as any).catch((err) => {
1508
+ console.warn(err)
1509
+ console.warn(preloadWarning)
1510
+ })
1511
+ }
1512
+ }
1513
+
1514
+ const handleEnter = (e: MouseEvent) => {
1515
+ const target = (e.target || {}) as LinkCurrentTargetElement
1516
+
1517
+ if (preload) {
1518
+ if (target.preloadTimeout) {
1519
+ return
1520
+ }
1521
+
1522
+ target.preloadTimeout = setTimeout(() => {
1523
+ target.preloadTimeout = null
1524
+ this.preloadRoute(nextOpts as any).catch((err) => {
1525
+ console.warn(err)
1526
+ console.warn(preloadWarning)
1527
+ })
1528
+ }, preloadDelay)
1529
+ }
1530
+ }
1531
+
1532
+ const handleLeave = (e: MouseEvent) => {
1533
+ const target = (e.target || {}) as LinkCurrentTargetElement
1534
+
1535
+ if (target.preloadTimeout) {
1536
+ clearTimeout(target.preloadTimeout)
1537
+ target.preloadTimeout = null
1538
+ }
1539
+ }
1540
+
1541
+ return {
1542
+ type: 'internal',
1543
+ next,
1544
+ handleFocus,
1545
+ handleClick,
1546
+ handleEnter,
1547
+ handleLeave,
1548
+ handleTouchStart,
1549
+ isActive,
1550
+ disabled,
1551
+ }
1552
+ }
1553
+
1554
+ matchRoute: MatchRouteFn<TRouteTree> = (location, opts) => {
1555
+ location = {
1556
+ ...location,
1557
+ to: location.to
1558
+ ? this.resolvePathWithBase((location.from || '') as string, location.to)
1559
+ : undefined,
1560
+ } as any
1561
+
1562
+ const next = this.buildLocation(location as any)
1563
+
1564
+ if (opts?.pending && this.state.status !== 'pending') {
1565
+ return false
1566
+ }
1567
+
1568
+ const baseLocation = opts?.pending
1569
+ ? this.latestLocation
1570
+ : this.state.resolvedLocation
1571
+
1572
+ if (!baseLocation) {
1573
+ return false
1574
+ }
1575
+
1576
+ const match = matchPathname(this.basepath, baseLocation.pathname, {
1577
+ ...opts,
1578
+ to: next.pathname,
1579
+ }) as any
1580
+
1581
+ if (!match) {
1582
+ return false
1583
+ }
1584
+
1585
+ if (match && (opts?.includeSearch ?? true)) {
1586
+ return deepEqual(baseLocation.search, next.search, true) ? match : false
1587
+ }
1588
+
1589
+ return match
1590
+ }
1591
+
1592
+ injectHtml = async (html: string | (() => Promise<string> | string)) => {
1593
+ this.injectedHtml.push(html)
1594
+ }
1595
+
1596
+ dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {
1597
+ if (typeof document === 'undefined') {
1598
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key)
1599
+
1600
+ this.injectHtml(async () => {
1601
+ const id = `__TSR_DEHYDRATED__${strKey}`
1602
+ const data =
1603
+ typeof getData === 'function' ? await (getData as any)() : getData
1604
+ return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${escapeJSON(
1605
+ strKey,
1606
+ )}"] = ${JSON.stringify(data)}
1607
+ ;(() => {
1608
+ var el = document.getElementById('${id}')
1609
+ el.parentElement.removeChild(el)
1610
+ })()
1611
+ </script>`
1612
+ })
1613
+
1614
+ return () => this.hydrateData<T>(key)
1615
+ }
1616
+
1617
+ return () => undefined
1618
+ }
1619
+
1620
+ hydrateData = <T extends any = unknown>(key: any) => {
1621
+ if (typeof document !== 'undefined') {
1622
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key)
1623
+
1624
+ return window[`__TSR_DEHYDRATED__${strKey}` as any] as T
1625
+ }
1626
+
1627
+ return undefined
1628
+ }
1629
+
1630
+ dehydrate = (): DehydratedRouter => {
1631
+ return {
1632
+ state: {
1633
+ dehydratedMatches: this.state.matches.map((d) =>
1634
+ pick(d, [
1635
+ 'fetchedAt',
1636
+ 'invalid',
1637
+ 'id',
1638
+ 'status',
1639
+ 'updatedAt',
1640
+ 'loaderData',
1641
+ ]),
1642
+ ),
1643
+ },
1644
+ }
1645
+ }
1646
+
1647
+ hydrate = async (__do_not_use_server_ctx?: HydrationCtx) => {
1648
+ let _ctx = __do_not_use_server_ctx
1649
+ // Client hydrates from window
1650
+ if (typeof document !== 'undefined') {
1651
+ _ctx = window.__TSR_DEHYDRATED__
1652
+ }
1653
+
1654
+ invariant(
1655
+ _ctx,
1656
+ 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',
1657
+ )
1658
+
1659
+ const ctx = _ctx
1660
+ this.dehydratedData = ctx.payload as any
1661
+ this.options.hydrate?.(ctx.payload as any)
1662
+ const dehydratedState = ctx.router.state
1663
+
1664
+ let matches = this.matchRoutes(
1665
+ this.state.location.pathname,
1666
+ this.state.location.search,
1667
+ ).map((match) => {
1668
+ const dehydratedMatch = dehydratedState.dehydratedMatches.find(
1669
+ (d) => d.id === match.id,
1670
+ )
1671
+
1672
+ invariant(
1673
+ dehydratedMatch,
1674
+ `Could not find a client-side match for dehydrated match with id: ${match.id}!`,
1675
+ )
1676
+
1677
+ if (dehydratedMatch) {
1678
+ return {
1679
+ ...match,
1680
+ ...dehydratedMatch,
1681
+ }
1682
+ }
1683
+ return match
1684
+ })
1685
+
1686
+ this.__store.setState((s) => {
1687
+ return {
1688
+ ...s,
1689
+ matches: matches as any,
1690
+ }
1691
+ })
1692
+ }
1693
+
1694
+ // resolveMatchPromise = (matchId: string, key: string, value: any) => {
1695
+ // state.matches
1696
+ // .find((d) => d.id === matchId)
1697
+ // ?.__promisesByKey[key]?.resolve(value)
1698
+ // }
1699
+ }
1700
+
1701
+ // A function that takes an import() argument which is a function and returns a new function that will
1702
+ // proxy arguments from the caller to the imported function, retaining all type
1703
+ // information along the way
1704
+ export function lazyFn<
1705
+ T extends Record<string, (...args: any[]) => any>,
1706
+ TKey extends keyof T = 'default',
1707
+ >(fn: () => Promise<T>, key?: TKey) {
1708
+ return async (...args: Parameters<T[TKey]>): Promise<ReturnType<T[TKey]>> => {
1709
+ const imported = await fn()
1710
+ return imported[key || 'default'](...args)
1711
+ }
1712
+ }
1713
+
1714
+ function isCtrlEvent(e: MouseEvent) {
1715
+ return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
1716
+ }
1717
+ export class SearchParamError extends Error {}
1718
+
1719
+ export class PathParamError extends Error {}
1720
+
1721
+ export function getInitialRouterState(
1722
+ location: ParsedLocation,
1723
+ ): RouterState<any> {
1724
+ return {
1725
+ isLoading: false,
1726
+ isTransitioning: false,
1727
+ status: 'idle',
1728
+ resolvedLocation: { ...location },
1729
+ location,
1730
+ matches: [],
1731
+ pendingMatches: [],
1732
+ lastUpdated: Date.now(),
1733
+ }
1734
+ }