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

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