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