@tanstack/router-core 0.0.1-beta.9 → 1.20.3-alpha.1

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 (194) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +5 -0
  3. package/dist/cjs/Matches.cjs +13 -0
  4. package/dist/cjs/Matches.cjs.map +1 -0
  5. package/dist/cjs/Matches.d.cts +109 -0
  6. package/dist/cjs/RouterProvider.d.cts +26 -0
  7. package/dist/cjs/defer.cjs +25 -0
  8. package/dist/cjs/defer.cjs.map +1 -0
  9. package/dist/cjs/defer.d.cts +20 -0
  10. package/dist/cjs/fileRoute.d.cts +23 -0
  11. package/dist/cjs/history.d.cts +8 -0
  12. package/dist/cjs/index.cjs +80 -0
  13. package/dist/cjs/index.cjs.map +1 -0
  14. package/dist/cjs/index.d.cts +41 -0
  15. package/dist/cjs/link.cjs +5 -0
  16. package/dist/cjs/link.cjs.map +1 -0
  17. package/dist/cjs/link.d.cts +200 -0
  18. package/dist/cjs/location.d.cts +12 -0
  19. package/dist/cjs/manifest.d.cts +24 -0
  20. package/dist/cjs/not-found.cjs +13 -0
  21. package/dist/cjs/not-found.cjs.map +1 -0
  22. package/dist/cjs/not-found.d.cts +20 -0
  23. package/dist/cjs/path.cjs +412 -0
  24. package/dist/cjs/path.cjs.map +1 -0
  25. package/dist/cjs/path.d.cts +56 -0
  26. package/dist/cjs/qss.cjs +38 -0
  27. package/dist/cjs/qss.cjs.map +1 -0
  28. package/dist/cjs/qss.d.cts +22 -0
  29. package/dist/cjs/redirect.cjs +34 -0
  30. package/dist/cjs/redirect.cjs.map +1 -0
  31. package/dist/cjs/redirect.d.cts +38 -0
  32. package/dist/cjs/root.cjs +5 -0
  33. package/dist/cjs/root.cjs.map +1 -0
  34. package/dist/cjs/root.d.cts +2 -0
  35. package/dist/cjs/route.cjs +119 -0
  36. package/dist/cjs/route.cjs.map +1 -0
  37. package/dist/cjs/route.d.cts +422 -0
  38. package/dist/cjs/routeInfo.d.cts +54 -0
  39. package/dist/cjs/router.cjs +1800 -0
  40. package/dist/cjs/router.cjs.map +1 -0
  41. package/dist/cjs/router.d.cts +630 -0
  42. package/dist/cjs/scroll-restoration.cjs +196 -0
  43. package/dist/cjs/scroll-restoration.cjs.map +1 -0
  44. package/dist/cjs/scroll-restoration.d.cts +38 -0
  45. package/dist/cjs/searchMiddleware.cjs +42 -0
  46. package/dist/cjs/searchMiddleware.cjs.map +1 -0
  47. package/dist/cjs/searchMiddleware.d.cts +5 -0
  48. package/dist/cjs/searchParams.cjs +61 -0
  49. package/dist/cjs/searchParams.cjs.map +1 -0
  50. package/dist/cjs/searchParams.d.cts +7 -0
  51. package/dist/cjs/serializer.d.cts +22 -0
  52. package/dist/cjs/structuralSharing.d.cts +4 -0
  53. package/dist/cjs/typePrimitives.d.cts +65 -0
  54. package/dist/cjs/useLoaderData.d.cts +5 -0
  55. package/dist/cjs/useLoaderDeps.d.cts +5 -0
  56. package/dist/cjs/useNavigate.d.cts +3 -0
  57. package/dist/cjs/useParams.d.cts +5 -0
  58. package/dist/cjs/useRouteContext.d.cts +9 -0
  59. package/dist/cjs/useSearch.d.cts +5 -0
  60. package/dist/cjs/utils.cjs +160 -0
  61. package/dist/cjs/utils.cjs.map +1 -0
  62. package/dist/cjs/utils.d.cts +105 -0
  63. package/dist/cjs/validators.d.cts +51 -0
  64. package/dist/esm/Matches.d.ts +109 -0
  65. package/dist/esm/Matches.js +13 -0
  66. package/dist/esm/Matches.js.map +1 -0
  67. package/dist/esm/RouterProvider.d.ts +26 -0
  68. package/dist/esm/defer.d.ts +20 -0
  69. package/dist/esm/defer.js +25 -0
  70. package/dist/esm/defer.js.map +1 -0
  71. package/dist/esm/fileRoute.d.ts +23 -0
  72. package/dist/esm/history.d.ts +8 -0
  73. package/dist/esm/index.d.ts +41 -0
  74. package/dist/esm/index.js +80 -0
  75. package/dist/esm/index.js.map +1 -0
  76. package/dist/esm/link.d.ts +200 -0
  77. package/dist/esm/link.js +5 -0
  78. package/dist/esm/link.js.map +1 -0
  79. package/dist/esm/location.d.ts +12 -0
  80. package/dist/esm/manifest.d.ts +24 -0
  81. package/dist/esm/not-found.d.ts +20 -0
  82. package/dist/esm/not-found.js +13 -0
  83. package/dist/esm/not-found.js.map +1 -0
  84. package/dist/esm/path.d.ts +56 -0
  85. package/dist/esm/path.js +412 -0
  86. package/dist/esm/path.js.map +1 -0
  87. package/dist/esm/qss.d.ts +22 -0
  88. package/dist/esm/qss.js +38 -0
  89. package/dist/esm/qss.js.map +1 -0
  90. package/dist/esm/redirect.d.ts +38 -0
  91. package/dist/esm/redirect.js +34 -0
  92. package/dist/esm/redirect.js.map +1 -0
  93. package/dist/esm/root.d.ts +2 -0
  94. package/dist/esm/root.js +5 -0
  95. package/dist/esm/root.js.map +1 -0
  96. package/dist/esm/route.d.ts +422 -0
  97. package/dist/esm/route.js +119 -0
  98. package/dist/esm/route.js.map +1 -0
  99. package/dist/esm/routeInfo.d.ts +54 -0
  100. package/dist/esm/router.d.ts +630 -0
  101. package/dist/esm/router.js +1800 -0
  102. package/dist/esm/router.js.map +1 -0
  103. package/dist/esm/scroll-restoration.d.ts +38 -0
  104. package/dist/esm/scroll-restoration.js +196 -0
  105. package/dist/esm/scroll-restoration.js.map +1 -0
  106. package/dist/esm/searchMiddleware.d.ts +5 -0
  107. package/dist/esm/searchMiddleware.js +42 -0
  108. package/dist/esm/searchMiddleware.js.map +1 -0
  109. package/dist/esm/searchParams.d.ts +7 -0
  110. package/dist/esm/searchParams.js +61 -0
  111. package/dist/esm/searchParams.js.map +1 -0
  112. package/dist/esm/serializer.d.ts +22 -0
  113. package/dist/esm/structuralSharing.d.ts +4 -0
  114. package/dist/esm/typePrimitives.d.ts +65 -0
  115. package/dist/esm/useLoaderData.d.ts +5 -0
  116. package/dist/esm/useLoaderDeps.d.ts +5 -0
  117. package/dist/esm/useNavigate.d.ts +3 -0
  118. package/dist/esm/useParams.d.ts +5 -0
  119. package/dist/esm/useRouteContext.d.ts +9 -0
  120. package/dist/esm/useSearch.d.ts +5 -0
  121. package/dist/esm/utils.d.ts +105 -0
  122. package/dist/esm/utils.js +160 -0
  123. package/dist/esm/utils.js.map +1 -0
  124. package/dist/esm/validators.d.ts +51 -0
  125. package/package.json +36 -32
  126. package/src/Matches.ts +239 -0
  127. package/src/RouterProvider.ts +50 -0
  128. package/src/defer.ts +52 -0
  129. package/src/fileRoute.ts +140 -0
  130. package/src/history.ts +9 -0
  131. package/src/index.ts +421 -19
  132. package/src/link.ts +580 -286
  133. package/src/location.ts +13 -0
  134. package/src/manifest.ts +32 -0
  135. package/src/not-found.ts +29 -0
  136. package/src/path.ts +425 -49
  137. package/src/qss.ts +70 -41
  138. package/src/redirect.ts +100 -0
  139. package/src/root.ts +2 -0
  140. package/src/route.ts +1682 -218
  141. package/src/routeInfo.ts +224 -217
  142. package/src/router.ts +3100 -1073
  143. package/src/scroll-restoration.ts +340 -0
  144. package/src/searchMiddleware.ts +54 -0
  145. package/src/searchParams.ts +43 -20
  146. package/src/serializer.ts +32 -0
  147. package/src/structuralSharing.ts +7 -0
  148. package/src/typePrimitives.ts +181 -0
  149. package/src/useLoaderData.ts +20 -0
  150. package/src/useLoaderDeps.ts +13 -0
  151. package/src/useNavigate.ts +13 -0
  152. package/src/useParams.ts +20 -0
  153. package/src/useRouteContext.ts +39 -0
  154. package/src/useSearch.ts +20 -0
  155. package/src/utils.ts +369 -75
  156. package/src/validators.ts +121 -0
  157. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +0 -33
  158. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +0 -1
  159. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js +0 -33
  160. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js.map +0 -1
  161. package/build/cjs/node_modules/history/index.js +0 -815
  162. package/build/cjs/node_modules/history/index.js.map +0 -1
  163. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js +0 -30
  164. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js.map +0 -1
  165. package/build/cjs/packages/router-core/src/index.js +0 -58
  166. package/build/cjs/packages/router-core/src/index.js.map +0 -1
  167. package/build/cjs/packages/router-core/src/path.js +0 -222
  168. package/build/cjs/packages/router-core/src/path.js.map +0 -1
  169. package/build/cjs/packages/router-core/src/qss.js +0 -71
  170. package/build/cjs/packages/router-core/src/qss.js.map +0 -1
  171. package/build/cjs/packages/router-core/src/route.js +0 -150
  172. package/build/cjs/packages/router-core/src/route.js.map +0 -1
  173. package/build/cjs/packages/router-core/src/routeConfig.js +0 -69
  174. package/build/cjs/packages/router-core/src/routeConfig.js.map +0 -1
  175. package/build/cjs/packages/router-core/src/routeMatch.js +0 -266
  176. package/build/cjs/packages/router-core/src/routeMatch.js.map +0 -1
  177. package/build/cjs/packages/router-core/src/router.js +0 -822
  178. package/build/cjs/packages/router-core/src/router.js.map +0 -1
  179. package/build/cjs/packages/router-core/src/searchParams.js +0 -70
  180. package/build/cjs/packages/router-core/src/searchParams.js.map +0 -1
  181. package/build/cjs/packages/router-core/src/utils.js +0 -125
  182. package/build/cjs/packages/router-core/src/utils.js.map +0 -1
  183. package/build/esm/index.js +0 -2481
  184. package/build/esm/index.js.map +0 -1
  185. package/build/stats-html.html +0 -4034
  186. package/build/stats-react.json +0 -493
  187. package/build/types/index.d.ts +0 -618
  188. package/build/umd/index.development.js +0 -2514
  189. package/build/umd/index.development.js.map +0 -1
  190. package/build/umd/index.production.js +0 -12
  191. package/build/umd/index.production.js.map +0 -1
  192. package/src/frameworks.ts +0 -12
  193. package/src/routeConfig.ts +0 -495
  194. package/src/routeMatch.ts +0 -374
@@ -0,0 +1,1800 @@
1
+ import { Store, batch } from "@tanstack/store";
2
+ import { createMemoryHistory, createBrowserHistory, parseHref } from "@tanstack/history";
3
+ import invariant from "tiny-invariant";
4
+ import { pick, createControlledPromise, deepEqual, replaceEqualDeep, last, functionalUpdate } from "./utils.js";
5
+ import { trimPath, resolvePath, cleanPath, matchPathname, trimPathRight, interpolatePath, joinPaths, trimPathLeft, parsePathname } from "./path.js";
6
+ import { isNotFound } from "./not-found.js";
7
+ import { setupScrollRestoration } from "./scroll-restoration.js";
8
+ import { defaultParseSearch, defaultStringifySearch } from "./searchParams.js";
9
+ import { rootRouteId } from "./root.js";
10
+ import { isRedirect } from "./redirect.js";
11
+ function defaultSerializeError(err) {
12
+ if (err instanceof Error) {
13
+ const obj = {
14
+ name: err.name,
15
+ message: err.message
16
+ };
17
+ if (process.env.NODE_ENV === "development") {
18
+ obj.stack = err.stack;
19
+ }
20
+ return obj;
21
+ }
22
+ return {
23
+ data: err
24
+ };
25
+ }
26
+ function getLocationChangeInfo(routerState) {
27
+ const fromLocation = routerState.resolvedLocation;
28
+ const toLocation = routerState.location;
29
+ const pathChanged = (fromLocation == null ? void 0 : fromLocation.pathname) !== toLocation.pathname;
30
+ const hrefChanged = (fromLocation == null ? void 0 : fromLocation.href) !== toLocation.href;
31
+ const hashChanged = (fromLocation == null ? void 0 : fromLocation.hash) !== toLocation.hash;
32
+ return { fromLocation, toLocation, pathChanged, hrefChanged, hashChanged };
33
+ }
34
+ class RouterCore {
35
+ /**
36
+ * @deprecated Use the `createRouter` function instead
37
+ */
38
+ constructor(options) {
39
+ this.tempLocationKey = `${Math.round(
40
+ Math.random() * 1e7
41
+ )}`;
42
+ this.resetNextScroll = true;
43
+ this.shouldViewTransition = void 0;
44
+ this.isViewTransitionTypesSupported = void 0;
45
+ this.subscribers = /* @__PURE__ */ new Set();
46
+ this.isScrollRestoring = false;
47
+ this.isScrollRestorationSetup = false;
48
+ this.startTransition = (fn) => fn();
49
+ this.update = (newOptions) => {
50
+ var _a;
51
+ if (newOptions.notFoundRoute) {
52
+ console.warn(
53
+ "The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/framework/react/guide/not-found-errors#migrating-from-notfoundroute for more info."
54
+ );
55
+ }
56
+ const previousOptions = this.options;
57
+ this.options = {
58
+ ...this.options,
59
+ ...newOptions
60
+ };
61
+ this.isServer = this.options.isServer ?? typeof document === "undefined";
62
+ this.pathParamsDecodeCharMap = this.options.pathParamsAllowedCharacters ? new Map(
63
+ this.options.pathParamsAllowedCharacters.map((char) => [
64
+ encodeURIComponent(char),
65
+ char
66
+ ])
67
+ ) : void 0;
68
+ if (!this.basepath || newOptions.basepath && newOptions.basepath !== previousOptions.basepath) {
69
+ if (newOptions.basepath === void 0 || newOptions.basepath === "" || newOptions.basepath === "/") {
70
+ this.basepath = "/";
71
+ } else {
72
+ this.basepath = `/${trimPath(newOptions.basepath)}`;
73
+ }
74
+ }
75
+ if (!this.history || this.options.history && this.options.history !== this.history) {
76
+ this.history = this.options.history ?? (this.isServer ? createMemoryHistory({
77
+ initialEntries: [this.basepath || "/"]
78
+ }) : createBrowserHistory());
79
+ this.latestLocation = this.parseLocation();
80
+ }
81
+ if (this.options.routeTree !== this.routeTree) {
82
+ this.routeTree = this.options.routeTree;
83
+ this.buildRouteTree();
84
+ }
85
+ if (!this.__store) {
86
+ this.__store = new Store(getInitialRouterState(this.latestLocation), {
87
+ onUpdate: () => {
88
+ this.__store.state = {
89
+ ...this.state,
90
+ cachedMatches: this.state.cachedMatches.filter(
91
+ (d) => !["redirected"].includes(d.status)
92
+ )
93
+ };
94
+ }
95
+ });
96
+ setupScrollRestoration(this);
97
+ }
98
+ if (typeof window !== "undefined" && "CSS" in window && typeof ((_a = window.CSS) == null ? void 0 : _a.supports) === "function") {
99
+ this.isViewTransitionTypesSupported = window.CSS.supports(
100
+ "selector(:active-view-transition-type(a)"
101
+ );
102
+ }
103
+ };
104
+ this.buildRouteTree = () => {
105
+ const { routesById, routesByPath, flatRoutes } = processRouteTree({
106
+ routeTree: this.routeTree,
107
+ initRoute: (route, i) => {
108
+ route.init({
109
+ originalIndex: i,
110
+ defaultSsr: this.options.defaultSsr
111
+ });
112
+ }
113
+ });
114
+ this.routesById = routesById;
115
+ this.routesByPath = routesByPath;
116
+ this.flatRoutes = flatRoutes;
117
+ const notFoundRoute = this.options.notFoundRoute;
118
+ if (notFoundRoute) {
119
+ notFoundRoute.init({
120
+ originalIndex: 99999999999,
121
+ defaultSsr: this.options.defaultSsr
122
+ });
123
+ this.routesById[notFoundRoute.id] = notFoundRoute;
124
+ }
125
+ };
126
+ this.subscribe = (eventType, fn) => {
127
+ const listener = {
128
+ eventType,
129
+ fn
130
+ };
131
+ this.subscribers.add(listener);
132
+ return () => {
133
+ this.subscribers.delete(listener);
134
+ };
135
+ };
136
+ this.emit = (routerEvent) => {
137
+ this.subscribers.forEach((listener) => {
138
+ if (listener.eventType === routerEvent.type) {
139
+ listener.fn(routerEvent);
140
+ }
141
+ });
142
+ };
143
+ this.parseLocation = (previousLocation, locationToParse) => {
144
+ const parse = ({
145
+ pathname,
146
+ search,
147
+ hash,
148
+ state
149
+ }) => {
150
+ const parsedSearch = this.options.parseSearch(search);
151
+ const searchStr = this.options.stringifySearch(parsedSearch);
152
+ return {
153
+ pathname,
154
+ searchStr,
155
+ search: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
156
+ hash: hash.split("#").reverse()[0] ?? "",
157
+ href: `${pathname}${searchStr}${hash}`,
158
+ state: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.state, state)
159
+ };
160
+ };
161
+ const location = parse(locationToParse ?? this.history.location);
162
+ const { __tempLocation, __tempKey } = location.state;
163
+ if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
164
+ const parsedTempLocation = parse(__tempLocation);
165
+ parsedTempLocation.state.key = location.state.key;
166
+ delete parsedTempLocation.state.__tempLocation;
167
+ return {
168
+ ...parsedTempLocation,
169
+ maskedLocation: location
170
+ };
171
+ }
172
+ return location;
173
+ };
174
+ this.resolvePathWithBase = (from, path) => {
175
+ const resolvedPath = resolvePath({
176
+ basepath: this.basepath,
177
+ base: from,
178
+ to: cleanPath(path),
179
+ trailingSlash: this.options.trailingSlash,
180
+ caseSensitive: this.options.caseSensitive
181
+ });
182
+ return resolvedPath;
183
+ };
184
+ this.matchRoutes = (pathnameOrNext, locationSearchOrOpts, opts) => {
185
+ if (typeof pathnameOrNext === "string") {
186
+ return this.matchRoutesInternal(
187
+ {
188
+ pathname: pathnameOrNext,
189
+ search: locationSearchOrOpts
190
+ },
191
+ opts
192
+ );
193
+ } else {
194
+ return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts);
195
+ }
196
+ };
197
+ this.getMatchedRoutes = (pathname, routePathname) => {
198
+ return getMatchedRoutes({
199
+ pathname,
200
+ routePathname,
201
+ basepath: this.basepath,
202
+ caseSensitive: this.options.caseSensitive,
203
+ routesByPath: this.routesByPath,
204
+ routesById: this.routesById,
205
+ flatRoutes: this.flatRoutes
206
+ });
207
+ };
208
+ this.cancelMatch = (id) => {
209
+ const match = this.getMatch(id);
210
+ if (!match) return;
211
+ match.abortController.abort();
212
+ clearTimeout(match.pendingTimeout);
213
+ };
214
+ this.cancelMatches = () => {
215
+ var _a;
216
+ (_a = this.state.pendingMatches) == null ? void 0 : _a.forEach((match) => {
217
+ this.cancelMatch(match.id);
218
+ });
219
+ };
220
+ this.buildLocation = (opts) => {
221
+ const build = (dest = {}, matchedRoutesResult) => {
222
+ var _a, _b, _c, _d, _e, _f, _g;
223
+ const fromMatches = dest._fromLocation ? this.matchRoutes(dest._fromLocation, { _buildLocation: true }) : this.state.matches;
224
+ const fromMatch = dest.from != null ? fromMatches.find(
225
+ (d) => matchPathname(this.basepath, trimPathRight(d.pathname), {
226
+ to: dest.from,
227
+ caseSensitive: false,
228
+ fuzzy: false
229
+ })
230
+ ) : void 0;
231
+ const fromPath = (fromMatch == null ? void 0 : fromMatch.pathname) || this.latestLocation.pathname;
232
+ invariant(
233
+ dest.from == null || fromMatch != null,
234
+ "Could not find match for from: " + dest.from
235
+ );
236
+ const fromSearch = ((_a = this.state.pendingMatches) == null ? void 0 : _a.length) ? (_b = last(this.state.pendingMatches)) == null ? void 0 : _b.search : ((_c = last(fromMatches)) == null ? void 0 : _c.search) || this.latestLocation.search;
237
+ const stayingMatches = matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.filter(
238
+ (d) => fromMatches.find((e) => e.routeId === d.id)
239
+ );
240
+ let pathname;
241
+ if (dest.to) {
242
+ const resolvePathTo = (fromMatch == null ? void 0 : fromMatch.fullPath) || ((_d = last(fromMatches)) == null ? void 0 : _d.fullPath) || this.latestLocation.pathname;
243
+ pathname = this.resolvePathWithBase(resolvePathTo, `${dest.to}`);
244
+ } else {
245
+ const fromRouteByFromPathRouteId = this.routesById[(_e = stayingMatches == null ? void 0 : stayingMatches.find((route) => {
246
+ const interpolatedPath = interpolatePath({
247
+ path: route.fullPath,
248
+ params: (matchedRoutesResult == null ? void 0 : matchedRoutesResult.routeParams) ?? {},
249
+ decodeCharMap: this.pathParamsDecodeCharMap
250
+ }).interpolatedPath;
251
+ const pathname2 = joinPaths([this.basepath, interpolatedPath]);
252
+ return pathname2 === fromPath;
253
+ })) == null ? void 0 : _e.id];
254
+ pathname = this.resolvePathWithBase(
255
+ fromPath,
256
+ (fromRouteByFromPathRouteId == null ? void 0 : fromRouteByFromPathRouteId.to) ?? fromPath
257
+ );
258
+ }
259
+ const prevParams = { ...(_f = last(fromMatches)) == null ? void 0 : _f.params };
260
+ let nextParams = (dest.params ?? true) === true ? prevParams : {
261
+ ...prevParams,
262
+ ...functionalUpdate(dest.params, prevParams)
263
+ };
264
+ if (Object.keys(nextParams).length > 0) {
265
+ matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.map((route) => {
266
+ var _a2;
267
+ return ((_a2 = route.options.params) == null ? void 0 : _a2.stringify) ?? route.options.stringifyParams;
268
+ }).filter(Boolean).forEach((fn) => {
269
+ nextParams = { ...nextParams, ...fn(nextParams) };
270
+ });
271
+ }
272
+ pathname = interpolatePath({
273
+ path: pathname,
274
+ params: nextParams ?? {},
275
+ leaveWildcards: false,
276
+ leaveParams: opts.leaveParams,
277
+ decodeCharMap: this.pathParamsDecodeCharMap
278
+ }).interpolatedPath;
279
+ let search = fromSearch;
280
+ if (opts._includeValidateSearch && ((_g = this.options.search) == null ? void 0 : _g.strict)) {
281
+ let validatedSearch = {};
282
+ matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.forEach((route) => {
283
+ try {
284
+ if (route.options.validateSearch) {
285
+ validatedSearch = {
286
+ ...validatedSearch,
287
+ ...validateSearch(route.options.validateSearch, {
288
+ ...validatedSearch,
289
+ ...search
290
+ }) ?? {}
291
+ };
292
+ }
293
+ } catch {
294
+ }
295
+ });
296
+ search = validatedSearch;
297
+ }
298
+ const applyMiddlewares = (search2) => {
299
+ const allMiddlewares = (matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.reduce(
300
+ (acc, route) => {
301
+ var _a2;
302
+ const middlewares = [];
303
+ if ("search" in route.options) {
304
+ if ((_a2 = route.options.search) == null ? void 0 : _a2.middlewares) {
305
+ middlewares.push(...route.options.search.middlewares);
306
+ }
307
+ } else if (route.options.preSearchFilters || route.options.postSearchFilters) {
308
+ const legacyMiddleware = ({
309
+ search: search3,
310
+ next
311
+ }) => {
312
+ let nextSearch = search3;
313
+ if ("preSearchFilters" in route.options && route.options.preSearchFilters) {
314
+ nextSearch = route.options.preSearchFilters.reduce(
315
+ (prev, next2) => next2(prev),
316
+ search3
317
+ );
318
+ }
319
+ const result = next(nextSearch);
320
+ if ("postSearchFilters" in route.options && route.options.postSearchFilters) {
321
+ return route.options.postSearchFilters.reduce(
322
+ (prev, next2) => next2(prev),
323
+ result
324
+ );
325
+ }
326
+ return result;
327
+ };
328
+ middlewares.push(legacyMiddleware);
329
+ }
330
+ if (opts._includeValidateSearch && route.options.validateSearch) {
331
+ const validate = ({ search: search3, next }) => {
332
+ const result = next(search3);
333
+ try {
334
+ const validatedSearch = {
335
+ ...result,
336
+ ...validateSearch(
337
+ route.options.validateSearch,
338
+ result
339
+ ) ?? {}
340
+ };
341
+ return validatedSearch;
342
+ } catch {
343
+ return result;
344
+ }
345
+ };
346
+ middlewares.push(validate);
347
+ }
348
+ return acc.concat(middlewares);
349
+ },
350
+ []
351
+ )) ?? [];
352
+ const final = ({ search: search3 }) => {
353
+ if (!dest.search) {
354
+ return {};
355
+ }
356
+ if (dest.search === true) {
357
+ return search3;
358
+ }
359
+ return functionalUpdate(dest.search, search3);
360
+ };
361
+ allMiddlewares.push(final);
362
+ const applyNext = (index, currentSearch) => {
363
+ if (index >= allMiddlewares.length) {
364
+ return currentSearch;
365
+ }
366
+ const middleware = allMiddlewares[index];
367
+ const next = (newSearch) => {
368
+ return applyNext(index + 1, newSearch);
369
+ };
370
+ return middleware({ search: currentSearch, next });
371
+ };
372
+ return applyNext(0, search2);
373
+ };
374
+ search = applyMiddlewares(search);
375
+ search = replaceEqualDeep(fromSearch, search);
376
+ const searchStr = this.options.stringifySearch(search);
377
+ const hash = dest.hash === true ? this.latestLocation.hash : dest.hash ? functionalUpdate(dest.hash, this.latestLocation.hash) : void 0;
378
+ const hashStr = hash ? `#${hash}` : "";
379
+ let nextState = dest.state === true ? this.latestLocation.state : dest.state ? functionalUpdate(dest.state, this.latestLocation.state) : {};
380
+ nextState = replaceEqualDeep(this.latestLocation.state, nextState);
381
+ return {
382
+ pathname,
383
+ search,
384
+ searchStr,
385
+ state: nextState,
386
+ hash: hash ?? "",
387
+ href: `${pathname}${searchStr}${hashStr}`,
388
+ unmaskOnReload: dest.unmaskOnReload
389
+ };
390
+ };
391
+ const buildWithMatches = (dest = {}, maskedDest) => {
392
+ var _a;
393
+ const next = build(dest);
394
+ let maskedNext = maskedDest ? build(maskedDest) : void 0;
395
+ if (!maskedNext) {
396
+ let params = {};
397
+ const foundMask = (_a = this.options.routeMasks) == null ? void 0 : _a.find((d) => {
398
+ const match = matchPathname(this.basepath, next.pathname, {
399
+ to: d.from,
400
+ caseSensitive: false,
401
+ fuzzy: false
402
+ });
403
+ if (match) {
404
+ params = match;
405
+ return true;
406
+ }
407
+ return false;
408
+ });
409
+ if (foundMask) {
410
+ const { from: _from, ...maskProps } = foundMask;
411
+ maskedDest = {
412
+ ...pick(opts, ["from"]),
413
+ ...maskProps,
414
+ params
415
+ };
416
+ maskedNext = build(maskedDest);
417
+ }
418
+ }
419
+ const nextMatches = this.getMatchedRoutes(
420
+ next.pathname,
421
+ dest.to
422
+ );
423
+ const final = build(dest, nextMatches);
424
+ if (maskedNext) {
425
+ const maskedMatches = this.getMatchedRoutes(
426
+ maskedNext.pathname,
427
+ maskedDest == null ? void 0 : maskedDest.to
428
+ );
429
+ const maskedFinal = build(maskedDest, maskedMatches);
430
+ final.maskedLocation = maskedFinal;
431
+ }
432
+ return final;
433
+ };
434
+ if (opts.mask) {
435
+ return buildWithMatches(opts, {
436
+ ...pick(opts, ["from"]),
437
+ ...opts.mask
438
+ });
439
+ }
440
+ return buildWithMatches(opts);
441
+ };
442
+ this.commitLocation = ({
443
+ viewTransition,
444
+ ignoreBlocker,
445
+ ...next
446
+ }) => {
447
+ const isSameState = () => {
448
+ const ignoredProps = [
449
+ "key",
450
+ "__TSR_index",
451
+ "__hashScrollIntoViewOptions"
452
+ ];
453
+ ignoredProps.forEach((prop) => {
454
+ next.state[prop] = this.latestLocation.state[prop];
455
+ });
456
+ const isEqual = deepEqual(next.state, this.latestLocation.state);
457
+ ignoredProps.forEach((prop) => {
458
+ delete next.state[prop];
459
+ });
460
+ return isEqual;
461
+ };
462
+ const isSameUrl = this.latestLocation.href === next.href;
463
+ const previousCommitPromise = this.commitLocationPromise;
464
+ this.commitLocationPromise = createControlledPromise(() => {
465
+ previousCommitPromise == null ? void 0 : previousCommitPromise.resolve();
466
+ });
467
+ if (isSameUrl && isSameState()) {
468
+ this.load();
469
+ } else {
470
+ let { maskedLocation, hashScrollIntoView, ...nextHistory } = next;
471
+ if (maskedLocation) {
472
+ nextHistory = {
473
+ ...maskedLocation,
474
+ state: {
475
+ ...maskedLocation.state,
476
+ __tempKey: void 0,
477
+ __tempLocation: {
478
+ ...nextHistory,
479
+ search: nextHistory.searchStr,
480
+ state: {
481
+ ...nextHistory.state,
482
+ __tempKey: void 0,
483
+ __tempLocation: void 0,
484
+ key: void 0
485
+ }
486
+ }
487
+ }
488
+ };
489
+ if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
490
+ nextHistory.state.__tempKey = this.tempLocationKey;
491
+ }
492
+ }
493
+ nextHistory.state.__hashScrollIntoViewOptions = hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true;
494
+ this.shouldViewTransition = viewTransition;
495
+ this.history[next.replace ? "replace" : "push"](
496
+ nextHistory.href,
497
+ nextHistory.state,
498
+ { ignoreBlocker }
499
+ );
500
+ }
501
+ this.resetNextScroll = next.resetScroll ?? true;
502
+ if (!this.history.subscribers.size) {
503
+ this.load();
504
+ }
505
+ return this.commitLocationPromise;
506
+ };
507
+ this.buildAndCommitLocation = ({
508
+ replace,
509
+ resetScroll,
510
+ hashScrollIntoView,
511
+ viewTransition,
512
+ ignoreBlocker,
513
+ href,
514
+ ...rest
515
+ } = {}) => {
516
+ if (href) {
517
+ const currentIndex = this.history.location.state.__TSR_index;
518
+ const parsed = parseHref(href, {
519
+ __TSR_index: replace ? currentIndex : currentIndex + 1
520
+ });
521
+ rest.to = parsed.pathname;
522
+ rest.search = this.options.parseSearch(parsed.search);
523
+ rest.hash = parsed.hash.slice(1);
524
+ }
525
+ const location = this.buildLocation({
526
+ ...rest,
527
+ _includeValidateSearch: true
528
+ });
529
+ return this.commitLocation({
530
+ ...location,
531
+ viewTransition,
532
+ replace,
533
+ resetScroll,
534
+ hashScrollIntoView,
535
+ ignoreBlocker
536
+ });
537
+ };
538
+ this.navigate = ({ to, reloadDocument, href, ...rest }) => {
539
+ if (!reloadDocument && href) {
540
+ try {
541
+ new URL(`${href}`);
542
+ reloadDocument = true;
543
+ } catch {
544
+ }
545
+ }
546
+ if (reloadDocument) {
547
+ if (!href) {
548
+ const location = this.buildLocation({ to, ...rest });
549
+ href = this.history.createHref(location.href);
550
+ }
551
+ if (rest.replace) {
552
+ window.location.replace(href);
553
+ } else {
554
+ window.location.href = href;
555
+ }
556
+ return;
557
+ }
558
+ return this.buildAndCommitLocation({
559
+ ...rest,
560
+ href,
561
+ to
562
+ });
563
+ };
564
+ this.beforeLoad = () => {
565
+ this.cancelMatches();
566
+ this.latestLocation = this.parseLocation(this.latestLocation);
567
+ const pendingMatches = this.matchRoutes(this.latestLocation);
568
+ this.__store.setState((s) => ({
569
+ ...s,
570
+ status: "pending",
571
+ isLoading: true,
572
+ location: this.latestLocation,
573
+ pendingMatches,
574
+ // If a cached moved to pendingMatches, remove it from cachedMatches
575
+ cachedMatches: s.cachedMatches.filter((d) => {
576
+ return !pendingMatches.find((e) => e.id === d.id);
577
+ })
578
+ }));
579
+ };
580
+ this.load = async (opts) => {
581
+ let redirect;
582
+ let notFound;
583
+ let loadPromise;
584
+ loadPromise = new Promise((resolve) => {
585
+ this.startTransition(async () => {
586
+ var _a;
587
+ try {
588
+ this.beforeLoad();
589
+ const next = this.latestLocation;
590
+ const prevLocation = this.state.resolvedLocation;
591
+ if (!this.state.redirect) {
592
+ this.emit({
593
+ type: "onBeforeNavigate",
594
+ ...getLocationChangeInfo({
595
+ resolvedLocation: prevLocation,
596
+ location: next
597
+ })
598
+ });
599
+ }
600
+ this.emit({
601
+ type: "onBeforeLoad",
602
+ ...getLocationChangeInfo({
603
+ resolvedLocation: prevLocation,
604
+ location: next
605
+ })
606
+ });
607
+ await this.loadMatches({
608
+ sync: opts == null ? void 0 : opts.sync,
609
+ matches: this.state.pendingMatches,
610
+ location: next,
611
+ // eslint-disable-next-line @typescript-eslint/require-await
612
+ onReady: async () => {
613
+ this.startViewTransition(async () => {
614
+ let exitingMatches;
615
+ let enteringMatches;
616
+ let stayingMatches;
617
+ batch(() => {
618
+ this.__store.setState((s) => {
619
+ const previousMatches = s.matches;
620
+ const newMatches = s.pendingMatches || s.matches;
621
+ exitingMatches = previousMatches.filter(
622
+ (match) => !newMatches.find((d) => d.id === match.id)
623
+ );
624
+ enteringMatches = newMatches.filter(
625
+ (match) => !previousMatches.find((d) => d.id === match.id)
626
+ );
627
+ stayingMatches = previousMatches.filter(
628
+ (match) => newMatches.find((d) => d.id === match.id)
629
+ );
630
+ return {
631
+ ...s,
632
+ isLoading: false,
633
+ loadedAt: Date.now(),
634
+ matches: newMatches,
635
+ pendingMatches: void 0,
636
+ cachedMatches: [
637
+ ...s.cachedMatches,
638
+ ...exitingMatches.filter((d) => d.status !== "error")
639
+ ]
640
+ };
641
+ });
642
+ this.clearExpiredCache();
643
+ });
644
+ [
645
+ [exitingMatches, "onLeave"],
646
+ [enteringMatches, "onEnter"],
647
+ [stayingMatches, "onStay"]
648
+ ].forEach(([matches, hook]) => {
649
+ matches.forEach((match) => {
650
+ var _a2, _b;
651
+ (_b = (_a2 = this.looseRoutesById[match.routeId].options)[hook]) == null ? void 0 : _b.call(_a2, match);
652
+ });
653
+ });
654
+ });
655
+ }
656
+ });
657
+ } catch (err) {
658
+ if (isRedirect(err)) {
659
+ redirect = err;
660
+ if (!this.isServer) {
661
+ this.navigate({
662
+ ...redirect.options,
663
+ replace: true,
664
+ ignoreBlocker: true
665
+ });
666
+ }
667
+ } else if (isNotFound(err)) {
668
+ notFound = err;
669
+ }
670
+ this.__store.setState((s) => ({
671
+ ...s,
672
+ statusCode: redirect ? redirect.status : notFound ? 404 : s.matches.some((d) => d.status === "error") ? 500 : 200,
673
+ redirect
674
+ }));
675
+ }
676
+ if (this.latestLoadPromise === loadPromise) {
677
+ (_a = this.commitLocationPromise) == null ? void 0 : _a.resolve();
678
+ this.latestLoadPromise = void 0;
679
+ this.commitLocationPromise = void 0;
680
+ }
681
+ resolve();
682
+ });
683
+ });
684
+ this.latestLoadPromise = loadPromise;
685
+ await loadPromise;
686
+ while (this.latestLoadPromise && loadPromise !== this.latestLoadPromise) {
687
+ await this.latestLoadPromise;
688
+ }
689
+ if (this.hasNotFoundMatch()) {
690
+ this.__store.setState((s) => ({
691
+ ...s,
692
+ statusCode: 404
693
+ }));
694
+ }
695
+ };
696
+ this.startViewTransition = (fn) => {
697
+ const shouldViewTransition = this.shouldViewTransition ?? this.options.defaultViewTransition;
698
+ delete this.shouldViewTransition;
699
+ if (shouldViewTransition && typeof document !== "undefined" && "startViewTransition" in document && typeof document.startViewTransition === "function") {
700
+ let startViewTransitionParams;
701
+ if (typeof shouldViewTransition === "object" && this.isViewTransitionTypesSupported) {
702
+ const next = this.latestLocation;
703
+ const prevLocation = this.state.resolvedLocation;
704
+ const resolvedViewTransitionTypes = typeof shouldViewTransition.types === "function" ? shouldViewTransition.types(
705
+ getLocationChangeInfo({
706
+ resolvedLocation: prevLocation,
707
+ location: next
708
+ })
709
+ ) : shouldViewTransition.types;
710
+ startViewTransitionParams = {
711
+ update: fn,
712
+ types: resolvedViewTransitionTypes
713
+ };
714
+ } else {
715
+ startViewTransitionParams = fn;
716
+ }
717
+ document.startViewTransition(startViewTransitionParams);
718
+ } else {
719
+ fn();
720
+ }
721
+ };
722
+ this.updateMatch = (id, updater) => {
723
+ var _a;
724
+ let updated;
725
+ const isPending = (_a = this.state.pendingMatches) == null ? void 0 : _a.find((d) => d.id === id);
726
+ const isMatched = this.state.matches.find((d) => d.id === id);
727
+ const isCached = this.state.cachedMatches.find((d) => d.id === id);
728
+ const matchesKey = isPending ? "pendingMatches" : isMatched ? "matches" : isCached ? "cachedMatches" : "";
729
+ if (matchesKey) {
730
+ this.__store.setState((s) => {
731
+ var _a2;
732
+ return {
733
+ ...s,
734
+ [matchesKey]: (_a2 = s[matchesKey]) == null ? void 0 : _a2.map(
735
+ (d) => d.id === id ? updated = updater(d) : d
736
+ )
737
+ };
738
+ });
739
+ }
740
+ return updated;
741
+ };
742
+ this.getMatch = (matchId) => {
743
+ return [
744
+ ...this.state.cachedMatches,
745
+ ...this.state.pendingMatches ?? [],
746
+ ...this.state.matches
747
+ ].find((d) => d.id === matchId);
748
+ };
749
+ this.loadMatches = async ({
750
+ location,
751
+ matches,
752
+ preload: allPreload,
753
+ onReady,
754
+ updateMatch = this.updateMatch,
755
+ sync
756
+ }) => {
757
+ let firstBadMatchIndex;
758
+ let rendered = false;
759
+ const triggerOnReady = async () => {
760
+ if (!rendered) {
761
+ rendered = true;
762
+ await (onReady == null ? void 0 : onReady());
763
+ }
764
+ };
765
+ const resolvePreload = (matchId) => {
766
+ return !!(allPreload && !this.state.matches.find((d) => d.id === matchId));
767
+ };
768
+ const handleRedirectAndNotFound = (match, err) => {
769
+ var _a, _b, _c, _d;
770
+ if (isRedirect(err) || isNotFound(err)) {
771
+ if (isRedirect(err)) {
772
+ if (err.redirectHandled) {
773
+ if (!err.options.reloadDocument) {
774
+ throw err;
775
+ }
776
+ }
777
+ }
778
+ updateMatch(match.id, (prev) => ({
779
+ ...prev,
780
+ status: isRedirect(err) ? "redirected" : isNotFound(err) ? "notFound" : "error",
781
+ isFetching: false,
782
+ error: err,
783
+ beforeLoadPromise: void 0,
784
+ loaderPromise: void 0
785
+ }));
786
+ if (!err.routeId) {
787
+ err.routeId = match.routeId;
788
+ }
789
+ (_a = match.beforeLoadPromise) == null ? void 0 : _a.resolve();
790
+ (_b = match.loaderPromise) == null ? void 0 : _b.resolve();
791
+ (_c = match.loadPromise) == null ? void 0 : _c.resolve();
792
+ if (isRedirect(err)) {
793
+ rendered = true;
794
+ err.options._fromLocation = location;
795
+ err.redirectHandled = true;
796
+ err = this.resolveRedirect(err);
797
+ throw err;
798
+ } else if (isNotFound(err)) {
799
+ this._handleNotFound(matches, err, {
800
+ updateMatch
801
+ });
802
+ (_d = this.serverSsr) == null ? void 0 : _d.onMatchSettled({
803
+ router: this,
804
+ match: this.getMatch(match.id)
805
+ });
806
+ throw err;
807
+ }
808
+ }
809
+ };
810
+ try {
811
+ await new Promise((resolveAll, rejectAll) => {
812
+ ;
813
+ (async () => {
814
+ var _a, _b, _c, _d;
815
+ try {
816
+ const handleSerialError = (index, err, routerCode) => {
817
+ var _a2, _b2;
818
+ const { id: matchId, routeId } = matches[index];
819
+ const route = this.looseRoutesById[routeId];
820
+ if (err instanceof Promise) {
821
+ throw err;
822
+ }
823
+ err.routerCode = routerCode;
824
+ firstBadMatchIndex = firstBadMatchIndex ?? index;
825
+ handleRedirectAndNotFound(this.getMatch(matchId), err);
826
+ try {
827
+ (_b2 = (_a2 = route.options).onError) == null ? void 0 : _b2.call(_a2, err);
828
+ } catch (errorHandlerErr) {
829
+ err = errorHandlerErr;
830
+ handleRedirectAndNotFound(this.getMatch(matchId), err);
831
+ }
832
+ updateMatch(matchId, (prev) => {
833
+ var _a3, _b3;
834
+ (_a3 = prev.beforeLoadPromise) == null ? void 0 : _a3.resolve();
835
+ (_b3 = prev.loadPromise) == null ? void 0 : _b3.resolve();
836
+ return {
837
+ ...prev,
838
+ error: err,
839
+ status: "error",
840
+ isFetching: false,
841
+ updatedAt: Date.now(),
842
+ abortController: new AbortController(),
843
+ beforeLoadPromise: void 0
844
+ };
845
+ });
846
+ };
847
+ for (const [index, { id: matchId, routeId }] of matches.entries()) {
848
+ const existingMatch = this.getMatch(matchId);
849
+ const parentMatchId = (_a = matches[index - 1]) == null ? void 0 : _a.id;
850
+ const route = this.looseRoutesById[routeId];
851
+ const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
852
+ const shouldPending = !!(onReady && !this.isServer && !resolvePreload(matchId) && (route.options.loader || route.options.beforeLoad || routeNeedsPreload(route)) && typeof pendingMs === "number" && pendingMs !== Infinity && (route.options.pendingComponent ?? ((_b = this.options) == null ? void 0 : _b.defaultPendingComponent)));
853
+ let executeBeforeLoad = true;
854
+ if (
855
+ // If we are in the middle of a load, either of these will be present
856
+ // (not to be confused with `loadPromise`, which is always defined)
857
+ existingMatch.beforeLoadPromise || existingMatch.loaderPromise
858
+ ) {
859
+ if (shouldPending) {
860
+ setTimeout(() => {
861
+ try {
862
+ triggerOnReady();
863
+ } catch {
864
+ }
865
+ }, pendingMs);
866
+ }
867
+ await existingMatch.beforeLoadPromise;
868
+ executeBeforeLoad = this.getMatch(matchId).status !== "success";
869
+ }
870
+ if (executeBeforeLoad) {
871
+ try {
872
+ updateMatch(matchId, (prev) => {
873
+ const prevLoadPromise = prev.loadPromise;
874
+ return {
875
+ ...prev,
876
+ loadPromise: createControlledPromise(() => {
877
+ prevLoadPromise == null ? void 0 : prevLoadPromise.resolve();
878
+ }),
879
+ beforeLoadPromise: createControlledPromise()
880
+ };
881
+ });
882
+ const abortController = new AbortController();
883
+ let pendingTimeout;
884
+ if (shouldPending) {
885
+ pendingTimeout = setTimeout(() => {
886
+ try {
887
+ triggerOnReady();
888
+ } catch {
889
+ }
890
+ }, pendingMs);
891
+ }
892
+ const { paramsError, searchError } = this.getMatch(matchId);
893
+ if (paramsError) {
894
+ handleSerialError(index, paramsError, "PARSE_PARAMS");
895
+ }
896
+ if (searchError) {
897
+ handleSerialError(index, searchError, "VALIDATE_SEARCH");
898
+ }
899
+ const getParentMatchContext = () => parentMatchId ? this.getMatch(parentMatchId).context : this.options.context ?? {};
900
+ updateMatch(matchId, (prev) => ({
901
+ ...prev,
902
+ isFetching: "beforeLoad",
903
+ fetchCount: prev.fetchCount + 1,
904
+ abortController,
905
+ pendingTimeout,
906
+ context: {
907
+ ...getParentMatchContext(),
908
+ ...prev.__routeContext
909
+ }
910
+ }));
911
+ const { search, params, context, cause } = this.getMatch(matchId);
912
+ const preload = resolvePreload(matchId);
913
+ const beforeLoadFnContext = {
914
+ search,
915
+ abortController,
916
+ params,
917
+ preload,
918
+ context,
919
+ location,
920
+ navigate: (opts) => this.navigate({ ...opts, _fromLocation: location }),
921
+ buildLocation: this.buildLocation,
922
+ cause: preload ? "preload" : cause,
923
+ matches
924
+ };
925
+ const beforeLoadContext = await ((_d = (_c = route.options).beforeLoad) == null ? void 0 : _d.call(_c, beforeLoadFnContext)) ?? {};
926
+ if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) {
927
+ handleSerialError(index, beforeLoadContext, "BEFORE_LOAD");
928
+ }
929
+ updateMatch(matchId, (prev) => {
930
+ return {
931
+ ...prev,
932
+ __beforeLoadContext: beforeLoadContext,
933
+ context: {
934
+ ...getParentMatchContext(),
935
+ ...prev.__routeContext,
936
+ ...beforeLoadContext
937
+ },
938
+ abortController
939
+ };
940
+ });
941
+ } catch (err) {
942
+ handleSerialError(index, err, "BEFORE_LOAD");
943
+ }
944
+ updateMatch(matchId, (prev) => {
945
+ var _a2;
946
+ (_a2 = prev.beforeLoadPromise) == null ? void 0 : _a2.resolve();
947
+ return {
948
+ ...prev,
949
+ beforeLoadPromise: void 0,
950
+ isFetching: false
951
+ };
952
+ });
953
+ }
954
+ }
955
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
956
+ const matchPromises = [];
957
+ validResolvedMatches.forEach(({ id: matchId, routeId }, index) => {
958
+ matchPromises.push(
959
+ (async () => {
960
+ const { loaderPromise: prevLoaderPromise } = this.getMatch(matchId);
961
+ let loaderShouldRunAsync = false;
962
+ let loaderIsRunningAsync = false;
963
+ if (prevLoaderPromise) {
964
+ await prevLoaderPromise;
965
+ const match = this.getMatch(matchId);
966
+ if (match.error) {
967
+ handleRedirectAndNotFound(match, match.error);
968
+ }
969
+ } else {
970
+ const parentMatchPromise = matchPromises[index - 1];
971
+ const route = this.looseRoutesById[routeId];
972
+ const getLoaderContext = () => {
973
+ const {
974
+ params,
975
+ loaderDeps,
976
+ abortController,
977
+ context,
978
+ cause
979
+ } = this.getMatch(matchId);
980
+ const preload2 = resolvePreload(matchId);
981
+ return {
982
+ params,
983
+ deps: loaderDeps,
984
+ preload: !!preload2,
985
+ parentMatchPromise,
986
+ abortController,
987
+ context,
988
+ location,
989
+ navigate: (opts) => this.navigate({ ...opts, _fromLocation: location }),
990
+ cause: preload2 ? "preload" : cause,
991
+ route
992
+ };
993
+ };
994
+ const age = Date.now() - this.getMatch(matchId).updatedAt;
995
+ const preload = resolvePreload(matchId);
996
+ const staleAge = preload ? route.options.preloadStaleTime ?? this.options.defaultPreloadStaleTime ?? 3e4 : route.options.staleTime ?? this.options.defaultStaleTime ?? 0;
997
+ const shouldReloadOption = route.options.shouldReload;
998
+ const shouldReload = typeof shouldReloadOption === "function" ? shouldReloadOption(getLoaderContext()) : shouldReloadOption;
999
+ updateMatch(matchId, (prev) => ({
1000
+ ...prev,
1001
+ loaderPromise: createControlledPromise(),
1002
+ preload: !!preload && !this.state.matches.find((d) => d.id === matchId)
1003
+ }));
1004
+ const runLoader = async () => {
1005
+ var _a2, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k;
1006
+ try {
1007
+ const potentialPendingMinPromise = async () => {
1008
+ const latestMatch = this.getMatch(matchId);
1009
+ if (latestMatch.minPendingPromise) {
1010
+ await latestMatch.minPendingPromise;
1011
+ }
1012
+ };
1013
+ try {
1014
+ this.loadRouteChunk(route);
1015
+ updateMatch(matchId, (prev) => ({
1016
+ ...prev,
1017
+ isFetching: "loader"
1018
+ }));
1019
+ const loaderData = await ((_b2 = (_a2 = route.options).loader) == null ? void 0 : _b2.call(_a2, getLoaderContext()));
1020
+ handleRedirectAndNotFound(
1021
+ this.getMatch(matchId),
1022
+ loaderData
1023
+ );
1024
+ await route._lazyPromise;
1025
+ await potentialPendingMinPromise();
1026
+ const assetContext = {
1027
+ matches,
1028
+ match: this.getMatch(matchId),
1029
+ params: this.getMatch(matchId).params,
1030
+ loaderData
1031
+ };
1032
+ const headFnContent = (_d2 = (_c2 = route.options).head) == null ? void 0 : _d2.call(_c2, assetContext);
1033
+ const meta = headFnContent == null ? void 0 : headFnContent.meta;
1034
+ const links = headFnContent == null ? void 0 : headFnContent.links;
1035
+ const headScripts = headFnContent == null ? void 0 : headFnContent.scripts;
1036
+ const scripts = (_f = (_e = route.options).scripts) == null ? void 0 : _f.call(_e, assetContext);
1037
+ const headers = (_h = (_g = route.options).headers) == null ? void 0 : _h.call(_g, {
1038
+ loaderData
1039
+ });
1040
+ await route._componentsPromise;
1041
+ updateMatch(matchId, (prev) => ({
1042
+ ...prev,
1043
+ error: void 0,
1044
+ status: "success",
1045
+ isFetching: false,
1046
+ updatedAt: Date.now(),
1047
+ loaderData,
1048
+ meta,
1049
+ links,
1050
+ headScripts,
1051
+ headers,
1052
+ scripts
1053
+ }));
1054
+ } catch (e) {
1055
+ let error = e;
1056
+ await potentialPendingMinPromise();
1057
+ handleRedirectAndNotFound(this.getMatch(matchId), e);
1058
+ try {
1059
+ (_j = (_i = route.options).onError) == null ? void 0 : _j.call(_i, e);
1060
+ } catch (onErrorError) {
1061
+ error = onErrorError;
1062
+ handleRedirectAndNotFound(
1063
+ this.getMatch(matchId),
1064
+ onErrorError
1065
+ );
1066
+ }
1067
+ updateMatch(matchId, (prev) => ({
1068
+ ...prev,
1069
+ error,
1070
+ status: "error",
1071
+ isFetching: false
1072
+ }));
1073
+ }
1074
+ (_k = this.serverSsr) == null ? void 0 : _k.onMatchSettled({
1075
+ router: this,
1076
+ match: this.getMatch(matchId)
1077
+ });
1078
+ } catch (err) {
1079
+ updateMatch(matchId, (prev) => ({
1080
+ ...prev,
1081
+ loaderPromise: void 0
1082
+ }));
1083
+ handleRedirectAndNotFound(this.getMatch(matchId), err);
1084
+ }
1085
+ };
1086
+ const { status, invalid } = this.getMatch(matchId);
1087
+ loaderShouldRunAsync = status === "success" && (invalid || (shouldReload ?? age > staleAge));
1088
+ if (preload && route.options.preload === false) {
1089
+ } else if (loaderShouldRunAsync && !sync) {
1090
+ loaderIsRunningAsync = true;
1091
+ (async () => {
1092
+ try {
1093
+ await runLoader();
1094
+ const { loaderPromise, loadPromise } = this.getMatch(matchId);
1095
+ loaderPromise == null ? void 0 : loaderPromise.resolve();
1096
+ loadPromise == null ? void 0 : loadPromise.resolve();
1097
+ updateMatch(matchId, (prev) => ({
1098
+ ...prev,
1099
+ loaderPromise: void 0
1100
+ }));
1101
+ } catch (err) {
1102
+ if (isRedirect(err)) {
1103
+ await this.navigate(err.options);
1104
+ }
1105
+ }
1106
+ })();
1107
+ } else if (status !== "success" || loaderShouldRunAsync && sync) {
1108
+ await runLoader();
1109
+ }
1110
+ }
1111
+ if (!loaderIsRunningAsync) {
1112
+ const { loaderPromise, loadPromise } = this.getMatch(matchId);
1113
+ loaderPromise == null ? void 0 : loaderPromise.resolve();
1114
+ loadPromise == null ? void 0 : loadPromise.resolve();
1115
+ }
1116
+ updateMatch(matchId, (prev) => ({
1117
+ ...prev,
1118
+ isFetching: loaderIsRunningAsync ? prev.isFetching : false,
1119
+ loaderPromise: loaderIsRunningAsync ? prev.loaderPromise : void 0,
1120
+ invalid: false
1121
+ }));
1122
+ return this.getMatch(matchId);
1123
+ })()
1124
+ );
1125
+ });
1126
+ await Promise.all(matchPromises);
1127
+ resolveAll();
1128
+ } catch (err) {
1129
+ rejectAll(err);
1130
+ }
1131
+ })();
1132
+ });
1133
+ await triggerOnReady();
1134
+ } catch (err) {
1135
+ if (isRedirect(err) || isNotFound(err)) {
1136
+ if (isNotFound(err) && !allPreload) {
1137
+ await triggerOnReady();
1138
+ }
1139
+ throw err;
1140
+ }
1141
+ }
1142
+ return matches;
1143
+ };
1144
+ this.invalidate = (opts) => {
1145
+ const invalidate = (d) => {
1146
+ var _a;
1147
+ if (((_a = opts == null ? void 0 : opts.filter) == null ? void 0 : _a.call(opts, d)) ?? true) {
1148
+ return {
1149
+ ...d,
1150
+ invalid: true,
1151
+ ...d.status === "error" ? { status: "pending", error: void 0 } : {}
1152
+ };
1153
+ }
1154
+ return d;
1155
+ };
1156
+ this.__store.setState((s) => {
1157
+ var _a;
1158
+ return {
1159
+ ...s,
1160
+ matches: s.matches.map(invalidate),
1161
+ cachedMatches: s.cachedMatches.map(invalidate),
1162
+ pendingMatches: (_a = s.pendingMatches) == null ? void 0 : _a.map(invalidate)
1163
+ };
1164
+ });
1165
+ return this.load({ sync: opts == null ? void 0 : opts.sync });
1166
+ };
1167
+ this.resolveRedirect = (redirect) => {
1168
+ if (!redirect.options.href) {
1169
+ redirect.options.href = this.buildLocation(redirect.options).href;
1170
+ redirect.headers.set("Location", redirect.options.href);
1171
+ }
1172
+ if (!redirect.headers.get("Location")) {
1173
+ redirect.headers.set("Location", redirect.options.href);
1174
+ }
1175
+ return redirect;
1176
+ };
1177
+ this.clearCache = (opts) => {
1178
+ const filter = opts == null ? void 0 : opts.filter;
1179
+ if (filter !== void 0) {
1180
+ this.__store.setState((s) => {
1181
+ return {
1182
+ ...s,
1183
+ cachedMatches: s.cachedMatches.filter(
1184
+ (m) => !filter(m)
1185
+ )
1186
+ };
1187
+ });
1188
+ } else {
1189
+ this.__store.setState((s) => {
1190
+ return {
1191
+ ...s,
1192
+ cachedMatches: []
1193
+ };
1194
+ });
1195
+ }
1196
+ };
1197
+ this.clearExpiredCache = () => {
1198
+ const filter = (d) => {
1199
+ const route = this.looseRoutesById[d.routeId];
1200
+ if (!route.options.loader) {
1201
+ return true;
1202
+ }
1203
+ const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 5 * 60 * 1e3;
1204
+ return !(d.status !== "error" && Date.now() - d.updatedAt < gcTime);
1205
+ };
1206
+ this.clearCache({ filter });
1207
+ };
1208
+ this.loadRouteChunk = (route) => {
1209
+ if (route._lazyPromise === void 0) {
1210
+ if (route.lazyFn) {
1211
+ route._lazyPromise = route.lazyFn().then((lazyRoute) => {
1212
+ const { id: _id, ...options2 } = lazyRoute.options;
1213
+ Object.assign(route.options, options2);
1214
+ });
1215
+ } else {
1216
+ route._lazyPromise = Promise.resolve();
1217
+ }
1218
+ }
1219
+ if (route._componentsPromise === void 0) {
1220
+ route._componentsPromise = route._lazyPromise.then(
1221
+ () => Promise.all(
1222
+ componentTypes.map(async (type) => {
1223
+ const component = route.options[type];
1224
+ if (component == null ? void 0 : component.preload) {
1225
+ await component.preload();
1226
+ }
1227
+ })
1228
+ )
1229
+ );
1230
+ }
1231
+ return route._componentsPromise;
1232
+ };
1233
+ this.preloadRoute = async (opts) => {
1234
+ const next = this.buildLocation(opts);
1235
+ let matches = this.matchRoutes(next, {
1236
+ throwOnError: true,
1237
+ preload: true,
1238
+ dest: opts
1239
+ });
1240
+ const activeMatchIds = new Set(
1241
+ [...this.state.matches, ...this.state.pendingMatches ?? []].map(
1242
+ (d) => d.id
1243
+ )
1244
+ );
1245
+ const loadedMatchIds = /* @__PURE__ */ new Set([
1246
+ ...activeMatchIds,
1247
+ ...this.state.cachedMatches.map((d) => d.id)
1248
+ ]);
1249
+ batch(() => {
1250
+ matches.forEach((match) => {
1251
+ if (!loadedMatchIds.has(match.id)) {
1252
+ this.__store.setState((s) => ({
1253
+ ...s,
1254
+ cachedMatches: [...s.cachedMatches, match]
1255
+ }));
1256
+ }
1257
+ });
1258
+ });
1259
+ try {
1260
+ matches = await this.loadMatches({
1261
+ matches,
1262
+ location: next,
1263
+ preload: true,
1264
+ updateMatch: (id, updater) => {
1265
+ if (activeMatchIds.has(id)) {
1266
+ matches = matches.map((d) => d.id === id ? updater(d) : d);
1267
+ } else {
1268
+ this.updateMatch(id, updater);
1269
+ }
1270
+ }
1271
+ });
1272
+ return matches;
1273
+ } catch (err) {
1274
+ if (isRedirect(err)) {
1275
+ if (err.options.reloadDocument) {
1276
+ return void 0;
1277
+ }
1278
+ return await this.preloadRoute({
1279
+ ...err.options,
1280
+ _fromLocation: next
1281
+ });
1282
+ }
1283
+ if (!isNotFound(err)) {
1284
+ console.error(err);
1285
+ }
1286
+ return void 0;
1287
+ }
1288
+ };
1289
+ this.matchRoute = (location, opts) => {
1290
+ const matchLocation = {
1291
+ ...location,
1292
+ to: location.to ? this.resolvePathWithBase(
1293
+ location.from || "",
1294
+ location.to
1295
+ ) : void 0,
1296
+ params: location.params || {},
1297
+ leaveParams: true
1298
+ };
1299
+ const next = this.buildLocation(matchLocation);
1300
+ if ((opts == null ? void 0 : opts.pending) && this.state.status !== "pending") {
1301
+ return false;
1302
+ }
1303
+ const pending = (opts == null ? void 0 : opts.pending) === void 0 ? !this.state.isLoading : opts.pending;
1304
+ const baseLocation = pending ? this.latestLocation : this.state.resolvedLocation || this.state.location;
1305
+ const match = matchPathname(this.basepath, baseLocation.pathname, {
1306
+ ...opts,
1307
+ to: next.pathname
1308
+ });
1309
+ if (!match) {
1310
+ return false;
1311
+ }
1312
+ if (location.params) {
1313
+ if (!deepEqual(match, location.params, { partial: true })) {
1314
+ return false;
1315
+ }
1316
+ }
1317
+ if (match && ((opts == null ? void 0 : opts.includeSearch) ?? true)) {
1318
+ return deepEqual(baseLocation.search, next.search, { partial: true }) ? match : false;
1319
+ }
1320
+ return match;
1321
+ };
1322
+ this._handleNotFound = (matches, err, {
1323
+ updateMatch = this.updateMatch
1324
+ } = {}) => {
1325
+ var _a;
1326
+ const routeCursor = this.routesById[err.routeId ?? ""] ?? this.routeTree;
1327
+ const matchesByRouteId = {};
1328
+ for (const match of matches) {
1329
+ matchesByRouteId[match.routeId] = match;
1330
+ }
1331
+ if (!routeCursor.options.notFoundComponent && ((_a = this.options) == null ? void 0 : _a.defaultNotFoundComponent)) {
1332
+ routeCursor.options.notFoundComponent = this.options.defaultNotFoundComponent;
1333
+ }
1334
+ invariant(
1335
+ routeCursor.options.notFoundComponent,
1336
+ "No notFoundComponent found. Please set a notFoundComponent on your route or provide a defaultNotFoundComponent to the router."
1337
+ );
1338
+ const matchForRoute = matchesByRouteId[routeCursor.id];
1339
+ invariant(
1340
+ matchForRoute,
1341
+ "Could not find match for route: " + routeCursor.id
1342
+ );
1343
+ updateMatch(matchForRoute.id, (prev) => ({
1344
+ ...prev,
1345
+ status: "notFound",
1346
+ error: err,
1347
+ isFetching: false
1348
+ }));
1349
+ if (err.routerCode === "BEFORE_LOAD" && routeCursor.parentRoute) {
1350
+ err.routeId = routeCursor.parentRoute.id;
1351
+ this._handleNotFound(matches, err, {
1352
+ updateMatch
1353
+ });
1354
+ }
1355
+ };
1356
+ this.hasNotFoundMatch = () => {
1357
+ return this.__store.state.matches.some(
1358
+ (d) => d.status === "notFound" || d.globalNotFound
1359
+ );
1360
+ };
1361
+ this.update({
1362
+ defaultPreloadDelay: 50,
1363
+ defaultPendingMs: 1e3,
1364
+ defaultPendingMinMs: 500,
1365
+ context: void 0,
1366
+ ...options,
1367
+ caseSensitive: options.caseSensitive ?? false,
1368
+ notFoundMode: options.notFoundMode ?? "fuzzy",
1369
+ stringifySearch: options.stringifySearch ?? defaultStringifySearch,
1370
+ parseSearch: options.parseSearch ?? defaultParseSearch
1371
+ });
1372
+ if (typeof document !== "undefined") {
1373
+ window.__TSR_ROUTER__ = this;
1374
+ }
1375
+ }
1376
+ get state() {
1377
+ return this.__store.state;
1378
+ }
1379
+ get looseRoutesById() {
1380
+ return this.routesById;
1381
+ }
1382
+ matchRoutesInternal(next, opts) {
1383
+ var _a;
1384
+ const { foundRoute, matchedRoutes, routeParams } = this.getMatchedRoutes(
1385
+ next.pathname,
1386
+ (_a = opts == null ? void 0 : opts.dest) == null ? void 0 : _a.to
1387
+ );
1388
+ let isGlobalNotFound = false;
1389
+ if (
1390
+ // If we found a route, and it's not an index route and we have left over path
1391
+ foundRoute ? foundRoute.path !== "/" && routeParams["**"] : (
1392
+ // Or if we didn't find a route and we have left over path
1393
+ trimPathRight(next.pathname)
1394
+ )
1395
+ ) {
1396
+ if (this.options.notFoundRoute) {
1397
+ matchedRoutes.push(this.options.notFoundRoute);
1398
+ } else {
1399
+ isGlobalNotFound = true;
1400
+ }
1401
+ }
1402
+ const globalNotFoundRouteId = (() => {
1403
+ if (!isGlobalNotFound) {
1404
+ return void 0;
1405
+ }
1406
+ if (this.options.notFoundMode !== "root") {
1407
+ for (let i = matchedRoutes.length - 1; i >= 0; i--) {
1408
+ const route = matchedRoutes[i];
1409
+ if (route.children) {
1410
+ return route.id;
1411
+ }
1412
+ }
1413
+ }
1414
+ return rootRouteId;
1415
+ })();
1416
+ const parseErrors = matchedRoutes.map((route) => {
1417
+ var _a2;
1418
+ let parsedParamsError;
1419
+ const parseParams = ((_a2 = route.options.params) == null ? void 0 : _a2.parse) ?? route.options.parseParams;
1420
+ if (parseParams) {
1421
+ try {
1422
+ const parsedParams = parseParams(routeParams);
1423
+ Object.assign(routeParams, parsedParams);
1424
+ } catch (err) {
1425
+ parsedParamsError = new PathParamError(err.message, {
1426
+ cause: err
1427
+ });
1428
+ if (opts == null ? void 0 : opts.throwOnError) {
1429
+ throw parsedParamsError;
1430
+ }
1431
+ return parsedParamsError;
1432
+ }
1433
+ }
1434
+ return;
1435
+ });
1436
+ const matches = [];
1437
+ const getParentContext = (parentMatch) => {
1438
+ const parentMatchId = parentMatch == null ? void 0 : parentMatch.id;
1439
+ const parentContext = !parentMatchId ? this.options.context ?? {} : parentMatch.context ?? this.options.context ?? {};
1440
+ return parentContext;
1441
+ };
1442
+ matchedRoutes.forEach((route, index) => {
1443
+ var _a2, _b;
1444
+ const parentMatch = matches[index - 1];
1445
+ const [preMatchSearch, strictMatchSearch, searchError] = (() => {
1446
+ const parentSearch = (parentMatch == null ? void 0 : parentMatch.search) ?? next.search;
1447
+ const parentStrictSearch = (parentMatch == null ? void 0 : parentMatch._strictSearch) ?? {};
1448
+ try {
1449
+ const strictSearch = validateSearch(route.options.validateSearch, { ...parentSearch }) ?? {};
1450
+ return [
1451
+ {
1452
+ ...parentSearch,
1453
+ ...strictSearch
1454
+ },
1455
+ { ...parentStrictSearch, ...strictSearch },
1456
+ void 0
1457
+ ];
1458
+ } catch (err) {
1459
+ let searchParamError = err;
1460
+ if (!(err instanceof SearchParamError)) {
1461
+ searchParamError = new SearchParamError(err.message, {
1462
+ cause: err
1463
+ });
1464
+ }
1465
+ if (opts == null ? void 0 : opts.throwOnError) {
1466
+ throw searchParamError;
1467
+ }
1468
+ return [parentSearch, {}, searchParamError];
1469
+ }
1470
+ })();
1471
+ const loaderDeps = ((_b = (_a2 = route.options).loaderDeps) == null ? void 0 : _b.call(_a2, {
1472
+ search: preMatchSearch
1473
+ })) ?? "";
1474
+ const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : "";
1475
+ const { usedParams, interpolatedPath } = interpolatePath({
1476
+ path: route.fullPath,
1477
+ params: routeParams,
1478
+ decodeCharMap: this.pathParamsDecodeCharMap
1479
+ });
1480
+ const matchId = interpolatePath({
1481
+ path: route.id,
1482
+ params: routeParams,
1483
+ leaveWildcards: true,
1484
+ decodeCharMap: this.pathParamsDecodeCharMap
1485
+ }).interpolatedPath + loaderDepsHash;
1486
+ const existingMatch = this.getMatch(matchId);
1487
+ const previousMatch = this.state.matches.find(
1488
+ (d) => d.routeId === route.id
1489
+ );
1490
+ const cause = previousMatch ? "stay" : "enter";
1491
+ let match;
1492
+ if (existingMatch) {
1493
+ match = {
1494
+ ...existingMatch,
1495
+ cause,
1496
+ params: previousMatch ? replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
1497
+ _strictParams: usedParams,
1498
+ search: previousMatch ? replaceEqualDeep(previousMatch.search, preMatchSearch) : replaceEqualDeep(existingMatch.search, preMatchSearch),
1499
+ _strictSearch: strictMatchSearch
1500
+ };
1501
+ } else {
1502
+ const status = route.options.loader || route.options.beforeLoad || route.lazyFn || routeNeedsPreload(route) ? "pending" : "success";
1503
+ match = {
1504
+ id: matchId,
1505
+ index,
1506
+ routeId: route.id,
1507
+ params: previousMatch ? replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
1508
+ _strictParams: usedParams,
1509
+ pathname: joinPaths([this.basepath, interpolatedPath]),
1510
+ updatedAt: Date.now(),
1511
+ search: previousMatch ? replaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch,
1512
+ _strictSearch: strictMatchSearch,
1513
+ searchError: void 0,
1514
+ status,
1515
+ isFetching: false,
1516
+ error: void 0,
1517
+ paramsError: parseErrors[index],
1518
+ __routeContext: {},
1519
+ __beforeLoadContext: {},
1520
+ context: {},
1521
+ abortController: new AbortController(),
1522
+ fetchCount: 0,
1523
+ cause,
1524
+ loaderDeps: previousMatch ? replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) : loaderDeps,
1525
+ invalid: false,
1526
+ preload: false,
1527
+ links: void 0,
1528
+ scripts: void 0,
1529
+ headScripts: void 0,
1530
+ meta: void 0,
1531
+ staticData: route.options.staticData || {},
1532
+ loadPromise: createControlledPromise(),
1533
+ fullPath: route.fullPath
1534
+ };
1535
+ }
1536
+ if (!(opts == null ? void 0 : opts.preload)) {
1537
+ match.globalNotFound = globalNotFoundRouteId === route.id;
1538
+ }
1539
+ match.searchError = searchError;
1540
+ const parentContext = getParentContext(parentMatch);
1541
+ match.context = {
1542
+ ...parentContext,
1543
+ ...match.__routeContext,
1544
+ ...match.__beforeLoadContext
1545
+ };
1546
+ matches.push(match);
1547
+ });
1548
+ matches.forEach((match, index) => {
1549
+ var _a2, _b, _c, _d, _e, _f, _g, _h;
1550
+ const route = this.looseRoutesById[match.routeId];
1551
+ const existingMatch = this.getMatch(match.id);
1552
+ if (!existingMatch && (opts == null ? void 0 : opts._buildLocation) !== true) {
1553
+ const parentMatch = matches[index - 1];
1554
+ const parentContext = getParentContext(parentMatch);
1555
+ const contextFnContext = {
1556
+ deps: match.loaderDeps,
1557
+ params: match.params,
1558
+ context: parentContext,
1559
+ location: next,
1560
+ navigate: (opts2) => this.navigate({ ...opts2, _fromLocation: next }),
1561
+ buildLocation: this.buildLocation,
1562
+ cause: match.cause,
1563
+ abortController: match.abortController,
1564
+ preload: !!match.preload,
1565
+ matches
1566
+ };
1567
+ match.__routeContext = ((_b = (_a2 = route.options).context) == null ? void 0 : _b.call(_a2, contextFnContext)) ?? {};
1568
+ match.context = {
1569
+ ...parentContext,
1570
+ ...match.__routeContext,
1571
+ ...match.__beforeLoadContext
1572
+ };
1573
+ }
1574
+ if (match.status === "success") {
1575
+ match.headers = (_d = (_c = route.options).headers) == null ? void 0 : _d.call(_c, {
1576
+ loaderData: match.loaderData
1577
+ });
1578
+ const assetContext = {
1579
+ matches,
1580
+ match,
1581
+ params: match.params,
1582
+ loaderData: match.loaderData
1583
+ };
1584
+ const headFnContent = (_f = (_e = route.options).head) == null ? void 0 : _f.call(_e, assetContext);
1585
+ match.links = headFnContent == null ? void 0 : headFnContent.links;
1586
+ match.headScripts = headFnContent == null ? void 0 : headFnContent.scripts;
1587
+ match.meta = headFnContent == null ? void 0 : headFnContent.meta;
1588
+ match.scripts = (_h = (_g = route.options).scripts) == null ? void 0 : _h.call(_g, assetContext);
1589
+ }
1590
+ });
1591
+ return matches;
1592
+ }
1593
+ }
1594
+ class SearchParamError extends Error {
1595
+ }
1596
+ class PathParamError extends Error {
1597
+ }
1598
+ function lazyFn(fn, key) {
1599
+ return async (...args) => {
1600
+ const imported = await fn();
1601
+ return imported[key || "default"](...args);
1602
+ };
1603
+ }
1604
+ function getInitialRouterState(location) {
1605
+ return {
1606
+ loadedAt: 0,
1607
+ isLoading: false,
1608
+ isTransitioning: false,
1609
+ status: "idle",
1610
+ resolvedLocation: void 0,
1611
+ location,
1612
+ matches: [],
1613
+ pendingMatches: [],
1614
+ cachedMatches: [],
1615
+ statusCode: 200
1616
+ };
1617
+ }
1618
+ function validateSearch(validateSearch2, input) {
1619
+ if (validateSearch2 == null) return {};
1620
+ if ("~standard" in validateSearch2) {
1621
+ const result = validateSearch2["~standard"].validate(input);
1622
+ if (result instanceof Promise)
1623
+ throw new SearchParamError("Async validation not supported");
1624
+ if (result.issues)
1625
+ throw new SearchParamError(JSON.stringify(result.issues, void 0, 2), {
1626
+ cause: result
1627
+ });
1628
+ return result.value;
1629
+ }
1630
+ if ("parse" in validateSearch2) {
1631
+ return validateSearch2.parse(input);
1632
+ }
1633
+ if (typeof validateSearch2 === "function") {
1634
+ return validateSearch2(input);
1635
+ }
1636
+ return {};
1637
+ }
1638
+ const componentTypes = [
1639
+ "component",
1640
+ "errorComponent",
1641
+ "pendingComponent",
1642
+ "notFoundComponent"
1643
+ ];
1644
+ function routeNeedsPreload(route) {
1645
+ var _a;
1646
+ for (const componentType of componentTypes) {
1647
+ if ((_a = route.options[componentType]) == null ? void 0 : _a.preload) {
1648
+ return true;
1649
+ }
1650
+ }
1651
+ return false;
1652
+ }
1653
+ function processRouteTree({
1654
+ routeTree,
1655
+ initRoute
1656
+ }) {
1657
+ const routesById = {};
1658
+ const routesByPath = {};
1659
+ const recurseRoutes = (childRoutes) => {
1660
+ childRoutes.forEach((childRoute, i) => {
1661
+ initRoute == null ? void 0 : initRoute(childRoute, i);
1662
+ const existingRoute = routesById[childRoute.id];
1663
+ invariant(
1664
+ !existingRoute,
1665
+ `Duplicate routes found with id: ${String(childRoute.id)}`
1666
+ );
1667
+ routesById[childRoute.id] = childRoute;
1668
+ if (!childRoute.isRoot && childRoute.path) {
1669
+ const trimmedFullPath = trimPathRight(childRoute.fullPath);
1670
+ if (!routesByPath[trimmedFullPath] || childRoute.fullPath.endsWith("/")) {
1671
+ routesByPath[trimmedFullPath] = childRoute;
1672
+ }
1673
+ }
1674
+ const children = childRoute.children;
1675
+ if (children == null ? void 0 : children.length) {
1676
+ recurseRoutes(children);
1677
+ }
1678
+ });
1679
+ };
1680
+ recurseRoutes([routeTree]);
1681
+ const scoredRoutes = [];
1682
+ const routes = Object.values(routesById);
1683
+ routes.forEach((d, i) => {
1684
+ var _a;
1685
+ if (d.isRoot || !d.path) {
1686
+ return;
1687
+ }
1688
+ const trimmed = trimPathLeft(d.fullPath);
1689
+ const parsed = parsePathname(trimmed);
1690
+ while (parsed.length > 1 && ((_a = parsed[0]) == null ? void 0 : _a.value) === "/") {
1691
+ parsed.shift();
1692
+ }
1693
+ const scores = parsed.map((segment) => {
1694
+ if (segment.value === "/") {
1695
+ return 0.75;
1696
+ }
1697
+ if (segment.type === "param" && segment.prefixSegment && segment.suffixSegment) {
1698
+ return 0.55;
1699
+ }
1700
+ if (segment.type === "param" && segment.prefixSegment) {
1701
+ return 0.52;
1702
+ }
1703
+ if (segment.type === "param" && segment.suffixSegment) {
1704
+ return 0.51;
1705
+ }
1706
+ if (segment.type === "param") {
1707
+ return 0.5;
1708
+ }
1709
+ if (segment.type === "wildcard" && segment.prefixSegment && segment.suffixSegment) {
1710
+ return 0.3;
1711
+ }
1712
+ if (segment.type === "wildcard" && segment.prefixSegment) {
1713
+ return 0.27;
1714
+ }
1715
+ if (segment.type === "wildcard" && segment.suffixSegment) {
1716
+ return 0.26;
1717
+ }
1718
+ if (segment.type === "wildcard") {
1719
+ return 0.25;
1720
+ }
1721
+ return 1;
1722
+ });
1723
+ scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores });
1724
+ });
1725
+ const flatRoutes = scoredRoutes.sort((a, b) => {
1726
+ const minLength = Math.min(a.scores.length, b.scores.length);
1727
+ for (let i = 0; i < minLength; i++) {
1728
+ if (a.scores[i] !== b.scores[i]) {
1729
+ return b.scores[i] - a.scores[i];
1730
+ }
1731
+ }
1732
+ if (a.scores.length !== b.scores.length) {
1733
+ return b.scores.length - a.scores.length;
1734
+ }
1735
+ for (let i = 0; i < minLength; i++) {
1736
+ if (a.parsed[i].value !== b.parsed[i].value) {
1737
+ return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
1738
+ }
1739
+ }
1740
+ return a.index - b.index;
1741
+ }).map((d, i) => {
1742
+ d.child.rank = i;
1743
+ return d.child;
1744
+ });
1745
+ return { routesById, routesByPath, flatRoutes };
1746
+ }
1747
+ function getMatchedRoutes({
1748
+ pathname,
1749
+ routePathname,
1750
+ basepath,
1751
+ caseSensitive,
1752
+ routesByPath,
1753
+ routesById,
1754
+ flatRoutes
1755
+ }) {
1756
+ let routeParams = {};
1757
+ const trimmedPath = trimPathRight(pathname);
1758
+ const getMatchedParams = (route) => {
1759
+ var _a;
1760
+ const result = matchPathname(basepath, trimmedPath, {
1761
+ to: route.fullPath,
1762
+ caseSensitive: ((_a = route.options) == null ? void 0 : _a.caseSensitive) ?? caseSensitive,
1763
+ fuzzy: true
1764
+ });
1765
+ return result;
1766
+ };
1767
+ let foundRoute = routePathname !== void 0 ? routesByPath[routePathname] : void 0;
1768
+ if (foundRoute) {
1769
+ routeParams = getMatchedParams(foundRoute);
1770
+ } else {
1771
+ foundRoute = flatRoutes.find((route) => {
1772
+ const matchedParams = getMatchedParams(route);
1773
+ if (matchedParams) {
1774
+ routeParams = matchedParams;
1775
+ return true;
1776
+ }
1777
+ return false;
1778
+ });
1779
+ }
1780
+ let routeCursor = foundRoute || routesById[rootRouteId];
1781
+ const matchedRoutes = [routeCursor];
1782
+ while (routeCursor.parentRoute) {
1783
+ routeCursor = routeCursor.parentRoute;
1784
+ matchedRoutes.unshift(routeCursor);
1785
+ }
1786
+ return { matchedRoutes, routeParams, foundRoute };
1787
+ }
1788
+ export {
1789
+ PathParamError,
1790
+ RouterCore,
1791
+ SearchParamError,
1792
+ componentTypes,
1793
+ defaultSerializeError,
1794
+ getInitialRouterState,
1795
+ getLocationChangeInfo,
1796
+ getMatchedRoutes,
1797
+ lazyFn,
1798
+ processRouteTree
1799
+ };
1800
+ //# sourceMappingURL=router.js.map