@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
@@ -0,0 +1,1085 @@
1
+ /**
2
+ * @tanstack/react-router/src/index.tsx
3
+ *
4
+ * Copyright (c) TanStack
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE.md file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ 'use strict';
12
+
13
+ var history = require('@tanstack/history');
14
+ var store = require('@tanstack/store');
15
+ var searchParams = require('./searchParams.js');
16
+ var utils = require('./utils.js');
17
+ var RouterProvider = require('./RouterProvider.js');
18
+ var path = require('./path.js');
19
+ var invariant = require('tiny-invariant');
20
+ var redirects = require('./redirects.js');
21
+
22
+ // import warning from 'tiny-warning'
23
+
24
+ //
25
+
26
+ const componentTypes = ['component', 'errorComponent', 'pendingComponent'];
27
+ class Router {
28
+ // Option-independent properties
29
+ tempLocationKey = `${Math.round(Math.random() * 10000000)}`;
30
+ resetNextScroll = true;
31
+ navigateTimeout = null;
32
+ latestLoadPromise = Promise.resolve();
33
+ subscribers = new Set();
34
+ injectedHtml = [];
35
+
36
+ // Must build in constructor
37
+
38
+ constructor(options) {
39
+ this.update({
40
+ defaultPreloadDelay: 50,
41
+ defaultPendingMs: 1000,
42
+ defaultPendingMinMs: 500,
43
+ context: undefined,
44
+ ...options,
45
+ stringifySearch: options?.stringifySearch ?? searchParams.defaultStringifySearch,
46
+ parseSearch: options?.parseSearch ?? searchParams.defaultParseSearch
47
+ });
48
+ }
49
+
50
+ // These are default implementations that can optionally be overridden
51
+ // by the router provider once rendered. We provide these so that the
52
+ // router can be used in a non-react environment if necessary
53
+ startReactTransition = fn => fn();
54
+ update = newOptions => {
55
+ this.options = {
56
+ ...this.options,
57
+ ...newOptions
58
+ };
59
+ this.basepath = `/${path.trimPath(newOptions.basepath ?? '') ?? ''}`;
60
+ if (!this.history || this.options.history && this.options.history !== this.history) {
61
+ this.history = this.options.history ?? (typeof document !== 'undefined' ? history.createBrowserHistory() : history.createMemoryHistory());
62
+ this.latestLocation = this.parseLocation();
63
+ }
64
+ if (this.options.routeTree !== this.routeTree) {
65
+ this.routeTree = this.options.routeTree;
66
+ this.buildRouteTree();
67
+ }
68
+ if (!this.__store) {
69
+ this.__store = new store.Store(getInitialRouterState(this.latestLocation), {
70
+ onUpdate: () => {
71
+ this.__store.state = {
72
+ ...this.state,
73
+ status: this.state.isTransitioning || this.state.isLoading ? 'pending' : 'idle'
74
+ };
75
+ }
76
+ });
77
+ }
78
+ };
79
+ get state() {
80
+ return this.__store.state;
81
+ }
82
+ buildRouteTree = () => {
83
+ this.routesById = {};
84
+ this.routesByPath = {};
85
+ const notFoundRoute = this.options.notFoundRoute;
86
+ if (notFoundRoute) {
87
+ notFoundRoute.init({
88
+ originalIndex: 99999999999
89
+ });
90
+ this.routesById[notFoundRoute.id] = notFoundRoute;
91
+ }
92
+ const recurseRoutes = childRoutes => {
93
+ childRoutes.forEach((childRoute, i) => {
94
+ childRoute.init({
95
+ originalIndex: i
96
+ });
97
+ const existingRoute = this.routesById[childRoute.id];
98
+ invariant(!existingRoute, `Duplicate routes found with id: ${String(childRoute.id)}`);
99
+ this.routesById[childRoute.id] = childRoute;
100
+ if (!childRoute.isRoot && childRoute.path) {
101
+ const trimmedFullPath = path.trimPathRight(childRoute.fullPath);
102
+ if (!this.routesByPath[trimmedFullPath] || childRoute.fullPath.endsWith('/')) {
103
+ this.routesByPath[trimmedFullPath] = childRoute;
104
+ }
105
+ }
106
+ const children = childRoute.children;
107
+ if (children?.length) {
108
+ recurseRoutes(children);
109
+ }
110
+ });
111
+ };
112
+ recurseRoutes([this.routeTree]);
113
+ const scoredRoutes = [];
114
+ Object.values(this.routesById).forEach((d, i) => {
115
+ if (d.isRoot || !d.path) {
116
+ return;
117
+ }
118
+ const trimmed = path.trimPathLeft(d.fullPath);
119
+ const parsed = path.parsePathname(trimmed);
120
+ while (parsed.length > 1 && parsed[0]?.value === '/') {
121
+ parsed.shift();
122
+ }
123
+ const scores = parsed.map(d => {
124
+ if (d.value === '/') {
125
+ return 0.75;
126
+ }
127
+ if (d.type === 'param') {
128
+ return 0.5;
129
+ }
130
+ if (d.type === 'wildcard') {
131
+ return 0.25;
132
+ }
133
+ return 1;
134
+ });
135
+ scoredRoutes.push({
136
+ child: d,
137
+ trimmed,
138
+ parsed,
139
+ index: i,
140
+ scores
141
+ });
142
+ });
143
+ this.flatRoutes = scoredRoutes.sort((a, b) => {
144
+ const minLength = Math.min(a.scores.length, b.scores.length);
145
+
146
+ // Sort by min available score
147
+ for (let i = 0; i < minLength; i++) {
148
+ if (a.scores[i] !== b.scores[i]) {
149
+ return b.scores[i] - a.scores[i];
150
+ }
151
+ }
152
+
153
+ // Sort by length of score
154
+ if (a.scores.length !== b.scores.length) {
155
+ return b.scores.length - a.scores.length;
156
+ }
157
+
158
+ // Sort by min available parsed value
159
+ for (let i = 0; i < minLength; i++) {
160
+ if (a.parsed[i].value !== b.parsed[i].value) {
161
+ return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
162
+ }
163
+ }
164
+
165
+ // Sort by original index
166
+ return a.index - b.index;
167
+ }).map((d, i) => {
168
+ d.child.rank = i;
169
+ return d.child;
170
+ });
171
+ };
172
+ subscribe = (eventType, fn) => {
173
+ const listener = {
174
+ eventType,
175
+ fn
176
+ };
177
+ this.subscribers.add(listener);
178
+ return () => {
179
+ this.subscribers.delete(listener);
180
+ };
181
+ };
182
+ emit = routerEvent => {
183
+ this.subscribers.forEach(listener => {
184
+ if (listener.eventType === routerEvent.type) {
185
+ listener.fn(routerEvent);
186
+ }
187
+ });
188
+ };
189
+ checkLatest = promise => {
190
+ return this.latestLoadPromise !== promise ? this.latestLoadPromise : undefined;
191
+ };
192
+ parseLocation = previousLocation => {
193
+ const parse = ({
194
+ pathname,
195
+ search,
196
+ hash,
197
+ state
198
+ }) => {
199
+ const parsedSearch = this.options.parseSearch(search);
200
+ return {
201
+ pathname: pathname,
202
+ searchStr: search,
203
+ search: utils.replaceEqualDeep(previousLocation?.search, parsedSearch),
204
+ hash: hash.split('#').reverse()[0] ?? '',
205
+ href: `${pathname}${search}${hash}`,
206
+ state: utils.replaceEqualDeep(previousLocation?.state, state)
207
+ };
208
+ };
209
+ const location = parse(this.history.location);
210
+ let {
211
+ __tempLocation,
212
+ __tempKey
213
+ } = location.state;
214
+ if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
215
+ // Sync up the location keys
216
+ const parsedTempLocation = parse(__tempLocation);
217
+ parsedTempLocation.state.key = location.state.key;
218
+ delete parsedTempLocation.state.__tempLocation;
219
+ return {
220
+ ...parsedTempLocation,
221
+ maskedLocation: location
222
+ };
223
+ }
224
+ return location;
225
+ };
226
+ resolvePathWithBase = (from, path$1) => {
227
+ return path.resolvePath(this.basepath, from, path.cleanPath(path$1));
228
+ };
229
+ get looseRoutesById() {
230
+ return this.routesById;
231
+ }
232
+ matchRoutes = (pathname, locationSearch, opts) => {
233
+ let routeParams = {};
234
+ let foundRoute = this.flatRoutes.find(route => {
235
+ const matchedParams = path.matchPathname(this.basepath, path.trimPathRight(pathname), {
236
+ to: route.fullPath,
237
+ caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive,
238
+ fuzzy: true
239
+ });
240
+ if (matchedParams) {
241
+ routeParams = matchedParams;
242
+ return true;
243
+ }
244
+ return false;
245
+ });
246
+ let routeCursor = foundRoute || this.routesById['__root__'];
247
+ let matchedRoutes = [routeCursor];
248
+
249
+ // Check to see if the route needs a 404 entry
250
+ if (
251
+ // If we found a route, and it's not an index route and we have left over path
252
+ (foundRoute ? foundRoute.path !== '/' && routeParams['**'] :
253
+ // Or if we didn't find a route and we have left over path
254
+ path.trimPathRight(pathname)) &&
255
+ // And we have a 404 route configured
256
+ this.options.notFoundRoute) {
257
+ matchedRoutes.push(this.options.notFoundRoute);
258
+ }
259
+ while (routeCursor?.parentRoute) {
260
+ routeCursor = routeCursor.parentRoute;
261
+ if (routeCursor) matchedRoutes.unshift(routeCursor);
262
+ }
263
+
264
+ // Existing matches are matches that are already loaded along with
265
+ // pending matches that are still loading
266
+
267
+ const parseErrors = matchedRoutes.map(route => {
268
+ let parsedParamsError;
269
+ if (route.options.parseParams) {
270
+ try {
271
+ const parsedParams = route.options.parseParams(routeParams);
272
+ // Add the parsed params to the accumulated params bag
273
+ Object.assign(routeParams, parsedParams);
274
+ } catch (err) {
275
+ parsedParamsError = new PathParamError(err.message, {
276
+ cause: err
277
+ });
278
+ if (opts?.throwOnError) {
279
+ throw parsedParamsError;
280
+ }
281
+ return parsedParamsError;
282
+ }
283
+ }
284
+ return;
285
+ });
286
+ const matches = [];
287
+ matchedRoutes.forEach((route, index) => {
288
+ // Take each matched route and resolve + validate its search params
289
+ // This has to happen serially because each route's search params
290
+ // can depend on the parent route's search params
291
+ // It must also happen before we create the match so that we can
292
+ // pass the search params to the route's potential key function
293
+ // which is used to uniquely identify the route match in state
294
+
295
+ const parentMatch = matches[index - 1];
296
+ const [preMatchSearch, searchError] = (() => {
297
+ // Validate the search params and stabilize them
298
+ const parentSearch = parentMatch?.search ?? locationSearch;
299
+ try {
300
+ const validator = typeof route.options.validateSearch === 'object' ? route.options.validateSearch.parse : route.options.validateSearch;
301
+ let search = validator?.(parentSearch) ?? {};
302
+ return [{
303
+ ...parentSearch,
304
+ ...search
305
+ }, undefined];
306
+ } catch (err) {
307
+ const searchError = new SearchParamError(err.message, {
308
+ cause: err
309
+ });
310
+ if (opts?.throwOnError) {
311
+ throw searchError;
312
+ }
313
+ return [parentSearch, searchError];
314
+ }
315
+ })();
316
+
317
+ // This is where we need to call route.options.loaderDeps() to get any additional
318
+ // deps that the route's loader function might need to run. We need to do this
319
+ // before we create the match so that we can pass the deps to the route's
320
+ // potential key function which is used to uniquely identify the route match in state
321
+
322
+ const loaderDeps = route.options.loaderDeps?.({
323
+ search: preMatchSearch
324
+ }) ?? '';
325
+ const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : '';
326
+ const interpolatedPath = path.interpolatePath(route.fullPath, routeParams);
327
+ const matchId = path.interpolatePath(route.id, routeParams, true) + loaderDepsHash;
328
+
329
+ // Waste not, want not. If we already have a match for this route,
330
+ // reuse it. This is important for layout routes, which might stick
331
+ // around between navigation actions that only change leaf routes.
332
+ const existingMatch = RouterProvider.getRouteMatch(this.state, matchId);
333
+ const cause = this.state.matches.find(d => d.id === matchId) ? 'stay' : 'enter';
334
+
335
+ // Create a fresh route match
336
+ const hasLoaders = !!(route.options.loader || componentTypes.some(d => route.options[d]?.preload));
337
+ const match = existingMatch ? {
338
+ ...existingMatch,
339
+ cause
340
+ } : {
341
+ id: matchId,
342
+ routeId: route.id,
343
+ params: routeParams,
344
+ pathname: path.joinPaths([this.basepath, interpolatedPath]),
345
+ updatedAt: Date.now(),
346
+ search: {},
347
+ searchError: undefined,
348
+ status: hasLoaders ? 'pending' : 'success',
349
+ showPending: false,
350
+ isFetching: false,
351
+ error: undefined,
352
+ paramsError: parseErrors[index],
353
+ loadPromise: Promise.resolve(),
354
+ routeContext: undefined,
355
+ context: undefined,
356
+ abortController: new AbortController(),
357
+ fetchCount: 0,
358
+ cause,
359
+ loaderDeps,
360
+ invalid: false,
361
+ preload: false
362
+ };
363
+
364
+ // Regardless of whether we're reusing an existing match or creating
365
+ // a new one, we need to update the match's search params
366
+ match.search = utils.replaceEqualDeep(match.search, preMatchSearch);
367
+ // And also update the searchError if there is one
368
+ match.searchError = searchError;
369
+ matches.push(match);
370
+ });
371
+ return matches;
372
+ };
373
+ cancelMatch = id => {
374
+ RouterProvider.getRouteMatch(this.state, id)?.abortController?.abort();
375
+ };
376
+ cancelMatches = () => {
377
+ this.state.pendingMatches?.forEach(match => {
378
+ this.cancelMatch(match.id);
379
+ });
380
+ };
381
+ buildLocation = opts => {
382
+ const build = (dest = {}, matches) => {
383
+ const from = this.latestLocation;
384
+ const fromSearch = (this.state.pendingMatches || this.state.matches).at(-1)?.search || from.search;
385
+ const fromPathname = dest.from ?? from.pathname;
386
+ let pathname = this.resolvePathWithBase(fromPathname, `${dest.to ?? ''}`);
387
+ const fromMatches = this.matchRoutes(fromPathname, fromSearch);
388
+ const stayingMatches = matches?.filter(d => fromMatches?.find(e => e.routeId === d.routeId));
389
+ const prevParams = {
390
+ ...utils.last(fromMatches)?.params
391
+ };
392
+ let nextParams = (dest.params ?? true) === true ? prevParams : utils.functionalUpdate(dest.params, prevParams);
393
+ if (nextParams) {
394
+ matches?.map(d => this.looseRoutesById[d.routeId].options.stringifyParams).filter(Boolean).forEach(fn => {
395
+ nextParams = {
396
+ ...nextParams,
397
+ ...fn(nextParams)
398
+ };
399
+ });
400
+ }
401
+ pathname = path.interpolatePath(pathname, nextParams ?? {});
402
+ const preSearchFilters = stayingMatches?.map(match => this.looseRoutesById[match.routeId].options.preSearchFilters ?? []).flat().filter(Boolean) ?? [];
403
+ const postSearchFilters = stayingMatches?.map(match => this.looseRoutesById[match.routeId].options.postSearchFilters ?? []).flat().filter(Boolean) ?? [];
404
+
405
+ // Pre filters first
406
+ const preFilteredSearch = preSearchFilters?.length ? preSearchFilters?.reduce((prev, next) => next(prev), fromSearch) : fromSearch;
407
+
408
+ // Then the link/navigate function
409
+ const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
410
+ : dest.search ? utils.functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
411
+ : preSearchFilters?.length ? preFilteredSearch // Preserve resolvedFrom filters
412
+ : {};
413
+
414
+ // Then post filters
415
+ const postFilteredSearch = postSearchFilters?.length ? postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
416
+ const search = utils.replaceEqualDeep(fromSearch, postFilteredSearch);
417
+ const searchStr = this.options.stringifySearch(search);
418
+ const hash = dest.hash === true ? from.hash : dest.hash ? utils.functionalUpdate(dest.hash, from.hash) : from.hash;
419
+ const hashStr = hash ? `#${hash}` : '';
420
+ let nextState = dest.state === true ? from.state : dest.state ? utils.functionalUpdate(dest.state, from.state) : from.state;
421
+ nextState = utils.replaceEqualDeep(from.state, nextState);
422
+ return {
423
+ pathname,
424
+ search,
425
+ searchStr,
426
+ state: nextState,
427
+ hash,
428
+ href: `${pathname}${searchStr}${hashStr}`,
429
+ unmaskOnReload: dest.unmaskOnReload
430
+ };
431
+ };
432
+ const buildWithMatches = (dest = {}, maskedDest) => {
433
+ let next = build(dest);
434
+ let maskedNext = maskedDest ? build(maskedDest) : undefined;
435
+ if (!maskedNext) {
436
+ let params = {};
437
+ let foundMask = this.options.routeMasks?.find(d => {
438
+ const match = path.matchPathname(this.basepath, next.pathname, {
439
+ to: d.from,
440
+ caseSensitive: false,
441
+ fuzzy: false
442
+ });
443
+ if (match) {
444
+ params = match;
445
+ return true;
446
+ }
447
+ return false;
448
+ });
449
+ if (foundMask) {
450
+ foundMask = {
451
+ ...foundMask,
452
+ from: path.interpolatePath(foundMask.from, params)
453
+ };
454
+ maskedDest = foundMask;
455
+ maskedNext = build(maskedDest);
456
+ }
457
+ }
458
+ const nextMatches = this.matchRoutes(next.pathname, next.search);
459
+ const maskedMatches = maskedNext ? this.matchRoutes(maskedNext.pathname, maskedNext.search) : undefined;
460
+ const maskedFinal = maskedNext ? build(maskedDest, maskedMatches) : undefined;
461
+ const final = build(dest, nextMatches);
462
+ if (maskedFinal) {
463
+ final.maskedLocation = maskedFinal;
464
+ }
465
+ return final;
466
+ };
467
+ if (opts.mask) {
468
+ return buildWithMatches(opts, {
469
+ ...utils.pick(opts, ['from']),
470
+ ...opts.mask
471
+ });
472
+ }
473
+ return buildWithMatches(opts);
474
+ };
475
+ commitLocation = async ({
476
+ startTransition,
477
+ ...next
478
+ }) => {
479
+ if (this.navigateTimeout) clearTimeout(this.navigateTimeout);
480
+ const isSameUrl = this.latestLocation.href === next.href;
481
+
482
+ // If the next urls are the same and we're not replacing,
483
+ // do nothing
484
+ if (!isSameUrl || !next.replace) {
485
+ let {
486
+ maskedLocation,
487
+ ...nextHistory
488
+ } = next;
489
+ if (maskedLocation) {
490
+ nextHistory = {
491
+ ...maskedLocation,
492
+ state: {
493
+ ...maskedLocation.state,
494
+ __tempKey: undefined,
495
+ __tempLocation: {
496
+ ...nextHistory,
497
+ search: nextHistory.searchStr,
498
+ state: {
499
+ ...nextHistory.state,
500
+ __tempKey: undefined,
501
+ __tempLocation: undefined,
502
+ key: undefined
503
+ }
504
+ }
505
+ }
506
+ };
507
+ if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
508
+ nextHistory.state.__tempKey = this.tempLocationKey;
509
+ }
510
+ }
511
+ const apply = () => {
512
+ this.history[next.replace ? 'replace' : 'push'](nextHistory.href, nextHistory.state);
513
+ };
514
+ if (startTransition ?? true) {
515
+ this.startReactTransition(apply);
516
+ } else {
517
+ apply();
518
+ }
519
+ }
520
+ this.resetNextScroll = next.resetScroll ?? true;
521
+ return this.latestLoadPromise;
522
+ };
523
+ buildAndCommitLocation = ({
524
+ replace,
525
+ resetScroll,
526
+ startTransition,
527
+ ...rest
528
+ } = {}) => {
529
+ const location = this.buildLocation(rest);
530
+ return this.commitLocation({
531
+ ...location,
532
+ startTransition,
533
+ replace,
534
+ resetScroll
535
+ });
536
+ };
537
+ navigate = ({
538
+ from,
539
+ to = '',
540
+ ...rest
541
+ }) => {
542
+ // If this link simply reloads the current route,
543
+ // make sure it has a new key so it will trigger a data refresh
544
+
545
+ // If this `to` is a valid external URL, return
546
+ // null for LinkUtils
547
+ const toString = String(to);
548
+ const fromString = typeof from === 'undefined' ? from : String(from);
549
+ let isExternal;
550
+ try {
551
+ new URL(`${toString}`);
552
+ isExternal = true;
553
+ } catch (e) {}
554
+ invariant(!isExternal, 'Attempting to navigate to external url with this.navigate!');
555
+ return this.buildAndCommitLocation({
556
+ ...rest,
557
+ from: fromString,
558
+ to: toString
559
+ });
560
+ };
561
+ loadMatches = async ({
562
+ checkLatest,
563
+ matches,
564
+ preload
565
+ }) => {
566
+ let latestPromise;
567
+ let firstBadMatchIndex;
568
+ const updateMatch = match => {
569
+ // const isPreload = this.state.cachedMatches.find((d) => d.id === match.id)
570
+ const isPending = this.state.pendingMatches?.find(d => d.id === match.id);
571
+ const isMatched = this.state.matches.find(d => d.id === match.id);
572
+ const matchesKey = isPending ? 'pendingMatches' : isMatched ? 'matches' : 'cachedMatches';
573
+ this.__store.setState(s => ({
574
+ ...s,
575
+ [matchesKey]: s[matchesKey]?.map(d => d.id === match.id ? match : d)
576
+ }));
577
+ };
578
+
579
+ // Check each match middleware to see if the route can be accessed
580
+ try {
581
+ for (let [index, match] of matches.entries()) {
582
+ const parentMatch = matches[index - 1];
583
+ const route = this.looseRoutesById[match.routeId];
584
+ const abortController = new AbortController();
585
+ const handleErrorAndRedirect = (err, code) => {
586
+ err.routerCode = code;
587
+ firstBadMatchIndex = firstBadMatchIndex ?? index;
588
+ if (redirects.isRedirect(err)) {
589
+ throw err;
590
+ }
591
+ try {
592
+ route.options.onError?.(err);
593
+ } catch (errorHandlerErr) {
594
+ err = errorHandlerErr;
595
+ if (redirects.isRedirect(errorHandlerErr)) {
596
+ throw errorHandlerErr;
597
+ }
598
+ }
599
+ matches[index] = match = {
600
+ ...match,
601
+ error: err,
602
+ status: 'error',
603
+ updatedAt: Date.now(),
604
+ abortController: new AbortController()
605
+ };
606
+ };
607
+ try {
608
+ if (match.paramsError) {
609
+ handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS');
610
+ }
611
+ if (match.searchError) {
612
+ handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH');
613
+ }
614
+ const parentContext = parentMatch?.context ?? this.options.context ?? {};
615
+ const beforeLoadContext = (await route.options.beforeLoad?.({
616
+ search: match.search,
617
+ abortController,
618
+ params: match.params,
619
+ preload: !!preload,
620
+ context: parentContext,
621
+ location: this.state.location,
622
+ // TOOD: just expose state and router, etc
623
+ navigate: opts => this.navigate({
624
+ ...opts,
625
+ from: match.pathname
626
+ }),
627
+ buildLocation: this.buildLocation,
628
+ cause: preload ? 'preload' : match.cause
629
+ })) ?? {};
630
+ if (redirects.isRedirect(beforeLoadContext)) {
631
+ throw beforeLoadContext;
632
+ }
633
+ const context = {
634
+ ...parentContext,
635
+ ...beforeLoadContext
636
+ };
637
+ matches[index] = match = {
638
+ ...match,
639
+ routeContext: utils.replaceEqualDeep(match.routeContext, beforeLoadContext),
640
+ context: utils.replaceEqualDeep(match.context, context),
641
+ abortController
642
+ };
643
+ } catch (err) {
644
+ handleErrorAndRedirect(err, 'BEFORE_LOAD');
645
+ break;
646
+ }
647
+ }
648
+ } catch (err) {
649
+ if (redirects.isRedirect(err)) {
650
+ if (!preload) this.navigate(err);
651
+ return matches;
652
+ }
653
+ throw err;
654
+ }
655
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
656
+ const matchPromises = [];
657
+ validResolvedMatches.forEach((match, index) => {
658
+ matchPromises.push(new Promise(async resolve => {
659
+ const parentMatchPromise = matchPromises[index - 1];
660
+ const route = this.looseRoutesById[match.routeId];
661
+ const handleErrorAndRedirect = err => {
662
+ if (redirects.isRedirect(err)) {
663
+ if (!preload) {
664
+ this.navigate(err);
665
+ }
666
+ return true;
667
+ }
668
+ return false;
669
+ };
670
+ let loadPromise;
671
+ matches[index] = match = {
672
+ ...match,
673
+ showPending: false
674
+ };
675
+ let didShowPending = false;
676
+ const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
677
+ const pendingMinMs = route.options.pendingMinMs ?? this.options.defaultPendingMinMs;
678
+ const shouldPending = !preload && pendingMs && (route.options.pendingComponent ?? this.options.defaultPendingComponent);
679
+ const loaderContext = {
680
+ params: match.params,
681
+ deps: match.loaderDeps,
682
+ preload: !!preload,
683
+ parentMatchPromise,
684
+ abortController: match.abortController,
685
+ context: match.context,
686
+ location: this.state.location,
687
+ navigate: opts => this.navigate({
688
+ ...opts,
689
+ from: match.pathname
690
+ }),
691
+ cause: preload ? 'preload' : match.cause
692
+ };
693
+ const fetch = async () => {
694
+ if (match.isFetching) {
695
+ loadPromise = RouterProvider.getRouteMatch(this.state, match.id)?.loadPromise;
696
+ } else {
697
+ // If the user doesn't want the route to reload, just
698
+ // resolve with the existing loader data
699
+
700
+ if (match.fetchCount && match.status === 'success') {
701
+ resolve();
702
+ }
703
+
704
+ // Otherwise, load the route
705
+ matches[index] = match = {
706
+ ...match,
707
+ isFetching: true,
708
+ fetchCount: match.fetchCount + 1
709
+ };
710
+ const componentsPromise = Promise.all(componentTypes.map(async type => {
711
+ const component = route.options[type];
712
+ if (component?.preload) {
713
+ await component.preload();
714
+ }
715
+ }));
716
+ const loaderPromise = route.options.loader?.(loaderContext);
717
+ loadPromise = Promise.all([componentsPromise, loaderPromise]).then(d => d[1]);
718
+ }
719
+ matches[index] = match = {
720
+ ...match,
721
+ loadPromise
722
+ };
723
+ updateMatch(match);
724
+ try {
725
+ const loaderData = await loadPromise;
726
+ if (latestPromise = checkLatest()) return await latestPromise;
727
+ if (redirects.isRedirect(loaderData)) {
728
+ if (handleErrorAndRedirect(loaderData)) return;
729
+ }
730
+ if (didShowPending && pendingMinMs) {
731
+ await new Promise(r => setTimeout(r, pendingMinMs));
732
+ }
733
+ if (latestPromise = checkLatest()) return await latestPromise;
734
+ matches[index] = match = {
735
+ ...match,
736
+ error: undefined,
737
+ status: 'success',
738
+ isFetching: false,
739
+ updatedAt: Date.now(),
740
+ loaderData,
741
+ loadPromise: undefined
742
+ };
743
+ } catch (error) {
744
+ if (latestPromise = checkLatest()) return await latestPromise;
745
+ if (handleErrorAndRedirect(error)) return;
746
+ try {
747
+ route.options.onError?.(error);
748
+ } catch (onErrorError) {
749
+ error = onErrorError;
750
+ if (handleErrorAndRedirect(onErrorError)) return;
751
+ }
752
+ matches[index] = match = {
753
+ ...match,
754
+ error,
755
+ status: 'error',
756
+ isFetching: false
757
+ };
758
+ }
759
+ updateMatch(match);
760
+ };
761
+
762
+ // This is where all of the stale-while-revalidate magic happens
763
+ const age = Date.now() - match.updatedAt;
764
+ let staleAge = preload ? route.options.preloadStaleTime ?? this.options.defaultPreloadStaleTime ?? 30_000 // 30 seconds for preloads by default
765
+ : route.options.staleTime ?? this.options.defaultStaleTime ?? 0;
766
+
767
+ // Default to reloading the route all the time
768
+ let shouldReload;
769
+ const shouldReloadOption = route.options.shouldReload;
770
+
771
+ // Allow shouldReload to get the last say,
772
+ // if provided.
773
+ shouldReload = typeof shouldReloadOption === 'function' ? shouldReloadOption(loaderContext) : shouldReloadOption;
774
+ matches[index] = match = {
775
+ ...match,
776
+ preload: !!preload && !this.state.matches.find(d => d.id === match.id)
777
+ };
778
+ if (match.status !== 'success') {
779
+ // If we need to potentially show the pending component,
780
+ // start a timer to show it after the pendingMs
781
+ if (shouldPending) {
782
+ new Promise(r => setTimeout(r, pendingMs)).then(async () => {
783
+ if (latestPromise = checkLatest()) return latestPromise;
784
+ didShowPending = true;
785
+ matches[index] = match = {
786
+ ...match,
787
+ showPending: true
788
+ };
789
+ updateMatch(match);
790
+ resolve();
791
+ });
792
+ }
793
+
794
+ // Critical Fetching, we need to await
795
+ await fetch();
796
+ } else if (match.invalid || (shouldReload ?? age > staleAge)) {
797
+ // Background Fetching, no need to wait
798
+ fetch();
799
+ }
800
+ resolve();
801
+ }));
802
+ });
803
+ await Promise.all(matchPromises);
804
+ return matches;
805
+ };
806
+ invalidate = () => {
807
+ const invalidate = d => ({
808
+ ...d,
809
+ invalid: true
810
+ });
811
+ this.__store.setState(s => ({
812
+ ...s,
813
+ matches: s.matches.map(invalidate),
814
+ cachedMatches: s.cachedMatches.map(invalidate),
815
+ pendingMatches: s.pendingMatches?.map(invalidate)
816
+ }));
817
+ this.load();
818
+ };
819
+ load = async () => {
820
+ const promise = new Promise(async (resolve, reject) => {
821
+ const next = this.latestLocation;
822
+ const prevLocation = this.state.resolvedLocation;
823
+ const pathDidChange = prevLocation.href !== next.href;
824
+ let latestPromise;
825
+
826
+ // Cancel any pending matches
827
+ this.cancelMatches();
828
+ this.emit({
829
+ type: 'onBeforeLoad',
830
+ fromLocation: prevLocation,
831
+ toLocation: next,
832
+ pathChanged: pathDidChange
833
+ });
834
+ let pendingMatches;
835
+ const previousMatches = this.state.matches;
836
+ this.__store.batch(() => {
837
+ this.cleanCache();
838
+
839
+ // Match the routes
840
+ pendingMatches = this.matchRoutes(next.pathname, next.search, {
841
+ debug: true
842
+ });
843
+
844
+ // Ingest the new matches
845
+ // If a cached moved to pendingMatches, remove it from cachedMatches
846
+ this.__store.setState(s => ({
847
+ ...s,
848
+ isLoading: true,
849
+ location: next,
850
+ pendingMatches,
851
+ cachedMatches: s.cachedMatches.filter(d => {
852
+ return !pendingMatches.find(e => e.id === d.id);
853
+ })
854
+ }));
855
+ });
856
+ try {
857
+ try {
858
+ // Load the matches
859
+ await this.loadMatches({
860
+ matches: pendingMatches,
861
+ checkLatest: () => this.checkLatest(promise)
862
+ });
863
+ } catch (err) {
864
+ // swallow this error, since we'll display the
865
+ // errors on the route components
866
+ }
867
+
868
+ // Only apply the latest transition
869
+ if (latestPromise = this.checkLatest(promise)) {
870
+ return latestPromise;
871
+ }
872
+ const exitingMatches = previousMatches.filter(match => !pendingMatches.find(d => d.id === match.id));
873
+ const enteringMatches = pendingMatches.filter(match => !previousMatches.find(d => d.id === match.id));
874
+ const stayingMatches = previousMatches.filter(match => pendingMatches.find(d => d.id === match.id));
875
+
876
+ // Commit the pending matches. If a previous match was
877
+ // removed, place it in the cachedMatches
878
+ this.__store.batch(() => {
879
+ this.__store.setState(s => ({
880
+ ...s,
881
+ isLoading: false,
882
+ matches: s.pendingMatches,
883
+ pendingMatches: undefined,
884
+ cachedMatches: [...s.cachedMatches, ...exitingMatches.filter(d => d.status !== 'error')]
885
+ }));
886
+ this.cleanCache();
887
+ })
888
+
889
+ //
890
+ ;
891
+ [[exitingMatches, 'onLeave'], [enteringMatches, 'onEnter'], [stayingMatches, 'onStay']].forEach(([matches, hook]) => {
892
+ matches.forEach(match => {
893
+ this.looseRoutesById[match.routeId].options[hook]?.(match);
894
+ });
895
+ });
896
+ this.emit({
897
+ type: 'onLoad',
898
+ fromLocation: prevLocation,
899
+ toLocation: next,
900
+ pathChanged: pathDidChange
901
+ });
902
+ resolve();
903
+ } catch (err) {
904
+ // Only apply the latest transition
905
+ if (latestPromise = this.checkLatest(promise)) {
906
+ return latestPromise;
907
+ }
908
+ reject(err);
909
+ }
910
+ });
911
+ this.latestLoadPromise = promise;
912
+ return this.latestLoadPromise;
913
+ };
914
+ cleanCache = () => {
915
+ // This is where all of the garbage collection magic happens
916
+ this.__store.setState(s => {
917
+ return {
918
+ ...s,
919
+ cachedMatches: s.cachedMatches.filter(d => {
920
+ const route = this.looseRoutesById[d.routeId];
921
+ if (!route.options.loader) {
922
+ return false;
923
+ }
924
+
925
+ // If the route was preloaded, use the preloadGcTime
926
+ // otherwise, use the gcTime
927
+ const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 5 * 60 * 1000;
928
+ return d.status !== 'error' && Date.now() - d.updatedAt < gcTime;
929
+ })
930
+ };
931
+ });
932
+ };
933
+ preloadRoute = async (navigateOpts = this.state.location) => {
934
+ let next = this.buildLocation(navigateOpts);
935
+ let matches = this.matchRoutes(next.pathname, next.search, {
936
+ throwOnError: true
937
+ });
938
+ const loadedMatchIds = Object.fromEntries([...this.state.matches, ...(this.state.pendingMatches ?? []), ...this.state.cachedMatches]?.map(d => [d.id, true]));
939
+ this.__store.batch(() => {
940
+ matches.forEach(match => {
941
+ if (!loadedMatchIds[match.id]) {
942
+ this.__store.setState(s => ({
943
+ ...s,
944
+ cachedMatches: [...s.cachedMatches, match]
945
+ }));
946
+ }
947
+ });
948
+ });
949
+ matches = await this.loadMatches({
950
+ matches,
951
+ preload: true,
952
+ checkLatest: () => undefined
953
+ });
954
+ return matches;
955
+ };
956
+ matchRoute = (location, opts) => {
957
+ location = {
958
+ ...location,
959
+ to: location.to ? this.resolvePathWithBase(location.from || '', location.to) : undefined
960
+ };
961
+ const next = this.buildLocation(location);
962
+ if (opts?.pending && this.state.status !== 'pending') {
963
+ return false;
964
+ }
965
+ const baseLocation = opts?.pending ? this.latestLocation : this.state.resolvedLocation;
966
+ if (!baseLocation) {
967
+ return false;
968
+ }
969
+ const match = path.matchPathname(this.basepath, baseLocation.pathname, {
970
+ ...opts,
971
+ to: next.pathname
972
+ });
973
+ if (!match) {
974
+ return false;
975
+ }
976
+ if (match && (opts?.includeSearch ?? true)) {
977
+ return utils.deepEqual(baseLocation.search, next.search, true) ? match : false;
978
+ }
979
+ return match;
980
+ };
981
+ injectHtml = async html => {
982
+ this.injectedHtml.push(html);
983
+ };
984
+ dehydrateData = (key, getData) => {
985
+ if (typeof document === 'undefined') {
986
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key);
987
+ this.injectHtml(async () => {
988
+ const id = `__TSR_DEHYDRATED__${strKey}`;
989
+ const data = typeof getData === 'function' ? await getData() : getData;
990
+ return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${utils.escapeJSON(strKey)}"] = ${JSON.stringify(data)}
991
+ ;(() => {
992
+ var el = document.getElementById('${id}')
993
+ el.parentElement.removeChild(el)
994
+ })()
995
+ </script>`;
996
+ });
997
+ return () => this.hydrateData(key);
998
+ }
999
+ return () => undefined;
1000
+ };
1001
+ hydrateData = key => {
1002
+ if (typeof document !== 'undefined') {
1003
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key);
1004
+ return window[`__TSR_DEHYDRATED__${strKey}`];
1005
+ }
1006
+ return undefined;
1007
+ };
1008
+ dehydrate = () => {
1009
+ return {
1010
+ state: {
1011
+ dehydratedMatches: this.state.matches.map(d => utils.pick(d, ['id', 'status', 'updatedAt', 'loaderData']))
1012
+ }
1013
+ };
1014
+ };
1015
+ hydrate = async __do_not_use_server_ctx => {
1016
+ let _ctx = __do_not_use_server_ctx;
1017
+ // Client hydrates from window
1018
+ if (typeof document !== 'undefined') {
1019
+ _ctx = window.__TSR_DEHYDRATED__;
1020
+ }
1021
+ invariant(_ctx, 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?');
1022
+ const ctx = _ctx;
1023
+ this.dehydratedData = ctx.payload;
1024
+ this.options.hydrate?.(ctx.payload);
1025
+ const dehydratedState = ctx.router.state;
1026
+ let matches = this.matchRoutes(this.state.location.pathname, this.state.location.search).map(match => {
1027
+ const dehydratedMatch = dehydratedState.dehydratedMatches.find(d => d.id === match.id);
1028
+ invariant(dehydratedMatch, `Could not find a client-side match for dehydrated match with id: ${match.id}!`);
1029
+ if (dehydratedMatch) {
1030
+ return {
1031
+ ...match,
1032
+ ...dehydratedMatch
1033
+ };
1034
+ }
1035
+ return match;
1036
+ });
1037
+ this.__store.setState(s => {
1038
+ return {
1039
+ ...s,
1040
+ matches: matches
1041
+ };
1042
+ });
1043
+ };
1044
+
1045
+ // resolveMatchPromise = (matchId: string, key: string, value: any) => {
1046
+ // state.matches
1047
+ // .find((d) => d.id === matchId)
1048
+ // ?.__promisesByKey[key]?.resolve(value)
1049
+ // }
1050
+ }
1051
+
1052
+ // A function that takes an import() argument which is a function and returns a new function that will
1053
+ // proxy arguments from the caller to the imported function, retaining all type
1054
+ // information along the way
1055
+ function lazyFn(fn, key) {
1056
+ return async (...args) => {
1057
+ const imported = await fn();
1058
+ return imported[key || 'default'](...args);
1059
+ };
1060
+ }
1061
+ class SearchParamError extends Error {}
1062
+ class PathParamError extends Error {}
1063
+ function getInitialRouterState(location) {
1064
+ return {
1065
+ isLoading: false,
1066
+ isTransitioning: false,
1067
+ status: 'idle',
1068
+ resolvedLocation: {
1069
+ ...location
1070
+ },
1071
+ location,
1072
+ matches: [],
1073
+ pendingMatches: [],
1074
+ cachedMatches: [],
1075
+ lastUpdated: Date.now()
1076
+ };
1077
+ }
1078
+
1079
+ exports.PathParamError = PathParamError;
1080
+ exports.Router = Router;
1081
+ exports.SearchParamError = SearchParamError;
1082
+ exports.componentTypes = componentTypes;
1083
+ exports.getInitialRouterState = getInitialRouterState;
1084
+ exports.lazyFn = lazyFn;
1085
+ //# sourceMappingURL=router.js.map