UNPKG

334 kB JavaScript View Raw
1"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }/**
2 * react-router v7.14.2
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11var __typeError = (msg) => {
12 throw TypeError(msg);
13};
14var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
15var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
16var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
17
18// lib/router/history.ts
19var Action = /* @__PURE__ */ ((Action2) => {
20 Action2["Pop"] = "POP";
21 Action2["Push"] = "PUSH";
22 Action2["Replace"] = "REPLACE";
23 return Action2;
24})(Action || {});
25var PopStateEventType = "popstate";
26function isLocation(obj) {
27 return typeof obj === "object" && obj != null && "pathname" in obj && "search" in obj && "hash" in obj && "state" in obj && "key" in obj;
28}
29function createMemoryHistory(options = {}) {
30 let { initialEntries = ["/"], initialIndex, v5Compat = false } = options;
31 let entries;
32 entries = initialEntries.map(
33 (entry, index2) => createMemoryLocation(
34 entry,
35 typeof entry === "string" ? null : entry.state,
36 index2 === 0 ? "default" : void 0,
37 typeof entry === "string" ? void 0 : entry.unstable_mask
38 )
39 );
40 let index = clampIndex(
41 initialIndex == null ? entries.length - 1 : initialIndex
42 );
43 let action = "POP" /* Pop */;
44 let listener = null;
45 function clampIndex(n) {
46 return Math.min(Math.max(n, 0), entries.length - 1);
47 }
48 function getCurrentLocation() {
49 return entries[index];
50 }
51 function createMemoryLocation(to, state = null, key, unstable_mask) {
52 let location = createLocation(
53 entries ? getCurrentLocation().pathname : "/",
54 to,
55 state,
56 key,
57 unstable_mask
58 );
59 warning(
60 location.pathname.charAt(0) === "/",
61 `relative pathnames are not supported in memory history: ${JSON.stringify(
62 to
63 )}`
64 );
65 return location;
66 }
67 function createHref(to) {
68 return typeof to === "string" ? to : createPath(to);
69 }
70 let history = {
71 get index() {
72 return index;
73 },
74 get action() {
75 return action;
76 },
77 get location() {
78 return getCurrentLocation();
79 },
80 createHref,
81 createURL(to) {
82 return new URL(createHref(to), "http://localhost");
83 },
84 encodeLocation(to) {
85 let path = typeof to === "string" ? parsePath(to) : to;
86 return {
87 pathname: path.pathname || "",
88 search: path.search || "",
89 hash: path.hash || ""
90 };
91 },
92 push(to, state) {
93 action = "PUSH" /* Push */;
94 let nextLocation = isLocation(to) ? to : createMemoryLocation(to, state);
95 index += 1;
96 entries.splice(index, entries.length, nextLocation);
97 if (v5Compat && listener) {
98 listener({ action, location: nextLocation, delta: 1 });
99 }
100 },
101 replace(to, state) {
102 action = "REPLACE" /* Replace */;
103 let nextLocation = isLocation(to) ? to : createMemoryLocation(to, state);
104 entries[index] = nextLocation;
105 if (v5Compat && listener) {
106 listener({ action, location: nextLocation, delta: 0 });
107 }
108 },
109 go(delta) {
110 action = "POP" /* Pop */;
111 let nextIndex = clampIndex(index + delta);
112 let nextLocation = entries[nextIndex];
113 index = nextIndex;
114 if (listener) {
115 listener({ action, location: nextLocation, delta });
116 }
117 },
118 listen(fn) {
119 listener = fn;
120 return () => {
121 listener = null;
122 };
123 }
124 };
125 return history;
126}
127function createBrowserHistory(options = {}) {
128 function createBrowserLocation(window2, globalHistory) {
129 let maskedLocation = _optionalChain([globalHistory, 'access', _2 => _2.state, 'optionalAccess', _3 => _3.masked]);
130 let { pathname, search, hash } = maskedLocation || window2.location;
131 return createLocation(
132 "",
133 { pathname, search, hash },
134 // state defaults to `null` because `window.history.state` does
135 globalHistory.state && globalHistory.state.usr || null,
136 globalHistory.state && globalHistory.state.key || "default",
137 maskedLocation ? {
138 pathname: window2.location.pathname,
139 search: window2.location.search,
140 hash: window2.location.hash
141 } : void 0
142 );
143 }
144 function createBrowserHref(window2, to) {
145 return typeof to === "string" ? to : createPath(to);
146 }
147 return getUrlBasedHistory(
148 createBrowserLocation,
149 createBrowserHref,
150 null,
151 options
152 );
153}
154function createHashHistory(options = {}) {
155 function createHashLocation(window2, globalHistory) {
156 let {
157 pathname = "/",
158 search = "",
159 hash = ""
160 } = parsePath(window2.location.hash.substring(1));
161 if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
162 pathname = "/" + pathname;
163 }
164 return createLocation(
165 "",
166 { pathname, search, hash },
167 // state defaults to `null` because `window.history.state` does
168 globalHistory.state && globalHistory.state.usr || null,
169 globalHistory.state && globalHistory.state.key || "default"
170 );
171 }
172 function createHashHref(window2, to) {
173 let base = window2.document.querySelector("base");
174 let href = "";
175 if (base && base.getAttribute("href")) {
176 let url = window2.location.href;
177 let hashIndex = url.indexOf("#");
178 href = hashIndex === -1 ? url : url.slice(0, hashIndex);
179 }
180 return href + "#" + (typeof to === "string" ? to : createPath(to));
181 }
182 function validateHashLocation(location, to) {
183 warning(
184 location.pathname.charAt(0) === "/",
185 `relative pathnames are not supported in hash history.push(${JSON.stringify(
186 to
187 )})`
188 );
189 }
190 return getUrlBasedHistory(
191 createHashLocation,
192 createHashHref,
193 validateHashLocation,
194 options
195 );
196}
197function invariant(value, message) {
198 if (value === false || value === null || typeof value === "undefined") {
199 throw new Error(message);
200 }
201}
202function warning(cond, message) {
203 if (!cond) {
204 if (typeof console !== "undefined") console.warn(message);
205 try {
206 throw new Error(message);
207 } catch (e) {
208 }
209 }
210}
211function createKey() {
212 return Math.random().toString(36).substring(2, 10);
213}
214function getHistoryState(location, index) {
215 return {
216 usr: location.state,
217 key: location.key,
218 idx: index,
219 masked: location.unstable_mask ? {
220 pathname: location.pathname,
221 search: location.search,
222 hash: location.hash
223 } : void 0
224 };
225}
226function createLocation(current, to, state = null, key, unstable_mask) {
227 let location = {
228 pathname: typeof current === "string" ? current : current.pathname,
229 search: "",
230 hash: "",
231 ...typeof to === "string" ? parsePath(to) : to,
232 state,
233 // TODO: This could be cleaned up. push/replace should probably just take
234 // full Locations now and avoid the need to run through this flow at all
235 // But that's a pretty big refactor to the current test suite so going to
236 // keep as is for the time being and just let any incoming keys take precedence
237 key: to && to.key || key || createKey(),
238 unstable_mask
239 };
240 return location;
241}
242function createPath({
243 pathname = "/",
244 search = "",
245 hash = ""
246}) {
247 if (search && search !== "?")
248 pathname += search.charAt(0) === "?" ? search : "?" + search;
249 if (hash && hash !== "#")
250 pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
251 return pathname;
252}
253function parsePath(path) {
254 let parsedPath = {};
255 if (path) {
256 let hashIndex = path.indexOf("#");
257 if (hashIndex >= 0) {
258 parsedPath.hash = path.substring(hashIndex);
259 path = path.substring(0, hashIndex);
260 }
261 let searchIndex = path.indexOf("?");
262 if (searchIndex >= 0) {
263 parsedPath.search = path.substring(searchIndex);
264 path = path.substring(0, searchIndex);
265 }
266 if (path) {
267 parsedPath.pathname = path;
268 }
269 }
270 return parsedPath;
271}
272function getUrlBasedHistory(getLocation, createHref, validateLocation, options = {}) {
273 let { window: window2 = document.defaultView, v5Compat = false } = options;
274 let globalHistory = window2.history;
275 let action = "POP" /* Pop */;
276 let listener = null;
277 let index = getIndex();
278 if (index == null) {
279 index = 0;
280 globalHistory.replaceState({ ...globalHistory.state, idx: index }, "");
281 }
282 function getIndex() {
283 let state = globalHistory.state || { idx: null };
284 return state.idx;
285 }
286 function handlePop() {
287 action = "POP" /* Pop */;
288 let nextIndex = getIndex();
289 let delta = nextIndex == null ? null : nextIndex - index;
290 index = nextIndex;
291 if (listener) {
292 listener({ action, location: history.location, delta });
293 }
294 }
295 function push(to, state) {
296 action = "PUSH" /* Push */;
297 let location = isLocation(to) ? to : createLocation(history.location, to, state);
298 if (validateLocation) validateLocation(location, to);
299 index = getIndex() + 1;
300 let historyState = getHistoryState(location, index);
301 let url = history.createHref(location.unstable_mask || location);
302 try {
303 globalHistory.pushState(historyState, "", url);
304 } catch (error) {
305 if (error instanceof DOMException && error.name === "DataCloneError") {
306 throw error;
307 }
308 window2.location.assign(url);
309 }
310 if (v5Compat && listener) {
311 listener({ action, location: history.location, delta: 1 });
312 }
313 }
314 function replace2(to, state) {
315 action = "REPLACE" /* Replace */;
316 let location = isLocation(to) ? to : createLocation(history.location, to, state);
317 if (validateLocation) validateLocation(location, to);
318 index = getIndex();
319 let historyState = getHistoryState(location, index);
320 let url = history.createHref(location.unstable_mask || location);
321 globalHistory.replaceState(historyState, "", url);
322 if (v5Compat && listener) {
323 listener({ action, location: history.location, delta: 0 });
324 }
325 }
326 function createURL(to) {
327 return createBrowserURLImpl(to);
328 }
329 let history = {
330 get action() {
331 return action;
332 },
333 get location() {
334 return getLocation(window2, globalHistory);
335 },
336 listen(fn) {
337 if (listener) {
338 throw new Error("A history only accepts one active listener");
339 }
340 window2.addEventListener(PopStateEventType, handlePop);
341 listener = fn;
342 return () => {
343 window2.removeEventListener(PopStateEventType, handlePop);
344 listener = null;
345 };
346 },
347 createHref(to) {
348 return createHref(window2, to);
349 },
350 createURL,
351 encodeLocation(to) {
352 let url = createURL(to);
353 return {
354 pathname: url.pathname,
355 search: url.search,
356 hash: url.hash
357 };
358 },
359 push,
360 replace: replace2,
361 go(n) {
362 return globalHistory.go(n);
363 }
364 };
365 return history;
366}
367function createBrowserURLImpl(to, isAbsolute = false) {
368 let base = "http://localhost";
369 if (typeof window !== "undefined") {
370 base = window.location.origin !== "null" ? window.location.origin : window.location.href;
371 }
372 invariant(base, "No window.location.(origin|href) available to create URL");
373 let href = typeof to === "string" ? to : createPath(to);
374 href = href.replace(/ $/, "%20");
375 if (!isAbsolute && href.startsWith("//")) {
376 href = base + href;
377 }
378 return new URL(href, base);
379}
380
381// lib/router/utils.ts
382function createContext(defaultValue) {
383 return { defaultValue };
384}
385var _map;
386var RouterContextProvider = class {
387 /**
388 * Create a new `RouterContextProvider` instance
389 * @param init An optional initial context map to populate the provider with
390 */
391 constructor(init) {
392 __privateAdd(this, _map, /* @__PURE__ */ new Map());
393 if (init) {
394 for (let [context, value] of init) {
395 this.set(context, value);
396 }
397 }
398 }
399 /**
400 * Access a value from the context. If no value has been set for the context,
401 * it will return the context's `defaultValue` if provided, or throw an error
402 * if no `defaultValue` was set.
403 * @param context The context to get the value for
404 * @returns The value for the context, or the context's `defaultValue` if no
405 * value was set
406 */
407 get(context) {
408 if (__privateGet(this, _map).has(context)) {
409 return __privateGet(this, _map).get(context);
410 }
411 if (context.defaultValue !== void 0) {
412 return context.defaultValue;
413 }
414 throw new Error("No value found for context");
415 }
416 /**
417 * Set a value for the context. If the context already has a value set, this
418 * will overwrite it.
419 *
420 * @param context The context to set the value for
421 * @param value The value to set for the context
422 * @returns {void}
423 */
424 set(context, value) {
425 __privateGet(this, _map).set(context, value);
426 }
427};
428_map = new WeakMap();
429var unsupportedLazyRouteObjectKeys = /* @__PURE__ */ new Set([
430 "lazy",
431 "caseSensitive",
432 "path",
433 "id",
434 "index",
435 "children"
436]);
437function isUnsupportedLazyRouteObjectKey(key) {
438 return unsupportedLazyRouteObjectKeys.has(
439 key
440 );
441}
442var unsupportedLazyRouteFunctionKeys = /* @__PURE__ */ new Set([
443 "lazy",
444 "caseSensitive",
445 "path",
446 "id",
447 "index",
448 "middleware",
449 "children"
450]);
451function isUnsupportedLazyRouteFunctionKey(key) {
452 return unsupportedLazyRouteFunctionKeys.has(
453 key
454 );
455}
456function isIndexRoute(route) {
457 return route.index === true;
458}
459function convertRoutesToDataRoutes(routes, mapRouteProperties2, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
460 return routes.map((route, index) => {
461 let treePath = [...parentPath, String(index)];
462 let id = typeof route.id === "string" ? route.id : treePath.join("-");
463 invariant(
464 route.index !== true || !route.children,
465 `Cannot specify children on an index route`
466 );
467 invariant(
468 allowInPlaceMutations || !manifest[id],
469 `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
470 );
471 if (isIndexRoute(route)) {
472 let indexRoute = {
473 ...route,
474 id
475 };
476 manifest[id] = mergeRouteUpdates(
477 indexRoute,
478 mapRouteProperties2(indexRoute)
479 );
480 return indexRoute;
481 } else {
482 let pathOrLayoutRoute = {
483 ...route,
484 id,
485 children: void 0
486 };
487 manifest[id] = mergeRouteUpdates(
488 pathOrLayoutRoute,
489 mapRouteProperties2(pathOrLayoutRoute)
490 );
491 if (route.children) {
492 pathOrLayoutRoute.children = convertRoutesToDataRoutes(
493 route.children,
494 mapRouteProperties2,
495 treePath,
496 manifest,
497 allowInPlaceMutations
498 );
499 }
500 return pathOrLayoutRoute;
501 }
502 });
503}
504function mergeRouteUpdates(route, updates) {
505 return Object.assign(route, {
506 ...updates,
507 ...typeof updates.lazy === "object" && updates.lazy != null ? {
508 lazy: {
509 ...route.lazy,
510 ...updates.lazy
511 }
512 } : {}
513 });
514}
515function matchRoutes(routes, locationArg, basename = "/") {
516 return matchRoutesImpl(routes, locationArg, basename, false);
517}
518function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
519 let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
520 let pathname = stripBasename(location.pathname || "/", basename);
521 if (pathname == null) {
522 return null;
523 }
524 let branches = flattenRoutes(routes);
525 rankRouteBranches(branches);
526 let matches = null;
527 for (let i = 0; matches == null && i < branches.length; ++i) {
528 let decoded = decodePath(pathname);
529 matches = matchRouteBranch(
530 branches[i],
531 decoded,
532 allowPartial
533 );
534 }
535 return matches;
536}
537function convertRouteMatchToUiMatch(match, loaderData) {
538 let { route, pathname, params } = match;
539 return {
540 id: route.id,
541 pathname,
542 params,
543 data: loaderData[route.id],
544 loaderData: loaderData[route.id],
545 handle: route.handle
546 };
547}
548function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
549 let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
550 let meta = {
551 relativePath: relativePath === void 0 ? route.path || "" : relativePath,
552 caseSensitive: route.caseSensitive === true,
553 childrenIndex: index,
554 route
555 };
556 if (meta.relativePath.startsWith("/")) {
557 if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) {
558 return;
559 }
560 invariant(
561 meta.relativePath.startsWith(parentPath),
562 `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`
563 );
564 meta.relativePath = meta.relativePath.slice(parentPath.length);
565 }
566 let path = joinPaths([parentPath, meta.relativePath]);
567 let routesMeta = parentsMeta.concat(meta);
568 if (route.children && route.children.length > 0) {
569 invariant(
570 // Our types know better, but runtime JS may not!
571 // @ts-expect-error
572 route.index !== true,
573 `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
574 );
575 flattenRoutes(
576 route.children,
577 branches,
578 routesMeta,
579 path,
580 hasParentOptionalSegments
581 );
582 }
583 if (route.path == null && !route.index) {
584 return;
585 }
586 branches.push({
587 path,
588 score: computeScore(path, route.index),
589 routesMeta
590 });
591 };
592 routes.forEach((route, index) => {
593 if (route.path === "" || !_optionalChain([route, 'access', _4 => _4.path, 'optionalAccess', _5 => _5.includes, 'call', _6 => _6("?")])) {
594 flattenRoute(route, index);
595 } else {
596 for (let exploded of explodeOptionalSegments(route.path)) {
597 flattenRoute(route, index, true, exploded);
598 }
599 }
600 });
601 return branches;
602}
603function explodeOptionalSegments(path) {
604 let segments = path.split("/");
605 if (segments.length === 0) return [];
606 let [first, ...rest] = segments;
607 let isOptional = first.endsWith("?");
608 let required = first.replace(/\?$/, "");
609 if (rest.length === 0) {
610 return isOptional ? [required, ""] : [required];
611 }
612 let restExploded = explodeOptionalSegments(rest.join("/"));
613 let result = [];
614 result.push(
615 ...restExploded.map(
616 (subpath) => subpath === "" ? required : [required, subpath].join("/")
617 )
618 );
619 if (isOptional) {
620 result.push(...restExploded);
621 }
622 return result.map(
623 (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
624 );
625}
626function rankRouteBranches(branches) {
627 branches.sort(
628 (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
629 a.routesMeta.map((meta) => meta.childrenIndex),
630 b.routesMeta.map((meta) => meta.childrenIndex)
631 )
632 );
633}
634var paramRe = /^:[\w-]+$/;
635var dynamicSegmentValue = 3;
636var indexRouteValue = 2;
637var emptySegmentValue = 1;
638var staticSegmentValue = 10;
639var splatPenalty = -2;
640var isSplat = (s) => s === "*";
641function computeScore(path, index) {
642 let segments = path.split("/");
643 let initialScore = segments.length;
644 if (segments.some(isSplat)) {
645 initialScore += splatPenalty;
646 }
647 if (index) {
648 initialScore += indexRouteValue;
649 }
650 return segments.filter((s) => !isSplat(s)).reduce(
651 (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
652 initialScore
653 );
654}
655function compareIndexes(a, b) {
656 let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
657 return siblings ? (
658 // If two routes are siblings, we should try to match the earlier sibling
659 // first. This allows people to have fine-grained control over the matching
660 // behavior by simply putting routes with identical paths in the order they
661 // want them tried.
662 a[a.length - 1] - b[b.length - 1]
663 ) : (
664 // Otherwise, it doesn't really make sense to rank non-siblings by index,
665 // so they sort equally.
666 0
667 );
668}
669function matchRouteBranch(branch, pathname, allowPartial = false) {
670 let { routesMeta } = branch;
671 let matchedParams = {};
672 let matchedPathname = "/";
673 let matches = [];
674 for (let i = 0; i < routesMeta.length; ++i) {
675 let meta = routesMeta[i];
676 let end = i === routesMeta.length - 1;
677 let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
678 let match = matchPath(
679 { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
680 remainingPathname
681 );
682 let route = meta.route;
683 if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
684 match = matchPath(
685 {
686 path: meta.relativePath,
687 caseSensitive: meta.caseSensitive,
688 end: false
689 },
690 remainingPathname
691 );
692 }
693 if (!match) {
694 return null;
695 }
696 Object.assign(matchedParams, match.params);
697 matches.push({
698 // TODO: Can this as be avoided?
699 params: matchedParams,
700 pathname: joinPaths([matchedPathname, match.pathname]),
701 pathnameBase: normalizePathname(
702 joinPaths([matchedPathname, match.pathnameBase])
703 ),
704 route
705 });
706 if (match.pathnameBase !== "/") {
707 matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
708 }
709 }
710 return matches;
711}
712function generatePath(originalPath, params = {}) {
713 let path = originalPath;
714 if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
715 warning(
716 false,
717 `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`
718 );
719 path = path.replace(/\*$/, "/*");
720 }
721 const prefix = path.startsWith("/") ? "/" : "";
722 const stringify2 = (p) => p == null ? "" : typeof p === "string" ? p : String(p);
723 const segments = path.split(/\/+/).map((segment, index, array) => {
724 const isLastSegment = index === array.length - 1;
725 if (isLastSegment && segment === "*") {
726 return stringify2(params["*"]);
727 }
728 const keyMatch = segment.match(/^:([\w-]+)(\??)(.*)/);
729 if (keyMatch) {
730 const [, key, optional, suffix] = keyMatch;
731 let param = params[key];
732 invariant(optional === "?" || param != null, `Missing ":${key}" param`);
733 return encodeURIComponent(stringify2(param)) + suffix;
734 }
735 return segment.replace(/\?$/g, "");
736 }).filter((segment) => !!segment);
737 return prefix + segments.join("/");
738}
739function matchPath(pattern, pathname) {
740 if (typeof pattern === "string") {
741 pattern = { path: pattern, caseSensitive: false, end: true };
742 }
743 let [matcher, compiledParams] = compilePath(
744 pattern.path,
745 pattern.caseSensitive,
746 pattern.end
747 );
748 let match = pathname.match(matcher);
749 if (!match) return null;
750 let matchedPathname = match[0];
751 let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
752 let captureGroups = match.slice(1);
753 let params = compiledParams.reduce(
754 (memo2, { paramName, isOptional }, index) => {
755 if (paramName === "*") {
756 let splatValue = captureGroups[index] || "";
757 pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
758 }
759 const value = captureGroups[index];
760 if (isOptional && !value) {
761 memo2[paramName] = void 0;
762 } else {
763 memo2[paramName] = (value || "").replace(/%2F/g, "/");
764 }
765 return memo2;
766 },
767 {}
768 );
769 return {
770 params,
771 pathname: matchedPathname,
772 pathnameBase,
773 pattern
774 };
775}
776function compilePath(path, caseSensitive = false, end = true) {
777 warning(
778 path === "*" || !path.endsWith("*") || path.endsWith("/*"),
779 `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`
780 );
781 let params = [];
782 let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
783 /\/:([\w-]+)(\?)?/g,
784 (match, paramName, isOptional, index, str) => {
785 params.push({ paramName, isOptional: isOptional != null });
786 if (isOptional) {
787 let nextChar = str.charAt(index + match.length);
788 if (nextChar && nextChar !== "/") {
789 return "/([^\\/]*)";
790 }
791 return "(?:/([^\\/]*))?";
792 }
793 return "/([^\\/]+)";
794 }
795 ).replace(/\/([\w-]+)\?(\/|$)/g, "(/$1)?$2");
796 if (path.endsWith("*")) {
797 params.push({ paramName: "*" });
798 regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
799 } else if (end) {
800 regexpSource += "\\/*$";
801 } else if (path !== "" && path !== "/") {
802 regexpSource += "(?:(?=\\/|$))";
803 } else {
804 }
805 let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
806 return [matcher, params];
807}
808function decodePath(value) {
809 try {
810 return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
811 } catch (error) {
812 warning(
813 false,
814 `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`
815 );
816 return value;
817 }
818}
819function stripBasename(pathname, basename) {
820 if (basename === "/") return pathname;
821 if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
822 return null;
823 }
824 let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
825 let nextChar = pathname.charAt(startIndex);
826 if (nextChar && nextChar !== "/") {
827 return null;
828 }
829 return pathname.slice(startIndex) || "/";
830}
831function prependBasename({
832 basename,
833 pathname
834}) {
835 return pathname === "/" ? basename : joinPaths([basename, pathname]);
836}
837var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
838var isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
839function resolvePath(to, fromPathname = "/") {
840 let {
841 pathname: toPathname,
842 search = "",
843 hash = ""
844 } = typeof to === "string" ? parsePath(to) : to;
845 let pathname;
846 if (toPathname) {
847 toPathname = removeDoubleSlashes(toPathname);
848 if (toPathname.startsWith("/")) {
849 pathname = resolvePathname(toPathname.substring(1), "/");
850 } else {
851 pathname = resolvePathname(toPathname, fromPathname);
852 }
853 } else {
854 pathname = fromPathname;
855 }
856 return {
857 pathname,
858 search: normalizeSearch(search),
859 hash: normalizeHash(hash)
860 };
861}
862function resolvePathname(relativePath, fromPathname) {
863 let segments = removeTrailingSlash(fromPathname).split("/");
864 let relativeSegments = relativePath.split("/");
865 relativeSegments.forEach((segment) => {
866 if (segment === "..") {
867 if (segments.length > 1) segments.pop();
868 } else if (segment !== ".") {
869 segments.push(segment);
870 }
871 });
872 return segments.length > 1 ? segments.join("/") : "/";
873}
874function getInvalidPathError(char, field, dest, path) {
875 return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
876 path
877 )}]. Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`;
878}
879function getPathContributingMatches(matches) {
880 return matches.filter(
881 (match, index) => index === 0 || match.route.path && match.route.path.length > 0
882 );
883}
884function getResolveToMatches(matches) {
885 let pathMatches = getPathContributingMatches(matches);
886 return pathMatches.map(
887 (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
888 );
889}
890function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
891 let to;
892 if (typeof toArg === "string") {
893 to = parsePath(toArg);
894 } else {
895 to = { ...toArg };
896 invariant(
897 !to.pathname || !to.pathname.includes("?"),
898 getInvalidPathError("?", "pathname", "search", to)
899 );
900 invariant(
901 !to.pathname || !to.pathname.includes("#"),
902 getInvalidPathError("#", "pathname", "hash", to)
903 );
904 invariant(
905 !to.search || !to.search.includes("#"),
906 getInvalidPathError("#", "search", "hash", to)
907 );
908 }
909 let isEmptyPath = toArg === "" || to.pathname === "";
910 let toPathname = isEmptyPath ? "/" : to.pathname;
911 let from;
912 if (toPathname == null) {
913 from = locationPathname;
914 } else {
915 let routePathnameIndex = routePathnames.length - 1;
916 if (!isPathRelative && toPathname.startsWith("..")) {
917 let toSegments = toPathname.split("/");
918 while (toSegments[0] === "..") {
919 toSegments.shift();
920 routePathnameIndex -= 1;
921 }
922 to.pathname = toSegments.join("/");
923 }
924 from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
925 }
926 let path = resolvePath(to, from);
927 let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
928 let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
929 if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
930 path.pathname += "/";
931 }
932 return path;
933}
934var removeDoubleSlashes = (path) => path.replace(/\/\/+/g, "/");
935var joinPaths = (paths) => removeDoubleSlashes(paths.join("/"));
936var removeTrailingSlash = (path) => path.replace(/\/+$/, "");
937var normalizePathname = (pathname) => removeTrailingSlash(pathname).replace(/^\/*/, "/");
938var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
939var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
940var DataWithResponseInit = class {
941 constructor(data2, init) {
942 this.type = "DataWithResponseInit";
943 this.data = data2;
944 this.init = init || null;
945 }
946};
947function data(data2, init) {
948 return new DataWithResponseInit(
949 data2,
950 typeof init === "number" ? { status: init } : init
951 );
952}
953var redirect = (url, init = 302) => {
954 let responseInit = init;
955 if (typeof responseInit === "number") {
956 responseInit = { status: responseInit };
957 } else if (typeof responseInit.status === "undefined") {
958 responseInit.status = 302;
959 }
960 let headers = new Headers(responseInit.headers);
961 headers.set("Location", url);
962 return new Response(null, { ...responseInit, headers });
963};
964var redirectDocument = (url, init) => {
965 let response = redirect(url, init);
966 response.headers.set("X-Remix-Reload-Document", "true");
967 return response;
968};
969var replace = (url, init) => {
970 let response = redirect(url, init);
971 response.headers.set("X-Remix-Replace", "true");
972 return response;
973};
974var ErrorResponseImpl = class {
975 constructor(status, statusText, data2, internal = false) {
976 this.status = status;
977 this.statusText = statusText || "";
978 this.internal = internal;
979 if (data2 instanceof Error) {
980 this.data = data2.toString();
981 this.error = data2;
982 } else {
983 this.data = data2;
984 }
985 }
986};
987function isRouteErrorResponse(error) {
988 return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
989}
990function getRoutePattern(matches) {
991 let parts = matches.map((m) => m.route.path).filter(Boolean);
992 return joinPaths(parts) || "/";
993}
994var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
995function parseToInfo(_to, basename) {
996 let to = _to;
997 if (typeof to !== "string" || !ABSOLUTE_URL_REGEX.test(to)) {
998 return {
999 absoluteURL: void 0,
1000 isExternal: false,
1001 to
1002 };
1003 }
1004 let absoluteURL = to;
1005 let isExternal = false;
1006 if (isBrowser) {
1007 try {
1008 let currentUrl = new URL(window.location.href);
1009 let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
1010 let path = stripBasename(targetUrl.pathname, basename);
1011 if (targetUrl.origin === currentUrl.origin && path != null) {
1012 to = path + targetUrl.search + targetUrl.hash;
1013 } else {
1014 isExternal = true;
1015 }
1016 } catch (e) {
1017 warning(
1018 false,
1019 `<Link to="${to}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`
1020 );
1021 }
1022 }
1023 return {
1024 absoluteURL,
1025 isExternal,
1026 to
1027 };
1028}
1029
1030// lib/router/instrumentation.ts
1031var UninstrumentedSymbol = Symbol("Uninstrumented");
1032function getRouteInstrumentationUpdates(fns, route) {
1033 let aggregated = {
1034 lazy: [],
1035 "lazy.loader": [],
1036 "lazy.action": [],
1037 "lazy.middleware": [],
1038 middleware: [],
1039 loader: [],
1040 action: []
1041 };
1042 fns.forEach(
1043 (fn) => fn({
1044 id: route.id,
1045 index: route.index,
1046 path: route.path,
1047 instrument(i) {
1048 let keys = Object.keys(aggregated);
1049 for (let key of keys) {
1050 if (i[key]) {
1051 aggregated[key].push(i[key]);
1052 }
1053 }
1054 }
1055 })
1056 );
1057 let updates = {};
1058 if (typeof route.lazy === "function" && aggregated.lazy.length > 0) {
1059 let instrumented = wrapImpl(aggregated.lazy, route.lazy, () => void 0);
1060 if (instrumented) {
1061 updates.lazy = instrumented;
1062 }
1063 }
1064 if (typeof route.lazy === "object") {
1065 let lazyObject = route.lazy;
1066 ["middleware", "loader", "action"].forEach((key) => {
1067 let lazyFn = lazyObject[key];
1068 let instrumentations = aggregated[`lazy.${key}`];
1069 if (typeof lazyFn === "function" && instrumentations.length > 0) {
1070 let instrumented = wrapImpl(instrumentations, lazyFn, () => void 0);
1071 if (instrumented) {
1072 updates.lazy = Object.assign(updates.lazy || {}, {
1073 [key]: instrumented
1074 });
1075 }
1076 }
1077 });
1078 }
1079 ["loader", "action"].forEach((key) => {
1080 let handler = route[key];
1081 if (typeof handler === "function" && aggregated[key].length > 0) {
1082 let original = _nullishCoalesce(handler[UninstrumentedSymbol], () => ( handler));
1083 let instrumented = wrapImpl(
1084 aggregated[key],
1085 original,
1086 (...args) => getHandlerInfo(args[0])
1087 );
1088 if (instrumented) {
1089 if (key === "loader" && original.hydrate === true) {
1090 instrumented.hydrate = true;
1091 }
1092 instrumented[UninstrumentedSymbol] = original;
1093 updates[key] = instrumented;
1094 }
1095 }
1096 });
1097 if (route.middleware && route.middleware.length > 0 && aggregated.middleware.length > 0) {
1098 updates.middleware = route.middleware.map((middleware) => {
1099 let original = _nullishCoalesce(middleware[UninstrumentedSymbol], () => ( middleware));
1100 let instrumented = wrapImpl(
1101 aggregated.middleware,
1102 original,
1103 (...args) => getHandlerInfo(args[0])
1104 );
1105 if (instrumented) {
1106 instrumented[UninstrumentedSymbol] = original;
1107 return instrumented;
1108 }
1109 return middleware;
1110 });
1111 }
1112 return updates;
1113}
1114function instrumentClientSideRouter(router, fns) {
1115 let aggregated = {
1116 navigate: [],
1117 fetch: []
1118 };
1119 fns.forEach(
1120 (fn) => fn({
1121 instrument(i) {
1122 let keys = Object.keys(i);
1123 for (let key of keys) {
1124 if (i[key]) {
1125 aggregated[key].push(i[key]);
1126 }
1127 }
1128 }
1129 })
1130 );
1131 if (aggregated.navigate.length > 0) {
1132 let navigate = _nullishCoalesce(router.navigate[UninstrumentedSymbol], () => ( router.navigate));
1133 let instrumentedNavigate = wrapImpl(
1134 aggregated.navigate,
1135 navigate,
1136 (...args) => {
1137 let [to, opts] = args;
1138 return {
1139 to: typeof to === "number" || typeof to === "string" ? to : to ? createPath(to) : ".",
1140 ...getRouterInfo(router, _nullishCoalesce(opts, () => ( {})))
1141 };
1142 }
1143 );
1144 if (instrumentedNavigate) {
1145 instrumentedNavigate[UninstrumentedSymbol] = navigate;
1146 router.navigate = instrumentedNavigate;
1147 }
1148 }
1149 if (aggregated.fetch.length > 0) {
1150 let fetch2 = _nullishCoalesce(router.fetch[UninstrumentedSymbol], () => ( router.fetch));
1151 let instrumentedFetch = wrapImpl(aggregated.fetch, fetch2, (...args) => {
1152 let [key, , href, opts] = args;
1153 return {
1154 href: _nullishCoalesce(href, () => ( ".")),
1155 fetcherKey: key,
1156 ...getRouterInfo(router, _nullishCoalesce(opts, () => ( {})))
1157 };
1158 });
1159 if (instrumentedFetch) {
1160 instrumentedFetch[UninstrumentedSymbol] = fetch2;
1161 router.fetch = instrumentedFetch;
1162 }
1163 }
1164 return router;
1165}
1166function instrumentHandler(handler, fns) {
1167 let aggregated = {
1168 request: []
1169 };
1170 fns.forEach(
1171 (fn) => fn({
1172 instrument(i) {
1173 let keys = Object.keys(i);
1174 for (let key of keys) {
1175 if (i[key]) {
1176 aggregated[key].push(i[key]);
1177 }
1178 }
1179 }
1180 })
1181 );
1182 let instrumentedHandler = handler;
1183 if (aggregated.request.length > 0) {
1184 instrumentedHandler = wrapImpl(aggregated.request, handler, (...args) => {
1185 let [request, context] = args;
1186 return {
1187 request: getReadonlyRequest(request),
1188 context: context != null ? getReadonlyContext(context) : context
1189 };
1190 });
1191 }
1192 return instrumentedHandler;
1193}
1194function wrapImpl(impls, handler, getInfo) {
1195 if (impls.length === 0) {
1196 return null;
1197 }
1198 return async (...args) => {
1199 let result = await recurseRight(
1200 impls,
1201 getInfo(...args),
1202 () => handler(...args),
1203 impls.length - 1
1204 );
1205 if (result.type === "error") {
1206 throw result.value;
1207 }
1208 return result.value;
1209 };
1210}
1211async function recurseRight(impls, info, handler, index) {
1212 let impl = impls[index];
1213 let result;
1214 if (!impl) {
1215 try {
1216 let value = await handler();
1217 result = { type: "success", value };
1218 } catch (e) {
1219 result = { type: "error", value: e };
1220 }
1221 } else {
1222 let handlerPromise = void 0;
1223 let callHandler = async () => {
1224 if (handlerPromise) {
1225 console.error("You cannot call instrumented handlers more than once");
1226 } else {
1227 handlerPromise = recurseRight(impls, info, handler, index - 1);
1228 }
1229 result = await handlerPromise;
1230 invariant(result, "Expected a result");
1231 if (result.type === "error" && result.value instanceof Error) {
1232 return { status: "error", error: result.value };
1233 }
1234 return { status: "success", error: void 0 };
1235 };
1236 try {
1237 await impl(callHandler, info);
1238 } catch (e) {
1239 console.error("An instrumentation function threw an error:", e);
1240 }
1241 if (!handlerPromise) {
1242 await callHandler();
1243 }
1244 await handlerPromise;
1245 }
1246 if (result) {
1247 return result;
1248 }
1249 return {
1250 type: "error",
1251 value: new Error("No result assigned in instrumentation chain.")
1252 };
1253}
1254function getHandlerInfo(args) {
1255 let { request, context, params, unstable_pattern } = args;
1256 return {
1257 request: getReadonlyRequest(request),
1258 params: { ...params },
1259 unstable_pattern,
1260 context: getReadonlyContext(context)
1261 };
1262}
1263function getRouterInfo(router, opts) {
1264 return {
1265 currentUrl: createPath(router.state.location),
1266 ..."formMethod" in opts ? { formMethod: opts.formMethod } : {},
1267 ..."formEncType" in opts ? { formEncType: opts.formEncType } : {},
1268 ..."formData" in opts ? { formData: opts.formData } : {},
1269 ..."body" in opts ? { body: opts.body } : {}
1270 };
1271}
1272function getReadonlyRequest(request) {
1273 return {
1274 method: request.method,
1275 url: request.url,
1276 headers: {
1277 get: (...args) => request.headers.get(...args)
1278 }
1279 };
1280}
1281function getReadonlyContext(context) {
1282 if (isPlainObject(context)) {
1283 let frozen = { ...context };
1284 Object.freeze(frozen);
1285 return frozen;
1286 } else {
1287 return {
1288 get: (ctx) => context.get(ctx)
1289 };
1290 }
1291}
1292var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
1293function isPlainObject(thing) {
1294 if (thing === null || typeof thing !== "object") {
1295 return false;
1296 }
1297 const proto = Object.getPrototypeOf(thing);
1298 return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames;
1299}
1300
1301// lib/router/router.ts
1302var validMutationMethodsArr = [
1303 "POST",
1304 "PUT",
1305 "PATCH",
1306 "DELETE"
1307];
1308var validMutationMethods = new Set(
1309 validMutationMethodsArr
1310);
1311var validRequestMethodsArr = [
1312 "GET",
1313 ...validMutationMethodsArr
1314];
1315var validRequestMethods = new Set(validRequestMethodsArr);
1316var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
1317var redirectPreserveMethodStatusCodes = /* @__PURE__ */ new Set([307, 308]);
1318var IDLE_NAVIGATION = {
1319 state: "idle",
1320 location: void 0,
1321 formMethod: void 0,
1322 formAction: void 0,
1323 formEncType: void 0,
1324 formData: void 0,
1325 json: void 0,
1326 text: void 0
1327};
1328var IDLE_FETCHER = {
1329 state: "idle",
1330 data: void 0,
1331 formMethod: void 0,
1332 formAction: void 0,
1333 formEncType: void 0,
1334 formData: void 0,
1335 json: void 0,
1336 text: void 0
1337};
1338var IDLE_BLOCKER = {
1339 state: "unblocked",
1340 proceed: void 0,
1341 reset: void 0,
1342 location: void 0
1343};
1344var defaultMapRouteProperties = (route) => ({
1345 hasErrorBoundary: Boolean(route.hasErrorBoundary)
1346});
1347var TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
1348var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
1349function createRouter(init) {
1350 const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : void 0;
1351 const isBrowser2 = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
1352 invariant(
1353 init.routes.length > 0,
1354 "You must provide a non-empty routes array to createRouter"
1355 );
1356 let hydrationRouteProperties2 = init.hydrationRouteProperties || [];
1357 let _mapRouteProperties = init.mapRouteProperties || defaultMapRouteProperties;
1358 let mapRouteProperties2 = _mapRouteProperties;
1359 if (init.unstable_instrumentations) {
1360 let instrumentations = init.unstable_instrumentations;
1361 mapRouteProperties2 = (route) => {
1362 return {
1363 ..._mapRouteProperties(route),
1364 ...getRouteInstrumentationUpdates(
1365 instrumentations.map((i) => i.route).filter(Boolean),
1366 route
1367 )
1368 };
1369 };
1370 }
1371 let manifest = {};
1372 let dataRoutes = convertRoutesToDataRoutes(
1373 init.routes,
1374 mapRouteProperties2,
1375 void 0,
1376 manifest
1377 );
1378 let inFlightDataRoutes;
1379 let basename = init.basename || "/";
1380 if (!basename.startsWith("/")) {
1381 basename = `/${basename}`;
1382 }
1383 let dataStrategyImpl = init.dataStrategy || defaultDataStrategyWithMiddleware;
1384 let future = {
1385 unstable_passThroughRequests: false,
1386 ...init.future
1387 };
1388 let unlistenHistory = null;
1389 let subscribers = /* @__PURE__ */ new Set();
1390 let savedScrollPositions = null;
1391 let getScrollRestorationKey = null;
1392 let getScrollPosition = null;
1393 let initialScrollRestored = init.hydrationData != null;
1394 let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
1395 let initialMatchesIsFOW = false;
1396 let initialErrors = null;
1397 let initialized;
1398 let renderFallback;
1399 if (initialMatches == null && !init.patchRoutesOnNavigation) {
1400 let error = getInternalRouterError(404, {
1401 pathname: init.history.location.pathname
1402 });
1403 let { matches, route } = getShortCircuitMatches(dataRoutes);
1404 initialized = true;
1405 renderFallback = !initialized;
1406 initialMatches = matches;
1407 initialErrors = { [route.id]: error };
1408 } else {
1409 if (initialMatches && !init.hydrationData) {
1410 let fogOfWar = checkFogOfWar(
1411 initialMatches,
1412 dataRoutes,
1413 init.history.location.pathname
1414 );
1415 if (fogOfWar.active) {
1416 initialMatches = null;
1417 }
1418 }
1419 if (!initialMatches) {
1420 initialized = false;
1421 renderFallback = !initialized;
1422 initialMatches = [];
1423 let fogOfWar = checkFogOfWar(
1424 null,
1425 dataRoutes,
1426 init.history.location.pathname
1427 );
1428 if (fogOfWar.active && fogOfWar.matches) {
1429 initialMatchesIsFOW = true;
1430 initialMatches = fogOfWar.matches;
1431 }
1432 } else if (initialMatches.some((m) => m.route.lazy)) {
1433 initialized = false;
1434 renderFallback = !initialized;
1435 } else if (!initialMatches.some((m) => routeHasLoaderOrMiddleware(m.route))) {
1436 initialized = true;
1437 renderFallback = !initialized;
1438 } else {
1439 let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
1440 let errors = init.hydrationData ? init.hydrationData.errors : null;
1441 let relevantMatches = initialMatches;
1442 if (errors) {
1443 let idx = initialMatches.findIndex(
1444 (m) => errors[m.route.id] !== void 0
1445 );
1446 relevantMatches = relevantMatches.slice(0, idx + 1);
1447 }
1448 renderFallback = false;
1449 initialized = true;
1450 relevantMatches.forEach((m) => {
1451 let status = getRouteHydrationStatus(m.route, loaderData, errors);
1452 renderFallback = renderFallback || status.renderFallback;
1453 initialized = initialized && !status.shouldLoad;
1454 });
1455 }
1456 }
1457 let router;
1458 let state = {
1459 historyAction: init.history.action,
1460 location: init.history.location,
1461 matches: initialMatches,
1462 initialized,
1463 renderFallback,
1464 navigation: IDLE_NAVIGATION,
1465 // Don't restore on initial updateState() if we were SSR'd
1466 restoreScrollPosition: init.hydrationData != null ? false : null,
1467 preventScrollReset: false,
1468 revalidation: "idle",
1469 loaderData: init.hydrationData && init.hydrationData.loaderData || {},
1470 actionData: init.hydrationData && init.hydrationData.actionData || null,
1471 errors: init.hydrationData && init.hydrationData.errors || initialErrors,
1472 fetchers: /* @__PURE__ */ new Map(),
1473 blockers: /* @__PURE__ */ new Map()
1474 };
1475 let pendingAction = "POP" /* Pop */;
1476 let pendingPopstateNavigationDfd = null;
1477 let pendingPreventScrollReset = false;
1478 let pendingNavigationController;
1479 let pendingViewTransitionEnabled = false;
1480 let appliedViewTransitions = /* @__PURE__ */ new Map();
1481 let removePageHideEventListener = null;
1482 let isUninterruptedRevalidation = false;
1483 let isRevalidationRequired = false;
1484 let cancelledFetcherLoads = /* @__PURE__ */ new Set();
1485 let fetchControllers = /* @__PURE__ */ new Map();
1486 let incrementingLoadId = 0;
1487 let pendingNavigationLoadId = -1;
1488 let fetchReloadIds = /* @__PURE__ */ new Map();
1489 let fetchRedirectIds = /* @__PURE__ */ new Set();
1490 let fetchLoadMatches = /* @__PURE__ */ new Map();
1491 let activeFetchers = /* @__PURE__ */ new Map();
1492 let fetchersQueuedForDeletion = /* @__PURE__ */ new Set();
1493 let blockerFunctions = /* @__PURE__ */ new Map();
1494 let unblockBlockerHistoryUpdate = void 0;
1495 let pendingRevalidationDfd = null;
1496 function initialize() {
1497 unlistenHistory = init.history.listen(
1498 ({ action: historyAction, location, delta }) => {
1499 if (unblockBlockerHistoryUpdate) {
1500 unblockBlockerHistoryUpdate();
1501 unblockBlockerHistoryUpdate = void 0;
1502 return;
1503 }
1504 warning(
1505 blockerFunctions.size === 0 || delta != null,
1506 "You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL."
1507 );
1508 let blockerKey = shouldBlockNavigation({
1509 currentLocation: state.location,
1510 nextLocation: location,
1511 historyAction
1512 });
1513 if (blockerKey && delta != null) {
1514 let nextHistoryUpdatePromise = new Promise((resolve) => {
1515 unblockBlockerHistoryUpdate = resolve;
1516 });
1517 init.history.go(delta * -1);
1518 updateBlocker(blockerKey, {
1519 state: "blocked",
1520 location,
1521 proceed() {
1522 updateBlocker(blockerKey, {
1523 state: "proceeding",
1524 proceed: void 0,
1525 reset: void 0,
1526 location
1527 });
1528 nextHistoryUpdatePromise.then(() => init.history.go(delta));
1529 },
1530 reset() {
1531 let blockers = new Map(state.blockers);
1532 blockers.set(blockerKey, IDLE_BLOCKER);
1533 updateState({ blockers });
1534 }
1535 });
1536 _optionalChain([pendingPopstateNavigationDfd, 'optionalAccess', _7 => _7.resolve, 'call', _8 => _8()]);
1537 pendingPopstateNavigationDfd = null;
1538 return;
1539 }
1540 return startNavigation(historyAction, location);
1541 }
1542 );
1543 if (isBrowser2) {
1544 restoreAppliedTransitions(routerWindow, appliedViewTransitions);
1545 let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
1546 routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
1547 removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
1548 }
1549 if (!state.initialized) {
1550 startNavigation("POP" /* Pop */, state.location, {
1551 initialHydration: true
1552 });
1553 }
1554 return router;
1555 }
1556 function dispose() {
1557 if (unlistenHistory) {
1558 unlistenHistory();
1559 }
1560 if (removePageHideEventListener) {
1561 removePageHideEventListener();
1562 }
1563 subscribers.clear();
1564 pendingNavigationController && pendingNavigationController.abort();
1565 state.fetchers.forEach((_, key) => deleteFetcher(key));
1566 state.blockers.forEach((_, key) => deleteBlocker(key));
1567 }
1568 function subscribe(fn) {
1569 subscribers.add(fn);
1570 return () => subscribers.delete(fn);
1571 }
1572 function updateState(newState, opts = {}) {
1573 if (newState.matches) {
1574 newState.matches = newState.matches.map((m) => {
1575 let route = manifest[m.route.id];
1576 let matchRoute = m.route;
1577 if (matchRoute.element !== route.element || matchRoute.errorElement !== route.errorElement || matchRoute.hydrateFallbackElement !== route.hydrateFallbackElement) {
1578 return {
1579 ...m,
1580 route
1581 };
1582 }
1583 return m;
1584 });
1585 }
1586 state = {
1587 ...state,
1588 ...newState
1589 };
1590 let unmountedFetchers = [];
1591 let mountedFetchers = [];
1592 state.fetchers.forEach((fetcher, key) => {
1593 if (fetcher.state === "idle") {
1594 if (fetchersQueuedForDeletion.has(key)) {
1595 unmountedFetchers.push(key);
1596 } else {
1597 mountedFetchers.push(key);
1598 }
1599 }
1600 });
1601 fetchersQueuedForDeletion.forEach((key) => {
1602 if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
1603 unmountedFetchers.push(key);
1604 }
1605 });
1606 [...subscribers].forEach(
1607 (subscriber) => subscriber(state, {
1608 deletedFetchers: unmountedFetchers,
1609 newErrors: _nullishCoalesce(newState.errors, () => ( null)),
1610 viewTransitionOpts: opts.viewTransitionOpts,
1611 flushSync: opts.flushSync === true
1612 })
1613 );
1614 unmountedFetchers.forEach((key) => deleteFetcher(key));
1615 mountedFetchers.forEach((key) => state.fetchers.delete(key));
1616 }
1617 function completeNavigation(location, newState, { flushSync } = {}) {
1618 let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && _optionalChain([location, 'access', _9 => _9.state, 'optionalAccess', _10 => _10._isRedirect]) !== true;
1619 let actionData;
1620 if (newState.actionData) {
1621 if (Object.keys(newState.actionData).length > 0) {
1622 actionData = newState.actionData;
1623 } else {
1624 actionData = null;
1625 }
1626 } else if (isActionReload) {
1627 actionData = state.actionData;
1628 } else {
1629 actionData = null;
1630 }
1631 let loaderData = newState.loaderData ? mergeLoaderData(
1632 state.loaderData,
1633 newState.loaderData,
1634 newState.matches || [],
1635 newState.errors
1636 ) : state.loaderData;
1637 let blockers = state.blockers;
1638 if (blockers.size > 0) {
1639 blockers = new Map(blockers);
1640 blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
1641 }
1642 let restoreScrollPosition = isUninterruptedRevalidation ? false : getSavedScrollPosition(location, newState.matches || state.matches);
1643 let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && _optionalChain([location, 'access', _11 => _11.state, 'optionalAccess', _12 => _12._isRedirect]) !== true;
1644 if (inFlightDataRoutes) {
1645 dataRoutes = inFlightDataRoutes;
1646 inFlightDataRoutes = void 0;
1647 }
1648 if (isUninterruptedRevalidation) {
1649 } else if (pendingAction === "POP" /* Pop */) {
1650 } else if (pendingAction === "PUSH" /* Push */) {
1651 init.history.push(location, location.state);
1652 } else if (pendingAction === "REPLACE" /* Replace */) {
1653 init.history.replace(location, location.state);
1654 }
1655 let viewTransitionOpts;
1656 if (pendingAction === "POP" /* Pop */) {
1657 let priorPaths = appliedViewTransitions.get(state.location.pathname);
1658 if (priorPaths && priorPaths.has(location.pathname)) {
1659 viewTransitionOpts = {
1660 currentLocation: state.location,
1661 nextLocation: location
1662 };
1663 } else if (appliedViewTransitions.has(location.pathname)) {
1664 viewTransitionOpts = {
1665 currentLocation: location,
1666 nextLocation: state.location
1667 };
1668 }
1669 } else if (pendingViewTransitionEnabled) {
1670 let toPaths = appliedViewTransitions.get(state.location.pathname);
1671 if (toPaths) {
1672 toPaths.add(location.pathname);
1673 } else {
1674 toPaths = /* @__PURE__ */ new Set([location.pathname]);
1675 appliedViewTransitions.set(state.location.pathname, toPaths);
1676 }
1677 viewTransitionOpts = {
1678 currentLocation: state.location,
1679 nextLocation: location
1680 };
1681 }
1682 updateState(
1683 {
1684 ...newState,
1685 // matches, errors, fetchers go through as-is
1686 actionData,
1687 loaderData,
1688 historyAction: pendingAction,
1689 location,
1690 initialized: true,
1691 renderFallback: false,
1692 navigation: IDLE_NAVIGATION,
1693 revalidation: "idle",
1694 restoreScrollPosition,
1695 preventScrollReset,
1696 blockers
1697 },
1698 {
1699 viewTransitionOpts,
1700 flushSync: flushSync === true
1701 }
1702 );
1703 pendingAction = "POP" /* Pop */;
1704 pendingPreventScrollReset = false;
1705 pendingViewTransitionEnabled = false;
1706 isUninterruptedRevalidation = false;
1707 isRevalidationRequired = false;
1708 _optionalChain([pendingPopstateNavigationDfd, 'optionalAccess', _13 => _13.resolve, 'call', _14 => _14()]);
1709 pendingPopstateNavigationDfd = null;
1710 _optionalChain([pendingRevalidationDfd, 'optionalAccess', _15 => _15.resolve, 'call', _16 => _16()]);
1711 pendingRevalidationDfd = null;
1712 }
1713 async function navigate(to, opts) {
1714 _optionalChain([pendingPopstateNavigationDfd, 'optionalAccess', _17 => _17.resolve, 'call', _18 => _18()]);
1715 pendingPopstateNavigationDfd = null;
1716 if (typeof to === "number") {
1717 if (!pendingPopstateNavigationDfd) {
1718 pendingPopstateNavigationDfd = createDeferred();
1719 }
1720 let promise = pendingPopstateNavigationDfd.promise;
1721 init.history.go(to);
1722 return promise;
1723 }
1724 let normalizedPath = normalizeTo(
1725 state.location,
1726 state.matches,
1727 basename,
1728 to,
1729 _optionalChain([opts, 'optionalAccess', _19 => _19.fromRouteId]),
1730 _optionalChain([opts, 'optionalAccess', _20 => _20.relative])
1731 );
1732 let { path, submission, error } = normalizeNavigateOptions(
1733 false,
1734 normalizedPath,
1735 opts
1736 );
1737 let maskPath;
1738 if (_optionalChain([opts, 'optionalAccess', _21 => _21.unstable_mask])) {
1739 let partialPath = typeof opts.unstable_mask === "string" ? parsePath(opts.unstable_mask) : {
1740 ...state.location.unstable_mask,
1741 ...opts.unstable_mask
1742 };
1743 maskPath = {
1744 pathname: "",
1745 search: "",
1746 hash: "",
1747 ...partialPath
1748 };
1749 }
1750 let currentLocation = state.location;
1751 let nextLocation = createLocation(
1752 currentLocation,
1753 path,
1754 opts && opts.state,
1755 void 0,
1756 maskPath
1757 );
1758 nextLocation = {
1759 ...nextLocation,
1760 ...init.history.encodeLocation(nextLocation)
1761 };
1762 let userReplace = opts && opts.replace != null ? opts.replace : void 0;
1763 let historyAction = "PUSH" /* Push */;
1764 if (userReplace === true) {
1765 historyAction = "REPLACE" /* Replace */;
1766 } else if (userReplace === false) {
1767 } else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
1768 historyAction = "REPLACE" /* Replace */;
1769 }
1770 let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : void 0;
1771 let flushSync = (opts && opts.flushSync) === true;
1772 let blockerKey = shouldBlockNavigation({
1773 currentLocation,
1774 nextLocation,
1775 historyAction
1776 });
1777 if (blockerKey) {
1778 updateBlocker(blockerKey, {
1779 state: "blocked",
1780 location: nextLocation,
1781 proceed() {
1782 updateBlocker(blockerKey, {
1783 state: "proceeding",
1784 proceed: void 0,
1785 reset: void 0,
1786 location: nextLocation
1787 });
1788 navigate(to, opts);
1789 },
1790 reset() {
1791 let blockers = new Map(state.blockers);
1792 blockers.set(blockerKey, IDLE_BLOCKER);
1793 updateState({ blockers });
1794 }
1795 });
1796 return;
1797 }
1798 await startNavigation(historyAction, nextLocation, {
1799 submission,
1800 // Send through the formData serialization error if we have one so we can
1801 // render at the right error boundary after we match routes
1802 pendingError: error,
1803 preventScrollReset,
1804 replace: opts && opts.replace,
1805 enableViewTransition: opts && opts.viewTransition,
1806 flushSync,
1807 callSiteDefaultShouldRevalidate: opts && opts.unstable_defaultShouldRevalidate
1808 });
1809 }
1810 function revalidate() {
1811 if (!pendingRevalidationDfd) {
1812 pendingRevalidationDfd = createDeferred();
1813 }
1814 interruptActiveLoads();
1815 updateState({ revalidation: "loading" });
1816 let promise = pendingRevalidationDfd.promise;
1817 if (state.navigation.state === "submitting") {
1818 return promise;
1819 }
1820 if (state.navigation.state === "idle") {
1821 startNavigation(state.historyAction, state.location, {
1822 startUninterruptedRevalidation: true
1823 });
1824 return promise;
1825 }
1826 startNavigation(
1827 pendingAction || state.historyAction,
1828 state.navigation.location,
1829 {
1830 overrideNavigation: state.navigation,
1831 // Proxy through any rending view transition
1832 enableViewTransition: pendingViewTransitionEnabled === true
1833 }
1834 );
1835 return promise;
1836 }
1837 async function startNavigation(historyAction, location, opts) {
1838 pendingNavigationController && pendingNavigationController.abort();
1839 pendingNavigationController = null;
1840 pendingAction = historyAction;
1841 isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
1842 saveScrollPosition(state.location, state.matches);
1843 pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
1844 pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
1845 let routesToUse = inFlightDataRoutes || dataRoutes;
1846 let loadingNavigation = opts && opts.overrideNavigation;
1847 let matches = _optionalChain([opts, 'optionalAccess', _22 => _22.initialHydration]) && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ? (
1848 // `matchRoutes()` has already been called if we're in here via `router.initialize()`
1849 state.matches
1850 ) : matchRoutes(routesToUse, location, basename);
1851 let flushSync = (opts && opts.flushSync) === true;
1852 if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
1853 completeNavigation(location, { matches }, { flushSync });
1854 return;
1855 }
1856 let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
1857 if (fogOfWar.active && fogOfWar.matches) {
1858 matches = fogOfWar.matches;
1859 }
1860 if (!matches) {
1861 let { error, notFoundMatches, route } = handleNavigational404(
1862 location.pathname
1863 );
1864 completeNavigation(
1865 location,
1866 {
1867 matches: notFoundMatches,
1868 loaderData: {},
1869 errors: {
1870 [route.id]: error
1871 }
1872 },
1873 { flushSync }
1874 );
1875 return;
1876 }
1877 pendingNavigationController = new AbortController();
1878 let request = createClientSideRequest(
1879 init.history,
1880 location,
1881 pendingNavigationController.signal,
1882 opts && opts.submission
1883 );
1884 let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
1885 let pendingActionResult;
1886 if (opts && opts.pendingError) {
1887 pendingActionResult = [
1888 findNearestBoundary(matches).route.id,
1889 { type: "error" /* error */, error: opts.pendingError }
1890 ];
1891 } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
1892 let actionResult = await handleAction(
1893 request,
1894 location,
1895 opts.submission,
1896 matches,
1897 scopedContext,
1898 fogOfWar.active,
1899 opts && opts.initialHydration === true,
1900 { replace: opts.replace, flushSync }
1901 );
1902 if (actionResult.shortCircuited) {
1903 return;
1904 }
1905 if (actionResult.pendingActionResult) {
1906 let [routeId, result] = actionResult.pendingActionResult;
1907 if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
1908 pendingNavigationController = null;
1909 completeNavigation(location, {
1910 matches: actionResult.matches,
1911 loaderData: {},
1912 errors: {
1913 [routeId]: result.error
1914 }
1915 });
1916 return;
1917 }
1918 }
1919 matches = actionResult.matches || matches;
1920 pendingActionResult = actionResult.pendingActionResult;
1921 loadingNavigation = getLoadingNavigation(location, opts.submission);
1922 flushSync = false;
1923 fogOfWar.active = false;
1924 request = createClientSideRequest(
1925 init.history,
1926 request.url,
1927 request.signal
1928 );
1929 }
1930 let {
1931 shortCircuited,
1932 matches: updatedMatches,
1933 loaderData,
1934 errors
1935 } = await handleLoaders(
1936 request,
1937 location,
1938 matches,
1939 scopedContext,
1940 fogOfWar.active,
1941 loadingNavigation,
1942 opts && opts.submission,
1943 opts && opts.fetcherSubmission,
1944 opts && opts.replace,
1945 opts && opts.initialHydration === true,
1946 flushSync,
1947 pendingActionResult,
1948 opts && opts.callSiteDefaultShouldRevalidate
1949 );
1950 if (shortCircuited) {
1951 return;
1952 }
1953 pendingNavigationController = null;
1954 completeNavigation(location, {
1955 matches: updatedMatches || matches,
1956 ...getActionDataForCommit(pendingActionResult),
1957 loaderData,
1958 errors
1959 });
1960 }
1961 async function handleAction(request, location, submission, matches, scopedContext, isFogOfWar, initialHydration, opts = {}) {
1962 interruptActiveLoads();
1963 let navigation = getSubmittingNavigation(location, submission);
1964 updateState({ navigation }, { flushSync: opts.flushSync === true });
1965 if (isFogOfWar) {
1966 let discoverResult = await discoverRoutes(
1967 matches,
1968 location.pathname,
1969 request.signal
1970 );
1971 if (discoverResult.type === "aborted") {
1972 return { shortCircuited: true };
1973 } else if (discoverResult.type === "error") {
1974 if (discoverResult.partialMatches.length === 0) {
1975 let { matches: matches2, route } = getShortCircuitMatches(dataRoutes);
1976 return {
1977 matches: matches2,
1978 pendingActionResult: [
1979 route.id,
1980 {
1981 type: "error" /* error */,
1982 error: discoverResult.error
1983 }
1984 ]
1985 };
1986 }
1987 let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
1988 return {
1989 matches: discoverResult.partialMatches,
1990 pendingActionResult: [
1991 boundaryId,
1992 {
1993 type: "error" /* error */,
1994 error: discoverResult.error
1995 }
1996 ]
1997 };
1998 } else if (!discoverResult.matches) {
1999 let { notFoundMatches, error, route } = handleNavigational404(
2000 location.pathname
2001 );
2002 return {
2003 matches: notFoundMatches,
2004 pendingActionResult: [
2005 route.id,
2006 {
2007 type: "error" /* error */,
2008 error
2009 }
2010 ]
2011 };
2012 } else {
2013 matches = discoverResult.matches;
2014 }
2015 }
2016 let result;
2017 let actionMatch = getTargetMatch(matches, location);
2018 if (!actionMatch.route.action && !actionMatch.route.lazy) {
2019 result = {
2020 type: "error" /* error */,
2021 error: getInternalRouterError(405, {
2022 method: request.method,
2023 pathname: location.pathname,
2024 routeId: actionMatch.route.id
2025 })
2026 };
2027 } else {
2028 let dsMatches = getTargetedDataStrategyMatches(
2029 mapRouteProperties2,
2030 manifest,
2031 request,
2032 location,
2033 matches,
2034 actionMatch,
2035 initialHydration ? [] : hydrationRouteProperties2,
2036 scopedContext
2037 );
2038 let results = await callDataStrategy(
2039 request,
2040 location,
2041 dsMatches,
2042 scopedContext,
2043 null
2044 );
2045 result = results[actionMatch.route.id];
2046 if (!result) {
2047 for (let match of matches) {
2048 if (results[match.route.id]) {
2049 result = results[match.route.id];
2050 break;
2051 }
2052 }
2053 }
2054 if (request.signal.aborted) {
2055 return { shortCircuited: true };
2056 }
2057 }
2058 if (isRedirectResult(result)) {
2059 let replace2;
2060 if (opts && opts.replace != null) {
2061 replace2 = opts.replace;
2062 } else {
2063 let location2 = normalizeRedirectLocation(
2064 result.response.headers.get("Location"),
2065 new URL(request.url),
2066 basename,
2067 init.history
2068 );
2069 replace2 = location2 === state.location.pathname + state.location.search;
2070 }
2071 await startRedirectNavigation(request, result, true, {
2072 submission,
2073 replace: replace2
2074 });
2075 return { shortCircuited: true };
2076 }
2077 if (isErrorResult(result)) {
2078 let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
2079 if ((opts && opts.replace) !== true) {
2080 pendingAction = "PUSH" /* Push */;
2081 }
2082 return {
2083 matches,
2084 pendingActionResult: [
2085 boundaryMatch.route.id,
2086 result,
2087 actionMatch.route.id
2088 ]
2089 };
2090 }
2091 return {
2092 matches,
2093 pendingActionResult: [actionMatch.route.id, result]
2094 };
2095 }
2096 async function handleLoaders(request, location, matches, scopedContext, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace2, initialHydration, flushSync, pendingActionResult, callSiteDefaultShouldRevalidate) {
2097 let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
2098 let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
2099 let shouldUpdateNavigationState = !isUninterruptedRevalidation && !initialHydration;
2100 if (isFogOfWar) {
2101 if (shouldUpdateNavigationState) {
2102 let actionData = getUpdatedActionData(pendingActionResult);
2103 updateState(
2104 {
2105 navigation: loadingNavigation,
2106 ...actionData !== void 0 ? { actionData } : {}
2107 },
2108 {
2109 flushSync
2110 }
2111 );
2112 }
2113 let discoverResult = await discoverRoutes(
2114 matches,
2115 location.pathname,
2116 request.signal
2117 );
2118 if (discoverResult.type === "aborted") {
2119 return { shortCircuited: true };
2120 } else if (discoverResult.type === "error") {
2121 if (discoverResult.partialMatches.length === 0) {
2122 let { matches: matches2, route } = getShortCircuitMatches(dataRoutes);
2123 return {
2124 matches: matches2,
2125 loaderData: {},
2126 errors: {
2127 [route.id]: discoverResult.error
2128 }
2129 };
2130 }
2131 let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
2132 return {
2133 matches: discoverResult.partialMatches,
2134 loaderData: {},
2135 errors: {
2136 [boundaryId]: discoverResult.error
2137 }
2138 };
2139 } else if (!discoverResult.matches) {
2140 let { error, notFoundMatches, route } = handleNavigational404(
2141 location.pathname
2142 );
2143 return {
2144 matches: notFoundMatches,
2145 loaderData: {},
2146 errors: {
2147 [route.id]: error
2148 }
2149 };
2150 } else {
2151 matches = discoverResult.matches;
2152 }
2153 }
2154 let routesToUse = inFlightDataRoutes || dataRoutes;
2155 let { dsMatches, revalidatingFetchers } = getMatchesToLoad(
2156 request,
2157 scopedContext,
2158 mapRouteProperties2,
2159 manifest,
2160 init.history,
2161 state,
2162 matches,
2163 activeSubmission,
2164 location,
2165 initialHydration ? [] : hydrationRouteProperties2,
2166 initialHydration === true,
2167 isRevalidationRequired,
2168 cancelledFetcherLoads,
2169 fetchersQueuedForDeletion,
2170 fetchLoadMatches,
2171 fetchRedirectIds,
2172 routesToUse,
2173 basename,
2174 init.patchRoutesOnNavigation != null,
2175 pendingActionResult,
2176 callSiteDefaultShouldRevalidate
2177 );
2178 pendingNavigationLoadId = ++incrementingLoadId;
2179 if (!init.dataStrategy && !dsMatches.some((m) => m.shouldLoad) && !dsMatches.some(
2180 (m) => m.route.middleware && m.route.middleware.length > 0
2181 ) && revalidatingFetchers.length === 0) {
2182 let updatedFetchers2 = markFetchRedirectsDone();
2183 completeNavigation(
2184 location,
2185 {
2186 matches,
2187 loaderData: {},
2188 // Commit pending error if we're short circuiting
2189 errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null,
2190 ...getActionDataForCommit(pendingActionResult),
2191 ...updatedFetchers2 ? { fetchers: new Map(state.fetchers) } : {}
2192 },
2193 { flushSync }
2194 );
2195 return { shortCircuited: true };
2196 }
2197 if (shouldUpdateNavigationState) {
2198 let updates = {};
2199 if (!isFogOfWar) {
2200 updates.navigation = loadingNavigation;
2201 let actionData = getUpdatedActionData(pendingActionResult);
2202 if (actionData !== void 0) {
2203 updates.actionData = actionData;
2204 }
2205 }
2206 if (revalidatingFetchers.length > 0) {
2207 updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
2208 }
2209 updateState(updates, { flushSync });
2210 }
2211 revalidatingFetchers.forEach((rf) => {
2212 abortFetcher(rf.key);
2213 if (rf.controller) {
2214 fetchControllers.set(rf.key, rf.controller);
2215 }
2216 });
2217 let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((f) => abortFetcher(f.key));
2218 if (pendingNavigationController) {
2219 pendingNavigationController.signal.addEventListener(
2220 "abort",
2221 abortPendingFetchRevalidations
2222 );
2223 }
2224 let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
2225 dsMatches,
2226 revalidatingFetchers,
2227 request,
2228 location,
2229 scopedContext
2230 );
2231 if (request.signal.aborted) {
2232 return { shortCircuited: true };
2233 }
2234 if (pendingNavigationController) {
2235 pendingNavigationController.signal.removeEventListener(
2236 "abort",
2237 abortPendingFetchRevalidations
2238 );
2239 }
2240 revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));
2241 let redirect2 = findRedirect(loaderResults);
2242 if (redirect2) {
2243 await startRedirectNavigation(request, redirect2.result, true, {
2244 replace: replace2
2245 });
2246 return { shortCircuited: true };
2247 }
2248 redirect2 = findRedirect(fetcherResults);
2249 if (redirect2) {
2250 fetchRedirectIds.add(redirect2.key);
2251 await startRedirectNavigation(request, redirect2.result, true, {
2252 replace: replace2
2253 });
2254 return { shortCircuited: true };
2255 }
2256 let { loaderData, errors } = processLoaderData(
2257 state,
2258 matches,
2259 loaderResults,
2260 pendingActionResult,
2261 revalidatingFetchers,
2262 fetcherResults
2263 );
2264 if (initialHydration && state.errors) {
2265 errors = { ...state.errors, ...errors };
2266 }
2267 let updatedFetchers = markFetchRedirectsDone();
2268 let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
2269 let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
2270 return {
2271 matches,
2272 loaderData,
2273 errors,
2274 ...shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}
2275 };
2276 }
2277 function getUpdatedActionData(pendingActionResult) {
2278 if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
2279 return {
2280 [pendingActionResult[0]]: pendingActionResult[1].data
2281 };
2282 } else if (state.actionData) {
2283 if (Object.keys(state.actionData).length === 0) {
2284 return null;
2285 } else {
2286 return state.actionData;
2287 }
2288 }
2289 }
2290 function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
2291 revalidatingFetchers.forEach((rf) => {
2292 let fetcher = state.fetchers.get(rf.key);
2293 let revalidatingFetcher = getLoadingFetcher(
2294 void 0,
2295 fetcher ? fetcher.data : void 0
2296 );
2297 state.fetchers.set(rf.key, revalidatingFetcher);
2298 });
2299 return new Map(state.fetchers);
2300 }
2301 async function fetch2(key, routeId, href, opts) {
2302 abortFetcher(key);
2303 let flushSync = (opts && opts.flushSync) === true;
2304 let routesToUse = inFlightDataRoutes || dataRoutes;
2305 let normalizedPath = normalizeTo(
2306 state.location,
2307 state.matches,
2308 basename,
2309 href,
2310 routeId,
2311 _optionalChain([opts, 'optionalAccess', _23 => _23.relative])
2312 );
2313 let matches = matchRoutes(routesToUse, normalizedPath, basename);
2314 let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
2315 if (fogOfWar.active && fogOfWar.matches) {
2316 matches = fogOfWar.matches;
2317 }
2318 if (!matches) {
2319 setFetcherError(
2320 key,
2321 routeId,
2322 getInternalRouterError(404, { pathname: normalizedPath }),
2323 { flushSync }
2324 );
2325 return;
2326 }
2327 let { path, submission, error } = normalizeNavigateOptions(
2328 true,
2329 normalizedPath,
2330 opts
2331 );
2332 if (error) {
2333 setFetcherError(key, routeId, error, { flushSync });
2334 return;
2335 }
2336 let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
2337 let preventScrollReset = (opts && opts.preventScrollReset) === true;
2338 if (submission && isMutationMethod(submission.formMethod)) {
2339 await handleFetcherAction(
2340 key,
2341 routeId,
2342 path,
2343 matches,
2344 scopedContext,
2345 fogOfWar.active,
2346 flushSync,
2347 preventScrollReset,
2348 submission,
2349 opts && opts.unstable_defaultShouldRevalidate
2350 );
2351 return;
2352 }
2353 fetchLoadMatches.set(key, { routeId, path });
2354 await handleFetcherLoader(
2355 key,
2356 routeId,
2357 path,
2358 matches,
2359 scopedContext,
2360 fogOfWar.active,
2361 flushSync,
2362 preventScrollReset,
2363 submission
2364 );
2365 }
2366 async function handleFetcherAction(key, routeId, path, requestMatches, scopedContext, isFogOfWar, flushSync, preventScrollReset, submission, callSiteDefaultShouldRevalidate) {
2367 interruptActiveLoads();
2368 fetchLoadMatches.delete(key);
2369 let existingFetcher = state.fetchers.get(key);
2370 updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
2371 flushSync
2372 });
2373 let abortController = new AbortController();
2374 let fetchRequest = createClientSideRequest(
2375 init.history,
2376 path,
2377 abortController.signal,
2378 submission
2379 );
2380 if (isFogOfWar) {
2381 let discoverResult = await discoverRoutes(
2382 requestMatches,
2383 new URL(fetchRequest.url).pathname,
2384 fetchRequest.signal,
2385 key
2386 );
2387 if (discoverResult.type === "aborted") {
2388 return;
2389 } else if (discoverResult.type === "error") {
2390 setFetcherError(key, routeId, discoverResult.error, { flushSync });
2391 return;
2392 } else if (!discoverResult.matches) {
2393 setFetcherError(
2394 key,
2395 routeId,
2396 getInternalRouterError(404, { pathname: path }),
2397 { flushSync }
2398 );
2399 return;
2400 } else {
2401 requestMatches = discoverResult.matches;
2402 }
2403 }
2404 let match = getTargetMatch(requestMatches, path);
2405 if (!match.route.action && !match.route.lazy) {
2406 let error = getInternalRouterError(405, {
2407 method: submission.formMethod,
2408 pathname: path,
2409 routeId
2410 });
2411 setFetcherError(key, routeId, error, { flushSync });
2412 return;
2413 }
2414 fetchControllers.set(key, abortController);
2415 let originatingLoadId = incrementingLoadId;
2416 let fetchMatches = getTargetedDataStrategyMatches(
2417 mapRouteProperties2,
2418 manifest,
2419 fetchRequest,
2420 path,
2421 requestMatches,
2422 match,
2423 hydrationRouteProperties2,
2424 scopedContext
2425 );
2426 let actionResults = await callDataStrategy(
2427 fetchRequest,
2428 path,
2429 fetchMatches,
2430 scopedContext,
2431 key
2432 );
2433 let actionResult = actionResults[match.route.id];
2434 if (!actionResult) {
2435 for (let match2 of fetchMatches) {
2436 if (actionResults[match2.route.id]) {
2437 actionResult = actionResults[match2.route.id];
2438 break;
2439 }
2440 }
2441 }
2442 if (fetchRequest.signal.aborted) {
2443 if (fetchControllers.get(key) === abortController) {
2444 fetchControllers.delete(key);
2445 }
2446 return;
2447 }
2448 if (fetchersQueuedForDeletion.has(key)) {
2449 if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
2450 updateFetcherState(key, getDoneFetcher(void 0));
2451 return;
2452 }
2453 } else {
2454 if (isRedirectResult(actionResult)) {
2455 fetchControllers.delete(key);
2456 if (pendingNavigationLoadId > originatingLoadId) {
2457 updateFetcherState(key, getDoneFetcher(void 0));
2458 return;
2459 } else {
2460 fetchRedirectIds.add(key);
2461 updateFetcherState(key, getLoadingFetcher(submission));
2462 return startRedirectNavigation(fetchRequest, actionResult, false, {
2463 fetcherSubmission: submission,
2464 preventScrollReset
2465 });
2466 }
2467 }
2468 if (isErrorResult(actionResult)) {
2469 setFetcherError(key, routeId, actionResult.error);
2470 return;
2471 }
2472 }
2473 let nextLocation = state.navigation.location || state.location;
2474 let revalidationRequest = createClientSideRequest(
2475 init.history,
2476 nextLocation,
2477 abortController.signal
2478 );
2479 let routesToUse = inFlightDataRoutes || dataRoutes;
2480 let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;
2481 invariant(matches, "Didn't find any matches after fetcher action");
2482 let loadId = ++incrementingLoadId;
2483 fetchReloadIds.set(key, loadId);
2484 let loadFetcher = getLoadingFetcher(submission, actionResult.data);
2485 state.fetchers.set(key, loadFetcher);
2486 let { dsMatches, revalidatingFetchers } = getMatchesToLoad(
2487 revalidationRequest,
2488 scopedContext,
2489 mapRouteProperties2,
2490 manifest,
2491 init.history,
2492 state,
2493 matches,
2494 submission,
2495 nextLocation,
2496 hydrationRouteProperties2,
2497 false,
2498 isRevalidationRequired,
2499 cancelledFetcherLoads,
2500 fetchersQueuedForDeletion,
2501 fetchLoadMatches,
2502 fetchRedirectIds,
2503 routesToUse,
2504 basename,
2505 init.patchRoutesOnNavigation != null,
2506 [match.route.id, actionResult],
2507 callSiteDefaultShouldRevalidate
2508 );
2509 revalidatingFetchers.filter((rf) => rf.key !== key).forEach((rf) => {
2510 let staleKey = rf.key;
2511 let existingFetcher2 = state.fetchers.get(staleKey);
2512 let revalidatingFetcher = getLoadingFetcher(
2513 void 0,
2514 existingFetcher2 ? existingFetcher2.data : void 0
2515 );
2516 state.fetchers.set(staleKey, revalidatingFetcher);
2517 abortFetcher(staleKey);
2518 if (rf.controller) {
2519 fetchControllers.set(staleKey, rf.controller);
2520 }
2521 });
2522 updateState({ fetchers: new Map(state.fetchers) });
2523 let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));
2524 abortController.signal.addEventListener(
2525 "abort",
2526 abortPendingFetchRevalidations
2527 );
2528 let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
2529 dsMatches,
2530 revalidatingFetchers,
2531 revalidationRequest,
2532 nextLocation,
2533 scopedContext
2534 );
2535 if (abortController.signal.aborted) {
2536 return;
2537 }
2538 abortController.signal.removeEventListener(
2539 "abort",
2540 abortPendingFetchRevalidations
2541 );
2542 fetchReloadIds.delete(key);
2543 fetchControllers.delete(key);
2544 revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));
2545 if (state.fetchers.has(key)) {
2546 let doneFetcher = getDoneFetcher(actionResult.data);
2547 state.fetchers.set(key, doneFetcher);
2548 }
2549 let redirect2 = findRedirect(loaderResults);
2550 if (redirect2) {
2551 return startRedirectNavigation(
2552 revalidationRequest,
2553 redirect2.result,
2554 false,
2555 { preventScrollReset }
2556 );
2557 }
2558 redirect2 = findRedirect(fetcherResults);
2559 if (redirect2) {
2560 fetchRedirectIds.add(redirect2.key);
2561 return startRedirectNavigation(
2562 revalidationRequest,
2563 redirect2.result,
2564 false,
2565 { preventScrollReset }
2566 );
2567 }
2568 let { loaderData, errors } = processLoaderData(
2569 state,
2570 matches,
2571 loaderResults,
2572 void 0,
2573 revalidatingFetchers,
2574 fetcherResults
2575 );
2576 abortStaleFetchLoads(loadId);
2577 if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
2578 invariant(pendingAction, "Expected pending action");
2579 pendingNavigationController && pendingNavigationController.abort();
2580 completeNavigation(state.navigation.location, {
2581 matches,
2582 loaderData,
2583 errors,
2584 fetchers: new Map(state.fetchers)
2585 });
2586 } else {
2587 updateState({
2588 errors,
2589 loaderData: mergeLoaderData(
2590 state.loaderData,
2591 loaderData,
2592 matches,
2593 errors
2594 ),
2595 fetchers: new Map(state.fetchers)
2596 });
2597 isRevalidationRequired = false;
2598 }
2599 }
2600 async function handleFetcherLoader(key, routeId, path, matches, scopedContext, isFogOfWar, flushSync, preventScrollReset, submission) {
2601 let existingFetcher = state.fetchers.get(key);
2602 updateFetcherState(
2603 key,
2604 getLoadingFetcher(
2605 submission,
2606 existingFetcher ? existingFetcher.data : void 0
2607 ),
2608 { flushSync }
2609 );
2610 let abortController = new AbortController();
2611 let fetchRequest = createClientSideRequest(
2612 init.history,
2613 path,
2614 abortController.signal
2615 );
2616 if (isFogOfWar) {
2617 let discoverResult = await discoverRoutes(
2618 matches,
2619 new URL(fetchRequest.url).pathname,
2620 fetchRequest.signal,
2621 key
2622 );
2623 if (discoverResult.type === "aborted") {
2624 return;
2625 } else if (discoverResult.type === "error") {
2626 setFetcherError(key, routeId, discoverResult.error, { flushSync });
2627 return;
2628 } else if (!discoverResult.matches) {
2629 setFetcherError(
2630 key,
2631 routeId,
2632 getInternalRouterError(404, { pathname: path }),
2633 { flushSync }
2634 );
2635 return;
2636 } else {
2637 matches = discoverResult.matches;
2638 }
2639 }
2640 let match = getTargetMatch(matches, path);
2641 fetchControllers.set(key, abortController);
2642 let originatingLoadId = incrementingLoadId;
2643 let dsMatches = getTargetedDataStrategyMatches(
2644 mapRouteProperties2,
2645 manifest,
2646 fetchRequest,
2647 path,
2648 matches,
2649 match,
2650 hydrationRouteProperties2,
2651 scopedContext
2652 );
2653 let results = await callDataStrategy(
2654 fetchRequest,
2655 path,
2656 dsMatches,
2657 scopedContext,
2658 key
2659 );
2660 let result = results[match.route.id];
2661 if (!result) {
2662 for (let match2 of matches) {
2663 if (results[match2.route.id]) {
2664 result = results[match2.route.id];
2665 break;
2666 }
2667 }
2668 }
2669 if (fetchControllers.get(key) === abortController) {
2670 fetchControllers.delete(key);
2671 }
2672 if (fetchRequest.signal.aborted) {
2673 return;
2674 }
2675 if (fetchersQueuedForDeletion.has(key)) {
2676 updateFetcherState(key, getDoneFetcher(void 0));
2677 return;
2678 }
2679 if (isRedirectResult(result)) {
2680 if (pendingNavigationLoadId > originatingLoadId) {
2681 updateFetcherState(key, getDoneFetcher(void 0));
2682 return;
2683 } else {
2684 fetchRedirectIds.add(key);
2685 await startRedirectNavigation(fetchRequest, result, false, {
2686 preventScrollReset
2687 });
2688 return;
2689 }
2690 }
2691 if (isErrorResult(result)) {
2692 setFetcherError(key, routeId, result.error);
2693 return;
2694 }
2695 updateFetcherState(key, getDoneFetcher(result.data));
2696 }
2697 async function startRedirectNavigation(request, redirect2, isNavigation, {
2698 submission,
2699 fetcherSubmission,
2700 preventScrollReset,
2701 replace: replace2
2702 } = {}) {
2703 if (!isNavigation) {
2704 _optionalChain([pendingPopstateNavigationDfd, 'optionalAccess', _24 => _24.resolve, 'call', _25 => _25()]);
2705 pendingPopstateNavigationDfd = null;
2706 }
2707 if (redirect2.response.headers.has("X-Remix-Revalidate")) {
2708 isRevalidationRequired = true;
2709 }
2710 let location = redirect2.response.headers.get("Location");
2711 invariant(location, "Expected a Location header on the redirect Response");
2712 location = normalizeRedirectLocation(
2713 location,
2714 new URL(request.url),
2715 basename,
2716 init.history
2717 );
2718 let redirectLocation = createLocation(state.location, location, {
2719 _isRedirect: true
2720 });
2721 if (isBrowser2) {
2722 let isDocumentReload = false;
2723 if (redirect2.response.headers.has("X-Remix-Reload-Document")) {
2724 isDocumentReload = true;
2725 } else if (isAbsoluteUrl(location)) {
2726 const url = createBrowserURLImpl(location, true);
2727 isDocumentReload = // Hard reload if it's an absolute URL to a new origin
2728 url.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename
2729 stripBasename(url.pathname, basename) == null;
2730 }
2731 if (isDocumentReload) {
2732 if (replace2) {
2733 routerWindow.location.replace(location);
2734 } else {
2735 routerWindow.location.assign(location);
2736 }
2737 return;
2738 }
2739 }
2740 pendingNavigationController = null;
2741 let redirectNavigationType = replace2 === true || redirect2.response.headers.has("X-Remix-Replace") ? "REPLACE" /* Replace */ : "PUSH" /* Push */;
2742 let { formMethod, formAction, formEncType } = state.navigation;
2743 if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
2744 submission = getSubmissionFromNavigation(state.navigation);
2745 }
2746 let activeSubmission = submission || fetcherSubmission;
2747 if (redirectPreserveMethodStatusCodes.has(redirect2.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
2748 await startNavigation(redirectNavigationType, redirectLocation, {
2749 submission: {
2750 ...activeSubmission,
2751 formAction: location
2752 },
2753 // Preserve these flags across redirects
2754 preventScrollReset: preventScrollReset || pendingPreventScrollReset,
2755 enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
2756 });
2757 } else {
2758 let overrideNavigation = getLoadingNavigation(
2759 redirectLocation,
2760 submission
2761 );
2762 await startNavigation(redirectNavigationType, redirectLocation, {
2763 overrideNavigation,
2764 // Send fetcher submissions through for shouldRevalidate
2765 fetcherSubmission,
2766 // Preserve these flags across redirects
2767 preventScrollReset: preventScrollReset || pendingPreventScrollReset,
2768 enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
2769 });
2770 }
2771 }
2772 async function callDataStrategy(request, path, matches, scopedContext, fetcherKey) {
2773 let results;
2774 let dataResults = {};
2775 try {
2776 results = await callDataStrategyImpl(
2777 dataStrategyImpl,
2778 request,
2779 path,
2780 matches,
2781 fetcherKey,
2782 scopedContext,
2783 false
2784 );
2785 } catch (e) {
2786 matches.filter((m) => m.shouldLoad).forEach((m) => {
2787 dataResults[m.route.id] = {
2788 type: "error" /* error */,
2789 error: e
2790 };
2791 });
2792 return dataResults;
2793 }
2794 if (request.signal.aborted) {
2795 return dataResults;
2796 }
2797 if (!isMutationMethod(request.method)) {
2798 for (let match of matches) {
2799 if (_optionalChain([results, 'access', _26 => _26[match.route.id], 'optionalAccess', _27 => _27.type]) === "error" /* error */) {
2800 break;
2801 }
2802 if (!results.hasOwnProperty(match.route.id) && !state.loaderData.hasOwnProperty(match.route.id) && (!state.errors || !state.errors.hasOwnProperty(match.route.id)) && match.shouldCallHandler()) {
2803 results[match.route.id] = {
2804 type: "error" /* error */,
2805 result: new Error(
2806 `No result returned from dataStrategy for route ${match.route.id}`
2807 )
2808 };
2809 }
2810 }
2811 }
2812 for (let [routeId, result] of Object.entries(results)) {
2813 if (isRedirectDataStrategyResult(result)) {
2814 let response = result.result;
2815 dataResults[routeId] = {
2816 type: "redirect" /* redirect */,
2817 response: normalizeRelativeRoutingRedirectResponse(
2818 response,
2819 request,
2820 routeId,
2821 matches,
2822 basename
2823 )
2824 };
2825 } else {
2826 dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
2827 }
2828 }
2829 return dataResults;
2830 }
2831 async function callLoadersAndMaybeResolveData(matches, fetchersToLoad, request, location, scopedContext) {
2832 let loaderResultsPromise = callDataStrategy(
2833 request,
2834 location,
2835 matches,
2836 scopedContext,
2837 null
2838 );
2839 let fetcherResultsPromise = Promise.all(
2840 fetchersToLoad.map(async (f) => {
2841 if (f.matches && f.match && f.request && f.controller) {
2842 let results = await callDataStrategy(
2843 f.request,
2844 f.path,
2845 f.matches,
2846 scopedContext,
2847 f.key
2848 );
2849 let result = results[f.match.route.id];
2850 return { [f.key]: result };
2851 } else {
2852 return Promise.resolve({
2853 [f.key]: {
2854 type: "error" /* error */,
2855 error: getInternalRouterError(404, {
2856 pathname: f.path
2857 })
2858 }
2859 });
2860 }
2861 })
2862 );
2863 let loaderResults = await loaderResultsPromise;
2864 let fetcherResults = (await fetcherResultsPromise).reduce(
2865 (acc, r) => Object.assign(acc, r),
2866 {}
2867 );
2868 return {
2869 loaderResults,
2870 fetcherResults
2871 };
2872 }
2873 function interruptActiveLoads() {
2874 isRevalidationRequired = true;
2875 fetchLoadMatches.forEach((_, key) => {
2876 if (fetchControllers.has(key)) {
2877 cancelledFetcherLoads.add(key);
2878 }
2879 abortFetcher(key);
2880 });
2881 }
2882 function updateFetcherState(key, fetcher, opts = {}) {
2883 state.fetchers.set(key, fetcher);
2884 updateState(
2885 { fetchers: new Map(state.fetchers) },
2886 { flushSync: (opts && opts.flushSync) === true }
2887 );
2888 }
2889 function setFetcherError(key, routeId, error, opts = {}) {
2890 let boundaryMatch = findNearestBoundary(state.matches, routeId);
2891 deleteFetcher(key);
2892 updateState(
2893 {
2894 errors: {
2895 [boundaryMatch.route.id]: error
2896 },
2897 fetchers: new Map(state.fetchers)
2898 },
2899 { flushSync: (opts && opts.flushSync) === true }
2900 );
2901 }
2902 function getFetcher(key) {
2903 activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
2904 if (fetchersQueuedForDeletion.has(key)) {
2905 fetchersQueuedForDeletion.delete(key);
2906 }
2907 return state.fetchers.get(key) || IDLE_FETCHER;
2908 }
2909 function resetFetcher(key, opts) {
2910 abortFetcher(key, _optionalChain([opts, 'optionalAccess', _28 => _28.reason]));
2911 updateFetcherState(key, getDoneFetcher(null));
2912 }
2913 function deleteFetcher(key) {
2914 let fetcher = state.fetchers.get(key);
2915 if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
2916 abortFetcher(key);
2917 }
2918 fetchLoadMatches.delete(key);
2919 fetchReloadIds.delete(key);
2920 fetchRedirectIds.delete(key);
2921 fetchersQueuedForDeletion.delete(key);
2922 cancelledFetcherLoads.delete(key);
2923 state.fetchers.delete(key);
2924 }
2925 function queueFetcherForDeletion(key) {
2926 let count = (activeFetchers.get(key) || 0) - 1;
2927 if (count <= 0) {
2928 activeFetchers.delete(key);
2929 fetchersQueuedForDeletion.add(key);
2930 } else {
2931 activeFetchers.set(key, count);
2932 }
2933 updateState({ fetchers: new Map(state.fetchers) });
2934 }
2935 function abortFetcher(key, reason) {
2936 let controller = fetchControllers.get(key);
2937 if (controller) {
2938 controller.abort(reason);
2939 fetchControllers.delete(key);
2940 }
2941 }
2942 function markFetchersDone(keys) {
2943 for (let key of keys) {
2944 let fetcher = getFetcher(key);
2945 let doneFetcher = getDoneFetcher(fetcher.data);
2946 state.fetchers.set(key, doneFetcher);
2947 }
2948 }
2949 function markFetchRedirectsDone() {
2950 let doneKeys = [];
2951 let updatedFetchers = false;
2952 for (let key of fetchRedirectIds) {
2953 let fetcher = state.fetchers.get(key);
2954 invariant(fetcher, `Expected fetcher: ${key}`);
2955 if (fetcher.state === "loading") {
2956 fetchRedirectIds.delete(key);
2957 doneKeys.push(key);
2958 updatedFetchers = true;
2959 }
2960 }
2961 markFetchersDone(doneKeys);
2962 return updatedFetchers;
2963 }
2964 function abortStaleFetchLoads(landedId) {
2965 let yeetedKeys = [];
2966 for (let [key, id] of fetchReloadIds) {
2967 if (id < landedId) {
2968 let fetcher = state.fetchers.get(key);
2969 invariant(fetcher, `Expected fetcher: ${key}`);
2970 if (fetcher.state === "loading") {
2971 abortFetcher(key);
2972 fetchReloadIds.delete(key);
2973 yeetedKeys.push(key);
2974 }
2975 }
2976 }
2977 markFetchersDone(yeetedKeys);
2978 return yeetedKeys.length > 0;
2979 }
2980 function getBlocker(key, fn) {
2981 let blocker = state.blockers.get(key) || IDLE_BLOCKER;
2982 if (blockerFunctions.get(key) !== fn) {
2983 blockerFunctions.set(key, fn);
2984 }
2985 return blocker;
2986 }
2987 function deleteBlocker(key) {
2988 state.blockers.delete(key);
2989 blockerFunctions.delete(key);
2990 }
2991 function updateBlocker(key, newBlocker) {
2992 let blocker = state.blockers.get(key) || IDLE_BLOCKER;
2993 invariant(
2994 blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked",
2995 `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`
2996 );
2997 let blockers = new Map(state.blockers);
2998 blockers.set(key, newBlocker);
2999 updateState({ blockers });
3000 }
3001 function shouldBlockNavigation({
3002 currentLocation,
3003 nextLocation,
3004 historyAction
3005 }) {
3006 if (blockerFunctions.size === 0) {
3007 return;
3008 }
3009 if (blockerFunctions.size > 1) {
3010 warning(false, "A router only supports one blocker at a time");
3011 }
3012 let entries = Array.from(blockerFunctions.entries());
3013 let [blockerKey, blockerFunction] = entries[entries.length - 1];
3014 let blocker = state.blockers.get(blockerKey);
3015 if (blocker && blocker.state === "proceeding") {
3016 return;
3017 }
3018 if (blockerFunction({ currentLocation, nextLocation, historyAction })) {
3019 return blockerKey;
3020 }
3021 }
3022 function handleNavigational404(pathname) {
3023 let error = getInternalRouterError(404, { pathname });
3024 let routesToUse = inFlightDataRoutes || dataRoutes;
3025 let { matches, route } = getShortCircuitMatches(routesToUse);
3026 return { notFoundMatches: matches, route, error };
3027 }
3028 function enableScrollRestoration(positions, getPosition, getKey) {
3029 savedScrollPositions = positions;
3030 getScrollPosition = getPosition;
3031 getScrollRestorationKey = getKey || null;
3032 if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
3033 initialScrollRestored = true;
3034 let y = getSavedScrollPosition(state.location, state.matches);
3035 if (y != null) {
3036 updateState({ restoreScrollPosition: y });
3037 }
3038 }
3039 return () => {
3040 savedScrollPositions = null;
3041 getScrollPosition = null;
3042 getScrollRestorationKey = null;
3043 };
3044 }
3045 function getScrollKey(location, matches) {
3046 if (getScrollRestorationKey) {
3047 let key = getScrollRestorationKey(
3048 location,
3049 matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))
3050 );
3051 return key || location.key;
3052 }
3053 return location.key;
3054 }
3055 function saveScrollPosition(location, matches) {
3056 if (savedScrollPositions && getScrollPosition) {
3057 let key = getScrollKey(location, matches);
3058 savedScrollPositions[key] = getScrollPosition();
3059 }
3060 }
3061 function getSavedScrollPosition(location, matches) {
3062 if (savedScrollPositions) {
3063 let key = getScrollKey(location, matches);
3064 let y = savedScrollPositions[key];
3065 if (typeof y === "number") {
3066 return y;
3067 }
3068 }
3069 return null;
3070 }
3071 function checkFogOfWar(matches, routesToUse, pathname) {
3072 if (init.patchRoutesOnNavigation) {
3073 if (!matches) {
3074 let fogMatches = matchRoutesImpl(
3075 routesToUse,
3076 pathname,
3077 basename,
3078 true
3079 );
3080 return { active: true, matches: fogMatches || [] };
3081 } else {
3082 if (Object.keys(matches[0].params).length > 0) {
3083 let partialMatches = matchRoutesImpl(
3084 routesToUse,
3085 pathname,
3086 basename,
3087 true
3088 );
3089 return { active: true, matches: partialMatches };
3090 }
3091 }
3092 }
3093 return { active: false, matches: null };
3094 }
3095 async function discoverRoutes(matches, pathname, signal, fetcherKey) {
3096 if (!init.patchRoutesOnNavigation) {
3097 return { type: "success", matches };
3098 }
3099 let partialMatches = matches;
3100 while (true) {
3101 let isNonHMR = inFlightDataRoutes == null;
3102 let routesToUse = inFlightDataRoutes || dataRoutes;
3103 let localManifest = manifest;
3104 try {
3105 await init.patchRoutesOnNavigation({
3106 signal,
3107 path: pathname,
3108 matches: partialMatches,
3109 fetcherKey,
3110 patch: (routeId, children) => {
3111 if (signal.aborted) return;
3112 patchRoutesImpl(
3113 routeId,
3114 children,
3115 routesToUse,
3116 localManifest,
3117 mapRouteProperties2,
3118 false
3119 );
3120 }
3121 });
3122 } catch (e) {
3123 return { type: "error", error: e, partialMatches };
3124 } finally {
3125 if (isNonHMR && !signal.aborted) {
3126 dataRoutes = [...dataRoutes];
3127 }
3128 }
3129 if (signal.aborted) {
3130 return { type: "aborted" };
3131 }
3132 let newMatches = matchRoutes(routesToUse, pathname, basename);
3133 let newPartialMatches = null;
3134 if (newMatches) {
3135 if (Object.keys(newMatches[0].params).length === 0) {
3136 return { type: "success", matches: newMatches };
3137 } else {
3138 newPartialMatches = matchRoutesImpl(
3139 routesToUse,
3140 pathname,
3141 basename,
3142 true
3143 );
3144 let matchedDeeper = newPartialMatches && partialMatches.length < newPartialMatches.length && compareMatches(
3145 partialMatches,
3146 newPartialMatches.slice(0, partialMatches.length)
3147 );
3148 if (!matchedDeeper) {
3149 return { type: "success", matches: newMatches };
3150 }
3151 }
3152 }
3153 if (!newPartialMatches) {
3154 newPartialMatches = matchRoutesImpl(
3155 routesToUse,
3156 pathname,
3157 basename,
3158 true
3159 );
3160 }
3161 if (!newPartialMatches || compareMatches(partialMatches, newPartialMatches)) {
3162 return { type: "success", matches: null };
3163 }
3164 partialMatches = newPartialMatches;
3165 }
3166 }
3167 function compareMatches(a, b) {
3168 return a.length === b.length && a.every((m, i) => m.route.id === b[i].route.id);
3169 }
3170 function _internalSetRoutes(newRoutes) {
3171 manifest = {};
3172 inFlightDataRoutes = convertRoutesToDataRoutes(
3173 newRoutes,
3174 mapRouteProperties2,
3175 void 0,
3176 manifest
3177 );
3178 }
3179 function patchRoutes(routeId, children, unstable_allowElementMutations = false) {
3180 let isNonHMR = inFlightDataRoutes == null;
3181 let routesToUse = inFlightDataRoutes || dataRoutes;
3182 patchRoutesImpl(
3183 routeId,
3184 children,
3185 routesToUse,
3186 manifest,
3187 mapRouteProperties2,
3188 unstable_allowElementMutations
3189 );
3190 if (isNonHMR) {
3191 dataRoutes = [...dataRoutes];
3192 updateState({});
3193 }
3194 }
3195 router = {
3196 get basename() {
3197 return basename;
3198 },
3199 get future() {
3200 return future;
3201 },
3202 get state() {
3203 return state;
3204 },
3205 get routes() {
3206 return dataRoutes;
3207 },
3208 get window() {
3209 return routerWindow;
3210 },
3211 initialize,
3212 subscribe,
3213 enableScrollRestoration,
3214 navigate,
3215 fetch: fetch2,
3216 revalidate,
3217 // Passthrough to history-aware createHref used by useHref so we get proper
3218 // hash-aware URLs in DOM paths
3219 createHref: (to) => init.history.createHref(to),
3220 encodeLocation: (to) => init.history.encodeLocation(to),
3221 getFetcher,
3222 resetFetcher,
3223 deleteFetcher: queueFetcherForDeletion,
3224 dispose,
3225 getBlocker,
3226 deleteBlocker,
3227 patchRoutes,
3228 _internalFetchControllers: fetchControllers,
3229 // TODO: Remove setRoutes, it's temporary to avoid dealing with
3230 // updating the tree while validating the update algorithm.
3231 _internalSetRoutes,
3232 _internalSetStateDoNotUseOrYouWillBreakYourApp(newState) {
3233 updateState(newState);
3234 }
3235 };
3236 if (init.unstable_instrumentations) {
3237 router = instrumentClientSideRouter(
3238 router,
3239 init.unstable_instrumentations.map((i) => i.router).filter(Boolean)
3240 );
3241 }
3242 return router;
3243}
3244function createStaticHandler(routes, opts) {
3245 invariant(
3246 routes.length > 0,
3247 "You must provide a non-empty routes array to createStaticHandler"
3248 );
3249 let manifest = {};
3250 let basename = (opts ? opts.basename : null) || "/";
3251 let _mapRouteProperties = _optionalChain([opts, 'optionalAccess', _29 => _29.mapRouteProperties]) || defaultMapRouteProperties;
3252 let mapRouteProperties2 = _mapRouteProperties;
3253 let future = {
3254 unstable_passThroughRequests: false,
3255 // unused in static handler
3256 ..._optionalChain([opts, 'optionalAccess', _30 => _30.future])
3257 };
3258 if (_optionalChain([opts, 'optionalAccess', _31 => _31.unstable_instrumentations])) {
3259 let instrumentations = opts.unstable_instrumentations;
3260 mapRouteProperties2 = (route) => {
3261 return {
3262 ..._mapRouteProperties(route),
3263 ...getRouteInstrumentationUpdates(
3264 instrumentations.map((i) => i.route).filter(Boolean),
3265 route
3266 )
3267 };
3268 };
3269 }
3270 let dataRoutes = convertRoutesToDataRoutes(
3271 routes,
3272 mapRouteProperties2,
3273 void 0,
3274 manifest
3275 );
3276 async function query(request, {
3277 requestContext,
3278 filterMatchesToLoad,
3279 skipLoaderErrorBubbling,
3280 skipRevalidation,
3281 dataStrategy,
3282 generateMiddlewareResponse,
3283 unstable_normalizePath
3284 } = {}) {
3285 let normalizePath = unstable_normalizePath || defaultNormalizePath;
3286 let method = request.method;
3287 let location = createLocation("", normalizePath(request), null, "default");
3288 let matches = matchRoutes(dataRoutes, location, basename);
3289 requestContext = requestContext != null ? requestContext : new RouterContextProvider();
3290 if (!isValidMethod(method) && method !== "HEAD") {
3291 let error = getInternalRouterError(405, { method });
3292 let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
3293 let staticContext = {
3294 basename,
3295 location,
3296 matches: methodNotAllowedMatches,
3297 loaderData: {},
3298 actionData: null,
3299 errors: {
3300 [route.id]: error
3301 },
3302 statusCode: error.status,
3303 loaderHeaders: {},
3304 actionHeaders: {}
3305 };
3306 return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
3307 } else if (!matches) {
3308 let error = getInternalRouterError(404, { pathname: location.pathname });
3309 let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
3310 let staticContext = {
3311 basename,
3312 location,
3313 matches: notFoundMatches,
3314 loaderData: {},
3315 actionData: null,
3316 errors: {
3317 [route.id]: error
3318 },
3319 statusCode: error.status,
3320 loaderHeaders: {},
3321 actionHeaders: {}
3322 };
3323 return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
3324 }
3325 if (generateMiddlewareResponse) {
3326 invariant(
3327 requestContext instanceof RouterContextProvider,
3328 "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `RouterContextProvider`"
3329 );
3330 try {
3331 await loadLazyMiddlewareForMatches(
3332 matches,
3333 manifest,
3334 mapRouteProperties2
3335 );
3336 let renderedStaticContext;
3337 let response = await runServerMiddlewarePipeline(
3338 {
3339 request,
3340 unstable_url: createDataFunctionUrl(request, location),
3341 unstable_pattern: getRoutePattern(matches),
3342 matches,
3343 params: matches[0].params,
3344 // If we're calling middleware then it must be enabled so we can cast
3345 // this to the proper type knowing it's not an `AppLoadContext`
3346 context: requestContext
3347 },
3348 async () => {
3349 let res = await generateMiddlewareResponse(
3350 async (revalidationRequest, opts2 = {}) => {
3351 let result2 = await queryImpl(
3352 revalidationRequest,
3353 location,
3354 matches,
3355 requestContext,
3356 dataStrategy || null,
3357 skipLoaderErrorBubbling === true,
3358 null,
3359 "filterMatchesToLoad" in opts2 ? _nullishCoalesce(opts2.filterMatchesToLoad, () => ( null)) : _nullishCoalesce(filterMatchesToLoad, () => ( null)),
3360 skipRevalidation === true
3361 );
3362 if (isResponse(result2)) {
3363 return result2;
3364 }
3365 renderedStaticContext = { location, basename, ...result2 };
3366 return renderedStaticContext;
3367 }
3368 );
3369 return res;
3370 },
3371 async (error, routeId) => {
3372 if (isRedirectResponse(error)) {
3373 return error;
3374 }
3375 if (isResponse(error)) {
3376 try {
3377 error = new ErrorResponseImpl(
3378 error.status,
3379 error.statusText,
3380 await parseResponseBody(error)
3381 );
3382 } catch (e) {
3383 error = e;
3384 }
3385 }
3386 if (isDataWithResponseInit(error)) {
3387 error = dataWithResponseInitToErrorResponse(error);
3388 }
3389 if (renderedStaticContext) {
3390 if (routeId in renderedStaticContext.loaderData) {
3391 renderedStaticContext.loaderData[routeId] = void 0;
3392 }
3393 let staticContext = getStaticContextFromError(
3394 dataRoutes,
3395 renderedStaticContext,
3396 error,
3397 skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id
3398 );
3399 return generateMiddlewareResponse(
3400 () => Promise.resolve(staticContext)
3401 );
3402 } else {
3403 let boundaryRouteId = skipLoaderErrorBubbling ? routeId : findNearestBoundary(
3404 matches,
3405 _optionalChain([matches, 'access', _32 => _32.find, 'call', _33 => _33(
3406 (m) => m.route.id === routeId || m.route.loader
3407 ), 'optionalAccess', _34 => _34.route, 'access', _35 => _35.id]) || routeId
3408 ).route.id;
3409 let staticContext = {
3410 matches,
3411 location,
3412 basename,
3413 loaderData: {},
3414 actionData: null,
3415 errors: {
3416 [boundaryRouteId]: error
3417 },
3418 statusCode: isRouteErrorResponse(error) ? error.status : 500,
3419 actionHeaders: {},
3420 loaderHeaders: {}
3421 };
3422 return generateMiddlewareResponse(
3423 () => Promise.resolve(staticContext)
3424 );
3425 }
3426 }
3427 );
3428 invariant(isResponse(response), "Expected a response in query()");
3429 return response;
3430 } catch (e) {
3431 if (isResponse(e)) {
3432 return e;
3433 }
3434 throw e;
3435 }
3436 }
3437 let result = await queryImpl(
3438 request,
3439 location,
3440 matches,
3441 requestContext,
3442 dataStrategy || null,
3443 skipLoaderErrorBubbling === true,
3444 null,
3445 filterMatchesToLoad || null,
3446 skipRevalidation === true
3447 );
3448 if (isResponse(result)) {
3449 return result;
3450 }
3451 return { location, basename, ...result };
3452 }
3453 async function queryRoute(request, {
3454 routeId,
3455 requestContext,
3456 dataStrategy,
3457 generateMiddlewareResponse,
3458 unstable_normalizePath
3459 } = {}) {
3460 let normalizePath = unstable_normalizePath || defaultNormalizePath;
3461 let method = request.method;
3462 let location = createLocation("", normalizePath(request), null, "default");
3463 let matches = matchRoutes(dataRoutes, location, basename);
3464 requestContext = requestContext != null ? requestContext : new RouterContextProvider();
3465 if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
3466 throw getInternalRouterError(405, { method });
3467 } else if (!matches) {
3468 throw getInternalRouterError(404, { pathname: location.pathname });
3469 }
3470 let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
3471 if (routeId && !match) {
3472 throw getInternalRouterError(403, {
3473 pathname: location.pathname,
3474 routeId
3475 });
3476 } else if (!match) {
3477 throw getInternalRouterError(404, { pathname: location.pathname });
3478 }
3479 if (generateMiddlewareResponse) {
3480 invariant(
3481 requestContext instanceof RouterContextProvider,
3482 "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `RouterContextProvider`"
3483 );
3484 await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties2);
3485 let response = await runServerMiddlewarePipeline(
3486 {
3487 request,
3488 unstable_url: createDataFunctionUrl(request, location),
3489 unstable_pattern: getRoutePattern(matches),
3490 matches,
3491 params: matches[0].params,
3492 // If we're calling middleware then it must be enabled so we can cast
3493 // this to the proper type knowing it's not an `AppLoadContext`
3494 context: requestContext
3495 },
3496 async () => {
3497 let res = await generateMiddlewareResponse(
3498 async (innerRequest) => {
3499 let result2 = await queryImpl(
3500 innerRequest,
3501 location,
3502 matches,
3503 requestContext,
3504 dataStrategy || null,
3505 false,
3506 match,
3507 null,
3508 false
3509 );
3510 let processed = handleQueryResult(result2);
3511 return isResponse(processed) ? processed : typeof processed === "string" ? new Response(processed) : Response.json(processed);
3512 }
3513 );
3514 return res;
3515 },
3516 (error) => {
3517 if (isDataWithResponseInit(error)) {
3518 return Promise.resolve(dataWithResponseInitToResponse(error));
3519 }
3520 if (isResponse(error)) {
3521 return Promise.resolve(error);
3522 }
3523 throw error;
3524 }
3525 );
3526 return response;
3527 }
3528 let result = await queryImpl(
3529 request,
3530 location,
3531 matches,
3532 requestContext,
3533 dataStrategy || null,
3534 false,
3535 match,
3536 null,
3537 false
3538 );
3539 return handleQueryResult(result);
3540 function handleQueryResult(result2) {
3541 if (isResponse(result2)) {
3542 return result2;
3543 }
3544 let error = result2.errors ? Object.values(result2.errors)[0] : void 0;
3545 if (error !== void 0) {
3546 throw error;
3547 }
3548 if (result2.actionData) {
3549 return Object.values(result2.actionData)[0];
3550 }
3551 if (result2.loaderData) {
3552 return Object.values(result2.loaderData)[0];
3553 }
3554 return void 0;
3555 }
3556 }
3557 async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
3558 invariant(
3559 request.signal,
3560 "query()/queryRoute() requests must contain an AbortController signal"
3561 );
3562 try {
3563 if (isMutationMethod(request.method)) {
3564 let result2 = await submit(
3565 request,
3566 location,
3567 matches,
3568 routeMatch || getTargetMatch(matches, location),
3569 requestContext,
3570 dataStrategy,
3571 skipLoaderErrorBubbling,
3572 routeMatch != null,
3573 filterMatchesToLoad,
3574 skipRevalidation
3575 );
3576 return result2;
3577 }
3578 let result = await loadRouteData(
3579 request,
3580 location,
3581 matches,
3582 requestContext,
3583 dataStrategy,
3584 skipLoaderErrorBubbling,
3585 routeMatch,
3586 filterMatchesToLoad
3587 );
3588 return isResponse(result) ? result : {
3589 ...result,
3590 actionData: null,
3591 actionHeaders: {}
3592 };
3593 } catch (e) {
3594 if (isDataStrategyResult(e) && isResponse(e.result)) {
3595 if (e.type === "error" /* error */) {
3596 throw e.result;
3597 }
3598 return e.result;
3599 }
3600 if (isRedirectResponse(e)) {
3601 return e;
3602 }
3603 throw e;
3604 }
3605 }
3606 async function submit(request, location, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
3607 let result;
3608 if (!actionMatch.route.action && !actionMatch.route.lazy) {
3609 let error = getInternalRouterError(405, {
3610 method: request.method,
3611 pathname: new URL(request.url).pathname,
3612 routeId: actionMatch.route.id
3613 });
3614 if (isRouteRequest) {
3615 throw error;
3616 }
3617 result = {
3618 type: "error" /* error */,
3619 error
3620 };
3621 } else {
3622 let dsMatches = getTargetedDataStrategyMatches(
3623 mapRouteProperties2,
3624 manifest,
3625 request,
3626 location,
3627 matches,
3628 actionMatch,
3629 [],
3630 requestContext
3631 );
3632 let results = await callDataStrategy(
3633 request,
3634 location,
3635 dsMatches,
3636 isRouteRequest,
3637 requestContext,
3638 dataStrategy
3639 );
3640 result = results[actionMatch.route.id];
3641 if (request.signal.aborted) {
3642 throwStaticHandlerAbortedError(request, isRouteRequest);
3643 }
3644 }
3645 if (isRedirectResult(result)) {
3646 throw new Response(null, {
3647 status: result.response.status,
3648 headers: {
3649 Location: result.response.headers.get("Location")
3650 }
3651 });
3652 }
3653 if (isRouteRequest) {
3654 if (isErrorResult(result)) {
3655 throw result.error;
3656 }
3657 return {
3658 matches: [actionMatch],
3659 loaderData: {},
3660 actionData: { [actionMatch.route.id]: result.data },
3661 errors: null,
3662 // Note: statusCode + headers are unused here since queryRoute will
3663 // return the raw Response or value
3664 statusCode: 200,
3665 loaderHeaders: {},
3666 actionHeaders: {}
3667 };
3668 }
3669 if (skipRevalidation) {
3670 if (isErrorResult(result)) {
3671 let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
3672 return {
3673 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
3674 actionData: null,
3675 actionHeaders: {
3676 ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
3677 },
3678 matches,
3679 loaderData: {},
3680 errors: {
3681 [boundaryMatch.route.id]: result.error
3682 },
3683 loaderHeaders: {}
3684 };
3685 } else {
3686 return {
3687 actionData: {
3688 [actionMatch.route.id]: result.data
3689 },
3690 actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
3691 matches,
3692 loaderData: {},
3693 errors: null,
3694 statusCode: result.statusCode || 200,
3695 loaderHeaders: {}
3696 };
3697 }
3698 }
3699 let loaderRequest = new Request(request.url, {
3700 headers: request.headers,
3701 redirect: request.redirect,
3702 signal: request.signal
3703 });
3704 if (isErrorResult(result)) {
3705 let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
3706 let handlerContext2 = await loadRouteData(
3707 loaderRequest,
3708 location,
3709 matches,
3710 requestContext,
3711 dataStrategy,
3712 skipLoaderErrorBubbling,
3713 null,
3714 filterMatchesToLoad,
3715 [boundaryMatch.route.id, result]
3716 );
3717 return {
3718 ...handlerContext2,
3719 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
3720 actionData: null,
3721 actionHeaders: {
3722 ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
3723 }
3724 };
3725 }
3726 let handlerContext = await loadRouteData(
3727 loaderRequest,
3728 location,
3729 matches,
3730 requestContext,
3731 dataStrategy,
3732 skipLoaderErrorBubbling,
3733 null,
3734 filterMatchesToLoad
3735 );
3736 return {
3737 ...handlerContext,
3738 actionData: {
3739 [actionMatch.route.id]: result.data
3740 },
3741 // action status codes take precedence over loader status codes
3742 ...result.statusCode ? { statusCode: result.statusCode } : {},
3743 actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
3744 };
3745 }
3746 async function loadRouteData(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
3747 let isRouteRequest = routeMatch != null;
3748 if (isRouteRequest && !_optionalChain([routeMatch, 'optionalAccess', _36 => _36.route, 'access', _37 => _37.loader]) && !_optionalChain([routeMatch, 'optionalAccess', _38 => _38.route, 'access', _39 => _39.lazy])) {
3749 throw getInternalRouterError(400, {
3750 method: request.method,
3751 pathname: new URL(request.url).pathname,
3752 routeId: _optionalChain([routeMatch, 'optionalAccess', _40 => _40.route, 'access', _41 => _41.id])
3753 });
3754 }
3755 let dsMatches;
3756 if (routeMatch) {
3757 dsMatches = getTargetedDataStrategyMatches(
3758 mapRouteProperties2,
3759 manifest,
3760 request,
3761 location,
3762 matches,
3763 routeMatch,
3764 [],
3765 requestContext
3766 );
3767 } else {
3768 let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? (
3769 // Up to but not including the boundary
3770 matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1
3771 ) : void 0;
3772 let pattern = getRoutePattern(matches);
3773 dsMatches = matches.map((match, index) => {
3774 if (maxIdx != null && index > maxIdx) {
3775 return getDataStrategyMatch(
3776 mapRouteProperties2,
3777 manifest,
3778 request,
3779 location,
3780 pattern,
3781 match,
3782 [],
3783 requestContext,
3784 false
3785 );
3786 }
3787 return getDataStrategyMatch(
3788 mapRouteProperties2,
3789 manifest,
3790 request,
3791 location,
3792 pattern,
3793 match,
3794 [],
3795 requestContext,
3796 (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match))
3797 );
3798 });
3799 }
3800 if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) {
3801 return {
3802 matches,
3803 loaderData: {},
3804 errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
3805 [pendingActionResult[0]]: pendingActionResult[1].error
3806 } : null,
3807 statusCode: 200,
3808 loaderHeaders: {}
3809 };
3810 }
3811 let results = await callDataStrategy(
3812 request,
3813 location,
3814 dsMatches,
3815 isRouteRequest,
3816 requestContext,
3817 dataStrategy
3818 );
3819 if (request.signal.aborted) {
3820 throwStaticHandlerAbortedError(request, isRouteRequest);
3821 }
3822 let handlerContext = processRouteLoaderData(
3823 matches,
3824 results,
3825 pendingActionResult,
3826 true,
3827 skipLoaderErrorBubbling
3828 );
3829 return {
3830 ...handlerContext,
3831 matches
3832 };
3833 }
3834 async function callDataStrategy(request, location, matches, isRouteRequest, requestContext, dataStrategy) {
3835 let results = await callDataStrategyImpl(
3836 dataStrategy || defaultDataStrategy,
3837 request,
3838 location,
3839 matches,
3840 null,
3841 requestContext,
3842 true
3843 );
3844 let dataResults = {};
3845 await Promise.all(
3846 matches.map(async (match) => {
3847 if (!(match.route.id in results)) {
3848 return;
3849 }
3850 let result = results[match.route.id];
3851 if (isRedirectDataStrategyResult(result)) {
3852 let response = result.result;
3853 throw normalizeRelativeRoutingRedirectResponse(
3854 response,
3855 request,
3856 match.route.id,
3857 matches,
3858 basename
3859 );
3860 }
3861 if (isRouteRequest) {
3862 if (isResponse(result.result)) {
3863 throw result;
3864 } else if (isDataWithResponseInit(result.result)) {
3865 throw dataWithResponseInitToResponse(result.result);
3866 }
3867 }
3868 dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
3869 })
3870 );
3871 return dataResults;
3872 }
3873 return {
3874 dataRoutes,
3875 query,
3876 queryRoute
3877 };
3878}
3879function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
3880 let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
3881 return {
3882 ...handlerContext,
3883 statusCode: isRouteErrorResponse(error) ? error.status : 500,
3884 errors: {
3885 [errorBoundaryId]: error
3886 }
3887 };
3888}
3889function throwStaticHandlerAbortedError(request, isRouteRequest) {
3890 if (request.signal.reason !== void 0) {
3891 throw request.signal.reason;
3892 }
3893 let method = isRouteRequest ? "queryRoute" : "query";
3894 throw new Error(
3895 `${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
3896 );
3897}
3898function isSubmissionNavigation(opts) {
3899 return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== void 0);
3900}
3901function defaultNormalizePath(request) {
3902 let url = new URL(request.url);
3903 return {
3904 pathname: url.pathname,
3905 search: url.search,
3906 hash: url.hash
3907 };
3908}
3909function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
3910 let contextualMatches;
3911 let activeRouteMatch;
3912 if (fromRouteId) {
3913 contextualMatches = [];
3914 for (let match of matches) {
3915 contextualMatches.push(match);
3916 if (match.route.id === fromRouteId) {
3917 activeRouteMatch = match;
3918 break;
3919 }
3920 }
3921 } else {
3922 contextualMatches = matches;
3923 activeRouteMatch = matches[matches.length - 1];
3924 }
3925 let path = resolveTo(
3926 to ? to : ".",
3927 getResolveToMatches(contextualMatches),
3928 stripBasename(location.pathname, basename) || location.pathname,
3929 relative === "path"
3930 );
3931 if (to == null) {
3932 path.search = location.search;
3933 path.hash = location.hash;
3934 }
3935 if ((to == null || to === "" || to === ".") && activeRouteMatch) {
3936 let nakedIndex = hasNakedIndexQuery(path.search);
3937 if (activeRouteMatch.route.index && !nakedIndex) {
3938 path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
3939 } else if (!activeRouteMatch.route.index && nakedIndex) {
3940 let params = new URLSearchParams(path.search);
3941 let indexValues = params.getAll("index");
3942 params.delete("index");
3943 indexValues.filter((v) => v).forEach((v) => params.append("index", v));
3944 let qs = params.toString();
3945 path.search = qs ? `?${qs}` : "";
3946 }
3947 }
3948 if (basename !== "/") {
3949 path.pathname = prependBasename({ basename, pathname: path.pathname });
3950 }
3951 return createPath(path);
3952}
3953function normalizeNavigateOptions(isFetcher, path, opts) {
3954 if (!opts || !isSubmissionNavigation(opts)) {
3955 return { path };
3956 }
3957 if (opts.formMethod && !isValidMethod(opts.formMethod)) {
3958 return {
3959 path,
3960 error: getInternalRouterError(405, { method: opts.formMethod })
3961 };
3962 }
3963 let getInvalidBodyError = () => ({
3964 path,
3965 error: getInternalRouterError(400, { type: "invalid-body" })
3966 });
3967 let rawFormMethod = opts.formMethod || "get";
3968 let formMethod = rawFormMethod.toUpperCase();
3969 let formAction = stripHashFromPath(path);
3970 if (opts.body !== void 0) {
3971 if (opts.formEncType === "text/plain") {
3972 if (!isMutationMethod(formMethod)) {
3973 return getInvalidBodyError();
3974 }
3975 let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? (
3976 // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
3977 Array.from(opts.body.entries()).reduce(
3978 (acc, [name, value]) => `${acc}${name}=${value}
3979`,
3980 ""
3981 )
3982 ) : String(opts.body);
3983 return {
3984 path,
3985 submission: {
3986 formMethod,
3987 formAction,
3988 formEncType: opts.formEncType,
3989 formData: void 0,
3990 json: void 0,
3991 text
3992 }
3993 };
3994 } else if (opts.formEncType === "application/json") {
3995 if (!isMutationMethod(formMethod)) {
3996 return getInvalidBodyError();
3997 }
3998 try {
3999 let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
4000 return {
4001 path,
4002 submission: {
4003 formMethod,
4004 formAction,
4005 formEncType: opts.formEncType,
4006 formData: void 0,
4007 json,
4008 text: void 0
4009 }
4010 };
4011 } catch (e) {
4012 return getInvalidBodyError();
4013 }
4014 }
4015 }
4016 invariant(
4017 typeof FormData === "function",
4018 "FormData is not available in this environment"
4019 );
4020 let searchParams;
4021 let formData;
4022 if (opts.formData) {
4023 searchParams = convertFormDataToSearchParams(opts.formData);
4024 formData = opts.formData;
4025 } else if (opts.body instanceof FormData) {
4026 searchParams = convertFormDataToSearchParams(opts.body);
4027 formData = opts.body;
4028 } else if (opts.body instanceof URLSearchParams) {
4029 searchParams = opts.body;
4030 formData = convertSearchParamsToFormData(searchParams);
4031 } else if (opts.body == null) {
4032 searchParams = new URLSearchParams();
4033 formData = new FormData();
4034 } else {
4035 try {
4036 searchParams = new URLSearchParams(opts.body);
4037 formData = convertSearchParamsToFormData(searchParams);
4038 } catch (e) {
4039 return getInvalidBodyError();
4040 }
4041 }
4042 let submission = {
4043 formMethod,
4044 formAction,
4045 formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
4046 formData,
4047 json: void 0,
4048 text: void 0
4049 };
4050 if (isMutationMethod(submission.formMethod)) {
4051 return { path, submission };
4052 }
4053 let parsedPath = parsePath(path);
4054 if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
4055 searchParams.append("index", "");
4056 }
4057 parsedPath.search = `?${searchParams}`;
4058 return { path: createPath(parsedPath), submission };
4059}
4060function getMatchesToLoad(request, scopedContext, mapRouteProperties2, manifest, history, state, matches, submission, location, lazyRoutePropertiesToSkip, initialHydration, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, hasPatchRoutesOnNavigation, pendingActionResult, callSiteDefaultShouldRevalidate) {
4061 let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : void 0;
4062 let currentUrl = history.createURL(state.location);
4063 let nextUrl = history.createURL(location);
4064 let maxIdx;
4065 if (initialHydration && state.errors) {
4066 let boundaryId = Object.keys(state.errors)[0];
4067 maxIdx = matches.findIndex((m) => m.route.id === boundaryId);
4068 } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
4069 let boundaryId = pendingActionResult[0];
4070 maxIdx = matches.findIndex((m) => m.route.id === boundaryId) - 1;
4071 }
4072 let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : void 0;
4073 let shouldSkipRevalidation = actionStatus && actionStatus >= 400;
4074 let baseShouldRevalidateArgs = {
4075 currentUrl,
4076 currentParams: _optionalChain([state, 'access', _42 => _42.matches, 'access', _43 => _43[0], 'optionalAccess', _44 => _44.params]) || {},
4077 nextUrl,
4078 nextParams: matches[0].params,
4079 ...submission,
4080 actionResult,
4081 actionStatus
4082 };
4083 let pattern = getRoutePattern(matches);
4084 let dsMatches = matches.map((match, index) => {
4085 let { route } = match;
4086 let forceShouldLoad = null;
4087 if (maxIdx != null && index > maxIdx) {
4088 forceShouldLoad = false;
4089 } else if (route.lazy) {
4090 forceShouldLoad = true;
4091 } else if (!routeHasLoaderOrMiddleware(route)) {
4092 forceShouldLoad = false;
4093 } else if (initialHydration) {
4094 let { shouldLoad: shouldLoad2 } = getRouteHydrationStatus(
4095 route,
4096 state.loaderData,
4097 state.errors
4098 );
4099 forceShouldLoad = shouldLoad2;
4100 } else if (isNewLoader(state.loaderData, state.matches[index], match)) {
4101 forceShouldLoad = true;
4102 }
4103 if (forceShouldLoad !== null) {
4104 return getDataStrategyMatch(
4105 mapRouteProperties2,
4106 manifest,
4107 request,
4108 location,
4109 pattern,
4110 match,
4111 lazyRoutePropertiesToSkip,
4112 scopedContext,
4113 forceShouldLoad
4114 );
4115 }
4116 let defaultShouldRevalidate = false;
4117 if (typeof callSiteDefaultShouldRevalidate === "boolean") {
4118 defaultShouldRevalidate = callSiteDefaultShouldRevalidate;
4119 } else if (shouldSkipRevalidation) {
4120 defaultShouldRevalidate = false;
4121 } else if (isRevalidationRequired) {
4122 defaultShouldRevalidate = true;
4123 } else if (currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search) {
4124 defaultShouldRevalidate = true;
4125 } else if (currentUrl.search !== nextUrl.search) {
4126 defaultShouldRevalidate = true;
4127 } else if (isNewRouteInstance(state.matches[index], match)) {
4128 defaultShouldRevalidate = true;
4129 }
4130 let shouldRevalidateArgs = {
4131 ...baseShouldRevalidateArgs,
4132 defaultShouldRevalidate
4133 };
4134 let shouldLoad = shouldRevalidateLoader(match, shouldRevalidateArgs);
4135 return getDataStrategyMatch(
4136 mapRouteProperties2,
4137 manifest,
4138 request,
4139 location,
4140 pattern,
4141 match,
4142 lazyRoutePropertiesToSkip,
4143 scopedContext,
4144 shouldLoad,
4145 shouldRevalidateArgs,
4146 callSiteDefaultShouldRevalidate
4147 );
4148 });
4149 let revalidatingFetchers = [];
4150 fetchLoadMatches.forEach((f, key) => {
4151 if (initialHydration || !matches.some((m) => m.route.id === f.routeId) || fetchersQueuedForDeletion.has(key)) {
4152 return;
4153 }
4154 let fetcher = state.fetchers.get(key);
4155 let isMidInitialLoad = fetcher && fetcher.state !== "idle" && fetcher.data === void 0;
4156 let fetcherMatches = matchRoutes(routesToUse, f.path, basename);
4157 if (!fetcherMatches) {
4158 if (hasPatchRoutesOnNavigation && isMidInitialLoad) {
4159 return;
4160 }
4161 revalidatingFetchers.push({
4162 key,
4163 routeId: f.routeId,
4164 path: f.path,
4165 matches: null,
4166 match: null,
4167 request: null,
4168 controller: null
4169 });
4170 return;
4171 }
4172 if (fetchRedirectIds.has(key)) {
4173 return;
4174 }
4175 let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
4176 let fetchController = new AbortController();
4177 let fetchRequest = createClientSideRequest(
4178 history,
4179 f.path,
4180 fetchController.signal
4181 );
4182 let fetcherDsMatches = null;
4183 if (cancelledFetcherLoads.has(key)) {
4184 cancelledFetcherLoads.delete(key);
4185 fetcherDsMatches = getTargetedDataStrategyMatches(
4186 mapRouteProperties2,
4187 manifest,
4188 fetchRequest,
4189 f.path,
4190 fetcherMatches,
4191 fetcherMatch,
4192 lazyRoutePropertiesToSkip,
4193 scopedContext
4194 );
4195 } else if (isMidInitialLoad) {
4196 if (isRevalidationRequired) {
4197 fetcherDsMatches = getTargetedDataStrategyMatches(
4198 mapRouteProperties2,
4199 manifest,
4200 fetchRequest,
4201 f.path,
4202 fetcherMatches,
4203 fetcherMatch,
4204 lazyRoutePropertiesToSkip,
4205 scopedContext
4206 );
4207 }
4208 } else {
4209 let defaultShouldRevalidate;
4210 if (typeof callSiteDefaultShouldRevalidate === "boolean") {
4211 defaultShouldRevalidate = callSiteDefaultShouldRevalidate;
4212 } else if (shouldSkipRevalidation) {
4213 defaultShouldRevalidate = false;
4214 } else {
4215 defaultShouldRevalidate = isRevalidationRequired;
4216 }
4217 let shouldRevalidateArgs = {
4218 ...baseShouldRevalidateArgs,
4219 defaultShouldRevalidate
4220 };
4221 if (shouldRevalidateLoader(fetcherMatch, shouldRevalidateArgs)) {
4222 fetcherDsMatches = getTargetedDataStrategyMatches(
4223 mapRouteProperties2,
4224 manifest,
4225 fetchRequest,
4226 f.path,
4227 fetcherMatches,
4228 fetcherMatch,
4229 lazyRoutePropertiesToSkip,
4230 scopedContext,
4231 shouldRevalidateArgs
4232 );
4233 }
4234 }
4235 if (fetcherDsMatches) {
4236 revalidatingFetchers.push({
4237 key,
4238 routeId: f.routeId,
4239 path: f.path,
4240 matches: fetcherDsMatches,
4241 match: fetcherMatch,
4242 request: fetchRequest,
4243 controller: fetchController
4244 });
4245 }
4246 });
4247 return { dsMatches, revalidatingFetchers };
4248}
4249function routeHasLoaderOrMiddleware(route) {
4250 return route.loader != null || route.middleware != null && route.middleware.length > 0;
4251}
4252function getRouteHydrationStatus(route, loaderData, errors) {
4253 if (route.lazy) {
4254 return { shouldLoad: true, renderFallback: true };
4255 }
4256 if (!routeHasLoaderOrMiddleware(route)) {
4257 return { shouldLoad: false, renderFallback: false };
4258 }
4259 let hasData = loaderData != null && route.id in loaderData;
4260 let hasError = errors != null && errors[route.id] !== void 0;
4261 if (!hasData && hasError) {
4262 return { shouldLoad: false, renderFallback: false };
4263 }
4264 if (typeof route.loader === "function" && route.loader.hydrate === true) {
4265 return { shouldLoad: true, renderFallback: !hasData };
4266 }
4267 let shouldLoad = !hasData && !hasError;
4268 return { shouldLoad, renderFallback: shouldLoad };
4269}
4270function isNewLoader(currentLoaderData, currentMatch, match) {
4271 let isNew = (
4272 // [a] -> [a, b]
4273 !currentMatch || // [a, b] -> [a, c]
4274 match.route.id !== currentMatch.route.id
4275 );
4276 let isMissingData = !currentLoaderData.hasOwnProperty(match.route.id);
4277 return isNew || isMissingData;
4278}
4279function isNewRouteInstance(currentMatch, match) {
4280 let currentPath = currentMatch.route.path;
4281 return (
4282 // param change for this match, /users/123 -> /users/456
4283 currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path
4284 // e.g. /files/images/avatar.jpg -> files/finances.xls
4285 currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
4286 );
4287}
4288function shouldRevalidateLoader(loaderMatch, arg) {
4289 if (loaderMatch.route.shouldRevalidate) {
4290 let routeChoice = loaderMatch.route.shouldRevalidate(arg);
4291 if (typeof routeChoice === "boolean") {
4292 return routeChoice;
4293 }
4294 }
4295 return arg.defaultShouldRevalidate;
4296}
4297function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties2, allowElementMutations) {
4298 let childrenToPatch;
4299 if (routeId) {
4300 let route = manifest[routeId];
4301 invariant(
4302 route,
4303 `No route found to patch children into: routeId = ${routeId}`
4304 );
4305 if (!route.children) {
4306 route.children = [];
4307 }
4308 childrenToPatch = route.children;
4309 } else {
4310 childrenToPatch = routesToUse;
4311 }
4312 let uniqueChildren = [];
4313 let existingChildren = [];
4314 children.forEach((newRoute) => {
4315 let existingRoute = childrenToPatch.find(
4316 (existingRoute2) => isSameRoute(newRoute, existingRoute2)
4317 );
4318 if (existingRoute) {
4319 existingChildren.push({ existingRoute, newRoute });
4320 } else {
4321 uniqueChildren.push(newRoute);
4322 }
4323 });
4324 if (uniqueChildren.length > 0) {
4325 let newRoutes = convertRoutesToDataRoutes(
4326 uniqueChildren,
4327 mapRouteProperties2,
4328 [routeId || "_", "patch", String(_optionalChain([childrenToPatch, 'optionalAccess', _45 => _45.length]) || "0")],
4329 manifest
4330 );
4331 childrenToPatch.push(...newRoutes);
4332 }
4333 if (allowElementMutations && existingChildren.length > 0) {
4334 for (let i = 0; i < existingChildren.length; i++) {
4335 let { existingRoute, newRoute } = existingChildren[i];
4336 let existingRouteTyped = existingRoute;
4337 let [newRouteTyped] = convertRoutesToDataRoutes(
4338 [newRoute],
4339 mapRouteProperties2,
4340 [],
4341 // Doesn't matter for mutated routes since they already have an id
4342 {},
4343 // Don't touch the manifest here since we're updating in place
4344 true
4345 );
4346 Object.assign(existingRouteTyped, {
4347 element: newRouteTyped.element ? newRouteTyped.element : existingRouteTyped.element,
4348 errorElement: newRouteTyped.errorElement ? newRouteTyped.errorElement : existingRouteTyped.errorElement,
4349 hydrateFallbackElement: newRouteTyped.hydrateFallbackElement ? newRouteTyped.hydrateFallbackElement : existingRouteTyped.hydrateFallbackElement
4350 });
4351 }
4352 }
4353}
4354function isSameRoute(newRoute, existingRoute) {
4355 if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
4356 return true;
4357 }
4358 if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
4359 return false;
4360 }
4361 if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
4362 return true;
4363 }
4364 return _nullishCoalesce(_optionalChain([newRoute, 'access', _46 => _46.children, 'optionalAccess', _47 => _47.every, 'call', _48 => _48(
4365 (aChild, i) => _optionalChain([existingRoute, 'access', _49 => _49.children, 'optionalAccess', _50 => _50.some, 'call', _51 => _51((bChild) => isSameRoute(aChild, bChild))])
4366 )]), () => ( false));
4367}
4368var lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
4369var loadLazyRouteProperty = ({
4370 key,
4371 route,
4372 manifest,
4373 mapRouteProperties: mapRouteProperties2
4374}) => {
4375 let routeToUpdate = manifest[route.id];
4376 invariant(routeToUpdate, "No route found in manifest");
4377 if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") {
4378 return;
4379 }
4380 let lazyFn = routeToUpdate.lazy[key];
4381 if (!lazyFn) {
4382 return;
4383 }
4384 let cache = lazyRoutePropertyCache.get(routeToUpdate);
4385 if (!cache) {
4386 cache = {};
4387 lazyRoutePropertyCache.set(routeToUpdate, cache);
4388 }
4389 let cachedPromise = cache[key];
4390 if (cachedPromise) {
4391 return cachedPromise;
4392 }
4393 let propertyPromise = (async () => {
4394 let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
4395 let staticRouteValue = routeToUpdate[key];
4396 let isStaticallyDefined = staticRouteValue !== void 0 && key !== "hasErrorBoundary";
4397 if (isUnsupported) {
4398 warning(
4399 !isUnsupported,
4400 "Route property " + key + " is not a supported lazy route property. This property will be ignored."
4401 );
4402 cache[key] = Promise.resolve();
4403 } else if (isStaticallyDefined) {
4404 warning(
4405 false,
4406 `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`
4407 );
4408 } else {
4409 let value = await lazyFn();
4410 if (value != null) {
4411 Object.assign(routeToUpdate, { [key]: value });
4412 Object.assign(routeToUpdate, mapRouteProperties2(routeToUpdate));
4413 }
4414 }
4415 if (typeof routeToUpdate.lazy === "object") {
4416 routeToUpdate.lazy[key] = void 0;
4417 if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) {
4418 routeToUpdate.lazy = void 0;
4419 }
4420 }
4421 })();
4422 cache[key] = propertyPromise;
4423 return propertyPromise;
4424};
4425var lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
4426function loadLazyRoute(route, type, manifest, mapRouteProperties2, lazyRoutePropertiesToSkip) {
4427 let routeToUpdate = manifest[route.id];
4428 invariant(routeToUpdate, "No route found in manifest");
4429 if (!route.lazy) {
4430 return {
4431 lazyRoutePromise: void 0,
4432 lazyHandlerPromise: void 0
4433 };
4434 }
4435 if (typeof route.lazy === "function") {
4436 let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
4437 if (cachedPromise) {
4438 return {
4439 lazyRoutePromise: cachedPromise,
4440 lazyHandlerPromise: cachedPromise
4441 };
4442 }
4443 let lazyRoutePromise2 = (async () => {
4444 invariant(
4445 typeof route.lazy === "function",
4446 "No lazy route function found"
4447 );
4448 let lazyRoute = await route.lazy();
4449 let routeUpdates = {};
4450 for (let lazyRouteProperty in lazyRoute) {
4451 let lazyValue = lazyRoute[lazyRouteProperty];
4452 if (lazyValue === void 0) {
4453 continue;
4454 }
4455 let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
4456 let staticRouteValue = routeToUpdate[lazyRouteProperty];
4457 let isStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
4458 // on the route updates
4459 lazyRouteProperty !== "hasErrorBoundary";
4460 if (isUnsupported) {
4461 warning(
4462 !isUnsupported,
4463 "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored."
4464 );
4465 } else if (isStaticallyDefined) {
4466 warning(
4467 !isStaticallyDefined,
4468 `Route "${routeToUpdate.id}" has a static property "${lazyRouteProperty}" defined but its lazy function is also returning a value for this property. The lazy route property "${lazyRouteProperty}" will be ignored.`
4469 );
4470 } else {
4471 routeUpdates[lazyRouteProperty] = lazyValue;
4472 }
4473 }
4474 Object.assign(routeToUpdate, routeUpdates);
4475 Object.assign(routeToUpdate, {
4476 // To keep things framework agnostic, we use the provided `mapRouteProperties`
4477 // function to set the framework-aware properties (`element`/`hasErrorBoundary`)
4478 // since the logic will differ between frameworks.
4479 ...mapRouteProperties2(routeToUpdate),
4480 lazy: void 0
4481 });
4482 })();
4483 lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise2);
4484 lazyRoutePromise2.catch(() => {
4485 });
4486 return {
4487 lazyRoutePromise: lazyRoutePromise2,
4488 lazyHandlerPromise: lazyRoutePromise2
4489 };
4490 }
4491 let lazyKeys = Object.keys(route.lazy);
4492 let lazyPropertyPromises = [];
4493 let lazyHandlerPromise = void 0;
4494 for (let key of lazyKeys) {
4495 if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) {
4496 continue;
4497 }
4498 let promise = loadLazyRouteProperty({
4499 key,
4500 route,
4501 manifest,
4502 mapRouteProperties: mapRouteProperties2
4503 });
4504 if (promise) {
4505 lazyPropertyPromises.push(promise);
4506 if (key === type) {
4507 lazyHandlerPromise = promise;
4508 }
4509 }
4510 }
4511 let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {
4512 }) : void 0;
4513 _optionalChain([lazyRoutePromise, 'optionalAccess', _52 => _52.catch, 'call', _53 => _53(() => {
4514 })]);
4515 _optionalChain([lazyHandlerPromise, 'optionalAccess', _54 => _54.catch, 'call', _55 => _55(() => {
4516 })]);
4517 return {
4518 lazyRoutePromise,
4519 lazyHandlerPromise
4520 };
4521}
4522function isNonNullable(value) {
4523 return value !== void 0;
4524}
4525function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties2) {
4526 let promises = matches.map(({ route }) => {
4527 if (typeof route.lazy !== "object" || !route.lazy.middleware) {
4528 return void 0;
4529 }
4530 return loadLazyRouteProperty({
4531 key: "middleware",
4532 route,
4533 manifest,
4534 mapRouteProperties: mapRouteProperties2
4535 });
4536 }).filter(isNonNullable);
4537 return promises.length > 0 ? Promise.all(promises) : void 0;
4538}
4539async function defaultDataStrategy(args) {
4540 let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
4541 let keyedResults = {};
4542 let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
4543 results.forEach((result, i) => {
4544 keyedResults[matchesToLoad[i].route.id] = result;
4545 });
4546 return keyedResults;
4547}
4548async function defaultDataStrategyWithMiddleware(args) {
4549 if (!args.matches.some((m) => m.route.middleware)) {
4550 return defaultDataStrategy(args);
4551 }
4552 return runClientMiddlewarePipeline(args, () => defaultDataStrategy(args));
4553}
4554function runServerMiddlewarePipeline(args, handler, errorHandler) {
4555 return runMiddlewarePipeline(
4556 args,
4557 handler,
4558 processResult,
4559 isResponse,
4560 errorHandler
4561 );
4562 function processResult(result) {
4563 return isDataWithResponseInit(result) ? dataWithResponseInitToResponse(result) : result;
4564 }
4565}
4566function runClientMiddlewarePipeline(args, handler) {
4567 return runMiddlewarePipeline(
4568 args,
4569 handler,
4570 (r) => {
4571 if (isRedirectResponse(r)) {
4572 throw r;
4573 }
4574 return r;
4575 },
4576 isDataStrategyResults,
4577 errorHandler
4578 );
4579 function errorHandler(error, routeId, nextResult) {
4580 if (nextResult) {
4581 return Promise.resolve(
4582 Object.assign(nextResult.value, {
4583 [routeId]: { type: "error", result: error }
4584 })
4585 );
4586 } else {
4587 let { matches } = args;
4588 let maxBoundaryIdx = Math.min(
4589 // Throwing route
4590 Math.max(
4591 matches.findIndex((m) => m.route.id === routeId),
4592 0
4593 ),
4594 // or the shallowest route that needs to load data
4595 Math.max(
4596 matches.findIndex((m) => m.shouldCallHandler()),
4597 0
4598 )
4599 );
4600 let boundaryRouteId = findNearestBoundary(
4601 matches,
4602 matches[maxBoundaryIdx].route.id
4603 ).route.id;
4604 return Promise.resolve({
4605 [boundaryRouteId]: { type: "error", result: error }
4606 });
4607 }
4608 }
4609}
4610async function runMiddlewarePipeline(args, handler, processResult, isResult, errorHandler) {
4611 let { matches, ...dataFnArgs } = args;
4612 let tuples = matches.flatMap(
4613 (m) => m.route.middleware ? m.route.middleware.map((fn) => [m.route.id, fn]) : []
4614 );
4615 let result = await callRouteMiddleware(
4616 dataFnArgs,
4617 tuples,
4618 handler,
4619 processResult,
4620 isResult,
4621 errorHandler
4622 );
4623 return result;
4624}
4625async function callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx = 0) {
4626 let { request } = args;
4627 if (request.signal.aborted) {
4628 throw _nullishCoalesce(request.signal.reason, () => ( new Error(`Request aborted: ${request.method} ${request.url}`)));
4629 }
4630 let tuple = middlewares[idx];
4631 if (!tuple) {
4632 let result = await handler();
4633 return result;
4634 }
4635 let [routeId, middleware] = tuple;
4636 let nextResult;
4637 let next = async () => {
4638 if (nextResult) {
4639 throw new Error("You may only call `next()` once per middleware");
4640 }
4641 try {
4642 let result = await callRouteMiddleware(
4643 args,
4644 middlewares,
4645 handler,
4646 processResult,
4647 isResult,
4648 errorHandler,
4649 idx + 1
4650 );
4651 nextResult = { value: result };
4652 return nextResult.value;
4653 } catch (error) {
4654 nextResult = { value: await errorHandler(error, routeId, nextResult) };
4655 return nextResult.value;
4656 }
4657 };
4658 try {
4659 let value = await middleware(args, next);
4660 let result = value != null ? processResult(value) : void 0;
4661 if (isResult(result)) {
4662 return result;
4663 } else if (nextResult) {
4664 return _nullishCoalesce(result, () => ( nextResult.value));
4665 } else {
4666 nextResult = { value: await next() };
4667 return nextResult.value;
4668 }
4669 } catch (error) {
4670 let response = await errorHandler(error, routeId, nextResult);
4671 return response;
4672 }
4673}
4674function getDataStrategyMatchLazyPromises(mapRouteProperties2, manifest, request, match, lazyRoutePropertiesToSkip) {
4675 let lazyMiddlewarePromise = loadLazyRouteProperty({
4676 key: "middleware",
4677 route: match.route,
4678 manifest,
4679 mapRouteProperties: mapRouteProperties2
4680 });
4681 let lazyRoutePromises = loadLazyRoute(
4682 match.route,
4683 isMutationMethod(request.method) ? "action" : "loader",
4684 manifest,
4685 mapRouteProperties2,
4686 lazyRoutePropertiesToSkip
4687 );
4688 return {
4689 middleware: lazyMiddlewarePromise,
4690 route: lazyRoutePromises.lazyRoutePromise,
4691 handler: lazyRoutePromises.lazyHandlerPromise
4692 };
4693}
4694function getDataStrategyMatch(mapRouteProperties2, manifest, request, path, unstable_pattern, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, shouldRevalidateArgs = null, callSiteDefaultShouldRevalidate) {
4695 let isUsingNewApi = false;
4696 let _lazyPromises = getDataStrategyMatchLazyPromises(
4697 mapRouteProperties2,
4698 manifest,
4699 request,
4700 match,
4701 lazyRoutePropertiesToSkip
4702 );
4703 return {
4704 ...match,
4705 _lazyPromises,
4706 shouldLoad,
4707 shouldRevalidateArgs,
4708 shouldCallHandler(defaultShouldRevalidate) {
4709 isUsingNewApi = true;
4710 if (!shouldRevalidateArgs) {
4711 return shouldLoad;
4712 }
4713 if (typeof callSiteDefaultShouldRevalidate === "boolean") {
4714 return shouldRevalidateLoader(match, {
4715 ...shouldRevalidateArgs,
4716 defaultShouldRevalidate: callSiteDefaultShouldRevalidate
4717 });
4718 }
4719 if (typeof defaultShouldRevalidate === "boolean") {
4720 return shouldRevalidateLoader(match, {
4721 ...shouldRevalidateArgs,
4722 defaultShouldRevalidate
4723 });
4724 }
4725 return shouldRevalidateLoader(match, shouldRevalidateArgs);
4726 },
4727 resolve(handlerOverride) {
4728 let { lazy, loader, middleware } = match.route;
4729 let callHandler = isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (lazy || loader);
4730 let isMiddlewareOnlyRoute = middleware && middleware.length > 0 && !loader && !lazy;
4731 if (callHandler && (isMutationMethod(request.method) || !isMiddlewareOnlyRoute)) {
4732 return callLoaderOrAction({
4733 request,
4734 path,
4735 unstable_pattern,
4736 match,
4737 lazyHandlerPromise: _optionalChain([_lazyPromises, 'optionalAccess', _56 => _56.handler]),
4738 lazyRoutePromise: _optionalChain([_lazyPromises, 'optionalAccess', _57 => _57.route]),
4739 handlerOverride,
4740 scopedContext
4741 });
4742 }
4743 return Promise.resolve({ type: "data" /* data */, result: void 0 });
4744 }
4745 };
4746}
4747function getTargetedDataStrategyMatches(mapRouteProperties2, manifest, request, path, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
4748 return matches.map((match) => {
4749 if (match.route.id !== targetMatch.route.id) {
4750 return {
4751 ...match,
4752 shouldLoad: false,
4753 shouldRevalidateArgs,
4754 shouldCallHandler: () => false,
4755 _lazyPromises: getDataStrategyMatchLazyPromises(
4756 mapRouteProperties2,
4757 manifest,
4758 request,
4759 match,
4760 lazyRoutePropertiesToSkip
4761 ),
4762 resolve: () => Promise.resolve({ type: "data", result: void 0 })
4763 };
4764 }
4765 return getDataStrategyMatch(
4766 mapRouteProperties2,
4767 manifest,
4768 request,
4769 path,
4770 getRoutePattern(matches),
4771 match,
4772 lazyRoutePropertiesToSkip,
4773 scopedContext,
4774 true,
4775 shouldRevalidateArgs
4776 );
4777 });
4778}
4779async function callDataStrategyImpl(dataStrategyImpl, request, path, matches, fetcherKey, scopedContext, isStaticHandler) {
4780 if (matches.some((m) => _optionalChain([m, 'access', _58 => _58._lazyPromises, 'optionalAccess', _59 => _59.middleware]))) {
4781 await Promise.all(matches.map((m) => _optionalChain([m, 'access', _60 => _60._lazyPromises, 'optionalAccess', _61 => _61.middleware])));
4782 }
4783 let dataStrategyArgs = {
4784 request,
4785 unstable_url: createDataFunctionUrl(request, path),
4786 unstable_pattern: getRoutePattern(matches),
4787 params: matches[0].params,
4788 context: scopedContext,
4789 matches
4790 };
4791 let runClientMiddleware = isStaticHandler ? () => {
4792 throw new Error(
4793 "You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`"
4794 );
4795 } : (cb) => {
4796 let typedDataStrategyArgs = dataStrategyArgs;
4797 return runClientMiddlewarePipeline(typedDataStrategyArgs, () => {
4798 return cb({
4799 ...typedDataStrategyArgs,
4800 fetcherKey,
4801 runClientMiddleware: () => {
4802 throw new Error(
4803 "Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler"
4804 );
4805 }
4806 });
4807 });
4808 };
4809 let results = await dataStrategyImpl({
4810 ...dataStrategyArgs,
4811 fetcherKey,
4812 runClientMiddleware
4813 });
4814 try {
4815 await Promise.all(
4816 matches.flatMap((m) => [
4817 _optionalChain([m, 'access', _62 => _62._lazyPromises, 'optionalAccess', _63 => _63.handler]),
4818 _optionalChain([m, 'access', _64 => _64._lazyPromises, 'optionalAccess', _65 => _65.route])
4819 ])
4820 );
4821 } catch (e) {
4822 }
4823 return results;
4824}
4825async function callLoaderOrAction({
4826 request,
4827 path,
4828 unstable_pattern,
4829 match,
4830 lazyHandlerPromise,
4831 lazyRoutePromise,
4832 handlerOverride,
4833 scopedContext
4834}) {
4835 let result;
4836 let onReject;
4837 let isAction = isMutationMethod(request.method);
4838 let type = isAction ? "action" : "loader";
4839 let runHandler = (handler) => {
4840 let reject;
4841 let abortPromise = new Promise((_, r) => reject = r);
4842 onReject = () => reject();
4843 request.signal.addEventListener("abort", onReject);
4844 let actualHandler = (ctx) => {
4845 if (typeof handler !== "function") {
4846 return Promise.reject(
4847 new Error(
4848 `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`
4849 )
4850 );
4851 }
4852 return handler(
4853 {
4854 request,
4855 unstable_url: createDataFunctionUrl(request, path),
4856 unstable_pattern,
4857 params: match.params,
4858 context: scopedContext
4859 },
4860 ...ctx !== void 0 ? [ctx] : []
4861 );
4862 };
4863 let handlerPromise = (async () => {
4864 try {
4865 let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
4866 return { type: "data", result: val };
4867 } catch (e) {
4868 return { type: "error", result: e };
4869 }
4870 })();
4871 return Promise.race([handlerPromise, abortPromise]);
4872 };
4873 try {
4874 let handler = isAction ? match.route.action : match.route.loader;
4875 if (lazyHandlerPromise || lazyRoutePromise) {
4876 if (handler) {
4877 let handlerError;
4878 let [value] = await Promise.all([
4879 // If the handler throws, don't let it immediately bubble out,
4880 // since we need to let the lazy() execution finish so we know if this
4881 // route has a boundary that can handle the error
4882 runHandler(handler).catch((e) => {
4883 handlerError = e;
4884 }),
4885 // Ensure all lazy route promises are resolved before continuing
4886 lazyHandlerPromise,
4887 lazyRoutePromise
4888 ]);
4889 if (handlerError !== void 0) {
4890 throw handlerError;
4891 }
4892 result = value;
4893 } else {
4894 await lazyHandlerPromise;
4895 let handler2 = isAction ? match.route.action : match.route.loader;
4896 if (handler2) {
4897 [result] = await Promise.all([runHandler(handler2), lazyRoutePromise]);
4898 } else if (type === "action") {
4899 let url = new URL(request.url);
4900 let pathname = url.pathname + url.search;
4901 throw getInternalRouterError(405, {
4902 method: request.method,
4903 pathname,
4904 routeId: match.route.id
4905 });
4906 } else {
4907 return { type: "data" /* data */, result: void 0 };
4908 }
4909 }
4910 } else if (!handler) {
4911 let url = new URL(request.url);
4912 let pathname = url.pathname + url.search;
4913 throw getInternalRouterError(404, {
4914 pathname
4915 });
4916 } else {
4917 result = await runHandler(handler);
4918 }
4919 } catch (e) {
4920 return { type: "error" /* error */, result: e };
4921 } finally {
4922 if (onReject) {
4923 request.signal.removeEventListener("abort", onReject);
4924 }
4925 }
4926 return result;
4927}
4928async function parseResponseBody(response) {
4929 let contentType = response.headers.get("Content-Type");
4930 if (contentType && /\bapplication\/json\b/.test(contentType)) {
4931 return response.body == null ? null : response.json();
4932 }
4933 return response.text();
4934}
4935async function convertDataStrategyResultToDataResult(dataStrategyResult) {
4936 let { result, type } = dataStrategyResult;
4937 if (isResponse(result)) {
4938 let data2;
4939 try {
4940 data2 = await parseResponseBody(result);
4941 } catch (e) {
4942 return { type: "error" /* error */, error: e };
4943 }
4944 if (type === "error" /* error */) {
4945 return {
4946 type: "error" /* error */,
4947 error: new ErrorResponseImpl(result.status, result.statusText, data2),
4948 statusCode: result.status,
4949 headers: result.headers
4950 };
4951 }
4952 return {
4953 type: "data" /* data */,
4954 data: data2,
4955 statusCode: result.status,
4956 headers: result.headers
4957 };
4958 }
4959 if (type === "error" /* error */) {
4960 if (isDataWithResponseInit(result)) {
4961 if (result.data instanceof Error) {
4962 return {
4963 type: "error" /* error */,
4964 error: result.data,
4965 statusCode: _optionalChain([result, 'access', _66 => _66.init, 'optionalAccess', _67 => _67.status]),
4966 headers: _optionalChain([result, 'access', _68 => _68.init, 'optionalAccess', _69 => _69.headers]) ? new Headers(result.init.headers) : void 0
4967 };
4968 }
4969 return {
4970 type: "error" /* error */,
4971 error: dataWithResponseInitToErrorResponse(result),
4972 statusCode: isRouteErrorResponse(result) ? result.status : void 0,
4973 headers: _optionalChain([result, 'access', _70 => _70.init, 'optionalAccess', _71 => _71.headers]) ? new Headers(result.init.headers) : void 0
4974 };
4975 }
4976 return {
4977 type: "error" /* error */,
4978 error: result,
4979 statusCode: isRouteErrorResponse(result) ? result.status : void 0
4980 };
4981 }
4982 if (isDataWithResponseInit(result)) {
4983 return {
4984 type: "data" /* data */,
4985 data: result.data,
4986 statusCode: _optionalChain([result, 'access', _72 => _72.init, 'optionalAccess', _73 => _73.status]),
4987 headers: _optionalChain([result, 'access', _74 => _74.init, 'optionalAccess', _75 => _75.headers]) ? new Headers(result.init.headers) : void 0
4988 };
4989 }
4990 return { type: "data" /* data */, data: result };
4991}
4992function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
4993 let location = response.headers.get("Location");
4994 invariant(
4995 location,
4996 "Redirects returned/thrown from loaders/actions must have a Location header"
4997 );
4998 if (!isAbsoluteUrl(location)) {
4999 let trimmedMatches = matches.slice(
5000 0,
5001 matches.findIndex((m) => m.route.id === routeId) + 1
5002 );
5003 location = normalizeTo(
5004 new URL(request.url),
5005 trimmedMatches,
5006 basename,
5007 location
5008 );
5009 response.headers.set("Location", location);
5010 }
5011 return response;
5012}
5013var invalidProtocols = [
5014 "about:",
5015 "blob:",
5016 "chrome:",
5017 "chrome-untrusted:",
5018 "content:",
5019 "data:",
5020 "devtools:",
5021 "file:",
5022 "filesystem:",
5023 // eslint-disable-next-line no-script-url
5024 "javascript:"
5025];
5026function normalizeRedirectLocation(location, currentUrl, basename, historyInstance) {
5027 if (isAbsoluteUrl(location)) {
5028 let normalizedLocation = location;
5029 let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
5030 if (invalidProtocols.includes(url.protocol)) {
5031 throw new Error("Invalid redirect location");
5032 }
5033 let isSameBasename = stripBasename(url.pathname, basename) != null;
5034 if (url.origin === currentUrl.origin && isSameBasename) {
5035 return removeDoubleSlashes(url.pathname) + url.search + url.hash;
5036 }
5037 }
5038 try {
5039 let url = historyInstance.createURL(location);
5040 if (invalidProtocols.includes(url.protocol)) {
5041 throw new Error("Invalid redirect location");
5042 }
5043 } catch (e) {
5044 }
5045 return location;
5046}
5047function createClientSideRequest(history, location, signal, submission) {
5048 let url = history.createURL(stripHashFromPath(location)).toString();
5049 let init = { signal };
5050 if (submission && isMutationMethod(submission.formMethod)) {
5051 let { formMethod, formEncType } = submission;
5052 init.method = formMethod.toUpperCase();
5053 if (formEncType === "application/json") {
5054 init.headers = new Headers({ "Content-Type": formEncType });
5055 init.body = JSON.stringify(submission.json);
5056 } else if (formEncType === "text/plain") {
5057 init.body = submission.text;
5058 } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
5059 init.body = convertFormDataToSearchParams(submission.formData);
5060 } else {
5061 init.body = submission.formData;
5062 }
5063 }
5064 return new Request(url, init);
5065}
5066function createDataFunctionUrl(request, path) {
5067 let url = new URL(request.url);
5068 let parsed = typeof path === "string" ? parsePath(path) : path;
5069 url.pathname = parsed.pathname || "/";
5070 if (parsed.search) {
5071 let searchParams = new URLSearchParams(parsed.search);
5072 let indexValues = searchParams.getAll("index");
5073 searchParams.delete("index");
5074 for (let value of indexValues.filter(Boolean)) {
5075 searchParams.append("index", value);
5076 }
5077 url.search = searchParams.size ? `?${searchParams.toString()}` : "";
5078 } else {
5079 url.search = "";
5080 }
5081 url.hash = parsed.hash || "";
5082 return url;
5083}
5084function convertFormDataToSearchParams(formData) {
5085 let searchParams = new URLSearchParams();
5086 for (let [key, value] of formData.entries()) {
5087 searchParams.append(key, typeof value === "string" ? value : value.name);
5088 }
5089 return searchParams;
5090}
5091function convertSearchParamsToFormData(searchParams) {
5092 let formData = new FormData();
5093 for (let [key, value] of searchParams.entries()) {
5094 formData.append(key, value);
5095 }
5096 return formData;
5097}
5098function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
5099 let loaderData = {};
5100 let errors = null;
5101 let statusCode;
5102 let foundError = false;
5103 let loaderHeaders = {};
5104 let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
5105 matches.forEach((match) => {
5106 if (!(match.route.id in results)) {
5107 return;
5108 }
5109 let id = match.route.id;
5110 let result = results[id];
5111 invariant(
5112 !isRedirectResult(result),
5113 "Cannot handle redirect results in processLoaderData"
5114 );
5115 if (isErrorResult(result)) {
5116 let error = result.error;
5117 if (pendingError !== void 0) {
5118 error = pendingError;
5119 pendingError = void 0;
5120 }
5121 errors = errors || {};
5122 if (skipLoaderErrorBubbling) {
5123 errors[id] = error;
5124 } else {
5125 let boundaryMatch = findNearestBoundary(matches, id);
5126 if (errors[boundaryMatch.route.id] == null) {
5127 errors[boundaryMatch.route.id] = error;
5128 }
5129 }
5130 if (!isStaticHandler) {
5131 loaderData[id] = ResetLoaderDataSymbol;
5132 }
5133 if (!foundError) {
5134 foundError = true;
5135 statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
5136 }
5137 if (result.headers) {
5138 loaderHeaders[id] = result.headers;
5139 }
5140 } else {
5141 loaderData[id] = result.data;
5142 if (result.statusCode && result.statusCode !== 200 && !foundError) {
5143 statusCode = result.statusCode;
5144 }
5145 if (result.headers) {
5146 loaderHeaders[id] = result.headers;
5147 }
5148 }
5149 });
5150 if (pendingError !== void 0 && pendingActionResult) {
5151 errors = { [pendingActionResult[0]]: pendingError };
5152 if (pendingActionResult[2]) {
5153 loaderData[pendingActionResult[2]] = void 0;
5154 }
5155 }
5156 return {
5157 loaderData,
5158 errors,
5159 statusCode: statusCode || 200,
5160 loaderHeaders
5161 };
5162}
5163function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults) {
5164 let { loaderData, errors } = processRouteLoaderData(
5165 matches,
5166 results,
5167 pendingActionResult
5168 );
5169 revalidatingFetchers.filter((f) => !f.matches || f.matches.some((m) => m.shouldLoad)).forEach((rf) => {
5170 let { key, match, controller } = rf;
5171 if (controller && controller.signal.aborted) {
5172 return;
5173 }
5174 let result = fetcherResults[key];
5175 invariant(result, "Did not find corresponding fetcher result");
5176 if (isErrorResult(result)) {
5177 let boundaryMatch = findNearestBoundary(state.matches, _optionalChain([match, 'optionalAccess', _76 => _76.route, 'access', _77 => _77.id]));
5178 if (!(errors && errors[boundaryMatch.route.id])) {
5179 errors = {
5180 ...errors,
5181 [boundaryMatch.route.id]: result.error
5182 };
5183 }
5184 state.fetchers.delete(key);
5185 } else if (isRedirectResult(result)) {
5186 invariant(false, "Unhandled fetcher revalidation redirect");
5187 } else {
5188 let doneFetcher = getDoneFetcher(result.data);
5189 state.fetchers.set(key, doneFetcher);
5190 }
5191 });
5192 return { loaderData, errors };
5193}
5194function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
5195 let mergedLoaderData = Object.entries(newLoaderData).filter(([, v]) => v !== ResetLoaderDataSymbol).reduce((merged, [k, v]) => {
5196 merged[k] = v;
5197 return merged;
5198 }, {});
5199 for (let match of matches) {
5200 let id = match.route.id;
5201 if (!newLoaderData.hasOwnProperty(id) && loaderData.hasOwnProperty(id) && match.route.loader) {
5202 mergedLoaderData[id] = loaderData[id];
5203 }
5204 if (errors && errors.hasOwnProperty(id)) {
5205 break;
5206 }
5207 }
5208 return mergedLoaderData;
5209}
5210function getActionDataForCommit(pendingActionResult) {
5211 if (!pendingActionResult) {
5212 return {};
5213 }
5214 return isErrorResult(pendingActionResult[1]) ? {
5215 // Clear out prior actionData on errors
5216 actionData: {}
5217 } : {
5218 actionData: {
5219 [pendingActionResult[0]]: pendingActionResult[1].data
5220 }
5221 };
5222}
5223function findNearestBoundary(matches, routeId) {
5224 let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
5225 return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
5226}
5227function getShortCircuitMatches(routes) {
5228 let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
5229 id: `__shim-error-route__`
5230 };
5231 return {
5232 matches: [
5233 {
5234 params: {},
5235 pathname: "",
5236 pathnameBase: "",
5237 route
5238 }
5239 ],
5240 route
5241 };
5242}
5243function getInternalRouterError(status, {
5244 pathname,
5245 routeId,
5246 method,
5247 type,
5248 message
5249} = {}) {
5250 let statusText = "Unknown Server Error";
5251 let errorMessage = "Unknown @remix-run/router error";
5252 if (status === 400) {
5253 statusText = "Bad Request";
5254 if (method && pathname && routeId) {
5255 errorMessage = `You made a ${method} request to "${pathname}" but did not provide a \`loader\` for route "${routeId}", so there is no way to handle the request.`;
5256 } else if (type === "invalid-body") {
5257 errorMessage = "Unable to encode submission body";
5258 }
5259 } else if (status === 403) {
5260 statusText = "Forbidden";
5261 errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
5262 } else if (status === 404) {
5263 statusText = "Not Found";
5264 errorMessage = `No route matches URL "${pathname}"`;
5265 } else if (status === 405) {
5266 statusText = "Method Not Allowed";
5267 if (method && pathname && routeId) {
5268 errorMessage = `You made a ${method.toUpperCase()} request to "${pathname}" but did not provide an \`action\` for route "${routeId}", so there is no way to handle the request.`;
5269 } else if (method) {
5270 errorMessage = `Invalid request method "${method.toUpperCase()}"`;
5271 }
5272 }
5273 return new ErrorResponseImpl(
5274 status || 500,
5275 statusText,
5276 new Error(errorMessage),
5277 true
5278 );
5279}
5280function findRedirect(results) {
5281 let entries = Object.entries(results);
5282 for (let i = entries.length - 1; i >= 0; i--) {
5283 let [key, result] = entries[i];
5284 if (isRedirectResult(result)) {
5285 return { key, result };
5286 }
5287 }
5288}
5289function stripHashFromPath(path) {
5290 let parsedPath = typeof path === "string" ? parsePath(path) : path;
5291 return createPath({ ...parsedPath, hash: "" });
5292}
5293function isHashChangeOnly(a, b) {
5294 if (a.pathname !== b.pathname || a.search !== b.search) {
5295 return false;
5296 }
5297 if (a.hash === "") {
5298 return b.hash !== "";
5299 } else if (a.hash === b.hash) {
5300 return true;
5301 } else if (b.hash !== "") {
5302 return true;
5303 }
5304 return false;
5305}
5306function dataWithResponseInitToResponse(data2) {
5307 return Response.json(data2.data, _nullishCoalesce(data2.init, () => ( void 0)));
5308}
5309function dataWithResponseInitToErrorResponse(data2) {
5310 return new ErrorResponseImpl(
5311 _nullishCoalesce(_optionalChain([data2, 'access', _78 => _78.init, 'optionalAccess', _79 => _79.status]), () => ( 500)),
5312 _nullishCoalesce(_optionalChain([data2, 'access', _80 => _80.init, 'optionalAccess', _81 => _81.statusText]), () => ( "Internal Server Error")),
5313 data2.data
5314 );
5315}
5316function isDataStrategyResults(result) {
5317 return result != null && typeof result === "object" && Object.entries(result).every(
5318 ([key, value]) => typeof key === "string" && isDataStrategyResult(value)
5319 );
5320}
5321function isDataStrategyResult(result) {
5322 return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" /* data */ || result.type === "error" /* error */);
5323}
5324function isRedirectDataStrategyResult(result) {
5325 return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
5326}
5327function isErrorResult(result) {
5328 return result.type === "error" /* error */;
5329}
5330function isRedirectResult(result) {
5331 return (result && result.type) === "redirect" /* redirect */;
5332}
5333function isDataWithResponseInit(value) {
5334 return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
5335}
5336function isResponse(value) {
5337 return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
5338}
5339function isRedirectStatusCode(statusCode) {
5340 return redirectStatusCodes.has(statusCode);
5341}
5342function isRedirectResponse(result) {
5343 return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
5344}
5345function isValidMethod(method) {
5346 return validRequestMethods.has(method.toUpperCase());
5347}
5348function isMutationMethod(method) {
5349 return validMutationMethods.has(method.toUpperCase());
5350}
5351function hasNakedIndexQuery(search) {
5352 return new URLSearchParams(search).getAll("index").some((v) => v === "");
5353}
5354function getTargetMatch(matches, location) {
5355 let search = typeof location === "string" ? parsePath(location).search : location.search;
5356 if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
5357 return matches[matches.length - 1];
5358 }
5359 let pathMatches = getPathContributingMatches(matches);
5360 return pathMatches[pathMatches.length - 1];
5361}
5362function getSubmissionFromNavigation(navigation) {
5363 let { formMethod, formAction, formEncType, text, formData, json } = navigation;
5364 if (!formMethod || !formAction || !formEncType) {
5365 return;
5366 }
5367 if (text != null) {
5368 return {
5369 formMethod,
5370 formAction,
5371 formEncType,
5372 formData: void 0,
5373 json: void 0,
5374 text
5375 };
5376 } else if (formData != null) {
5377 return {
5378 formMethod,
5379 formAction,
5380 formEncType,
5381 formData,
5382 json: void 0,
5383 text: void 0
5384 };
5385 } else if (json !== void 0) {
5386 return {
5387 formMethod,
5388 formAction,
5389 formEncType,
5390 formData: void 0,
5391 json,
5392 text: void 0
5393 };
5394 }
5395}
5396function getLoadingNavigation(location, submission) {
5397 if (submission) {
5398 let navigation = {
5399 state: "loading",
5400 location,
5401 formMethod: submission.formMethod,
5402 formAction: submission.formAction,
5403 formEncType: submission.formEncType,
5404 formData: submission.formData,
5405 json: submission.json,
5406 text: submission.text
5407 };
5408 return navigation;
5409 } else {
5410 let navigation = {
5411 state: "loading",
5412 location,
5413 formMethod: void 0,
5414 formAction: void 0,
5415 formEncType: void 0,
5416 formData: void 0,
5417 json: void 0,
5418 text: void 0
5419 };
5420 return navigation;
5421 }
5422}
5423function getSubmittingNavigation(location, submission) {
5424 let navigation = {
5425 state: "submitting",
5426 location,
5427 formMethod: submission.formMethod,
5428 formAction: submission.formAction,
5429 formEncType: submission.formEncType,
5430 formData: submission.formData,
5431 json: submission.json,
5432 text: submission.text
5433 };
5434 return navigation;
5435}
5436function getLoadingFetcher(submission, data2) {
5437 if (submission) {
5438 let fetcher = {
5439 state: "loading",
5440 formMethod: submission.formMethod,
5441 formAction: submission.formAction,
5442 formEncType: submission.formEncType,
5443 formData: submission.formData,
5444 json: submission.json,
5445 text: submission.text,
5446 data: data2
5447 };
5448 return fetcher;
5449 } else {
5450 let fetcher = {
5451 state: "loading",
5452 formMethod: void 0,
5453 formAction: void 0,
5454 formEncType: void 0,
5455 formData: void 0,
5456 json: void 0,
5457 text: void 0,
5458 data: data2
5459 };
5460 return fetcher;
5461 }
5462}
5463function getSubmittingFetcher(submission, existingFetcher) {
5464 let fetcher = {
5465 state: "submitting",
5466 formMethod: submission.formMethod,
5467 formAction: submission.formAction,
5468 formEncType: submission.formEncType,
5469 formData: submission.formData,
5470 json: submission.json,
5471 text: submission.text,
5472 data: existingFetcher ? existingFetcher.data : void 0
5473 };
5474 return fetcher;
5475}
5476function getDoneFetcher(data2) {
5477 let fetcher = {
5478 state: "idle",
5479 formMethod: void 0,
5480 formAction: void 0,
5481 formEncType: void 0,
5482 formData: void 0,
5483 json: void 0,
5484 text: void 0,
5485 data: data2
5486 };
5487 return fetcher;
5488}
5489function restoreAppliedTransitions(_window, transitions) {
5490 try {
5491 let sessionPositions = _window.sessionStorage.getItem(
5492 TRANSITIONS_STORAGE_KEY
5493 );
5494 if (sessionPositions) {
5495 let json = JSON.parse(sessionPositions);
5496 for (let [k, v] of Object.entries(json || {})) {
5497 if (v && Array.isArray(v)) {
5498 transitions.set(k, new Set(v || []));
5499 }
5500 }
5501 }
5502 } catch (e) {
5503 }
5504}
5505function persistAppliedTransitions(_window, transitions) {
5506 if (transitions.size > 0) {
5507 let json = {};
5508 for (let [k, v] of transitions) {
5509 json[k] = [...v];
5510 }
5511 try {
5512 _window.sessionStorage.setItem(
5513 TRANSITIONS_STORAGE_KEY,
5514 JSON.stringify(json)
5515 );
5516 } catch (error) {
5517 warning(
5518 false,
5519 `Failed to save applied view transitions in sessionStorage (${error}).`
5520 );
5521 }
5522 }
5523}
5524function createDeferred() {
5525 let resolve;
5526 let reject;
5527 let promise = new Promise((res, rej) => {
5528 resolve = async (val) => {
5529 res(val);
5530 try {
5531 await promise;
5532 } catch (e) {
5533 }
5534 };
5535 reject = async (error) => {
5536 rej(error);
5537 try {
5538 await promise;
5539 } catch (e) {
5540 }
5541 };
5542 });
5543 return {
5544 promise,
5545 //@ts-ignore
5546 resolve,
5547 //@ts-ignore
5548 reject
5549 };
5550}
5551
5552// lib/dom/ssr/single-fetch.tsx
5553var _react = require('react'); var React = _interopRequireWildcard(_react); var React2 = _interopRequireWildcard(_react); var React3 = _interopRequireWildcard(_react); var React8 = _interopRequireWildcard(_react); var React7 = _interopRequireWildcard(_react); var React6 = _interopRequireWildcard(_react); var React5 = _interopRequireWildcard(_react); var React4 = _interopRequireWildcard(_react); var React9 = _interopRequireWildcard(_react);
5554
5555// vendor/turbo-stream-v2/utils.ts
5556var HOLE = -1;
5557var NAN = -2;
5558var NEGATIVE_INFINITY = -3;
5559var NEGATIVE_ZERO = -4;
5560var NULL = -5;
5561var POSITIVE_INFINITY = -6;
5562var UNDEFINED = -7;
5563var TYPE_BIGINT = "B";
5564var TYPE_DATE = "D";
5565var TYPE_ERROR = "E";
5566var TYPE_MAP = "M";
5567var TYPE_NULL_OBJECT = "N";
5568var TYPE_PROMISE = "P";
5569var TYPE_REGEXP = "R";
5570var TYPE_SET = "S";
5571var TYPE_SYMBOL = "Y";
5572var TYPE_URL = "U";
5573var TYPE_PREVIOUS_RESOLVED = "Z";
5574var SUPPORTED_ERROR_TYPES = [
5575 "EvalError",
5576 "RangeError",
5577 "ReferenceError",
5578 "SyntaxError",
5579 "TypeError",
5580 "URIError"
5581];
5582var Deferred = class {
5583 constructor() {
5584 this.promise = new Promise((resolve, reject) => {
5585 this.resolve = resolve;
5586 this.reject = reject;
5587 });
5588 }
5589};
5590function createLineSplittingTransform() {
5591 const decoder = new TextDecoder();
5592 let leftover = "";
5593 return new TransformStream({
5594 transform(chunk, controller) {
5595 const str = decoder.decode(chunk, { stream: true });
5596 const parts = (leftover + str).split("\n");
5597 leftover = parts.pop() || "";
5598 for (const part of parts) {
5599 controller.enqueue(part);
5600 }
5601 },
5602 flush(controller) {
5603 if (leftover) {
5604 controller.enqueue(leftover);
5605 }
5606 }
5607 });
5608}
5609
5610// vendor/turbo-stream-v2/flatten.ts
5611var TIME_LIMIT_MS = 1;
5612var getNow = () => Date.now();
5613var yieldToMain = () => new Promise((resolve) => setTimeout(resolve, 0));
5614async function flatten(input) {
5615 const { indices } = this;
5616 const existing = indices.get(input);
5617 if (existing) return [existing];
5618 if (input === void 0) return UNDEFINED;
5619 if (input === null) return NULL;
5620 if (Number.isNaN(input)) return NAN;
5621 if (input === Number.POSITIVE_INFINITY) return POSITIVE_INFINITY;
5622 if (input === Number.NEGATIVE_INFINITY) return NEGATIVE_INFINITY;
5623 if (input === 0 && 1 / input < 0) return NEGATIVE_ZERO;
5624 const index = this.index++;
5625 indices.set(input, index);
5626 const stack = [[input, index]];
5627 await stringify.call(this, stack);
5628 return index;
5629}
5630async function stringify(stack) {
5631 const { deferred, indices, plugins, postPlugins } = this;
5632 const str = this.stringified;
5633 let lastYieldTime = getNow();
5634 const flattenValue = (value) => {
5635 const existing = indices.get(value);
5636 if (existing) return [existing];
5637 if (value === void 0) return UNDEFINED;
5638 if (value === null) return NULL;
5639 if (Number.isNaN(value)) return NAN;
5640 if (value === Number.POSITIVE_INFINITY) return POSITIVE_INFINITY;
5641 if (value === Number.NEGATIVE_INFINITY) return NEGATIVE_INFINITY;
5642 if (value === 0 && 1 / value < 0) return NEGATIVE_ZERO;
5643 const index = this.index++;
5644 indices.set(value, index);
5645 stack.push([value, index]);
5646 return index;
5647 };
5648 let i = 0;
5649 while (stack.length > 0) {
5650 const now = getNow();
5651 if (++i % 6e3 === 0 && now - lastYieldTime >= TIME_LIMIT_MS) {
5652 await yieldToMain();
5653 lastYieldTime = getNow();
5654 }
5655 const [input, index] = stack.pop();
5656 const partsForObj = (obj) => Object.keys(obj).map((k) => `"_${flattenValue(k)}":${flattenValue(obj[k])}`).join(",");
5657 let error = null;
5658 switch (typeof input) {
5659 case "boolean":
5660 case "number":
5661 case "string":
5662 str[index] = JSON.stringify(input);
5663 break;
5664 case "bigint":
5665 str[index] = `["${TYPE_BIGINT}","${input}"]`;
5666 break;
5667 case "symbol": {
5668 const keyFor = Symbol.keyFor(input);
5669 if (!keyFor) {
5670 error = new Error(
5671 "Cannot encode symbol unless created with Symbol.for()"
5672 );
5673 } else {
5674 str[index] = `["${TYPE_SYMBOL}",${JSON.stringify(keyFor)}]`;
5675 }
5676 break;
5677 }
5678 case "object": {
5679 if (!input) {
5680 str[index] = `${NULL}`;
5681 break;
5682 }
5683 const isArray = Array.isArray(input);
5684 let pluginHandled = false;
5685 if (!isArray && plugins) {
5686 for (const plugin of plugins) {
5687 const pluginResult = plugin(input);
5688 if (Array.isArray(pluginResult)) {
5689 pluginHandled = true;
5690 const [pluginIdentifier, ...rest] = pluginResult;
5691 str[index] = `[${JSON.stringify(pluginIdentifier)}`;
5692 if (rest.length > 0) {
5693 str[index] += `,${rest.map((v) => flattenValue(v)).join(",")}`;
5694 }
5695 str[index] += "]";
5696 break;
5697 }
5698 }
5699 }
5700 if (!pluginHandled) {
5701 let result = isArray ? "[" : "{";
5702 if (isArray) {
5703 for (let i2 = 0; i2 < input.length; i2++)
5704 result += (i2 ? "," : "") + (i2 in input ? flattenValue(input[i2]) : HOLE);
5705 str[index] = `${result}]`;
5706 } else if (input instanceof Date) {
5707 const dateTime = input.getTime();
5708 str[index] = `["${TYPE_DATE}",${Number.isNaN(dateTime) ? JSON.stringify("invalid") : dateTime}]`;
5709 } else if (input instanceof URL) {
5710 str[index] = `["${TYPE_URL}",${JSON.stringify(input.href)}]`;
5711 } else if (input instanceof RegExp) {
5712 str[index] = `["${TYPE_REGEXP}",${JSON.stringify(
5713 input.source
5714 )},${JSON.stringify(input.flags)}]`;
5715 } else if (input instanceof Set) {
5716 if (input.size > 0) {
5717 str[index] = `["${TYPE_SET}",${[...input].map((val) => flattenValue(val)).join(",")}]`;
5718 } else {
5719 str[index] = `["${TYPE_SET}"]`;
5720 }
5721 } else if (input instanceof Map) {
5722 if (input.size > 0) {
5723 str[index] = `["${TYPE_MAP}",${[...input].flatMap(([k, v]) => [flattenValue(k), flattenValue(v)]).join(",")}]`;
5724 } else {
5725 str[index] = `["${TYPE_MAP}"]`;
5726 }
5727 } else if (input instanceof Promise) {
5728 str[index] = `["${TYPE_PROMISE}",${index}]`;
5729 deferred[index] = input;
5730 } else if (input instanceof Error) {
5731 str[index] = `["${TYPE_ERROR}",${JSON.stringify(input.message)}`;
5732 if (input.name !== "Error") {
5733 str[index] += `,${JSON.stringify(input.name)}`;
5734 }
5735 str[index] += "]";
5736 } else if (Object.getPrototypeOf(input) === null) {
5737 str[index] = `["${TYPE_NULL_OBJECT}",{${partsForObj(input)}}]`;
5738 } else if (isPlainObject2(input)) {
5739 str[index] = `{${partsForObj(input)}}`;
5740 } else {
5741 error = new Error("Cannot encode object with prototype");
5742 }
5743 }
5744 break;
5745 }
5746 default: {
5747 const isArray = Array.isArray(input);
5748 let pluginHandled = false;
5749 if (!isArray && plugins) {
5750 for (const plugin of plugins) {
5751 const pluginResult = plugin(input);
5752 if (Array.isArray(pluginResult)) {
5753 pluginHandled = true;
5754 const [pluginIdentifier, ...rest] = pluginResult;
5755 str[index] = `[${JSON.stringify(pluginIdentifier)}`;
5756 if (rest.length > 0) {
5757 str[index] += `,${rest.map((v) => flattenValue(v)).join(",")}`;
5758 }
5759 str[index] += "]";
5760 break;
5761 }
5762 }
5763 }
5764 if (!pluginHandled) {
5765 error = new Error("Cannot encode function or unexpected type");
5766 }
5767 }
5768 }
5769 if (error) {
5770 let pluginHandled = false;
5771 if (postPlugins) {
5772 for (const plugin of postPlugins) {
5773 const pluginResult = plugin(input);
5774 if (Array.isArray(pluginResult)) {
5775 pluginHandled = true;
5776 const [pluginIdentifier, ...rest] = pluginResult;
5777 str[index] = `[${JSON.stringify(pluginIdentifier)}`;
5778 if (rest.length > 0) {
5779 str[index] += `,${rest.map((v) => flattenValue(v)).join(",")}`;
5780 }
5781 str[index] += "]";
5782 break;
5783 }
5784 }
5785 }
5786 if (!pluginHandled) {
5787 throw error;
5788 }
5789 }
5790 }
5791}
5792var objectProtoNames2 = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
5793function isPlainObject2(thing) {
5794 const proto = Object.getPrototypeOf(thing);
5795 return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames2;
5796}
5797
5798// vendor/turbo-stream-v2/unflatten.ts
5799var globalObj = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : void 0;
5800function unflatten(parsed) {
5801 const { hydrated, values } = this;
5802 if (typeof parsed === "number") return hydrate.call(this, parsed);
5803 if (!Array.isArray(parsed) || !parsed.length) throw new SyntaxError();
5804 const startIndex = values.length;
5805 for (const value of parsed) {
5806 values.push(value);
5807 }
5808 hydrated.length = values.length;
5809 return hydrate.call(this, startIndex);
5810}
5811function hydrate(index) {
5812 const { hydrated, values, deferred, plugins } = this;
5813 let result;
5814 const stack = [
5815 [
5816 index,
5817 (v) => {
5818 result = v;
5819 }
5820 ]
5821 ];
5822 let postRun = [];
5823 while (stack.length > 0) {
5824 const [index2, set] = stack.pop();
5825 switch (index2) {
5826 case UNDEFINED:
5827 set(void 0);
5828 continue;
5829 case NULL:
5830 set(null);
5831 continue;
5832 case NAN:
5833 set(NaN);
5834 continue;
5835 case POSITIVE_INFINITY:
5836 set(Infinity);
5837 continue;
5838 case NEGATIVE_INFINITY:
5839 set(-Infinity);
5840 continue;
5841 case NEGATIVE_ZERO:
5842 set(-0);
5843 continue;
5844 }
5845 if (hydrated[index2]) {
5846 set(hydrated[index2]);
5847 continue;
5848 }
5849 const value = values[index2];
5850 if (!value || typeof value !== "object") {
5851 hydrated[index2] = value;
5852 set(value);
5853 continue;
5854 }
5855 if (Array.isArray(value)) {
5856 if (typeof value[0] === "string") {
5857 const [type, b, c] = value;
5858 switch (type) {
5859 case TYPE_DATE:
5860 set(hydrated[index2] = new Date(b));
5861 continue;
5862 case TYPE_URL:
5863 set(hydrated[index2] = new URL(b));
5864 continue;
5865 case TYPE_BIGINT:
5866 set(hydrated[index2] = BigInt(b));
5867 continue;
5868 case TYPE_REGEXP:
5869 set(hydrated[index2] = new RegExp(b, c));
5870 continue;
5871 case TYPE_SYMBOL:
5872 set(hydrated[index2] = Symbol.for(b));
5873 continue;
5874 case TYPE_SET:
5875 const newSet = /* @__PURE__ */ new Set();
5876 hydrated[index2] = newSet;
5877 for (let i = value.length - 1; i > 0; i--)
5878 stack.push([
5879 value[i],
5880 (v) => {
5881 newSet.add(v);
5882 }
5883 ]);
5884 set(newSet);
5885 continue;
5886 case TYPE_MAP:
5887 const map = /* @__PURE__ */ new Map();
5888 hydrated[index2] = map;
5889 for (let i = value.length - 2; i > 0; i -= 2) {
5890 const r = [];
5891 stack.push([
5892 value[i + 1],
5893 (v) => {
5894 r[1] = v;
5895 }
5896 ]);
5897 stack.push([
5898 value[i],
5899 (k) => {
5900 r[0] = k;
5901 }
5902 ]);
5903 postRun.push(() => {
5904 map.set(r[0], r[1]);
5905 });
5906 }
5907 set(map);
5908 continue;
5909 case TYPE_NULL_OBJECT:
5910 const obj = /* @__PURE__ */ Object.create(null);
5911 hydrated[index2] = obj;
5912 for (const key of Object.keys(b).reverse()) {
5913 const r = [];
5914 stack.push([
5915 b[key],
5916 (v) => {
5917 r[1] = v;
5918 }
5919 ]);
5920 stack.push([
5921 Number(key.slice(1)),
5922 (k) => {
5923 r[0] = k;
5924 }
5925 ]);
5926 postRun.push(() => {
5927 obj[r[0]] = r[1];
5928 });
5929 }
5930 set(obj);
5931 continue;
5932 case TYPE_PROMISE:
5933 if (hydrated[b]) {
5934 set(hydrated[index2] = hydrated[b]);
5935 } else {
5936 const d = new Deferred();
5937 deferred[b] = d;
5938 set(hydrated[index2] = d.promise);
5939 }
5940 continue;
5941 case TYPE_ERROR:
5942 const [, message, errorType] = value;
5943 let error = errorType && globalObj && SUPPORTED_ERROR_TYPES.includes(errorType) && errorType in globalObj && typeof globalObj[errorType] === "function" ? new globalObj[errorType](message) : new Error(message);
5944 hydrated[index2] = error;
5945 set(error);
5946 continue;
5947 case TYPE_PREVIOUS_RESOLVED:
5948 set(hydrated[index2] = hydrated[b]);
5949 continue;
5950 default:
5951 if (Array.isArray(plugins)) {
5952 const r = [];
5953 const vals = value.slice(1);
5954 for (let i = 0; i < vals.length; i++) {
5955 const v = vals[i];
5956 stack.push([
5957 v,
5958 (v2) => {
5959 r[i] = v2;
5960 }
5961 ]);
5962 }
5963 postRun.push(() => {
5964 for (const plugin of plugins) {
5965 const result2 = plugin(value[0], ...r);
5966 if (result2) {
5967 set(hydrated[index2] = result2.value);
5968 return;
5969 }
5970 }
5971 throw new SyntaxError();
5972 });
5973 continue;
5974 }
5975 throw new SyntaxError();
5976 }
5977 } else {
5978 const array = [];
5979 hydrated[index2] = array;
5980 for (let i = 0; i < value.length; i++) {
5981 const n = value[i];
5982 if (n !== HOLE) {
5983 stack.push([
5984 n,
5985 (v) => {
5986 array[i] = v;
5987 }
5988 ]);
5989 }
5990 }
5991 set(array);
5992 continue;
5993 }
5994 } else {
5995 const object = {};
5996 hydrated[index2] = object;
5997 for (const key of Object.keys(value).reverse()) {
5998 const r = [];
5999 stack.push([
6000 value[key],
6001 (v) => {
6002 r[1] = v;
6003 }
6004 ]);
6005 stack.push([
6006 Number(key.slice(1)),
6007 (k) => {
6008 r[0] = k;
6009 }
6010 ]);
6011 postRun.push(() => {
6012 object[r[0]] = r[1];
6013 });
6014 }
6015 set(object);
6016 continue;
6017 }
6018 }
6019 while (postRun.length > 0) {
6020 postRun.pop()();
6021 }
6022 return result;
6023}
6024
6025// vendor/turbo-stream-v2/turbo-stream.ts
6026async function decode(readable, options) {
6027 const { plugins } = _nullishCoalesce(options, () => ( {}));
6028 const done = new Deferred();
6029 const reader = readable.pipeThrough(createLineSplittingTransform()).getReader();
6030 const decoder = {
6031 values: [],
6032 hydrated: [],
6033 deferred: {},
6034 plugins
6035 };
6036 const decoded = await decodeInitial.call(decoder, reader);
6037 let donePromise = done.promise;
6038 if (decoded.done) {
6039 done.resolve();
6040 } else {
6041 donePromise = decodeDeferred.call(decoder, reader).then(done.resolve).catch((reason) => {
6042 for (const deferred of Object.values(decoder.deferred)) {
6043 deferred.reject(reason);
6044 }
6045 done.reject(reason);
6046 });
6047 }
6048 return {
6049 done: donePromise.then(() => reader.closed),
6050 value: decoded.value
6051 };
6052}
6053async function decodeInitial(reader) {
6054 const read = await reader.read();
6055 if (!read.value) {
6056 throw new SyntaxError();
6057 }
6058 let line;
6059 try {
6060 line = JSON.parse(read.value);
6061 } catch (reason) {
6062 throw new SyntaxError();
6063 }
6064 return {
6065 done: read.done,
6066 value: unflatten.call(this, line)
6067 };
6068}
6069async function decodeDeferred(reader) {
6070 let read = await reader.read();
6071 while (!read.done) {
6072 if (!read.value) continue;
6073 const line = read.value;
6074 switch (line[0]) {
6075 case TYPE_PROMISE: {
6076 const colonIndex = line.indexOf(":");
6077 const deferredId = Number(line.slice(1, colonIndex));
6078 const deferred = this.deferred[deferredId];
6079 if (!deferred) {
6080 throw new Error(`Deferred ID ${deferredId} not found in stream`);
6081 }
6082 const lineData = line.slice(colonIndex + 1);
6083 let jsonLine;
6084 try {
6085 jsonLine = JSON.parse(lineData);
6086 } catch (reason) {
6087 throw new SyntaxError();
6088 }
6089 const value = unflatten.call(this, jsonLine);
6090 deferred.resolve(value);
6091 break;
6092 }
6093 case TYPE_ERROR: {
6094 const colonIndex = line.indexOf(":");
6095 const deferredId = Number(line.slice(1, colonIndex));
6096 const deferred = this.deferred[deferredId];
6097 if (!deferred) {
6098 throw new Error(`Deferred ID ${deferredId} not found in stream`);
6099 }
6100 const lineData = line.slice(colonIndex + 1);
6101 let jsonLine;
6102 try {
6103 jsonLine = JSON.parse(lineData);
6104 } catch (reason) {
6105 throw new SyntaxError();
6106 }
6107 const value = unflatten.call(this, jsonLine);
6108 deferred.reject(value);
6109 break;
6110 }
6111 default:
6112 throw new SyntaxError();
6113 }
6114 read = await reader.read();
6115 }
6116}
6117function encode(input, options) {
6118 const { onComplete, plugins, postPlugins, signal } = _nullishCoalesce(options, () => ( {}));
6119 const encoder = {
6120 deferred: {},
6121 index: 0,
6122 indices: /* @__PURE__ */ new Map(),
6123 stringified: [],
6124 plugins,
6125 postPlugins,
6126 signal
6127 };
6128 const textEncoder = new TextEncoder();
6129 let lastSentIndex = 0;
6130 const readable = new ReadableStream({
6131 async start(controller) {
6132 const id = await flatten.call(encoder, input);
6133 if (Array.isArray(id)) {
6134 throw new Error("This should never happen");
6135 }
6136 if (id < 0) {
6137 controller.enqueue(textEncoder.encode(`${id}
6138`));
6139 } else {
6140 controller.enqueue(
6141 textEncoder.encode(`[${encoder.stringified.join(",")}]
6142`)
6143 );
6144 lastSentIndex = encoder.stringified.length - 1;
6145 }
6146 const seenPromises = /* @__PURE__ */ new WeakSet();
6147 let processingChain = Promise.resolve();
6148 if (Object.keys(encoder.deferred).length) {
6149 let raceDone;
6150 const racePromise = new Promise((resolve, reject) => {
6151 raceDone = resolve;
6152 if (signal) {
6153 const rejectPromise = () => reject(signal.reason || new Error("Signal was aborted."));
6154 if (signal.aborted) {
6155 rejectPromise();
6156 } else {
6157 signal.addEventListener("abort", (event) => {
6158 rejectPromise();
6159 });
6160 }
6161 }
6162 });
6163 while (Object.keys(encoder.deferred).length > 0) {
6164 for (const [deferredId, deferred] of Object.entries(
6165 encoder.deferred
6166 )) {
6167 if (seenPromises.has(deferred)) continue;
6168 seenPromises.add(
6169 // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
6170 encoder.deferred[Number(deferredId)] = Promise.race([
6171 racePromise,
6172 deferred
6173 ]).then(
6174 (resolved) => {
6175 processingChain = processingChain.then(async () => {
6176 const id2 = await flatten.call(encoder, resolved);
6177 if (Array.isArray(id2)) {
6178 controller.enqueue(
6179 textEncoder.encode(
6180 `${TYPE_PROMISE}${deferredId}:[["${TYPE_PREVIOUS_RESOLVED}",${id2[0]}]]
6181`
6182 )
6183 );
6184 encoder.index++;
6185 lastSentIndex++;
6186 } else if (id2 < 0) {
6187 controller.enqueue(
6188 textEncoder.encode(
6189 `${TYPE_PROMISE}${deferredId}:${id2}
6190`
6191 )
6192 );
6193 } else {
6194 const values = encoder.stringified.slice(lastSentIndex + 1).join(",");
6195 controller.enqueue(
6196 textEncoder.encode(
6197 `${TYPE_PROMISE}${deferredId}:[${values}]
6198`
6199 )
6200 );
6201 lastSentIndex = encoder.stringified.length - 1;
6202 }
6203 });
6204 return processingChain;
6205 },
6206 (reason) => {
6207 processingChain = processingChain.then(async () => {
6208 if (!reason || typeof reason !== "object" || !(reason instanceof Error)) {
6209 reason = new Error("An unknown error occurred");
6210 }
6211 const id2 = await flatten.call(encoder, reason);
6212 if (Array.isArray(id2)) {
6213 controller.enqueue(
6214 textEncoder.encode(
6215 `${TYPE_ERROR}${deferredId}:[["${TYPE_PREVIOUS_RESOLVED}",${id2[0]}]]
6216`
6217 )
6218 );
6219 encoder.index++;
6220 lastSentIndex++;
6221 } else if (id2 < 0) {
6222 controller.enqueue(
6223 textEncoder.encode(
6224 `${TYPE_ERROR}${deferredId}:${id2}
6225`
6226 )
6227 );
6228 } else {
6229 const values = encoder.stringified.slice(lastSentIndex + 1).join(",");
6230 controller.enqueue(
6231 textEncoder.encode(
6232 `${TYPE_ERROR}${deferredId}:[${values}]
6233`
6234 )
6235 );
6236 lastSentIndex = encoder.stringified.length - 1;
6237 }
6238 });
6239 return processingChain;
6240 }
6241 ).finally(() => {
6242 delete encoder.deferred[Number(deferredId)];
6243 })
6244 );
6245 }
6246 await Promise.race(Object.values(encoder.deferred));
6247 }
6248 raceDone();
6249 }
6250 await Promise.all(Object.values(encoder.deferred));
6251 await processingChain;
6252 controller.close();
6253 _optionalChain([onComplete, 'optionalCall', _82 => _82()]);
6254 }
6255 });
6256 return readable;
6257}
6258
6259// lib/dom/ssr/data.ts
6260async function createRequestInit(request) {
6261 let init = { signal: request.signal };
6262 if (request.method !== "GET") {
6263 init.method = request.method;
6264 let contentType = request.headers.get("Content-Type");
6265 if (contentType && /\bapplication\/json\b/.test(contentType)) {
6266 init.headers = { "Content-Type": contentType };
6267 init.body = JSON.stringify(await request.json());
6268 } else if (contentType && /\btext\/plain\b/.test(contentType)) {
6269 init.headers = { "Content-Type": contentType };
6270 init.body = await request.text();
6271 } else if (contentType && /\bapplication\/x-www-form-urlencoded\b/.test(contentType)) {
6272 init.body = new URLSearchParams(await request.text());
6273 } else {
6274 init.body = await request.formData();
6275 }
6276 }
6277 return init;
6278}
6279
6280// lib/dom/ssr/markup.ts
6281var ESCAPE_LOOKUP = {
6282 "&": "\\u0026",
6283 ">": "\\u003e",
6284 "<": "\\u003c",
6285 "\u2028": "\\u2028",
6286 "\u2029": "\\u2029"
6287};
6288var ESCAPE_REGEX = /[&><\u2028\u2029]/g;
6289function escapeHtml(html) {
6290 return html.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
6291}
6292
6293// lib/dom/ssr/invariant.ts
6294function invariant2(value, message) {
6295 if (value === false || value === null || typeof value === "undefined") {
6296 throw new Error(message);
6297 }
6298}
6299
6300// lib/dom/ssr/single-fetch.tsx
6301var SingleFetchRedirectSymbol = Symbol("SingleFetchRedirect");
6302var SingleFetchNoResultError = class extends Error {
6303};
6304var SINGLE_FETCH_REDIRECT_STATUS = 202;
6305var NO_BODY_STATUS_CODES = /* @__PURE__ */ new Set([100, 101, 204, 205]);
6306function StreamTransfer({
6307 context,
6308 identifier,
6309 reader,
6310 textDecoder,
6311 nonce
6312}) {
6313 if (!context.renderMeta || !context.renderMeta.didRenderScripts) {
6314 return null;
6315 }
6316 if (!context.renderMeta.streamCache) {
6317 context.renderMeta.streamCache = {};
6318 }
6319 let { streamCache } = context.renderMeta;
6320 let promise = streamCache[identifier];
6321 if (!promise) {
6322 promise = streamCache[identifier] = reader.read().then((result) => {
6323 streamCache[identifier].result = {
6324 done: result.done,
6325 value: textDecoder.decode(result.value, { stream: true })
6326 };
6327 }).catch((e) => {
6328 streamCache[identifier].error = e;
6329 });
6330 }
6331 if (promise.error) {
6332 throw promise.error;
6333 }
6334 if (promise.result === void 0) {
6335 throw promise;
6336 }
6337 let { done, value } = promise.result;
6338 let scriptTag = value ? /* @__PURE__ */ React.createElement(
6339 "script",
6340 {
6341 nonce,
6342 dangerouslySetInnerHTML: {
6343 __html: `window.__reactRouterContext.streamController.enqueue(${escapeHtml(
6344 JSON.stringify(value)
6345 )});`
6346 }
6347 }
6348 ) : null;
6349 if (done) {
6350 return /* @__PURE__ */ React.createElement(React.Fragment, null, scriptTag, /* @__PURE__ */ React.createElement(
6351 "script",
6352 {
6353 nonce,
6354 dangerouslySetInnerHTML: {
6355 __html: `window.__reactRouterContext.streamController.close();`
6356 }
6357 }
6358 ));
6359 } else {
6360 return /* @__PURE__ */ React.createElement(React.Fragment, null, scriptTag, /* @__PURE__ */ React.createElement(React.Suspense, null, /* @__PURE__ */ React.createElement(
6361 StreamTransfer,
6362 {
6363 context,
6364 identifier: identifier + 1,
6365 reader,
6366 textDecoder,
6367 nonce
6368 }
6369 )));
6370 }
6371}
6372function getTurboStreamSingleFetchDataStrategy(getRouter, manifest, routeModules, ssr, basename, trailingSlashAware) {
6373 let dataStrategy = getSingleFetchDataStrategyImpl(
6374 getRouter,
6375 (match) => {
6376 let manifestRoute = manifest.routes[match.route.id];
6377 invariant2(manifestRoute, "Route not found in manifest");
6378 let routeModule = routeModules[match.route.id];
6379 return {
6380 hasLoader: manifestRoute.hasLoader,
6381 hasClientLoader: manifestRoute.hasClientLoader,
6382 hasShouldRevalidate: Boolean(_optionalChain([routeModule, 'optionalAccess', _83 => _83.shouldRevalidate]))
6383 };
6384 },
6385 fetchAndDecodeViaTurboStream,
6386 ssr,
6387 basename,
6388 trailingSlashAware
6389 );
6390 return async (args) => args.runClientMiddleware(dataStrategy);
6391}
6392function getSingleFetchDataStrategyImpl(getRouter, getRouteInfo, fetchAndDecode, ssr, basename, trailingSlashAware, shouldAllowOptOut = () => true) {
6393 return async (args) => {
6394 let { request, matches, fetcherKey } = args;
6395 let router = getRouter();
6396 if (request.method !== "GET") {
6397 return singleFetchActionStrategy(
6398 args,
6399 fetchAndDecode,
6400 basename,
6401 trailingSlashAware
6402 );
6403 }
6404 let foundRevalidatingServerLoader = matches.some((m) => {
6405 let { hasLoader, hasClientLoader } = getRouteInfo(m);
6406 return m.shouldCallHandler() && hasLoader && !hasClientLoader;
6407 });
6408 if (!ssr && !foundRevalidatingServerLoader) {
6409 return nonSsrStrategy(
6410 args,
6411 getRouteInfo,
6412 fetchAndDecode,
6413 basename,
6414 trailingSlashAware
6415 );
6416 }
6417 if (fetcherKey) {
6418 return singleFetchLoaderFetcherStrategy(
6419 args,
6420 fetchAndDecode,
6421 basename,
6422 trailingSlashAware
6423 );
6424 }
6425 return singleFetchLoaderNavigationStrategy(
6426 args,
6427 router,
6428 getRouteInfo,
6429 fetchAndDecode,
6430 ssr,
6431 basename,
6432 trailingSlashAware,
6433 shouldAllowOptOut
6434 );
6435 };
6436}
6437async function singleFetchActionStrategy(args, fetchAndDecode, basename, trailingSlashAware) {
6438 let actionMatch = args.matches.find((m) => m.shouldCallHandler());
6439 invariant2(actionMatch, "No action match found");
6440 let actionStatus = void 0;
6441 let result = await actionMatch.resolve(async (handler) => {
6442 let result2 = await handler(async () => {
6443 let { data: data2, status } = await fetchAndDecode(
6444 args,
6445 basename,
6446 trailingSlashAware,
6447 [actionMatch.route.id]
6448 );
6449 actionStatus = status;
6450 return unwrapSingleFetchResult(data2, actionMatch.route.id);
6451 });
6452 return result2;
6453 });
6454 if (isResponse(result.result) || isRouteErrorResponse(result.result) || isDataWithResponseInit(result.result)) {
6455 return { [actionMatch.route.id]: result };
6456 }
6457 return {
6458 [actionMatch.route.id]: {
6459 type: result.type,
6460 result: data(result.result, actionStatus)
6461 }
6462 };
6463}
6464async function nonSsrStrategy(args, getRouteInfo, fetchAndDecode, basename, trailingSlashAware) {
6465 let matchesToLoad = args.matches.filter((m) => m.shouldCallHandler());
6466 let results = {};
6467 await Promise.all(
6468 matchesToLoad.map(
6469 (m) => m.resolve(async (handler) => {
6470 try {
6471 let { hasClientLoader } = getRouteInfo(m);
6472 let routeId = m.route.id;
6473 let result = hasClientLoader ? await handler(async () => {
6474 let { data: data2 } = await fetchAndDecode(
6475 args,
6476 basename,
6477 trailingSlashAware,
6478 [routeId]
6479 );
6480 return unwrapSingleFetchResult(data2, routeId);
6481 }) : await handler();
6482 results[m.route.id] = { type: "data", result };
6483 } catch (e) {
6484 results[m.route.id] = { type: "error", result: e };
6485 }
6486 })
6487 )
6488 );
6489 return results;
6490}
6491async function singleFetchLoaderNavigationStrategy(args, router, getRouteInfo, fetchAndDecode, ssr, basename, trailingSlashAware, shouldAllowOptOut = () => true) {
6492 let routesParams = /* @__PURE__ */ new Set();
6493 let foundOptOutRoute = false;
6494 let routeDfds = args.matches.map(() => createDeferred2());
6495 let singleFetchDfd = createDeferred2();
6496 let results = {};
6497 let resolvePromise = Promise.all(
6498 args.matches.map(
6499 async (m, i) => m.resolve(async (handler) => {
6500 routeDfds[i].resolve();
6501 let routeId = m.route.id;
6502 let { hasLoader, hasClientLoader, hasShouldRevalidate } = getRouteInfo(m);
6503 let defaultShouldRevalidate = !m.shouldRevalidateArgs || m.shouldRevalidateArgs.actionStatus == null || m.shouldRevalidateArgs.actionStatus < 400;
6504 let shouldCall = m.shouldCallHandler(defaultShouldRevalidate);
6505 if (!shouldCall) {
6506 foundOptOutRoute || (foundOptOutRoute = m.shouldRevalidateArgs != null && // This is a revalidation,
6507 hasLoader && // for a route with a server loader,
6508 hasShouldRevalidate === true);
6509 return;
6510 }
6511 if (shouldAllowOptOut(m) && hasClientLoader) {
6512 if (hasLoader) {
6513 foundOptOutRoute = true;
6514 }
6515 try {
6516 let result = await handler(async () => {
6517 let { data: data2 } = await fetchAndDecode(
6518 args,
6519 basename,
6520 trailingSlashAware,
6521 [routeId]
6522 );
6523 return unwrapSingleFetchResult(data2, routeId);
6524 });
6525 results[routeId] = { type: "data", result };
6526 } catch (e) {
6527 results[routeId] = { type: "error", result: e };
6528 }
6529 return;
6530 }
6531 if (hasLoader) {
6532 routesParams.add(routeId);
6533 }
6534 try {
6535 let result = await handler(async () => {
6536 let data2 = await singleFetchDfd.promise;
6537 return unwrapSingleFetchResult(data2, routeId);
6538 });
6539 results[routeId] = { type: "data", result };
6540 } catch (e) {
6541 results[routeId] = { type: "error", result: e };
6542 }
6543 })
6544 )
6545 );
6546 await Promise.all(routeDfds.map((d) => d.promise));
6547 let isInitialLoad = !router.state.initialized && router.state.navigation.state === "idle";
6548 if ((isInitialLoad || routesParams.size === 0) && !window.__reactRouterHdrActive) {
6549 singleFetchDfd.resolve({ routes: {} });
6550 } else {
6551 let targetRoutes = ssr && foundOptOutRoute && routesParams.size > 0 ? [...routesParams.keys()] : void 0;
6552 try {
6553 let data2 = await fetchAndDecode(
6554 args,
6555 basename,
6556 trailingSlashAware,
6557 targetRoutes
6558 );
6559 singleFetchDfd.resolve(data2.data);
6560 } catch (e) {
6561 singleFetchDfd.reject(e);
6562 }
6563 }
6564 await resolvePromise;
6565 await bubbleMiddlewareErrors(
6566 singleFetchDfd.promise,
6567 args.matches,
6568 routesParams,
6569 results
6570 );
6571 return results;
6572}
6573async function bubbleMiddlewareErrors(singleFetchPromise, matches, routesParams, results) {
6574 try {
6575 let middlewareError;
6576 let fetchedData = await singleFetchPromise;
6577 if ("routes" in fetchedData) {
6578 for (let match of matches) {
6579 if (match.route.id in fetchedData.routes) {
6580 let routeResult = fetchedData.routes[match.route.id];
6581 if ("error" in routeResult) {
6582 middlewareError = routeResult.error;
6583 if (_optionalChain([results, 'access', _84 => _84[match.route.id], 'optionalAccess', _85 => _85.result]) == null) {
6584 results[match.route.id] = {
6585 type: "error",
6586 result: middlewareError
6587 };
6588 }
6589 break;
6590 }
6591 }
6592 }
6593 }
6594 if (middlewareError !== void 0) {
6595 Array.from(routesParams.values()).forEach((routeId) => {
6596 if (results[routeId].result instanceof SingleFetchNoResultError) {
6597 results[routeId].result = middlewareError;
6598 }
6599 });
6600 }
6601 } catch (e) {
6602 }
6603}
6604async function singleFetchLoaderFetcherStrategy(args, fetchAndDecode, basename, trailingSlashAware) {
6605 let fetcherMatch = args.matches.find((m) => m.shouldCallHandler());
6606 invariant2(fetcherMatch, "No fetcher match found");
6607 let routeId = fetcherMatch.route.id;
6608 let result = await fetcherMatch.resolve(
6609 async (handler) => handler(async () => {
6610 let { data: data2 } = await fetchAndDecode(args, basename, trailingSlashAware, [
6611 routeId
6612 ]);
6613 return unwrapSingleFetchResult(data2, routeId);
6614 })
6615 );
6616 return { [fetcherMatch.route.id]: result };
6617}
6618function stripIndexParam(url) {
6619 let indexValues = url.searchParams.getAll("index");
6620 url.searchParams.delete("index");
6621 let indexValuesToKeep = [];
6622 for (let indexValue of indexValues) {
6623 if (indexValue) {
6624 indexValuesToKeep.push(indexValue);
6625 }
6626 }
6627 for (let toKeep of indexValuesToKeep) {
6628 url.searchParams.append("index", toKeep);
6629 }
6630 return url;
6631}
6632function singleFetchUrl(reqUrl, basename, trailingSlashAware, extension) {
6633 let url = typeof reqUrl === "string" ? new URL(
6634 reqUrl,
6635 // This can be called during the SSR flow via PrefetchPageLinksImpl so
6636 // don't assume window is available
6637 typeof window === "undefined" ? "server://singlefetch/" : window.location.origin
6638 ) : reqUrl;
6639 if (trailingSlashAware) {
6640 if (url.pathname.endsWith("/")) {
6641 url.pathname = `${url.pathname}_.${extension}`;
6642 } else {
6643 url.pathname = `${url.pathname}.${extension}`;
6644 }
6645 } else {
6646 if (url.pathname === "/") {
6647 url.pathname = `_root.${extension}`;
6648 } else if (basename && stripBasename(url.pathname, basename) === "/") {
6649 url.pathname = `${removeTrailingSlash(basename)}/_root.${extension}`;
6650 } else {
6651 url.pathname = `${removeTrailingSlash(url.pathname)}.${extension}`;
6652 }
6653 }
6654 return url;
6655}
6656async function fetchAndDecodeViaTurboStream(args, basename, trailingSlashAware, targetRoutes) {
6657 let { request } = args;
6658 let url = singleFetchUrl(request.url, basename, trailingSlashAware, "data");
6659 if (request.method === "GET") {
6660 url = stripIndexParam(url);
6661 if (targetRoutes) {
6662 url.searchParams.set("_routes", targetRoutes.join(","));
6663 }
6664 }
6665 let res = await fetch(url, await createRequestInit(request));
6666 if (res.status >= 400 && !res.headers.has("X-Remix-Response")) {
6667 throw new ErrorResponseImpl(res.status, res.statusText, await res.text());
6668 }
6669 if (res.status === 204 && res.headers.has("X-Remix-Redirect")) {
6670 return {
6671 status: SINGLE_FETCH_REDIRECT_STATUS,
6672 data: {
6673 redirect: {
6674 redirect: res.headers.get("X-Remix-Redirect"),
6675 status: Number(res.headers.get("X-Remix-Status") || "302"),
6676 revalidate: res.headers.get("X-Remix-Revalidate") === "true",
6677 reload: res.headers.get("X-Remix-Reload-Document") === "true",
6678 replace: res.headers.get("X-Remix-Replace") === "true"
6679 }
6680 }
6681 };
6682 }
6683 if (NO_BODY_STATUS_CODES.has(res.status)) {
6684 let routes = {};
6685 if (targetRoutes && request.method !== "GET") {
6686 routes[targetRoutes[0]] = { data: void 0 };
6687 }
6688 return {
6689 status: res.status,
6690 data: { routes }
6691 };
6692 }
6693 invariant2(res.body, "No response body to decode");
6694 try {
6695 let decoded = await decodeViaTurboStream(res.body, window);
6696 let data2;
6697 if (request.method === "GET") {
6698 let typed = decoded.value;
6699 if (SingleFetchRedirectSymbol in typed) {
6700 data2 = { redirect: typed[SingleFetchRedirectSymbol] };
6701 } else {
6702 data2 = { routes: typed };
6703 }
6704 } else {
6705 let typed = decoded.value;
6706 let routeId = _optionalChain([targetRoutes, 'optionalAccess', _86 => _86[0]]);
6707 invariant2(routeId, "No routeId found for single fetch call decoding");
6708 if ("redirect" in typed) {
6709 data2 = { redirect: typed };
6710 } else {
6711 data2 = { routes: { [routeId]: typed } };
6712 }
6713 }
6714 return { status: res.status, data: data2 };
6715 } catch (e) {
6716 throw new Error("Unable to decode turbo-stream response");
6717 }
6718}
6719function decodeViaTurboStream(body, global) {
6720 return decode(body, {
6721 plugins: [
6722 (type, ...rest) => {
6723 if (type === "SanitizedError") {
6724 let [name, message, stack] = rest;
6725 let Constructor = Error;
6726 if (name && SUPPORTED_ERROR_TYPES.includes(name) && name in global && // @ts-expect-error
6727 typeof global[name] === "function") {
6728 Constructor = global[name];
6729 }
6730 let error = new Constructor(message);
6731 error.stack = stack;
6732 return { value: error };
6733 }
6734 if (type === "ErrorResponse") {
6735 let [data2, status, statusText] = rest;
6736 return {
6737 value: new ErrorResponseImpl(status, statusText, data2)
6738 };
6739 }
6740 if (type === "SingleFetchRedirect") {
6741 return { value: { [SingleFetchRedirectSymbol]: rest[0] } };
6742 }
6743 if (type === "SingleFetchClassInstance") {
6744 return { value: rest[0] };
6745 }
6746 if (type === "SingleFetchFallback") {
6747 return { value: void 0 };
6748 }
6749 }
6750 ]
6751 });
6752}
6753function unwrapSingleFetchResult(result, routeId) {
6754 if ("redirect" in result) {
6755 let {
6756 redirect: location,
6757 revalidate,
6758 reload,
6759 replace: replace2,
6760 status
6761 } = result.redirect;
6762 throw redirect(location, {
6763 status,
6764 headers: {
6765 // Three R's of redirecting (lol Veep)
6766 ...revalidate ? { "X-Remix-Revalidate": "yes" } : null,
6767 ...reload ? { "X-Remix-Reload-Document": "yes" } : null,
6768 ...replace2 ? { "X-Remix-Replace": "yes" } : null
6769 }
6770 });
6771 }
6772 let routeResult = result.routes[routeId];
6773 if (routeResult == null) {
6774 throw new SingleFetchNoResultError(
6775 `No result found for routeId "${routeId}"`
6776 );
6777 } else if ("error" in routeResult) {
6778 throw routeResult.error;
6779 } else if ("data" in routeResult) {
6780 return routeResult.data;
6781 } else {
6782 throw new Error(`Invalid response found for routeId "${routeId}"`);
6783 }
6784}
6785function createDeferred2() {
6786 let resolve;
6787 let reject;
6788 let promise = new Promise((res, rej) => {
6789 resolve = async (val) => {
6790 res(val);
6791 try {
6792 await promise;
6793 } catch (e) {
6794 }
6795 };
6796 reject = async (error) => {
6797 rej(error);
6798 try {
6799 await promise;
6800 } catch (e) {
6801 }
6802 };
6803 });
6804 return {
6805 promise,
6806 //@ts-ignore
6807 resolve,
6808 //@ts-ignore
6809 reject
6810 };
6811}
6812
6813// lib/context.ts
6814
6815var DataRouterContext = React2.createContext(null);
6816DataRouterContext.displayName = "DataRouter";
6817var DataRouterStateContext = React2.createContext(null);
6818DataRouterStateContext.displayName = "DataRouterState";
6819var RSCRouterContext = React2.createContext(false);
6820function useIsRSCRouterContext() {
6821 return React2.useContext(RSCRouterContext);
6822}
6823var ViewTransitionContext = React2.createContext({
6824 isTransitioning: false
6825});
6826ViewTransitionContext.displayName = "ViewTransition";
6827var FetchersContext = React2.createContext(
6828 /* @__PURE__ */ new Map()
6829);
6830FetchersContext.displayName = "Fetchers";
6831var AwaitContext = React2.createContext(null);
6832AwaitContext.displayName = "Await";
6833var AwaitContextProvider = (props) => React2.createElement(AwaitContext.Provider, props);
6834var NavigationContext = React2.createContext(
6835 null
6836);
6837NavigationContext.displayName = "Navigation";
6838var LocationContext = React2.createContext(
6839 null
6840);
6841LocationContext.displayName = "Location";
6842var RouteContext = React2.createContext({
6843 outlet: null,
6844 matches: [],
6845 isDataRoute: false
6846});
6847RouteContext.displayName = "Route";
6848var RouteErrorContext = React2.createContext(null);
6849RouteErrorContext.displayName = "RouteError";
6850var ENABLE_DEV_WARNINGS = false;
6851
6852// lib/hooks.tsx
6853
6854
6855// lib/errors.ts
6856var ERROR_DIGEST_BASE = "REACT_ROUTER_ERROR";
6857var ERROR_DIGEST_REDIRECT = "REDIRECT";
6858var ERROR_DIGEST_ROUTE_ERROR_RESPONSE = "ROUTE_ERROR_RESPONSE";
6859function decodeRedirectErrorDigest(digest) {
6860 if (digest.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:{`)) {
6861 try {
6862 let parsed = JSON.parse(digest.slice(28));
6863 if (typeof parsed === "object" && parsed && typeof parsed.status === "number" && typeof parsed.statusText === "string" && typeof parsed.location === "string" && typeof parsed.reloadDocument === "boolean" && typeof parsed.replace === "boolean") {
6864 return parsed;
6865 }
6866 } catch (e2) {
6867 }
6868 }
6869}
6870function decodeRouteErrorResponseDigest(digest) {
6871 if (digest.startsWith(
6872 `${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:{`
6873 )) {
6874 try {
6875 let parsed = JSON.parse(digest.slice(40));
6876 if (typeof parsed === "object" && parsed && typeof parsed.status === "number" && typeof parsed.statusText === "string") {
6877 return new ErrorResponseImpl(
6878 parsed.status,
6879 parsed.statusText,
6880 parsed.data
6881 );
6882 }
6883 } catch (e3) {
6884 }
6885 }
6886}
6887
6888// lib/hooks.tsx
6889function useHref(to, { relative } = {}) {
6890 invariant(
6891 useInRouterContext(),
6892 // TODO: This error is probably because they somehow have 2 versions of the
6893 // router loaded. We can help them understand how to avoid that.
6894 `useHref() may be used only in the context of a <Router> component.`
6895 );
6896 let { basename, navigator } = React3.useContext(NavigationContext);
6897 let { hash, pathname, search } = useResolvedPath(to, { relative });
6898 let joinedPathname = pathname;
6899 if (basename !== "/") {
6900 joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
6901 }
6902 return navigator.createHref({ pathname: joinedPathname, search, hash });
6903}
6904function useInRouterContext() {
6905 return React3.useContext(LocationContext) != null;
6906}
6907function useLocation() {
6908 invariant(
6909 useInRouterContext(),
6910 // TODO: This error is probably because they somehow have 2 versions of the
6911 // router loaded. We can help them understand how to avoid that.
6912 `useLocation() may be used only in the context of a <Router> component.`
6913 );
6914 return React3.useContext(LocationContext).location;
6915}
6916function useNavigationType() {
6917 return React3.useContext(LocationContext).navigationType;
6918}
6919function useMatch(pattern) {
6920 invariant(
6921 useInRouterContext(),
6922 // TODO: This error is probably because they somehow have 2 versions of the
6923 // router loaded. We can help them understand how to avoid that.
6924 `useMatch() may be used only in the context of a <Router> component.`
6925 );
6926 let { pathname } = useLocation();
6927 return React3.useMemo(
6928 () => matchPath(pattern, decodePath(pathname)),
6929 [pathname, pattern]
6930 );
6931}
6932var navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when your component is first rendered.`;
6933function useIsomorphicLayoutEffect(cb) {
6934 let isStatic = React3.useContext(NavigationContext).static;
6935 if (!isStatic) {
6936 React3.useLayoutEffect(cb);
6937 }
6938}
6939function useNavigate() {
6940 let { isDataRoute } = React3.useContext(RouteContext);
6941 return isDataRoute ? useNavigateStable() : useNavigateUnstable();
6942}
6943function useNavigateUnstable() {
6944 invariant(
6945 useInRouterContext(),
6946 // TODO: This error is probably because they somehow have 2 versions of the
6947 // router loaded. We can help them understand how to avoid that.
6948 `useNavigate() may be used only in the context of a <Router> component.`
6949 );
6950 let dataRouterContext = React3.useContext(DataRouterContext);
6951 let { basename, navigator } = React3.useContext(NavigationContext);
6952 let { matches } = React3.useContext(RouteContext);
6953 let { pathname: locationPathname } = useLocation();
6954 let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
6955 let activeRef = React3.useRef(false);
6956 useIsomorphicLayoutEffect(() => {
6957 activeRef.current = true;
6958 });
6959 let navigate = React3.useCallback(
6960 (to, options = {}) => {
6961 warning(activeRef.current, navigateEffectWarning);
6962 if (!activeRef.current) return;
6963 if (typeof to === "number") {
6964 navigator.go(to);
6965 return;
6966 }
6967 let path = resolveTo(
6968 to,
6969 JSON.parse(routePathnamesJson),
6970 locationPathname,
6971 options.relative === "path"
6972 );
6973 if (dataRouterContext == null && basename !== "/") {
6974 path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
6975 }
6976 (!!options.replace ? navigator.replace : navigator.push)(
6977 path,
6978 options.state,
6979 options
6980 );
6981 },
6982 [
6983 basename,
6984 navigator,
6985 routePathnamesJson,
6986 locationPathname,
6987 dataRouterContext
6988 ]
6989 );
6990 return navigate;
6991}
6992var OutletContext = React3.createContext(null);
6993function useOutletContext() {
6994 return React3.useContext(OutletContext);
6995}
6996function useOutlet(context) {
6997 let outlet = React3.useContext(RouteContext).outlet;
6998 return React3.useMemo(
6999 () => outlet && /* @__PURE__ */ React3.createElement(OutletContext.Provider, { value: context }, outlet),
7000 [outlet, context]
7001 );
7002}
7003function useParams() {
7004 let { matches } = React3.useContext(RouteContext);
7005 let routeMatch = matches[matches.length - 1];
7006 return _nullishCoalesce(_optionalChain([routeMatch, 'optionalAccess', _87 => _87.params]), () => ( {}));
7007}
7008function useResolvedPath(to, { relative } = {}) {
7009 let { matches } = React3.useContext(RouteContext);
7010 let { pathname: locationPathname } = useLocation();
7011 let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
7012 return React3.useMemo(
7013 () => resolveTo(
7014 to,
7015 JSON.parse(routePathnamesJson),
7016 locationPathname,
7017 relative === "path"
7018 ),
7019 [to, routePathnamesJson, locationPathname, relative]
7020 );
7021}
7022function useRoutes(routes, locationArg) {
7023 return useRoutesImpl(routes, locationArg);
7024}
7025function useRoutesImpl(routes, locationArg, dataRouterOpts) {
7026 invariant(
7027 useInRouterContext(),
7028 // TODO: This error is probably because they somehow have 2 versions of the
7029 // router loaded. We can help them understand how to avoid that.
7030 `useRoutes() may be used only in the context of a <Router> component.`
7031 );
7032 let { navigator } = React3.useContext(NavigationContext);
7033 let { matches: parentMatches } = React3.useContext(RouteContext);
7034 let routeMatch = parentMatches[parentMatches.length - 1];
7035 let parentParams = routeMatch ? routeMatch.params : {};
7036 let parentPathname = routeMatch ? routeMatch.pathname : "/";
7037 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
7038 let parentRoute = routeMatch && routeMatch.route;
7039 if (ENABLE_DEV_WARNINGS) {
7040 let parentPath = parentRoute && parentRoute.path || "";
7041 warningOnce(
7042 parentPathname,
7043 !parentRoute || parentPath.endsWith("*") || parentPath.endsWith("*?"),
7044 `You rendered descendant <Routes> (or called \`useRoutes()\`) at "${parentPathname}" (under <Route path="${parentPath}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
7045
7046Please change the parent <Route path="${parentPath}"> to <Route path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`
7047 );
7048 }
7049 let locationFromContext = useLocation();
7050 let location;
7051 if (locationArg) {
7052 let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
7053 invariant(
7054 parentPathnameBase === "/" || _optionalChain([parsedLocationArg, 'access', _88 => _88.pathname, 'optionalAccess', _89 => _89.startsWith, 'call', _90 => _90(parentPathnameBase)]),
7055 `When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${parentPathnameBase}" but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`
7056 );
7057 location = parsedLocationArg;
7058 } else {
7059 location = locationFromContext;
7060 }
7061 let pathname = location.pathname || "/";
7062 let remainingPathname = pathname;
7063 if (parentPathnameBase !== "/") {
7064 let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
7065 let segments = pathname.replace(/^\//, "").split("/");
7066 remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
7067 }
7068 let matches = matchRoutes(routes, { pathname: remainingPathname });
7069 if (ENABLE_DEV_WARNINGS) {
7070 warning(
7071 parentRoute || matches != null,
7072 `No routes matched location "${location.pathname}${location.search}${location.hash}" `
7073 );
7074 warning(
7075 matches == null || matches[matches.length - 1].route.element !== void 0 || matches[matches.length - 1].route.Component !== void 0 || matches[matches.length - 1].route.lazy !== void 0,
7076 `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`
7077 );
7078 }
7079 let renderedMatches = _renderMatches(
7080 matches && matches.map(
7081 (match) => Object.assign({}, match, {
7082 params: Object.assign({}, parentParams, match.params),
7083 pathname: joinPaths([
7084 parentPathnameBase,
7085 // Re-encode pathnames that were decoded inside matchRoutes.
7086 // Pre-encode `%`, `?` and `#` ahead of `encodeLocation` because it uses
7087 // `new URL()` internally and we need to prevent it from treating
7088 // them as separators
7089 navigator.encodeLocation ? navigator.encodeLocation(
7090 match.pathname.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23")
7091 ).pathname : match.pathname
7092 ]),
7093 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([
7094 parentPathnameBase,
7095 // Re-encode pathnames that were decoded inside matchRoutes
7096 // Pre-encode `%`, `?` and `#` ahead of `encodeLocation` because it uses
7097 // `new URL()` internally and we need to prevent it from treating
7098 // them as separators
7099 navigator.encodeLocation ? navigator.encodeLocation(
7100 match.pathnameBase.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23")
7101 ).pathname : match.pathnameBase
7102 ])
7103 })
7104 ),
7105 parentMatches,
7106 dataRouterOpts
7107 );
7108 if (locationArg && renderedMatches) {
7109 return /* @__PURE__ */ React3.createElement(
7110 LocationContext.Provider,
7111 {
7112 value: {
7113 location: {
7114 pathname: "/",
7115 search: "",
7116 hash: "",
7117 state: null,
7118 key: "default",
7119 unstable_mask: void 0,
7120 ...location
7121 },
7122 navigationType: "POP" /* Pop */
7123 }
7124 },
7125 renderedMatches
7126 );
7127 }
7128 return renderedMatches;
7129}
7130function DefaultErrorComponent() {
7131 let error = useRouteError();
7132 let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
7133 let stack = error instanceof Error ? error.stack : null;
7134 let lightgrey = "rgba(200,200,200, 0.5)";
7135 let preStyles = { padding: "0.5rem", backgroundColor: lightgrey };
7136 let codeStyles = { padding: "2px 4px", backgroundColor: lightgrey };
7137 let devInfo = null;
7138 if (ENABLE_DEV_WARNINGS) {
7139 console.error(
7140 "Error handled by React Router default ErrorBoundary:",
7141 error
7142 );
7143 devInfo = /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("p", null, "\u{1F4BF} Hey developer \u{1F44B}"), /* @__PURE__ */ React3.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /* @__PURE__ */ React3.createElement("code", { style: codeStyles }, "ErrorBoundary"), " or", " ", /* @__PURE__ */ React3.createElement("code", { style: codeStyles }, "errorElement"), " prop on your route."));
7144 }
7145 return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ React3.createElement("h3", { style: { fontStyle: "italic" } }, message), stack ? /* @__PURE__ */ React3.createElement("pre", { style: preStyles }, stack) : null, devInfo);
7146}
7147var defaultErrorElement = /* @__PURE__ */ React3.createElement(DefaultErrorComponent, null);
7148var RenderErrorBoundary = class extends React3.Component {
7149 constructor(props) {
7150 super(props);
7151 this.state = {
7152 location: props.location,
7153 revalidation: props.revalidation,
7154 error: props.error
7155 };
7156 }
7157 static getDerivedStateFromError(error) {
7158 return { error };
7159 }
7160 static getDerivedStateFromProps(props, state) {
7161 if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
7162 return {
7163 error: props.error,
7164 location: props.location,
7165 revalidation: props.revalidation
7166 };
7167 }
7168 return {
7169 error: props.error !== void 0 ? props.error : state.error,
7170 location: state.location,
7171 revalidation: props.revalidation || state.revalidation
7172 };
7173 }
7174 componentDidCatch(error, errorInfo) {
7175 if (this.props.onError) {
7176 this.props.onError(error, errorInfo);
7177 } else {
7178 console.error(
7179 "React Router caught the following error during render",
7180 error
7181 );
7182 }
7183 }
7184 render() {
7185 let error = this.state.error;
7186 if (this.context && typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
7187 const decoded = decodeRouteErrorResponseDigest(error.digest);
7188 if (decoded) error = decoded;
7189 }
7190 let result = error !== void 0 ? /* @__PURE__ */ React3.createElement(RouteContext.Provider, { value: this.props.routeContext }, /* @__PURE__ */ React3.createElement(
7191 RouteErrorContext.Provider,
7192 {
7193 value: error,
7194 children: this.props.component
7195 }
7196 )) : this.props.children;
7197 if (this.context) {
7198 return /* @__PURE__ */ React3.createElement(RSCErrorHandler, { error }, result);
7199 }
7200 return result;
7201 }
7202};
7203RenderErrorBoundary.contextType = RSCRouterContext;
7204var errorRedirectHandledMap = /* @__PURE__ */ new WeakMap();
7205function RSCErrorHandler({
7206 children,
7207 error
7208}) {
7209 let { basename } = React3.useContext(NavigationContext);
7210 if (typeof error === "object" && error && "digest" in error && typeof error.digest === "string") {
7211 let redirect2 = decodeRedirectErrorDigest(error.digest);
7212 if (redirect2) {
7213 let existingRedirect = errorRedirectHandledMap.get(error);
7214 if (existingRedirect) throw existingRedirect;
7215 let parsed = parseToInfo(redirect2.location, basename);
7216 if (isBrowser && !errorRedirectHandledMap.get(error)) {
7217 if (parsed.isExternal || redirect2.reloadDocument) {
7218 window.location.href = parsed.absoluteURL || parsed.to;
7219 } else {
7220 const redirectPromise = Promise.resolve().then(
7221 () => window.__reactRouterDataRouter.navigate(parsed.to, {
7222 replace: redirect2.replace
7223 })
7224 );
7225 errorRedirectHandledMap.set(error, redirectPromise);
7226 throw redirectPromise;
7227 }
7228 }
7229 return /* @__PURE__ */ React3.createElement(
7230 "meta",
7231 {
7232 httpEquiv: "refresh",
7233 content: `0;url=${parsed.absoluteURL || parsed.to}`
7234 }
7235 );
7236 }
7237 }
7238 return children;
7239}
7240function RenderedRoute({ routeContext, match, children }) {
7241 let dataRouterContext = React3.useContext(DataRouterContext);
7242 if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
7243 dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
7244 }
7245 return /* @__PURE__ */ React3.createElement(RouteContext.Provider, { value: routeContext }, children);
7246}
7247function _renderMatches(matches, parentMatches = [], dataRouterOpts) {
7248 let dataRouterState = _optionalChain([dataRouterOpts, 'optionalAccess', _91 => _91.state]);
7249 if (matches == null) {
7250 if (!dataRouterState) {
7251 return null;
7252 }
7253 if (dataRouterState.errors) {
7254 matches = dataRouterState.matches;
7255 } else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
7256 matches = dataRouterState.matches;
7257 } else {
7258 return null;
7259 }
7260 }
7261 let renderedMatches = matches;
7262 let errors = _optionalChain([dataRouterState, 'optionalAccess', _92 => _92.errors]);
7263 if (errors != null) {
7264 let errorIndex = renderedMatches.findIndex(
7265 (m) => m.route.id && _optionalChain([errors, 'optionalAccess', _93 => _93[m.route.id]]) !== void 0
7266 );
7267 invariant(
7268 errorIndex >= 0,
7269 `Could not find a matching route for errors on route IDs: ${Object.keys(
7270 errors
7271 ).join(",")}`
7272 );
7273 renderedMatches = renderedMatches.slice(
7274 0,
7275 Math.min(renderedMatches.length, errorIndex + 1)
7276 );
7277 }
7278 let renderFallback = false;
7279 let fallbackIndex = -1;
7280 if (dataRouterOpts && dataRouterState) {
7281 renderFallback = dataRouterState.renderFallback;
7282 for (let i = 0; i < renderedMatches.length; i++) {
7283 let match = renderedMatches[i];
7284 if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
7285 fallbackIndex = i;
7286 }
7287 if (match.route.id) {
7288 let { loaderData, errors: errors2 } = dataRouterState;
7289 let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors2 || errors2[match.route.id] === void 0);
7290 if (match.route.lazy || needsToRunLoader) {
7291 if (dataRouterOpts.isStatic) {
7292 renderFallback = true;
7293 }
7294 if (fallbackIndex >= 0) {
7295 renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
7296 } else {
7297 renderedMatches = [renderedMatches[0]];
7298 }
7299 break;
7300 }
7301 }
7302 }
7303 }
7304 let onErrorHandler = _optionalChain([dataRouterOpts, 'optionalAccess', _94 => _94.onError]);
7305 let onError = dataRouterState && onErrorHandler ? (error, errorInfo) => {
7306 onErrorHandler(error, {
7307 location: dataRouterState.location,
7308 params: _nullishCoalesce(_optionalChain([dataRouterState, 'access', _95 => _95.matches, 'optionalAccess', _96 => _96[0], 'optionalAccess', _97 => _97.params]), () => ( {})),
7309 unstable_pattern: getRoutePattern(dataRouterState.matches),
7310 errorInfo
7311 });
7312 } : void 0;
7313 return renderedMatches.reduceRight(
7314 (outlet, match, index) => {
7315 let error;
7316 let shouldRenderHydrateFallback = false;
7317 let errorElement = null;
7318 let hydrateFallbackElement = null;
7319 if (dataRouterState) {
7320 error = errors && match.route.id ? errors[match.route.id] : void 0;
7321 errorElement = match.route.errorElement || defaultErrorElement;
7322 if (renderFallback) {
7323 if (fallbackIndex < 0 && index === 0) {
7324 warningOnce(
7325 "route-fallback",
7326 false,
7327 "No `HydrateFallback` element provided to render during initial hydration"
7328 );
7329 shouldRenderHydrateFallback = true;
7330 hydrateFallbackElement = null;
7331 } else if (fallbackIndex === index) {
7332 shouldRenderHydrateFallback = true;
7333 hydrateFallbackElement = match.route.hydrateFallbackElement || null;
7334 }
7335 }
7336 }
7337 let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1));
7338 let getChildren = () => {
7339 let children;
7340 if (error) {
7341 children = errorElement;
7342 } else if (shouldRenderHydrateFallback) {
7343 children = hydrateFallbackElement;
7344 } else if (match.route.Component) {
7345 children = /* @__PURE__ */ React3.createElement(match.route.Component, null);
7346 } else if (match.route.element) {
7347 children = match.route.element;
7348 } else {
7349 children = outlet;
7350 }
7351 return /* @__PURE__ */ React3.createElement(
7352 RenderedRoute,
7353 {
7354 match,
7355 routeContext: {
7356 outlet,
7357 matches: matches2,
7358 isDataRoute: dataRouterState != null
7359 },
7360 children
7361 }
7362 );
7363 };
7364 return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ React3.createElement(
7365 RenderErrorBoundary,
7366 {
7367 location: dataRouterState.location,
7368 revalidation: dataRouterState.revalidation,
7369 component: errorElement,
7370 error,
7371 children: getChildren(),
7372 routeContext: { outlet: null, matches: matches2, isDataRoute: true },
7373 onError
7374 }
7375 ) : getChildren();
7376 },
7377 null
7378 );
7379}
7380function getDataRouterConsoleError(hookName) {
7381 return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
7382}
7383function useDataRouterContext(hookName) {
7384 let ctx = React3.useContext(DataRouterContext);
7385 invariant(ctx, getDataRouterConsoleError(hookName));
7386 return ctx;
7387}
7388function useDataRouterState(hookName) {
7389 let state = React3.useContext(DataRouterStateContext);
7390 invariant(state, getDataRouterConsoleError(hookName));
7391 return state;
7392}
7393function useRouteContext(hookName) {
7394 let route = React3.useContext(RouteContext);
7395 invariant(route, getDataRouterConsoleError(hookName));
7396 return route;
7397}
7398function useCurrentRouteId(hookName) {
7399 let route = useRouteContext(hookName);
7400 let thisRoute = route.matches[route.matches.length - 1];
7401 invariant(
7402 thisRoute.route.id,
7403 `${hookName} can only be used on routes that contain a unique "id"`
7404 );
7405 return thisRoute.route.id;
7406}
7407function useRouteId() {
7408 return useCurrentRouteId("useRouteId" /* UseRouteId */);
7409}
7410function useNavigation() {
7411 let state = useDataRouterState("useNavigation" /* UseNavigation */);
7412 return state.navigation;
7413}
7414function useRevalidator() {
7415 let dataRouterContext = useDataRouterContext("useRevalidator" /* UseRevalidator */);
7416 let state = useDataRouterState("useRevalidator" /* UseRevalidator */);
7417 let revalidate = React3.useCallback(async () => {
7418 await dataRouterContext.router.revalidate();
7419 }, [dataRouterContext.router]);
7420 return React3.useMemo(
7421 () => ({ revalidate, state: state.revalidation }),
7422 [revalidate, state.revalidation]
7423 );
7424}
7425function useMatches() {
7426 let { matches, loaderData } = useDataRouterState(
7427 "useMatches" /* UseMatches */
7428 );
7429 return React3.useMemo(
7430 () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),
7431 [matches, loaderData]
7432 );
7433}
7434function useLoaderData() {
7435 let state = useDataRouterState("useLoaderData" /* UseLoaderData */);
7436 let routeId = useCurrentRouteId("useLoaderData" /* UseLoaderData */);
7437 return state.loaderData[routeId];
7438}
7439function useRouteLoaderData(routeId) {
7440 let state = useDataRouterState("useRouteLoaderData" /* UseRouteLoaderData */);
7441 return state.loaderData[routeId];
7442}
7443function useActionData() {
7444 let state = useDataRouterState("useActionData" /* UseActionData */);
7445 let routeId = useCurrentRouteId("useLoaderData" /* UseLoaderData */);
7446 return state.actionData ? state.actionData[routeId] : void 0;
7447}
7448function useRouteError() {
7449 let error = React3.useContext(RouteErrorContext);
7450 let state = useDataRouterState("useRouteError" /* UseRouteError */);
7451 let routeId = useCurrentRouteId("useRouteError" /* UseRouteError */);
7452 if (error !== void 0) {
7453 return error;
7454 }
7455 return _optionalChain([state, 'access', _98 => _98.errors, 'optionalAccess', _99 => _99[routeId]]);
7456}
7457function useAsyncValue() {
7458 let value = React3.useContext(AwaitContext);
7459 return _optionalChain([value, 'optionalAccess', _100 => _100._data]);
7460}
7461function useAsyncError() {
7462 let value = React3.useContext(AwaitContext);
7463 return _optionalChain([value, 'optionalAccess', _101 => _101._error]);
7464}
7465var blockerId = 0;
7466function useBlocker(shouldBlock) {
7467 let { router, basename } = useDataRouterContext("useBlocker" /* UseBlocker */);
7468 let state = useDataRouterState("useBlocker" /* UseBlocker */);
7469 let [blockerKey, setBlockerKey] = React3.useState("");
7470 let blockerFunction = React3.useCallback(
7471 (arg) => {
7472 if (typeof shouldBlock !== "function") {
7473 return !!shouldBlock;
7474 }
7475 if (basename === "/") {
7476 return shouldBlock(arg);
7477 }
7478 let { currentLocation, nextLocation, historyAction } = arg;
7479 return shouldBlock({
7480 currentLocation: {
7481 ...currentLocation,
7482 pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
7483 },
7484 nextLocation: {
7485 ...nextLocation,
7486 pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
7487 },
7488 historyAction
7489 });
7490 },
7491 [basename, shouldBlock]
7492 );
7493 React3.useEffect(() => {
7494 let key = String(++blockerId);
7495 setBlockerKey(key);
7496 return () => router.deleteBlocker(key);
7497 }, [router]);
7498 React3.useEffect(() => {
7499 if (blockerKey !== "") {
7500 router.getBlocker(blockerKey, blockerFunction);
7501 }
7502 }, [router, blockerKey, blockerFunction]);
7503 return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
7504}
7505function useNavigateStable() {
7506 let { router } = useDataRouterContext("useNavigate" /* UseNavigateStable */);
7507 let id = useCurrentRouteId("useNavigate" /* UseNavigateStable */);
7508 let activeRef = React3.useRef(false);
7509 useIsomorphicLayoutEffect(() => {
7510 activeRef.current = true;
7511 });
7512 let navigate = React3.useCallback(
7513 async (to, options = {}) => {
7514 warning(activeRef.current, navigateEffectWarning);
7515 if (!activeRef.current) return;
7516 if (typeof to === "number") {
7517 await router.navigate(to);
7518 } else {
7519 await router.navigate(to, { fromRouteId: id, ...options });
7520 }
7521 },
7522 [router, id]
7523 );
7524 return navigate;
7525}
7526var alreadyWarned = {};
7527function warningOnce(key, cond, message) {
7528 if (!cond && !alreadyWarned[key]) {
7529 alreadyWarned[key] = true;
7530 warning(false, message);
7531 }
7532}
7533function useRoute(...args) {
7534 const currentRouteId = useCurrentRouteId(
7535 "useRoute" /* UseRoute */
7536 );
7537 const id = _nullishCoalesce(args[0], () => ( currentRouteId));
7538 const state = useDataRouterState("useRoute" /* UseRoute */);
7539 const route = state.matches.find(({ route: route2 }) => route2.id === id);
7540 if (route === void 0) return void 0;
7541 return {
7542 handle: route.route.handle,
7543 loaderData: state.loaderData[id],
7544 actionData: _optionalChain([state, 'access', _102 => _102.actionData, 'optionalAccess', _103 => _103[id]])
7545 };
7546}
7547
7548// lib/dom/ssr/errorBoundaries.tsx
7549
7550
7551// lib/dom/ssr/components.tsx
7552
7553
7554// lib/dom/ssr/routeModules.ts
7555async function loadRouteModule(route, routeModulesCache) {
7556 if (route.id in routeModulesCache) {
7557 return routeModulesCache[route.id];
7558 }
7559 try {
7560 let routeModule = await Promise.resolve().then(() => _interopRequireWildcard(require(
7561 /* @vite-ignore */
7562 /* webpackIgnore: true */
7563 route.module
7564 )));
7565 routeModulesCache[route.id] = routeModule;
7566 return routeModule;
7567 } catch (error) {
7568 console.error(
7569 `Error loading route module \`${route.module}\`, reloading page...`
7570 );
7571 console.error(error);
7572 if (window.__reactRouterContext && window.__reactRouterContext.isSpaMode && // @ts-expect-error
7573 void 0) {
7574 throw error;
7575 }
7576 window.location.reload();
7577 return new Promise(() => {
7578 });
7579 }
7580}
7581
7582// lib/dom/ssr/links.ts
7583function getKeyedLinksForMatches(matches, routeModules, manifest) {
7584 let descriptors = matches.map((match) => {
7585 let module = routeModules[match.route.id];
7586 let route = manifest.routes[match.route.id];
7587 return [
7588 route && route.css ? route.css.map((href) => ({ rel: "stylesheet", href })) : [],
7589 _optionalChain([module, 'optionalAccess', _104 => _104.links, 'optionalCall', _105 => _105()]) || []
7590 ];
7591 }).flat(2);
7592 let preloads = getModuleLinkHrefs(matches, manifest);
7593 return dedupeLinkDescriptors(descriptors, preloads);
7594}
7595function getRouteCssDescriptors(route) {
7596 if (!route.css) return [];
7597 return route.css.map((href) => ({ rel: "stylesheet", href }));
7598}
7599async function prefetchRouteCss(route) {
7600 if (!route.css) return;
7601 let descriptors = getRouteCssDescriptors(route);
7602 await Promise.all(descriptors.map(prefetchStyleLink));
7603}
7604async function prefetchStyleLinks(route, routeModule) {
7605 if (!route.css && !routeModule.links || !isPreloadSupported()) return;
7606 let descriptors = [];
7607 if (route.css) {
7608 descriptors.push(...getRouteCssDescriptors(route));
7609 }
7610 if (routeModule.links) {
7611 descriptors.push(...routeModule.links());
7612 }
7613 if (descriptors.length === 0) return;
7614 let styleLinks = [];
7615 for (let descriptor of descriptors) {
7616 if (!isPageLinkDescriptor(descriptor) && descriptor.rel === "stylesheet") {
7617 styleLinks.push({
7618 ...descriptor,
7619 rel: "preload",
7620 as: "style"
7621 });
7622 }
7623 }
7624 await Promise.all(styleLinks.map(prefetchStyleLink));
7625}
7626async function prefetchStyleLink(descriptor) {
7627 return new Promise((resolve) => {
7628 if (descriptor.media && !window.matchMedia(descriptor.media).matches || document.querySelector(
7629 `link[rel="stylesheet"][href="${descriptor.href}"]`
7630 )) {
7631 return resolve();
7632 }
7633 let link = document.createElement("link");
7634 Object.assign(link, descriptor);
7635 function removeLink() {
7636 if (document.head.contains(link)) {
7637 document.head.removeChild(link);
7638 }
7639 }
7640 link.onload = () => {
7641 removeLink();
7642 resolve();
7643 };
7644 link.onerror = () => {
7645 removeLink();
7646 resolve();
7647 };
7648 document.head.appendChild(link);
7649 });
7650}
7651function isPageLinkDescriptor(object) {
7652 return object != null && typeof object.page === "string";
7653}
7654function isHtmlLinkDescriptor(object) {
7655 if (object == null) {
7656 return false;
7657 }
7658 if (object.href == null) {
7659 return object.rel === "preload" && typeof object.imageSrcSet === "string" && typeof object.imageSizes === "string";
7660 }
7661 return typeof object.rel === "string" && typeof object.href === "string";
7662}
7663async function getKeyedPrefetchLinks(matches, manifest, routeModules) {
7664 let links = await Promise.all(
7665 matches.map(async (match) => {
7666 let route = manifest.routes[match.route.id];
7667 if (route) {
7668 let mod = await loadRouteModule(route, routeModules);
7669 return mod.links ? mod.links() : [];
7670 }
7671 return [];
7672 })
7673 );
7674 return dedupeLinkDescriptors(
7675 links.flat(1).filter(isHtmlLinkDescriptor).filter((link) => link.rel === "stylesheet" || link.rel === "preload").map(
7676 (link) => link.rel === "stylesheet" ? { ...link, rel: "prefetch", as: "style" } : { ...link, rel: "prefetch" }
7677 )
7678 );
7679}
7680function getNewMatchesForLinks(page, nextMatches, currentMatches, manifest, location, mode) {
7681 let isNew = (match, index) => {
7682 if (!currentMatches[index]) return true;
7683 return match.route.id !== currentMatches[index].route.id;
7684 };
7685 let matchPathChanged = (match, index) => {
7686 return (
7687 // param change, /users/123 -> /users/456
7688 currentMatches[index].pathname !== match.pathname || // splat param changed, which is not present in match.path
7689 // e.g. /files/images/avatar.jpg -> files/finances.xls
7690 _optionalChain([currentMatches, 'access', _106 => _106[index], 'access', _107 => _107.route, 'access', _108 => _108.path, 'optionalAccess', _109 => _109.endsWith, 'call', _110 => _110("*")]) && currentMatches[index].params["*"] !== match.params["*"]
7691 );
7692 };
7693 if (mode === "assets") {
7694 return nextMatches.filter(
7695 (match, index) => isNew(match, index) || matchPathChanged(match, index)
7696 );
7697 }
7698 if (mode === "data") {
7699 return nextMatches.filter((match, index) => {
7700 let manifestRoute = manifest.routes[match.route.id];
7701 if (!manifestRoute || !manifestRoute.hasLoader) {
7702 return false;
7703 }
7704 if (isNew(match, index) || matchPathChanged(match, index)) {
7705 return true;
7706 }
7707 if (match.route.shouldRevalidate) {
7708 let routeChoice = match.route.shouldRevalidate({
7709 currentUrl: new URL(
7710 location.pathname + location.search + location.hash,
7711 window.origin
7712 ),
7713 currentParams: _optionalChain([currentMatches, 'access', _111 => _111[0], 'optionalAccess', _112 => _112.params]) || {},
7714 nextUrl: new URL(page, window.origin),
7715 nextParams: match.params,
7716 defaultShouldRevalidate: true
7717 });
7718 if (typeof routeChoice === "boolean") {
7719 return routeChoice;
7720 }
7721 }
7722 return true;
7723 });
7724 }
7725 return [];
7726}
7727function getModuleLinkHrefs(matches, manifest, { includeHydrateFallback } = {}) {
7728 return dedupeHrefs(
7729 matches.map((match) => {
7730 let route = manifest.routes[match.route.id];
7731 if (!route) return [];
7732 let hrefs = [route.module];
7733 if (route.clientActionModule) {
7734 hrefs = hrefs.concat(route.clientActionModule);
7735 }
7736 if (route.clientLoaderModule) {
7737 hrefs = hrefs.concat(route.clientLoaderModule);
7738 }
7739 if (includeHydrateFallback && route.hydrateFallbackModule) {
7740 hrefs = hrefs.concat(route.hydrateFallbackModule);
7741 }
7742 if (route.imports) {
7743 hrefs = hrefs.concat(route.imports);
7744 }
7745 return hrefs;
7746 }).flat(1)
7747 );
7748}
7749function dedupeHrefs(hrefs) {
7750 return [...new Set(hrefs)];
7751}
7752function sortKeys(obj) {
7753 let sorted = {};
7754 let keys = Object.keys(obj).sort();
7755 for (let key of keys) {
7756 sorted[key] = obj[key];
7757 }
7758 return sorted;
7759}
7760function dedupeLinkDescriptors(descriptors, preloads) {
7761 let set = /* @__PURE__ */ new Set();
7762 let preloadsSet = new Set(preloads);
7763 return descriptors.reduce((deduped, descriptor) => {
7764 let alreadyModulePreload = preloads && !isPageLinkDescriptor(descriptor) && descriptor.as === "script" && descriptor.href && preloadsSet.has(descriptor.href);
7765 if (alreadyModulePreload) {
7766 return deduped;
7767 }
7768 let key = JSON.stringify(sortKeys(descriptor));
7769 if (!set.has(key)) {
7770 set.add(key);
7771 deduped.push({ key, link: descriptor });
7772 }
7773 return deduped;
7774 }, []);
7775}
7776var _isPreloadSupported;
7777function isPreloadSupported() {
7778 if (_isPreloadSupported !== void 0) {
7779 return _isPreloadSupported;
7780 }
7781 let el = document.createElement("link");
7782 _isPreloadSupported = el.relList.supports("preload");
7783 el = null;
7784 return _isPreloadSupported;
7785}
7786
7787// lib/server-runtime/warnings.ts
7788var alreadyWarned2 = {};
7789function warnOnce(condition, message) {
7790 if (!condition && !alreadyWarned2[message]) {
7791 alreadyWarned2[message] = true;
7792 console.warn(message);
7793 }
7794}
7795
7796// lib/dom/ssr/fog-of-war.ts
7797
7798
7799// lib/dom/ssr/routes.tsx
7800
7801
7802// lib/dom/ssr/fallback.tsx
7803
7804function RemixRootDefaultHydrateFallback() {
7805 return /* @__PURE__ */ React4.createElement(BoundaryShell, { title: "Loading...", renderScripts: true }, ENABLE_DEV_WARNINGS ? /* @__PURE__ */ React4.createElement(
7806 "script",
7807 {
7808 dangerouslySetInnerHTML: {
7809 __html: `
7810 console.log(
7811 "\u{1F4BF} Hey developer \u{1F44B}. You can provide a way better UX than this " +
7812 "when your app is loading JS modules and/or running \`clientLoader\` " +
7813 "functions. Check out https://reactrouter.com/start/framework/route-module#hydratefallback " +
7814 "for more information."
7815 );
7816 `
7817 }
7818 }
7819 ) : null);
7820}
7821
7822// lib/dom/ssr/routes.tsx
7823function groupRoutesByParentId(manifest) {
7824 let routes = {};
7825 Object.values(manifest).forEach((route) => {
7826 if (route) {
7827 let parentId = route.parentId || "";
7828 if (!routes[parentId]) {
7829 routes[parentId] = [];
7830 }
7831 routes[parentId].push(route);
7832 }
7833 });
7834 return routes;
7835}
7836function getRouteComponents(route, routeModule, isSpaMode) {
7837 let Component4 = getRouteModuleComponent(routeModule);
7838 let HydrateFallback = routeModule.HydrateFallback && (!isSpaMode || route.id === "root") ? routeModule.HydrateFallback : route.id === "root" ? RemixRootDefaultHydrateFallback : void 0;
7839 let ErrorBoundary = routeModule.ErrorBoundary ? routeModule.ErrorBoundary : route.id === "root" ? () => /* @__PURE__ */ React5.createElement(RemixRootDefaultErrorBoundary, { error: useRouteError() }) : void 0;
7840 if (route.id === "root" && routeModule.Layout) {
7841 return {
7842 ...Component4 ? {
7843 element: /* @__PURE__ */ React5.createElement(routeModule.Layout, null, /* @__PURE__ */ React5.createElement(Component4, null))
7844 } : { Component: Component4 },
7845 ...ErrorBoundary ? {
7846 errorElement: /* @__PURE__ */ React5.createElement(routeModule.Layout, null, /* @__PURE__ */ React5.createElement(ErrorBoundary, null))
7847 } : { ErrorBoundary },
7848 ...HydrateFallback ? {
7849 hydrateFallbackElement: /* @__PURE__ */ React5.createElement(routeModule.Layout, null, /* @__PURE__ */ React5.createElement(HydrateFallback, null))
7850 } : { HydrateFallback }
7851 };
7852 }
7853 return { Component: Component4, ErrorBoundary, HydrateFallback };
7854}
7855function createServerRoutes(manifest, routeModules, future, isSpaMode, parentId = "", routesByParentId = groupRoutesByParentId(manifest), spaModeLazyPromise = Promise.resolve({ Component: () => null })) {
7856 return (routesByParentId[parentId] || []).map((route) => {
7857 let routeModule = routeModules[route.id];
7858 invariant2(
7859 routeModule,
7860 "No `routeModule` available to create server routes"
7861 );
7862 let dataRoute = {
7863 ...getRouteComponents(route, routeModule, isSpaMode),
7864 caseSensitive: route.caseSensitive,
7865 id: route.id,
7866 index: route.index,
7867 path: route.path,
7868 handle: routeModule.handle,
7869 // For SPA Mode, all routes are lazy except root. However we tell the
7870 // router root is also lazy here too since we don't need a full
7871 // implementation - we just need a `lazy` prop to tell the RR rendering
7872 // where to stop which is always at the root route in SPA mode
7873 lazy: isSpaMode ? () => spaModeLazyPromise : void 0,
7874 // For partial hydration rendering, we need to indicate when the route
7875 // has a loader/clientLoader, but it won't ever be called during the static
7876 // render, so just give it a no-op function so we can render down to the
7877 // proper fallback
7878 loader: route.hasLoader || route.hasClientLoader ? () => null : void 0
7879 // We don't need middleware/action/shouldRevalidate on these routes since
7880 // they're for a static render
7881 };
7882 let children = createServerRoutes(
7883 manifest,
7884 routeModules,
7885 future,
7886 isSpaMode,
7887 route.id,
7888 routesByParentId,
7889 spaModeLazyPromise
7890 );
7891 if (children.length > 0) dataRoute.children = children;
7892 return dataRoute;
7893 });
7894}
7895function createClientRoutesWithHMRRevalidationOptOut(needsRevalidation, manifest, routeModulesCache, initialState, ssr, isSpaMode) {
7896 return createClientRoutes(
7897 manifest,
7898 routeModulesCache,
7899 initialState,
7900 ssr,
7901 isSpaMode,
7902 "",
7903 groupRoutesByParentId(manifest),
7904 needsRevalidation
7905 );
7906}
7907function preventInvalidServerHandlerCall(type, route) {
7908 if (type === "loader" && !route.hasLoader || type === "action" && !route.hasAction) {
7909 let fn = type === "action" ? "serverAction()" : "serverLoader()";
7910 let msg = `You are trying to call ${fn} on a route that does not have a server ${type} (routeId: "${route.id}")`;
7911 console.error(msg);
7912 throw new ErrorResponseImpl(400, "Bad Request", new Error(msg), true);
7913 }
7914}
7915function noActionDefinedError(type, routeId) {
7916 let article = type === "clientAction" ? "a" : "an";
7917 let msg = `Route "${routeId}" does not have ${article} ${type}, but you are trying to submit to it. To fix this, please add ${article} \`${type}\` function to the route`;
7918 console.error(msg);
7919 throw new ErrorResponseImpl(405, "Method Not Allowed", new Error(msg), true);
7920}
7921function createClientRoutes(manifest, routeModulesCache, initialState, ssr, isSpaMode, parentId = "", routesByParentId = groupRoutesByParentId(manifest), needsRevalidation) {
7922 return (routesByParentId[parentId] || []).map((route) => {
7923 let routeModule = routeModulesCache[route.id];
7924 function fetchServerHandler(singleFetch) {
7925 invariant2(
7926 typeof singleFetch === "function",
7927 "No single fetch function available for route handler"
7928 );
7929 return singleFetch();
7930 }
7931 function fetchServerLoader(singleFetch) {
7932 if (!route.hasLoader) return Promise.resolve(null);
7933 return fetchServerHandler(singleFetch);
7934 }
7935 function fetchServerAction(singleFetch) {
7936 if (!route.hasAction) {
7937 throw noActionDefinedError("action", route.id);
7938 }
7939 return fetchServerHandler(singleFetch);
7940 }
7941 function prefetchModule(modulePath) {
7942 Promise.resolve().then(() => _interopRequireWildcard(require(
7943 /* @vite-ignore */
7944 /* webpackIgnore: true */
7945 modulePath
7946 )));
7947 }
7948 function prefetchRouteModuleChunks(route2) {
7949 if (route2.clientActionModule) {
7950 prefetchModule(route2.clientActionModule);
7951 }
7952 if (route2.clientLoaderModule) {
7953 prefetchModule(route2.clientLoaderModule);
7954 }
7955 }
7956 async function prefetchStylesAndCallHandler(handler) {
7957 let cachedModule = routeModulesCache[route.id];
7958 let linkPrefetchPromise = cachedModule ? prefetchStyleLinks(route, cachedModule) : Promise.resolve();
7959 try {
7960 return handler();
7961 } finally {
7962 await linkPrefetchPromise;
7963 }
7964 }
7965 let dataRoute = {
7966 id: route.id,
7967 index: route.index,
7968 path: route.path
7969 };
7970 if (routeModule) {
7971 Object.assign(dataRoute, {
7972 ...dataRoute,
7973 ...getRouteComponents(route, routeModule, isSpaMode),
7974 middleware: routeModule.clientMiddleware,
7975 handle: routeModule.handle,
7976 shouldRevalidate: getShouldRevalidateFunction(
7977 dataRoute.path,
7978 routeModule,
7979 route,
7980 ssr,
7981 needsRevalidation
7982 )
7983 });
7984 let hasInitialData = initialState && initialState.loaderData && route.id in initialState.loaderData;
7985 let initialData = hasInitialData ? _optionalChain([initialState, 'optionalAccess', _113 => _113.loaderData, 'optionalAccess', _114 => _114[route.id]]) : void 0;
7986 let hasInitialError = initialState && initialState.errors && route.id in initialState.errors;
7987 let initialError = hasInitialError ? _optionalChain([initialState, 'optionalAccess', _115 => _115.errors, 'optionalAccess', _116 => _116[route.id]]) : void 0;
7988 let isHydrationRequest = needsRevalidation == null && (_optionalChain([routeModule, 'access', _117 => _117.clientLoader, 'optionalAccess', _118 => _118.hydrate]) === true || !route.hasLoader);
7989 dataRoute.loader = async ({
7990 request,
7991 params,
7992 context,
7993 unstable_pattern,
7994 unstable_url
7995 }, singleFetch) => {
7996 try {
7997 let result = await prefetchStylesAndCallHandler(async () => {
7998 invariant2(
7999 routeModule,
8000 "No `routeModule` available for critical-route loader"
8001 );
8002 if (!routeModule.clientLoader) {
8003 return fetchServerLoader(singleFetch);
8004 }
8005 return routeModule.clientLoader({
8006 request,
8007 params,
8008 context,
8009 unstable_pattern,
8010 unstable_url,
8011 async serverLoader() {
8012 preventInvalidServerHandlerCall("loader", route);
8013 if (isHydrationRequest) {
8014 if (hasInitialData) {
8015 return initialData;
8016 }
8017 if (hasInitialError) {
8018 throw initialError;
8019 }
8020 }
8021 return fetchServerLoader(singleFetch);
8022 }
8023 });
8024 });
8025 return result;
8026 } finally {
8027 isHydrationRequest = false;
8028 }
8029 };
8030 dataRoute.loader.hydrate = shouldHydrateRouteLoader(
8031 route.id,
8032 routeModule.clientLoader,
8033 route.hasLoader,
8034 isSpaMode
8035 );
8036 dataRoute.action = ({
8037 request,
8038 params,
8039 context,
8040 unstable_pattern,
8041 unstable_url
8042 }, singleFetch) => {
8043 return prefetchStylesAndCallHandler(async () => {
8044 invariant2(
8045 routeModule,
8046 "No `routeModule` available for critical-route action"
8047 );
8048 if (!routeModule.clientAction) {
8049 if (isSpaMode) {
8050 throw noActionDefinedError("clientAction", route.id);
8051 }
8052 return fetchServerAction(singleFetch);
8053 }
8054 return routeModule.clientAction({
8055 request,
8056 params,
8057 context,
8058 unstable_pattern,
8059 unstable_url,
8060 async serverAction() {
8061 preventInvalidServerHandlerCall("action", route);
8062 return fetchServerAction(singleFetch);
8063 }
8064 });
8065 });
8066 };
8067 } else {
8068 if (!route.hasClientLoader) {
8069 dataRoute.loader = (_, singleFetch) => prefetchStylesAndCallHandler(() => {
8070 return fetchServerLoader(singleFetch);
8071 });
8072 }
8073 if (!route.hasClientAction) {
8074 dataRoute.action = (_, singleFetch) => prefetchStylesAndCallHandler(() => {
8075 if (isSpaMode) {
8076 throw noActionDefinedError("clientAction", route.id);
8077 }
8078 return fetchServerAction(singleFetch);
8079 });
8080 }
8081 let lazyRoutePromise;
8082 async function getLazyRoute() {
8083 if (lazyRoutePromise) {
8084 return await lazyRoutePromise;
8085 }
8086 lazyRoutePromise = (async () => {
8087 if (route.clientLoaderModule || route.clientActionModule) {
8088 await new Promise((resolve) => setTimeout(resolve, 0));
8089 }
8090 let routeModulePromise = loadRouteModuleWithBlockingLinks(
8091 route,
8092 routeModulesCache
8093 );
8094 prefetchRouteModuleChunks(route);
8095 return await routeModulePromise;
8096 })();
8097 return await lazyRoutePromise;
8098 }
8099 dataRoute.lazy = {
8100 loader: route.hasClientLoader ? async () => {
8101 let { clientLoader } = route.clientLoaderModule ? await Promise.resolve().then(() => _interopRequireWildcard(require(
8102 /* @vite-ignore */
8103 /* webpackIgnore: true */
8104 route.clientLoaderModule
8105 ))) : await getLazyRoute();
8106 invariant2(clientLoader, "No `clientLoader` export found");
8107 return (args, singleFetch) => clientLoader({
8108 ...args,
8109 async serverLoader() {
8110 preventInvalidServerHandlerCall("loader", route);
8111 return fetchServerLoader(singleFetch);
8112 }
8113 });
8114 } : void 0,
8115 action: route.hasClientAction ? async () => {
8116 let clientActionPromise = route.clientActionModule ? Promise.resolve().then(() => _interopRequireWildcard(require(
8117 /* @vite-ignore */
8118 /* webpackIgnore: true */
8119 route.clientActionModule
8120 ))) : getLazyRoute();
8121 prefetchRouteModuleChunks(route);
8122 let { clientAction } = await clientActionPromise;
8123 invariant2(clientAction, "No `clientAction` export found");
8124 return (args, singleFetch) => clientAction({
8125 ...args,
8126 async serverAction() {
8127 preventInvalidServerHandlerCall("action", route);
8128 return fetchServerAction(singleFetch);
8129 }
8130 });
8131 } : void 0,
8132 middleware: route.hasClientMiddleware ? async () => {
8133 let { clientMiddleware } = route.clientMiddlewareModule ? await Promise.resolve().then(() => _interopRequireWildcard(require(
8134 /* @vite-ignore */
8135 /* webpackIgnore: true */
8136 route.clientMiddlewareModule
8137 ))) : await getLazyRoute();
8138 invariant2(clientMiddleware, "No `clientMiddleware` export found");
8139 return clientMiddleware;
8140 } : void 0,
8141 shouldRevalidate: async () => {
8142 let lazyRoute = await getLazyRoute();
8143 return getShouldRevalidateFunction(
8144 dataRoute.path,
8145 lazyRoute,
8146 route,
8147 ssr,
8148 needsRevalidation
8149 );
8150 },
8151 handle: async () => (await getLazyRoute()).handle,
8152 // No need to wrap these in layout since the root route is never
8153 // loaded via route.lazy()
8154 Component: async () => (await getLazyRoute()).Component,
8155 ErrorBoundary: route.hasErrorBoundary ? async () => (await getLazyRoute()).ErrorBoundary : void 0
8156 };
8157 }
8158 let children = createClientRoutes(
8159 manifest,
8160 routeModulesCache,
8161 initialState,
8162 ssr,
8163 isSpaMode,
8164 route.id,
8165 routesByParentId,
8166 needsRevalidation
8167 );
8168 if (children.length > 0) dataRoute.children = children;
8169 return dataRoute;
8170 });
8171}
8172function getShouldRevalidateFunction(path, route, manifestRoute, ssr, needsRevalidation) {
8173 if (needsRevalidation) {
8174 return wrapShouldRevalidateForHdr(
8175 manifestRoute.id,
8176 route.shouldRevalidate,
8177 needsRevalidation
8178 );
8179 }
8180 if (!ssr && manifestRoute.hasLoader && !manifestRoute.hasClientLoader) {
8181 let myParams = path ? compilePath(path)[1].map((p) => p.paramName) : [];
8182 const didParamsChange = (opts) => myParams.some((p) => opts.currentParams[p] !== opts.nextParams[p]);
8183 if (route.shouldRevalidate) {
8184 let fn = route.shouldRevalidate;
8185 return (opts) => fn({
8186 ...opts,
8187 defaultShouldRevalidate: didParamsChange(opts)
8188 });
8189 } else {
8190 return (opts) => didParamsChange(opts);
8191 }
8192 }
8193 return route.shouldRevalidate;
8194}
8195function wrapShouldRevalidateForHdr(routeId, routeShouldRevalidate, needsRevalidation) {
8196 let handledRevalidation = false;
8197 return (arg) => {
8198 if (!handledRevalidation) {
8199 handledRevalidation = true;
8200 return needsRevalidation.has(routeId);
8201 }
8202 return routeShouldRevalidate ? routeShouldRevalidate(arg) : arg.defaultShouldRevalidate;
8203 };
8204}
8205async function loadRouteModuleWithBlockingLinks(route, routeModules) {
8206 let routeModulePromise = loadRouteModule(route, routeModules);
8207 let prefetchRouteCssPromise = prefetchRouteCss(route);
8208 let routeModule = await routeModulePromise;
8209 await Promise.all([
8210 prefetchRouteCssPromise,
8211 prefetchStyleLinks(route, routeModule)
8212 ]);
8213 return {
8214 Component: getRouteModuleComponent(routeModule),
8215 ErrorBoundary: routeModule.ErrorBoundary,
8216 clientMiddleware: routeModule.clientMiddleware,
8217 clientAction: routeModule.clientAction,
8218 clientLoader: routeModule.clientLoader,
8219 handle: routeModule.handle,
8220 links: routeModule.links,
8221 meta: routeModule.meta,
8222 shouldRevalidate: routeModule.shouldRevalidate
8223 };
8224}
8225function getRouteModuleComponent(routeModule) {
8226 if (routeModule.default == null) return void 0;
8227 let isEmptyObject = typeof routeModule.default === "object" && Object.keys(routeModule.default).length === 0;
8228 if (!isEmptyObject) {
8229 return routeModule.default;
8230 }
8231}
8232function shouldHydrateRouteLoader(routeId, clientLoader, hasLoader, isSpaMode) {
8233 return isSpaMode && routeId !== "root" || clientLoader != null && (clientLoader.hydrate === true || hasLoader !== true);
8234}
8235
8236// lib/dom/ssr/fog-of-war.ts
8237var nextPaths = /* @__PURE__ */ new Set();
8238var discoveredPathsMaxSize = 1e3;
8239var discoveredPaths = /* @__PURE__ */ new Set();
8240var URL_LIMIT = 7680;
8241function isFogOfWarEnabled(routeDiscovery, ssr) {
8242 return routeDiscovery.mode === "lazy" && ssr === true;
8243}
8244function getPartialManifest({ sri, ...manifest }, router) {
8245 let routeIds = new Set(router.state.matches.map((m) => m.route.id));
8246 let segments = router.state.location.pathname.split("/").filter(Boolean);
8247 let paths = ["/"];
8248 segments.pop();
8249 while (segments.length > 0) {
8250 paths.push(`/${segments.join("/")}`);
8251 segments.pop();
8252 }
8253 paths.forEach((path) => {
8254 let matches = matchRoutes(router.routes, path, router.basename);
8255 if (matches) {
8256 matches.forEach((m) => routeIds.add(m.route.id));
8257 }
8258 });
8259 let initialRoutes = [...routeIds].reduce(
8260 (acc, id) => Object.assign(acc, { [id]: manifest.routes[id] }),
8261 {}
8262 );
8263 return {
8264 ...manifest,
8265 routes: initialRoutes,
8266 sri: sri ? true : void 0
8267 };
8268}
8269function getPatchRoutesOnNavigationFunction(getRouter, manifest, routeModules, ssr, routeDiscovery, isSpaMode, basename) {
8270 if (!isFogOfWarEnabled(routeDiscovery, ssr)) {
8271 return void 0;
8272 }
8273 return async ({ path, patch, signal, fetcherKey }) => {
8274 if (discoveredPaths.has(path)) {
8275 return;
8276 }
8277 let { state } = getRouter();
8278 await fetchAndApplyManifestPatches(
8279 [path],
8280 // If we're patching for a fetcher call, reload the current location
8281 // Otherwise prefer any ongoing navigation location
8282 fetcherKey ? window.location.href : createPath(state.navigation.location || state.location),
8283 manifest,
8284 routeModules,
8285 ssr,
8286 isSpaMode,
8287 basename,
8288 routeDiscovery.manifestPath,
8289 patch,
8290 signal
8291 );
8292 };
8293}
8294function useFogOFWarDiscovery(router, manifest, routeModules, ssr, routeDiscovery, isSpaMode) {
8295 React6.useEffect(() => {
8296 if (!isFogOfWarEnabled(routeDiscovery, ssr) || // @ts-expect-error - TS doesn't know about this yet
8297 _optionalChain([window, 'access', _119 => _119.navigator, 'optionalAccess', _120 => _120.connection, 'optionalAccess', _121 => _121.saveData]) === true) {
8298 return;
8299 }
8300 function registerElement(el) {
8301 let path = el.tagName === "FORM" ? el.getAttribute("action") : el.getAttribute("href");
8302 if (!path) {
8303 return;
8304 }
8305 let pathname = el.tagName === "A" ? el.pathname : new URL(path, window.location.origin).pathname;
8306 if (!discoveredPaths.has(pathname)) {
8307 nextPaths.add(pathname);
8308 }
8309 }
8310 async function fetchPatches() {
8311 document.querySelectorAll("a[data-discover], form[data-discover]").forEach(registerElement);
8312 let lazyPaths = Array.from(nextPaths.keys()).filter((path) => {
8313 if (discoveredPaths.has(path)) {
8314 nextPaths.delete(path);
8315 return false;
8316 }
8317 return true;
8318 });
8319 if (lazyPaths.length === 0) {
8320 return;
8321 }
8322 try {
8323 await fetchAndApplyManifestPatches(
8324 lazyPaths,
8325 null,
8326 manifest,
8327 routeModules,
8328 ssr,
8329 isSpaMode,
8330 router.basename,
8331 routeDiscovery.manifestPath,
8332 router.patchRoutes
8333 );
8334 } catch (e) {
8335 console.error("Failed to fetch manifest patches", e);
8336 }
8337 }
8338 let debouncedFetchPatches = debounce(fetchPatches, 100);
8339 fetchPatches();
8340 let observer = new MutationObserver(() => debouncedFetchPatches());
8341 observer.observe(document.documentElement, {
8342 subtree: true,
8343 childList: true,
8344 attributes: true,
8345 attributeFilter: ["data-discover", "href", "action"]
8346 });
8347 return () => observer.disconnect();
8348 }, [ssr, isSpaMode, manifest, routeModules, router, routeDiscovery]);
8349}
8350function getManifestPath(_manifestPath, basename) {
8351 let manifestPath = _manifestPath || "/__manifest";
8352 return basename == null ? manifestPath : joinPaths([basename, manifestPath]);
8353}
8354var MANIFEST_VERSION_STORAGE_KEY = "react-router-manifest-version";
8355async function fetchAndApplyManifestPatches(paths, errorReloadPath, manifest, routeModules, ssr, isSpaMode, basename, manifestPath, patchRoutes, signal) {
8356 const searchParams = new URLSearchParams();
8357 searchParams.set("paths", paths.sort().join(","));
8358 searchParams.set("version", manifest.version);
8359 let url = new URL(
8360 getManifestPath(manifestPath, basename),
8361 window.location.origin
8362 );
8363 url.search = searchParams.toString();
8364 if (url.toString().length > URL_LIMIT) {
8365 nextPaths.clear();
8366 return;
8367 }
8368 let serverPatches;
8369 try {
8370 let res = await fetch(url, { signal });
8371 if (!res.ok) {
8372 throw new Error(`${res.status} ${res.statusText}`);
8373 } else if (res.status === 204 && res.headers.has("X-Remix-Reload-Document")) {
8374 if (!errorReloadPath) {
8375 console.warn(
8376 "Detected a manifest version mismatch during eager route discovery. The next navigation/fetch to an undiscovered route will result in a new document navigation to sync up with the latest manifest."
8377 );
8378 return;
8379 }
8380 try {
8381 if (sessionStorage.getItem(MANIFEST_VERSION_STORAGE_KEY) === manifest.version) {
8382 console.error(
8383 "Unable to discover routes due to manifest version mismatch."
8384 );
8385 return;
8386 }
8387 sessionStorage.setItem(MANIFEST_VERSION_STORAGE_KEY, manifest.version);
8388 } catch (e4) {
8389 }
8390 window.location.href = errorReloadPath;
8391 console.warn("Detected manifest version mismatch, reloading...");
8392 await new Promise(() => {
8393 });
8394 } else if (res.status >= 400) {
8395 throw new Error(await res.text());
8396 }
8397 try {
8398 sessionStorage.removeItem(MANIFEST_VERSION_STORAGE_KEY);
8399 } catch (e5) {
8400 }
8401 serverPatches = await res.json();
8402 } catch (e) {
8403 if (_optionalChain([signal, 'optionalAccess', _122 => _122.aborted])) return;
8404 throw e;
8405 }
8406 let knownRoutes = new Set(Object.keys(manifest.routes));
8407 let patches = Object.values(serverPatches).reduce((acc, route) => {
8408 if (route && !knownRoutes.has(route.id)) {
8409 acc[route.id] = route;
8410 }
8411 return acc;
8412 }, {});
8413 Object.assign(manifest.routes, patches);
8414 paths.forEach((p) => addToFifoQueue(p, discoveredPaths));
8415 let parentIds = /* @__PURE__ */ new Set();
8416 Object.values(patches).forEach((patch) => {
8417 if (patch && (!patch.parentId || !patches[patch.parentId])) {
8418 parentIds.add(patch.parentId);
8419 }
8420 });
8421 parentIds.forEach(
8422 (parentId) => patchRoutes(
8423 parentId || null,
8424 createClientRoutes(patches, routeModules, null, ssr, isSpaMode, parentId)
8425 )
8426 );
8427}
8428function addToFifoQueue(path, queue) {
8429 if (queue.size >= discoveredPathsMaxSize) {
8430 let first = queue.values().next().value;
8431 queue.delete(first);
8432 }
8433 queue.add(path);
8434}
8435function debounce(callback, wait) {
8436 let timeoutId;
8437 return (...args) => {
8438 window.clearTimeout(timeoutId);
8439 timeoutId = window.setTimeout(() => callback(...args), wait);
8440 };
8441}
8442
8443// lib/dom/ssr/components.tsx
8444function useDataRouterContext2() {
8445 let context = React7.useContext(DataRouterContext);
8446 invariant2(
8447 context,
8448 "You must render this element inside a <DataRouterContext.Provider> element"
8449 );
8450 return context;
8451}
8452function useDataRouterStateContext() {
8453 let context = React7.useContext(DataRouterStateContext);
8454 invariant2(
8455 context,
8456 "You must render this element inside a <DataRouterStateContext.Provider> element"
8457 );
8458 return context;
8459}
8460var FrameworkContext = React7.createContext(void 0);
8461FrameworkContext.displayName = "FrameworkContext";
8462function useFrameworkContext() {
8463 let context = React7.useContext(FrameworkContext);
8464 invariant2(
8465 context,
8466 "You must render this element inside a <HydratedRouter> element"
8467 );
8468 return context;
8469}
8470function usePrefetchBehavior(prefetch, theirElementProps) {
8471 let frameworkContext = React7.useContext(FrameworkContext);
8472 let [maybePrefetch, setMaybePrefetch] = React7.useState(false);
8473 let [shouldPrefetch, setShouldPrefetch] = React7.useState(false);
8474 let { onFocus, onBlur, onMouseEnter, onMouseLeave, onTouchStart } = theirElementProps;
8475 let ref = React7.useRef(null);
8476 React7.useEffect(() => {
8477 if (prefetch === "render") {
8478 setShouldPrefetch(true);
8479 }
8480 if (prefetch === "viewport") {
8481 let callback = (entries) => {
8482 entries.forEach((entry) => {
8483 setShouldPrefetch(entry.isIntersecting);
8484 });
8485 };
8486 let observer = new IntersectionObserver(callback, { threshold: 0.5 });
8487 if (ref.current) observer.observe(ref.current);
8488 return () => {
8489 observer.disconnect();
8490 };
8491 }
8492 }, [prefetch]);
8493 React7.useEffect(() => {
8494 if (maybePrefetch) {
8495 let id = setTimeout(() => {
8496 setShouldPrefetch(true);
8497 }, 100);
8498 return () => {
8499 clearTimeout(id);
8500 };
8501 }
8502 }, [maybePrefetch]);
8503 let setIntent = () => {
8504 setMaybePrefetch(true);
8505 };
8506 let cancelIntent = () => {
8507 setMaybePrefetch(false);
8508 setShouldPrefetch(false);
8509 };
8510 if (!frameworkContext) {
8511 return [false, ref, {}];
8512 }
8513 if (prefetch !== "intent") {
8514 return [shouldPrefetch, ref, {}];
8515 }
8516 return [
8517 shouldPrefetch,
8518 ref,
8519 {
8520 onFocus: composeEventHandlers(onFocus, setIntent),
8521 onBlur: composeEventHandlers(onBlur, cancelIntent),
8522 onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),
8523 onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),
8524 onTouchStart: composeEventHandlers(onTouchStart, setIntent)
8525 }
8526 ];
8527}
8528function composeEventHandlers(theirHandler, ourHandler) {
8529 return (event) => {
8530 theirHandler && theirHandler(event);
8531 if (!event.defaultPrevented) {
8532 ourHandler(event);
8533 }
8534 };
8535}
8536function getActiveMatches(matches, errors, isSpaMode) {
8537 if (isSpaMode && !isHydrated) {
8538 return [matches[0]];
8539 }
8540 if (errors) {
8541 let errorIdx = matches.findIndex((m) => errors[m.route.id] !== void 0);
8542 return matches.slice(0, errorIdx + 1);
8543 }
8544 return matches;
8545}
8546var CRITICAL_CSS_DATA_ATTRIBUTE = "data-react-router-critical-css";
8547function Links({ nonce, crossOrigin }) {
8548 let { isSpaMode, manifest, routeModules, criticalCss } = useFrameworkContext();
8549 let { errors, matches: routerMatches } = useDataRouterStateContext();
8550 let matches = getActiveMatches(routerMatches, errors, isSpaMode);
8551 let keyedLinks = React7.useMemo(
8552 () => getKeyedLinksForMatches(matches, routeModules, manifest),
8553 [matches, routeModules, manifest]
8554 );
8555 return /* @__PURE__ */ React7.createElement(React7.Fragment, null, typeof criticalCss === "string" ? /* @__PURE__ */ React7.createElement(
8556 "style",
8557 {
8558 ...{ [CRITICAL_CSS_DATA_ATTRIBUTE]: "" },
8559 nonce,
8560 dangerouslySetInnerHTML: { __html: criticalCss }
8561 }
8562 ) : null, typeof criticalCss === "object" ? /* @__PURE__ */ React7.createElement(
8563 "link",
8564 {
8565 ...{ [CRITICAL_CSS_DATA_ATTRIBUTE]: "" },
8566 rel: "stylesheet",
8567 href: criticalCss.href,
8568 nonce,
8569 crossOrigin
8570 }
8571 ) : null, keyedLinks.map(
8572 ({ key, link }) => isPageLinkDescriptor(link) ? /* @__PURE__ */ React7.createElement(
8573 PrefetchPageLinks,
8574 {
8575 key,
8576 nonce,
8577 ...link,
8578 crossOrigin: _nullishCoalesce(link.crossOrigin, () => ( crossOrigin))
8579 }
8580 ) : /* @__PURE__ */ React7.createElement(
8581 "link",
8582 {
8583 key,
8584 nonce,
8585 ...link,
8586 crossOrigin: _nullishCoalesce(link.crossOrigin, () => ( crossOrigin))
8587 }
8588 )
8589 ));
8590}
8591function PrefetchPageLinks({ page, ...linkProps }) {
8592 let rsc = useIsRSCRouterContext();
8593 let { router } = useDataRouterContext2();
8594 let matches = React7.useMemo(
8595 () => matchRoutes(router.routes, page, router.basename),
8596 [router.routes, page, router.basename]
8597 );
8598 if (!matches) {
8599 return null;
8600 }
8601 if (rsc) {
8602 return /* @__PURE__ */ React7.createElement(RSCPrefetchPageLinksImpl, { page, matches, ...linkProps });
8603 }
8604 return /* @__PURE__ */ React7.createElement(PrefetchPageLinksImpl, { page, matches, ...linkProps });
8605}
8606function useKeyedPrefetchLinks(matches) {
8607 let { manifest, routeModules } = useFrameworkContext();
8608 let [keyedPrefetchLinks, setKeyedPrefetchLinks] = React7.useState([]);
8609 React7.useEffect(() => {
8610 let interrupted = false;
8611 void getKeyedPrefetchLinks(matches, manifest, routeModules).then(
8612 (links) => {
8613 if (!interrupted) {
8614 setKeyedPrefetchLinks(links);
8615 }
8616 }
8617 );
8618 return () => {
8619 interrupted = true;
8620 };
8621 }, [matches, manifest, routeModules]);
8622 return keyedPrefetchLinks;
8623}
8624function RSCPrefetchPageLinksImpl({
8625 page,
8626 matches: nextMatches,
8627 ...linkProps
8628}) {
8629 let location = useLocation();
8630 let { future } = useFrameworkContext();
8631 let { basename } = useDataRouterContext2();
8632 let dataHrefs = React7.useMemo(() => {
8633 if (page === location.pathname + location.search + location.hash) {
8634 return [];
8635 }
8636 let url = singleFetchUrl(
8637 page,
8638 basename,
8639 future.unstable_trailingSlashAwareDataRequests,
8640 "rsc"
8641 );
8642 let hasSomeRoutesWithShouldRevalidate = false;
8643 let targetRoutes = [];
8644 for (let match of nextMatches) {
8645 if (typeof match.route.shouldRevalidate === "function") {
8646 hasSomeRoutesWithShouldRevalidate = true;
8647 } else {
8648 targetRoutes.push(match.route.id);
8649 }
8650 }
8651 if (hasSomeRoutesWithShouldRevalidate && targetRoutes.length > 0) {
8652 url.searchParams.set("_routes", targetRoutes.join(","));
8653 }
8654 return [url.pathname + url.search];
8655 }, [
8656 basename,
8657 future.unstable_trailingSlashAwareDataRequests,
8658 page,
8659 location,
8660 nextMatches
8661 ]);
8662 return /* @__PURE__ */ React7.createElement(React7.Fragment, null, dataHrefs.map((href) => /* @__PURE__ */ React7.createElement("link", { key: href, rel: "prefetch", as: "fetch", href, ...linkProps })));
8663}
8664function PrefetchPageLinksImpl({
8665 page,
8666 matches: nextMatches,
8667 ...linkProps
8668}) {
8669 let location = useLocation();
8670 let { future, manifest, routeModules } = useFrameworkContext();
8671 let { basename } = useDataRouterContext2();
8672 let { loaderData, matches } = useDataRouterStateContext();
8673 let newMatchesForData = React7.useMemo(
8674 () => getNewMatchesForLinks(
8675 page,
8676 nextMatches,
8677 matches,
8678 manifest,
8679 location,
8680 "data"
8681 ),
8682 [page, nextMatches, matches, manifest, location]
8683 );
8684 let newMatchesForAssets = React7.useMemo(
8685 () => getNewMatchesForLinks(
8686 page,
8687 nextMatches,
8688 matches,
8689 manifest,
8690 location,
8691 "assets"
8692 ),
8693 [page, nextMatches, matches, manifest, location]
8694 );
8695 let dataHrefs = React7.useMemo(() => {
8696 if (page === location.pathname + location.search + location.hash) {
8697 return [];
8698 }
8699 let routesParams = /* @__PURE__ */ new Set();
8700 let foundOptOutRoute = false;
8701 nextMatches.forEach((m) => {
8702 let manifestRoute = manifest.routes[m.route.id];
8703 if (!manifestRoute || !manifestRoute.hasLoader) {
8704 return;
8705 }
8706 if (!newMatchesForData.some((m2) => m2.route.id === m.route.id) && m.route.id in loaderData && _optionalChain([routeModules, 'access', _123 => _123[m.route.id], 'optionalAccess', _124 => _124.shouldRevalidate])) {
8707 foundOptOutRoute = true;
8708 } else if (manifestRoute.hasClientLoader) {
8709 foundOptOutRoute = true;
8710 } else {
8711 routesParams.add(m.route.id);
8712 }
8713 });
8714 if (routesParams.size === 0) {
8715 return [];
8716 }
8717 let url = singleFetchUrl(
8718 page,
8719 basename,
8720 future.unstable_trailingSlashAwareDataRequests,
8721 "data"
8722 );
8723 if (foundOptOutRoute && routesParams.size > 0) {
8724 url.searchParams.set(
8725 "_routes",
8726 nextMatches.filter((m) => routesParams.has(m.route.id)).map((m) => m.route.id).join(",")
8727 );
8728 }
8729 return [url.pathname + url.search];
8730 }, [
8731 basename,
8732 future.unstable_trailingSlashAwareDataRequests,
8733 loaderData,
8734 location,
8735 manifest,
8736 newMatchesForData,
8737 nextMatches,
8738 page,
8739 routeModules
8740 ]);
8741 let moduleHrefs = React7.useMemo(
8742 () => getModuleLinkHrefs(newMatchesForAssets, manifest),
8743 [newMatchesForAssets, manifest]
8744 );
8745 let keyedPrefetchLinks = useKeyedPrefetchLinks(newMatchesForAssets);
8746 return /* @__PURE__ */ React7.createElement(React7.Fragment, null, dataHrefs.map((href) => /* @__PURE__ */ React7.createElement("link", { key: href, rel: "prefetch", as: "fetch", href, ...linkProps })), moduleHrefs.map((href) => /* @__PURE__ */ React7.createElement("link", { key: href, rel: "modulepreload", href, ...linkProps })), keyedPrefetchLinks.map(({ key, link }) => (
8747 // these don't spread `linkProps` because they are full link descriptors
8748 // already with their own props
8749 /* @__PURE__ */ React7.createElement(
8750 "link",
8751 {
8752 key,
8753 nonce: linkProps.nonce,
8754 ...link,
8755 crossOrigin: _nullishCoalesce(link.crossOrigin, () => ( linkProps.crossOrigin))
8756 }
8757 )
8758 )));
8759}
8760function Meta() {
8761 let { isSpaMode, routeModules } = useFrameworkContext();
8762 let {
8763 errors,
8764 matches: routerMatches,
8765 loaderData
8766 } = useDataRouterStateContext();
8767 let location = useLocation();
8768 let _matches = getActiveMatches(routerMatches, errors, isSpaMode);
8769 let error = null;
8770 if (errors) {
8771 error = errors[_matches[_matches.length - 1].route.id];
8772 }
8773 let meta = [];
8774 let leafMeta = null;
8775 let matches = [];
8776 for (let i = 0; i < _matches.length; i++) {
8777 let _match = _matches[i];
8778 let routeId = _match.route.id;
8779 let data2 = loaderData[routeId];
8780 let params = _match.params;
8781 let routeModule = routeModules[routeId];
8782 let routeMeta = [];
8783 let match = {
8784 id: routeId,
8785 data: data2,
8786 loaderData: data2,
8787 meta: [],
8788 params: _match.params,
8789 pathname: _match.pathname,
8790 handle: _match.route.handle,
8791 error
8792 };
8793 matches[i] = match;
8794 if (_optionalChain([routeModule, 'optionalAccess', _125 => _125.meta])) {
8795 routeMeta = typeof routeModule.meta === "function" ? routeModule.meta({
8796 data: data2,
8797 loaderData: data2,
8798 params,
8799 location,
8800 matches,
8801 error
8802 }) : Array.isArray(routeModule.meta) ? [...routeModule.meta] : routeModule.meta;
8803 } else if (leafMeta) {
8804 routeMeta = [...leafMeta];
8805 }
8806 routeMeta = routeMeta || [];
8807 if (!Array.isArray(routeMeta)) {
8808 throw new Error(
8809 "The route at " + _match.route.path + " returns an invalid value. All route meta functions must return an array of meta objects.\n\nTo reference the meta function API, see https://reactrouter.com/start/framework/route-module#meta"
8810 );
8811 }
8812 match.meta = routeMeta;
8813 matches[i] = match;
8814 meta = [...routeMeta];
8815 leafMeta = meta;
8816 }
8817 return /* @__PURE__ */ React7.createElement(React7.Fragment, null, meta.flat().map((metaProps) => {
8818 if (!metaProps) {
8819 return null;
8820 }
8821 if ("tagName" in metaProps) {
8822 let { tagName, ...rest } = metaProps;
8823 if (!isValidMetaTag(tagName)) {
8824 console.warn(
8825 `A meta object uses an invalid tagName: ${tagName}. Expected either 'link' or 'meta'`
8826 );
8827 return null;
8828 }
8829 let Comp = tagName;
8830 return /* @__PURE__ */ React7.createElement(Comp, { key: JSON.stringify(rest), ...rest });
8831 }
8832 if ("title" in metaProps) {
8833 return /* @__PURE__ */ React7.createElement("title", { key: "title" }, String(metaProps.title));
8834 }
8835 if ("charset" in metaProps) {
8836 _nullishCoalesce(metaProps.charSet, () => ( (metaProps.charSet = metaProps.charset)));
8837 delete metaProps.charset;
8838 }
8839 if ("charSet" in metaProps && metaProps.charSet != null) {
8840 return typeof metaProps.charSet === "string" ? /* @__PURE__ */ React7.createElement("meta", { key: "charSet", charSet: metaProps.charSet }) : null;
8841 }
8842 if ("script:ld+json" in metaProps) {
8843 try {
8844 let json = JSON.stringify(metaProps["script:ld+json"]);
8845 return /* @__PURE__ */ React7.createElement(
8846 "script",
8847 {
8848 key: `script:ld+json:${json}`,
8849 type: "application/ld+json",
8850 dangerouslySetInnerHTML: { __html: escapeHtml(json) }
8851 }
8852 );
8853 } catch (err) {
8854 return null;
8855 }
8856 }
8857 return /* @__PURE__ */ React7.createElement("meta", { key: JSON.stringify(metaProps), ...metaProps });
8858 }));
8859}
8860function isValidMetaTag(tagName) {
8861 return typeof tagName === "string" && /^(meta|link)$/.test(tagName);
8862}
8863var isHydrated = false;
8864function setIsHydrated() {
8865 isHydrated = true;
8866}
8867function Scripts(scriptProps) {
8868 let {
8869 manifest,
8870 serverHandoffString,
8871 isSpaMode,
8872 renderMeta,
8873 routeDiscovery,
8874 ssr
8875 } = useFrameworkContext();
8876 let { router, static: isStatic, staticContext } = useDataRouterContext2();
8877 let { matches: routerMatches } = useDataRouterStateContext();
8878 let isRSCRouterContext = useIsRSCRouterContext();
8879 let enableFogOfWar = isFogOfWarEnabled(routeDiscovery, ssr);
8880 if (renderMeta) {
8881 renderMeta.didRenderScripts = true;
8882 }
8883 let matches = getActiveMatches(routerMatches, null, isSpaMode);
8884 React7.useEffect(() => {
8885 setIsHydrated();
8886 }, []);
8887 let initialScripts = React7.useMemo(() => {
8888 if (isRSCRouterContext) {
8889 return null;
8890 }
8891 let streamScript = "window.__reactRouterContext.stream = new ReadableStream({start(controller){window.__reactRouterContext.streamController = controller;}}).pipeThrough(new TextEncoderStream());";
8892 let contextScript = staticContext ? `window.__reactRouterContext = ${serverHandoffString};${streamScript}` : " ";
8893 let routeModulesScript = !isStatic ? " " : `${_optionalChain([manifest, 'access', _126 => _126.hmr, 'optionalAccess', _127 => _127.runtime]) ? `import ${JSON.stringify(manifest.hmr.runtime)};` : ""}${!enableFogOfWar ? `import ${JSON.stringify(manifest.url)}` : ""};
8894${matches.map((match, routeIndex) => {
8895 let routeVarName = `route${routeIndex}`;
8896 let manifestEntry = manifest.routes[match.route.id];
8897 invariant2(manifestEntry, `Route ${match.route.id} not found in manifest`);
8898 let {
8899 clientActionModule,
8900 clientLoaderModule,
8901 clientMiddlewareModule,
8902 hydrateFallbackModule,
8903 module
8904 } = manifestEntry;
8905 let chunks = [
8906 ...clientActionModule ? [
8907 {
8908 module: clientActionModule,
8909 varName: `${routeVarName}_clientAction`
8910 }
8911 ] : [],
8912 ...clientLoaderModule ? [
8913 {
8914 module: clientLoaderModule,
8915 varName: `${routeVarName}_clientLoader`
8916 }
8917 ] : [],
8918 ...clientMiddlewareModule ? [
8919 {
8920 module: clientMiddlewareModule,
8921 varName: `${routeVarName}_clientMiddleware`
8922 }
8923 ] : [],
8924 ...hydrateFallbackModule ? [
8925 {
8926 module: hydrateFallbackModule,
8927 varName: `${routeVarName}_HydrateFallback`
8928 }
8929 ] : [],
8930 { module, varName: `${routeVarName}_main` }
8931 ];
8932 if (chunks.length === 1) {
8933 return `import * as ${routeVarName} from ${JSON.stringify(module)};`;
8934 }
8935 let chunkImportsSnippet = chunks.map((chunk) => `import * as ${chunk.varName} from "${chunk.module}";`).join("\n");
8936 let mergedChunksSnippet = `const ${routeVarName} = {${chunks.map((chunk) => `...${chunk.varName}`).join(",")}};`;
8937 return [chunkImportsSnippet, mergedChunksSnippet].join("\n");
8938 }).join("\n")}
8939 ${enableFogOfWar ? (
8940 // Inline a minimal manifest with the SSR matches
8941 `window.__reactRouterManifest = ${JSON.stringify(
8942 getPartialManifest(manifest, router),
8943 null,
8944 2
8945 )};`
8946 ) : ""}
8947 window.__reactRouterRouteModules = {${matches.map((match, index) => `${JSON.stringify(match.route.id)}:route${index}`).join(",")}};
8948
8949import(${JSON.stringify(manifest.entry.module)});`;
8950 return /* @__PURE__ */ React7.createElement(React7.Fragment, null, /* @__PURE__ */ React7.createElement(
8951 "script",
8952 {
8953 ...scriptProps,
8954 suppressHydrationWarning: true,
8955 dangerouslySetInnerHTML: { __html: contextScript },
8956 type: void 0
8957 }
8958 ), /* @__PURE__ */ React7.createElement(
8959 "script",
8960 {
8961 ...scriptProps,
8962 suppressHydrationWarning: true,
8963 dangerouslySetInnerHTML: { __html: routeModulesScript },
8964 type: "module",
8965 async: true
8966 }
8967 ));
8968 }, []);
8969 let preloads = isHydrated || isRSCRouterContext ? [] : dedupe(
8970 manifest.entry.imports.concat(
8971 getModuleLinkHrefs(matches, manifest, {
8972 includeHydrateFallback: true
8973 })
8974 )
8975 );
8976 let sri = typeof manifest.sri === "object" ? manifest.sri : {};
8977 warnOnce(
8978 !isRSCRouterContext,
8979 "The <Scripts /> element is a no-op when using RSC and can be safely removed."
8980 );
8981 return isHydrated || isRSCRouterContext ? null : /* @__PURE__ */ React7.createElement(React7.Fragment, null, typeof manifest.sri === "object" ? /* @__PURE__ */ React7.createElement(
8982 "script",
8983 {
8984 ...scriptProps,
8985 "rr-importmap": "",
8986 type: "importmap",
8987 suppressHydrationWarning: true,
8988 dangerouslySetInnerHTML: {
8989 __html: JSON.stringify({
8990 integrity: sri
8991 })
8992 }
8993 }
8994 ) : null, !enableFogOfWar ? /* @__PURE__ */ React7.createElement(
8995 "link",
8996 {
8997 rel: "modulepreload",
8998 href: manifest.url,
8999 crossOrigin: scriptProps.crossOrigin,
9000 integrity: sri[manifest.url],
9001 suppressHydrationWarning: true
9002 }
9003 ) : null, /* @__PURE__ */ React7.createElement(
9004 "link",
9005 {
9006 rel: "modulepreload",
9007 href: manifest.entry.module,
9008 crossOrigin: scriptProps.crossOrigin,
9009 integrity: sri[manifest.entry.module],
9010 suppressHydrationWarning: true
9011 }
9012 ), preloads.map((path) => /* @__PURE__ */ React7.createElement(
9013 "link",
9014 {
9015 key: path,
9016 rel: "modulepreload",
9017 href: path,
9018 crossOrigin: scriptProps.crossOrigin,
9019 integrity: sri[path],
9020 suppressHydrationWarning: true
9021 }
9022 )), initialScripts);
9023}
9024function dedupe(array) {
9025 return [...new Set(array)];
9026}
9027function mergeRefs(...refs) {
9028 return (value) => {
9029 refs.forEach((ref) => {
9030 if (typeof ref === "function") {
9031 ref(value);
9032 } else if (ref != null) {
9033 ref.current = value;
9034 }
9035 });
9036 };
9037}
9038
9039// lib/dom/ssr/errorBoundaries.tsx
9040var RemixErrorBoundary = class extends React8.Component {
9041 constructor(props) {
9042 super(props);
9043 this.state = { error: props.error || null, location: props.location };
9044 }
9045 static getDerivedStateFromError(error) {
9046 return { error };
9047 }
9048 static getDerivedStateFromProps(props, state) {
9049 if (state.location !== props.location) {
9050 return { error: props.error || null, location: props.location };
9051 }
9052 return { error: props.error || state.error, location: state.location };
9053 }
9054 render() {
9055 if (this.state.error) {
9056 return /* @__PURE__ */ React8.createElement(
9057 RemixRootDefaultErrorBoundary,
9058 {
9059 error: this.state.error,
9060 isOutsideRemixApp: true
9061 }
9062 );
9063 } else {
9064 return this.props.children;
9065 }
9066 }
9067};
9068function RemixRootDefaultErrorBoundary({
9069 error,
9070 isOutsideRemixApp
9071}) {
9072 console.error(error);
9073 let heyDeveloper = /* @__PURE__ */ React8.createElement(
9074 "script",
9075 {
9076 dangerouslySetInnerHTML: {
9077 __html: `
9078 console.log(
9079 "\u{1F4BF} Hey developer \u{1F44B}. You can provide a way better UX than this when your app throws errors. Check out https://reactrouter.com/how-to/error-boundary for more information."
9080 );
9081 `
9082 }
9083 }
9084 );
9085 if (isRouteErrorResponse(error)) {
9086 return /* @__PURE__ */ React8.createElement(BoundaryShell, { title: "Unhandled Thrown Response!" }, /* @__PURE__ */ React8.createElement("h1", { style: { fontSize: "24px" } }, error.status, " ", error.statusText), ENABLE_DEV_WARNINGS ? heyDeveloper : null);
9087 }
9088 let errorInstance;
9089 if (error instanceof Error) {
9090 errorInstance = error;
9091 } else {
9092 let errorString = error == null ? "Unknown Error" : typeof error === "object" && "toString" in error ? error.toString() : JSON.stringify(error);
9093 errorInstance = new Error(errorString);
9094 }
9095 return /* @__PURE__ */ React8.createElement(
9096 BoundaryShell,
9097 {
9098 title: "Application Error!",
9099 isOutsideRemixApp
9100 },
9101 /* @__PURE__ */ React8.createElement("h1", { style: { fontSize: "24px" } }, "Application Error"),
9102 /* @__PURE__ */ React8.createElement(
9103 "pre",
9104 {
9105 style: {
9106 padding: "2rem",
9107 background: "hsla(10, 50%, 50%, 0.1)",
9108 color: "red",
9109 overflow: "auto"
9110 }
9111 },
9112 errorInstance.stack
9113 ),
9114 heyDeveloper
9115 );
9116}
9117function BoundaryShell({
9118 title,
9119 renderScripts,
9120 isOutsideRemixApp,
9121 children
9122}) {
9123 let { routeModules } = useFrameworkContext();
9124 if (_optionalChain([routeModules, 'access', _128 => _128.root, 'optionalAccess', _129 => _129.Layout]) && !isOutsideRemixApp) {
9125 return children;
9126 }
9127 return /* @__PURE__ */ React8.createElement("html", { lang: "en" }, /* @__PURE__ */ React8.createElement("head", null, /* @__PURE__ */ React8.createElement("meta", { charSet: "utf-8" }), /* @__PURE__ */ React8.createElement(
9128 "meta",
9129 {
9130 name: "viewport",
9131 content: "width=device-width,initial-scale=1,viewport-fit=cover"
9132 }
9133 ), /* @__PURE__ */ React8.createElement("title", null, title)), /* @__PURE__ */ React8.createElement("body", null, /* @__PURE__ */ React8.createElement("main", { style: { fontFamily: "system-ui, sans-serif", padding: "2rem" } }, children, renderScripts ? /* @__PURE__ */ React8.createElement(Scripts, null) : null)));
9134}
9135
9136// lib/components.tsx
9137
9138var USE_OPTIMISTIC = "useOptimistic";
9139var useOptimisticImpl = React9[USE_OPTIMISTIC];
9140var stableUseOptimisticSetter = () => void 0;
9141function useOptimisticSafe(val) {
9142 if (useOptimisticImpl) {
9143 return useOptimisticImpl(val);
9144 } else {
9145 return [val, stableUseOptimisticSetter];
9146 }
9147}
9148function mapRouteProperties(route) {
9149 let updates = {
9150 // Note: this check also occurs in createRoutesFromChildren so update
9151 // there if you change this -- please and thank you!
9152 hasErrorBoundary: route.hasErrorBoundary || route.ErrorBoundary != null || route.errorElement != null
9153 };
9154 if (route.Component) {
9155 if (ENABLE_DEV_WARNINGS) {
9156 if (route.element) {
9157 warning(
9158 false,
9159 "You should not include both `Component` and `element` on your route - `Component` will be used."
9160 );
9161 }
9162 }
9163 Object.assign(updates, {
9164 element: React9.createElement(route.Component),
9165 Component: void 0
9166 });
9167 }
9168 if (route.HydrateFallback) {
9169 if (ENABLE_DEV_WARNINGS) {
9170 if (route.hydrateFallbackElement) {
9171 warning(
9172 false,
9173 "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used."
9174 );
9175 }
9176 }
9177 Object.assign(updates, {
9178 hydrateFallbackElement: React9.createElement(route.HydrateFallback),
9179 HydrateFallback: void 0
9180 });
9181 }
9182 if (route.ErrorBoundary) {
9183 if (ENABLE_DEV_WARNINGS) {
9184 if (route.errorElement) {
9185 warning(
9186 false,
9187 "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used."
9188 );
9189 }
9190 }
9191 Object.assign(updates, {
9192 errorElement: React9.createElement(route.ErrorBoundary),
9193 ErrorBoundary: void 0
9194 });
9195 }
9196 return updates;
9197}
9198var hydrationRouteProperties = [
9199 "HydrateFallback",
9200 "hydrateFallbackElement"
9201];
9202function createMemoryRouter(routes, opts) {
9203 return createRouter({
9204 basename: _optionalChain([opts, 'optionalAccess', _130 => _130.basename]),
9205 getContext: _optionalChain([opts, 'optionalAccess', _131 => _131.getContext]),
9206 future: _optionalChain([opts, 'optionalAccess', _132 => _132.future]),
9207 history: createMemoryHistory({
9208 initialEntries: _optionalChain([opts, 'optionalAccess', _133 => _133.initialEntries]),
9209 initialIndex: _optionalChain([opts, 'optionalAccess', _134 => _134.initialIndex])
9210 }),
9211 hydrationData: _optionalChain([opts, 'optionalAccess', _135 => _135.hydrationData]),
9212 routes,
9213 hydrationRouteProperties,
9214 mapRouteProperties,
9215 dataStrategy: _optionalChain([opts, 'optionalAccess', _136 => _136.dataStrategy]),
9216 patchRoutesOnNavigation: _optionalChain([opts, 'optionalAccess', _137 => _137.patchRoutesOnNavigation]),
9217 unstable_instrumentations: _optionalChain([opts, 'optionalAccess', _138 => _138.unstable_instrumentations])
9218 }).initialize();
9219}
9220var Deferred2 = class {
9221 constructor() {
9222 this.status = "pending";
9223 this.promise = new Promise((resolve, reject) => {
9224 this.resolve = (value) => {
9225 if (this.status === "pending") {
9226 this.status = "resolved";
9227 resolve(value);
9228 }
9229 };
9230 this.reject = (reason) => {
9231 if (this.status === "pending") {
9232 this.status = "rejected";
9233 reject(reason);
9234 }
9235 };
9236 });
9237 }
9238};
9239function RouterProvider({
9240 router,
9241 flushSync: reactDomFlushSyncImpl,
9242 onError,
9243 unstable_useTransitions
9244}) {
9245 let unstable_rsc = useIsRSCRouterContext();
9246 unstable_useTransitions = unstable_rsc || unstable_useTransitions;
9247 let [_state, setStateImpl] = React9.useState(router.state);
9248 let [state, setOptimisticState] = useOptimisticSafe(_state);
9249 let [pendingState, setPendingState] = React9.useState();
9250 let [vtContext, setVtContext] = React9.useState({
9251 isTransitioning: false
9252 });
9253 let [renderDfd, setRenderDfd] = React9.useState();
9254 let [transition, setTransition] = React9.useState();
9255 let [interruption, setInterruption] = React9.useState();
9256 let fetcherData = React9.useRef(/* @__PURE__ */ new Map());
9257 let setState = React9.useCallback(
9258 (newState, { deletedFetchers, newErrors, flushSync, viewTransitionOpts }) => {
9259 if (newErrors && onError) {
9260 Object.values(newErrors).forEach(
9261 (error) => onError(error, {
9262 location: newState.location,
9263 params: _nullishCoalesce(_optionalChain([newState, 'access', _139 => _139.matches, 'access', _140 => _140[0], 'optionalAccess', _141 => _141.params]), () => ( {})),
9264 unstable_pattern: getRoutePattern(newState.matches)
9265 })
9266 );
9267 }
9268 newState.fetchers.forEach((fetcher, key) => {
9269 if (fetcher.data !== void 0) {
9270 fetcherData.current.set(key, fetcher.data);
9271 }
9272 });
9273 deletedFetchers.forEach((key) => fetcherData.current.delete(key));
9274 warnOnce(
9275 flushSync === false || reactDomFlushSyncImpl != null,
9276 'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.'
9277 );
9278 let isViewTransitionAvailable = router.window != null && router.window.document != null && typeof router.window.document.startViewTransition === "function";
9279 warnOnce(
9280 viewTransitionOpts == null || isViewTransitionAvailable,
9281 "You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."
9282 );
9283 if (!viewTransitionOpts || !isViewTransitionAvailable) {
9284 if (reactDomFlushSyncImpl && flushSync) {
9285 reactDomFlushSyncImpl(() => setStateImpl(newState));
9286 } else if (unstable_useTransitions === false) {
9287 setStateImpl(newState);
9288 } else {
9289 React9.startTransition(() => {
9290 if (unstable_useTransitions === true) {
9291 setOptimisticState((s) => getOptimisticRouterState(s, newState));
9292 }
9293 setStateImpl(newState);
9294 });
9295 }
9296 return;
9297 }
9298 if (reactDomFlushSyncImpl && flushSync) {
9299 reactDomFlushSyncImpl(() => {
9300 if (transition) {
9301 _optionalChain([renderDfd, 'optionalAccess', _142 => _142.resolve, 'call', _143 => _143()]);
9302 transition.skipTransition();
9303 }
9304 setVtContext({
9305 isTransitioning: true,
9306 flushSync: true,
9307 currentLocation: viewTransitionOpts.currentLocation,
9308 nextLocation: viewTransitionOpts.nextLocation
9309 });
9310 });
9311 let t = router.window.document.startViewTransition(() => {
9312 reactDomFlushSyncImpl(() => setStateImpl(newState));
9313 });
9314 t.finished.finally(() => {
9315 reactDomFlushSyncImpl(() => {
9316 setRenderDfd(void 0);
9317 setTransition(void 0);
9318 setPendingState(void 0);
9319 setVtContext({ isTransitioning: false });
9320 });
9321 });
9322 reactDomFlushSyncImpl(() => setTransition(t));
9323 return;
9324 }
9325 if (transition) {
9326 _optionalChain([renderDfd, 'optionalAccess', _144 => _144.resolve, 'call', _145 => _145()]);
9327 transition.skipTransition();
9328 setInterruption({
9329 state: newState,
9330 currentLocation: viewTransitionOpts.currentLocation,
9331 nextLocation: viewTransitionOpts.nextLocation
9332 });
9333 } else {
9334 setPendingState(newState);
9335 setVtContext({
9336 isTransitioning: true,
9337 flushSync: false,
9338 currentLocation: viewTransitionOpts.currentLocation,
9339 nextLocation: viewTransitionOpts.nextLocation
9340 });
9341 }
9342 },
9343 [
9344 router.window,
9345 reactDomFlushSyncImpl,
9346 transition,
9347 renderDfd,
9348 unstable_useTransitions,
9349 setOptimisticState,
9350 onError
9351 ]
9352 );
9353 React9.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
9354 let initialized = state.initialized;
9355 React9.useLayoutEffect(() => {
9356 if (!initialized && router.state.initialized) {
9357 setState(router.state, {
9358 deletedFetchers: [],
9359 flushSync: false,
9360 newErrors: null
9361 });
9362 }
9363 }, [initialized, setState, router.state]);
9364 React9.useEffect(() => {
9365 if (vtContext.isTransitioning && !vtContext.flushSync) {
9366 setRenderDfd(new Deferred2());
9367 }
9368 }, [vtContext]);
9369 React9.useEffect(() => {
9370 if (renderDfd && pendingState && router.window) {
9371 let newState = pendingState;
9372 let renderPromise = renderDfd.promise;
9373 let transition2 = router.window.document.startViewTransition(async () => {
9374 if (unstable_useTransitions === false) {
9375 setStateImpl(newState);
9376 } else {
9377 React9.startTransition(() => {
9378 if (unstable_useTransitions === true) {
9379 setOptimisticState((s) => getOptimisticRouterState(s, newState));
9380 }
9381 setStateImpl(newState);
9382 });
9383 }
9384 await renderPromise;
9385 });
9386 transition2.finished.finally(() => {
9387 setRenderDfd(void 0);
9388 setTransition(void 0);
9389 setPendingState(void 0);
9390 setVtContext({ isTransitioning: false });
9391 });
9392 setTransition(transition2);
9393 }
9394 }, [
9395 pendingState,
9396 renderDfd,
9397 router.window,
9398 unstable_useTransitions,
9399 setOptimisticState
9400 ]);
9401 React9.useEffect(() => {
9402 if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
9403 renderDfd.resolve();
9404 }
9405 }, [renderDfd, transition, state.location, pendingState]);
9406 React9.useEffect(() => {
9407 if (!vtContext.isTransitioning && interruption) {
9408 setPendingState(interruption.state);
9409 setVtContext({
9410 isTransitioning: true,
9411 flushSync: false,
9412 currentLocation: interruption.currentLocation,
9413 nextLocation: interruption.nextLocation
9414 });
9415 setInterruption(void 0);
9416 }
9417 }, [vtContext.isTransitioning, interruption]);
9418 let navigator = React9.useMemo(() => {
9419 return {
9420 createHref: router.createHref,
9421 encodeLocation: router.encodeLocation,
9422 go: (n) => router.navigate(n),
9423 push: (to, state2, opts) => router.navigate(to, {
9424 state: state2,
9425 preventScrollReset: _optionalChain([opts, 'optionalAccess', _146 => _146.preventScrollReset])
9426 }),
9427 replace: (to, state2, opts) => router.navigate(to, {
9428 replace: true,
9429 state: state2,
9430 preventScrollReset: _optionalChain([opts, 'optionalAccess', _147 => _147.preventScrollReset])
9431 })
9432 };
9433 }, [router]);
9434 let basename = router.basename || "/";
9435 let dataRouterContext = React9.useMemo(
9436 () => ({
9437 router,
9438 navigator,
9439 static: false,
9440 basename,
9441 onError
9442 }),
9443 [router, navigator, basename, onError]
9444 );
9445 return /* @__PURE__ */ React9.createElement(React9.Fragment, null, /* @__PURE__ */ React9.createElement(DataRouterContext.Provider, { value: dataRouterContext }, /* @__PURE__ */ React9.createElement(DataRouterStateContext.Provider, { value: state }, /* @__PURE__ */ React9.createElement(FetchersContext.Provider, { value: fetcherData.current }, /* @__PURE__ */ React9.createElement(ViewTransitionContext.Provider, { value: vtContext }, /* @__PURE__ */ React9.createElement(
9446 Router,
9447 {
9448 basename,
9449 location: state.location,
9450 navigationType: state.historyAction,
9451 navigator,
9452 unstable_useTransitions
9453 },
9454 /* @__PURE__ */ React9.createElement(
9455 MemoizedDataRoutes,
9456 {
9457 routes: router.routes,
9458 future: router.future,
9459 state,
9460 isStatic: false,
9461 onError
9462 }
9463 )
9464 ))))), null);
9465}
9466function getOptimisticRouterState(currentState, newState) {
9467 return {
9468 // Don't surface "current location specific" stuff mid-navigation
9469 // (historyAction, location, matches, loaderData, errors, initialized,
9470 // restoreScroll, preventScrollReset, blockers, etc.)
9471 ...currentState,
9472 // Only surface "pending/in-flight stuff"
9473 // (navigation, revalidation, actionData, fetchers, )
9474 navigation: newState.navigation.state !== "idle" ? newState.navigation : currentState.navigation,
9475 revalidation: newState.revalidation !== "idle" ? newState.revalidation : currentState.revalidation,
9476 actionData: newState.navigation.state !== "submitting" ? newState.actionData : currentState.actionData,
9477 fetchers: newState.fetchers
9478 };
9479}
9480var MemoizedDataRoutes = React9.memo(DataRoutes);
9481function DataRoutes({
9482 routes,
9483 future,
9484 state,
9485 isStatic,
9486 onError
9487}) {
9488 return useRoutesImpl(routes, void 0, { state, isStatic, onError, future });
9489}
9490function MemoryRouter({
9491 basename,
9492 children,
9493 initialEntries,
9494 initialIndex,
9495 unstable_useTransitions
9496}) {
9497 let historyRef = React9.useRef();
9498 if (historyRef.current == null) {
9499 historyRef.current = createMemoryHistory({
9500 initialEntries,
9501 initialIndex,
9502 v5Compat: true
9503 });
9504 }
9505 let history = historyRef.current;
9506 let [state, setStateImpl] = React9.useState({
9507 action: history.action,
9508 location: history.location
9509 });
9510 let setState = React9.useCallback(
9511 (newState) => {
9512 if (unstable_useTransitions === false) {
9513 setStateImpl(newState);
9514 } else {
9515 React9.startTransition(() => setStateImpl(newState));
9516 }
9517 },
9518 [unstable_useTransitions]
9519 );
9520 React9.useLayoutEffect(() => history.listen(setState), [history, setState]);
9521 return /* @__PURE__ */ React9.createElement(
9522 Router,
9523 {
9524 basename,
9525 children,
9526 location: state.location,
9527 navigationType: state.action,
9528 navigator: history,
9529 unstable_useTransitions
9530 }
9531 );
9532}
9533function Navigate({
9534 to,
9535 replace: replace2,
9536 state,
9537 relative
9538}) {
9539 invariant(
9540 useInRouterContext(),
9541 // TODO: This error is probably because they somehow have 2 versions of
9542 // the router loaded. We can help them understand how to avoid that.
9543 `<Navigate> may be used only in the context of a <Router> component.`
9544 );
9545 let { static: isStatic } = React9.useContext(NavigationContext);
9546 warning(
9547 !isStatic,
9548 `<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`
9549 );
9550 let { matches } = React9.useContext(RouteContext);
9551 let { pathname: locationPathname } = useLocation();
9552 let navigate = useNavigate();
9553 let path = resolveTo(
9554 to,
9555 getResolveToMatches(matches),
9556 locationPathname,
9557 relative === "path"
9558 );
9559 let jsonPath = JSON.stringify(path);
9560 React9.useEffect(() => {
9561 navigate(JSON.parse(jsonPath), { replace: replace2, state, relative });
9562 }, [navigate, jsonPath, relative, replace2, state]);
9563 return null;
9564}
9565function Outlet(props) {
9566 return useOutlet(props.context);
9567}
9568function Route(props) {
9569 invariant(
9570 false,
9571 `A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`
9572 );
9573}
9574function Router({
9575 basename: basenameProp = "/",
9576 children = null,
9577 location: locationProp,
9578 navigationType = "POP" /* Pop */,
9579 navigator,
9580 static: staticProp = false,
9581 unstable_useTransitions
9582}) {
9583 invariant(
9584 !useInRouterContext(),
9585 `You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`
9586 );
9587 let basename = basenameProp.replace(/^\/*/, "/");
9588 let navigationContext = React9.useMemo(
9589 () => ({
9590 basename,
9591 navigator,
9592 static: staticProp,
9593 unstable_useTransitions,
9594 future: {}
9595 }),
9596 [basename, navigator, staticProp, unstable_useTransitions]
9597 );
9598 if (typeof locationProp === "string") {
9599 locationProp = parsePath(locationProp);
9600 }
9601 let {
9602 pathname = "/",
9603 search = "",
9604 hash = "",
9605 state = null,
9606 key = "default",
9607 unstable_mask
9608 } = locationProp;
9609 let locationContext = React9.useMemo(() => {
9610 let trailingPathname = stripBasename(pathname, basename);
9611 if (trailingPathname == null) {
9612 return null;
9613 }
9614 return {
9615 location: {
9616 pathname: trailingPathname,
9617 search,
9618 hash,
9619 state,
9620 key,
9621 unstable_mask
9622 },
9623 navigationType
9624 };
9625 }, [
9626 basename,
9627 pathname,
9628 search,
9629 hash,
9630 state,
9631 key,
9632 navigationType,
9633 unstable_mask
9634 ]);
9635 warning(
9636 locationContext != null,
9637 `<Router basename="${basename}"> is not able to match the URL "${pathname}${search}${hash}" because it does not start with the basename, so the <Router> won't render anything.`
9638 );
9639 if (locationContext == null) {
9640 return null;
9641 }
9642 return /* @__PURE__ */ React9.createElement(NavigationContext.Provider, { value: navigationContext }, /* @__PURE__ */ React9.createElement(LocationContext.Provider, { children, value: locationContext }));
9643}
9644function Routes({
9645 children,
9646 location
9647}) {
9648 return useRoutes(createRoutesFromChildren(children), location);
9649}
9650function Await({
9651 children,
9652 errorElement,
9653 resolve
9654}) {
9655 let dataRouterContext = React9.useContext(DataRouterContext);
9656 let dataRouterStateContext = React9.useContext(DataRouterStateContext);
9657 let onError = React9.useCallback(
9658 (error, errorInfo) => {
9659 if (dataRouterContext && dataRouterContext.onError && dataRouterStateContext) {
9660 dataRouterContext.onError(error, {
9661 location: dataRouterStateContext.location,
9662 params: _optionalChain([dataRouterStateContext, 'access', _148 => _148.matches, 'access', _149 => _149[0], 'optionalAccess', _150 => _150.params]) || {},
9663 unstable_pattern: getRoutePattern(dataRouterStateContext.matches),
9664 errorInfo
9665 });
9666 }
9667 },
9668 [dataRouterContext, dataRouterStateContext]
9669 );
9670 return /* @__PURE__ */ React9.createElement(
9671 AwaitErrorBoundary,
9672 {
9673 resolve,
9674 errorElement,
9675 onError
9676 },
9677 /* @__PURE__ */ React9.createElement(ResolveAwait, null, children)
9678 );
9679}
9680var AwaitErrorBoundary = class extends React9.Component {
9681 constructor(props) {
9682 super(props);
9683 this.state = { error: null };
9684 }
9685 static getDerivedStateFromError(error) {
9686 return { error };
9687 }
9688 componentDidCatch(error, errorInfo) {
9689 if (this.props.onError) {
9690 this.props.onError(error, errorInfo);
9691 } else {
9692 console.error(
9693 "<Await> caught the following error during render",
9694 error,
9695 errorInfo
9696 );
9697 }
9698 }
9699 render() {
9700 let { children, errorElement, resolve } = this.props;
9701 let promise = null;
9702 let status = 0 /* pending */;
9703 if (!(resolve instanceof Promise)) {
9704 status = 1 /* success */;
9705 promise = Promise.resolve();
9706 Object.defineProperty(promise, "_tracked", { get: () => true });
9707 Object.defineProperty(promise, "_data", { get: () => resolve });
9708 } else if (this.state.error) {
9709 status = 2 /* error */;
9710 let renderError = this.state.error;
9711 promise = Promise.reject().catch(() => {
9712 });
9713 Object.defineProperty(promise, "_tracked", { get: () => true });
9714 Object.defineProperty(promise, "_error", { get: () => renderError });
9715 } else if (resolve._tracked) {
9716 promise = resolve;
9717 status = "_error" in promise ? 2 /* error */ : "_data" in promise ? 1 /* success */ : 0 /* pending */;
9718 } else {
9719 status = 0 /* pending */;
9720 Object.defineProperty(resolve, "_tracked", { get: () => true });
9721 promise = resolve.then(
9722 (data2) => Object.defineProperty(resolve, "_data", { get: () => data2 }),
9723 (error) => {
9724 _optionalChain([this, 'access', _151 => _151.props, 'access', _152 => _152.onError, 'optionalCall', _153 => _153(error)]);
9725 Object.defineProperty(resolve, "_error", { get: () => error });
9726 }
9727 );
9728 }
9729 if (status === 2 /* error */ && !errorElement) {
9730 throw promise._error;
9731 }
9732 if (status === 2 /* error */) {
9733 return /* @__PURE__ */ React9.createElement(AwaitContext.Provider, { value: promise, children: errorElement });
9734 }
9735 if (status === 1 /* success */) {
9736 return /* @__PURE__ */ React9.createElement(AwaitContext.Provider, { value: promise, children });
9737 }
9738 throw promise;
9739 }
9740};
9741function ResolveAwait({
9742 children
9743}) {
9744 let data2 = useAsyncValue();
9745 let toRender = typeof children === "function" ? children(data2) : children;
9746 return /* @__PURE__ */ React9.createElement(React9.Fragment, null, toRender);
9747}
9748function createRoutesFromChildren(children, parentPath = []) {
9749 let routes = [];
9750 React9.Children.forEach(children, (element, index) => {
9751 if (!React9.isValidElement(element)) {
9752 return;
9753 }
9754 let treePath = [...parentPath, index];
9755 if (element.type === React9.Fragment) {
9756 routes.push.apply(
9757 routes,
9758 createRoutesFromChildren(element.props.children, treePath)
9759 );
9760 return;
9761 }
9762 invariant(
9763 element.type === Route,
9764 `[${typeof element.type === "string" ? element.type : element.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`
9765 );
9766 invariant(
9767 !element.props.index || !element.props.children,
9768 "An index route cannot have child routes."
9769 );
9770 let route = {
9771 id: element.props.id || treePath.join("-"),
9772 caseSensitive: element.props.caseSensitive,
9773 element: element.props.element,
9774 Component: element.props.Component,
9775 index: element.props.index,
9776 path: element.props.path,
9777 middleware: element.props.middleware,
9778 loader: element.props.loader,
9779 action: element.props.action,
9780 hydrateFallbackElement: element.props.hydrateFallbackElement,
9781 HydrateFallback: element.props.HydrateFallback,
9782 errorElement: element.props.errorElement,
9783 ErrorBoundary: element.props.ErrorBoundary,
9784 hasErrorBoundary: element.props.hasErrorBoundary === true || element.props.ErrorBoundary != null || element.props.errorElement != null,
9785 shouldRevalidate: element.props.shouldRevalidate,
9786 handle: element.props.handle,
9787 lazy: element.props.lazy
9788 };
9789 if (element.props.children) {
9790 route.children = createRoutesFromChildren(
9791 element.props.children,
9792 treePath
9793 );
9794 }
9795 routes.push(route);
9796 });
9797 return routes;
9798}
9799var createRoutesFromElements = createRoutesFromChildren;
9800function renderMatches(matches) {
9801 return _renderMatches(matches);
9802}
9803function useRouteComponentProps() {
9804 return {
9805 params: useParams(),
9806 loaderData: useLoaderData(),
9807 actionData: useActionData(),
9808 matches: useMatches()
9809 };
9810}
9811function WithComponentProps({
9812 children
9813}) {
9814 const props = useRouteComponentProps();
9815 return React9.cloneElement(children, props);
9816}
9817function withComponentProps(Component4) {
9818 return function WithComponentProps2() {
9819 const props = useRouteComponentProps();
9820 return React9.createElement(Component4, props);
9821 };
9822}
9823function useHydrateFallbackProps() {
9824 return {
9825 params: useParams(),
9826 loaderData: useLoaderData(),
9827 actionData: useActionData()
9828 };
9829}
9830function WithHydrateFallbackProps({
9831 children
9832}) {
9833 const props = useHydrateFallbackProps();
9834 return React9.cloneElement(children, props);
9835}
9836function withHydrateFallbackProps(HydrateFallback) {
9837 return function WithHydrateFallbackProps2() {
9838 const props = useHydrateFallbackProps();
9839 return React9.createElement(HydrateFallback, props);
9840 };
9841}
9842function useErrorBoundaryProps() {
9843 return {
9844 params: useParams(),
9845 loaderData: useLoaderData(),
9846 actionData: useActionData(),
9847 error: useRouteError()
9848 };
9849}
9850function WithErrorBoundaryProps({
9851 children
9852}) {
9853 const props = useErrorBoundaryProps();
9854 return React9.cloneElement(children, props);
9855}
9856function withErrorBoundaryProps(ErrorBoundary) {
9857 return function WithErrorBoundaryProps2() {
9858 const props = useErrorBoundaryProps();
9859 return React9.createElement(ErrorBoundary, props);
9860 };
9861}
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989exports.Action = Action; exports.createMemoryHistory = createMemoryHistory; exports.createBrowserHistory = createBrowserHistory; exports.createHashHistory = createHashHistory; exports.invariant = invariant; exports.warning = warning; exports.createPath = createPath; exports.parsePath = parsePath; exports.createContext = createContext; exports.RouterContextProvider = RouterContextProvider; exports.convertRoutesToDataRoutes = convertRoutesToDataRoutes; exports.matchRoutes = matchRoutes; exports.generatePath = generatePath; exports.matchPath = matchPath; exports.stripBasename = stripBasename; exports.resolvePath = resolvePath; exports.resolveTo = resolveTo; exports.joinPaths = joinPaths; exports.data = data; exports.redirect = redirect; exports.redirectDocument = redirectDocument; exports.replace = replace; exports.ErrorResponseImpl = ErrorResponseImpl; exports.isRouteErrorResponse = isRouteErrorResponse; exports.parseToInfo = parseToInfo; exports.escapeHtml = escapeHtml; exports.encode = encode; exports.instrumentHandler = instrumentHandler; exports.IDLE_NAVIGATION = IDLE_NAVIGATION; exports.IDLE_FETCHER = IDLE_FETCHER; exports.IDLE_BLOCKER = IDLE_BLOCKER; exports.createRouter = createRouter; exports.createStaticHandler = createStaticHandler; exports.getStaticContextFromError = getStaticContextFromError; exports.invalidProtocols = invalidProtocols; exports.isDataWithResponseInit = isDataWithResponseInit; exports.isResponse = isResponse; exports.isRedirectStatusCode = isRedirectStatusCode; exports.isRedirectResponse = isRedirectResponse; exports.isMutationMethod = isMutationMethod; exports.createRequestInit = createRequestInit; exports.SingleFetchRedirectSymbol = SingleFetchRedirectSymbol; exports.SINGLE_FETCH_REDIRECT_STATUS = SINGLE_FETCH_REDIRECT_STATUS; exports.NO_BODY_STATUS_CODES = NO_BODY_STATUS_CODES; exports.StreamTransfer = StreamTransfer; exports.getTurboStreamSingleFetchDataStrategy = getTurboStreamSingleFetchDataStrategy; exports.getSingleFetchDataStrategyImpl = getSingleFetchDataStrategyImpl; exports.stripIndexParam = stripIndexParam; exports.singleFetchUrl = singleFetchUrl; exports.decodeViaTurboStream = decodeViaTurboStream; exports.DataRouterContext = DataRouterContext; exports.DataRouterStateContext = DataRouterStateContext; exports.RSCRouterContext = RSCRouterContext; exports.ViewTransitionContext = ViewTransitionContext; exports.FetchersContext = FetchersContext; exports.AwaitContextProvider = AwaitContextProvider; exports.NavigationContext = NavigationContext; exports.LocationContext = LocationContext; exports.RouteContext = RouteContext; exports.ENABLE_DEV_WARNINGS = ENABLE_DEV_WARNINGS; exports.warnOnce = warnOnce; exports.decodeRedirectErrorDigest = decodeRedirectErrorDigest; exports.decodeRouteErrorResponseDigest = decodeRouteErrorResponseDigest; exports.useHref = useHref; exports.useInRouterContext = useInRouterContext; exports.useLocation = useLocation; exports.useNavigationType = useNavigationType; exports.useMatch = useMatch; exports.useNavigate = useNavigate; exports.useOutletContext = useOutletContext; exports.useOutlet = useOutlet; exports.useParams = useParams; exports.useResolvedPath = useResolvedPath; exports.useRoutes = useRoutes; exports.useRouteId = useRouteId; exports.useNavigation = useNavigation; exports.useRevalidator = useRevalidator; exports.useMatches = useMatches; exports.useLoaderData = useLoaderData; exports.useRouteLoaderData = useRouteLoaderData; exports.useActionData = useActionData; exports.useRouteError = useRouteError; exports.useAsyncValue = useAsyncValue; exports.useAsyncError = useAsyncError; exports.useBlocker = useBlocker; exports.useRoute = useRoute; exports.RemixErrorBoundary = RemixErrorBoundary; exports.createServerRoutes = createServerRoutes; exports.createClientRoutesWithHMRRevalidationOptOut = createClientRoutesWithHMRRevalidationOptOut; exports.noActionDefinedError = noActionDefinedError; exports.createClientRoutes = createClientRoutes; exports.shouldHydrateRouteLoader = shouldHydrateRouteLoader; exports.getPatchRoutesOnNavigationFunction = getPatchRoutesOnNavigationFunction; exports.useFogOFWarDiscovery = useFogOFWarDiscovery; exports.getManifestPath = getManifestPath; exports.FrameworkContext = FrameworkContext; exports.usePrefetchBehavior = usePrefetchBehavior; exports.CRITICAL_CSS_DATA_ATTRIBUTE = CRITICAL_CSS_DATA_ATTRIBUTE; exports.Links = Links; exports.PrefetchPageLinks = PrefetchPageLinks; exports.Meta = Meta; exports.setIsHydrated = setIsHydrated; exports.Scripts = Scripts; exports.mergeRefs = mergeRefs; exports.mapRouteProperties = mapRouteProperties; exports.hydrationRouteProperties = hydrationRouteProperties; exports.createMemoryRouter = createMemoryRouter; exports.RouterProvider = RouterProvider; exports.DataRoutes = DataRoutes; exports.MemoryRouter = MemoryRouter; exports.Navigate = Navigate; exports.Outlet = Outlet; exports.Route = Route; exports.Router = Router; exports.Routes = Routes; exports.Await = Await; exports.createRoutesFromChildren = createRoutesFromChildren; exports.createRoutesFromElements = createRoutesFromElements; exports.renderMatches = renderMatches; exports.WithComponentProps = WithComponentProps; exports.withComponentProps = withComponentProps; exports.WithHydrateFallbackProps = WithHydrateFallbackProps; exports.withHydrateFallbackProps = withHydrateFallbackProps; exports.WithErrorBoundaryProps = WithErrorBoundaryProps; exports.withErrorBoundaryProps = withErrorBoundaryProps;