@tanstack/solid-router 1.108.0

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