@tanstack/react-router 1.114.24 → 1.114.27

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