@tanstack/solid-router 1.114.24 → 1.114.25

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