PluginProbe
Gutenberg / 22.9.0
Gutenberg v22.9.0
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / build / modules / route / index.js

index.js in Gutenberg 22.9.0, at build/modules/route/index.js

5,729 lines 181.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 var __create = Object.create;
2 var __defProp = Object.defineProperty;
3 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4 var __getOwnPropNames = Object.getOwnPropertyNames;
5 var __getProtoOf = Object.getPrototypeOf;
6 var __hasOwnProp = Object.prototype.hasOwnProperty;
7 var __commonJS = (cb, mod) => function __require() {
8 return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9 };
10 var __copyProps = (to, from, except, desc) => {
11 if (from && typeof from === "object" || typeof from === "function") {
12 for (let key of __getOwnPropNames(from))
13 if (!__hasOwnProp.call(to, key) && key !== except)
14 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15 }
16 return to;
17 };
18 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19 // If the importer is in node compatibility mode or this is not an ESM
20 // file that has been converted to a CommonJS file using a Babel-
21 // compatible transform (i.e. "__esModule" has not been set), then set
22 // "default" to the CommonJS "module.exports" for node compatibility.
23 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24 mod
25 ));
26
27 // vendor-external:react/jsx-runtime
28 var require_jsx_runtime = __commonJS({
29 "vendor-external:react/jsx-runtime"(exports, module) {
30 module.exports = window.ReactJSXRuntime;
31 }
32 });
33
34 // vendor-external:react
35 var require_react = __commonJS({
36 "vendor-external:react"(exports, module) {
37 module.exports = window.React;
38 }
39 });
40
41 // node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js
42 var require_use_sync_external_store_shim_development = __commonJS({
43 "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js"(exports) {
44 "use strict";
45 (function() {
46 function is(x, y) {
47 return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
48 }
49 function useSyncExternalStore$2(subscribe2, getSnapshot) {
50 didWarnOld18Alpha || void 0 === React13.startTransition || (didWarnOld18Alpha = true, console.error(
51 "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
52 ));
53 var value = getSnapshot();
54 if (!didWarnUncachedGetSnapshot) {
55 var cachedValue = getSnapshot();
56 objectIs(value, cachedValue) || (console.error(
57 "The result of getSnapshot should be cached to avoid an infinite loop"
58 ), didWarnUncachedGetSnapshot = true);
59 }
60 cachedValue = useState5({
61 inst: { value, getSnapshot }
62 });
63 var inst = cachedValue[0].inst, forceUpdate = cachedValue[1];
64 useLayoutEffect3(
65 function() {
66 inst.value = value;
67 inst.getSnapshot = getSnapshot;
68 checkIfSnapshotChanged(inst) && forceUpdate({ inst });
69 },
70 [subscribe2, value, getSnapshot]
71 );
72 useEffect6(
73 function() {
74 checkIfSnapshotChanged(inst) && forceUpdate({ inst });
75 return subscribe2(function() {
76 checkIfSnapshotChanged(inst) && forceUpdate({ inst });
77 });
78 },
79 [subscribe2]
80 );
81 useDebugValue(value);
82 return value;
83 }
84 function checkIfSnapshotChanged(inst) {
85 var latestGetSnapshot = inst.getSnapshot;
86 inst = inst.value;
87 try {
88 var nextValue = latestGetSnapshot();
89 return !objectIs(inst, nextValue);
90 } catch (error) {
91 return true;
92 }
93 }
94 function useSyncExternalStore$1(subscribe2, getSnapshot) {
95 return getSnapshot();
96 }
97 "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
98 var React13 = require_react(), objectIs = "function" === typeof Object.is ? Object.is : is, useState5 = React13.useState, useEffect6 = React13.useEffect, useLayoutEffect3 = React13.useLayoutEffect, useDebugValue = React13.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2;
99 exports.useSyncExternalStore = void 0 !== React13.useSyncExternalStore ? React13.useSyncExternalStore : shim;
100 "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
101 })();
102 }
103 });
104
105 // node_modules/use-sync-external-store/shim/index.js
106 var require_shim = __commonJS({
107 "node_modules/use-sync-external-store/shim/index.js"(exports, module) {
108 "use strict";
109 if (false) {
110 module.exports = null;
111 } else {
112 module.exports = require_use_sync_external_store_shim_development();
113 }
114 }
115 });
116
117 // node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js
118 var require_with_selector_development = __commonJS({
119 "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js"(exports) {
120 "use strict";
121 (function() {
122 function is(x, y) {
123 return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
124 }
125 "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
126 var React13 = require_react(), shim = require_shim(), objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore = shim.useSyncExternalStore, useRef7 = React13.useRef, useEffect6 = React13.useEffect, useMemo3 = React13.useMemo, useDebugValue = React13.useDebugValue;
127 exports.useSyncExternalStoreWithSelector = function(subscribe2, getSnapshot, getServerSnapshot, selector, isEqual) {
128 var instRef = useRef7(null);
129 if (null === instRef.current) {
130 var inst = { hasValue: false, value: null };
131 instRef.current = inst;
132 } else inst = instRef.current;
133 instRef = useMemo3(
134 function() {
135 function memoizedSelector(nextSnapshot) {
136 if (!hasMemo) {
137 hasMemo = true;
138 memoizedSnapshot = nextSnapshot;
139 nextSnapshot = selector(nextSnapshot);
140 if (void 0 !== isEqual && inst.hasValue) {
141 var currentSelection = inst.value;
142 if (isEqual(currentSelection, nextSnapshot))
143 return memoizedSelection = currentSelection;
144 }
145 return memoizedSelection = nextSnapshot;
146 }
147 currentSelection = memoizedSelection;
148 if (objectIs(memoizedSnapshot, nextSnapshot))
149 return currentSelection;
150 var nextSelection = selector(nextSnapshot);
151 if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
152 return memoizedSnapshot = nextSnapshot, currentSelection;
153 memoizedSnapshot = nextSnapshot;
154 return memoizedSelection = nextSelection;
155 }
156 var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot;
157 return [
158 function() {
159 return memoizedSelector(getSnapshot());
160 },
161 null === maybeGetServerSnapshot ? void 0 : function() {
162 return memoizedSelector(maybeGetServerSnapshot());
163 }
164 ];
165 },
166 [getSnapshot, getServerSnapshot, selector, isEqual]
167 );
168 var value = useSyncExternalStore(subscribe2, instRef[0], instRef[1]);
169 useEffect6(
170 function() {
171 inst.hasValue = true;
172 inst.value = value;
173 },
174 [value]
175 );
176 useDebugValue(value);
177 return value;
178 };
179 "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
180 })();
181 }
182 });
183
184 // node_modules/use-sync-external-store/shim/with-selector.js
185 var require_with_selector = __commonJS({
186 "node_modules/use-sync-external-store/shim/with-selector.js"(exports, module) {
187 "use strict";
188 if (false) {
189 module.exports = null;
190 } else {
191 module.exports = require_with_selector_development();
192 }
193 }
194 });
195
196 // vendor-external:react-dom
197 var require_react_dom = __commonJS({
198 "vendor-external:react-dom"(exports, module) {
199 module.exports = window.ReactDOM;
200 }
201 });
202
203 // package-external:@wordpress/private-apis
204 var require_private_apis = __commonJS({
205 "package-external:@wordpress/private-apis"(exports, module) {
206 module.exports = window.wp.privateApis;
207 }
208 });
209
210 // node_modules/@tanstack/store/dist/esm/scheduler.js
211 var __storeToDerived = /* @__PURE__ */ new WeakMap();
212 var __derivedToStore = /* @__PURE__ */ new WeakMap();
213 var __depsThatHaveWrittenThisTick = {
214 current: []
215 };
216 var __isFlushing = false;
217 var __batchDepth = 0;
218 var __pendingUpdates = /* @__PURE__ */ new Set();
219 var __initialBatchValues = /* @__PURE__ */ new Map();
220 function __flush_internals(relatedVals) {
221 for (const derived of relatedVals) {
222 if (__depsThatHaveWrittenThisTick.current.includes(derived)) {
223 continue;
224 }
225 __depsThatHaveWrittenThisTick.current.push(derived);
226 derived.recompute();
227 const stores = __derivedToStore.get(derived);
228 if (stores) {
229 for (const store of stores) {
230 const relatedLinkedDerivedVals = __storeToDerived.get(store);
231 if (!(relatedLinkedDerivedVals == null ? void 0 : relatedLinkedDerivedVals.length)) continue;
232 __flush_internals(relatedLinkedDerivedVals);
233 }
234 }
235 }
236 }
237 function __notifyListeners(store) {
238 const value = {
239 prevVal: store.prevState,
240 currentVal: store.state
241 };
242 for (const listener of store.listeners) {
243 listener(value);
244 }
245 }
246 function __notifyDerivedListeners(derived) {
247 const value = {
248 prevVal: derived.prevState,
249 currentVal: derived.state
250 };
251 for (const listener of derived.listeners) {
252 listener(value);
253 }
254 }
255 function __flush(store) {
256 if (__batchDepth > 0 && !__initialBatchValues.has(store)) {
257 __initialBatchValues.set(store, store.prevState);
258 }
259 __pendingUpdates.add(store);
260 if (__batchDepth > 0) return;
261 if (__isFlushing) return;
262 try {
263 __isFlushing = true;
264 while (__pendingUpdates.size > 0) {
265 const stores = Array.from(__pendingUpdates);
266 __pendingUpdates.clear();
267 for (const store2 of stores) {
268 const prevState = __initialBatchValues.get(store2) ?? store2.prevState;
269 store2.prevState = prevState;
270 __notifyListeners(store2);
271 }
272 for (const store2 of stores) {
273 const derivedVals = __storeToDerived.get(store2);
274 if (!derivedVals) continue;
275 __depsThatHaveWrittenThisTick.current.push(store2);
276 __flush_internals(derivedVals);
277 }
278 for (const store2 of stores) {
279 const derivedVals = __storeToDerived.get(store2);
280 if (!derivedVals) continue;
281 for (const derived of derivedVals) {
282 __notifyDerivedListeners(derived);
283 }
284 }
285 }
286 } finally {
287 __isFlushing = false;
288 __depsThatHaveWrittenThisTick.current = [];
289 __initialBatchValues.clear();
290 }
291 }
292 function batch(fn) {
293 __batchDepth++;
294 try {
295 fn();
296 } finally {
297 __batchDepth--;
298 if (__batchDepth === 0) {
299 const pendingUpdateToFlush = __pendingUpdates.values().next().value;
300 if (pendingUpdateToFlush) {
301 __flush(pendingUpdateToFlush);
302 }
303 }
304 }
305 }
306
307 // node_modules/@tanstack/store/dist/esm/types.js
308 function isUpdaterFunction(updater) {
309 return typeof updater === "function";
310 }
311
312 // node_modules/@tanstack/store/dist/esm/store.js
313 var Store = class {
314 constructor(initialState, options) {
315 this.listeners = /* @__PURE__ */ new Set();
316 this.subscribe = (listener) => {
317 var _a, _b;
318 this.listeners.add(listener);
319 const unsub = (_b = (_a = this.options) == null ? void 0 : _a.onSubscribe) == null ? void 0 : _b.call(_a, listener, this);
320 return () => {
321 this.listeners.delete(listener);
322 unsub == null ? void 0 : unsub();
323 };
324 };
325 this.prevState = initialState;
326 this.state = initialState;
327 this.options = options;
328 }
329 setState(updater) {
330 var _a, _b, _c;
331 this.prevState = this.state;
332 if ((_a = this.options) == null ? void 0 : _a.updateFn) {
333 this.state = this.options.updateFn(this.prevState)(updater);
334 } else {
335 if (isUpdaterFunction(updater)) {
336 this.state = updater(this.prevState);
337 } else {
338 this.state = updater;
339 }
340 }
341 (_c = (_b = this.options) == null ? void 0 : _b.onUpdate) == null ? void 0 : _c.call(_b);
342 __flush(this);
343 }
344 };
345
346 // node_modules/@tanstack/history/dist/esm/index.js
347 var stateIndexKey = "__TSR_index";
348 var popStateEvent = "popstate";
349 var beforeUnloadEvent = "beforeunload";
350 function createHistory(opts) {
351 let location = opts.getLocation();
352 const subscribers = /* @__PURE__ */ new Set();
353 const notify = (action) => {
354 location = opts.getLocation();
355 subscribers.forEach((subscriber) => subscriber({ location, action }));
356 };
357 const handleIndexChange = (action) => {
358 if (opts.notifyOnIndexChange ?? true) notify(action);
359 else location = opts.getLocation();
360 };
361 const tryNavigation = async ({
362 task,
363 navigateOpts,
364 ...actionInfo
365 }) => {
366 const ignoreBlocker = navigateOpts?.ignoreBlocker ?? false;
367 if (ignoreBlocker) {
368 task();
369 return;
370 }
371 const blockers = opts.getBlockers?.() ?? [];
372 const isPushOrReplace = actionInfo.type === "PUSH" || actionInfo.type === "REPLACE";
373 if (typeof document !== "undefined" && blockers.length && isPushOrReplace) {
374 for (const blocker of blockers) {
375 const nextLocation = parseHref(actionInfo.path, actionInfo.state);
376 const isBlocked = await blocker.blockerFn({
377 currentLocation: location,
378 nextLocation,
379 action: actionInfo.type
380 });
381 if (isBlocked) {
382 opts.onBlocked?.();
383 return;
384 }
385 }
386 }
387 task();
388 };
389 return {
390 get location() {
391 return location;
392 },
393 get length() {
394 return opts.getLength();
395 },
396 subscribers,
397 subscribe: (cb) => {
398 subscribers.add(cb);
399 return () => {
400 subscribers.delete(cb);
401 };
402 },
403 push: (path, state, navigateOpts) => {
404 const currentIndex = location.state[stateIndexKey];
405 state = assignKeyAndIndex(currentIndex + 1, state);
406 tryNavigation({
407 task: () => {
408 opts.pushState(path, state);
409 notify({ type: "PUSH" });
410 },
411 navigateOpts,
412 type: "PUSH",
413 path,
414 state
415 });
416 },
417 replace: (path, state, navigateOpts) => {
418 const currentIndex = location.state[stateIndexKey];
419 state = assignKeyAndIndex(currentIndex, state);
420 tryNavigation({
421 task: () => {
422 opts.replaceState(path, state);
423 notify({ type: "REPLACE" });
424 },
425 navigateOpts,
426 type: "REPLACE",
427 path,
428 state
429 });
430 },
431 go: (index, navigateOpts) => {
432 tryNavigation({
433 task: () => {
434 opts.go(index);
435 handleIndexChange({ type: "GO", index });
436 },
437 navigateOpts,
438 type: "GO"
439 });
440 },
441 back: (navigateOpts) => {
442 tryNavigation({
443 task: () => {
444 opts.back(navigateOpts?.ignoreBlocker ?? false);
445 handleIndexChange({ type: "BACK" });
446 },
447 navigateOpts,
448 type: "BACK"
449 });
450 },
451 forward: (navigateOpts) => {
452 tryNavigation({
453 task: () => {
454 opts.forward(navigateOpts?.ignoreBlocker ?? false);
455 handleIndexChange({ type: "FORWARD" });
456 },
457 navigateOpts,
458 type: "FORWARD"
459 });
460 },
461 canGoBack: () => location.state[stateIndexKey] !== 0,
462 createHref: (str) => opts.createHref(str),
463 block: (blocker) => {
464 if (!opts.setBlockers) return () => {
465 };
466 const blockers = opts.getBlockers?.() ?? [];
467 opts.setBlockers([...blockers, blocker]);
468 return () => {
469 const blockers2 = opts.getBlockers?.() ?? [];
470 opts.setBlockers?.(blockers2.filter((b) => b !== blocker));
471 };
472 },
473 flush: () => opts.flush?.(),
474 destroy: () => opts.destroy?.(),
475 notify
476 };
477 }
478 function assignKeyAndIndex(index, state) {
479 if (!state) {
480 state = {};
481 }
482 const key = createRandomKey();
483 return {
484 ...state,
485 key,
486 // TODO: Remove in v2 - use __TSR_key instead
487 __TSR_key: key,
488 [stateIndexKey]: index
489 };
490 }
491 function createBrowserHistory(opts) {
492 const win = opts?.window ?? (typeof document !== "undefined" ? window : void 0);
493 const originalPushState = win.history.pushState;
494 const originalReplaceState = win.history.replaceState;
495 let blockers = [];
496 const _getBlockers = () => blockers;
497 const _setBlockers = (newBlockers) => blockers = newBlockers;
498 const createHref = opts?.createHref ?? ((path) => path);
499 const parseLocation = opts?.parseLocation ?? (() => parseHref(
500 `${win.location.pathname}${win.location.search}${win.location.hash}`,
501 win.history.state
502 ));
503 if (!win.history.state?.__TSR_key && !win.history.state?.key) {
504 const addedKey = createRandomKey();
505 win.history.replaceState(
506 {
507 [stateIndexKey]: 0,
508 key: addedKey,
509 // TODO: Remove in v2 - use __TSR_key instead
510 __TSR_key: addedKey
511 },
512 ""
513 );
514 }
515 let currentLocation = parseLocation();
516 let rollbackLocation;
517 let nextPopIsGo = false;
518 let ignoreNextPop = false;
519 let skipBlockerNextPop = false;
520 let ignoreNextBeforeUnload = false;
521 const getLocation = () => currentLocation;
522 let next;
523 let scheduled;
524 const flush = () => {
525 if (!next) {
526 return;
527 }
528 history._ignoreSubscribers = true;
529 (next.isPush ? win.history.pushState : win.history.replaceState)(
530 next.state,
531 "",
532 next.href
533 );
534 history._ignoreSubscribers = false;
535 next = void 0;
536 scheduled = void 0;
537 rollbackLocation = void 0;
538 };
539 const queueHistoryAction = (type, destHref, state) => {
540 const href = createHref(destHref);
541 if (!scheduled) {
542 rollbackLocation = currentLocation;
543 }
544 currentLocation = parseHref(destHref, state);
545 next = {
546 href,
547 state,
548 isPush: next?.isPush || type === "push"
549 };
550 if (!scheduled) {
551 scheduled = Promise.resolve().then(() => flush());
552 }
553 };
554 const onPushPop = (type) => {
555 currentLocation = parseLocation();
556 history.notify({ type });
557 };
558 const onPushPopEvent = async () => {
559 if (ignoreNextPop) {
560 ignoreNextPop = false;
561 return;
562 }
563 const nextLocation = parseLocation();
564 const delta = nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey];
565 const isForward = delta === 1;
566 const isBack = delta === -1;
567 const isGo = !isForward && !isBack || nextPopIsGo;
568 nextPopIsGo = false;
569 const action = isGo ? "GO" : isBack ? "BACK" : "FORWARD";
570 const notify = isGo ? {
571 type: "GO",
572 index: delta
573 } : {
574 type: isBack ? "BACK" : "FORWARD"
575 };
576 if (skipBlockerNextPop) {
577 skipBlockerNextPop = false;
578 } else {
579 const blockers2 = _getBlockers();
580 if (typeof document !== "undefined" && blockers2.length) {
581 for (const blocker of blockers2) {
582 const isBlocked = await blocker.blockerFn({
583 currentLocation,
584 nextLocation,
585 action
586 });
587 if (isBlocked) {
588 ignoreNextPop = true;
589 win.history.go(1);
590 history.notify(notify);
591 return;
592 }
593 }
594 }
595 }
596 currentLocation = parseLocation();
597 history.notify(notify);
598 };
599 const onBeforeUnload = (e) => {
600 if (ignoreNextBeforeUnload) {
601 ignoreNextBeforeUnload = false;
602 return;
603 }
604 let shouldBlock = false;
605 const blockers2 = _getBlockers();
606 if (typeof document !== "undefined" && blockers2.length) {
607 for (const blocker of blockers2) {
608 const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true;
609 if (shouldHaveBeforeUnload === true) {
610 shouldBlock = true;
611 break;
612 }
613 if (typeof shouldHaveBeforeUnload === "function" && shouldHaveBeforeUnload() === true) {
614 shouldBlock = true;
615 break;
616 }
617 }
618 }
619 if (shouldBlock) {
620 e.preventDefault();
621 return e.returnValue = "";
622 }
623 return;
624 };
625 const history = createHistory({
626 getLocation,
627 getLength: () => win.history.length,
628 pushState: (href, state) => queueHistoryAction("push", href, state),
629 replaceState: (href, state) => queueHistoryAction("replace", href, state),
630 back: (ignoreBlocker) => {
631 if (ignoreBlocker) skipBlockerNextPop = true;
632 ignoreNextBeforeUnload = true;
633 return win.history.back();
634 },
635 forward: (ignoreBlocker) => {
636 if (ignoreBlocker) skipBlockerNextPop = true;
637 ignoreNextBeforeUnload = true;
638 win.history.forward();
639 },
640 go: (n) => {
641 nextPopIsGo = true;
642 win.history.go(n);
643 },
644 createHref: (href) => createHref(href),
645 flush,
646 destroy: () => {
647 win.history.pushState = originalPushState;
648 win.history.replaceState = originalReplaceState;
649 win.removeEventListener(beforeUnloadEvent, onBeforeUnload, {
650 capture: true
651 });
652 win.removeEventListener(popStateEvent, onPushPopEvent);
653 },
654 onBlocked: () => {
655 if (rollbackLocation && currentLocation !== rollbackLocation) {
656 currentLocation = rollbackLocation;
657 }
658 },
659 getBlockers: _getBlockers,
660 setBlockers: _setBlockers,
661 notifyOnIndexChange: false
662 });
663 win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
664 win.addEventListener(popStateEvent, onPushPopEvent);
665 win.history.pushState = function(...args) {
666 const res = originalPushState.apply(win.history, args);
667 if (!history._ignoreSubscribers) onPushPop("PUSH");
668 return res;
669 };
670 win.history.replaceState = function(...args) {
671 const res = originalReplaceState.apply(win.history, args);
672 if (!history._ignoreSubscribers) onPushPop("REPLACE");
673 return res;
674 };
675 return history;
676 }
677 function createMemoryHistory(opts = {
678 initialEntries: ["/"]
679 }) {
680 const entries = opts.initialEntries;
681 let index = opts.initialIndex ? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1) : entries.length - 1;
682 const states = entries.map(
683 (_entry, index2) => assignKeyAndIndex(index2, void 0)
684 );
685 const getLocation = () => parseHref(entries[index], states[index]);
686 return createHistory({
687 getLocation,
688 getLength: () => entries.length,
689 pushState: (path, state) => {
690 if (index < entries.length - 1) {
691 entries.splice(index + 1);
692 states.splice(index + 1);
693 }
694 states.push(state);
695 entries.push(path);
696 index = Math.max(entries.length - 1, 0);
697 },
698 replaceState: (path, state) => {
699 states[index] = state;
700 entries[index] = path;
701 },
702 back: () => {
703 index = Math.max(index - 1, 0);
704 },
705 forward: () => {
706 index = Math.min(index + 1, entries.length - 1);
707 },
708 go: (n) => {
709 index = Math.min(Math.max(index + n, 0), entries.length - 1);
710 },
711 createHref: (path) => path
712 });
713 }
714 function parseHref(href, state) {
715 const hashIndex = href.indexOf("#");
716 const searchIndex = href.indexOf("?");
717 const addedKey = createRandomKey();
718 return {
719 href,
720 pathname: href.substring(
721 0,
722 hashIndex > 0 ? searchIndex > 0 ? Math.min(hashIndex, searchIndex) : hashIndex : searchIndex > 0 ? searchIndex : href.length
723 ),
724 hash: hashIndex > -1 ? href.substring(hashIndex) : "",
725 search: searchIndex > -1 ? href.slice(searchIndex, hashIndex === -1 ? void 0 : hashIndex) : "",
726 state: state || { [stateIndexKey]: 0, key: addedKey, __TSR_key: addedKey }
727 };
728 }
729 function createRandomKey() {
730 return (Math.random() + 1).toString(36).substring(7);
731 }
732
733 // node_modules/@tanstack/router-core/dist/esm/utils.js
734 function last(arr) {
735 return arr[arr.length - 1];
736 }
737 function isFunction(d) {
738 return typeof d === "function";
739 }
740 function functionalUpdate(updater, previous) {
741 if (isFunction(updater)) {
742 return updater(previous);
743 }
744 return updater;
745 }
746 var hasOwn = Object.prototype.hasOwnProperty;
747 function replaceEqualDeep(prev, _next) {
748 if (prev === _next) {
749 return prev;
750 }
751 const next = _next;
752 const array = isPlainArray(prev) && isPlainArray(next);
753 if (!array && !(isPlainObject(prev) && isPlainObject(next))) return next;
754 const prevItems = array ? prev : getEnumerableOwnKeys(prev);
755 if (!prevItems) return next;
756 const nextItems = array ? next : getEnumerableOwnKeys(next);
757 if (!nextItems) return next;
758 const prevSize = prevItems.length;
759 const nextSize = nextItems.length;
760 const copy = array ? new Array(nextSize) : {};
761 let equalItems = 0;
762 for (let i = 0; i < nextSize; i++) {
763 const key = array ? i : nextItems[i];
764 const p = prev[key];
765 const n = next[key];
766 if (p === n) {
767 copy[key] = p;
768 if (array ? i < prevSize : hasOwn.call(prev, key)) equalItems++;
769 continue;
770 }
771 if (p === null || n === null || typeof p !== "object" || typeof n !== "object") {
772 copy[key] = n;
773 continue;
774 }
775 const v = replaceEqualDeep(p, n);
776 copy[key] = v;
777 if (v === p) equalItems++;
778 }
779 return prevSize === nextSize && equalItems === prevSize ? prev : copy;
780 }
781 function getEnumerableOwnKeys(o) {
782 const keys = [];
783 const names = Object.getOwnPropertyNames(o);
784 for (const name of names) {
785 if (!Object.prototype.propertyIsEnumerable.call(o, name)) return false;
786 keys.push(name);
787 }
788 const symbols = Object.getOwnPropertySymbols(o);
789 for (const symbol of symbols) {
790 if (!Object.prototype.propertyIsEnumerable.call(o, symbol)) return false;
791 keys.push(symbol);
792 }
793 return keys;
794 }
795 function isPlainObject(o) {
796 if (!hasObjectPrototype(o)) {
797 return false;
798 }
799 const ctor = o.constructor;
800 if (typeof ctor === "undefined") {
801 return true;
802 }
803 const prot = ctor.prototype;
804 if (!hasObjectPrototype(prot)) {
805 return false;
806 }
807 if (!prot.hasOwnProperty("isPrototypeOf")) {
808 return false;
809 }
810 return true;
811 }
812 function hasObjectPrototype(o) {
813 return Object.prototype.toString.call(o) === "[object Object]";
814 }
815 function isPlainArray(value) {
816 return Array.isArray(value) && value.length === Object.keys(value).length;
817 }
818 function deepEqual(a, b, opts) {
819 if (a === b) {
820 return true;
821 }
822 if (typeof a !== typeof b) {
823 return false;
824 }
825 if (Array.isArray(a) && Array.isArray(b)) {
826 if (a.length !== b.length) return false;
827 for (let i = 0, l = a.length; i < l; i++) {
828 if (!deepEqual(a[i], b[i], opts)) return false;
829 }
830 return true;
831 }
832 if (isPlainObject(a) && isPlainObject(b)) {
833 const ignoreUndefined = opts?.ignoreUndefined ?? true;
834 if (opts?.partial) {
835 for (const k in b) {
836 if (!ignoreUndefined || b[k] !== void 0) {
837 if (!deepEqual(a[k], b[k], opts)) return false;
838 }
839 }
840 return true;
841 }
842 let aCount = 0;
843 if (!ignoreUndefined) {
844 aCount = Object.keys(a).length;
845 } else {
846 for (const k in a) {
847 if (a[k] !== void 0) aCount++;
848 }
849 }
850 let bCount = 0;
851 for (const k in b) {
852 if (!ignoreUndefined || b[k] !== void 0) {
853 bCount++;
854 if (bCount > aCount || !deepEqual(a[k], b[k], opts)) return false;
855 }
856 }
857 return aCount === bCount;
858 }
859 return false;
860 }
861 function createControlledPromise(onResolve) {
862 let resolveLoadPromise;
863 let rejectLoadPromise;
864 const controlledPromise = new Promise((resolve, reject) => {
865 resolveLoadPromise = resolve;
866 rejectLoadPromise = reject;
867 });
868 controlledPromise.status = "pending";
869 controlledPromise.resolve = (value) => {
870 controlledPromise.status = "resolved";
871 controlledPromise.value = value;
872 resolveLoadPromise(value);
873 onResolve?.(value);
874 };
875 controlledPromise.reject = (e) => {
876 controlledPromise.status = "rejected";
877 rejectLoadPromise(e);
878 };
879 return controlledPromise;
880 }
881 function isPromise(value) {
882 return Boolean(
883 value && typeof value === "object" && typeof value.then === "function"
884 );
885 }
886 function findLast(array, predicate) {
887 for (let i = array.length - 1; i >= 0; i--) {
888 const item = array[i];
889 if (predicate(item)) return item;
890 }
891 return void 0;
892 }
893 var DECODE_IGNORE_LIST = Array.from(
894 (/* @__PURE__ */ new Map([
895 ["%", "%25"],
896 ["\\", "%5C"],
897 ["/", "%2F"],
898 [";", "%3B"],
899 [":", "%3A"],
900 ["@", "%40"],
901 ["&", "%26"],
902 ["=", "%3D"],
903 ["+", "%2B"],
904 ["$", "%24"],
905 [",", "%2C"]
906 ])).values()
907 );
908 function decodePathSegment(part, decodeIgnore = DECODE_IGNORE_LIST, startIndex = 0) {
909 function decode2(part2) {
910 try {
911 return decodeURIComponent(part2);
912 } catch {
913 return part2.replaceAll(/%[0-9A-Fa-f]{2}/g, (match) => {
914 try {
915 return decodeURIComponent(match);
916 } catch {
917 return match;
918 }
919 });
920 }
921 }
922 if (part === "" || !part.match(/%[0-9A-Fa-f]{2}/g)) return part;
923 for (let i = startIndex; i < decodeIgnore.length; i++) {
924 const char = decodeIgnore[i];
925 if (char && part.includes(char)) {
926 const partsToDecode = part.split(char);
927 const partsToJoin = [];
928 for (const partToDecode of partsToDecode) {
929 partsToJoin.push(decodePathSegment(partToDecode, decodeIgnore, i + 1));
930 }
931 return partsToJoin.join(char);
932 }
933 }
934 return decode2(part);
935 }
936
937 // node_modules/tiny-invariant/dist/esm/tiny-invariant.js
938 var isProduction = false;
939 var prefix = "Invariant failed";
940 function invariant(condition, message) {
941 if (condition) {
942 return;
943 }
944 if (isProduction) {
945 throw new Error(prefix);
946 }
947 var provided = typeof message === "function" ? message() : message;
948 var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix;
949 throw new Error(value);
950 }
951
952 // node_modules/@tanstack/router-core/dist/esm/path.js
953 var SEGMENT_TYPE_PATHNAME = 0;
954 var SEGMENT_TYPE_PARAM = 1;
955 var SEGMENT_TYPE_WILDCARD = 2;
956 var SEGMENT_TYPE_OPTIONAL_PARAM = 3;
957 function joinPaths(paths) {
958 return cleanPath(
959 paths.filter((val) => {
960 return val !== void 0;
961 }).join("/")
962 );
963 }
964 function cleanPath(path) {
965 return path.replace(/\/{2,}/g, "/");
966 }
967 function trimPathLeft(path) {
968 return path === "/" ? path : path.replace(/^\/{1,}/, "");
969 }
970 function trimPathRight(path) {
971 return path === "/" ? path : path.replace(/\/{1,}$/, "");
972 }
973 function trimPath(path) {
974 return trimPathRight(trimPathLeft(path));
975 }
976 function removeTrailingSlash(value, basepath) {
977 if (value?.endsWith("/") && value !== "/" && value !== `${basepath}/`) {
978 return value.slice(0, -1);
979 }
980 return value;
981 }
982 function exactPathTest(pathName1, pathName2, basepath) {
983 return removeTrailingSlash(pathName1, basepath) === removeTrailingSlash(pathName2, basepath);
984 }
985 function segmentToString(segment) {
986 const { type, value } = segment;
987 if (type === SEGMENT_TYPE_PATHNAME) {
988 return value;
989 }
990 const { prefixSegment, suffixSegment } = segment;
991 if (type === SEGMENT_TYPE_PARAM) {
992 const param = value.substring(1);
993 if (prefixSegment && suffixSegment) {
994 return `${prefixSegment}{$${param}}${suffixSegment}`;
995 } else if (prefixSegment) {
996 return `${prefixSegment}{$${param}}`;
997 } else if (suffixSegment) {
998 return `{$${param}}${suffixSegment}`;
999 }
1000 }
1001 if (type === SEGMENT_TYPE_OPTIONAL_PARAM) {
1002 const param = value.substring(1);
1003 if (prefixSegment && suffixSegment) {
1004 return `${prefixSegment}{-$${param}}${suffixSegment}`;
1005 } else if (prefixSegment) {
1006 return `${prefixSegment}{-$${param}}`;
1007 } else if (suffixSegment) {
1008 return `{-$${param}}${suffixSegment}`;
1009 }
1010 return `{-$${param}}`;
1011 }
1012 if (type === SEGMENT_TYPE_WILDCARD) {
1013 if (prefixSegment && suffixSegment) {
1014 return `${prefixSegment}{$}${suffixSegment}`;
1015 } else if (prefixSegment) {
1016 return `${prefixSegment}{$}`;
1017 } else if (suffixSegment) {
1018 return `{$}${suffixSegment}`;
1019 }
1020 }
1021 return value;
1022 }
1023 function resolvePath({
1024 base,
1025 to,
1026 trailingSlash = "never",
1027 parseCache
1028 }) {
1029 let baseSegments = parsePathname(base, parseCache).slice();
1030 const toSegments = parsePathname(to, parseCache);
1031 if (baseSegments.length > 1 && last(baseSegments)?.value === "/") {
1032 baseSegments.pop();
1033 }
1034 for (let index = 0, length = toSegments.length; index < length; index++) {
1035 const toSegment = toSegments[index];
1036 const value = toSegment.value;
1037 if (value === "/") {
1038 if (!index) {
1039 baseSegments = [toSegment];
1040 } else if (index === length - 1) {
1041 baseSegments.push(toSegment);
1042 } else ;
1043 } else if (value === "..") {
1044 baseSegments.pop();
1045 } else if (value === ".") ;
1046 else {
1047 baseSegments.push(toSegment);
1048 }
1049 }
1050 if (baseSegments.length > 1) {
1051 if (last(baseSegments).value === "/") {
1052 if (trailingSlash === "never") {
1053 baseSegments.pop();
1054 }
1055 } else if (trailingSlash === "always") {
1056 baseSegments.push({ type: SEGMENT_TYPE_PATHNAME, value: "/" });
1057 }
1058 }
1059 const segmentValues = baseSegments.map(segmentToString);
1060 const joined = joinPaths(segmentValues);
1061 return joined;
1062 }
1063 var parsePathname = (pathname, cache) => {
1064 if (!pathname) return [];
1065 const cached = cache?.get(pathname);
1066 if (cached) return cached;
1067 const parsed = baseParsePathname(pathname);
1068 cache?.set(pathname, parsed);
1069 return parsed;
1070 };
1071 var PARAM_RE = /^\$.{1,}$/;
1072 var PARAM_W_CURLY_BRACES_RE = /^(.*?)\{(\$[a-zA-Z_$][a-zA-Z0-9_$]*)\}(.*)$/;
1073 var OPTIONAL_PARAM_W_CURLY_BRACES_RE = /^(.*?)\{-(\$[a-zA-Z_$][a-zA-Z0-9_$]*)\}(.*)$/;
1074 var WILDCARD_RE = /^\$$/;
1075 var WILDCARD_W_CURLY_BRACES_RE = /^(.*?)\{\$\}(.*)$/;
1076 function baseParsePathname(pathname) {
1077 pathname = cleanPath(pathname);
1078 const segments = [];
1079 if (pathname.slice(0, 1) === "/") {
1080 pathname = pathname.substring(1);
1081 segments.push({
1082 type: SEGMENT_TYPE_PATHNAME,
1083 value: "/"
1084 });
1085 }
1086 if (!pathname) {
1087 return segments;
1088 }
1089 const split = pathname.split("/").filter(Boolean);
1090 segments.push(
1091 ...split.map((part) => {
1092 const wildcardBracesMatch = part.match(WILDCARD_W_CURLY_BRACES_RE);
1093 if (wildcardBracesMatch) {
1094 const prefix2 = wildcardBracesMatch[1];
1095 const suffix = wildcardBracesMatch[2];
1096 return {
1097 type: SEGMENT_TYPE_WILDCARD,
1098 value: "$",
1099 prefixSegment: prefix2 || void 0,
1100 suffixSegment: suffix || void 0
1101 };
1102 }
1103 const optionalParamBracesMatch = part.match(
1104 OPTIONAL_PARAM_W_CURLY_BRACES_RE
1105 );
1106 if (optionalParamBracesMatch) {
1107 const prefix2 = optionalParamBracesMatch[1];
1108 const paramName = optionalParamBracesMatch[2];
1109 const suffix = optionalParamBracesMatch[3];
1110 return {
1111 type: SEGMENT_TYPE_OPTIONAL_PARAM,
1112 value: paramName,
1113 // Now just $paramName (no prefix)
1114 prefixSegment: prefix2 || void 0,
1115 suffixSegment: suffix || void 0
1116 };
1117 }
1118 const paramBracesMatch = part.match(PARAM_W_CURLY_BRACES_RE);
1119 if (paramBracesMatch) {
1120 const prefix2 = paramBracesMatch[1];
1121 const paramName = paramBracesMatch[2];
1122 const suffix = paramBracesMatch[3];
1123 return {
1124 type: SEGMENT_TYPE_PARAM,
1125 value: "" + paramName,
1126 prefixSegment: prefix2 || void 0,
1127 suffixSegment: suffix || void 0
1128 };
1129 }
1130 if (PARAM_RE.test(part)) {
1131 const paramName = part.substring(1);
1132 return {
1133 type: SEGMENT_TYPE_PARAM,
1134 value: "$" + paramName,
1135 prefixSegment: void 0,
1136 suffixSegment: void 0
1137 };
1138 }
1139 if (WILDCARD_RE.test(part)) {
1140 return {
1141 type: SEGMENT_TYPE_WILDCARD,
1142 value: "$",
1143 prefixSegment: void 0,
1144 suffixSegment: void 0
1145 };
1146 }
1147 return {
1148 type: SEGMENT_TYPE_PATHNAME,
1149 value: decodePathSegment(part)
1150 };
1151 })
1152 );
1153 if (pathname.slice(-1) === "/") {
1154 pathname = pathname.substring(1);
1155 segments.push({
1156 type: SEGMENT_TYPE_PATHNAME,
1157 value: "/"
1158 });
1159 }
1160 return segments;
1161 }
1162 function interpolatePath({
1163 path,
1164 params,
1165 leaveWildcards,
1166 leaveParams,
1167 decodeCharMap,
1168 parseCache
1169 }) {
1170 const interpolatedPathSegments = parsePathname(path, parseCache);
1171 function encodeParam(key) {
1172 const value = params[key];
1173 const isValueString = typeof value === "string";
1174 if (key === "*" || key === "_splat") {
1175 return isValueString ? encodeURI(value) : value;
1176 } else {
1177 return isValueString ? encodePathParam(value, decodeCharMap) : value;
1178 }
1179 }
1180 let isMissingParams = false;
1181 const usedParams = {};
1182 const interpolatedPath = joinPaths(
1183 interpolatedPathSegments.map((segment) => {
1184 if (segment.type === SEGMENT_TYPE_PATHNAME) {
1185 return segment.value;
1186 }
1187 if (segment.type === SEGMENT_TYPE_WILDCARD) {
1188 usedParams._splat = params._splat;
1189 usedParams["*"] = params._splat;
1190 const segmentPrefix = segment.prefixSegment || "";
1191 const segmentSuffix = segment.suffixSegment || "";
1192 if (!params._splat) {
1193 isMissingParams = true;
1194 if (leaveWildcards) {
1195 return `${segmentPrefix}${segment.value}${segmentSuffix}`;
1196 }
1197 if (segmentPrefix || segmentSuffix) {
1198 return `${segmentPrefix}${segmentSuffix}`;
1199 }
1200 return void 0;
1201 }
1202 const value = encodeParam("_splat");
1203 if (leaveWildcards) {
1204 return `${segmentPrefix}${segment.value}${value ?? ""}${segmentSuffix}`;
1205 }
1206 return `${segmentPrefix}${value}${segmentSuffix}`;
1207 }
1208 if (segment.type === SEGMENT_TYPE_PARAM) {
1209 const key = segment.value.substring(1);
1210 if (!isMissingParams && !(key in params)) {
1211 isMissingParams = true;
1212 }
1213 usedParams[key] = params[key];
1214 const segmentPrefix = segment.prefixSegment || "";
1215 const segmentSuffix = segment.suffixSegment || "";
1216 if (leaveParams) {
1217 const value = encodeParam(segment.value);
1218 return `${segmentPrefix}${segment.value}${value ?? ""}${segmentSuffix}`;
1219 }
1220 return `${segmentPrefix}${encodeParam(key) ?? "undefined"}${segmentSuffix}`;
1221 }
1222 if (segment.type === SEGMENT_TYPE_OPTIONAL_PARAM) {
1223 const key = segment.value.substring(1);
1224 const segmentPrefix = segment.prefixSegment || "";
1225 const segmentSuffix = segment.suffixSegment || "";
1226 if (!(key in params) || params[key] == null) {
1227 if (leaveWildcards) {
1228 return `${segmentPrefix}${key}${segmentSuffix}`;
1229 }
1230 if (segmentPrefix || segmentSuffix) {
1231 return `${segmentPrefix}${segmentSuffix}`;
1232 }
1233 return void 0;
1234 }
1235 usedParams[key] = params[key];
1236 if (leaveParams) {
1237 const value = encodeParam(segment.value);
1238 return `${segmentPrefix}${segment.value}${value ?? ""}${segmentSuffix}`;
1239 }
1240 if (leaveWildcards) {
1241 return `${segmentPrefix}${key}${encodeParam(key) ?? ""}${segmentSuffix}`;
1242 }
1243 return `${segmentPrefix}${encodeParam(key) ?? ""}${segmentSuffix}`;
1244 }
1245 return segment.value;
1246 })
1247 );
1248 return { usedParams, interpolatedPath, isMissingParams };
1249 }
1250 function encodePathParam(value, decodeCharMap) {
1251 let encoded = encodeURIComponent(value);
1252 if (decodeCharMap) {
1253 for (const [encodedChar, char] of decodeCharMap) {
1254 encoded = encoded.replaceAll(encodedChar, char);
1255 }
1256 }
1257 return encoded;
1258 }
1259 function matchPathname(currentPathname, matchLocation, parseCache) {
1260 const pathParams = matchByPath(currentPathname, matchLocation, parseCache);
1261 if (matchLocation.to && !pathParams) {
1262 return;
1263 }
1264 return pathParams ?? {};
1265 }
1266 function matchByPath(from, {
1267 to,
1268 fuzzy,
1269 caseSensitive
1270 }, parseCache) {
1271 const stringTo = to;
1272 const baseSegments = parsePathname(
1273 from.startsWith("/") ? from : `/${from}`,
1274 parseCache
1275 );
1276 const routeSegments = parsePathname(
1277 stringTo.startsWith("/") ? stringTo : `/${stringTo}`,
1278 parseCache
1279 );
1280 const params = {};
1281 const result = isMatch(
1282 baseSegments,
1283 routeSegments,
1284 params,
1285 fuzzy,
1286 caseSensitive
1287 );
1288 return result ? params : void 0;
1289 }
1290 function isMatch(baseSegments, routeSegments, params, fuzzy, caseSensitive) {
1291 let baseIndex = 0;
1292 let routeIndex = 0;
1293 while (baseIndex < baseSegments.length || routeIndex < routeSegments.length) {
1294 const baseSegment = baseSegments[baseIndex];
1295 const routeSegment = routeSegments[routeIndex];
1296 if (routeSegment) {
1297 if (routeSegment.type === SEGMENT_TYPE_WILDCARD) {
1298 const remainingBaseSegments = baseSegments.slice(baseIndex);
1299 let _splat;
1300 if (routeSegment.prefixSegment || routeSegment.suffixSegment) {
1301 if (!baseSegment) return false;
1302 const prefix2 = routeSegment.prefixSegment || "";
1303 const suffix = routeSegment.suffixSegment || "";
1304 const baseValue = baseSegment.value;
1305 if ("prefixSegment" in routeSegment) {
1306 if (!baseValue.startsWith(prefix2)) {
1307 return false;
1308 }
1309 }
1310 if ("suffixSegment" in routeSegment) {
1311 if (!baseSegments[baseSegments.length - 1]?.value.endsWith(suffix)) {
1312 return false;
1313 }
1314 }
1315 let rejoinedSplat = decodeURI(
1316 joinPaths(remainingBaseSegments.map((d) => d.value))
1317 );
1318 if (prefix2 && rejoinedSplat.startsWith(prefix2)) {
1319 rejoinedSplat = rejoinedSplat.slice(prefix2.length);
1320 }
1321 if (suffix && rejoinedSplat.endsWith(suffix)) {
1322 rejoinedSplat = rejoinedSplat.slice(
1323 0,
1324 rejoinedSplat.length - suffix.length
1325 );
1326 }
1327 _splat = rejoinedSplat;
1328 } else {
1329 _splat = decodeURI(
1330 joinPaths(remainingBaseSegments.map((d) => d.value))
1331 );
1332 }
1333 params["*"] = _splat;
1334 params["_splat"] = _splat;
1335 return true;
1336 }
1337 if (routeSegment.type === SEGMENT_TYPE_PATHNAME) {
1338 if (routeSegment.value === "/" && !baseSegment?.value) {
1339 routeIndex++;
1340 continue;
1341 }
1342 if (baseSegment) {
1343 if (caseSensitive) {
1344 if (routeSegment.value !== baseSegment.value) {
1345 return false;
1346 }
1347 } else if (routeSegment.value.toLowerCase() !== baseSegment.value.toLowerCase()) {
1348 return false;
1349 }
1350 baseIndex++;
1351 routeIndex++;
1352 continue;
1353 } else {
1354 return false;
1355 }
1356 }
1357 if (routeSegment.type === SEGMENT_TYPE_PARAM) {
1358 if (!baseSegment) {
1359 return false;
1360 }
1361 if (baseSegment.value === "/") {
1362 return false;
1363 }
1364 let _paramValue = "";
1365 let matched = false;
1366 if (routeSegment.prefixSegment || routeSegment.suffixSegment) {
1367 const prefix2 = routeSegment.prefixSegment || "";
1368 const suffix = routeSegment.suffixSegment || "";
1369 const baseValue = baseSegment.value;
1370 if (prefix2 && !baseValue.startsWith(prefix2)) {
1371 return false;
1372 }
1373 if (suffix && !baseValue.endsWith(suffix)) {
1374 return false;
1375 }
1376 let paramValue = baseValue;
1377 if (prefix2 && paramValue.startsWith(prefix2)) {
1378 paramValue = paramValue.slice(prefix2.length);
1379 }
1380 if (suffix && paramValue.endsWith(suffix)) {
1381 paramValue = paramValue.slice(0, paramValue.length - suffix.length);
1382 }
1383 _paramValue = decodeURIComponent(paramValue);
1384 matched = true;
1385 } else {
1386 _paramValue = decodeURIComponent(baseSegment.value);
1387 matched = true;
1388 }
1389 if (matched) {
1390 params[routeSegment.value.substring(1)] = _paramValue;
1391 baseIndex++;
1392 }
1393 routeIndex++;
1394 continue;
1395 }
1396 if (routeSegment.type === SEGMENT_TYPE_OPTIONAL_PARAM) {
1397 if (!baseSegment) {
1398 routeIndex++;
1399 continue;
1400 }
1401 if (baseSegment.value === "/") {
1402 routeIndex++;
1403 continue;
1404 }
1405 let _paramValue = "";
1406 let matched = false;
1407 if (routeSegment.prefixSegment || routeSegment.suffixSegment) {
1408 const prefix2 = routeSegment.prefixSegment || "";
1409 const suffix = routeSegment.suffixSegment || "";
1410 const baseValue = baseSegment.value;
1411 if ((!prefix2 || baseValue.startsWith(prefix2)) && (!suffix || baseValue.endsWith(suffix))) {
1412 let paramValue = baseValue;
1413 if (prefix2 && paramValue.startsWith(prefix2)) {
1414 paramValue = paramValue.slice(prefix2.length);
1415 }
1416 if (suffix && paramValue.endsWith(suffix)) {
1417 paramValue = paramValue.slice(
1418 0,
1419 paramValue.length - suffix.length
1420 );
1421 }
1422 _paramValue = decodeURIComponent(paramValue);
1423 matched = true;
1424 }
1425 } else {
1426 let shouldMatchOptional = true;
1427 for (let lookAhead = routeIndex + 1; lookAhead < routeSegments.length; lookAhead++) {
1428 const futureRouteSegment = routeSegments[lookAhead];
1429 if (futureRouteSegment?.type === SEGMENT_TYPE_PATHNAME && futureRouteSegment.value === baseSegment.value) {
1430 shouldMatchOptional = false;
1431 break;
1432 }
1433 if (futureRouteSegment?.type === SEGMENT_TYPE_PARAM || futureRouteSegment?.type === SEGMENT_TYPE_WILDCARD) {
1434 if (baseSegments.length < routeSegments.length) {
1435 shouldMatchOptional = false;
1436 }
1437 break;
1438 }
1439 }
1440 if (shouldMatchOptional) {
1441 _paramValue = decodeURIComponent(baseSegment.value);
1442 matched = true;
1443 }
1444 }
1445 if (matched) {
1446 params[routeSegment.value.substring(1)] = _paramValue;
1447 baseIndex++;
1448 }
1449 routeIndex++;
1450 continue;
1451 }
1452 }
1453 if (baseIndex < baseSegments.length && routeIndex >= routeSegments.length) {
1454 params["**"] = joinPaths(
1455 baseSegments.slice(baseIndex).map((d) => d.value)
1456 );
1457 return !!fuzzy && routeSegments[routeSegments.length - 1]?.value !== "/";
1458 }
1459 if (routeIndex < routeSegments.length && baseIndex >= baseSegments.length) {
1460 for (let i = routeIndex; i < routeSegments.length; i++) {
1461 if (routeSegments[i]?.type !== SEGMENT_TYPE_OPTIONAL_PARAM) {
1462 return false;
1463 }
1464 }
1465 break;
1466 }
1467 break;
1468 }
1469 return true;
1470 }
1471
1472 // node_modules/@tanstack/router-core/dist/esm/process-route-tree.js
1473 var SLASH_SCORE = 0.75;
1474 var STATIC_SEGMENT_SCORE = 1;
1475 var REQUIRED_PARAM_BASE_SCORE = 0.5;
1476 var OPTIONAL_PARAM_BASE_SCORE = 0.4;
1477 var WILDCARD_PARAM_BASE_SCORE = 0.25;
1478 var STATIC_AFTER_DYNAMIC_BONUS_SCORE = 0.2;
1479 var BOTH_PRESENCE_BASE_SCORE = 0.05;
1480 var PREFIX_PRESENCE_BASE_SCORE = 0.02;
1481 var SUFFIX_PRESENCE_BASE_SCORE = 0.01;
1482 var PREFIX_LENGTH_SCORE_MULTIPLIER = 2e-4;
1483 var SUFFIX_LENGTH_SCORE_MULTIPLIER = 1e-4;
1484 function handleParam(segment, baseScore) {
1485 if (segment.prefixSegment && segment.suffixSegment) {
1486 return baseScore + BOTH_PRESENCE_BASE_SCORE + PREFIX_LENGTH_SCORE_MULTIPLIER * segment.prefixSegment.length + SUFFIX_LENGTH_SCORE_MULTIPLIER * segment.suffixSegment.length;
1487 }
1488 if (segment.prefixSegment) {
1489 return baseScore + PREFIX_PRESENCE_BASE_SCORE + PREFIX_LENGTH_SCORE_MULTIPLIER * segment.prefixSegment.length;
1490 }
1491 if (segment.suffixSegment) {
1492 return baseScore + SUFFIX_PRESENCE_BASE_SCORE + SUFFIX_LENGTH_SCORE_MULTIPLIER * segment.suffixSegment.length;
1493 }
1494 return baseScore;
1495 }
1496 function sortRoutes(routes) {
1497 const scoredRoutes = [];
1498 routes.forEach((d, i) => {
1499 if (d.isRoot || !d.path) {
1500 return;
1501 }
1502 const trimmed = trimPathLeft(d.fullPath);
1503 let parsed = parsePathname(trimmed);
1504 let skip = 0;
1505 while (parsed.length > skip + 1 && parsed[skip]?.value === "/") {
1506 skip++;
1507 }
1508 if (skip > 0) parsed = parsed.slice(skip);
1509 let optionalParamCount = 0;
1510 let hasStaticAfter = false;
1511 const scores = parsed.map((segment, index) => {
1512 if (segment.value === "/") {
1513 return SLASH_SCORE;
1514 }
1515 if (segment.type === SEGMENT_TYPE_PATHNAME) {
1516 return STATIC_SEGMENT_SCORE;
1517 }
1518 let baseScore = void 0;
1519 if (segment.type === SEGMENT_TYPE_PARAM) {
1520 baseScore = REQUIRED_PARAM_BASE_SCORE;
1521 } else if (segment.type === SEGMENT_TYPE_OPTIONAL_PARAM) {
1522 baseScore = OPTIONAL_PARAM_BASE_SCORE;
1523 optionalParamCount++;
1524 } else {
1525 baseScore = WILDCARD_PARAM_BASE_SCORE;
1526 }
1527 for (let i2 = index + 1; i2 < parsed.length; i2++) {
1528 const nextSegment = parsed[i2];
1529 if (nextSegment.type === SEGMENT_TYPE_PATHNAME && nextSegment.value !== "/") {
1530 hasStaticAfter = true;
1531 return handleParam(
1532 segment,
1533 baseScore + STATIC_AFTER_DYNAMIC_BONUS_SCORE
1534 );
1535 }
1536 }
1537 return handleParam(segment, baseScore);
1538 });
1539 scoredRoutes.push({
1540 child: d,
1541 trimmed,
1542 parsed,
1543 index: i,
1544 scores,
1545 optionalParamCount,
1546 hasStaticAfter
1547 });
1548 });
1549 const flatRoutes = scoredRoutes.sort((a, b) => {
1550 const minLength = Math.min(a.scores.length, b.scores.length);
1551 for (let i = 0; i < minLength; i++) {
1552 if (a.scores[i] !== b.scores[i]) {
1553 return b.scores[i] - a.scores[i];
1554 }
1555 }
1556 if (a.scores.length !== b.scores.length) {
1557 if (a.optionalParamCount !== b.optionalParamCount) {
1558 if (a.hasStaticAfter === b.hasStaticAfter) {
1559 return a.optionalParamCount - b.optionalParamCount;
1560 } else if (a.hasStaticAfter && !b.hasStaticAfter) {
1561 return -1;
1562 } else if (!a.hasStaticAfter && b.hasStaticAfter) {
1563 return 1;
1564 }
1565 }
1566 return b.scores.length - a.scores.length;
1567 }
1568 for (let i = 0; i < minLength; i++) {
1569 if (a.parsed[i].value !== b.parsed[i].value) {
1570 return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
1571 }
1572 }
1573 return a.index - b.index;
1574 }).map((d, i) => {
1575 d.child.rank = i;
1576 return d.child;
1577 });
1578 return flatRoutes;
1579 }
1580 function processRouteTree({
1581 routeTree,
1582 initRoute
1583 }) {
1584 const routesById = {};
1585 const routesByPath = {};
1586 const recurseRoutes = (childRoutes) => {
1587 childRoutes.forEach((childRoute, i) => {
1588 initRoute?.(childRoute, i);
1589 const existingRoute = routesById[childRoute.id];
1590 invariant(
1591 !existingRoute,
1592 `Duplicate routes found with id: ${String(childRoute.id)}`
1593 );
1594 routesById[childRoute.id] = childRoute;
1595 if (!childRoute.isRoot && childRoute.path) {
1596 const trimmedFullPath = trimPathRight(childRoute.fullPath);
1597 if (!routesByPath[trimmedFullPath] || childRoute.fullPath.endsWith("/")) {
1598 routesByPath[trimmedFullPath] = childRoute;
1599 }
1600 }
1601 const children = childRoute.children;
1602 if (children?.length) {
1603 recurseRoutes(children);
1604 }
1605 });
1606 };
1607 recurseRoutes([routeTree]);
1608 const flatRoutes = sortRoutes(Object.values(routesById));
1609 return { routesById, routesByPath, flatRoutes };
1610 }
1611
1612 // node_modules/@tanstack/router-core/dist/esm/not-found.js
1613 function notFound(options = {}) {
1614 options.isNotFound = true;
1615 if (options.throw) throw options;
1616 return options;
1617 }
1618 function isNotFound(obj) {
1619 return !!obj?.isNotFound;
1620 }
1621
1622 // node_modules/@tanstack/router-core/dist/esm/scroll-restoration.js
1623 function getSafeSessionStorage() {
1624 try {
1625 if (typeof window !== "undefined" && typeof window.sessionStorage === "object") {
1626 return window.sessionStorage;
1627 }
1628 } catch {
1629 }
1630 return void 0;
1631 }
1632 var storageKey = "tsr-scroll-restoration-v1_3";
1633 var throttle = (fn, wait) => {
1634 let timeout;
1635 return (...args) => {
1636 if (!timeout) {
1637 timeout = setTimeout(() => {
1638 fn(...args);
1639 timeout = null;
1640 }, wait);
1641 }
1642 };
1643 };
1644 function createScrollRestorationCache() {
1645 const safeSessionStorage = getSafeSessionStorage();
1646 if (!safeSessionStorage) {
1647 return null;
1648 }
1649 const persistedState = safeSessionStorage.getItem(storageKey);
1650 let state = persistedState ? JSON.parse(persistedState) : {};
1651 return {
1652 state,
1653 // This setter is simply to make sure that we set the sessionStorage right
1654 // after the state is updated. It doesn't necessarily need to be a functional
1655 // update.
1656 set: (updater) => (state = functionalUpdate(updater, state) || state, safeSessionStorage.setItem(storageKey, JSON.stringify(state)))
1657 };
1658 }
1659 var scrollRestorationCache = createScrollRestorationCache();
1660 var defaultGetScrollRestorationKey = (location) => {
1661 return location.state.__TSR_key || location.href;
1662 };
1663 function getCssSelector(el) {
1664 const path = [];
1665 let parent;
1666 while (parent = el.parentNode) {
1667 path.push(
1668 `${el.tagName}:nth-child(${Array.prototype.indexOf.call(parent.children, el) + 1})`
1669 );
1670 el = parent;
1671 }
1672 return `${path.reverse().join(" > ")}`.toLowerCase();
1673 }
1674 var ignoreScroll = false;
1675 function restoreScroll({
1676 storageKey: storageKey2,
1677 key,
1678 behavior,
1679 shouldScrollRestoration,
1680 scrollToTopSelectors,
1681 location
1682 }) {
1683 let byKey;
1684 try {
1685 byKey = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
1686 } catch (error) {
1687 console.error(error);
1688 return;
1689 }
1690 const resolvedKey = key || window.history.state?.__TSR_key;
1691 const elementEntries = byKey[resolvedKey];
1692 ignoreScroll = true;
1693 scroll: {
1694 if (shouldScrollRestoration && elementEntries && Object.keys(elementEntries).length > 0) {
1695 for (const elementSelector in elementEntries) {
1696 const entry = elementEntries[elementSelector];
1697 if (elementSelector === "window") {
1698 window.scrollTo({
1699 top: entry.scrollY,
1700 left: entry.scrollX,
1701 behavior
1702 });
1703 } else if (elementSelector) {
1704 const element = document.querySelector(elementSelector);
1705 if (element) {
1706 element.scrollLeft = entry.scrollX;
1707 element.scrollTop = entry.scrollY;
1708 }
1709 }
1710 }
1711 break scroll;
1712 }
1713 const hash = (location ?? window.location).hash.split("#", 2)[1];
1714 if (hash) {
1715 const hashScrollIntoViewOptions = window.history.state?.__hashScrollIntoViewOptions ?? true;
1716 if (hashScrollIntoViewOptions) {
1717 const el = document.getElementById(hash);
1718 if (el) {
1719 el.scrollIntoView(hashScrollIntoViewOptions);
1720 }
1721 }
1722 break scroll;
1723 }
1724 const scrollOptions = { top: 0, left: 0, behavior };
1725 window.scrollTo(scrollOptions);
1726 if (scrollToTopSelectors) {
1727 for (const selector of scrollToTopSelectors) {
1728 if (selector === "window") continue;
1729 const element = typeof selector === "function" ? selector() : document.querySelector(selector);
1730 if (element) element.scrollTo(scrollOptions);
1731 }
1732 }
1733 }
1734 ignoreScroll = false;
1735 }
1736 function setupScrollRestoration(router, force) {
1737 if (!scrollRestorationCache && !router.isServer) {
1738 return;
1739 }
1740 const shouldScrollRestoration = force ?? router.options.scrollRestoration ?? false;
1741 if (shouldScrollRestoration) {
1742 router.isScrollRestoring = true;
1743 }
1744 if (router.isServer || router.isScrollRestorationSetup || !scrollRestorationCache) {
1745 return;
1746 }
1747 router.isScrollRestorationSetup = true;
1748 ignoreScroll = false;
1749 const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
1750 window.history.scrollRestoration = "manual";
1751 const onScroll = (event) => {
1752 if (ignoreScroll || !router.isScrollRestoring) {
1753 return;
1754 }
1755 let elementSelector = "";
1756 if (event.target === document || event.target === window) {
1757 elementSelector = "window";
1758 } else {
1759 const attrId = event.target.getAttribute(
1760 "data-scroll-restoration-id"
1761 );
1762 if (attrId) {
1763 elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
1764 } else {
1765 elementSelector = getCssSelector(event.target);
1766 }
1767 }
1768 const restoreKey = getKey(router.state.location);
1769 scrollRestorationCache.set((state) => {
1770 const keyEntry = state[restoreKey] ||= {};
1771 const elementEntry = keyEntry[elementSelector] ||= {};
1772 if (elementSelector === "window") {
1773 elementEntry.scrollX = window.scrollX || 0;
1774 elementEntry.scrollY = window.scrollY || 0;
1775 } else if (elementSelector) {
1776 const element = document.querySelector(elementSelector);
1777 if (element) {
1778 elementEntry.scrollX = element.scrollLeft || 0;
1779 elementEntry.scrollY = element.scrollTop || 0;
1780 }
1781 }
1782 return state;
1783 });
1784 };
1785 if (typeof document !== "undefined") {
1786 document.addEventListener("scroll", throttle(onScroll, 100), true);
1787 }
1788 router.subscribe("onRendered", (event) => {
1789 const cacheKey = getKey(event.toLocation);
1790 if (!router.resetNextScroll) {
1791 router.resetNextScroll = true;
1792 return;
1793 }
1794 if (typeof router.options.scrollRestoration === "function") {
1795 const shouldRestore = router.options.scrollRestoration({
1796 location: router.latestLocation
1797 });
1798 if (!shouldRestore) {
1799 return;
1800 }
1801 }
1802 restoreScroll({
1803 storageKey,
1804 key: cacheKey,
1805 behavior: router.options.scrollRestorationBehavior,
1806 shouldScrollRestoration: router.isScrollRestoring,
1807 scrollToTopSelectors: router.options.scrollToTopSelectors,
1808 location: router.history.location
1809 });
1810 if (router.isScrollRestoring) {
1811 scrollRestorationCache.set((state) => {
1812 state[cacheKey] ||= {};
1813 return state;
1814 });
1815 }
1816 });
1817 }
1818 function handleHashScroll(router) {
1819 if (typeof document !== "undefined" && document.querySelector) {
1820 const hashScrollIntoViewOptions = router.state.location.state.__hashScrollIntoViewOptions ?? true;
1821 if (hashScrollIntoViewOptions && router.state.location.hash !== "") {
1822 const el = document.getElementById(router.state.location.hash);
1823 if (el) {
1824 el.scrollIntoView(hashScrollIntoViewOptions);
1825 }
1826 }
1827 }
1828 }
1829
1830 // node_modules/@tanstack/router-core/dist/esm/qss.js
1831 function encode(obj, stringify = String) {
1832 const result = new URLSearchParams();
1833 for (const key in obj) {
1834 const val = obj[key];
1835 if (val !== void 0) {
1836 result.set(key, stringify(val));
1837 }
1838 }
1839 return result.toString();
1840 }
1841 function toValue(str) {
1842 if (!str) return "";
1843 if (str === "false") return false;
1844 if (str === "true") return true;
1845 return +str * 0 === 0 && +str + "" === str ? +str : str;
1846 }
1847 function decode(str) {
1848 const searchParams = new URLSearchParams(str);
1849 const result = {};
1850 for (const [key, value] of searchParams.entries()) {
1851 const previousValue = result[key];
1852 if (previousValue == null) {
1853 result[key] = toValue(value);
1854 } else if (Array.isArray(previousValue)) {
1855 previousValue.push(toValue(value));
1856 } else {
1857 result[key] = [previousValue, toValue(value)];
1858 }
1859 }
1860 return result;
1861 }
1862
1863 // node_modules/@tanstack/router-core/dist/esm/searchParams.js
1864 var defaultParseSearch = parseSearchWith(JSON.parse);
1865 var defaultStringifySearch = stringifySearchWith(
1866 JSON.stringify,
1867 JSON.parse
1868 );
1869 function parseSearchWith(parser) {
1870 return (searchStr) => {
1871 if (searchStr[0] === "?") {
1872 searchStr = searchStr.substring(1);
1873 }
1874 const query = decode(searchStr);
1875 for (const key in query) {
1876 const value = query[key];
1877 if (typeof value === "string") {
1878 try {
1879 query[key] = parser(value);
1880 } catch (_err) {
1881 }
1882 }
1883 }
1884 return query;
1885 };
1886 }
1887 function stringifySearchWith(stringify, parser) {
1888 const hasParser = typeof parser === "function";
1889 function stringifyValue(val) {
1890 if (typeof val === "object" && val !== null) {
1891 try {
1892 return stringify(val);
1893 } catch (_err) {
1894 }
1895 } else if (hasParser && typeof val === "string") {
1896 try {
1897 parser(val);
1898 return stringify(val);
1899 } catch (_err) {
1900 }
1901 }
1902 return val;
1903 }
1904 return (search) => {
1905 const searchStr = encode(search, stringifyValue);
1906 return searchStr ? `?${searchStr}` : "";
1907 };
1908 }
1909
1910 // node_modules/@tanstack/router-core/dist/esm/root.js
1911 var rootRouteId = "__root__";
1912
1913 // node_modules/@tanstack/router-core/dist/esm/redirect.js
1914 function redirect(opts) {
1915 opts.statusCode = opts.statusCode || opts.code || 307;
1916 if (!opts.reloadDocument && typeof opts.href === "string") {
1917 try {
1918 new URL(opts.href);
1919 opts.reloadDocument = true;
1920 } catch {
1921 }
1922 }
1923 const headers = new Headers(opts.headers);
1924 if (opts.href && headers.get("Location") === null) {
1925 headers.set("Location", opts.href);
1926 }
1927 const response = new Response(null, {
1928 status: opts.statusCode,
1929 headers
1930 });
1931 response.options = opts;
1932 if (opts.throw) {
1933 throw response;
1934 }
1935 return response;
1936 }
1937 function isRedirect(obj) {
1938 return obj instanceof Response && !!obj.options;
1939 }
1940
1941 // node_modules/@tanstack/router-core/dist/esm/lru-cache.js
1942 function createLRUCache(max) {
1943 const cache = /* @__PURE__ */ new Map();
1944 let oldest;
1945 let newest;
1946 const touch = (entry) => {
1947 if (!entry.next) return;
1948 if (!entry.prev) {
1949 entry.next.prev = void 0;
1950 oldest = entry.next;
1951 entry.next = void 0;
1952 if (newest) {
1953 entry.prev = newest;
1954 newest.next = entry;
1955 }
1956 } else {
1957 entry.prev.next = entry.next;
1958 entry.next.prev = entry.prev;
1959 entry.next = void 0;
1960 if (newest) {
1961 newest.next = entry;
1962 entry.prev = newest;
1963 }
1964 }
1965 newest = entry;
1966 };
1967 return {
1968 get(key) {
1969 const entry = cache.get(key);
1970 if (!entry) return void 0;
1971 touch(entry);
1972 return entry.value;
1973 },
1974 set(key, value) {
1975 if (cache.size >= max && oldest) {
1976 const toDelete = oldest;
1977 cache.delete(toDelete.key);
1978 if (toDelete.next) {
1979 oldest = toDelete.next;
1980 toDelete.next.prev = void 0;
1981 }
1982 if (toDelete === newest) {
1983 newest = void 0;
1984 }
1985 }
1986 const existing = cache.get(key);
1987 if (existing) {
1988 existing.value = value;
1989 touch(existing);
1990 } else {
1991 const entry = { key, value, prev: newest };
1992 if (newest) newest.next = entry;
1993 newest = entry;
1994 if (!oldest) oldest = entry;
1995 cache.set(key, entry);
1996 }
1997 }
1998 };
1999 }
2000
2001 // node_modules/@tanstack/router-core/dist/esm/load-matches.js
2002 var triggerOnReady = (inner) => {
2003 if (!inner.rendered) {
2004 inner.rendered = true;
2005 return inner.onReady?.();
2006 }
2007 };
2008 var resolvePreload = (inner, matchId) => {
2009 return !!(inner.preload && !inner.router.state.matches.some((d) => d.id === matchId));
2010 };
2011 var _handleNotFound = (inner, err) => {
2012 const routeCursor = inner.router.routesById[err.routeId ?? ""] ?? inner.router.routeTree;
2013 if (!routeCursor.options.notFoundComponent && inner.router.options?.defaultNotFoundComponent) {
2014 routeCursor.options.notFoundComponent = inner.router.options.defaultNotFoundComponent;
2015 }
2016 invariant(
2017 routeCursor.options.notFoundComponent,
2018 "No notFoundComponent found. Please set a notFoundComponent on your route or provide a defaultNotFoundComponent to the router."
2019 );
2020 const matchForRoute = inner.matches.find((m) => m.routeId === routeCursor.id);
2021 invariant(matchForRoute, "Could not find match for route: " + routeCursor.id);
2022 inner.updateMatch(matchForRoute.id, (prev) => ({
2023 ...prev,
2024 status: "notFound",
2025 error: err,
2026 isFetching: false
2027 }));
2028 if (err.routerCode === "BEFORE_LOAD" && routeCursor.parentRoute) {
2029 err.routeId = routeCursor.parentRoute.id;
2030 _handleNotFound(inner, err);
2031 }
2032 };
2033 var handleRedirectAndNotFound = (inner, match, err) => {
2034 if (!isRedirect(err) && !isNotFound(err)) return;
2035 if (isRedirect(err) && err.redirectHandled && !err.options.reloadDocument) {
2036 throw err;
2037 }
2038 if (match) {
2039 match._nonReactive.beforeLoadPromise?.resolve();
2040 match._nonReactive.loaderPromise?.resolve();
2041 match._nonReactive.beforeLoadPromise = void 0;
2042 match._nonReactive.loaderPromise = void 0;
2043 const status = isRedirect(err) ? "redirected" : "notFound";
2044 inner.updateMatch(match.id, (prev) => ({
2045 ...prev,
2046 status,
2047 isFetching: false,
2048 error: err
2049 }));
2050 if (isNotFound(err) && !err.routeId) {
2051 err.routeId = match.routeId;
2052 }
2053 match._nonReactive.loadPromise?.resolve();
2054 }
2055 if (isRedirect(err)) {
2056 inner.rendered = true;
2057 err.options._fromLocation = inner.location;
2058 err.redirectHandled = true;
2059 err = inner.router.resolveRedirect(err);
2060 throw err;
2061 } else {
2062 _handleNotFound(inner, err);
2063 throw err;
2064 }
2065 };
2066 var shouldSkipLoader = (inner, matchId) => {
2067 const match = inner.router.getMatch(matchId);
2068 if (!inner.router.isServer && match._nonReactive.dehydrated) {
2069 return true;
2070 }
2071 if (inner.router.isServer && match.ssr === false) {
2072 return true;
2073 }
2074 return false;
2075 };
2076 var handleSerialError = (inner, index, err, routerCode) => {
2077 const { id: matchId, routeId } = inner.matches[index];
2078 const route = inner.router.looseRoutesById[routeId];
2079 if (err instanceof Promise) {
2080 throw err;
2081 }
2082 err.routerCode = routerCode;
2083 inner.firstBadMatchIndex ??= index;
2084 handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err);
2085 try {
2086 route.options.onError?.(err);
2087 } catch (errorHandlerErr) {
2088 err = errorHandlerErr;
2089 handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err);
2090 }
2091 inner.updateMatch(matchId, (prev) => {
2092 prev._nonReactive.beforeLoadPromise?.resolve();
2093 prev._nonReactive.beforeLoadPromise = void 0;
2094 prev._nonReactive.loadPromise?.resolve();
2095 return {
2096 ...prev,
2097 error: err,
2098 status: "error",
2099 isFetching: false,
2100 updatedAt: Date.now(),
2101 abortController: new AbortController()
2102 };
2103 });
2104 };
2105 var isBeforeLoadSsr = (inner, matchId, index, route) => {
2106 const existingMatch = inner.router.getMatch(matchId);
2107 const parentMatchId = inner.matches[index - 1]?.id;
2108 const parentMatch = parentMatchId ? inner.router.getMatch(parentMatchId) : void 0;
2109 if (inner.router.isShell()) {
2110 existingMatch.ssr = matchId === rootRouteId;
2111 return;
2112 }
2113 if (parentMatch?.ssr === false) {
2114 existingMatch.ssr = false;
2115 return;
2116 }
2117 const parentOverride = (tempSsr2) => {
2118 if (tempSsr2 === true && parentMatch?.ssr === "data-only") {
2119 return "data-only";
2120 }
2121 return tempSsr2;
2122 };
2123 const defaultSsr = inner.router.options.defaultSsr ?? true;
2124 if (route.options.ssr === void 0) {
2125 existingMatch.ssr = parentOverride(defaultSsr);
2126 return;
2127 }
2128 if (typeof route.options.ssr !== "function") {
2129 existingMatch.ssr = parentOverride(route.options.ssr);
2130 return;
2131 }
2132 const { search, params } = existingMatch;
2133 const ssrFnContext = {
2134 search: makeMaybe(search, existingMatch.searchError),
2135 params: makeMaybe(params, existingMatch.paramsError),
2136 location: inner.location,
2137 matches: inner.matches.map((match) => ({
2138 index: match.index,
2139 pathname: match.pathname,
2140 fullPath: match.fullPath,
2141 staticData: match.staticData,
2142 id: match.id,
2143 routeId: match.routeId,
2144 search: makeMaybe(match.search, match.searchError),
2145 params: makeMaybe(match.params, match.paramsError),
2146 ssr: match.ssr
2147 }))
2148 };
2149 const tempSsr = route.options.ssr(ssrFnContext);
2150 if (isPromise(tempSsr)) {
2151 return tempSsr.then((ssr) => {
2152 existingMatch.ssr = parentOverride(ssr ?? defaultSsr);
2153 });
2154 }
2155 existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr);
2156 return;
2157 };
2158 var setupPendingTimeout = (inner, matchId, route, match) => {
2159 if (match._nonReactive.pendingTimeout !== void 0) return;
2160 const pendingMs = route.options.pendingMs ?? inner.router.options.defaultPendingMs;
2161 const shouldPending = !!(inner.onReady && !inner.router.isServer && !resolvePreload(inner, matchId) && (route.options.loader || route.options.beforeLoad || routeNeedsPreload(route)) && typeof pendingMs === "number" && pendingMs !== Infinity && (route.options.pendingComponent ?? inner.router.options?.defaultPendingComponent));
2162 if (shouldPending) {
2163 const pendingTimeout = setTimeout(() => {
2164 triggerOnReady(inner);
2165 }, pendingMs);
2166 match._nonReactive.pendingTimeout = pendingTimeout;
2167 }
2168 };
2169 var preBeforeLoadSetup = (inner, matchId, route) => {
2170 const existingMatch = inner.router.getMatch(matchId);
2171 if (!existingMatch._nonReactive.beforeLoadPromise && !existingMatch._nonReactive.loaderPromise)
2172 return;
2173 setupPendingTimeout(inner, matchId, route, existingMatch);
2174 const then = () => {
2175 const match = inner.router.getMatch(matchId);
2176 if (match.preload && (match.status === "redirected" || match.status === "notFound")) {
2177 handleRedirectAndNotFound(inner, match, match.error);
2178 }
2179 };
2180 return existingMatch._nonReactive.beforeLoadPromise ? existingMatch._nonReactive.beforeLoadPromise.then(then) : then();
2181 };
2182 var executeBeforeLoad = (inner, matchId, index, route) => {
2183 const match = inner.router.getMatch(matchId);
2184 const prevLoadPromise = match._nonReactive.loadPromise;
2185 match._nonReactive.loadPromise = createControlledPromise(() => {
2186 prevLoadPromise?.resolve();
2187 });
2188 const { paramsError, searchError } = match;
2189 if (paramsError) {
2190 handleSerialError(inner, index, paramsError, "PARSE_PARAMS");
2191 }
2192 if (searchError) {
2193 handleSerialError(inner, index, searchError, "VALIDATE_SEARCH");
2194 }
2195 setupPendingTimeout(inner, matchId, route, match);
2196 const abortController = new AbortController();
2197 const parentMatchId = inner.matches[index - 1]?.id;
2198 const parentMatch = parentMatchId ? inner.router.getMatch(parentMatchId) : void 0;
2199 const parentMatchContext = parentMatch?.context ?? inner.router.options.context ?? void 0;
2200 const context = { ...parentMatchContext, ...match.__routeContext };
2201 let isPending = false;
2202 const pending = () => {
2203 if (isPending) return;
2204 isPending = true;
2205 inner.updateMatch(matchId, (prev) => ({
2206 ...prev,
2207 isFetching: "beforeLoad",
2208 fetchCount: prev.fetchCount + 1,
2209 abortController,
2210 context
2211 }));
2212 };
2213 const resolve = () => {
2214 match._nonReactive.beforeLoadPromise?.resolve();
2215 match._nonReactive.beforeLoadPromise = void 0;
2216 inner.updateMatch(matchId, (prev) => ({
2217 ...prev,
2218 isFetching: false
2219 }));
2220 };
2221 if (!route.options.beforeLoad) {
2222 batch(() => {
2223 pending();
2224 resolve();
2225 });
2226 return;
2227 }
2228 match._nonReactive.beforeLoadPromise = createControlledPromise();
2229 const { search, params, cause } = match;
2230 const preload = resolvePreload(inner, matchId);
2231 const beforeLoadFnContext = {
2232 search,
2233 abortController,
2234 params,
2235 preload,
2236 context,
2237 location: inner.location,
2238 navigate: (opts) => inner.router.navigate({
2239 ...opts,
2240 _fromLocation: inner.location
2241 }),
2242 buildLocation: inner.router.buildLocation,
2243 cause: preload ? "preload" : cause,
2244 matches: inner.matches,
2245 ...inner.router.options.additionalContext
2246 };
2247 const updateContext = (beforeLoadContext2) => {
2248 if (beforeLoadContext2 === void 0) {
2249 batch(() => {
2250 pending();
2251 resolve();
2252 });
2253 return;
2254 }
2255 if (isRedirect(beforeLoadContext2) || isNotFound(beforeLoadContext2)) {
2256 pending();
2257 handleSerialError(inner, index, beforeLoadContext2, "BEFORE_LOAD");
2258 }
2259 batch(() => {
2260 pending();
2261 inner.updateMatch(matchId, (prev) => ({
2262 ...prev,
2263 __beforeLoadContext: beforeLoadContext2,
2264 context: {
2265 ...prev.context,
2266 ...beforeLoadContext2
2267 }
2268 }));
2269 resolve();
2270 });
2271 };
2272 let beforeLoadContext;
2273 try {
2274 beforeLoadContext = route.options.beforeLoad(beforeLoadFnContext);
2275 if (isPromise(beforeLoadContext)) {
2276 pending();
2277 return beforeLoadContext.catch((err) => {
2278 handleSerialError(inner, index, err, "BEFORE_LOAD");
2279 }).then(updateContext);
2280 }
2281 } catch (err) {
2282 pending();
2283 handleSerialError(inner, index, err, "BEFORE_LOAD");
2284 }
2285 updateContext(beforeLoadContext);
2286 return;
2287 };
2288 var handleBeforeLoad = (inner, index) => {
2289 const { id: matchId, routeId } = inner.matches[index];
2290 const route = inner.router.looseRoutesById[routeId];
2291 const serverSsr = () => {
2292 if (inner.router.isServer) {
2293 const maybePromise = isBeforeLoadSsr(inner, matchId, index, route);
2294 if (isPromise(maybePromise)) return maybePromise.then(queueExecution);
2295 }
2296 return queueExecution();
2297 };
2298 const execute = () => executeBeforeLoad(inner, matchId, index, route);
2299 const queueExecution = () => {
2300 if (shouldSkipLoader(inner, matchId)) return;
2301 const result = preBeforeLoadSetup(inner, matchId, route);
2302 return isPromise(result) ? result.then(execute) : execute();
2303 };
2304 return serverSsr();
2305 };
2306 var executeHead = (inner, matchId, route) => {
2307 const match = inner.router.getMatch(matchId);
2308 if (!match) {
2309 return;
2310 }
2311 if (!route.options.head && !route.options.scripts && !route.options.headers) {
2312 return;
2313 }
2314 const assetContext = {
2315 matches: inner.matches,
2316 match,
2317 params: match.params,
2318 loaderData: match.loaderData
2319 };
2320 return Promise.all([
2321 route.options.head?.(assetContext),
2322 route.options.scripts?.(assetContext),
2323 route.options.headers?.(assetContext)
2324 ]).then(([headFnContent, scripts, headers]) => {
2325 const meta = headFnContent?.meta;
2326 const links = headFnContent?.links;
2327 const headScripts = headFnContent?.scripts;
2328 const styles = headFnContent?.styles;
2329 return {
2330 meta,
2331 links,
2332 headScripts,
2333 headers,
2334 scripts,
2335 styles
2336 };
2337 });
2338 };
2339 var getLoaderContext = (inner, matchId, index, route) => {
2340 const parentMatchPromise = inner.matchPromises[index - 1];
2341 const { params, loaderDeps, abortController, context, cause } = inner.router.getMatch(matchId);
2342 const preload = resolvePreload(inner, matchId);
2343 return {
2344 params,
2345 deps: loaderDeps,
2346 preload: !!preload,
2347 parentMatchPromise,
2348 abortController,
2349 context,
2350 location: inner.location,
2351 navigate: (opts) => inner.router.navigate({
2352 ...opts,
2353 _fromLocation: inner.location
2354 }),
2355 cause: preload ? "preload" : cause,
2356 route,
2357 ...inner.router.options.additionalContext
2358 };
2359 };
2360 var runLoader = async (inner, matchId, index, route) => {
2361 try {
2362 const match = inner.router.getMatch(matchId);
2363 try {
2364 if (!inner.router.isServer || match.ssr === true) {
2365 loadRouteChunk(route);
2366 }
2367 const loaderResult = route.options.loader?.(
2368 getLoaderContext(inner, matchId, index, route)
2369 );
2370 const loaderResultIsPromise = route.options.loader && isPromise(loaderResult);
2371 const willLoadSomething = !!(loaderResultIsPromise || route._lazyPromise || route._componentsPromise || route.options.head || route.options.scripts || route.options.headers || match._nonReactive.minPendingPromise);
2372 if (willLoadSomething) {
2373 inner.updateMatch(matchId, (prev) => ({
2374 ...prev,
2375 isFetching: "loader"
2376 }));
2377 }
2378 if (route.options.loader) {
2379 const loaderData = loaderResultIsPromise ? await loaderResult : loaderResult;
2380 handleRedirectAndNotFound(
2381 inner,
2382 inner.router.getMatch(matchId),
2383 loaderData
2384 );
2385 if (loaderData !== void 0) {
2386 inner.updateMatch(matchId, (prev) => ({
2387 ...prev,
2388 loaderData
2389 }));
2390 }
2391 }
2392 if (route._lazyPromise) await route._lazyPromise;
2393 const headResult = executeHead(inner, matchId, route);
2394 const head = headResult ? await headResult : void 0;
2395 const pendingPromise = match._nonReactive.minPendingPromise;
2396 if (pendingPromise) await pendingPromise;
2397 if (route._componentsPromise) await route._componentsPromise;
2398 inner.updateMatch(matchId, (prev) => ({
2399 ...prev,
2400 error: void 0,
2401 status: "success",
2402 isFetching: false,
2403 updatedAt: Date.now(),
2404 ...head
2405 }));
2406 } catch (e) {
2407 let error = e;
2408 const pendingPromise = match._nonReactive.minPendingPromise;
2409 if (pendingPromise) await pendingPromise;
2410 if (isNotFound(e)) {
2411 await route.options.notFoundComponent?.preload?.();
2412 }
2413 handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), e);
2414 try {
2415 route.options.onError?.(e);
2416 } catch (onErrorError) {
2417 error = onErrorError;
2418 handleRedirectAndNotFound(
2419 inner,
2420 inner.router.getMatch(matchId),
2421 onErrorError
2422 );
2423 }
2424 const headResult = executeHead(inner, matchId, route);
2425 const head = headResult ? await headResult : void 0;
2426 inner.updateMatch(matchId, (prev) => ({
2427 ...prev,
2428 error,
2429 status: "error",
2430 isFetching: false,
2431 ...head
2432 }));
2433 }
2434 } catch (err) {
2435 const match = inner.router.getMatch(matchId);
2436 if (match) {
2437 const headResult = executeHead(inner, matchId, route);
2438 if (headResult) {
2439 const head = await headResult;
2440 inner.updateMatch(matchId, (prev) => ({
2441 ...prev,
2442 ...head
2443 }));
2444 }
2445 match._nonReactive.loaderPromise = void 0;
2446 }
2447 handleRedirectAndNotFound(inner, match, err);
2448 }
2449 };
2450 var loadRouteMatch = async (inner, index) => {
2451 const { id: matchId, routeId } = inner.matches[index];
2452 let loaderShouldRunAsync = false;
2453 let loaderIsRunningAsync = false;
2454 const route = inner.router.looseRoutesById[routeId];
2455 if (shouldSkipLoader(inner, matchId)) {
2456 if (inner.router.isServer) {
2457 const headResult = executeHead(inner, matchId, route);
2458 if (headResult) {
2459 const head = await headResult;
2460 inner.updateMatch(matchId, (prev) => ({
2461 ...prev,
2462 ...head
2463 }));
2464 }
2465 return inner.router.getMatch(matchId);
2466 }
2467 } else {
2468 const prevMatch = inner.router.getMatch(matchId);
2469 if (prevMatch._nonReactive.loaderPromise) {
2470 if (prevMatch.status === "success" && !inner.sync && !prevMatch.preload) {
2471 return prevMatch;
2472 }
2473 await prevMatch._nonReactive.loaderPromise;
2474 const match2 = inner.router.getMatch(matchId);
2475 if (match2.error) {
2476 handleRedirectAndNotFound(inner, match2, match2.error);
2477 }
2478 } else {
2479 const age = Date.now() - prevMatch.updatedAt;
2480 const preload = resolvePreload(inner, matchId);
2481 const staleAge = preload ? route.options.preloadStaleTime ?? inner.router.options.defaultPreloadStaleTime ?? 3e4 : route.options.staleTime ?? inner.router.options.defaultStaleTime ?? 0;
2482 const shouldReloadOption = route.options.shouldReload;
2483 const shouldReload = typeof shouldReloadOption === "function" ? shouldReloadOption(getLoaderContext(inner, matchId, index, route)) : shouldReloadOption;
2484 const nextPreload = !!preload && !inner.router.state.matches.some((d) => d.id === matchId);
2485 const match2 = inner.router.getMatch(matchId);
2486 match2._nonReactive.loaderPromise = createControlledPromise();
2487 if (nextPreload !== match2.preload) {
2488 inner.updateMatch(matchId, (prev) => ({
2489 ...prev,
2490 preload: nextPreload
2491 }));
2492 }
2493 const { status, invalid } = match2;
2494 loaderShouldRunAsync = status === "success" && (invalid || (shouldReload ?? age > staleAge));
2495 if (preload && route.options.preload === false) ;
2496 else if (loaderShouldRunAsync && !inner.sync) {
2497 loaderIsRunningAsync = true;
2498 (async () => {
2499 try {
2500 await runLoader(inner, matchId, index, route);
2501 const match3 = inner.router.getMatch(matchId);
2502 match3._nonReactive.loaderPromise?.resolve();
2503 match3._nonReactive.loadPromise?.resolve();
2504 match3._nonReactive.loaderPromise = void 0;
2505 } catch (err) {
2506 if (isRedirect(err)) {
2507 await inner.router.navigate(err.options);
2508 }
2509 }
2510 })();
2511 } else if (status !== "success" || loaderShouldRunAsync && inner.sync) {
2512 await runLoader(inner, matchId, index, route);
2513 } else {
2514 const headResult = executeHead(inner, matchId, route);
2515 if (headResult) {
2516 const head = await headResult;
2517 inner.updateMatch(matchId, (prev) => ({
2518 ...prev,
2519 ...head
2520 }));
2521 }
2522 }
2523 }
2524 }
2525 const match = inner.router.getMatch(matchId);
2526 if (!loaderIsRunningAsync) {
2527 match._nonReactive.loaderPromise?.resolve();
2528 match._nonReactive.loadPromise?.resolve();
2529 }
2530 clearTimeout(match._nonReactive.pendingTimeout);
2531 match._nonReactive.pendingTimeout = void 0;
2532 if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = void 0;
2533 match._nonReactive.dehydrated = void 0;
2534 const nextIsFetching = loaderIsRunningAsync ? match.isFetching : false;
2535 if (nextIsFetching !== match.isFetching || match.invalid !== false) {
2536 inner.updateMatch(matchId, (prev) => ({
2537 ...prev,
2538 isFetching: nextIsFetching,
2539 invalid: false
2540 }));
2541 return inner.router.getMatch(matchId);
2542 } else {
2543 return match;
2544 }
2545 };
2546 async function loadMatches(arg) {
2547 const inner = Object.assign(arg, {
2548 matchPromises: []
2549 });
2550 if (!inner.router.isServer && inner.router.state.matches.some((d) => d._forcePending)) {
2551 triggerOnReady(inner);
2552 }
2553 try {
2554 for (let i = 0; i < inner.matches.length; i++) {
2555 const beforeLoad = handleBeforeLoad(inner, i);
2556 if (isPromise(beforeLoad)) await beforeLoad;
2557 }
2558 const max = inner.firstBadMatchIndex ?? inner.matches.length;
2559 for (let i = 0; i < max; i++) {
2560 inner.matchPromises.push(loadRouteMatch(inner, i));
2561 }
2562 await Promise.all(inner.matchPromises);
2563 const readyPromise = triggerOnReady(inner);
2564 if (isPromise(readyPromise)) await readyPromise;
2565 } catch (err) {
2566 if (isNotFound(err) && !inner.preload) {
2567 const readyPromise = triggerOnReady(inner);
2568 if (isPromise(readyPromise)) await readyPromise;
2569 throw err;
2570 }
2571 if (isRedirect(err)) {
2572 throw err;
2573 }
2574 }
2575 return inner.matches;
2576 }
2577 async function loadRouteChunk(route) {
2578 if (!route._lazyLoaded && route._lazyPromise === void 0) {
2579 if (route.lazyFn) {
2580 route._lazyPromise = route.lazyFn().then((lazyRoute) => {
2581 const { id: _id, ...options } = lazyRoute.options;
2582 Object.assign(route.options, options);
2583 route._lazyLoaded = true;
2584 route._lazyPromise = void 0;
2585 });
2586 } else {
2587 route._lazyLoaded = true;
2588 }
2589 }
2590 if (!route._componentsLoaded && route._componentsPromise === void 0) {
2591 const loadComponents = () => {
2592 const preloads = [];
2593 for (const type of componentTypes) {
2594 const preload = route.options[type]?.preload;
2595 if (preload) preloads.push(preload());
2596 }
2597 if (preloads.length)
2598 return Promise.all(preloads).then(() => {
2599 route._componentsLoaded = true;
2600 route._componentsPromise = void 0;
2601 });
2602 route._componentsLoaded = true;
2603 route._componentsPromise = void 0;
2604 return;
2605 };
2606 route._componentsPromise = route._lazyPromise ? route._lazyPromise.then(loadComponents) : loadComponents();
2607 }
2608 return route._componentsPromise;
2609 }
2610 function makeMaybe(value, error) {
2611 if (error) {
2612 return { status: "error", error };
2613 }
2614 return { status: "success", value };
2615 }
2616 function routeNeedsPreload(route) {
2617 for (const componentType of componentTypes) {
2618 if (route.options[componentType]?.preload) {
2619 return true;
2620 }
2621 }
2622 return false;
2623 }
2624 var componentTypes = [
2625 "component",
2626 "errorComponent",
2627 "pendingComponent",
2628 "notFoundComponent"
2629 ];
2630
2631 // node_modules/@tanstack/router-core/dist/esm/rewrite.js
2632 function composeRewrites(rewrites) {
2633 return {
2634 input: ({ url }) => {
2635 for (const rewrite of rewrites) {
2636 url = executeRewriteInput(rewrite, url);
2637 }
2638 return url;
2639 },
2640 output: ({ url }) => {
2641 for (let i = rewrites.length - 1; i >= 0; i--) {
2642 url = executeRewriteOutput(rewrites[i], url);
2643 }
2644 return url;
2645 }
2646 };
2647 }
2648 function rewriteBasepath(opts) {
2649 const trimmedBasepath = trimPath(opts.basepath);
2650 const normalizedBasepath = `/${trimmedBasepath}`;
2651 const normalizedBasepathWithSlash = `${normalizedBasepath}/`;
2652 const checkBasepath = opts.caseSensitive ? normalizedBasepath : normalizedBasepath.toLowerCase();
2653 const checkBasepathWithSlash = opts.caseSensitive ? normalizedBasepathWithSlash : normalizedBasepathWithSlash.toLowerCase();
2654 return {
2655 input: ({ url }) => {
2656 const pathname = opts.caseSensitive ? url.pathname : url.pathname.toLowerCase();
2657 if (pathname === checkBasepath) {
2658 url.pathname = "/";
2659 } else if (pathname.startsWith(checkBasepathWithSlash)) {
2660 url.pathname = url.pathname.slice(normalizedBasepath.length);
2661 }
2662 return url;
2663 },
2664 output: ({ url }) => {
2665 url.pathname = joinPaths(["/", trimmedBasepath, url.pathname]);
2666 return url;
2667 }
2668 };
2669 }
2670 function executeRewriteInput(rewrite, url) {
2671 const res = rewrite?.input?.({ url });
2672 if (res) {
2673 if (typeof res === "string") {
2674 return new URL(res);
2675 } else if (res instanceof URL) {
2676 return res;
2677 }
2678 }
2679 return url;
2680 }
2681 function executeRewriteOutput(rewrite, url) {
2682 const res = rewrite?.output?.({ url });
2683 if (res) {
2684 if (typeof res === "string") {
2685 return new URL(res);
2686 } else if (res instanceof URL) {
2687 return res;
2688 }
2689 }
2690 return url;
2691 }
2692
2693 // node_modules/@tanstack/router-core/dist/esm/router.js
2694 function getLocationChangeInfo(routerState) {
2695 const fromLocation = routerState.resolvedLocation;
2696 const toLocation = routerState.location;
2697 const pathChanged = fromLocation?.pathname !== toLocation.pathname;
2698 const hrefChanged = fromLocation?.href !== toLocation.href;
2699 const hashChanged = fromLocation?.hash !== toLocation.hash;
2700 return { fromLocation, toLocation, pathChanged, hrefChanged, hashChanged };
2701 }
2702 var RouterCore = class {
2703 /**
2704 * @deprecated Use the `createRouter` function instead
2705 */
2706 constructor(options) {
2707 this.tempLocationKey = `${Math.round(
2708 Math.random() * 1e7
2709 )}`;
2710 this.resetNextScroll = true;
2711 this.shouldViewTransition = void 0;
2712 this.isViewTransitionTypesSupported = void 0;
2713 this.subscribers = /* @__PURE__ */ new Set();
2714 this.isScrollRestoring = false;
2715 this.isScrollRestorationSetup = false;
2716 this.startTransition = (fn) => fn();
2717 this.update = (newOptions) => {
2718 if (newOptions.notFoundRoute) {
2719 console.warn(
2720 "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."
2721 );
2722 }
2723 const prevOptions = this.options;
2724 const prevBasepath = this.basepath ?? prevOptions?.basepath ?? "/";
2725 const basepathWasUnset = this.basepath === void 0;
2726 const prevRewriteOption = prevOptions?.rewrite;
2727 this.options = {
2728 ...prevOptions,
2729 ...newOptions
2730 };
2731 this.isServer = this.options.isServer ?? typeof document === "undefined";
2732 this.pathParamsDecodeCharMap = this.options.pathParamsAllowedCharacters ? new Map(
2733 this.options.pathParamsAllowedCharacters.map((char) => [
2734 encodeURIComponent(char),
2735 char
2736 ])
2737 ) : void 0;
2738 if (!this.history || this.options.history && this.options.history !== this.history) {
2739 if (!this.options.history) {
2740 if (!this.isServer) {
2741 this.history = createBrowserHistory();
2742 }
2743 } else {
2744 this.history = this.options.history;
2745 }
2746 }
2747 this.origin = this.options.origin;
2748 if (!this.origin) {
2749 if (!this.isServer && window?.origin && window.origin !== "null") {
2750 this.origin = window.origin;
2751 } else {
2752 this.origin = "http://localhost";
2753 }
2754 }
2755 if (this.history) {
2756 this.updateLatestLocation();
2757 }
2758 if (this.options.routeTree !== this.routeTree) {
2759 this.routeTree = this.options.routeTree;
2760 this.buildRouteTree();
2761 }
2762 if (!this.__store && this.latestLocation) {
2763 this.__store = new Store(getInitialRouterState(this.latestLocation), {
2764 onUpdate: () => {
2765 this.__store.state = {
2766 ...this.state,
2767 cachedMatches: this.state.cachedMatches.filter(
2768 (d) => !["redirected"].includes(d.status)
2769 )
2770 };
2771 }
2772 });
2773 setupScrollRestoration(this);
2774 }
2775 let needsLocationUpdate = false;
2776 const nextBasepath = this.options.basepath ?? "/";
2777 const nextRewriteOption = this.options.rewrite;
2778 const basepathChanged = basepathWasUnset || prevBasepath !== nextBasepath;
2779 const rewriteChanged = prevRewriteOption !== nextRewriteOption;
2780 if (basepathChanged || rewriteChanged) {
2781 this.basepath = nextBasepath;
2782 const rewrites = [];
2783 if (trimPath(nextBasepath) !== "") {
2784 rewrites.push(
2785 rewriteBasepath({
2786 basepath: nextBasepath
2787 })
2788 );
2789 }
2790 if (nextRewriteOption) {
2791 rewrites.push(nextRewriteOption);
2792 }
2793 this.rewrite = rewrites.length === 0 ? void 0 : rewrites.length === 1 ? rewrites[0] : composeRewrites(rewrites);
2794 if (this.history) {
2795 this.updateLatestLocation();
2796 }
2797 needsLocationUpdate = true;
2798 }
2799 if (needsLocationUpdate && this.__store) {
2800 this.__store.state = {
2801 ...this.state,
2802 location: this.latestLocation
2803 };
2804 }
2805 if (typeof window !== "undefined" && "CSS" in window && typeof window.CSS?.supports === "function") {
2806 this.isViewTransitionTypesSupported = window.CSS.supports(
2807 "selector(:active-view-transition-type(a)"
2808 );
2809 }
2810 };
2811 this.updateLatestLocation = () => {
2812 this.latestLocation = this.parseLocation(
2813 this.history.location,
2814 this.latestLocation
2815 );
2816 };
2817 this.buildRouteTree = () => {
2818 const { routesById, routesByPath, flatRoutes } = processRouteTree({
2819 routeTree: this.routeTree,
2820 initRoute: (route, i) => {
2821 route.init({
2822 originalIndex: i
2823 });
2824 }
2825 });
2826 this.routesById = routesById;
2827 this.routesByPath = routesByPath;
2828 this.flatRoutes = flatRoutes;
2829 const notFoundRoute = this.options.notFoundRoute;
2830 if (notFoundRoute) {
2831 notFoundRoute.init({
2832 originalIndex: 99999999999
2833 });
2834 this.routesById[notFoundRoute.id] = notFoundRoute;
2835 }
2836 };
2837 this.subscribe = (eventType, fn) => {
2838 const listener = {
2839 eventType,
2840 fn
2841 };
2842 this.subscribers.add(listener);
2843 return () => {
2844 this.subscribers.delete(listener);
2845 };
2846 };
2847 this.emit = (routerEvent) => {
2848 this.subscribers.forEach((listener) => {
2849 if (listener.eventType === routerEvent.type) {
2850 listener.fn(routerEvent);
2851 }
2852 });
2853 };
2854 this.parseLocation = (locationToParse, previousLocation) => {
2855 const parse = ({
2856 href,
2857 state
2858 }) => {
2859 const fullUrl = new URL(href, this.origin);
2860 const url = executeRewriteInput(this.rewrite, fullUrl);
2861 const parsedSearch = this.options.parseSearch(url.search);
2862 const searchStr = this.options.stringifySearch(parsedSearch);
2863 url.search = searchStr;
2864 const fullPath = url.href.replace(url.origin, "");
2865 const { pathname, hash } = url;
2866 return {
2867 href: fullPath,
2868 publicHref: href,
2869 url: url.href,
2870 pathname,
2871 searchStr,
2872 search: replaceEqualDeep(previousLocation?.search, parsedSearch),
2873 hash: hash.split("#").reverse()[0] ?? "",
2874 state: replaceEqualDeep(previousLocation?.state, state)
2875 };
2876 };
2877 const location = parse(locationToParse);
2878 const { __tempLocation, __tempKey } = location.state;
2879 if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
2880 const parsedTempLocation = parse(__tempLocation);
2881 parsedTempLocation.state.key = location.state.key;
2882 parsedTempLocation.state.__TSR_key = location.state.__TSR_key;
2883 delete parsedTempLocation.state.__tempLocation;
2884 return {
2885 ...parsedTempLocation,
2886 maskedLocation: location
2887 };
2888 }
2889 return location;
2890 };
2891 this.resolvePathWithBase = (from, path) => {
2892 const resolvedPath = resolvePath({
2893 base: from,
2894 to: cleanPath(path),
2895 trailingSlash: this.options.trailingSlash,
2896 parseCache: this.parsePathnameCache
2897 });
2898 return resolvedPath;
2899 };
2900 this.matchRoutes = (pathnameOrNext, locationSearchOrOpts, opts) => {
2901 if (typeof pathnameOrNext === "string") {
2902 return this.matchRoutesInternal(
2903 {
2904 pathname: pathnameOrNext,
2905 search: locationSearchOrOpts
2906 },
2907 opts
2908 );
2909 }
2910 return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts);
2911 };
2912 this.parsePathnameCache = createLRUCache(1e3);
2913 this.getMatchedRoutes = (pathname, routePathname) => {
2914 return getMatchedRoutes({
2915 pathname,
2916 routePathname,
2917 caseSensitive: this.options.caseSensitive,
2918 routesByPath: this.routesByPath,
2919 routesById: this.routesById,
2920 flatRoutes: this.flatRoutes,
2921 parseCache: this.parsePathnameCache
2922 });
2923 };
2924 this.cancelMatch = (id) => {
2925 const match = this.getMatch(id);
2926 if (!match) return;
2927 match.abortController.abort();
2928 clearTimeout(match._nonReactive.pendingTimeout);
2929 match._nonReactive.pendingTimeout = void 0;
2930 };
2931 this.cancelMatches = () => {
2932 this.state.pendingMatches?.forEach((match) => {
2933 this.cancelMatch(match.id);
2934 });
2935 };
2936 this.buildLocation = (opts) => {
2937 const build = (dest = {}) => {
2938 const currentLocation = dest._fromLocation || this.latestLocation;
2939 const allCurrentLocationMatches = this.matchRoutes(currentLocation, {
2940 _buildLocation: true
2941 });
2942 const lastMatch = last(allCurrentLocationMatches);
2943 if (dest.from && true && dest._isNavigate) {
2944 const allFromMatches = this.getMatchedRoutes(
2945 dest.from,
2946 void 0
2947 ).matchedRoutes;
2948 const matchedFrom = findLast(allCurrentLocationMatches, (d) => {
2949 return comparePaths(d.fullPath, dest.from);
2950 });
2951 const matchedCurrent = findLast(allFromMatches, (d) => {
2952 return comparePaths(d.fullPath, lastMatch.fullPath);
2953 });
2954 if (!matchedFrom && !matchedCurrent) {
2955 console.warn(`Could not find match for from: ${dest.from}`);
2956 }
2957 }
2958 const defaultedFromPath = dest.unsafeRelative === "path" ? currentLocation.pathname : dest.from ?? lastMatch.fullPath;
2959 const fromPath = this.resolvePathWithBase(defaultedFromPath, ".");
2960 const fromSearch = lastMatch.search;
2961 const fromParams = { ...lastMatch.params };
2962 const nextTo = dest.to ? this.resolvePathWithBase(fromPath, `${dest.to}`) : this.resolvePathWithBase(fromPath, ".");
2963 const nextParams = dest.params === false || dest.params === null ? {} : (dest.params ?? true) === true ? fromParams : Object.assign(
2964 fromParams,
2965 functionalUpdate(dest.params, fromParams)
2966 );
2967 const interpolatedNextTo = interpolatePath({
2968 path: nextTo,
2969 params: nextParams,
2970 parseCache: this.parsePathnameCache
2971 }).interpolatedPath;
2972 const destRoutes = this.matchRoutes(interpolatedNextTo, void 0, {
2973 _buildLocation: true
2974 }).map((d) => this.looseRoutesById[d.routeId]);
2975 if (Object.keys(nextParams).length > 0) {
2976 for (const route of destRoutes) {
2977 const fn = route.options.params?.stringify ?? route.options.stringifyParams;
2978 if (fn) {
2979 Object.assign(nextParams, fn(nextParams));
2980 }
2981 }
2982 }
2983 const nextPathname = decodePathSegment(
2984 interpolatePath({
2985 // Use the original template path for interpolation
2986 // This preserves the original parameter syntax including optional parameters
2987 path: nextTo,
2988 params: nextParams,
2989 leaveWildcards: false,
2990 leaveParams: opts.leaveParams,
2991 decodeCharMap: this.pathParamsDecodeCharMap,
2992 parseCache: this.parsePathnameCache
2993 }).interpolatedPath
2994 );
2995 let nextSearch = fromSearch;
2996 if (opts._includeValidateSearch && this.options.search?.strict) {
2997 const validatedSearch = {};
2998 destRoutes.forEach((route) => {
2999 if (route.options.validateSearch) {
3000 try {
3001 Object.assign(
3002 validatedSearch,
3003 validateSearch(route.options.validateSearch, {
3004 ...validatedSearch,
3005 ...nextSearch
3006 })
3007 );
3008 } catch {
3009 }
3010 }
3011 });
3012 nextSearch = validatedSearch;
3013 }
3014 nextSearch = applySearchMiddleware({
3015 search: nextSearch,
3016 dest,
3017 destRoutes,
3018 _includeValidateSearch: opts._includeValidateSearch
3019 });
3020 nextSearch = replaceEqualDeep(fromSearch, nextSearch);
3021 const searchStr = this.options.stringifySearch(nextSearch);
3022 const hash = dest.hash === true ? currentLocation.hash : dest.hash ? functionalUpdate(dest.hash, currentLocation.hash) : void 0;
3023 const hashStr = hash ? `#${hash}` : "";
3024 let nextState = dest.state === true ? currentLocation.state : dest.state ? functionalUpdate(dest.state, currentLocation.state) : {};
3025 nextState = replaceEqualDeep(currentLocation.state, nextState);
3026 const fullPath = `${nextPathname}${searchStr}${hashStr}`;
3027 const url = new URL(fullPath, this.origin);
3028 const rewrittenUrl = executeRewriteOutput(this.rewrite, url);
3029 return {
3030 publicHref: rewrittenUrl.pathname + rewrittenUrl.search + rewrittenUrl.hash,
3031 href: fullPath,
3032 url: rewrittenUrl.href,
3033 pathname: nextPathname,
3034 search: nextSearch,
3035 searchStr,
3036 state: nextState,
3037 hash: hash ?? "",
3038 unmaskOnReload: dest.unmaskOnReload
3039 };
3040 };
3041 const buildWithMatches = (dest = {}, maskedDest) => {
3042 const next = build(dest);
3043 let maskedNext = maskedDest ? build(maskedDest) : void 0;
3044 if (!maskedNext) {
3045 let params = {};
3046 const foundMask = this.options.routeMasks?.find((d) => {
3047 const match = matchPathname(
3048 next.pathname,
3049 {
3050 to: d.from,
3051 caseSensitive: false,
3052 fuzzy: false
3053 },
3054 this.parsePathnameCache
3055 );
3056 if (match) {
3057 params = match;
3058 return true;
3059 }
3060 return false;
3061 });
3062 if (foundMask) {
3063 const { from: _from, ...maskProps } = foundMask;
3064 maskedDest = {
3065 from: opts.from,
3066 ...maskProps,
3067 params
3068 };
3069 maskedNext = build(maskedDest);
3070 }
3071 }
3072 if (maskedNext) {
3073 next.maskedLocation = maskedNext;
3074 }
3075 return next;
3076 };
3077 if (opts.mask) {
3078 return buildWithMatches(opts, {
3079 from: opts.from,
3080 ...opts.mask
3081 });
3082 }
3083 return buildWithMatches(opts);
3084 };
3085 this.commitLocation = ({
3086 viewTransition,
3087 ignoreBlocker,
3088 ...next
3089 }) => {
3090 const isSameState = () => {
3091 const ignoredProps = [
3092 "key",
3093 // TODO: Remove in v2 - use __TSR_key instead
3094 "__TSR_key",
3095 "__TSR_index",
3096 "__hashScrollIntoViewOptions"
3097 ];
3098 ignoredProps.forEach((prop) => {
3099 next.state[prop] = this.latestLocation.state[prop];
3100 });
3101 const isEqual = deepEqual(next.state, this.latestLocation.state);
3102 ignoredProps.forEach((prop) => {
3103 delete next.state[prop];
3104 });
3105 return isEqual;
3106 };
3107 const isSameUrl = trimPathRight(this.latestLocation.href) === trimPathRight(next.href);
3108 const previousCommitPromise = this.commitLocationPromise;
3109 this.commitLocationPromise = createControlledPromise(() => {
3110 previousCommitPromise?.resolve();
3111 });
3112 if (isSameUrl && isSameState()) {
3113 this.load();
3114 } else {
3115 let { maskedLocation, hashScrollIntoView, ...nextHistory } = next;
3116 if (maskedLocation) {
3117 nextHistory = {
3118 ...maskedLocation,
3119 state: {
3120 ...maskedLocation.state,
3121 __tempKey: void 0,
3122 __tempLocation: {
3123 ...nextHistory,
3124 search: nextHistory.searchStr,
3125 state: {
3126 ...nextHistory.state,
3127 __tempKey: void 0,
3128 __tempLocation: void 0,
3129 __TSR_key: void 0,
3130 key: void 0
3131 // TODO: Remove in v2 - use __TSR_key instead
3132 }
3133 }
3134 }
3135 };
3136 if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
3137 nextHistory.state.__tempKey = this.tempLocationKey;
3138 }
3139 }
3140 nextHistory.state.__hashScrollIntoViewOptions = hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true;
3141 this.shouldViewTransition = viewTransition;
3142 this.history[next.replace ? "replace" : "push"](
3143 nextHistory.publicHref,
3144 nextHistory.state,
3145 { ignoreBlocker }
3146 );
3147 }
3148 this.resetNextScroll = next.resetScroll ?? true;
3149 if (!this.history.subscribers.size) {
3150 this.load();
3151 }
3152 return this.commitLocationPromise;
3153 };
3154 this.buildAndCommitLocation = ({
3155 replace,
3156 resetScroll,
3157 hashScrollIntoView,
3158 viewTransition,
3159 ignoreBlocker,
3160 href,
3161 ...rest
3162 } = {}) => {
3163 if (href) {
3164 const currentIndex = this.history.location.state.__TSR_index;
3165 const parsed = parseHref(href, {
3166 __TSR_index: replace ? currentIndex : currentIndex + 1
3167 });
3168 rest.to = parsed.pathname;
3169 rest.search = this.options.parseSearch(parsed.search);
3170 rest.hash = parsed.hash.slice(1);
3171 }
3172 const location = this.buildLocation({
3173 ...rest,
3174 _includeValidateSearch: true
3175 });
3176 return this.commitLocation({
3177 ...location,
3178 viewTransition,
3179 replace,
3180 resetScroll,
3181 hashScrollIntoView,
3182 ignoreBlocker
3183 });
3184 };
3185 this.navigate = ({ to, reloadDocument, href, ...rest }) => {
3186 if (!reloadDocument && href) {
3187 try {
3188 new URL(`${href}`);
3189 reloadDocument = true;
3190 } catch {
3191 }
3192 }
3193 if (reloadDocument) {
3194 if (!href) {
3195 const location = this.buildLocation({ to, ...rest });
3196 href = location.url;
3197 }
3198 if (rest.replace) {
3199 window.location.replace(href);
3200 } else {
3201 window.location.href = href;
3202 }
3203 return Promise.resolve();
3204 }
3205 return this.buildAndCommitLocation({
3206 ...rest,
3207 href,
3208 to,
3209 _isNavigate: true
3210 });
3211 };
3212 this.beforeLoad = () => {
3213 this.cancelMatches();
3214 this.updateLatestLocation();
3215 if (this.isServer) {
3216 const nextLocation = this.buildLocation({
3217 to: this.latestLocation.pathname,
3218 search: true,
3219 params: true,
3220 hash: true,
3221 state: true,
3222 _includeValidateSearch: true
3223 });
3224 const normalizeUrl = (url) => {
3225 try {
3226 return encodeURI(decodeURI(url));
3227 } catch {
3228 return url;
3229 }
3230 };
3231 if (trimPath(normalizeUrl(this.latestLocation.href)) !== trimPath(normalizeUrl(nextLocation.href))) {
3232 let href = nextLocation.url;
3233 if (this.origin && href.startsWith(this.origin)) {
3234 href = href.replace(this.origin, "") || "/";
3235 }
3236 throw redirect({ href });
3237 }
3238 }
3239 const pendingMatches = this.matchRoutes(this.latestLocation);
3240 this.__store.setState((s) => ({
3241 ...s,
3242 status: "pending",
3243 statusCode: 200,
3244 isLoading: true,
3245 location: this.latestLocation,
3246 pendingMatches,
3247 // If a cached moved to pendingMatches, remove it from cachedMatches
3248 cachedMatches: s.cachedMatches.filter(
3249 (d) => !pendingMatches.some((e) => e.id === d.id)
3250 )
3251 }));
3252 };
3253 this.load = async (opts) => {
3254 let redirect2;
3255 let notFound2;
3256 let loadPromise;
3257 loadPromise = new Promise((resolve) => {
3258 this.startTransition(async () => {
3259 try {
3260 this.beforeLoad();
3261 const next = this.latestLocation;
3262 const prevLocation = this.state.resolvedLocation;
3263 if (!this.state.redirect) {
3264 this.emit({
3265 type: "onBeforeNavigate",
3266 ...getLocationChangeInfo({
3267 resolvedLocation: prevLocation,
3268 location: next
3269 })
3270 });
3271 }
3272 this.emit({
3273 type: "onBeforeLoad",
3274 ...getLocationChangeInfo({
3275 resolvedLocation: prevLocation,
3276 location: next
3277 })
3278 });
3279 await loadMatches({
3280 router: this,
3281 sync: opts?.sync,
3282 matches: this.state.pendingMatches,
3283 location: next,
3284 updateMatch: this.updateMatch,
3285 // eslint-disable-next-line @typescript-eslint/require-await
3286 onReady: async () => {
3287 this.startViewTransition(async () => {
3288 let exitingMatches;
3289 let enteringMatches;
3290 let stayingMatches;
3291 batch(() => {
3292 this.__store.setState((s) => {
3293 const previousMatches = s.matches;
3294 const newMatches = s.pendingMatches || s.matches;
3295 exitingMatches = previousMatches.filter(
3296 (match) => !newMatches.some((d) => d.id === match.id)
3297 );
3298 enteringMatches = newMatches.filter(
3299 (match) => !previousMatches.some((d) => d.id === match.id)
3300 );
3301 stayingMatches = previousMatches.filter(
3302 (match) => newMatches.some((d) => d.id === match.id)
3303 );
3304 return {
3305 ...s,
3306 isLoading: false,
3307 loadedAt: Date.now(),
3308 matches: newMatches,
3309 pendingMatches: void 0,
3310 cachedMatches: [
3311 ...s.cachedMatches,
3312 ...exitingMatches.filter((d) => d.status !== "error")
3313 ]
3314 };
3315 });
3316 this.clearExpiredCache();
3317 });
3318 [
3319 [exitingMatches, "onLeave"],
3320 [enteringMatches, "onEnter"],
3321 [stayingMatches, "onStay"]
3322 ].forEach(([matches, hook]) => {
3323 matches.forEach((match) => {
3324 this.looseRoutesById[match.routeId].options[hook]?.(match);
3325 });
3326 });
3327 });
3328 }
3329 });
3330 } catch (err) {
3331 if (isRedirect(err)) {
3332 redirect2 = err;
3333 if (!this.isServer) {
3334 this.navigate({
3335 ...redirect2.options,
3336 replace: true,
3337 ignoreBlocker: true
3338 });
3339 }
3340 } else if (isNotFound(err)) {
3341 notFound2 = err;
3342 }
3343 this.__store.setState((s) => ({
3344 ...s,
3345 statusCode: redirect2 ? redirect2.status : notFound2 ? 404 : s.matches.some((d) => d.status === "error") ? 500 : 200,
3346 redirect: redirect2
3347 }));
3348 }
3349 if (this.latestLoadPromise === loadPromise) {
3350 this.commitLocationPromise?.resolve();
3351 this.latestLoadPromise = void 0;
3352 this.commitLocationPromise = void 0;
3353 }
3354 resolve();
3355 });
3356 });
3357 this.latestLoadPromise = loadPromise;
3358 await loadPromise;
3359 while (this.latestLoadPromise && loadPromise !== this.latestLoadPromise) {
3360 await this.latestLoadPromise;
3361 }
3362 let newStatusCode = void 0;
3363 if (this.hasNotFoundMatch()) {
3364 newStatusCode = 404;
3365 } else if (this.__store.state.matches.some((d) => d.status === "error")) {
3366 newStatusCode = 500;
3367 }
3368 if (newStatusCode !== void 0) {
3369 this.__store.setState((s) => ({
3370 ...s,
3371 statusCode: newStatusCode
3372 }));
3373 }
3374 };
3375 this.startViewTransition = (fn) => {
3376 const shouldViewTransition = this.shouldViewTransition ?? this.options.defaultViewTransition;
3377 delete this.shouldViewTransition;
3378 if (shouldViewTransition && typeof document !== "undefined" && "startViewTransition" in document && typeof document.startViewTransition === "function") {
3379 let startViewTransitionParams;
3380 if (typeof shouldViewTransition === "object" && this.isViewTransitionTypesSupported) {
3381 const next = this.latestLocation;
3382 const prevLocation = this.state.resolvedLocation;
3383 const resolvedViewTransitionTypes = typeof shouldViewTransition.types === "function" ? shouldViewTransition.types(
3384 getLocationChangeInfo({
3385 resolvedLocation: prevLocation,
3386 location: next
3387 })
3388 ) : shouldViewTransition.types;
3389 if (resolvedViewTransitionTypes === false) {
3390 fn();
3391 return;
3392 }
3393 startViewTransitionParams = {
3394 update: fn,
3395 types: resolvedViewTransitionTypes
3396 };
3397 } else {
3398 startViewTransitionParams = fn;
3399 }
3400 document.startViewTransition(startViewTransitionParams);
3401 } else {
3402 fn();
3403 }
3404 };
3405 this.updateMatch = (id, updater) => {
3406 const matchesKey = this.state.pendingMatches?.some((d) => d.id === id) ? "pendingMatches" : this.state.matches.some((d) => d.id === id) ? "matches" : this.state.cachedMatches.some((d) => d.id === id) ? "cachedMatches" : "";
3407 if (matchesKey) {
3408 this.__store.setState((s) => ({
3409 ...s,
3410 [matchesKey]: s[matchesKey]?.map((d) => d.id === id ? updater(d) : d)
3411 }));
3412 }
3413 };
3414 this.getMatch = (matchId) => {
3415 const findFn = (d) => d.id === matchId;
3416 return this.state.cachedMatches.find(findFn) ?? this.state.pendingMatches?.find(findFn) ?? this.state.matches.find(findFn);
3417 };
3418 this.invalidate = (opts) => {
3419 const invalidate = (d) => {
3420 if (opts?.filter?.(d) ?? true) {
3421 return {
3422 ...d,
3423 invalid: true,
3424 ...opts?.forcePending || d.status === "error" ? { status: "pending", error: void 0 } : void 0
3425 };
3426 }
3427 return d;
3428 };
3429 this.__store.setState((s) => ({
3430 ...s,
3431 matches: s.matches.map(invalidate),
3432 cachedMatches: s.cachedMatches.map(invalidate),
3433 pendingMatches: s.pendingMatches?.map(invalidate)
3434 }));
3435 this.shouldViewTransition = false;
3436 return this.load({ sync: opts?.sync });
3437 };
3438 this.resolveRedirect = (redirect2) => {
3439 if (!redirect2.options.href) {
3440 const location = this.buildLocation(redirect2.options);
3441 let href = location.url;
3442 if (this.origin && href.startsWith(this.origin)) {
3443 href = href.replace(this.origin, "") || "/";
3444 }
3445 redirect2.options.href = location.href;
3446 redirect2.headers.set("Location", href);
3447 }
3448 if (!redirect2.headers.get("Location")) {
3449 redirect2.headers.set("Location", redirect2.options.href);
3450 }
3451 return redirect2;
3452 };
3453 this.clearCache = (opts) => {
3454 const filter = opts?.filter;
3455 if (filter !== void 0) {
3456 this.__store.setState((s) => {
3457 return {
3458 ...s,
3459 cachedMatches: s.cachedMatches.filter(
3460 (m) => !filter(m)
3461 )
3462 };
3463 });
3464 } else {
3465 this.__store.setState((s) => {
3466 return {
3467 ...s,
3468 cachedMatches: []
3469 };
3470 });
3471 }
3472 };
3473 this.clearExpiredCache = () => {
3474 const filter = (d) => {
3475 const route = this.looseRoutesById[d.routeId];
3476 if (!route.options.loader) {
3477 return true;
3478 }
3479 const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 5 * 60 * 1e3;
3480 const isError = d.status === "error";
3481 if (isError) return true;
3482 const gcEligible = Date.now() - d.updatedAt >= gcTime;
3483 return gcEligible;
3484 };
3485 this.clearCache({ filter });
3486 };
3487 this.loadRouteChunk = loadRouteChunk;
3488 this.preloadRoute = async (opts) => {
3489 const next = this.buildLocation(opts);
3490 let matches = this.matchRoutes(next, {
3491 throwOnError: true,
3492 preload: true,
3493 dest: opts
3494 });
3495 const activeMatchIds = new Set(
3496 [...this.state.matches, ...this.state.pendingMatches ?? []].map(
3497 (d) => d.id
3498 )
3499 );
3500 const loadedMatchIds = /* @__PURE__ */ new Set([
3501 ...activeMatchIds,
3502 ...this.state.cachedMatches.map((d) => d.id)
3503 ]);
3504 batch(() => {
3505 matches.forEach((match) => {
3506 if (!loadedMatchIds.has(match.id)) {
3507 this.__store.setState((s) => ({
3508 ...s,
3509 cachedMatches: [...s.cachedMatches, match]
3510 }));
3511 }
3512 });
3513 });
3514 try {
3515 matches = await loadMatches({
3516 router: this,
3517 matches,
3518 location: next,
3519 preload: true,
3520 updateMatch: (id, updater) => {
3521 if (activeMatchIds.has(id)) {
3522 matches = matches.map((d) => d.id === id ? updater(d) : d);
3523 } else {
3524 this.updateMatch(id, updater);
3525 }
3526 }
3527 });
3528 return matches;
3529 } catch (err) {
3530 if (isRedirect(err)) {
3531 if (err.options.reloadDocument) {
3532 return void 0;
3533 }
3534 return await this.preloadRoute({
3535 ...err.options,
3536 _fromLocation: next
3537 });
3538 }
3539 if (!isNotFound(err)) {
3540 console.error(err);
3541 }
3542 return void 0;
3543 }
3544 };
3545 this.matchRoute = (location, opts) => {
3546 const matchLocation = {
3547 ...location,
3548 to: location.to ? this.resolvePathWithBase(
3549 location.from || "",
3550 location.to
3551 ) : void 0,
3552 params: location.params || {},
3553 leaveParams: true
3554 };
3555 const next = this.buildLocation(matchLocation);
3556 if (opts?.pending && this.state.status !== "pending") {
3557 return false;
3558 }
3559 const pending = opts?.pending === void 0 ? !this.state.isLoading : opts.pending;
3560 const baseLocation = pending ? this.latestLocation : this.state.resolvedLocation || this.state.location;
3561 const match = matchPathname(
3562 baseLocation.pathname,
3563 {
3564 ...opts,
3565 to: next.pathname
3566 },
3567 this.parsePathnameCache
3568 );
3569 if (!match) {
3570 return false;
3571 }
3572 if (location.params) {
3573 if (!deepEqual(match, location.params, { partial: true })) {
3574 return false;
3575 }
3576 }
3577 if (match && (opts?.includeSearch ?? true)) {
3578 return deepEqual(baseLocation.search, next.search, { partial: true }) ? match : false;
3579 }
3580 return match;
3581 };
3582 this.hasNotFoundMatch = () => {
3583 return this.__store.state.matches.some(
3584 (d) => d.status === "notFound" || d.globalNotFound
3585 );
3586 };
3587 this.update({
3588 defaultPreloadDelay: 50,
3589 defaultPendingMs: 1e3,
3590 defaultPendingMinMs: 500,
3591 context: void 0,
3592 ...options,
3593 caseSensitive: options.caseSensitive ?? false,
3594 notFoundMode: options.notFoundMode ?? "fuzzy",
3595 stringifySearch: options.stringifySearch ?? defaultStringifySearch,
3596 parseSearch: options.parseSearch ?? defaultParseSearch
3597 });
3598 if (typeof document !== "undefined") {
3599 self.__TSR_ROUTER__ = this;
3600 }
3601 }
3602 isShell() {
3603 return !!this.options.isShell;
3604 }
3605 isPrerendering() {
3606 return !!this.options.isPrerendering;
3607 }
3608 get state() {
3609 return this.__store.state;
3610 }
3611 get looseRoutesById() {
3612 return this.routesById;
3613 }
3614 matchRoutesInternal(next, opts) {
3615 const { foundRoute, matchedRoutes, routeParams } = this.getMatchedRoutes(
3616 next.pathname,
3617 opts?.dest?.to
3618 );
3619 let isGlobalNotFound = false;
3620 if (
3621 // If we found a route, and it's not an index route and we have left over path
3622 foundRoute ? foundRoute.path !== "/" && routeParams["**"] : (
3623 // Or if we didn't find a route and we have left over path
3624 trimPathRight(next.pathname)
3625 )
3626 ) {
3627 if (this.options.notFoundRoute) {
3628 matchedRoutes.push(this.options.notFoundRoute);
3629 } else {
3630 isGlobalNotFound = true;
3631 }
3632 }
3633 const globalNotFoundRouteId = (() => {
3634 if (!isGlobalNotFound) {
3635 return void 0;
3636 }
3637 if (this.options.notFoundMode !== "root") {
3638 for (let i = matchedRoutes.length - 1; i >= 0; i--) {
3639 const route = matchedRoutes[i];
3640 if (route.children) {
3641 return route.id;
3642 }
3643 }
3644 }
3645 return rootRouteId;
3646 })();
3647 const matches = [];
3648 const getParentContext = (parentMatch) => {
3649 const parentMatchId = parentMatch?.id;
3650 const parentContext = !parentMatchId ? this.options.context ?? void 0 : parentMatch.context ?? this.options.context ?? void 0;
3651 return parentContext;
3652 };
3653 matchedRoutes.forEach((route, index) => {
3654 const parentMatch = matches[index - 1];
3655 const [preMatchSearch, strictMatchSearch, searchError] = (() => {
3656 const parentSearch = parentMatch?.search ?? next.search;
3657 const parentStrictSearch = parentMatch?._strictSearch ?? void 0;
3658 try {
3659 const strictSearch = validateSearch(route.options.validateSearch, { ...parentSearch }) ?? void 0;
3660 return [
3661 {
3662 ...parentSearch,
3663 ...strictSearch
3664 },
3665 { ...parentStrictSearch, ...strictSearch },
3666 void 0
3667 ];
3668 } catch (err) {
3669 let searchParamError = err;
3670 if (!(err instanceof SearchParamError)) {
3671 searchParamError = new SearchParamError(err.message, {
3672 cause: err
3673 });
3674 }
3675 if (opts?.throwOnError) {
3676 throw searchParamError;
3677 }
3678 return [parentSearch, {}, searchParamError];
3679 }
3680 })();
3681 const loaderDeps = route.options.loaderDeps?.({
3682 search: preMatchSearch
3683 }) ?? "";
3684 const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : "";
3685 const { interpolatedPath, usedParams } = interpolatePath({
3686 path: route.fullPath,
3687 params: routeParams,
3688 decodeCharMap: this.pathParamsDecodeCharMap
3689 });
3690 const matchId = interpolatePath({
3691 path: route.id,
3692 params: routeParams,
3693 leaveWildcards: true,
3694 decodeCharMap: this.pathParamsDecodeCharMap,
3695 parseCache: this.parsePathnameCache
3696 }).interpolatedPath + loaderDepsHash;
3697 const existingMatch = this.getMatch(matchId);
3698 const previousMatch = this.state.matches.find(
3699 (d) => d.routeId === route.id
3700 );
3701 const strictParams = existingMatch?._strictParams ?? usedParams;
3702 let paramsError = void 0;
3703 if (!existingMatch) {
3704 const strictParseParams = route.options.params?.parse ?? route.options.parseParams;
3705 if (strictParseParams) {
3706 try {
3707 Object.assign(
3708 strictParams,
3709 strictParseParams(strictParams)
3710 );
3711 } catch (err) {
3712 paramsError = new PathParamError(err.message, {
3713 cause: err
3714 });
3715 if (opts?.throwOnError) {
3716 throw paramsError;
3717 }
3718 }
3719 }
3720 }
3721 Object.assign(routeParams, strictParams);
3722 const cause = previousMatch ? "stay" : "enter";
3723 let match;
3724 if (existingMatch) {
3725 match = {
3726 ...existingMatch,
3727 cause,
3728 params: previousMatch ? replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
3729 _strictParams: strictParams,
3730 search: previousMatch ? replaceEqualDeep(previousMatch.search, preMatchSearch) : replaceEqualDeep(existingMatch.search, preMatchSearch),
3731 _strictSearch: strictMatchSearch
3732 };
3733 } else {
3734 const status = route.options.loader || route.options.beforeLoad || route.lazyFn || routeNeedsPreload(route) ? "pending" : "success";
3735 match = {
3736 id: matchId,
3737 index,
3738 routeId: route.id,
3739 params: previousMatch ? replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
3740 _strictParams: strictParams,
3741 pathname: interpolatedPath,
3742 updatedAt: Date.now(),
3743 search: previousMatch ? replaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch,
3744 _strictSearch: strictMatchSearch,
3745 searchError: void 0,
3746 status,
3747 isFetching: false,
3748 error: void 0,
3749 paramsError,
3750 __routeContext: void 0,
3751 _nonReactive: {
3752 loadPromise: createControlledPromise()
3753 },
3754 __beforeLoadContext: void 0,
3755 context: {},
3756 abortController: new AbortController(),
3757 fetchCount: 0,
3758 cause,
3759 loaderDeps: previousMatch ? replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) : loaderDeps,
3760 invalid: false,
3761 preload: false,
3762 links: void 0,
3763 scripts: void 0,
3764 headScripts: void 0,
3765 meta: void 0,
3766 staticData: route.options.staticData || {},
3767 fullPath: route.fullPath
3768 };
3769 }
3770 if (!opts?.preload) {
3771 match.globalNotFound = globalNotFoundRouteId === route.id;
3772 }
3773 match.searchError = searchError;
3774 const parentContext = getParentContext(parentMatch);
3775 match.context = {
3776 ...parentContext,
3777 ...match.__routeContext,
3778 ...match.__beforeLoadContext
3779 };
3780 matches.push(match);
3781 });
3782 matches.forEach((match, index) => {
3783 const route = this.looseRoutesById[match.routeId];
3784 const existingMatch = this.getMatch(match.id);
3785 if (!existingMatch && opts?._buildLocation !== true) {
3786 const parentMatch = matches[index - 1];
3787 const parentContext = getParentContext(parentMatch);
3788 if (route.options.context) {
3789 const contextFnContext = {
3790 deps: match.loaderDeps,
3791 params: match.params,
3792 context: parentContext ?? {},
3793 location: next,
3794 navigate: (opts2) => this.navigate({ ...opts2, _fromLocation: next }),
3795 buildLocation: this.buildLocation,
3796 cause: match.cause,
3797 abortController: match.abortController,
3798 preload: !!match.preload,
3799 matches
3800 };
3801 match.__routeContext = route.options.context(contextFnContext) ?? void 0;
3802 }
3803 match.context = {
3804 ...parentContext,
3805 ...match.__routeContext,
3806 ...match.__beforeLoadContext
3807 };
3808 }
3809 });
3810 return matches;
3811 }
3812 };
3813 var SearchParamError = class extends Error {
3814 };
3815 var PathParamError = class extends Error {
3816 };
3817 var normalize = (str) => str.endsWith("/") && str.length > 1 ? str.slice(0, -1) : str;
3818 function comparePaths(a, b) {
3819 return normalize(a) === normalize(b);
3820 }
3821 function getInitialRouterState(location) {
3822 return {
3823 loadedAt: 0,
3824 isLoading: false,
3825 isTransitioning: false,
3826 status: "idle",
3827 resolvedLocation: void 0,
3828 location,
3829 matches: [],
3830 pendingMatches: [],
3831 cachedMatches: [],
3832 statusCode: 200
3833 };
3834 }
3835 function validateSearch(validateSearch2, input) {
3836 if (validateSearch2 == null) return {};
3837 if ("~standard" in validateSearch2) {
3838 const result = validateSearch2["~standard"].validate(input);
3839 if (result instanceof Promise)
3840 throw new SearchParamError("Async validation not supported");
3841 if (result.issues)
3842 throw new SearchParamError(JSON.stringify(result.issues, void 0, 2), {
3843 cause: result
3844 });
3845 return result.value;
3846 }
3847 if ("parse" in validateSearch2) {
3848 return validateSearch2.parse(input);
3849 }
3850 if (typeof validateSearch2 === "function") {
3851 return validateSearch2(input);
3852 }
3853 return {};
3854 }
3855 function getMatchedRoutes({
3856 pathname,
3857 routePathname,
3858 caseSensitive,
3859 routesByPath,
3860 routesById,
3861 flatRoutes,
3862 parseCache
3863 }) {
3864 let routeParams = {};
3865 const trimmedPath = trimPathRight(pathname);
3866 const getMatchedParams = (route) => {
3867 const result = matchPathname(
3868 trimmedPath,
3869 {
3870 to: route.fullPath,
3871 caseSensitive: route.options?.caseSensitive ?? caseSensitive,
3872 // we need fuzzy matching for `notFoundMode: 'fuzzy'`
3873 fuzzy: true
3874 },
3875 parseCache
3876 );
3877 return result;
3878 };
3879 let foundRoute = routePathname !== void 0 ? routesByPath[routePathname] : void 0;
3880 if (foundRoute) {
3881 routeParams = getMatchedParams(foundRoute);
3882 } else {
3883 let fuzzyMatch = void 0;
3884 for (const route of flatRoutes) {
3885 const matchedParams = getMatchedParams(route);
3886 if (matchedParams) {
3887 if (route.path !== "/" && matchedParams["**"]) {
3888 if (!fuzzyMatch) {
3889 fuzzyMatch = { foundRoute: route, routeParams: matchedParams };
3890 }
3891 } else {
3892 foundRoute = route;
3893 routeParams = matchedParams;
3894 break;
3895 }
3896 }
3897 }
3898 if (!foundRoute && fuzzyMatch) {
3899 foundRoute = fuzzyMatch.foundRoute;
3900 routeParams = fuzzyMatch.routeParams;
3901 }
3902 }
3903 let routeCursor = foundRoute || routesById[rootRouteId];
3904 const matchedRoutes = [routeCursor];
3905 while (routeCursor.parentRoute) {
3906 routeCursor = routeCursor.parentRoute;
3907 matchedRoutes.push(routeCursor);
3908 }
3909 matchedRoutes.reverse();
3910 return { matchedRoutes, routeParams, foundRoute };
3911 }
3912 function applySearchMiddleware({
3913 search,
3914 dest,
3915 destRoutes,
3916 _includeValidateSearch
3917 }) {
3918 const allMiddlewares = destRoutes.reduce(
3919 (acc, route) => {
3920 const middlewares = [];
3921 if ("search" in route.options) {
3922 if (route.options.search?.middlewares) {
3923 middlewares.push(...route.options.search.middlewares);
3924 }
3925 } else if (route.options.preSearchFilters || route.options.postSearchFilters) {
3926 const legacyMiddleware = ({
3927 search: search2,
3928 next
3929 }) => {
3930 let nextSearch = search2;
3931 if ("preSearchFilters" in route.options && route.options.preSearchFilters) {
3932 nextSearch = route.options.preSearchFilters.reduce(
3933 (prev, next2) => next2(prev),
3934 search2
3935 );
3936 }
3937 const result = next(nextSearch);
3938 if ("postSearchFilters" in route.options && route.options.postSearchFilters) {
3939 return route.options.postSearchFilters.reduce(
3940 (prev, next2) => next2(prev),
3941 result
3942 );
3943 }
3944 return result;
3945 };
3946 middlewares.push(legacyMiddleware);
3947 }
3948 if (_includeValidateSearch && route.options.validateSearch) {
3949 const validate = ({ search: search2, next }) => {
3950 const result = next(search2);
3951 try {
3952 const validatedSearch = {
3953 ...result,
3954 ...validateSearch(route.options.validateSearch, result) ?? void 0
3955 };
3956 return validatedSearch;
3957 } catch {
3958 return result;
3959 }
3960 };
3961 middlewares.push(validate);
3962 }
3963 return acc.concat(middlewares);
3964 },
3965 []
3966 ) ?? [];
3967 const final = ({ search: search2 }) => {
3968 if (!dest.search) {
3969 return {};
3970 }
3971 if (dest.search === true) {
3972 return search2;
3973 }
3974 return functionalUpdate(dest.search, search2);
3975 };
3976 allMiddlewares.push(final);
3977 const applyNext = (index, currentSearch) => {
3978 if (index >= allMiddlewares.length) {
3979 return currentSearch;
3980 }
3981 const middleware = allMiddlewares[index];
3982 const next = (newSearch) => {
3983 return applyNext(index + 1, newSearch);
3984 };
3985 return middleware({ search: currentSearch, next });
3986 };
3987 return applyNext(0, search);
3988 }
3989
3990 // node_modules/@tanstack/router-core/dist/esm/link.js
3991 var preloadWarning = "Error preloading route! \u261D\uFE0F";
3992
3993 // node_modules/@tanstack/router-core/dist/esm/route.js
3994 var BaseRoute = class {
3995 constructor(options) {
3996 this.init = (opts) => {
3997 this.originalIndex = opts.originalIndex;
3998 const options2 = this.options;
3999 const isRoot = !options2?.path && !options2?.id;
4000 this.parentRoute = this.options.getParentRoute?.();
4001 if (isRoot) {
4002 this._path = rootRouteId;
4003 } else if (!this.parentRoute) {
4004 invariant(
4005 false,
4006 `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`
4007 );
4008 }
4009 let path = isRoot ? rootRouteId : options2?.path;
4010 if (path && path !== "/") {
4011 path = trimPathLeft(path);
4012 }
4013 const customId = options2?.id || path;
4014 let id = isRoot ? rootRouteId : joinPaths([
4015 this.parentRoute.id === rootRouteId ? "" : this.parentRoute.id,
4016 customId
4017 ]);
4018 if (path === rootRouteId) {
4019 path = "/";
4020 }
4021 if (id !== rootRouteId) {
4022 id = joinPaths(["/", id]);
4023 }
4024 const fullPath = id === rootRouteId ? "/" : joinPaths([this.parentRoute.fullPath, path]);
4025 this._path = path;
4026 this._id = id;
4027 this._fullPath = fullPath;
4028 this._to = fullPath;
4029 };
4030 this.clone = (other) => {
4031 this._path = other._path;
4032 this._id = other._id;
4033 this._fullPath = other._fullPath;
4034 this._to = other._to;
4035 this.options.getParentRoute = other.options.getParentRoute;
4036 this.children = other.children;
4037 };
4038 this.addChildren = (children) => {
4039 return this._addFileChildren(children);
4040 };
4041 this._addFileChildren = (children) => {
4042 if (Array.isArray(children)) {
4043 this.children = children;
4044 }
4045 if (typeof children === "object" && children !== null) {
4046 this.children = Object.values(children);
4047 }
4048 return this;
4049 };
4050 this._addFileTypes = () => {
4051 return this;
4052 };
4053 this.updateLoader = (options2) => {
4054 Object.assign(this.options, options2);
4055 return this;
4056 };
4057 this.update = (options2) => {
4058 Object.assign(this.options, options2);
4059 return this;
4060 };
4061 this.lazy = (lazyFn2) => {
4062 this.lazyFn = lazyFn2;
4063 return this;
4064 };
4065 this.options = options || {};
4066 this.isRoot = !options?.getParentRoute;
4067 if (options?.id && options?.path) {
4068 throw new Error(`Route cannot have both an 'id' and a 'path' option.`);
4069 }
4070 }
4071 get to() {
4072 return this._to;
4073 }
4074 get id() {
4075 return this._id;
4076 }
4077 get path() {
4078 return this._path;
4079 }
4080 get fullPath() {
4081 return this._fullPath;
4082 }
4083 };
4084 var BaseRootRoute = class extends BaseRoute {
4085 constructor(options) {
4086 super(options);
4087 }
4088 };
4089
4090 // node_modules/@tanstack/react-router/dist/esm/CatchBoundary.js
4091 var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
4092 var React = __toESM(require_react(), 1);
4093 function CatchBoundary(props) {
4094 const errorComponent = props.errorComponent ?? ErrorComponent;
4095 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
4096 CatchBoundaryImpl,
4097 {
4098 getResetKey: props.getResetKey,
4099 onCatch: props.onCatch,
4100 children: ({ error, reset }) => {
4101 if (error) {
4102 return React.createElement(errorComponent, {
4103 error,
4104 reset
4105 });
4106 }
4107 return props.children;
4108 }
4109 }
4110 );
4111 }
4112 var CatchBoundaryImpl = class extends React.Component {
4113 constructor() {
4114 super(...arguments);
4115 this.state = { error: null };
4116 }
4117 static getDerivedStateFromProps(props) {
4118 return { resetKey: props.getResetKey() };
4119 }
4120 static getDerivedStateFromError(error) {
4121 return { error };
4122 }
4123 reset() {
4124 this.setState({ error: null });
4125 }
4126 componentDidUpdate(prevProps, prevState) {
4127 if (prevState.error && prevState.resetKey !== this.state.resetKey) {
4128 this.reset();
4129 }
4130 }
4131 componentDidCatch(error, errorInfo) {
4132 if (this.props.onCatch) {
4133 this.props.onCatch(error, errorInfo);
4134 }
4135 }
4136 render() {
4137 return this.props.children({
4138 error: this.state.resetKey !== this.props.getResetKey() ? null : this.state.error,
4139 reset: () => {
4140 this.reset();
4141 }
4142 });
4143 }
4144 };
4145 function ErrorComponent({ error }) {
4146 const [show, setShow] = React.useState(true);
4147 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { padding: ".5rem", maxWidth: "100%" }, children: [
4148 /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: ".5rem" }, children: [
4149 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { style: { fontSize: "1rem" }, children: "Something went wrong!" }),
4150 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
4151 "button",
4152 {
4153 style: {
4154 appearance: "none",
4155 fontSize: ".6em",
4156 border: "1px solid currentColor",
4157 padding: ".1rem .2rem",
4158 fontWeight: "bold",
4159 borderRadius: ".25rem"
4160 },
4161 onClick: () => setShow((d) => !d),
4162 children: show ? "Hide Error" : "Show Error"
4163 }
4164 )
4165 ] }),
4166 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: { height: ".25rem" } }),
4167 show ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
4168 "pre",
4169 {
4170 style: {
4171 fontSize: ".7em",
4172 border: "1px solid red",
4173 borderRadius: ".25rem",
4174 padding: ".3rem",
4175 color: "red",
4176 overflow: "auto"
4177 },
4178 children: error.message ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: error.message }) : null
4179 }
4180 ) }) : null
4181 ] });
4182 }
4183
4184 // node_modules/@tanstack/react-router/dist/esm/ClientOnly.js
4185 var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
4186 var import_react = __toESM(require_react(), 1);
4187 function ClientOnly({ children, fallback = null }) {
4188 return useHydrated() ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react.default.Fragment, { children }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react.default.Fragment, { children: fallback });
4189 }
4190 function useHydrated() {
4191 return import_react.default.useSyncExternalStore(
4192 subscribe,
4193 () => true,
4194 () => false
4195 );
4196 }
4197 function subscribe() {
4198 return () => {
4199 };
4200 }
4201
4202 // node_modules/tiny-warning/dist/tiny-warning.esm.js
4203 var isProduction2 = false;
4204 function warning(condition, message) {
4205 if (!isProduction2) {
4206 if (condition) {
4207 return;
4208 }
4209 var text = "Warning: " + message;
4210 if (typeof console !== "undefined") {
4211 console.warn(text);
4212 }
4213 try {
4214 throw Error(text);
4215 } catch (x) {
4216 }
4217 }
4218 }
4219 var tiny_warning_esm_default = warning;
4220
4221 // node_modules/@tanstack/react-router/dist/esm/route.js
4222 var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
4223 var import_react3 = __toESM(require_react(), 1);
4224
4225 // node_modules/@tanstack/react-router/dist/esm/useMatch.js
4226 var React5 = __toESM(require_react(), 1);
4227
4228 // node_modules/@tanstack/react-store/dist/esm/index.js
4229 var import_with_selector = __toESM(require_with_selector(), 1);
4230 function useStore(store, selector = (d) => d, options = {}) {
4231 const equal = options.equal ?? shallow;
4232 const slice = (0, import_with_selector.useSyncExternalStoreWithSelector)(
4233 store.subscribe,
4234 () => store.state,
4235 () => store.state,
4236 selector,
4237 equal
4238 );
4239 return slice;
4240 }
4241 function shallow(objA, objB) {
4242 if (Object.is(objA, objB)) {
4243 return true;
4244 }
4245 if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
4246 return false;
4247 }
4248 if (objA instanceof Map && objB instanceof Map) {
4249 if (objA.size !== objB.size) return false;
4250 for (const [k, v] of objA) {
4251 if (!objB.has(k) || !Object.is(v, objB.get(k))) return false;
4252 }
4253 return true;
4254 }
4255 if (objA instanceof Set && objB instanceof Set) {
4256 if (objA.size !== objB.size) return false;
4257 for (const v of objA) {
4258 if (!objB.has(v)) return false;
4259 }
4260 return true;
4261 }
4262 if (objA instanceof Date && objB instanceof Date) {
4263 if (objA.getTime() !== objB.getTime()) return false;
4264 return true;
4265 }
4266 const keysA = getOwnKeys(objA);
4267 if (keysA.length !== getOwnKeys(objB).length) {
4268 return false;
4269 }
4270 for (let i = 0; i < keysA.length; i++) {
4271 if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !Object.is(objA[keysA[i]], objB[keysA[i]])) {
4272 return false;
4273 }
4274 }
4275 return true;
4276 }
4277 function getOwnKeys(obj) {
4278 return Object.keys(obj).concat(
4279 Object.getOwnPropertySymbols(obj)
4280 );
4281 }
4282
4283 // node_modules/@tanstack/react-router/dist/esm/useRouterState.js
4284 var import_react2 = __toESM(require_react(), 1);
4285
4286 // node_modules/@tanstack/react-router/dist/esm/useRouter.js
4287 var React3 = __toESM(require_react(), 1);
4288
4289 // node_modules/@tanstack/react-router/dist/esm/routerContext.js
4290 var React2 = __toESM(require_react(), 1);
4291 var routerContext = React2.createContext(null);
4292 function getRouterContext() {
4293 if (typeof document === "undefined") {
4294 return routerContext;
4295 }
4296 if (window.__TSR_ROUTER_CONTEXT__) {
4297 return window.__TSR_ROUTER_CONTEXT__;
4298 }
4299 window.__TSR_ROUTER_CONTEXT__ = routerContext;
4300 return routerContext;
4301 }
4302
4303 // node_modules/@tanstack/react-router/dist/esm/useRouter.js
4304 function useRouter(opts) {
4305 const value = React3.useContext(getRouterContext());
4306 tiny_warning_esm_default(
4307 !((opts?.warn ?? true) && !value),
4308 "useRouter must be used inside a <RouterProvider> component!"
4309 );
4310 return value;
4311 }
4312
4313 // node_modules/@tanstack/react-router/dist/esm/useRouterState.js
4314 function useRouterState(opts) {
4315 const contextRouter = useRouter({
4316 warn: opts?.router === void 0
4317 });
4318 const router = opts?.router || contextRouter;
4319 const previousResult = (0, import_react2.useRef)(void 0);
4320 return useStore(router.__store, (state) => {
4321 if (opts?.select) {
4322 if (opts.structuralSharing ?? router.options.defaultStructuralSharing) {
4323 const newSlice = replaceEqualDeep(
4324 previousResult.current,
4325 opts.select(state)
4326 );
4327 previousResult.current = newSlice;
4328 return newSlice;
4329 }
4330 return opts.select(state);
4331 }
4332 return state;
4333 });
4334 }
4335
4336 // node_modules/@tanstack/react-router/dist/esm/matchContext.js
4337 var React4 = __toESM(require_react(), 1);
4338 var matchContext = React4.createContext(void 0);
4339 var dummyMatchContext = React4.createContext(
4340 void 0
4341 );
4342
4343 // node_modules/@tanstack/react-router/dist/esm/useMatch.js
4344 function useMatch(opts) {
4345 const nearestMatchId = React5.useContext(
4346 opts.from ? dummyMatchContext : matchContext
4347 );
4348 const matchSelection = useRouterState({
4349 select: (state) => {
4350 const match = state.matches.find(
4351 (d) => opts.from ? opts.from === d.routeId : d.id === nearestMatchId
4352 );
4353 invariant(
4354 !((opts.shouldThrow ?? true) && !match),
4355 `Could not find ${opts.from ? `an active match from "${opts.from}"` : "a nearest match!"}`
4356 );
4357 if (match === void 0) {
4358 return void 0;
4359 }
4360 return opts.select ? opts.select(match) : match;
4361 },
4362 structuralSharing: opts.structuralSharing
4363 });
4364 return matchSelection;
4365 }
4366
4367 // node_modules/@tanstack/react-router/dist/esm/useLoaderData.js
4368 function useLoaderData(opts) {
4369 return useMatch({
4370 from: opts.from,
4371 strict: opts.strict,
4372 structuralSharing: opts.structuralSharing,
4373 select: (s) => {
4374 return opts.select ? opts.select(s.loaderData) : s.loaderData;
4375 }
4376 });
4377 }
4378
4379 // node_modules/@tanstack/react-router/dist/esm/useLoaderDeps.js
4380 function useLoaderDeps(opts) {
4381 const { select, ...rest } = opts;
4382 return useMatch({
4383 ...rest,
4384 select: (s) => {
4385 return select ? select(s.loaderDeps) : s.loaderDeps;
4386 }
4387 });
4388 }
4389
4390 // node_modules/@tanstack/react-router/dist/esm/useParams.js
4391 function useParams(opts) {
4392 return useMatch({
4393 from: opts.from,
4394 shouldThrow: opts.shouldThrow,
4395 structuralSharing: opts.structuralSharing,
4396 strict: opts.strict,
4397 select: (match) => {
4398 const params = opts.strict === false ? match.params : match._strictParams;
4399 return opts.select ? opts.select(params) : params;
4400 }
4401 });
4402 }
4403
4404 // node_modules/@tanstack/react-router/dist/esm/useSearch.js
4405 function useSearch(opts) {
4406 return useMatch({
4407 from: opts.from,
4408 strict: opts.strict,
4409 shouldThrow: opts.shouldThrow,
4410 structuralSharing: opts.structuralSharing,
4411 select: (match) => {
4412 return opts.select ? opts.select(match.search) : match.search;
4413 }
4414 });
4415 }
4416
4417 // node_modules/@tanstack/react-router/dist/esm/useNavigate.js
4418 var React6 = __toESM(require_react(), 1);
4419 function useNavigate(_defaultOpts) {
4420 const router = useRouter();
4421 return React6.useCallback(
4422 (options) => {
4423 return router.navigate({
4424 ...options,
4425 from: options.from ?? _defaultOpts?.from
4426 });
4427 },
4428 [_defaultOpts?.from, router]
4429 );
4430 }
4431
4432 // node_modules/@tanstack/react-router/dist/esm/link.js
4433 var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
4434 var React8 = __toESM(require_react(), 1);
4435 var import_react_dom = __toESM(require_react_dom(), 1);
4436
4437 // node_modules/@tanstack/react-router/dist/esm/utils.js
4438 var React7 = __toESM(require_react(), 1);
4439 var useLayoutEffect2 = typeof window !== "undefined" ? React7.useLayoutEffect : React7.useEffect;
4440 function usePrevious(value) {
4441 const ref = React7.useRef({
4442 value,
4443 prev: null
4444 });
4445 const current = ref.current.value;
4446 if (value !== current) {
4447 ref.current = {
4448 value,
4449 prev: current
4450 };
4451 }
4452 return ref.current.prev;
4453 }
4454 function useIntersectionObserver(ref, callback, intersectionObserverOptions2 = {}, options = {}) {
4455 React7.useEffect(() => {
4456 if (!ref.current || options.disabled || typeof IntersectionObserver !== "function") {
4457 return;
4458 }
4459 const observer = new IntersectionObserver(([entry]) => {
4460 callback(entry);
4461 }, intersectionObserverOptions2);
4462 observer.observe(ref.current);
4463 return () => {
4464 observer.disconnect();
4465 };
4466 }, [callback, intersectionObserverOptions2, options.disabled, ref]);
4467 }
4468 function useForwardedRef(ref) {
4469 const innerRef = React7.useRef(null);
4470 React7.useImperativeHandle(ref, () => innerRef.current, []);
4471 return innerRef;
4472 }
4473
4474 // node_modules/@tanstack/react-router/dist/esm/link.js
4475 function useLinkProps(options, forwardedRef) {
4476 const router = useRouter();
4477 const [isTransitioning, setIsTransitioning] = React8.useState(false);
4478 const hasRenderFetched = React8.useRef(false);
4479 const innerRef = useForwardedRef(forwardedRef);
4480 const {
4481 // custom props
4482 activeProps,
4483 inactiveProps,
4484 activeOptions,
4485 to,
4486 preload: userPreload,
4487 preloadDelay: userPreloadDelay,
4488 hashScrollIntoView,
4489 replace,
4490 startTransition: startTransition2,
4491 resetScroll,
4492 viewTransition,
4493 // element props
4494 children,
4495 target,
4496 disabled,
4497 style,
4498 className,
4499 onClick,
4500 onFocus,
4501 onMouseEnter,
4502 onMouseLeave,
4503 onTouchStart,
4504 ignoreBlocker,
4505 // prevent these from being returned
4506 params: _params,
4507 search: _search,
4508 hash: _hash,
4509 state: _state,
4510 mask: _mask,
4511 reloadDocument: _reloadDocument,
4512 unsafeRelative: _unsafeRelative,
4513 from: _from,
4514 _fromLocation,
4515 ...propsSafeToSpread
4516 } = options;
4517 const currentSearch = useRouterState({
4518 select: (s) => s.location.search,
4519 structuralSharing: true
4520 });
4521 const from = options.from;
4522 const _options = React8.useMemo(
4523 () => {
4524 return { ...options, from };
4525 },
4526 // eslint-disable-next-line react-hooks/exhaustive-deps
4527 [
4528 router,
4529 currentSearch,
4530 from,
4531 options._fromLocation,
4532 options.hash,
4533 options.to,
4534 options.search,
4535 options.params,
4536 options.state,
4537 options.mask,
4538 options.unsafeRelative
4539 ]
4540 );
4541 const next = React8.useMemo(
4542 () => router.buildLocation({ ..._options }),
4543 [router, _options]
4544 );
4545 const hrefOption = React8.useMemo(() => {
4546 if (disabled) {
4547 return void 0;
4548 }
4549 let href = next.maskedLocation ? next.maskedLocation.url : next.url;
4550 let external = false;
4551 if (router.origin) {
4552 if (href.startsWith(router.origin)) {
4553 href = router.history.createHref(href.replace(router.origin, "")) || "/";
4554 } else {
4555 external = true;
4556 }
4557 }
4558 return { href, external };
4559 }, [disabled, next.maskedLocation, next.url, router.origin, router.history]);
4560 const externalLink = React8.useMemo(() => {
4561 if (hrefOption?.external) {
4562 return hrefOption.href;
4563 }
4564 try {
4565 new URL(to);
4566 return to;
4567 } catch {
4568 }
4569 return void 0;
4570 }, [to, hrefOption]);
4571 const preload = options.reloadDocument || externalLink ? false : userPreload ?? router.options.defaultPreload;
4572 const preloadDelay = userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0;
4573 const isActive = useRouterState({
4574 select: (s) => {
4575 if (externalLink) return false;
4576 if (activeOptions?.exact) {
4577 const testExact = exactPathTest(
4578 s.location.pathname,
4579 next.pathname,
4580 router.basepath
4581 );
4582 if (!testExact) {
4583 return false;
4584 }
4585 } else {
4586 const currentPathSplit = removeTrailingSlash(
4587 s.location.pathname,
4588 router.basepath
4589 );
4590 const nextPathSplit = removeTrailingSlash(
4591 next.pathname,
4592 router.basepath
4593 );
4594 const pathIsFuzzyEqual = currentPathSplit.startsWith(nextPathSplit) && (currentPathSplit.length === nextPathSplit.length || currentPathSplit[nextPathSplit.length] === "/");
4595 if (!pathIsFuzzyEqual) {
4596 return false;
4597 }
4598 }
4599 if (activeOptions?.includeSearch ?? true) {
4600 const searchTest = deepEqual(s.location.search, next.search, {
4601 partial: !activeOptions?.exact,
4602 ignoreUndefined: !activeOptions?.explicitUndefined
4603 });
4604 if (!searchTest) {
4605 return false;
4606 }
4607 }
4608 if (activeOptions?.includeHash) {
4609 return s.location.hash === next.hash;
4610 }
4611 return true;
4612 }
4613 });
4614 const doPreload = React8.useCallback(() => {
4615 router.preloadRoute({ ..._options }).catch((err) => {
4616 console.warn(err);
4617 console.warn(preloadWarning);
4618 });
4619 }, [router, _options]);
4620 const preloadViewportIoCallback = React8.useCallback(
4621 (entry) => {
4622 if (entry?.isIntersecting) {
4623 doPreload();
4624 }
4625 },
4626 [doPreload]
4627 );
4628 useIntersectionObserver(
4629 innerRef,
4630 preloadViewportIoCallback,
4631 intersectionObserverOptions,
4632 { disabled: !!disabled || !(preload === "viewport") }
4633 );
4634 React8.useEffect(() => {
4635 if (hasRenderFetched.current) {
4636 return;
4637 }
4638 if (!disabled && preload === "render") {
4639 doPreload();
4640 hasRenderFetched.current = true;
4641 }
4642 }, [disabled, doPreload, preload]);
4643 const handleClick = (e) => {
4644 const elementTarget = e.currentTarget.getAttribute("target");
4645 const effectiveTarget = target !== void 0 ? target : elementTarget;
4646 if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!effectiveTarget || effectiveTarget === "_self") && e.button === 0) {
4647 e.preventDefault();
4648 (0, import_react_dom.flushSync)(() => {
4649 setIsTransitioning(true);
4650 });
4651 const unsub = router.subscribe("onResolved", () => {
4652 unsub();
4653 setIsTransitioning(false);
4654 });
4655 router.navigate({
4656 ..._options,
4657 replace,
4658 resetScroll,
4659 hashScrollIntoView,
4660 startTransition: startTransition2,
4661 viewTransition,
4662 ignoreBlocker
4663 });
4664 }
4665 };
4666 if (externalLink) {
4667 return {
4668 ...propsSafeToSpread,
4669 ref: innerRef,
4670 href: externalLink,
4671 ...children && { children },
4672 ...target && { target },
4673 ...disabled && { disabled },
4674 ...style && { style },
4675 ...className && { className },
4676 ...onClick && { onClick },
4677 ...onFocus && { onFocus },
4678 ...onMouseEnter && { onMouseEnter },
4679 ...onMouseLeave && { onMouseLeave },
4680 ...onTouchStart && { onTouchStart }
4681 };
4682 }
4683 const handleFocus = (_) => {
4684 if (disabled) return;
4685 if (preload) {
4686 doPreload();
4687 }
4688 };
4689 const handleTouchStart = handleFocus;
4690 const handleEnter = (e) => {
4691 if (disabled || !preload) return;
4692 if (!preloadDelay) {
4693 doPreload();
4694 } else {
4695 const eventTarget = e.target;
4696 if (timeoutMap.has(eventTarget)) {
4697 return;
4698 }
4699 const id = setTimeout(() => {
4700 timeoutMap.delete(eventTarget);
4701 doPreload();
4702 }, preloadDelay);
4703 timeoutMap.set(eventTarget, id);
4704 }
4705 };
4706 const handleLeave = (e) => {
4707 if (disabled || !preload || !preloadDelay) return;
4708 const eventTarget = e.target;
4709 const id = timeoutMap.get(eventTarget);
4710 if (id) {
4711 clearTimeout(id);
4712 timeoutMap.delete(eventTarget);
4713 }
4714 };
4715 const resolvedActiveProps = isActive ? functionalUpdate(activeProps, {}) ?? STATIC_ACTIVE_OBJECT : STATIC_EMPTY_OBJECT;
4716 const resolvedInactiveProps = isActive ? STATIC_EMPTY_OBJECT : functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT;
4717 const resolvedClassName = [
4718 className,
4719 resolvedActiveProps.className,
4720 resolvedInactiveProps.className
4721 ].filter(Boolean).join(" ");
4722 const resolvedStyle = (style || resolvedActiveProps.style || resolvedInactiveProps.style) && {
4723 ...style,
4724 ...resolvedActiveProps.style,
4725 ...resolvedInactiveProps.style
4726 };
4727 return {
4728 ...propsSafeToSpread,
4729 ...resolvedActiveProps,
4730 ...resolvedInactiveProps,
4731 href: hrefOption?.href,
4732 ref: innerRef,
4733 onClick: composeHandlers([onClick, handleClick]),
4734 onFocus: composeHandlers([onFocus, handleFocus]),
4735 onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),
4736 onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),
4737 onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),
4738 disabled: !!disabled,
4739 target,
4740 ...resolvedStyle && { style: resolvedStyle },
4741 ...resolvedClassName && { className: resolvedClassName },
4742 ...disabled && STATIC_DISABLED_PROPS,
4743 ...isActive && STATIC_ACTIVE_PROPS,
4744 ...isTransitioning && STATIC_TRANSITIONING_PROPS
4745 };
4746 }
4747 var STATIC_EMPTY_OBJECT = {};
4748 var STATIC_ACTIVE_OBJECT = { className: "active" };
4749 var STATIC_DISABLED_PROPS = { role: "link", "aria-disabled": true };
4750 var STATIC_ACTIVE_PROPS = { "data-status": "active", "aria-current": "page" };
4751 var STATIC_TRANSITIONING_PROPS = { "data-transitioning": "transitioning" };
4752 var timeoutMap = /* @__PURE__ */ new WeakMap();
4753 var intersectionObserverOptions = {
4754 rootMargin: "100px"
4755 };
4756 var composeHandlers = (handlers) => (e) => {
4757 for (const handler of handlers) {
4758 if (!handler) continue;
4759 if (e.defaultPrevented) return;
4760 handler(e);
4761 }
4762 };
4763 function createLink(Comp) {
4764 return React8.forwardRef(function CreatedLink(props, ref) {
4765 return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Link, { ...props, _asChild: Comp, ref });
4766 });
4767 }
4768 var Link = React8.forwardRef(
4769 (props, ref) => {
4770 const { _asChild, ...rest } = props;
4771 const {
4772 type: _type,
4773 ref: innerRef,
4774 ...linkProps
4775 } = useLinkProps(rest, ref);
4776 const children = typeof rest.children === "function" ? rest.children({
4777 isActive: linkProps["data-status"] === "active"
4778 }) : rest.children;
4779 if (_asChild === void 0) {
4780 delete linkProps.disabled;
4781 }
4782 return React8.createElement(
4783 _asChild ? _asChild : "a",
4784 {
4785 ...linkProps,
4786 ref: innerRef
4787 },
4788 children
4789 );
4790 }
4791 );
4792 function isCtrlEvent(e) {
4793 return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
4794 }
4795
4796 // node_modules/@tanstack/react-router/dist/esm/route.js
4797 var Route = class extends BaseRoute {
4798 /**
4799 * @deprecated Use the `createRoute` function instead.
4800 */
4801 constructor(options) {
4802 super(options);
4803 this.useMatch = (opts) => {
4804 return useMatch({
4805 select: opts?.select,
4806 from: this.id,
4807 structuralSharing: opts?.structuralSharing
4808 });
4809 };
4810 this.useRouteContext = (opts) => {
4811 return useMatch({
4812 ...opts,
4813 from: this.id,
4814 select: (d) => opts?.select ? opts.select(d.context) : d.context
4815 });
4816 };
4817 this.useSearch = (opts) => {
4818 return useSearch({
4819 select: opts?.select,
4820 structuralSharing: opts?.structuralSharing,
4821 from: this.id
4822 });
4823 };
4824 this.useParams = (opts) => {
4825 return useParams({
4826 select: opts?.select,
4827 structuralSharing: opts?.structuralSharing,
4828 from: this.id
4829 });
4830 };
4831 this.useLoaderDeps = (opts) => {
4832 return useLoaderDeps({ ...opts, from: this.id });
4833 };
4834 this.useLoaderData = (opts) => {
4835 return useLoaderData({ ...opts, from: this.id });
4836 };
4837 this.useNavigate = () => {
4838 return useNavigate({ from: this.fullPath });
4839 };
4840 this.Link = import_react3.default.forwardRef(
4841 (props, ref) => {
4842 return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Link, { ref, from: this.fullPath, ...props });
4843 }
4844 );
4845 this.$$typeof = /* @__PURE__ */ Symbol.for("react.memo");
4846 }
4847 };
4848 function createRoute(options) {
4849 return new Route(
4850 // TODO: Help us TypeChris, you're our only hope!
4851 options
4852 );
4853 }
4854 var RootRoute = class extends BaseRootRoute {
4855 /**
4856 * @deprecated `RootRoute` is now an internal implementation detail. Use `createRootRoute()` instead.
4857 */
4858 constructor(options) {
4859 super(options);
4860 this.useMatch = (opts) => {
4861 return useMatch({
4862 select: opts?.select,
4863 from: this.id,
4864 structuralSharing: opts?.structuralSharing
4865 });
4866 };
4867 this.useRouteContext = (opts) => {
4868 return useMatch({
4869 ...opts,
4870 from: this.id,
4871 select: (d) => opts?.select ? opts.select(d.context) : d.context
4872 });
4873 };
4874 this.useSearch = (opts) => {
4875 return useSearch({
4876 select: opts?.select,
4877 structuralSharing: opts?.structuralSharing,
4878 from: this.id
4879 });
4880 };
4881 this.useParams = (opts) => {
4882 return useParams({
4883 select: opts?.select,
4884 structuralSharing: opts?.structuralSharing,
4885 from: this.id
4886 });
4887 };
4888 this.useLoaderDeps = (opts) => {
4889 return useLoaderDeps({ ...opts, from: this.id });
4890 };
4891 this.useLoaderData = (opts) => {
4892 return useLoaderData({ ...opts, from: this.id });
4893 };
4894 this.useNavigate = () => {
4895 return useNavigate({ from: this.fullPath });
4896 };
4897 this.Link = import_react3.default.forwardRef(
4898 (props, ref) => {
4899 return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Link, { ref, from: this.fullPath, ...props });
4900 }
4901 );
4902 this.$$typeof = /* @__PURE__ */ Symbol.for("react.memo");
4903 }
4904 };
4905 function createRootRoute(options) {
4906 return new RootRoute(options);
4907 }
4908
4909 // node_modules/@tanstack/react-router/dist/esm/fileRoute.js
4910 function createFileRoute(path) {
4911 if (typeof path === "object") {
4912 return new FileRoute(path, {
4913 silent: true
4914 }).createRoute(path);
4915 }
4916 return new FileRoute(path, {
4917 silent: true
4918 }).createRoute;
4919 }
4920 var FileRoute = class {
4921 constructor(path, _opts) {
4922 this.path = path;
4923 this.createRoute = (options) => {
4924 tiny_warning_esm_default(
4925 this.silent,
4926 "FileRoute is deprecated and will be removed in the next major version. Use the createFileRoute(path)(options) function instead."
4927 );
4928 const route = createRoute(options);
4929 route.isRoot = false;
4930 return route;
4931 };
4932 this.silent = _opts?.silent;
4933 }
4934 };
4935 var LazyRoute = class {
4936 constructor(opts) {
4937 this.useMatch = (opts2) => {
4938 return useMatch({
4939 select: opts2?.select,
4940 from: this.options.id,
4941 structuralSharing: opts2?.structuralSharing
4942 });
4943 };
4944 this.useRouteContext = (opts2) => {
4945 return useMatch({
4946 from: this.options.id,
4947 select: (d) => opts2?.select ? opts2.select(d.context) : d.context
4948 });
4949 };
4950 this.useSearch = (opts2) => {
4951 return useSearch({
4952 select: opts2?.select,
4953 structuralSharing: opts2?.structuralSharing,
4954 from: this.options.id
4955 });
4956 };
4957 this.useParams = (opts2) => {
4958 return useParams({
4959 select: opts2?.select,
4960 structuralSharing: opts2?.structuralSharing,
4961 from: this.options.id
4962 });
4963 };
4964 this.useLoaderDeps = (opts2) => {
4965 return useLoaderDeps({ ...opts2, from: this.options.id });
4966 };
4967 this.useLoaderData = (opts2) => {
4968 return useLoaderData({ ...opts2, from: this.options.id });
4969 };
4970 this.useNavigate = () => {
4971 const router = useRouter();
4972 return useNavigate({ from: router.routesById[this.options.id].fullPath });
4973 };
4974 this.options = opts;
4975 this.$$typeof = /* @__PURE__ */ Symbol.for("react.memo");
4976 }
4977 };
4978 function createLazyRoute(id) {
4979 return (opts) => {
4980 return new LazyRoute({
4981 id,
4982 ...opts
4983 });
4984 };
4985 }
4986 function createLazyFileRoute(id) {
4987 if (typeof id === "object") {
4988 return new LazyRoute(id);
4989 }
4990 return (opts) => new LazyRoute({ id, ...opts });
4991 }
4992
4993 // node_modules/@tanstack/react-router/dist/esm/Matches.js
4994 var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
4995 var React11 = __toESM(require_react(), 1);
4996
4997 // node_modules/@tanstack/react-router/dist/esm/Transitioner.js
4998 var React9 = __toESM(require_react(), 1);
4999 function Transitioner() {
5000 const router = useRouter();
5001 const mountLoadForRouter = React9.useRef({ router, mounted: false });
5002 const [isTransitioning, setIsTransitioning] = React9.useState(false);
5003 const { hasPendingMatches, isLoading } = useRouterState({
5004 select: (s) => ({
5005 isLoading: s.isLoading,
5006 hasPendingMatches: s.matches.some((d) => d.status === "pending")
5007 }),
5008 structuralSharing: true
5009 });
5010 const previousIsLoading = usePrevious(isLoading);
5011 const isAnyPending = isLoading || isTransitioning || hasPendingMatches;
5012 const previousIsAnyPending = usePrevious(isAnyPending);
5013 const isPagePending = isLoading || hasPendingMatches;
5014 const previousIsPagePending = usePrevious(isPagePending);
5015 router.startTransition = (fn) => {
5016 setIsTransitioning(true);
5017 React9.startTransition(() => {
5018 fn();
5019 setIsTransitioning(false);
5020 });
5021 };
5022 React9.useEffect(() => {
5023 const unsub = router.history.subscribe(router.load);
5024 const nextLocation = router.buildLocation({
5025 to: router.latestLocation.pathname,
5026 search: true,
5027 params: true,
5028 hash: true,
5029 state: true,
5030 _includeValidateSearch: true
5031 });
5032 if (trimPathRight(router.latestLocation.href) !== trimPathRight(nextLocation.href)) {
5033 router.commitLocation({ ...nextLocation, replace: true });
5034 }
5035 return () => {
5036 unsub();
5037 };
5038 }, [router, router.history]);
5039 useLayoutEffect2(() => {
5040 if (
5041 // if we are hydrating from SSR, loading is triggered in ssr-client
5042 typeof window !== "undefined" && router.ssr || mountLoadForRouter.current.router === router && mountLoadForRouter.current.mounted
5043 ) {
5044 return;
5045 }
5046 mountLoadForRouter.current = { router, mounted: true };
5047 const tryLoad = async () => {
5048 try {
5049 await router.load();
5050 } catch (err) {
5051 console.error(err);
5052 }
5053 };
5054 tryLoad();
5055 }, [router]);
5056 useLayoutEffect2(() => {
5057 if (previousIsLoading && !isLoading) {
5058 router.emit({
5059 type: "onLoad",
5060 // When the new URL has committed, when the new matches have been loaded into state.matches
5061 ...getLocationChangeInfo(router.state)
5062 });
5063 }
5064 }, [previousIsLoading, router, isLoading]);
5065 useLayoutEffect2(() => {
5066 if (previousIsPagePending && !isPagePending) {
5067 router.emit({
5068 type: "onBeforeRouteMount",
5069 ...getLocationChangeInfo(router.state)
5070 });
5071 }
5072 }, [isPagePending, previousIsPagePending, router]);
5073 useLayoutEffect2(() => {
5074 if (previousIsAnyPending && !isAnyPending) {
5075 router.emit({
5076 type: "onResolved",
5077 ...getLocationChangeInfo(router.state)
5078 });
5079 router.__store.setState((s) => ({
5080 ...s,
5081 status: "idle",
5082 resolvedLocation: s.location
5083 }));
5084 handleHashScroll(router);
5085 }
5086 }, [isAnyPending, previousIsAnyPending, router]);
5087 return null;
5088 }
5089
5090 // node_modules/@tanstack/react-router/dist/esm/Match.js
5091 var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
5092 var React10 = __toESM(require_react(), 1);
5093
5094 // node_modules/@tanstack/react-router/dist/esm/not-found.js
5095 var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
5096 function CatchNotFound(props) {
5097 const resetKey = useRouterState({
5098 select: (s) => `not-found-${s.location.pathname}-${s.status}`
5099 });
5100 return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
5101 CatchBoundary,
5102 {
5103 getResetKey: () => resetKey,
5104 onCatch: (error, errorInfo) => {
5105 if (isNotFound(error)) {
5106 props.onCatch?.(error, errorInfo);
5107 } else {
5108 throw error;
5109 }
5110 },
5111 errorComponent: ({ error }) => {
5112 if (isNotFound(error)) {
5113 return props.fallback?.(error);
5114 } else {
5115 throw error;
5116 }
5117 },
5118 children: props.children
5119 }
5120 );
5121 }
5122 function DefaultGlobalNotFound() {
5123 return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { children: "Not Found" });
5124 }
5125
5126 // node_modules/@tanstack/react-router/dist/esm/SafeFragment.js
5127 var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
5128 function SafeFragment(props) {
5129 return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: props.children });
5130 }
5131
5132 // node_modules/@tanstack/react-router/dist/esm/renderRouteNotFound.js
5133 var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
5134 function renderRouteNotFound(router, route, data) {
5135 if (!route.options.notFoundComponent) {
5136 if (router.options.defaultNotFoundComponent) {
5137 return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(router.options.defaultNotFoundComponent, { data });
5138 }
5139 if (true) {
5140 tiny_warning_esm_default(
5141 route.options.notFoundComponent,
5142 `A notFoundError was encountered on the route with ID "${route.id}", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (<div>Not Found<div>)`
5143 );
5144 }
5145 return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(DefaultGlobalNotFound, {});
5146 }
5147 return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(route.options.notFoundComponent, { data });
5148 }
5149
5150 // node_modules/@tanstack/react-router/dist/esm/scroll-restoration.js
5151 var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
5152
5153 // node_modules/@tanstack/react-router/dist/esm/ScriptOnce.js
5154 var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
5155 function ScriptOnce({ children }) {
5156 const router = useRouter();
5157 if (!router.isServer) {
5158 return null;
5159 }
5160 return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
5161 "script",
5162 {
5163 nonce: router.options.ssr?.nonce,
5164 className: "$tsr",
5165 dangerouslySetInnerHTML: {
5166 __html: [children].filter(Boolean).join("\n") + ";$_TSR.c()"
5167 }
5168 }
5169 );
5170 }
5171
5172 // node_modules/@tanstack/react-router/dist/esm/scroll-restoration.js
5173 function ScrollRestoration() {
5174 const router = useRouter();
5175 if (!router.isScrollRestoring || !router.isServer) {
5176 return null;
5177 }
5178 if (typeof router.options.scrollRestoration === "function") {
5179 const shouldRestore = router.options.scrollRestoration({
5180 location: router.latestLocation
5181 });
5182 if (!shouldRestore) {
5183 return null;
5184 }
5185 }
5186 const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
5187 const userKey = getKey(router.latestLocation);
5188 const resolvedKey = userKey !== defaultGetScrollRestorationKey(router.latestLocation) ? userKey : void 0;
5189 const restoreScrollOptions = {
5190 storageKey,
5191 shouldScrollRestoration: true
5192 };
5193 if (resolvedKey) {
5194 restoreScrollOptions.key = resolvedKey;
5195 }
5196 return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
5197 ScriptOnce,
5198 {
5199 children: `(${restoreScroll.toString()})(${JSON.stringify(restoreScrollOptions)})`
5200 }
5201 );
5202 }
5203
5204 // node_modules/@tanstack/react-router/dist/esm/Match.js
5205 var Match = React10.memo(function MatchImpl({
5206 matchId
5207 }) {
5208 const router = useRouter();
5209 const matchState = useRouterState({
5210 select: (s) => {
5211 const match = s.matches.find((d) => d.id === matchId);
5212 invariant(
5213 match,
5214 `Could not find match for matchId "${matchId}". Please file an issue!`
5215 );
5216 return {
5217 routeId: match.routeId,
5218 ssr: match.ssr,
5219 _displayPending: match._displayPending
5220 };
5221 },
5222 structuralSharing: true
5223 });
5224 const route = router.routesById[matchState.routeId];
5225 const PendingComponent = route.options.pendingComponent ?? router.options.defaultPendingComponent;
5226 const pendingElement = PendingComponent ? /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(PendingComponent, {}) : null;
5227 const routeErrorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent;
5228 const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch;
5229 const routeNotFoundComponent = route.isRoot ? (
5230 // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component
5231 route.options.notFoundComponent ?? router.options.notFoundRoute?.options.component
5232 ) : route.options.notFoundComponent;
5233 const resolvedNoSsr = matchState.ssr === false || matchState.ssr === "data-only";
5234 const ResolvedSuspenseBoundary = (
5235 // If we're on the root route, allow forcefully wrapping in suspense
5236 (!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) && (route.options.wrapInSuspense ?? PendingComponent ?? (route.options.errorComponent?.preload || resolvedNoSsr)) ? React10.Suspense : SafeFragment
5237 );
5238 const ResolvedCatchBoundary = routeErrorComponent ? CatchBoundary : SafeFragment;
5239 const ResolvedNotFoundBoundary = routeNotFoundComponent ? CatchNotFound : SafeFragment;
5240 const resetKey = useRouterState({
5241 select: (s) => s.loadedAt
5242 });
5243 const parentRouteId = useRouterState({
5244 select: (s) => {
5245 const index = s.matches.findIndex((d) => d.id === matchId);
5246 return s.matches[index - 1]?.routeId;
5247 }
5248 });
5249 const ShellComponent = route.isRoot ? route.options.shellComponent ?? SafeFragment : SafeFragment;
5250 return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(ShellComponent, { children: [
5251 /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(matchContext.Provider, { value: matchId, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(ResolvedSuspenseBoundary, { fallback: pendingElement, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
5252 ResolvedCatchBoundary,
5253 {
5254 getResetKey: () => resetKey,
5255 errorComponent: routeErrorComponent || ErrorComponent,
5256 onCatch: (error, errorInfo) => {
5257 if (isNotFound(error)) throw error;
5258 tiny_warning_esm_default(false, `Error in route match: ${matchId}`);
5259 routeOnCatch?.(error, errorInfo);
5260 },
5261 children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
5262 ResolvedNotFoundBoundary,
5263 {
5264 fallback: (error) => {
5265 if (!routeNotFoundComponent || error.routeId && error.routeId !== matchState.routeId || !error.routeId && !route.isRoot)
5266 throw error;
5267 return React10.createElement(routeNotFoundComponent, error);
5268 },
5269 children: resolvedNoSsr || matchState._displayPending ? /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(ClientOnly, { fallback: pendingElement, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(MatchInner, { matchId }) }) : /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(MatchInner, { matchId })
5270 }
5271 )
5272 }
5273 ) }) }),
5274 parentRouteId === rootRouteId && router.options.scrollRestoration ? /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
5275 /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(OnRendered, {}),
5276 /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(ScrollRestoration, {})
5277 ] }) : null
5278 ] });
5279 });
5280 function OnRendered() {
5281 const router = useRouter();
5282 const prevLocationRef = React10.useRef(
5283 void 0
5284 );
5285 return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
5286 "script",
5287 {
5288 suppressHydrationWarning: true,
5289 ref: (el) => {
5290 if (el && (prevLocationRef.current === void 0 || prevLocationRef.current.href !== router.latestLocation.href)) {
5291 router.emit({
5292 type: "onRendered",
5293 ...getLocationChangeInfo(router.state)
5294 });
5295 prevLocationRef.current = router.latestLocation;
5296 }
5297 }
5298 },
5299 router.latestLocation.state.__TSR_key
5300 );
5301 }
5302 var MatchInner = React10.memo(function MatchInnerImpl({
5303 matchId
5304 }) {
5305 const router = useRouter();
5306 const { match, key, routeId } = useRouterState({
5307 select: (s) => {
5308 const match2 = s.matches.find((d) => d.id === matchId);
5309 const routeId2 = match2.routeId;
5310 const remountFn = router.routesById[routeId2].options.remountDeps ?? router.options.defaultRemountDeps;
5311 const remountDeps = remountFn?.({
5312 routeId: routeId2,
5313 loaderDeps: match2.loaderDeps,
5314 params: match2._strictParams,
5315 search: match2._strictSearch
5316 });
5317 const key2 = remountDeps ? JSON.stringify(remountDeps) : void 0;
5318 return {
5319 key: key2,
5320 routeId: routeId2,
5321 match: {
5322 id: match2.id,
5323 status: match2.status,
5324 error: match2.error,
5325 _forcePending: match2._forcePending,
5326 _displayPending: match2._displayPending
5327 }
5328 };
5329 },
5330 structuralSharing: true
5331 });
5332 const route = router.routesById[routeId];
5333 const out = React10.useMemo(() => {
5334 const Comp = route.options.component ?? router.options.defaultComponent;
5335 if (Comp) {
5336 return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Comp, {}, key);
5337 }
5338 return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Outlet, {});
5339 }, [key, route.options.component, router.options.defaultComponent]);
5340 if (match._displayPending) {
5341 throw router.getMatch(match.id)?._nonReactive.displayPendingPromise;
5342 }
5343 if (match._forcePending) {
5344 throw router.getMatch(match.id)?._nonReactive.minPendingPromise;
5345 }
5346 if (match.status === "pending") {
5347 const pendingMinMs = route.options.pendingMinMs ?? router.options.defaultPendingMinMs;
5348 if (pendingMinMs) {
5349 const routerMatch = router.getMatch(match.id);
5350 if (routerMatch && !routerMatch._nonReactive.minPendingPromise) {
5351 if (!router.isServer) {
5352 const minPendingPromise = createControlledPromise();
5353 routerMatch._nonReactive.minPendingPromise = minPendingPromise;
5354 setTimeout(() => {
5355 minPendingPromise.resolve();
5356 routerMatch._nonReactive.minPendingPromise = void 0;
5357 }, pendingMinMs);
5358 }
5359 }
5360 }
5361 throw router.getMatch(match.id)?._nonReactive.loadPromise;
5362 }
5363 if (match.status === "notFound") {
5364 invariant(isNotFound(match.error), "Expected a notFound error");
5365 return renderRouteNotFound(router, route, match.error);
5366 }
5367 if (match.status === "redirected") {
5368 invariant(isRedirect(match.error), "Expected a redirect error");
5369 throw router.getMatch(match.id)?._nonReactive.loadPromise;
5370 }
5371 if (match.status === "error") {
5372 if (router.isServer) {
5373 const RouteErrorComponent = (route.options.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent;
5374 return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
5375 RouteErrorComponent,
5376 {
5377 error: match.error,
5378 reset: void 0,
5379 info: {
5380 componentStack: ""
5381 }
5382 }
5383 );
5384 }
5385 throw match.error;
5386 }
5387 return out;
5388 });
5389 var Outlet = React10.memo(function OutletImpl() {
5390 const router = useRouter();
5391 const matchId = React10.useContext(matchContext);
5392 const routeId = useRouterState({
5393 select: (s) => s.matches.find((d) => d.id === matchId)?.routeId
5394 });
5395 const route = router.routesById[routeId];
5396 const parentGlobalNotFound = useRouterState({
5397 select: (s) => {
5398 const matches = s.matches;
5399 const parentMatch = matches.find((d) => d.id === matchId);
5400 invariant(
5401 parentMatch,
5402 `Could not find parent match for matchId "${matchId}"`
5403 );
5404 return parentMatch.globalNotFound;
5405 }
5406 });
5407 const childMatchId = useRouterState({
5408 select: (s) => {
5409 const matches = s.matches;
5410 const index = matches.findIndex((d) => d.id === matchId);
5411 return matches[index + 1]?.id;
5412 }
5413 });
5414 const pendingElement = router.options.defaultPendingComponent ? /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(router.options.defaultPendingComponent, {}) : null;
5415 if (parentGlobalNotFound) {
5416 return renderRouteNotFound(router, route, void 0);
5417 }
5418 if (!childMatchId) {
5419 return null;
5420 }
5421 const nextMatch = /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Match, { matchId: childMatchId });
5422 if (matchId === rootRouteId) {
5423 return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(React10.Suspense, { fallback: pendingElement, children: nextMatch });
5424 }
5425 return nextMatch;
5426 });
5427
5428 // node_modules/@tanstack/react-router/dist/esm/Matches.js
5429 function Matches() {
5430 const router = useRouter();
5431 const rootRoute = router.routesById[rootRouteId];
5432 const PendingComponent = rootRoute.options.pendingComponent ?? router.options.defaultPendingComponent;
5433 const pendingElement = PendingComponent ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(PendingComponent, {}) : null;
5434 const ResolvedSuspense = router.isServer || typeof document !== "undefined" && router.ssr ? SafeFragment : React11.Suspense;
5435 const inner = /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(ResolvedSuspense, { fallback: pendingElement, children: [
5436 !router.isServer && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Transitioner, {}),
5437 /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(MatchesInner, {})
5438 ] });
5439 return router.options.InnerWrap ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(router.options.InnerWrap, { children: inner }) : inner;
5440 }
5441 function MatchesInner() {
5442 const router = useRouter();
5443 const matchId = useRouterState({
5444 select: (s) => {
5445 return s.matches[0]?.id;
5446 }
5447 });
5448 const resetKey = useRouterState({
5449 select: (s) => s.loadedAt
5450 });
5451 const matchComponent = matchId ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Match, { matchId }) : null;
5452 return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(matchContext.Provider, { value: matchId, children: router.options.disableGlobalCatchBoundary ? matchComponent : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
5453 CatchBoundary,
5454 {
5455 getResetKey: () => resetKey,
5456 errorComponent: ErrorComponent,
5457 onCatch: (error) => {
5458 tiny_warning_esm_default(
5459 false,
5460 `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`
5461 );
5462 tiny_warning_esm_default(false, error.message || error.toString());
5463 },
5464 children: matchComponent
5465 }
5466 ) });
5467 }
5468 function useMatches(opts) {
5469 return useRouterState({
5470 select: (state) => {
5471 const matches = state.matches;
5472 return opts?.select ? opts.select(matches) : matches;
5473 },
5474 structuralSharing: opts?.structuralSharing
5475 });
5476 }
5477
5478 // node_modules/@tanstack/react-router/dist/esm/router.js
5479 var createRouter = (options) => {
5480 return new Router(options);
5481 };
5482 var Router = class extends RouterCore {
5483 constructor(options) {
5484 super(options);
5485 }
5486 };
5487 if (typeof globalThis !== "undefined") {
5488 globalThis.createFileRoute = createFileRoute;
5489 globalThis.createLazyFileRoute = createLazyFileRoute;
5490 } else if (typeof window !== "undefined") {
5491 window.createFileRoute = createFileRoute;
5492 window.createLazyFileRoute = createLazyFileRoute;
5493 }
5494
5495 // node_modules/@tanstack/react-router/dist/esm/RouterProvider.js
5496 var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
5497 function RouterContextProvider({
5498 router,
5499 children,
5500 ...rest
5501 }) {
5502 if (Object.keys(rest).length > 0) {
5503 router.update({
5504 ...router.options,
5505 ...rest,
5506 context: {
5507 ...router.options.context,
5508 ...rest.context
5509 }
5510 });
5511 }
5512 const routerContext2 = getRouterContext();
5513 const provider = /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(routerContext2.Provider, { value: router, children });
5514 if (router.options.Wrap) {
5515 return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(router.options.Wrap, { children: provider });
5516 }
5517 return provider;
5518 }
5519 function RouterProvider({ router, ...rest }) {
5520 return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(RouterContextProvider, { router, ...rest, children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Matches, {}) });
5521 }
5522
5523 // node_modules/@tanstack/react-router/dist/esm/useBlocker.js
5524 var React12 = __toESM(require_react(), 1);
5525 function _resolveBlockerOpts(opts, condition) {
5526 if (opts === void 0) {
5527 return {
5528 shouldBlockFn: () => true,
5529 withResolver: false
5530 };
5531 }
5532 if ("shouldBlockFn" in opts) {
5533 return opts;
5534 }
5535 if (typeof opts === "function") {
5536 const shouldBlock2 = Boolean(condition ?? true);
5537 const _customBlockerFn2 = async () => {
5538 if (shouldBlock2) return await opts();
5539 return false;
5540 };
5541 return {
5542 shouldBlockFn: _customBlockerFn2,
5543 enableBeforeUnload: shouldBlock2,
5544 withResolver: false
5545 };
5546 }
5547 const shouldBlock = Boolean(opts.condition ?? true);
5548 const fn = opts.blockerFn;
5549 const _customBlockerFn = async () => {
5550 if (shouldBlock && fn !== void 0) {
5551 return await fn();
5552 }
5553 return shouldBlock;
5554 };
5555 return {
5556 shouldBlockFn: _customBlockerFn,
5557 enableBeforeUnload: shouldBlock,
5558 withResolver: fn === void 0
5559 };
5560 }
5561 function useBlocker(opts, condition) {
5562 const {
5563 shouldBlockFn,
5564 enableBeforeUnload = true,
5565 disabled = false,
5566 withResolver = false
5567 } = _resolveBlockerOpts(opts, condition);
5568 const router = useRouter();
5569 const { history } = router;
5570 const [resolver, setResolver] = React12.useState({
5571 status: "idle",
5572 current: void 0,
5573 next: void 0,
5574 action: void 0,
5575 proceed: void 0,
5576 reset: void 0
5577 });
5578 React12.useEffect(() => {
5579 const blockerFnComposed = async (blockerFnArgs) => {
5580 function getLocation(location) {
5581 const parsedLocation = router.parseLocation(location);
5582 const matchedRoutes = router.getMatchedRoutes(
5583 parsedLocation.pathname,
5584 void 0
5585 );
5586 if (matchedRoutes.foundRoute === void 0) {
5587 throw new Error(`No route found for location ${location.href}`);
5588 }
5589 return {
5590 routeId: matchedRoutes.foundRoute.id,
5591 fullPath: matchedRoutes.foundRoute.fullPath,
5592 pathname: parsedLocation.pathname,
5593 params: matchedRoutes.routeParams,
5594 search: parsedLocation.search
5595 };
5596 }
5597 const current = getLocation(blockerFnArgs.currentLocation);
5598 const next = getLocation(blockerFnArgs.nextLocation);
5599 const shouldBlock = await shouldBlockFn({
5600 action: blockerFnArgs.action,
5601 current,
5602 next
5603 });
5604 if (!withResolver) {
5605 return shouldBlock;
5606 }
5607 if (!shouldBlock) {
5608 return false;
5609 }
5610 const promise = new Promise((resolve) => {
5611 setResolver({
5612 status: "blocked",
5613 current,
5614 next,
5615 action: blockerFnArgs.action,
5616 proceed: () => resolve(false),
5617 reset: () => resolve(true)
5618 });
5619 });
5620 const canNavigateAsync = await promise;
5621 setResolver({
5622 status: "idle",
5623 current: void 0,
5624 next: void 0,
5625 action: void 0,
5626 proceed: void 0,
5627 reset: void 0
5628 });
5629 return canNavigateAsync;
5630 };
5631 return disabled ? void 0 : history.block({ blockerFn: blockerFnComposed, enableBeforeUnload });
5632 }, [
5633 shouldBlockFn,
5634 enableBeforeUnload,
5635 disabled,
5636 withResolver,
5637 history,
5638 router
5639 ]);
5640 return resolver;
5641 }
5642
5643 // node_modules/@tanstack/react-router/dist/esm/useLocation.js
5644 function useLocation(opts) {
5645 return useRouterState({
5646 select: (state) => opts?.select ? opts.select(state.location) : state.location
5647 });
5648 }
5649
5650 // node_modules/@tanstack/react-router/dist/esm/useCanGoBack.js
5651 function useCanGoBack() {
5652 return useRouterState({ select: (s) => s.location.state.__TSR_index !== 0 });
5653 }
5654
5655 // packages/route/build-module/lock-unlock.mjs
5656 var import_private_apis = __toESM(require_private_apis(), 1);
5657 var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
5658 "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
5659 "@wordpress/route"
5660 );
5661
5662 // packages/route/build-module/private-apis.mjs
5663 var privateApis = {};
5664 lock(privateApis, {
5665 // Router creation and setup
5666 createBrowserHistory,
5667 createLazyRoute,
5668 createMemoryHistory,
5669 createRouter,
5670 createRootRoute,
5671 createRoute,
5672 Outlet,
5673 RouterProvider,
5674 // Internal routing utilities
5675 redirect,
5676 createLink,
5677 useCanGoBack,
5678 useLoaderData,
5679 useLocation,
5680 useMatches,
5681 useRouter,
5682 useRouterState,
5683 useBlocker,
5684 // History utilities
5685 parseHref
5686 });
5687
5688 // packages/route/build-module/index.mjs
5689 function useInvalidate() {
5690 const router = useRouter();
5691 return () => router.invalidate();
5692 }
5693 export {
5694 Link,
5695 notFound,
5696 privateApis,
5697 redirect,
5698 useInvalidate,
5699 useLinkProps,
5700 useNavigate,
5701 useParams,
5702 useSearch
5703 };
5704 /*! Bundled license information:
5705
5706 use-sync-external-store/cjs/use-sync-external-store-shim.development.js:
5707 (**
5708 * @license React
5709 * use-sync-external-store-shim.development.js
5710 *
5711 * Copyright (c) Meta Platforms, Inc. and affiliates.
5712 *
5713 * This source code is licensed under the MIT license found in the
5714 * LICENSE file in the root directory of this source tree.
5715 *)
5716
5717 use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js:
5718 (**
5719 * @license React
5720 * use-sync-external-store-shim/with-selector.development.js
5721 *
5722 * Copyright (c) Meta Platforms, Inc. and affiliates.
5723 *
5724 * This source code is licensed under the MIT license found in the
5725 * LICENSE file in the root directory of this source tree.
5726 *)
5727 */
5728 //# sourceMappingURL=index.js.map
5729