@tanstack/react-router 0.0.1-beta.83 → 1.0.0

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