-
-
Notifications
You must be signed in to change notification settings - Fork 696
/
router.ts
3039 lines (2673 loc) · 94 KB
/
router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
createBrowserHistory,
createMemoryHistory,
parseHref,
} from '@tanstack/history'
import { Store } from '@tanstack/react-store'
import invariant from 'tiny-invariant'
import warning from 'tiny-warning'
import { rootRouteId } from './root'
import { defaultParseSearch, defaultStringifySearch } from './searchParams'
import {
createControlledPromise,
deepEqual,
functionalUpdate,
last,
pick,
replaceEqualDeep,
} from './utils'
import {
cleanPath,
interpolatePath,
joinPaths,
matchPathname,
parsePathname,
resolvePath,
trimPath,
trimPathLeft,
trimPathRight,
} from './path'
import { isRedirect, isResolvedRedirect } from './redirects'
import { isNotFound } from './not-found'
import { defaultTransformer } from './transformer'
import type * as React from 'react'
import type {
HistoryLocation,
HistoryState,
RouterHistory,
} from '@tanstack/history'
import type { NoInfer } from '@tanstack/react-store'
import type { Manifest } from './manifest'
import type {
AnyContext,
AnyRoute,
AnyRouteWithContext,
AnySearchSchema,
AnySearchValidator,
BeforeLoadContextOptions,
ErrorRouteComponent,
LoaderFnContext,
NotFoundRouteComponent,
RootRoute,
RouteComponent,
RouteContextOptions,
RouteMask,
SearchMiddleware,
} from './route'
import type {
FullSearchSchema,
RouteById,
RoutePaths,
RoutesById,
RoutesByPath,
} from './routeInfo'
import type {
ControlledPromise,
NonNullableUpdater,
PickAsRequired,
Updater,
} from './utils'
import type {
AnyRouteMatch,
MakeRouteMatch,
MakeRouteMatchUnion,
MatchRouteOptions,
} from './Matches'
import type { ParsedLocation } from './location'
import type { SearchParser, SearchSerializer } from './searchParams'
import type {
BuildLocationFn,
CommitLocationOptions,
NavigateFn,
} from './RouterProvider'
import type { AnyRedirect, ResolvedRedirect } from './redirects'
import type { NotFoundError } from './not-found'
import type { NavigateOptions, ResolveRelativePath, ToOptions } from './link'
import type { RouterTransformer } from './transformer'
declare global {
interface Window {
__TSR__?: {
matches: Array<{
__beforeLoadContext?: string
loaderData?: string
extracted?: Array<ExtractedEntry>
}>
streamedValues: Record<
string,
{
value: any
parsed: any
}
>
cleanScripts: () => void
dehydrated?: any
}
__TSR_ROUTER_CONTEXT__?: React.Context<Router<any, any>>
}
}
export interface Register {
// router: Router
}
export type AnyRouter = Router<any, any, any, any>
export type AnyRouterWithContext<TContext> = Router<
AnyRouteWithContext<TContext>,
any,
any,
any
>
export type RegisteredRouter = Register extends {
router: infer TRouter extends AnyRouter
}
? TRouter
: AnyRouter
export type HydrationCtx = {
router: DehydratedRouter
payload: Record<string, any>
}
export type InferRouterContext<TRouteTree extends AnyRoute> =
TRouteTree extends RootRoute<
any,
infer TRouterContext extends AnyContext,
any,
any,
any,
any,
any,
any
>
? TRouterContext
: AnyContext
export type ExtractedEntry = {
dataType: '__beforeLoadContext' | 'loaderData'
type: 'promise' | 'stream'
path: Array<string>
value: any
id: number
streamState?: StreamState
matchIndex: number
}
export type StreamState = {
promises: Array<ControlledPromise<string | null>>
}
export type RouterContextOptions<TRouteTree extends AnyRoute> =
AnyContext extends InferRouterContext<TRouteTree>
? {
context?: InferRouterContext<TRouteTree>
}
: {
context: InferRouterContext<TRouteTree>
}
export type TrailingSlashOption = 'always' | 'never' | 'preserve'
export interface RouterOptions<
TRouteTree extends AnyRoute,
TTrailingSlashOption extends TrailingSlashOption,
TDehydrated extends Record<string, any> = Record<string, any>,
TSerializedError extends Record<string, any> = Record<string, any>,
> {
/**
* The history object that will be used to manage the browser history.
*
* If not provided, a new createBrowserHistory instance will be created and used.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#history-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/history-types)
*/
history?: RouterHistory
/**
* A function that will be used to stringify search params when generating links.
*
* @default defaultStringifySearch
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#stringifysearch-method)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization)
*/
stringifySearch?: SearchSerializer
/**
* A function that will be used to parse search params when parsing the current location.
*
* @default defaultParseSearch
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#parsesearch-method)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization)
*/
parseSearch?: SearchParser
/**
* If `false`, routes will not be preloaded by default in any way.
*
* If `'intent'`, routes will be preloaded by default when the user hovers over a link or a `touchstart` event is detected on a `<Link>`.
*
* If `'viewport'`, routes will be preloaded by default when they are within the viewport.
*
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreload-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading)
*/
defaultPreload?: false | 'intent' | 'viewport' | 'render'
/**
* The delay in milliseconds that a route must be hovered over or touched before it is preloaded.
*
* @default 50
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloaddelay-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading#preload-delay)
*/
defaultPreloadDelay?: number
/**
* The default `component` a route should use if no component is provided.
*
* @default Outlet
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultcomponent-property)
*/
defaultComponent?: RouteComponent
/**
* The default `errorComponent` a route should use if no error component is provided.
*
* @default ErrorComponent
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaulterrorcomponent-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#handling-errors-with-routeoptionserrorcomponent)
*/
defaultErrorComponent?: ErrorRouteComponent
/**
* The default `pendingComponent` a route should use if no pending component is provided.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpendingcomponent-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#showing-a-pending-component)
*/
defaultPendingComponent?: RouteComponent
/**
* The default `pendingMs` a route should use if no pendingMs is provided.
*
* @default 1000
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpendingms-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#avoiding-pending-component-flash)
*/
defaultPendingMs?: number
/**
* The default `pendingMinMs` a route should use if no pendingMinMs is provided.
*
* @default 500
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpendingminms-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#avoiding-pending-component-flash)
*/
defaultPendingMinMs?: number
/**
* The default `staleTime` a route should use if no staleTime is provided. This is the time in milliseconds that a route will be considered fresh.
*
* @default 0
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultstaletime-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#key-options)
*/
defaultStaleTime?: number
/**
* The default `preloadStaleTime` a route should use if no preloadStaleTime is provided.
*
* @default 30_000 `(30 seconds)`
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloadstaletime-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading)
*/
defaultPreloadStaleTime?: number
/**
* The default `defaultPreloadGcTime` a route should use if no preloadGcTime is provided.
*
* @default 1_800_000 `(30 minutes)`
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloadgctime-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading)
*/
defaultPreloadGcTime?: number
/**
* The default `onCatch` handler for errors caught by the Router ErrorBoundary
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultoncatch-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#handling-errors-with-routeoptionsoncatch)
*/
defaultOnCatch?: (error: Error, errorInfo: React.ErrorInfo) => void
/**
* If `true`, route navigations will called using `document.startViewTransition()`.
*
* If the browser does not support this api, this option will be ignored.
*
* See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for more information on how this function works.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultviewtransition-property)
*/
defaultViewTransition?: boolean
/**
* @default 'fuzzy'
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#notfoundmode-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/not-found-errors#the-notfoundmode-option)
*/
notFoundMode?: 'root' | 'fuzzy'
/**
* The default `gcTime` a route should use if no gcTime is provided.
*
* @default 1_800_000 `(30 minutes)`
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultgctime-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#key-options)
*/
defaultGcTime?: number
/**
* If `true`, all routes will be matched as case-sensitive.
*
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#casesensitive-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/route-trees#case-sensitivity)
*/
caseSensitive?: boolean
/**
*
* The route tree that will be used to configure the router instance.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#routetree-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/route-trees)
*/
routeTree?: TRouteTree
/**
* The basepath for then entire router. This is useful for mounting a router instance at a subpath.
*
* @default '/'
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#basepath-property)
*/
basepath?: string
/**
* The root context that will be provided to all routes in the route tree.
*
* This can be used to provide a context to all routes in the tree without having to provide it to each route individually.
*
* Optional or required if the root route was created with [`createRootRouteWithContext()`](https://tanstack.com/router/latest/docs/framework/react/api/router/createRootRouteWithContextFunction).
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#context-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/router-context)
*/
context?: InferRouterContext<TRouteTree>
/**
* A function that will be called when the router is dehydrated.
*
* The return value of this function will be serialized and stored in the router's dehydrated state.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#dehydrate-method)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/external-data-loading#critical-dehydrationhydration)
*/
dehydrate?: () => TDehydrated
/**
* A function that will be called when the router is hydrated.
*
* The return value of this function will be serialized and stored in the router's dehydrated state.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#hydrate-method)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/external-data-loading#critical-dehydrationhydration)
*/
hydrate?: (dehydrated: TDehydrated) => void
/**
* An array of route masks that will be used to mask routes in the route tree.
*
* Route masking is when you display a route at a different path than the one it is configured to match, like a modal popup that when shared will unmask to the modal's content instead of the modal's context.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#routemasks-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/route-masking)
*/
routeMasks?: Array<RouteMask<TRouteTree>>
/**
* If `true`, route masks will, by default, be removed when the page is reloaded.
*
* This can be overridden on a per-mask basis by setting the `unmaskOnReload` option on the mask, or on a per-navigation basis by setting the `unmaskOnReload` option in the `Navigate` options.
*
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#unmaskonreload-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/route-masking#unmasking-on-page-reload)
*/
unmaskOnReload?: boolean
/**
* A component that will be used to wrap the entire router.
*
* This is useful for providing a context to the entire router.
*
* Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#wrap-property)
*/
Wrap?: (props: { children: any }) => React.JSX.Element
/**
* A component that will be used to wrap the inner contents of the router.
*
* This is useful for providing a context to the inner contents of the router where you also need access to the router context and hooks.
*
* Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#innerwrap-property)
*/
InnerWrap?: (props: { children: any }) => React.JSX.Element
/**
* Use `notFoundComponent` instead.
*
* @deprecated
* See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#notfoundroute-property)
*/
notFoundRoute?: AnyRoute
/**
* The default `notFoundComponent` a route should use if no notFound component is provided.
*
* @default NotFound
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultnotfoundcomponent-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/not-found-errors#default-router-wide-not-found-handling)
*/
defaultNotFoundComponent?: NotFoundRouteComponent
/**
* The transformer that will be used when sending data between the server and the client during SSR.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#transformer-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/ssr#data-transformers)
*/
transformer?: RouterTransformer
/**
* The serializer object that will be used to determine how errors are serialized and deserialized between the server and the client.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#errorserializer-property)
*/
errorSerializer?: RouterErrorSerializer<TSerializedError>
/**
* Configures how trailing slashes are treated.
*
* - `'always'` will add a trailing slash if not present
* - `'never'` will remove the trailing slash if present
* - `'preserve'` will not modify the trailing slash.
*
* @default 'never'
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#trailingslash-property)
*/
trailingSlash?: TTrailingSlashOption
/**
* While usually automatic, sometimes it can be useful to force the router into a server-side state, e.g. when using the router in a non-browser environment that has access to a global.document object.
*
* @default typeof document !== 'undefined'
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#isserver-property)
*/
isServer?: boolean
defaultSsr?: boolean
search?: {
/**
* Configures how unknown search params (= not returned by any `validateSearch`) are treated.
*
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#search.strict-property)
*/
strict?: boolean
}
/**
* Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#pathparamsallowedcharacters-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/path-params#allowed-characters)
*/
pathParamsAllowedCharacters?: Array<
';' | ':' | '@' | '&' | '=' | '+' | '$' | ','
>
}
export interface RouterErrorSerializer<TSerializedError> {
serialize: (err: unknown) => TSerializedError
deserialize: (err: TSerializedError) => unknown
}
export interface RouterState<
TRouteTree extends AnyRoute = AnyRoute,
TRouteMatch = MakeRouteMatch<TRouteTree>,
> {
status: 'pending' | 'idle'
loadedAt: number
isLoading: boolean
isTransitioning: boolean
matches: Array<TRouteMatch>
pendingMatches?: Array<TRouteMatch>
cachedMatches: Array<TRouteMatch>
location: ParsedLocation<FullSearchSchema<TRouteTree>>
resolvedLocation: ParsedLocation<FullSearchSchema<TRouteTree>>
statusCode: number
redirect?: ResolvedRedirect
}
export type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void
export interface BuildNextOptions {
to?: string | number | null
params?: true | Updater<unknown>
search?: true | Updater<unknown>
hash?: true | Updater<string>
state?: true | NonNullableUpdater<HistoryState>
mask?: {
to?: string | number | null
params?: true | Updater<unknown>
search?: true | Updater<unknown>
hash?: true | Updater<string>
state?: true | NonNullableUpdater<HistoryState>
unmaskOnReload?: boolean
}
from?: string
_fromLocation?: ParsedLocation
}
export interface MatchedRoutesResult {
matchedRoutes: Array<AnyRoute>
routeParams: Record<string, string>
}
export interface DehydratedRouterState {
dehydratedMatches: Array<DehydratedRouteMatch>
}
export type DehydratedRouteMatch = Pick<
MakeRouteMatch,
'id' | 'status' | 'updatedAt' | 'loaderData'
>
export interface DehydratedRouter {
state: DehydratedRouterState
manifest?: Manifest
}
export type RouterConstructorOptions<
TRouteTree extends AnyRoute,
TTrailingSlashOption extends TrailingSlashOption,
TDehydrated extends Record<string, any>,
TSerializedError extends Record<string, any>,
> = Omit<
RouterOptions<
TRouteTree,
TTrailingSlashOption,
TDehydrated,
TSerializedError
>,
'context'
> &
RouterContextOptions<TRouteTree>
export const componentTypes = [
'component',
'errorComponent',
'pendingComponent',
'notFoundComponent',
] as const
function routeNeedsPreload(route: AnyRoute) {
for (const componentType of componentTypes) {
if ((route.options[componentType] as any)?.preload) {
return true
}
}
return false
}
function validateSearch(
validateSearch: AnySearchValidator,
input: unknown,
): unknown {
if (validateSearch == null) return {}
if ('~validate' in validateSearch) {
const result = validateSearch['~validate']({ value: input })
if ('value' in result) return result.value
throw new SearchParamError(JSON.stringify(result.issues, undefined, 2))
}
if ('parse' in validateSearch) {
return validateSearch.parse(input)
}
if (typeof validateSearch === 'function') {
return validateSearch(input)
}
return {}
}
export type RouterEvents = {
onBeforeNavigate: {
type: 'onBeforeNavigate'
fromLocation: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
}
onBeforeLoad: {
type: 'onBeforeLoad'
fromLocation: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
}
onLoad: {
type: 'onLoad'
fromLocation: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
}
onResolved: {
type: 'onResolved'
fromLocation: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
}
onBeforeRouteMount: {
type: 'onBeforeRouteMount'
fromLocation: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
}
}
export type RouterEvent = RouterEvents[keyof RouterEvents]
export type RouterListener<TRouterEvent extends RouterEvent> = {
eventType: TRouterEvent['type']
fn: ListenerFn<TRouterEvent>
}
export function createRouter<
TRouteTree extends AnyRoute,
TTrailingSlashOption extends TrailingSlashOption,
TDehydrated extends Record<string, any> = Record<string, any>,
TSerializedError extends Record<string, any> = Record<string, any>,
>(
options: undefined extends number
? 'strictNullChecks must be enabled in tsconfig.json'
: RouterConstructorOptions<
TRouteTree,
TTrailingSlashOption,
TDehydrated,
TSerializedError
>,
) {
return new Router<
TRouteTree,
TTrailingSlashOption,
TDehydrated,
TSerializedError
>(options)
}
type MatchRoutesOpts = {
preload?: boolean
throwOnError?: boolean
_buildLocation?: boolean
dest?: BuildNextOptions
}
export class Router<
in out TRouteTree extends AnyRoute,
in out TTrailingSlashOption extends TrailingSlashOption,
in out TDehydrated extends Record<string, any> = Record<string, any>,
in out TSerializedError extends Record<string, any> = Record<string, any>,
> {
// Option-independent properties
tempLocationKey: string | undefined = `${Math.round(
Math.random() * 10000000,
)}`
resetNextScroll = true
shouldViewTransition?: boolean = undefined
subscribers = new Set<RouterListener<RouterEvent>>()
dehydratedData?: TDehydrated
viewTransitionPromise?: ControlledPromise<true>
manifest?: Manifest
AfterEachMatch?: (props: {
match: Pick<
AnyRouteMatch,
'id' | 'status' | 'error' | 'loadPromise' | 'minPendingPromise'
>
matchIndex: number
}) => any
serializeLoaderData?: (
type: '__beforeLoadContext' | 'loaderData',
loaderData: any,
ctx: {
router: AnyRouter
match: AnyRouteMatch
},
) => any
serializer?: (data: any) => string
// Must build in constructor
__store!: Store<RouterState<TRouteTree>>
options!: PickAsRequired<
Omit<
RouterOptions<
TRouteTree,
TTrailingSlashOption,
TDehydrated,
TSerializedError
>,
'transformer'
> & {
transformer: RouterTransformer
},
'stringifySearch' | 'parseSearch' | 'context'
>
history!: RouterHistory
latestLocation!: ParsedLocation<FullSearchSchema<TRouteTree>>
basepath!: string
routeTree!: TRouteTree
routesById!: RoutesById<TRouteTree>
routesByPath!: RoutesByPath<TRouteTree>
flatRoutes!: Array<AnyRoute>
isServer!: boolean
pathParamsDecodeCharMap?: Map<string, string>
/**
* @deprecated Use the `createRouter` function instead
*/
constructor(
options: RouterConstructorOptions<
TRouteTree,
TTrailingSlashOption,
TDehydrated,
TSerializedError
>,
) {
this.update({
defaultPreloadDelay: 50,
defaultPendingMs: 1000,
defaultPendingMinMs: 500,
context: undefined!,
...options,
caseSensitive: options.caseSensitive ?? false,
notFoundMode: options.notFoundMode ?? 'fuzzy',
stringifySearch: options.stringifySearch ?? defaultStringifySearch,
parseSearch: options.parseSearch ?? defaultParseSearch,
transformer: options.transformer ?? defaultTransformer,
})
if (typeof document !== 'undefined') {
;(window as any).__TSR__ROUTER__ = this
}
}
// These are default implementations that can optionally be overridden
// by the router provider once rendered. We provide these so that the
// router can be used in a non-react environment if necessary
startReactTransition: (fn: () => void) => void = (fn) => fn()
update = (
newOptions: RouterConstructorOptions<
TRouteTree,
TTrailingSlashOption,
TDehydrated,
TSerializedError
>,
) => {
if (newOptions.notFoundRoute) {
console.warn(
'The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.',
)
}
const previousOptions = this.options
this.options = {
...this.options,
...newOptions,
}
this.isServer = this.options.isServer ?? typeof document === 'undefined'
this.pathParamsDecodeCharMap = this.options.pathParamsAllowedCharacters
? new Map(
this.options.pathParamsAllowedCharacters.map((char) => [
encodeURIComponent(char),
char,
]),
)
: undefined
if (
!this.basepath ||
(newOptions.basepath && newOptions.basepath !== previousOptions.basepath)
) {
if (
newOptions.basepath === undefined ||
newOptions.basepath === '' ||
newOptions.basepath === '/'
) {
this.basepath = '/'
} else {
this.basepath = `/${trimPath(newOptions.basepath)}`
}
}
if (
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
!this.history ||
(this.options.history && this.options.history !== this.history)
) {
this.history =
this.options.history ??
(this.isServer
? createMemoryHistory({
initialEntries: [this.basepath || '/'],
})
: createBrowserHistory())
this.latestLocation = this.parseLocation()
}
if (this.options.routeTree !== this.routeTree) {
this.routeTree = this.options.routeTree as TRouteTree
this.buildRouteTree()
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!this.__store) {
this.__store = new Store(getInitialRouterState(this.latestLocation), {
onUpdate: () => {
this.__store.state = {
...this.state,
cachedMatches: this.state.cachedMatches.filter(
(d) => !['redirected'].includes(d.status),
),
}
},
})
}
}
get state() {
return this.__store.state
}
buildRouteTree = () => {
this.routesById = {} as RoutesById<TRouteTree>
this.routesByPath = {} as RoutesByPath<TRouteTree>
const notFoundRoute = this.options.notFoundRoute
if (notFoundRoute) {
notFoundRoute.init({
originalIndex: 99999999999,
defaultSsr: this.options.defaultSsr,
})
;(this.routesById as any)[notFoundRoute.id] = notFoundRoute
}
const recurseRoutes = (childRoutes: Array<AnyRoute>) => {
childRoutes.forEach((childRoute, i) => {
childRoute.init({
originalIndex: i,
defaultSsr: this.options.defaultSsr,
})
const existingRoute = (this.routesById as any)[childRoute.id]
invariant(
!existingRoute,
`Duplicate routes found with id: ${String(childRoute.id)}`,
)
;(this.routesById as any)[childRoute.id] = childRoute
if (!childRoute.isRoot && childRoute.path) {
const trimmedFullPath = trimPathRight(childRoute.fullPath)
if (
!(this.routesByPath as any)[trimmedFullPath] ||
childRoute.fullPath.endsWith('/')
) {
;(this.routesByPath as any)[trimmedFullPath] = childRoute
}
}
const children = childRoute.children
if (children?.length) {
recurseRoutes(children)
}
})
}
recurseRoutes([this.routeTree])
const scoredRoutes: Array<{
child: AnyRoute
trimmed: string
parsed: ReturnType<typeof parsePathname>
index: number
scores: Array<number>
}> = []
const routes: Array<AnyRoute> = Object.values(this.routesById)
routes.forEach((d, i) => {
if (d.isRoot || !d.path) {
return
}
const trimmed = trimPathLeft(d.fullPath)
const parsed = parsePathname(trimmed)
while (parsed.length > 1 && parsed[0]?.value === '/') {
parsed.shift()
}
const scores = parsed.map((segment) => {
if (segment.value === '/') {
return 0.75
}
if (segment.type === 'param') {
return 0.5
}
if (segment.type === 'wildcard') {
return 0.25
}
return 1
})
scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores })
})
this.flatRoutes = scoredRoutes
.sort((a, b) => {
const minLength = Math.min(a.scores.length, b.scores.length)
// Sort by min available score
for (let i = 0; i < minLength; i++) {
if (a.scores[i] !== b.scores[i]) {
return b.scores[i]! - a.scores[i]!
}
}
// Sort by length of score
if (a.scores.length !== b.scores.length) {
return b.scores.length - a.scores.length
}
// Sort by min available parsed value
for (let i = 0; i < minLength; i++) {
if (a.parsed[i]!.value !== b.parsed[i]!.value) {
return a.parsed[i]!.value > b.parsed[i]!.value ? 1 : -1
}
}
// Sort by original index
return a.index - b.index
})
.map((d, i) => {
d.child.rank = i
return d.child
})
}
subscribe = <TType extends keyof RouterEvents>(
eventType: TType,
fn: ListenerFn<RouterEvents[TType]>,
) => {
const listener: RouterListener<any> = {
eventType,
fn,
}
this.subscribers.add(listener)
return () => {
this.subscribers.delete(listener)
}
}
emit = (routerEvent: RouterEvent) => {
this.subscribers.forEach((listener) => {
if (listener.eventType === routerEvent.type) {
listener.fn(routerEvent)
}
})
}
parseLocation = (
previousLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>,
): ParsedLocation<FullSearchSchema<TRouteTree>> => {
const parse = ({
pathname,
search,
hash,
state,
}: HistoryLocation): ParsedLocation<FullSearchSchema<TRouteTree>> => {
const parsedSearch = this.options.parseSearch(search)
const searchStr = this.options.stringifySearch(parsedSearch)