UNPKG

136 kBJavaScriptView Raw
1/**
2 * react-router v8.5.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 */
11import { AsyncLocalStorage } from "node:async_hooks";
12import * as React from "react";
13import { parse, serialize, splitSetCookieString } from "cookie-es";
14import { BrowserRouter, Form, HashRouter, Link, Links, MemoryRouter, Meta, NavLink, Navigate, Outlet, Outlet as Outlet$1, Route, Router, RouterProvider, Routes, ScrollRestoration, StaticRouter, StaticRouterProvider, UNSAFE_AwaitContextProvider, UNSAFE_WithComponentProps, UNSAFE_WithErrorBoundaryProps, UNSAFE_WithHydrateFallbackProps, unstable_HistoryRouter } from "react-router/internal/react-server-client";
15//#region lib/router/url.ts
16const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i;
17//#endregion
18//#region lib/router/history.ts
19function invariant$1(value, message) {
20 if (value === false || value === null || typeof value === "undefined") throw new Error(message);
21}
22function warning(cond, message) {
23 if (!cond) {
24 if (typeof console !== "undefined") console.warn(message);
25 try {
26 throw new Error(message);
27 } catch {}
28 }
29}
30function createKey$1() {
31 return Math.random().toString(36).substring(2, 10);
32}
33/**
34* Creates a Location object with a unique key from the given Path
35*/
36function createLocation(current, to, state = null, key, mask) {
37 return {
38 pathname: typeof current === "string" ? current : current.pathname,
39 search: "",
40 hash: "",
41 ...typeof to === "string" ? parsePath(to) : to,
42 state,
43 key: to && to.key || key || createKey$1(),
44 mask
45 };
46}
47/**
48* Creates a string URL path from the given pathname, search, and hash components.
49*
50* @public
51* @category Utils
52* @param path The pathname, search, and hash components to combine.
53* @returns The combined URL path.
54*/
55function createPath({ pathname = "/", search = "", hash = "" }) {
56 if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
57 if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
58 return pathname;
59}
60/**
61* Parses a string URL path into its separate pathname, search, and hash components.
62*
63* @public
64* @category Utils
65* @param path The URL path to parse.
66* @returns The parsed pathname, search, and hash components.
67*/
68function parsePath(path) {
69 let parsedPath = {};
70 if (path) {
71 let hashIndex = path.indexOf("#");
72 if (hashIndex >= 0) {
73 parsedPath.hash = path.substring(hashIndex);
74 path = path.substring(0, hashIndex);
75 }
76 let searchIndex = path.indexOf("?");
77 if (searchIndex >= 0) {
78 parsedPath.search = path.substring(searchIndex);
79 path = path.substring(0, searchIndex);
80 }
81 if (path) parsedPath.pathname = path;
82 }
83 return parsedPath;
84}
85//#endregion
86//#region lib/router/navigation.ts
87const DEFAULT_NAVIGATION_URL = new URL("http://localhost");
88function isSameOrigin(a, b) {
89 return a.origin === b.origin && (a.origin !== "null" || a.protocol === b.protocol && a.host === b.host);
90}
91function isExplicitUrl(destination, target) {
92 if (destination.startsWith("//")) return true;
93 let protocol = target.protocol.toLowerCase();
94 if (!destination.toLowerCase().startsWith(protocol)) return false;
95 return target.host === "" || destination.slice(protocol.length).startsWith("//");
96}
97function validateDocumentNavigationTarget(destination) {
98 let normalized = destination.replace(/[\t\n\r]/g, "");
99 let start = 0;
100 while (normalized.charCodeAt(start) <= 32) start++;
101 normalized = normalized.slice(start);
102 if (!ABSOLUTE_URL_REGEX.test(normalized)) return;
103 let target;
104 try {
105 target = new URL(destination, DEFAULT_NAVIGATION_URL);
106 } catch {
107 return;
108 }
109 if (!isExplicitUrl(destination, target)) throw new Error("External navigation is not allowed");
110}
111function validateNavigationTarget(original, resolved, currentUrl, externalPolicy) {
112 let originalUrl = null;
113 try {
114 originalUrl = original == null ? null : new URL(original, currentUrl);
115 } catch {}
116 let resolvedUrl = new URL(resolved, currentUrl);
117 let originalIsExternal = originalUrl != null && !isSameOrigin(originalUrl, currentUrl);
118 let resolvedIsExternal = !isSameOrigin(resolvedUrl, currentUrl);
119 if (externalPolicy === "reject") {
120 if (originalIsExternal || resolvedIsExternal) throw new Error("External navigation is not allowed");
121 } else if (resolvedIsExternal) {
122 if (originalUrl == null || !isExplicitUrl(original, originalUrl) || !isSameOrigin(originalUrl, resolvedUrl)) throw new Error("External navigation is not allowed");
123 }
124}
125//#endregion
126//#region lib/router/utils.ts
127/**
128* Creates a type-safe {@link RouterContext} object that can be used to
129* store and retrieve arbitrary values in [`action`](../../start/framework/route-module#action)s,
130* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
131* Similar to React's [`createContext`](https://react.dev/reference/react/createContext),
132* but specifically designed for React Router's request/response lifecycle.
133*
134* If a `defaultValue` is provided, it will be returned from `context.get()`
135* when no value has been set for the context. Otherwise, reading this context
136* when no value has been set will throw an error.
137*
138* ```tsx filename=app/context.ts
139* import { createContext } from "react-router";
140*
141* // Create a context for user data
142* export const userContext =
143* createContext<User | null>(null);
144* ```
145*
146* ```tsx filename=app/middleware/auth.ts
147* import { getUserFromSession } from "~/auth.server";
148* import { userContext } from "~/context";
149*
150* export const authMiddleware = async ({
151* context,
152* request,
153* }) => {
154* const user = await getUserFromSession(request);
155* context.set(userContext, user);
156* };
157* ```
158*
159* ```tsx filename=app/routes/profile.tsx
160* import { userContext } from "~/context";
161*
162* export async function loader({
163* context,
164* }: Route.LoaderArgs) {
165* const user = context.get(userContext);
166*
167* if (!user) {
168* throw new Response("Unauthorized", { status: 401 });
169* }
170*
171* return { user };
172* }
173* ```
174*
175* @public
176* @category Utils
177* @mode framework
178* @mode data
179* @param defaultValue An optional default value for the context. This value
180* will be returned if no value has been set for this context.
181* @returns A {@link RouterContext} object that can be used with
182* `context.get()` and `context.set()` in [`action`](../../start/framework/route-module#action)s,
183* [`loader`](../../start/framework/route-module#loader)s, and [middleware](../../how-to/middleware).
184*/
185function createContext(defaultValue) {
186 return { defaultValue };
187}
188/**
189* Provides methods for writing/reading values in application context in a
190* type-safe way. Primarily for usage with [middleware](../../how-to/middleware).
191*
192* @example
193* import {
194* createContext,
195* RouterContextProvider
196* } from "react-router";
197*
198* const userContext = createContext<User | null>(null);
199* const contextProvider = new RouterContextProvider();
200* contextProvider.set(userContext, getUser());
201* // ^ Type-safe
202* const user = contextProvider.get(userContext);
203* // ^ User
204*
205* @public
206* @category Utils
207* @mode framework
208* @mode data
209*/
210var RouterContextProvider = class {
211 #map = /* @__PURE__ */ new Map();
212 /**
213 * Create a new `RouterContextProvider` instance
214 * @param init An optional initial context map to populate the provider with
215 */
216 constructor(init) {
217 if (init) for (let [context, value] of init) this.set(context, value);
218 }
219 /**
220 * Access a value from the context. If no value has been set for the context,
221 * it will return the context's `defaultValue` if provided, or throw an error
222 * if no `defaultValue` was set.
223 * @param context The context to get the value for
224 * @returns The value for the context, or the context's `defaultValue` if no
225 * value was set
226 */
227 get(context) {
228 if (this.#map.has(context)) return this.#map.get(context);
229 if (context.defaultValue !== void 0) return context.defaultValue;
230 throw new Error("No value found for context");
231 }
232 /**
233 * Set a value for the context. If the context already has a value set, this
234 * will overwrite it.
235 *
236 * @param context The context to set the value for
237 * @param value The value to set for the context
238 * @returns {void}
239 */
240 set(context, value) {
241 this.#map.set(context, value);
242 }
243};
244const unsupportedLazyRouteObjectKeys = new Set([
245 "lazy",
246 "caseSensitive",
247 "path",
248 "id",
249 "index",
250 "children",
251 "unstable_validateParams"
252]);
253function isUnsupportedLazyRouteObjectKey(key) {
254 return unsupportedLazyRouteObjectKeys.has(key);
255}
256const unsupportedLazyRouteFunctionKeys = new Set([
257 "lazy",
258 "caseSensitive",
259 "path",
260 "id",
261 "index",
262 "middleware",
263 "children",
264 "unstable_validateParams"
265]);
266function isUnsupportedLazyRouteFunctionKey(key) {
267 return unsupportedLazyRouteFunctionKeys.has(key);
268}
269function isIndexRoute(route) {
270 return route.index === true;
271}
272function defaultMapRouteProperties(route) {
273 let updates = {};
274 if (route.Component) Object.assign(updates, {
275 element: React.createElement(route.Component),
276 Component: void 0
277 });
278 if (route.HydrateFallback) Object.assign(updates, {
279 hydrateFallbackElement: React.createElement(route.HydrateFallback),
280 HydrateFallback: void 0
281 });
282 if (route.ErrorBoundary) Object.assign(updates, {
283 errorElement: React.createElement(route.ErrorBoundary),
284 ErrorBoundary: void 0
285 });
286 return updates;
287}
288function convertRoutesToDataRoutes(routes, mapRouteProperties = defaultMapRouteProperties, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
289 return routes.map((route, index) => {
290 let treePath = [...parentPath, String(index)];
291 let id = typeof route.id === "string" ? route.id : treePath.join("-");
292 invariant$1(route.index !== true || !route.children, `Cannot specify children on an index route`);
293 invariant$1(allowInPlaceMutations || !manifest[id], `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`);
294 if (isIndexRoute(route)) {
295 let indexRoute = {
296 ...route,
297 id
298 };
299 manifest[id] = mergeRouteUpdates(indexRoute, mapRouteProperties(indexRoute));
300 return indexRoute;
301 } else {
302 let pathOrLayoutRoute = {
303 ...route,
304 id,
305 children: void 0
306 };
307 manifest[id] = mergeRouteUpdates(pathOrLayoutRoute, mapRouteProperties(pathOrLayoutRoute));
308 if (route.children) pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest, allowInPlaceMutations);
309 return pathOrLayoutRoute;
310 }
311 });
312}
313function mergeRouteUpdates(route, updates) {
314 return Object.assign(route, {
315 ...updates,
316 ...typeof updates.lazy === "object" && updates.lazy != null ? { lazy: {
317 ...route.lazy,
318 ...updates.lazy
319 } } : {}
320 });
321}
322/**
323* Matches the given routes to a location and returns the match data.
324*
325* @example
326* import { matchRoutes } from "react-router";
327*
328* let routes = [{
329* path: "/",
330* Component: Root,
331* children: [{
332* path: "dashboard",
333* Component: Dashboard,
334* }]
335* }];
336*
337* matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]
338*
339* @public
340* @category Utils
341* @param routes The array of route objects to match against.
342* @param locationArg The location to match against, either a string path or a
343* partial {@link Location} object
344* @param basename Optional base path to strip from the location before matching.
345* Defaults to `/`.
346* @returns An array of matched routes, or `null` if no matches were found.
347*/
348function matchRoutes(routes, locationArg, basename = "/") {
349 return matchRoutesImpl(routes, locationArg, basename, false);
350}
351function matchRoutesImpl(routes, locationArg, basename, allowPartial, precomputedBranches) {
352 let pathname = stripBasename((typeof locationArg === "string" ? parsePath(locationArg) : locationArg).pathname || "/", basename);
353 if (pathname == null) return null;
354 let branches = precomputedBranches ?? flattenAndRankRoutes(routes);
355 let matches = null;
356 let decoded = decodePath(pathname);
357 for (let i = 0; matches == null && i < branches.length; ++i) matches = matchRouteBranch(branches[i], decoded, allowPartial);
358 return matches;
359}
360function convertRouteMatchToUiMatch(match, loaderData) {
361 let { route, pathname, params } = match;
362 return {
363 id: route.id,
364 pathname,
365 params,
366 loaderData: loaderData[route.id],
367 handle: route.handle
368 };
369}
370function flattenAndRankRoutes(routes) {
371 let branches = flattenRoutes(routes);
372 rankRouteBranches(branches);
373 return branches;
374}
375function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
376 let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
377 let meta = {
378 relativePath: relativePath === void 0 ? route.path || "" : relativePath,
379 caseSensitive: route.caseSensitive === true,
380 childrenIndex: index,
381 route
382 };
383 if (meta.relativePath.startsWith("/")) {
384 if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) return;
385 invariant$1(meta.relativePath.startsWith(parentPath), `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.`);
386 meta.relativePath = meta.relativePath.slice(parentPath.length);
387 }
388 let path = joinPaths([parentPath, meta.relativePath]);
389 let routesMeta = parentsMeta.concat(meta);
390 if (route.children && route.children.length > 0) {
391 invariant$1(route.index !== true, `Index routes must not have child routes. Please remove all child routes from route path "${path}".`);
392 flattenRoutes(route.children, branches, routesMeta, path, hasParentOptionalSegments);
393 }
394 if (route.path == null && !route.index) return;
395 branches.push({
396 path,
397 score: computeScore(path, route.index),
398 routesMeta: routesMeta.map((meta, i) => {
399 let [matcher, params] = compilePath(meta.relativePath, meta.caseSensitive, i === routesMeta.length - 1);
400 return {
401 ...meta,
402 matcher,
403 compiledParams: params
404 };
405 })
406 });
407 };
408 routes.forEach((route, index) => {
409 if (route.path === "" || !route.path?.includes("?")) flattenRoute(route, index);
410 else for (let exploded of explodeOptionalSegments(route.path)) flattenRoute(route, index, true, exploded);
411 });
412 return branches;
413}
414function explodeOptionalSegments(path) {
415 let segments = path.split("/");
416 if (segments.length === 0) return [];
417 let [first, ...rest] = segments;
418 let isOptional = first.endsWith("?");
419 let required = first.replace(/\?$/, "");
420 if (rest.length === 0) return isOptional ? [required, ""] : [required];
421 let restExploded = explodeOptionalSegments(rest.join("/"));
422 let result = [];
423 result.push(...restExploded.map((subpath) => subpath === "" ? required : [required, subpath].join("/")));
424 if (isOptional) result.push(...restExploded);
425 return result.map((exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded);
426}
427function rankRouteBranches(branches) {
428 branches.sort((a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(a.routesMeta.map((meta) => meta.childrenIndex), b.routesMeta.map((meta) => meta.childrenIndex)));
429}
430const paramRe = /^:[\w-]+$/;
431const partialParamRe = /^:[\w-]+/;
432const partialDynamicSegmentValue = 3.5;
433const dynamicSegmentValue = 3;
434const indexRouteValue = 2;
435const emptySegmentValue = 1;
436const staticSegmentValue = 10;
437const splatPenalty = -2;
438const isSplat = (s) => s === "*";
439function computeScore(path, index) {
440 let segments = path.split("/");
441 let initialScore = segments.length;
442 if (segments.some(isSplat)) initialScore += splatPenalty;
443 if (index) initialScore += indexRouteValue;
444 return segments.filter((s) => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : partialParamRe.test(segment) ? partialDynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
445}
446function compareIndexes(a, b) {
447 return a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]) ? a[a.length - 1] - b[b.length - 1] : 0;
448}
449function matchRouteBranch(branch, pathname, allowPartial = false) {
450 let { routesMeta } = branch;
451 let matchedParams = {};
452 let matchedPathname = "/";
453 let matches = [];
454 for (let i = 0; i < routesMeta.length; ++i) {
455 let meta = routesMeta[i];
456 let end = i === routesMeta.length - 1;
457 let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
458 let pattern = {
459 path: meta.relativePath,
460 caseSensitive: meta.caseSensitive,
461 end
462 };
463 let match = meta.matcher && meta.compiledParams ? matchPathImpl(pattern, remainingPathname, meta.matcher, meta.compiledParams) : matchPath(pattern, remainingPathname);
464 let route = meta.route;
465 if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) match = matchPath({
466 path: meta.relativePath,
467 caseSensitive: meta.caseSensitive,
468 end: false
469 }, remainingPathname);
470 if (!match) return null;
471 Object.assign(matchedParams, match.params);
472 matches.push({
473 params: matchedParams,
474 pathname: joinPaths([matchedPathname, match.pathname]),
475 pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
476 route
477 });
478 if (match.pathnameBase !== "/") matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
479 }
480 return matches;
481}
482/**
483* Characters that `encodeURIComponent` escapes but that are valid literally in
484* a URL path segment. Per RFC 3986 §3.3, a path segment is made of `pchar`:
485*
486* ```
487* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
488* sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
489* ```
490*
491* `encodeURIComponent` targets query-string values, where `$ & + , ; = : @`
492* are delimiters and must be escaped — but in a path segment they carry no
493* special meaning, and browsers keep them literal in `location.pathname`.
494* (`! ' ( ) *` and the unreserved set are already left alone by
495* `encodeURIComponent`, so they need no restoring.)
496*/
497const PATH_PARAM_OVERESCAPED = {
498 "%24": "$",
499 "%26": "&",
500 "%2B": "+",
501 "%2C": ",",
502 "%3A": ":",
503 "%3B": ";",
504 "%3D": "=",
505 "%40": "@"
506};
507/**
508* Encodes a param value for interpolation into a single URL path segment.
509*
510* Escapes characters that would break the path (`/ ? # %`, whitespace,
511* non-ASCII, …) while leaving characters that RFC 3986 permits literally in a
512* path segment untouched. Escaping those would needlessly rewrite URLs — e.g.
513* a semver build param `1.0.0+1` would become `1.0.0%2B1` even though browsers
514* display and match the `+` literally in `location.pathname`.
515*
516* See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3))
517*
518* @param value The param value to encode.
519* @returns The encoded value, safe for use as a single path segment.
520*/
521function encodePathParam(value) {
522 return encodeURIComponent(value).replace(/%(?:24|26|2B|2C|3A|3B|3D|40)/g, (match) => PATH_PARAM_OVERESCAPED[match]);
523}
524/**
525* Performs pattern matching on a URL pathname and returns information about
526* the match.
527*
528* @public
529* @category Utils
530* @param pattern The pattern to match against the URL pathname. This can be a
531* string or a {@link PathPattern} object. If a string is provided, it will be
532* treated as a pattern with `caseSensitive` set to `false` and `end` set to
533* `true`.
534* @param pathname The URL pathname to match against the pattern.
535* @returns A path match object if the pattern matches the pathname,
536* or `null` if it does not match.
537*/
538function matchPath(pattern, pathname) {
539 if (typeof pattern === "string") pattern = {
540 path: pattern,
541 caseSensitive: false,
542 end: true
543 };
544 let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
545 return matchPathImpl(pattern, pathname, matcher, compiledParams);
546}
547function matchPathImpl(pattern, pathname, matcher, compiledParams) {
548 let match = pathname.match(matcher);
549 if (!match) return null;
550 let matchedPathname = match[0];
551 let pathnameBase = removeTrailingSlash(matchedPathname, 1);
552 let captureGroups = match.slice(1);
553 return {
554 params: compiledParams.reduce((memo, { paramName, isOptional }, index) => {
555 if (paramName === "*") {
556 let splatValue = captureGroups[index] || "";
557 pathnameBase = removeTrailingSlash(matchedPathname.slice(0, matchedPathname.length - splatValue.length), 1);
558 }
559 const value = captureGroups[index];
560 if (isOptional && !value) memo[paramName] = void 0;
561 else memo[paramName] = (value || "").replace(/%2F/g, "/");
562 return memo;
563 }, {}),
564 pathname: matchedPathname,
565 pathnameBase,
566 pattern
567 };
568}
569function compilePath(path, caseSensitive = false, end = true) {
570 warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), `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(/\*$/, "/*")}".`);
571 let params = [];
572 let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(/\/:([\w-]+)(\?)?/g, (match, paramName, isOptional, index, str) => {
573 params.push({
574 paramName,
575 isOptional: isOptional != null
576 });
577 if (isOptional) {
578 let nextChar = str.charAt(index + match.length);
579 if (nextChar && nextChar !== "/") return "/([^\\/]*)";
580 return "(?:/([^\\/]*))?";
581 }
582 return "/([^\\/]+)";
583 }).replace(/\/((?:[^/?()[\]*^\\]|\\.)+)\?(?=\/|$|\()/g, "(?:/$1)?");
584 if (path.endsWith("*")) {
585 params.push({ paramName: "*" });
586 regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
587 } else if (end) regexpSource += "\\/*$";
588 else if (path !== "" && path !== "/") regexpSource += "(?:(?=\\/|$))";
589 return [new RegExp(regexpSource, caseSensitive ? void 0 : "i"), params];
590}
591function decodePath(value) {
592 try {
593 return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
594 } catch (error) {
595 warning(false, `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}).`);
596 return value;
597 }
598}
599function stripBasename(pathname, basename) {
600 if (basename === "/") return pathname;
601 if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) return null;
602 let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
603 let nextChar = pathname.charAt(startIndex);
604 if (nextChar && nextChar !== "/") return null;
605 return pathname.slice(startIndex) || "/";
606}
607function prependBasename({ basename, pathname }) {
608 return pathname === "/" ? basename : joinPaths([basename, pathname]);
609}
610const isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
611/**
612* Returns a resolved {@link Path} object relative to the given pathname.
613*
614* @public
615* @category Utils
616* @param to The path to resolve, either a string or a partial {@link Path}
617* object.
618* @param fromPathname The pathname to resolve the path from. Defaults to `/`.
619* @returns A {@link Path} object with the resolved pathname, search, and hash.
620*/
621function resolvePath(to, fromPathname = "/") {
622 let { pathname: toPathname, search = "", hash = "" } = typeof to === "string" ? parsePath(to) : to;
623 let pathname;
624 if (toPathname) {
625 toPathname = removeDoubleSlashes(toPathname);
626 if (toPathname.startsWith("/") || toPathname.startsWith("\\")) pathname = resolvePathname(toPathname.substring(1), "/");
627 else pathname = resolvePathname(toPathname, fromPathname);
628 } else pathname = fromPathname;
629 return {
630 pathname,
631 search: normalizeSearch(search),
632 hash: normalizeHash(hash)
633 };
634}
635function resolvePathname(relativePath, fromPathname) {
636 let segments = removeTrailingSlash(fromPathname).split("/");
637 relativePath.split("/").forEach((segment) => {
638 if (segment === "..") {
639 if (segments.length > 1) segments.pop();
640 } else if (segment !== ".") segments.push(segment);
641 });
642 return segments.length > 1 ? segments.join("/") : "/";
643}
644function getInvalidPathError(char, field, dest, path) {
645 return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(path)}]. 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.`;
646}
647function getPathContributingMatches(matches) {
648 return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
649}
650function getResolveToMatches(matches) {
651 let pathMatches = getPathContributingMatches(matches);
652 return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
653}
654function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
655 let to;
656 if (typeof toArg === "string") to = parsePath(toArg);
657 else {
658 to = { ...toArg };
659 invariant$1(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
660 invariant$1(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
661 invariant$1(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
662 }
663 let isEmptyPath = toArg === "" || to.pathname === "";
664 let toPathname = isEmptyPath ? "/" : to.pathname;
665 let from;
666 if (toPathname == null) from = locationPathname;
667 else {
668 let routePathnameIndex = routePathnames.length - 1;
669 if (!isPathRelative && toPathname.startsWith("..")) {
670 let toSegments = toPathname.split("/");
671 while (toSegments[0] === "..") {
672 toSegments.shift();
673 routePathnameIndex -= 1;
674 }
675 to.pathname = toSegments.join("/");
676 }
677 from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
678 }
679 let path = resolvePath(to, from);
680 let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
681 let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
682 if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) path.pathname += "/";
683 return path;
684}
685const removeDoubleSlashes = (path) => path.replace(/[\\/]{2,}/g, "/");
686const joinPaths = (paths) => removeDoubleSlashes(paths.join("/"));
687function removeTrailingSlash(path, minLength = 0) {
688 let end = path.length;
689 while (end > minLength && path.charCodeAt(end - 1) === 47) end--;
690 return end === path.length ? path : path.slice(0, end);
691}
692const normalizePathname = (pathname) => removeTrailingSlash(pathname).replace(/^\/*/, "/");
693const normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
694const normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
695var DataWithResponseInit = class {
696 type = "DataWithResponseInit";
697 data;
698 init;
699 constructor(data, init) {
700 this.data = data;
701 this.init = init || null;
702 }
703};
704/**
705* Create "responses" that contain `headers`/`status` without forcing
706* serialization into an actual [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
707*
708* @example
709* import { data } from "react-router";
710*
711* export async function action({ request }: Route.ActionArgs) {
712* let formData = await request.formData();
713* let item = await createItem(formData);
714* return data(item, {
715* headers: { "X-Custom-Header": "value" }
716* status: 201,
717* });
718* }
719*
720* @public
721* @category Utils
722* @mode framework
723* @mode data
724* @param data The data to be included in the response.
725* @param init The status code or a `ResponseInit` object to be included in the
726* response.
727* @returns A {@link DataWithResponseInit} instance containing the data and
728* response init.
729*/
730function data(data, init) {
731 return new DataWithResponseInit(data, typeof init === "number" ? { status: init } : init);
732}
733/**
734* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
735* Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
736* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
737*
738* This utility accepts absolute URLs and can navigate to external domains, so
739* the application should validate any user-supplied inputs to redirects.
740*
741* @example
742* import { redirect } from "react-router";
743*
744* export async function loader({ request }: Route.LoaderArgs) {
745* if (!isLoggedIn(request))
746* throw redirect("/login");
747* }
748*
749* // ...
750* }
751*
752* @public
753* @category Utils
754* @mode framework
755* @mode data
756* @param url The URL to redirect to.
757* @param init The status code or a `ResponseInit` object to be included in the
758* response.
759* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
760* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
761* header.
762*/
763const redirect$1 = (url, init = 302) => {
764 validateDocumentNavigationTarget(url);
765 let responseInit = init;
766 if (typeof responseInit === "number") responseInit = { status: responseInit };
767 let headers = new Headers(responseInit.headers);
768 headers.set("Location", url);
769 if (typeof responseInit.status === "undefined") responseInit = {
770 ...responseInit,
771 status: 302
772 };
773 return new Response(null, {
774 ...responseInit,
775 headers
776 });
777};
778/**
779* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
780* that will force a document reload to the new location. Sets the status code
781* and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
782* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
783*
784* This utility accepts absolute URLs and can navigate to external domains, so
785* the application should validate any user-supplied inputs to redirects.
786*
787* ```tsx filename=routes/logout.tsx
788* import { redirectDocument } from "react-router";
789*
790* import { destroySession } from "../sessions.server";
791*
792* export async function action({ request }: Route.ActionArgs) {
793* let session = await getSession(request.headers.get("Cookie"));
794* return redirectDocument("/", {
795* headers: { "Set-Cookie": await destroySession(session) }
796* });
797* }
798* ```
799*
800* @public
801* @category Utils
802* @mode framework
803* @mode data
804* @param url The URL to redirect to.
805* @param init The status code or a `ResponseInit` object to be included in the
806* response.
807* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
808* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
809* header.
810*/
811const redirectDocument$1 = (url, init) => {
812 let response = redirect$1(url, init);
813 response.headers.set("X-Remix-Reload-Document", "true");
814 return response;
815};
816/**
817* A redirect [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
818* that will perform a [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)
819* instead of a [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
820* for client-side navigation redirects. Sets the status code and the [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
821* header. Defaults to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302).
822*
823* @example
824* import { replace } from "react-router";
825*
826* export async function loader() {
827* return replace("/new-location");
828* }
829*
830* @public
831* @category Utils
832* @mode framework
833* @mode data
834* @param url The URL to redirect to.
835* @param init The status code or a `ResponseInit` object to be included in the
836* response.
837* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
838* object with the redirect status and [`Location`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location)
839* header.
840*/
841const replace$1 = (url, init) => {
842 let response = redirect$1(url, init);
843 response.headers.set("X-Remix-Replace", "true");
844 return response;
845};
846var ErrorResponseImpl = class {
847 status;
848 statusText;
849 data;
850 error;
851 internal;
852 constructor(status, statusText, data, internal = false) {
853 this.status = status;
854 this.statusText = statusText || "";
855 this.internal = internal;
856 if (data instanceof Error) {
857 this.data = data.toString();
858 this.error = data;
859 } else this.data = data;
860 }
861};
862/**
863* Check if the given error is an {@link ErrorResponse} generated from a 4xx/5xx
864* [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
865* thrown from an [`action`](../../start/framework/route-module#action) or
866* [`loader`](../../start/framework/route-module#loader) function.
867*
868* @example
869* import { isRouteErrorResponse } from "react-router";
870*
871* export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
872* if (isRouteErrorResponse(error)) {
873* return (
874* <>
875* <p>Error: `${error.status}: ${error.statusText}`</p>
876* <p>{error.data}</p>
877* </>
878* );
879* }
880*
881* return (
882* <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p>
883* );
884* }
885*
886* @public
887* @category Utils
888* @mode framework
889* @mode data
890* @param error The error to check.
891* @returns `true` if the error is an {@link ErrorResponse}, `false` otherwise.
892*/
893function isRouteErrorResponse(error) {
894 return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
895}
896function getRoutePattern(matches) {
897 return joinPaths(matches.map((m) => m.route.path).filter(Boolean)) || "/";
898}
899function createDataFunctionUrl(request, path) {
900 let url = new URL(typeof request === "string" || request instanceof URL ? request : request.url);
901 let parsed = typeof path === "string" ? parsePath(path) : path;
902 url.pathname = parsed.pathname || "/";
903 if (parsed.search) {
904 let searchParams = new URLSearchParams(parsed.search);
905 let indexValues = searchParams.getAll("index");
906 searchParams.delete("index");
907 for (let value of indexValues.filter(Boolean)) searchParams.append("index", value);
908 let search = searchParams.toString();
909 url.search = search ? `?${search}` : "";
910 } else url.search = "";
911 url.hash = parsed.hash || "";
912 return url;
913}
914typeof window !== "undefined" && typeof window.document !== "undefined" && window.document.createElement;
915//#endregion
916//#region lib/router/instrumentation.ts
917const UninstrumentedSymbol = Symbol("Uninstrumented");
918function getRouteInstrumentationUpdates(fns, route) {
919 let aggregated = {
920 lazy: [],
921 "lazy.loader": [],
922 "lazy.action": [],
923 "lazy.middleware": [],
924 middleware: [],
925 loader: [],
926 action: []
927 };
928 fns.forEach((fn) => fn({
929 id: route.id,
930 index: route.index,
931 path: route.path,
932 instrument(i) {
933 if (i.lazy != null) aggregated.lazy.push(i.lazy);
934 if (i["lazy.loader"] != null) aggregated["lazy.loader"].push(i["lazy.loader"]);
935 if (i["lazy.action"] != null) aggregated["lazy.action"].push(i["lazy.action"]);
936 if (i["lazy.middleware"] != null) aggregated["lazy.middleware"].push(i["lazy.middleware"]);
937 if (i.middleware != null) aggregated.middleware.push(i.middleware);
938 if (i.loader != null) aggregated.loader.push(i.loader);
939 if (i.action != null) aggregated.action.push(i.action);
940 }
941 }));
942 let updates = {};
943 if (typeof route.lazy === "function" && aggregated.lazy.length > 0) {
944 let lazy = route.lazy;
945 updates.lazy = async (...args) => {
946 return throwOrReturnResult(await recurseRight(aggregated.lazy, void 0, () => lazy(...args), getInstrumentationInnerResult));
947 };
948 }
949 if (typeof route.lazy === "object") {
950 let lazyObject = route.lazy;
951 if (typeof lazyObject.middleware === "function" && aggregated["lazy.middleware"].length > 0) {
952 let middleware = lazyObject.middleware;
953 updates.lazy = Object.assign(updates.lazy || {}, { middleware: async (...args) => {
954 return throwOrReturnResult(await recurseRight(aggregated["lazy.middleware"], void 0, () => middleware(...args), getInstrumentationInnerResult));
955 } });
956 }
957 if (typeof lazyObject.loader === "function" && aggregated["lazy.loader"].length > 0) {
958 let loader = lazyObject.loader;
959 updates.lazy = Object.assign(updates.lazy || {}, { loader: async (...args) => {
960 return throwOrReturnResult(await recurseRight(aggregated["lazy.loader"], void 0, () => loader(...args), getInstrumentationInnerResult));
961 } });
962 }
963 if (typeof lazyObject.action === "function" && aggregated["lazy.action"].length > 0) {
964 let action = lazyObject.action;
965 updates.lazy = Object.assign(updates.lazy || {}, { action: async (...args) => {
966 return throwOrReturnResult(await recurseRight(aggregated["lazy.action"], void 0, () => action(...args), getInstrumentationInnerResult));
967 } });
968 }
969 }
970 if (typeof route.loader === "function" && aggregated.loader.length > 0) {
971 let original = getUninstrumentedHandler(route.loader);
972 let instrumented = async (...args) => {
973 return throwOrReturnResult(await recurseRight(aggregated.loader, getHandlerInfo(args[0]), () => original(...args), getInstrumentationInnerResult));
974 };
975 if (original.hydrate === true) instrumented.hydrate = true;
976 setUninstrumentedHandler(instrumented, original);
977 updates.loader = instrumented;
978 }
979 if (typeof route.action === "function" && aggregated.action.length > 0) {
980 let original = getUninstrumentedHandler(route.action);
981 let instrumented = async (...args) => {
982 return throwOrReturnResult(await recurseRight(aggregated.action, getHandlerInfo(args[0]), () => original(...args), getInstrumentationInnerResult));
983 };
984 setUninstrumentedHandler(instrumented, original);
985 updates.action = instrumented;
986 }
987 if (route.middleware && route.middleware.length > 0 && aggregated.middleware.length > 0) updates.middleware = route.middleware.map((middleware) => {
988 let original = getUninstrumentedHandler(middleware);
989 let instrumented = async (...args) => {
990 return throwOrReturnResult(await recurseRight(aggregated.middleware, getHandlerInfo(args[0]), () => original(...args), getInstrumentationInnerResult));
991 };
992 setUninstrumentedHandler(instrumented, original);
993 return instrumented;
994 });
995 return updates;
996}
997function getUninstrumentedHandler(handler) {
998 return handler[UninstrumentedSymbol] ?? handler;
999}
1000function setUninstrumentedHandler(handler, uninstrumentedHandler) {
1001 handler[UninstrumentedSymbol] = uninstrumentedHandler;
1002}
1003function throwOrReturnResult(result) {
1004 if (result.type === "error") throw result.value;
1005 return result.value;
1006}
1007async function recurseRight(impls, info, handler, getInnerResult, state = {
1008 result: null,
1009 innerResult: null
1010}, index = impls.length - 1) {
1011 let impl = impls[index];
1012 if (!impl) {
1013 try {
1014 state.result = {
1015 type: "success",
1016 value: await handler()
1017 };
1018 } catch (e) {
1019 state.result = {
1020 type: "error",
1021 value: e
1022 };
1023 }
1024 state.innerResult = getInnerResult(state.result, info);
1025 } else {
1026 let handlerPromise = void 0;
1027 let callHandler = async () => {
1028 if (handlerPromise) console.error("You cannot call instrumented handlers more than once");
1029 else handlerPromise = recurseRight(impls, info, handler, getInnerResult, state, index - 1);
1030 await handlerPromise;
1031 invariant$1(state.innerResult, "Expected an inner result");
1032 return state.innerResult;
1033 };
1034 try {
1035 await impl(callHandler, info);
1036 } catch (e) {
1037 console.error("An instrumentation function threw an error:", e);
1038 }
1039 if (!handlerPromise) await callHandler();
1040 await handlerPromise;
1041 }
1042 if (state.result) return state.result;
1043 state.result = {
1044 type: "error",
1045 value: /* @__PURE__ */ new Error("No result assigned in instrumentation chain.")
1046 };
1047 state.innerResult = getInnerResult(state.result, info);
1048 return state.result;
1049}
1050function getInstrumentationInnerResult(result) {
1051 if (result.type === "error" && result.value instanceof Error) return {
1052 status: "error",
1053 error: result.value
1054 };
1055 return {
1056 status: "success",
1057 error: void 0
1058 };
1059}
1060function getHandlerInfo(args) {
1061 let { request, context, params } = args;
1062 return {
1063 ...args,
1064 request: getReadonlyRequest(request),
1065 params: { ...params },
1066 context: getReadonlyContext(context)
1067 };
1068}
1069function getReadonlyRequest(request) {
1070 return {
1071 method: request.method,
1072 url: request.url,
1073 headers: { get: (...args) => request.headers.get(...args) }
1074 };
1075}
1076function getReadonlyContext(context) {
1077 return { get: (ctx) => context.get(ctx) };
1078}
1079//#endregion
1080//#region lib/router/matcher.ts
1081var V6RegExMatcher = class {
1082 #routes = [];
1083 #branches = [];
1084 #basename;
1085 #matchCost = 0;
1086 constructor(basename) {
1087 this.#basename = basename;
1088 }
1089 update(routes) {
1090 this.#routes = routes;
1091 this.#branches = flattenAndRankRoutes(routes);
1092 this.#matchCost = this.#branches.reduce((total, branch) => total + branch.routesMeta.length, 0);
1093 }
1094 get matchCost() {
1095 return this.#matchCost;
1096 }
1097 match(locationArg, allowPartial = false) {
1098 return matchRoutesImpl(this.#routes, locationArg, this.#basename, allowPartial, this.#branches);
1099 }
1100};
1101//#endregion
1102//#region lib/router/router.ts
1103const validMutationMethodsArr = [
1104 "POST",
1105 "PUT",
1106 "PATCH",
1107 "DELETE"
1108];
1109const validMutationMethods = new Set(validMutationMethodsArr);
1110const validRequestMethodsArr = ["GET", ...validMutationMethodsArr];
1111const validRequestMethods = new Set(validRequestMethodsArr);
1112const redirectStatusCodes = new Set([
1113 301,
1114 302,
1115 303,
1116 307,
1117 308
1118]);
1119const ResetLoaderDataSymbol = Symbol("ResetLoaderData");
1120function createDataRouteMatcher(future, basename) {
1121 if (future.unstable_routePatternMatching) {
1122 let RoutePatternMatcher = void 0;
1123 invariant$1(RoutePatternMatcher, "You must call unstable_preloadRoutePattern() from \"react-router/route-pattern\" before enabling future.unstable_routePatternMatching.");
1124 return new RoutePatternMatcher(basename);
1125 }
1126 return new V6RegExMatcher(basename);
1127}
1128/**
1129* Create a static handler to perform server-side data loading
1130*
1131* @example
1132* export async function handleRequest(request: Request) {
1133* let { query, dataRoutes } = createStaticHandler(routes);
1134* let context = await query(request);
1135*
1136* if (context instanceof Response) {
1137* return context;
1138* }
1139*
1140* let router = createStaticRouter(dataRoutes, context);
1141* return new Response(
1142* ReactDOMServer.renderToString(<StaticRouterProvider ... />),
1143* { headers: { "Content-Type": "text/html" } }
1144* );
1145* }
1146*
1147* @public
1148* @category Data Routers
1149* @mode data
1150* @param routes The {@link RouteObject | route objects} to create a static
1151* handler for
1152* @param opts Options
1153* @param opts.basename The base URL for the static handler (default: `/`)
1154* @param opts.future Future flags for the static handler
1155* @returns A static handler that can be used to query data for the provided
1156* routes
1157*/
1158function createStaticHandler(routes, opts) {
1159 invariant$1(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
1160 let manifest = {};
1161 let basename = (opts ? opts.basename : null) || "/";
1162 let _mapRouteProperties = opts?.mapRouteProperties;
1163 let mapRouteProperties = _mapRouteProperties ? _mapRouteProperties : () => ({});
1164 let dataRouteMatcher = createDataRouteMatcher({ ...opts?.future }, basename);
1165 if (opts?.instrumentations) {
1166 let instrumentations = opts.instrumentations;
1167 mapRouteProperties = (route) => {
1168 return {
1169 ..._mapRouteProperties?.(route),
1170 ...getRouteInstrumentationUpdates(instrumentations.map((i) => i.route).filter(Boolean), route)
1171 };
1172 };
1173 }
1174 let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, void 0, manifest);
1175 dataRouteMatcher.update(dataRoutes);
1176 let match = (locationArg) => dataRouteMatcher.match(locationArg);
1177 /**
1178 * The query() method is intended for document requests, in which we want to
1179 * call an optional action and potentially multiple loaders for all nested
1180 * routes. It returns a StaticHandlerContext object, which is very similar
1181 * to the router state (location, loaderData, actionData, errors, etc.) and
1182 * also adds SSR-specific information such as the statusCode and headers
1183 * from action/loaders Responses.
1184 *
1185 * It _should_ never throw and should report all errors through the
1186 * returned handlerContext.errors object, properly associating errors to
1187 * their error boundary. Additionally, it tracks _deepestRenderedBoundaryId
1188 * which can be used to emulate React error boundaries during SSR by performing
1189 * a second pass only down to the boundaryId.
1190 *
1191 * The one exception where we do not return a StaticHandlerContext is when a
1192 * redirect response is returned or thrown from any action/loader. We
1193 * propagate that out and return the raw Response so the HTTP server can
1194 * return it directly.
1195 *
1196 * - `opts.requestContext` is an optional server context that will be passed
1197 * to actions/loaders in the `context` parameter
1198 * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent
1199 * the bubbling of errors which allows single-fetch-type implementations
1200 * where the client will handle the bubbling and we may need to return data
1201 * for the handling route
1202 */
1203 async function query(request, { requestContext, filterMatchesToLoad, skipLoaderErrorBubbling, skipRevalidation, dataStrategy, generateMiddlewareResponse, normalizePath } = {}) {
1204 let normalizePathImpl = normalizePath || defaultNormalizePath;
1205 let method = request.method;
1206 let location = createLocation("", normalizePathImpl(request), null, "default");
1207 let matches = dataRouteMatcher.match(location);
1208 requestContext = requestContext != null ? requestContext : new RouterContextProvider();
1209 if (!isValidMethod(method) && method !== "HEAD") {
1210 let error = getInternalRouterError(405, { method });
1211 let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
1212 let staticContext = {
1213 basename,
1214 location,
1215 matches: methodNotAllowedMatches,
1216 loaderData: {},
1217 actionData: null,
1218 errors: { [route.id]: error },
1219 statusCode: error.status,
1220 loaderHeaders: {},
1221 actionHeaders: {},
1222 _match: match
1223 };
1224 return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
1225 } else if (!matches) {
1226 let error = getInternalRouterError(404, { pathname: location.pathname });
1227 let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
1228 let staticContext = {
1229 basename,
1230 location,
1231 matches: notFoundMatches,
1232 loaderData: {},
1233 actionData: null,
1234 errors: { [route.id]: error },
1235 statusCode: error.status,
1236 loaderHeaders: {},
1237 actionHeaders: {},
1238 _match: match
1239 };
1240 return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
1241 }
1242 if (generateMiddlewareResponse) {
1243 invariant$1(requestContext instanceof RouterContextProvider, "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `RouterContextProvider`");
1244 try {
1245 await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties);
1246 let renderedStaticContext;
1247 let response = await runServerMiddlewarePipeline({
1248 request,
1249 url: createDataFunctionUrl(request, location),
1250 pattern: getRoutePattern(matches),
1251 matches,
1252 params: matches[0].params,
1253 context: requestContext
1254 }, async () => {
1255 return await generateMiddlewareResponse(async (revalidationRequest, opts = {}) => {
1256 let result = await queryImpl(revalidationRequest, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null, "filterMatchesToLoad" in opts ? opts.filterMatchesToLoad ?? null : filterMatchesToLoad ?? null, skipRevalidation === true);
1257 if (isResponse(result)) return result;
1258 renderedStaticContext = {
1259 location,
1260 basename,
1261 ...result,
1262 _match: match
1263 };
1264 return renderedStaticContext;
1265 });
1266 }, async (error, routeId) => {
1267 if (isRedirectResponse(error)) return error;
1268 if (isResponse(error)) try {
1269 error = new ErrorResponseImpl(error.status, error.statusText, await parseResponseBody(error));
1270 } catch (e) {
1271 error = e;
1272 }
1273 if (isDataWithResponseInit(error)) error = dataWithResponseInitToErrorResponse(error);
1274 if (renderedStaticContext) {
1275 if (routeId in renderedStaticContext.loaderData) renderedStaticContext.loaderData[routeId] = void 0;
1276 let staticContext = getStaticContextFromError(dataRoutes, renderedStaticContext, error, skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id);
1277 return generateMiddlewareResponse(() => Promise.resolve(staticContext));
1278 } else {
1279 let staticContext = {
1280 matches,
1281 location,
1282 basename,
1283 loaderData: {},
1284 actionData: null,
1285 errors: { [skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, matches.find((m) => m.route.id === routeId || m.route.loader)?.route.id || routeId).route.id]: error },
1286 statusCode: isRouteErrorResponse(error) ? error.status : 500,
1287 actionHeaders: {},
1288 loaderHeaders: {},
1289 _match: match
1290 };
1291 return generateMiddlewareResponse(() => Promise.resolve(staticContext));
1292 }
1293 });
1294 invariant$1(isResponse(response), "Expected a response in query()");
1295 return response;
1296 } catch (e) {
1297 if (isResponse(e)) return e;
1298 throw e;
1299 }
1300 }
1301 let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null, filterMatchesToLoad || null, skipRevalidation === true);
1302 if (isResponse(result)) return result;
1303 return {
1304 location,
1305 basename,
1306 ...result,
1307 _match: match
1308 };
1309 }
1310 /**
1311 * The queryRoute() method is intended for targeted route requests, either
1312 * for fetch ?_data requests or resource route requests. In this case, we
1313 * are only ever calling a single action or loader, and we are returning the
1314 * returned value directly. In most cases, this will be a Response returned
1315 * from the action/loader, but it may be a primitive or other value as well -
1316 * and in such cases the calling context should handle that accordingly.
1317 *
1318 * We do respect the throw/return differentiation, so if an action/loader
1319 * throws, then this method will throw the value. This is important so we
1320 * can do proper boundary identification in Remix where a thrown Response
1321 * must go to the Catch Boundary but a returned Response is happy-path.
1322 *
1323 * One thing to note is that any Router-initiated Errors that make sense
1324 * to associate with a status code will be thrown as an ErrorResponse
1325 * instance which include the raw Error, such that the calling context can
1326 * serialize the error as they see fit while including the proper response
1327 * code. Examples here are 404 and 405 errors that occur prior to reaching
1328 * any user-defined loaders.
1329 *
1330 * - `opts.routeId` allows you to specify the specific route handler to call.
1331 * If not provided the handler will determine the proper route by matching
1332 * against `request.url`
1333 * - `opts.requestContext` is an optional server context that will be passed
1334 * to actions/loaders in the `context` parameter
1335 */
1336 async function queryRoute(request, { routeId, requestContext, dataStrategy, generateMiddlewareResponse, normalizePath } = {}) {
1337 let normalizePathImpl = normalizePath || defaultNormalizePath;
1338 let method = request.method;
1339 let location = createLocation("", normalizePathImpl(request), null, "default");
1340 let matches = dataRouteMatcher.match(location);
1341 requestContext = requestContext != null ? requestContext : new RouterContextProvider();
1342 if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") throw getInternalRouterError(405, { method });
1343 else if (!matches) throw getInternalRouterError(404, { pathname: location.pathname });
1344 let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
1345 if (routeId && !match) throw getInternalRouterError(403, {
1346 pathname: location.pathname,
1347 routeId
1348 });
1349 else if (!match) throw getInternalRouterError(404, { pathname: location.pathname });
1350 if (generateMiddlewareResponse) {
1351 invariant$1(requestContext instanceof RouterContextProvider, "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `RouterContextProvider`");
1352 await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties);
1353 return await runServerMiddlewarePipeline({
1354 request,
1355 url: createDataFunctionUrl(request, location),
1356 pattern: getRoutePattern(matches),
1357 matches,
1358 params: matches[0].params,
1359 context: requestContext
1360 }, async () => {
1361 return await generateMiddlewareResponse(async (innerRequest) => {
1362 let processed = handleQueryResult(await queryImpl(innerRequest, location, matches, requestContext, dataStrategy || null, false, match, null, false));
1363 return isResponse(processed) ? processed : typeof processed === "string" ? new Response(processed) : Response.json(processed);
1364 });
1365 }, (error) => {
1366 if (isDataWithResponseInit(error)) return Promise.resolve(dataWithResponseInitToResponse(error));
1367 if (isResponse(error)) return Promise.resolve(error);
1368 throw error;
1369 });
1370 }
1371 return handleQueryResult(await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match, null, false));
1372 function handleQueryResult(result) {
1373 if (isResponse(result)) return result;
1374 let error = result.errors ? Object.values(result.errors)[0] : void 0;
1375 if (error !== void 0) throw error;
1376 if (result.actionData) return Object.values(result.actionData)[0];
1377 if (result.loaderData) return Object.values(result.loaderData)[0];
1378 }
1379 }
1380 async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
1381 invariant$1(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
1382 try {
1383 if (isMutationMethod(request.method)) return await submit(request, location, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null, filterMatchesToLoad, skipRevalidation);
1384 let result = await loadRouteData(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad);
1385 return isResponse(result) ? result : {
1386 ...result,
1387 actionData: null,
1388 actionHeaders: {}
1389 };
1390 } catch (e) {
1391 if (isDataStrategyResult(e) && isResponse(e.result)) {
1392 if (e.type === "error") throw e.result;
1393 return e.result;
1394 }
1395 if (isRedirectResponse(e)) return e;
1396 throw e;
1397 }
1398 }
1399 async function submit(request, location, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
1400 let result;
1401 if (!actionMatch.route.action && !actionMatch.route.lazy) {
1402 let error = getInternalRouterError(405, {
1403 method: request.method,
1404 pathname: new URL(request.url).pathname,
1405 routeId: actionMatch.route.id
1406 });
1407 if (isRouteRequest) throw error;
1408 result = {
1409 type: "error",
1410 error
1411 };
1412 } else {
1413 result = (await callDataStrategy(request, location, getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, location, matches, actionMatch, [], requestContext), isRouteRequest, requestContext, dataStrategy))[actionMatch.route.id];
1414 if (request.signal.aborted) throwStaticHandlerAbortedError(request, isRouteRequest);
1415 }
1416 if (isRedirectResult(result)) throw new Response(null, {
1417 status: result.response.status,
1418 headers: { Location: result.response.headers.get("Location") }
1419 });
1420 if (isRouteRequest) {
1421 if (isErrorResult(result)) throw result.error;
1422 return {
1423 matches: [actionMatch],
1424 loaderData: {},
1425 actionData: { [actionMatch.route.id]: result.data },
1426 errors: null,
1427 statusCode: 200,
1428 loaderHeaders: {},
1429 actionHeaders: {}
1430 };
1431 }
1432 if (skipRevalidation) if (isErrorResult(result)) {
1433 let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
1434 return {
1435 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1436 actionData: null,
1437 actionHeaders: { ...result.headers ? { [actionMatch.route.id]: result.headers } : {} },
1438 matches,
1439 loaderData: {},
1440 errors: { [boundaryMatch.route.id]: result.error },
1441 loaderHeaders: {}
1442 };
1443 } else return {
1444 actionData: { [actionMatch.route.id]: result.data },
1445 actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
1446 matches,
1447 loaderData: {},
1448 errors: null,
1449 statusCode: result.statusCode || 200,
1450 loaderHeaders: {}
1451 };
1452 let loaderRequest = new Request(request.url, {
1453 headers: request.headers,
1454 redirect: request.redirect,
1455 signal: request.signal
1456 });
1457 if (isErrorResult(result)) return {
1458 ...await loadRouteData(loaderRequest, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, filterMatchesToLoad, [(skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id)).route.id, result]),
1459 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1460 actionData: null,
1461 actionHeaders: { ...result.headers ? { [actionMatch.route.id]: result.headers } : {} }
1462 };
1463 return {
1464 ...await loadRouteData(loaderRequest, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, filterMatchesToLoad),
1465 actionData: { [actionMatch.route.id]: result.data },
1466 ...result.statusCode ? { statusCode: result.statusCode } : {},
1467 actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
1468 };
1469 }
1470 async function loadRouteData(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
1471 let isRouteRequest = routeMatch != null;
1472 if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) throw getInternalRouterError(400, {
1473 method: request.method,
1474 pathname: new URL(request.url).pathname,
1475 routeId: routeMatch?.route.id
1476 });
1477 let dsMatches;
1478 if (routeMatch) dsMatches = getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, location, matches, routeMatch, [], requestContext);
1479 else {
1480 let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1 : void 0;
1481 let pattern = getRoutePattern(matches);
1482 dsMatches = matches.map((match, index) => {
1483 if (maxIdx != null && index > maxIdx) return getDataStrategyMatch(mapRouteProperties, manifest, request, location, pattern, match, [], requestContext, false);
1484 return getDataStrategyMatch(mapRouteProperties, manifest, request, location, pattern, match, [], requestContext, (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match)));
1485 });
1486 }
1487 if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) return {
1488 matches,
1489 loaderData: {},
1490 errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null,
1491 statusCode: 200,
1492 loaderHeaders: {}
1493 };
1494 let results = await callDataStrategy(request, location, dsMatches, isRouteRequest, requestContext, dataStrategy);
1495 if (request.signal.aborted) throwStaticHandlerAbortedError(request, isRouteRequest);
1496 return {
1497 ...processRouteLoaderData(matches, results, pendingActionResult, true, skipLoaderErrorBubbling),
1498 matches
1499 };
1500 }
1501 async function callDataStrategy(request, location, matches, isRouteRequest, requestContext, dataStrategy) {
1502 let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, request, location, matches, null, "static", requestContext, true);
1503 let dataResults = {};
1504 await Promise.all(matches.map(async (match) => {
1505 if (!(match.route.id in results)) return;
1506 let result = results[match.route.id];
1507 if (isRedirectDataStrategyResult(result)) {
1508 let response = result.result;
1509 throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename);
1510 }
1511 if (isRouteRequest) {
1512 if (isResponse(result.result)) throw result;
1513 else if (isDataWithResponseInit(result.result)) throw dataWithResponseInitToResponse(result.result);
1514 }
1515 dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
1516 }));
1517 return dataResults;
1518 }
1519 return {
1520 dataRoutes,
1521 get _matchCost() {
1522 return dataRouteMatcher instanceof V6RegExMatcher ? dataRouteMatcher.matchCost : void 0;
1523 },
1524 match,
1525 query,
1526 queryRoute
1527 };
1528}
1529/**
1530* Given an existing StaticHandlerContext and an error thrown at render time,
1531* provide an updated StaticHandlerContext suitable for a second SSR render
1532*
1533* @category Utils
1534*/
1535function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
1536 let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
1537 return {
1538 ...handlerContext,
1539 statusCode: isRouteErrorResponse(error) ? error.status : 500,
1540 errors: { [errorBoundaryId]: error }
1541 };
1542}
1543function throwStaticHandlerAbortedError(request, isRouteRequest) {
1544 if (request.signal.reason !== void 0) throw request.signal.reason;
1545 throw new Error(`${isRouteRequest ? "queryRoute" : "query"}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`);
1546}
1547function defaultNormalizePath(request) {
1548 let url = new URL(request.url);
1549 return {
1550 pathname: url.pathname,
1551 search: url.search,
1552 hash: url.hash
1553 };
1554}
1555function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
1556 let contextualMatches;
1557 let activeRouteMatch;
1558 if (fromRouteId) {
1559 contextualMatches = [];
1560 for (let match of matches) {
1561 contextualMatches.push(match);
1562 if (match.route.id === fromRouteId) {
1563 activeRouteMatch = match;
1564 break;
1565 }
1566 }
1567 } else {
1568 contextualMatches = matches;
1569 activeRouteMatch = matches[matches.length - 1];
1570 }
1571 let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches), stripBasename(location.pathname, basename) || location.pathname, relative === "path");
1572 if (to == null) {
1573 path.search = location.search;
1574 path.hash = location.hash;
1575 }
1576 if ((to == null || to === "" || to === ".") && activeRouteMatch) {
1577 let nakedIndex = hasNakedIndexQuery(path.search);
1578 if (activeRouteMatch.route.index && !nakedIndex) path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
1579 else if (!activeRouteMatch.route.index && nakedIndex) {
1580 let params = new URLSearchParams(path.search);
1581 let indexValues = params.getAll("index");
1582 params.delete("index");
1583 indexValues.filter((v) => v).forEach((v) => params.append("index", v));
1584 let qs = params.toString();
1585 path.search = qs ? `?${qs}` : "";
1586 }
1587 }
1588 if (basename !== "/") path.pathname = prependBasename({
1589 basename,
1590 pathname: path.pathname
1591 });
1592 return createPath(path);
1593}
1594function shouldRevalidateLoader(loaderMatch, arg) {
1595 if (loaderMatch.route.shouldRevalidate) {
1596 let routeChoice = loaderMatch.route.shouldRevalidate(arg);
1597 if (typeof routeChoice === "boolean") return routeChoice;
1598 }
1599 return arg.defaultShouldRevalidate;
1600}
1601const lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
1602const loadLazyRouteProperty = ({ key, route, manifest, mapRouteProperties }) => {
1603 let routeToUpdate = manifest[route.id];
1604 invariant$1(routeToUpdate, "No route found in manifest");
1605 if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") return;
1606 let lazyFn = routeToUpdate.lazy[key];
1607 if (!lazyFn) return;
1608 let cache = lazyRoutePropertyCache.get(routeToUpdate);
1609 if (!cache) {
1610 cache = {};
1611 lazyRoutePropertyCache.set(routeToUpdate, cache);
1612 }
1613 let cachedPromise = cache[key];
1614 if (cachedPromise) return cachedPromise;
1615 let propertyPromise = (async () => {
1616 let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
1617 let isStaticallyDefined = routeToUpdate[key] !== void 0;
1618 if (isUnsupported) {
1619 warning(!isUnsupported, "Route property " + key + " is not a supported lazy route property. This property will be ignored.");
1620 cache[key] = Promise.resolve();
1621 } else if (isStaticallyDefined) warning(false, `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`);
1622 else {
1623 let value = await lazyFn();
1624 if (value != null) {
1625 Object.assign(routeToUpdate, { [key]: value });
1626 Object.assign(routeToUpdate, mapRouteProperties(routeToUpdate));
1627 }
1628 }
1629 if (typeof routeToUpdate.lazy === "object") {
1630 routeToUpdate.lazy[key] = void 0;
1631 if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) routeToUpdate.lazy = void 0;
1632 }
1633 })();
1634 cache[key] = propertyPromise;
1635 propertyPromise.catch(() => {
1636 if (cache[key] === propertyPromise) delete cache[key];
1637 });
1638 return propertyPromise;
1639};
1640const lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
1641/**
1642* Execute route.lazy functions to lazily load route modules (loader, action,
1643* shouldRevalidate) and update the routeManifest in place which shares objects
1644* with dataRoutes so those get updated as well.
1645*/
1646function loadLazyRoute(route, type, manifest, mapRouteProperties, lazyRoutePropertiesToSkip) {
1647 let routeToUpdate = manifest[route.id];
1648 invariant$1(routeToUpdate, "No route found in manifest");
1649 if (!route.lazy) return {
1650 lazyRoutePromise: void 0,
1651 lazyHandlerPromise: void 0
1652 };
1653 if (typeof route.lazy === "function") {
1654 let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
1655 if (cachedPromise) return {
1656 lazyRoutePromise: cachedPromise,
1657 lazyHandlerPromise: cachedPromise
1658 };
1659 let lazyRoutePromise = (async () => {
1660 invariant$1(typeof route.lazy === "function", "No lazy route function found");
1661 let lazyRoute = await route.lazy();
1662 let routeUpdates = {};
1663 for (let lazyRouteProperty in lazyRoute) {
1664 let lazyValue = lazyRoute[lazyRouteProperty];
1665 if (lazyValue === void 0) continue;
1666 let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
1667 let isStaticallyDefined = routeToUpdate[lazyRouteProperty] !== void 0;
1668 if (isUnsupported) warning(!isUnsupported, "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored.");
1669 else if (isStaticallyDefined) warning(!isStaticallyDefined, `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.`);
1670 else routeUpdates[lazyRouteProperty] = lazyValue;
1671 }
1672 Object.assign(routeToUpdate, routeUpdates);
1673 Object.assign(routeToUpdate, {
1674 ...mapRouteProperties(routeToUpdate),
1675 lazy: void 0
1676 });
1677 })();
1678 lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise);
1679 lazyRoutePromise.catch(() => {
1680 if (lazyRouteFunctionCache.get(routeToUpdate) === lazyRoutePromise) lazyRouteFunctionCache.delete(routeToUpdate);
1681 });
1682 return {
1683 lazyRoutePromise,
1684 lazyHandlerPromise: lazyRoutePromise
1685 };
1686 }
1687 let lazyKeys = Object.keys(route.lazy);
1688 let lazyPropertyPromises = [];
1689 let lazyHandlerPromise = void 0;
1690 for (let key of lazyKeys) {
1691 if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) continue;
1692 let promise = loadLazyRouteProperty({
1693 key,
1694 route,
1695 manifest,
1696 mapRouteProperties
1697 });
1698 if (promise) {
1699 lazyPropertyPromises.push(promise);
1700 if (key === type) lazyHandlerPromise = promise;
1701 }
1702 }
1703 let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {}) : void 0;
1704 lazyRoutePromise?.catch(() => {});
1705 lazyHandlerPromise?.catch(() => {});
1706 return {
1707 lazyRoutePromise,
1708 lazyHandlerPromise
1709 };
1710}
1711function isNonNullable(value) {
1712 return value !== void 0;
1713}
1714function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties) {
1715 let promises = matches.map(({ route }) => {
1716 if (typeof route.lazy !== "object" || !route.lazy.middleware) return;
1717 return loadLazyRouteProperty({
1718 key: "middleware",
1719 route,
1720 manifest,
1721 mapRouteProperties
1722 });
1723 }).filter(isNonNullable);
1724 return promises.length > 0 ? Promise.all(promises) : void 0;
1725}
1726async function defaultDataStrategy(args) {
1727 let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
1728 let keyedResults = {};
1729 (await Promise.all(matchesToLoad.map((m) => m.resolve()))).forEach((result, i) => {
1730 keyedResults[matchesToLoad[i].route.id] = result;
1731 });
1732 return keyedResults;
1733}
1734function runServerMiddlewarePipeline(args, handler, errorHandler) {
1735 return runMiddlewarePipeline(args, handler, processResult, isResponse, errorHandler);
1736 function processResult(result) {
1737 return isDataWithResponseInit(result) ? dataWithResponseInitToResponse(result) : result;
1738 }
1739}
1740function runClientMiddlewarePipeline(args, handler) {
1741 return runMiddlewarePipeline(args, handler, (r) => {
1742 if (isRedirectResponse(r)) throw r;
1743 return r;
1744 }, isDataStrategyResults, errorHandler);
1745 async function errorHandler(error, routeId, nextResult) {
1746 if (nextResult) return Object.assign(nextResult.value, { [routeId]: {
1747 type: "error",
1748 result: error
1749 } });
1750 else {
1751 let { matches } = args;
1752 let maxBoundaryIdx = Math.min(Math.max(matches.findIndex((m) => m.route.id === routeId), 0), Math.max(matches.findIndex((m) => m.shouldCallHandler()), 0));
1753 let deepestRouteId = matches[maxBoundaryIdx].route.id;
1754 for (let match of matches.slice(0, maxBoundaryIdx + 1)) try {
1755 await match._lazyPromises?.route;
1756 } catch {
1757 deepestRouteId = match.route.id;
1758 break;
1759 }
1760 return { [findNearestBoundary(matches, deepestRouteId).route.id]: {
1761 type: "error",
1762 result: error
1763 } };
1764 }
1765 }
1766}
1767async function runMiddlewarePipeline(args, handler, processResult, isResult, errorHandler) {
1768 let { matches, ...dataFnArgs } = args;
1769 return await callRouteMiddleware(dataFnArgs, matches.flatMap((m) => m.route.middleware ? m.route.middleware.map((fn) => [m.route.id, fn]) : []), handler, processResult, isResult, errorHandler);
1770}
1771async function callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx = 0) {
1772 let { request } = args;
1773 if (request.signal.aborted) throw request.signal.reason ?? /* @__PURE__ */ new Error(`Request aborted: ${request.method} ${request.url}`);
1774 let tuple = middlewares[idx];
1775 if (!tuple) return await handler();
1776 let [routeId, middleware] = tuple;
1777 let nextResult;
1778 let next = async () => {
1779 if (nextResult) throw new Error("You may only call `next()` once per middleware");
1780 try {
1781 nextResult = { value: await callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx + 1) };
1782 return nextResult.value;
1783 } catch (error) {
1784 nextResult = { value: await errorHandler(error, routeId, nextResult) };
1785 return nextResult.value;
1786 }
1787 };
1788 try {
1789 let value = await middleware(args, next);
1790 let result = value != null ? processResult(value) : void 0;
1791 if (isResult(result)) return result;
1792 else if (nextResult) return result ?? nextResult.value;
1793 else {
1794 nextResult = { value: await next() };
1795 return nextResult.value;
1796 }
1797 } catch (error) {
1798 return await errorHandler(error, routeId, nextResult);
1799 }
1800}
1801function getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip) {
1802 let lazyMiddlewarePromise = loadLazyRouteProperty({
1803 key: "middleware",
1804 route: match.route,
1805 manifest,
1806 mapRouteProperties
1807 });
1808 let lazyRoutePromises = loadLazyRoute(match.route, isMutationMethod(request.method) ? "action" : "loader", manifest, mapRouteProperties, lazyRoutePropertiesToSkip);
1809 return {
1810 middleware: lazyMiddlewarePromise,
1811 route: lazyRoutePromises.lazyRoutePromise,
1812 handler: lazyRoutePromises.lazyHandlerPromise
1813 };
1814}
1815function getDataStrategyMatch(mapRouteProperties, manifest, request, path, pattern, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, shouldRevalidateArgs = null, callSiteDefaultShouldRevalidate) {
1816 let isUsingNewApi = false;
1817 let _lazyPromises = getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip);
1818 return {
1819 ...match,
1820 _lazyPromises,
1821 shouldLoad,
1822 shouldRevalidateArgs,
1823 shouldCallHandler(defaultShouldRevalidate) {
1824 isUsingNewApi = true;
1825 if (!shouldRevalidateArgs) return shouldLoad;
1826 if (typeof callSiteDefaultShouldRevalidate === "boolean") return shouldRevalidateLoader(match, {
1827 ...shouldRevalidateArgs,
1828 defaultShouldRevalidate: callSiteDefaultShouldRevalidate
1829 });
1830 if (typeof defaultShouldRevalidate === "boolean") return shouldRevalidateLoader(match, {
1831 ...shouldRevalidateArgs,
1832 defaultShouldRevalidate
1833 });
1834 return shouldRevalidateLoader(match, shouldRevalidateArgs);
1835 },
1836 resolve(handlerOverride) {
1837 let { lazy, loader, middleware } = match.route;
1838 let callHandler = isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (lazy || loader);
1839 let isMiddlewareOnlyRoute = middleware && middleware.length > 0 && !loader && !lazy;
1840 if (callHandler && (isMutationMethod(request.method) || !isMiddlewareOnlyRoute)) return callLoaderOrAction({
1841 request,
1842 path,
1843 pattern,
1844 match,
1845 lazyHandlerPromise: _lazyPromises?.handler,
1846 lazyRoutePromise: _lazyPromises?.route,
1847 handlerOverride,
1848 scopedContext
1849 });
1850 return Promise.resolve({
1851 type: "data",
1852 result: void 0
1853 });
1854 }
1855 };
1856}
1857function getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, path, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
1858 return matches.map((match) => {
1859 if (match.route.id !== targetMatch.route.id) return {
1860 ...match,
1861 shouldLoad: false,
1862 shouldRevalidateArgs,
1863 shouldCallHandler: () => false,
1864 _lazyPromises: getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip),
1865 resolve: () => Promise.resolve({
1866 type: "data",
1867 result: void 0
1868 })
1869 };
1870 return getDataStrategyMatch(mapRouteProperties, manifest, request, path, getRoutePattern(matches), match, lazyRoutePropertiesToSkip, scopedContext, true, shouldRevalidateArgs);
1871 });
1872}
1873async function callDataStrategyImpl(dataStrategyImpl, request, path, matches, fetcherKey, initiator, scopedContext, isStaticHandler, navigationType = null) {
1874 if (matches.some((m) => m._lazyPromises?.middleware)) await Promise.all(matches.map((m) => m._lazyPromises?.middleware));
1875 let dataStrategyArgs = {
1876 request,
1877 url: createDataFunctionUrl(request, path),
1878 pattern: getRoutePattern(matches),
1879 params: matches[0].params,
1880 context: scopedContext,
1881 matches,
1882 unstable_initiator: initiator,
1883 unstable_navigationType: initiator === "navigation" ? navigationType : null
1884 };
1885 let runClientMiddleware = isStaticHandler ? () => {
1886 throw new Error("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`");
1887 } : (cb) => {
1888 let typedDataStrategyArgs = dataStrategyArgs;
1889 return runClientMiddlewarePipeline(typedDataStrategyArgs, () => {
1890 return cb({
1891 ...typedDataStrategyArgs,
1892 fetcherKey,
1893 runClientMiddleware: () => {
1894 throw new Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler");
1895 }
1896 });
1897 });
1898 };
1899 let results = await dataStrategyImpl({
1900 ...dataStrategyArgs,
1901 fetcherKey,
1902 runClientMiddleware
1903 });
1904 try {
1905 await Promise.all(matches.flatMap((m) => [m._lazyPromises?.handler, m._lazyPromises?.route]));
1906 } catch {}
1907 return results;
1908}
1909async function callLoaderOrAction({ request, path, pattern, match, lazyHandlerPromise, lazyRoutePromise, handlerOverride, scopedContext }) {
1910 let result;
1911 let onReject;
1912 let isAction = isMutationMethod(request.method);
1913 let type = isAction ? "action" : "loader";
1914 let runHandler = (handler) => {
1915 let reject;
1916 let abortPromise = new Promise((_, r) => reject = r);
1917 onReject = () => reject();
1918 request.signal.addEventListener("abort", onReject);
1919 let actualHandler = (ctx) => {
1920 if (typeof handler !== "function") return Promise.reject(/* @__PURE__ */ new Error(`You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`));
1921 return handler({
1922 request,
1923 url: createDataFunctionUrl(request, path),
1924 pattern,
1925 params: match.params,
1926 context: scopedContext
1927 }, ...ctx !== void 0 ? [ctx] : []);
1928 };
1929 let handlerPromise = (async () => {
1930 try {
1931 return {
1932 type: "data",
1933 result: await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler())
1934 };
1935 } catch (e) {
1936 return {
1937 type: "error",
1938 result: e
1939 };
1940 }
1941 })();
1942 return Promise.race([handlerPromise, abortPromise]);
1943 };
1944 try {
1945 let handler = isAction ? match.route.action : match.route.loader;
1946 if (lazyHandlerPromise || lazyRoutePromise) if (handler) {
1947 let handlerError;
1948 let [value] = await Promise.all([
1949 runHandler(handler).catch((e) => {
1950 handlerError = e;
1951 }),
1952 lazyHandlerPromise,
1953 lazyRoutePromise
1954 ]);
1955 if (handlerError !== void 0) throw handlerError;
1956 result = value;
1957 } else {
1958 await lazyHandlerPromise;
1959 let handler = isAction ? match.route.action : match.route.loader;
1960 if (handler) [result] = await Promise.all([runHandler(handler), lazyRoutePromise]);
1961 else if (type === "action") {
1962 let url = new URL(request.url);
1963 let pathname = url.pathname + url.search;
1964 throw getInternalRouterError(405, {
1965 method: request.method,
1966 pathname,
1967 routeId: match.route.id
1968 });
1969 } else {
1970 await lazyRoutePromise;
1971 return {
1972 type: "data",
1973 result: void 0
1974 };
1975 }
1976 }
1977 else if (!handler) {
1978 let url = new URL(request.url);
1979 throw getInternalRouterError(404, { pathname: url.pathname + url.search });
1980 } else result = await runHandler(handler);
1981 } catch (e) {
1982 return {
1983 type: "error",
1984 result: e
1985 };
1986 } finally {
1987 if (onReject) request.signal.removeEventListener("abort", onReject);
1988 }
1989 return result;
1990}
1991async function parseResponseBody(response) {
1992 let contentType = response.headers.get("Content-Type");
1993 if (contentType && /\bapplication\/json\b/.test(contentType)) return response.body == null ? null : response.json();
1994 return response.text();
1995}
1996async function convertDataStrategyResultToDataResult(dataStrategyResult) {
1997 let { result, type } = dataStrategyResult;
1998 if (isResponse(result)) {
1999 let data;
2000 try {
2001 data = await parseResponseBody(result);
2002 } catch (e) {
2003 return {
2004 type: "error",
2005 error: e
2006 };
2007 }
2008 if (type === "error") return {
2009 type: "error",
2010 error: new ErrorResponseImpl(result.status, result.statusText, data),
2011 statusCode: result.status,
2012 headers: result.headers
2013 };
2014 return {
2015 type: "data",
2016 data,
2017 statusCode: result.status,
2018 headers: result.headers
2019 };
2020 }
2021 if (type === "error") {
2022 if (isDataWithResponseInit(result)) {
2023 if (result.data instanceof Error) return {
2024 type: "error",
2025 error: result.data,
2026 statusCode: result.init?.status,
2027 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
2028 };
2029 return {
2030 type: "error",
2031 error: dataWithResponseInitToErrorResponse(result),
2032 statusCode: isRouteErrorResponse(result) ? result.status : void 0,
2033 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
2034 };
2035 }
2036 return {
2037 type: "error",
2038 error: result,
2039 statusCode: isRouteErrorResponse(result) ? result.status : void 0
2040 };
2041 }
2042 if (isDataWithResponseInit(result)) return {
2043 type: "data",
2044 data: result.data,
2045 statusCode: result.init?.status,
2046 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
2047 };
2048 return {
2049 type: "data",
2050 data: result
2051 };
2052}
2053function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
2054 let location = response.headers.get("Location");
2055 invariant$1(location, "Redirects returned/thrown from loaders/actions must have a Location header");
2056 validateNavigationTarget(location, location, new URL(request.url), "allow-explicit");
2057 if (!isAbsoluteUrl(location)) {
2058 let trimmedMatches = matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1);
2059 location = normalizeTo(new URL(request.url), trimmedMatches, basename, location);
2060 response.headers.set("Location", location);
2061 }
2062 return response;
2063}
2064function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
2065 let loaderData = {};
2066 let errors = null;
2067 let statusCode;
2068 let foundError = false;
2069 let loaderHeaders = {};
2070 let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
2071 matches.forEach((match) => {
2072 if (!(match.route.id in results)) return;
2073 let id = match.route.id;
2074 let result = results[id];
2075 invariant$1(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
2076 if (isErrorResult(result)) {
2077 let error = result.error;
2078 if (pendingError !== void 0) {
2079 error = pendingError;
2080 pendingError = void 0;
2081 }
2082 errors = errors || {};
2083 if (skipLoaderErrorBubbling) errors[id] = error;
2084 else {
2085 let boundaryMatch = findNearestBoundary(matches, id);
2086 if (errors[boundaryMatch.route.id] == null) errors[boundaryMatch.route.id] = error;
2087 }
2088 if (!isStaticHandler) loaderData[id] = ResetLoaderDataSymbol;
2089 if (!foundError) {
2090 foundError = true;
2091 statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
2092 }
2093 if (result.headers) loaderHeaders[id] = result.headers;
2094 } else {
2095 loaderData[id] = result.data;
2096 if (result.statusCode && result.statusCode !== 200 && !foundError) statusCode = result.statusCode;
2097 if (result.headers) loaderHeaders[id] = result.headers;
2098 }
2099 });
2100 if (pendingError !== void 0 && pendingActionResult) {
2101 errors = { [pendingActionResult[0]]: pendingError };
2102 if (pendingActionResult[2]) loaderData[pendingActionResult[2]] = void 0;
2103 }
2104 return {
2105 loaderData,
2106 errors,
2107 statusCode: statusCode || 200,
2108 loaderHeaders
2109 };
2110}
2111function findNearestBoundary(matches, routeId) {
2112 return (routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches]).reverse().find((m) => m.route.ErrorBoundary != null || m.route.errorElement != null) || matches[0];
2113}
2114function getShortCircuitMatches(routes) {
2115 let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || { id: `__shim-error-route__` };
2116 return {
2117 matches: [{
2118 params: {},
2119 pathname: "",
2120 pathnameBase: "",
2121 route
2122 }],
2123 route
2124 };
2125}
2126function getInternalRouterError(status, { pathname, routeId, method, type, message } = {}) {
2127 let statusText = "Unknown Server Error";
2128 let errorMessage = "Unknown @remix-run/router error";
2129 if (status === 400) {
2130 statusText = "Bad Request";
2131 if (method && pathname && routeId) 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.`;
2132 else if (type === "invalid-body") errorMessage = "Unable to encode submission body";
2133 } else if (status === 403) {
2134 statusText = "Forbidden";
2135 errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
2136 } else if (status === 404) {
2137 statusText = "Not Found";
2138 errorMessage = `No route matches URL "${pathname}"`;
2139 } else if (status === 405) {
2140 statusText = "Method Not Allowed";
2141 if (method && pathname && routeId) 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.`;
2142 else if (method) errorMessage = `Invalid request method "${method.toUpperCase()}"`;
2143 }
2144 return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);
2145}
2146function dataWithResponseInitToResponse(data) {
2147 return Response.json(data.data, data.init ?? void 0);
2148}
2149function dataWithResponseInitToErrorResponse(data) {
2150 return new ErrorResponseImpl(data.init?.status ?? 500, data.init?.statusText ?? "Internal Server Error", data.data);
2151}
2152function isDataStrategyResults(result) {
2153 return result != null && typeof result === "object" && Object.entries(result).every(([key, value]) => typeof key === "string" && isDataStrategyResult(value));
2154}
2155function isDataStrategyResult(result) {
2156 return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" || result.type === "error");
2157}
2158function isRedirectDataStrategyResult(result) {
2159 return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
2160}
2161function isErrorResult(result) {
2162 return result.type === "error";
2163}
2164function isRedirectResult(result) {
2165 return (result && result.type) === "redirect";
2166}
2167function isDataWithResponseInit(value) {
2168 return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
2169}
2170function isResponse(value) {
2171 return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
2172}
2173function isRedirectStatusCode(statusCode) {
2174 return redirectStatusCodes.has(statusCode);
2175}
2176function isRedirectResponse(result) {
2177 return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
2178}
2179function isValidMethod(method) {
2180 return validRequestMethods.has(method.toUpperCase());
2181}
2182function isMutationMethod(method) {
2183 return validMutationMethods.has(method.toUpperCase());
2184}
2185function hasNakedIndexQuery(search) {
2186 return new URLSearchParams(search).getAll("index").some((v) => v === "");
2187}
2188function getTargetMatch(matches, location) {
2189 let search = typeof location === "string" ? parsePath(location).search : location.search;
2190 if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) return matches[matches.length - 1];
2191 let pathMatches = getPathContributingMatches(matches);
2192 return pathMatches[pathMatches.length - 1];
2193}
2194//#endregion
2195//#region lib/server-runtime/invariant.ts
2196function invariant(value, message) {
2197 if (value === false || value === null || typeof value === "undefined") {
2198 console.error("The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose");
2199 throw new Error(message);
2200 }
2201}
2202//#endregion
2203//#region lib/server-runtime/headers.ts
2204function getDocumentHeadersImpl(context, getRouteHeadersFn, _defaultHeaders) {
2205 let boundaryIdx = context.errors ? context.matches.findIndex((m) => context.errors[m.route.id]) : -1;
2206 let matches = boundaryIdx >= 0 ? context.matches.slice(0, boundaryIdx + 1) : context.matches;
2207 let errorHeaders;
2208 if (boundaryIdx >= 0) {
2209 let { actionHeaders, actionData, loaderHeaders, loaderData } = context;
2210 context.matches.slice(boundaryIdx).some((match) => {
2211 let id = match.route.id;
2212 if (actionHeaders[id] && (!actionData || !actionData.hasOwnProperty(id))) errorHeaders = actionHeaders[id];
2213 else if (loaderHeaders[id] && !loaderData.hasOwnProperty(id)) errorHeaders = loaderHeaders[id];
2214 return errorHeaders != null;
2215 });
2216 }
2217 const defaultHeaders = new Headers(_defaultHeaders);
2218 return matches.reduce((parentHeaders, match, idx) => {
2219 let { id } = match.route;
2220 let loaderHeaders = context.loaderHeaders[id] || new Headers();
2221 let actionHeaders = context.actionHeaders[id] || new Headers();
2222 let includeErrorHeaders = errorHeaders != null && idx === matches.length - 1;
2223 let includeErrorCookies = includeErrorHeaders && errorHeaders !== loaderHeaders && errorHeaders !== actionHeaders;
2224 let headersFn = getRouteHeadersFn(match);
2225 if (headersFn == null) {
2226 let headers = new Headers(parentHeaders);
2227 if (includeErrorCookies) prependCookies(errorHeaders, headers);
2228 prependCookies(actionHeaders, headers);
2229 prependCookies(loaderHeaders, headers);
2230 return headers;
2231 }
2232 let headers = new Headers(typeof headersFn === "function" ? headersFn({
2233 loaderHeaders,
2234 parentHeaders,
2235 actionHeaders,
2236 errorHeaders: includeErrorHeaders ? errorHeaders : void 0
2237 }) : headersFn);
2238 if (includeErrorCookies) prependCookies(errorHeaders, headers);
2239 prependCookies(actionHeaders, headers);
2240 prependCookies(loaderHeaders, headers);
2241 prependCookies(parentHeaders, headers);
2242 return headers;
2243 }, new Headers(defaultHeaders));
2244}
2245function prependCookies(parentHeaders, childHeaders) {
2246 let parentSetCookieString = parentHeaders.get("Set-Cookie");
2247 if (parentSetCookieString) {
2248 let cookies = splitSetCookieString(parentSetCookieString);
2249 let childCookies = new Set(childHeaders.getSetCookie());
2250 cookies.forEach((cookie) => {
2251 if (!childCookies.has(cookie)) childHeaders.append("Set-Cookie", cookie);
2252 });
2253 }
2254}
2255//#endregion
2256//#region lib/server-runtime/warnings.ts
2257const alreadyWarned = {};
2258function warnOnce(condition, message) {
2259 if (!condition && !alreadyWarned[message]) {
2260 alreadyWarned[message] = true;
2261 console.warn(message);
2262 }
2263}
2264//#endregion
2265//#region lib/errors.ts
2266const ERROR_DIGEST_BASE = "REACT_ROUTER_ERROR";
2267const ERROR_DIGEST_REDIRECT = "REDIRECT";
2268const ERROR_DIGEST_ROUTE_ERROR_RESPONSE = "ROUTE_ERROR_RESPONSE";
2269function createRedirectErrorDigest(response) {
2270 return `${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:${JSON.stringify({
2271 status: response.status,
2272 statusText: response.statusText,
2273 location: response.headers.get("Location"),
2274 reloadDocument: response.headers.get("X-Remix-Reload-Document") === "true",
2275 replace: response.headers.get("X-Remix-Replace") === "true"
2276 })}`;
2277}
2278function createRouteErrorResponseDigest(response) {
2279 let status = 500;
2280 let statusText = "";
2281 let data;
2282 if (isDataWithResponseInit(response)) {
2283 status = response.init?.status ?? status;
2284 statusText = response.init?.statusText ?? statusText;
2285 data = response.data;
2286 } else {
2287 status = response.status;
2288 statusText = response.statusText;
2289 data = void 0;
2290 }
2291 return `${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:${JSON.stringify({
2292 status,
2293 statusText,
2294 data
2295 })}`;
2296}
2297function getPathsWithAncestors(paths) {
2298 let result = /* @__PURE__ */ new Set();
2299 paths.forEach((path) => {
2300 if (!path.startsWith("/")) path = `/${path}`;
2301 for (let i = 1; i < path.length; i++) if (path[i] === "/") result.add(path.slice(0, i));
2302 result.add(path);
2303 });
2304 return Array.from(result);
2305}
2306const MANIFEST_MATCH_COST_LIMIT = 5e4;
2307const MANIFEST_MATCH_COST_SEGMENT_THRESHOLD = 10;
2308function shouldUseInitialRouteDiscovery(pathname, matchCost = 0) {
2309 let segmentCount = pathname.split("/").length - 1;
2310 return Math.max(segmentCount - 1, 0) * pathname.length + 1 > 7680 || segmentCount > MANIFEST_MATCH_COST_SEGMENT_THRESHOLD && segmentCount * matchCost > MANIFEST_MATCH_COST_LIMIT;
2311}
2312//#endregion
2313//#region lib/actions.ts
2314function throwIfPotentialCSRFAttack(request, allowedActionOrigins) {
2315 let originHeader = request.headers.get("origin");
2316 let originDomain = null;
2317 let originUrl = null;
2318 try {
2319 if (typeof originHeader === "string" && originHeader !== "null") {
2320 originUrl = new URL(originHeader);
2321 originDomain = originUrl.host;
2322 } else originDomain = originHeader;
2323 } catch {
2324 throw new Error(`\`origin\` header is not a valid URL. Aborting the action.`);
2325 }
2326 let requestUrl = new URL(request.url);
2327 let originMatchesRequest = originUrl ? originUrl.origin === requestUrl.origin : originDomain === requestUrl.host;
2328 if (originDomain && !originMatchesRequest) {
2329 if (!isAllowedOrigin(originDomain, allowedActionOrigins)) throw new Error("The `request.url` origin does not match `origin` header from a forwarded action request. Aborting the action.");
2330 }
2331}
2332function matchWildcardDomain(domain, pattern) {
2333 const domainParts = domain.split(".");
2334 const patternParts = pattern.split(".");
2335 if (patternParts.length < 1) return false;
2336 if (domainParts.length < patternParts.length) return false;
2337 while (patternParts.length) {
2338 const patternPart = patternParts.pop();
2339 const domainPart = domainParts.pop();
2340 switch (patternPart) {
2341 case "": return false;
2342 case "*": if (domainPart) continue;
2343 else return false;
2344 case "**":
2345 if (patternParts.length > 0) return false;
2346 return domainPart !== void 0;
2347 case void 0:
2348 default: if (domainPart !== patternPart) return false;
2349 }
2350 }
2351 return domainParts.length === 0;
2352}
2353function isAllowedOrigin(originDomain, allowedActionOrigins = []) {
2354 return allowedActionOrigins.some((allowedOrigin) => allowedOrigin && (allowedOrigin === originDomain || matchWildcardDomain(originDomain, allowedOrigin)));
2355}
2356//#endregion
2357//#region lib/server-runtime/urls.ts
2358function getNormalizedPath(request) {
2359 let url = new URL(request.url);
2360 let pathname = url.pathname;
2361 if (pathname.endsWith("/_.data")) pathname = pathname.replace(/_\.data$/, "");
2362 else pathname = pathname.replace(/\.data$/, "");
2363 let searchParams = new URLSearchParams(url.search);
2364 searchParams.delete("_routes");
2365 let search = searchParams.toString();
2366 if (search) search = `?${search}`;
2367 return {
2368 pathname,
2369 search,
2370 hash: ""
2371 };
2372}
2373//#endregion
2374//#region lib/rsc/server.rsc.ts
2375const Outlet$2 = Outlet$1;
2376const WithComponentProps = UNSAFE_WithComponentProps;
2377const WithErrorBoundaryProps = UNSAFE_WithErrorBoundaryProps;
2378const WithHydrateFallbackProps = UNSAFE_WithHydrateFallbackProps;
2379const globalVar = typeof globalThis !== "undefined" ? globalThis : global;
2380const ServerStorage = globalVar.___reactRouterServerStorage___ ??= new AsyncLocalStorage();
2381function getRequest() {
2382 const ctx = ServerStorage.getStore();
2383 if (!ctx) throw new Error("getRequest must be called from within a React Server render context");
2384 return ctx.request;
2385}
2386const redirect = (...args) => {
2387 const response = redirect$1(...args);
2388 const ctx = ServerStorage.getStore();
2389 if (ctx && ctx.runningAction) ctx.redirect = response;
2390 return response;
2391};
2392const redirectDocument = (...args) => {
2393 const response = redirectDocument$1(...args);
2394 const ctx = ServerStorage.getStore();
2395 if (ctx && ctx.runningAction) ctx.redirect = response;
2396 return response;
2397};
2398const replace = (...args) => {
2399 const response = replace$1(...args);
2400 const ctx = ServerStorage.getStore();
2401 if (ctx && ctx.runningAction) ctx.redirect = response;
2402 return response;
2403};
2404const cachedResolvePromise = React.cache(async (resolve) => {
2405 return Promise.allSettled([resolve]).then((r) => r[0]);
2406});
2407const Await = (async (props) => {
2408 invariant$1("resolve" in props !== "unstable_promise" in props, "<Await> requires exactly one of `resolve` or `unstable_promise`");
2409 let { children, errorElement } = props;
2410 let usePromise = "unstable_promise" in props;
2411 let resolved = await cachedResolvePromise(usePromise ? props.unstable_promise : props.resolve);
2412 if (resolved.status === "rejected" && !errorElement) throw resolved.reason;
2413 if (resolved.status === "rejected") return React.createElement(UNSAFE_AwaitContextProvider, {
2414 children: React.createElement(React.Fragment, null, errorElement),
2415 value: usePromise ? resolved : {
2416 _tracked: true,
2417 _error: resolved.reason
2418 }
2419 });
2420 const toRender = typeof children === "function" ? children(resolved.value) : children;
2421 return React.createElement(UNSAFE_AwaitContextProvider, {
2422 children: toRender,
2423 value: usePromise ? resolved : {
2424 _tracked: true,
2425 _data: resolved.value
2426 }
2427 });
2428});
2429/**
2430* Matches the given routes to a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2431* and returns an [RSC](https://react.dev/reference/rsc/server-components)
2432* [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2433* encoding an {@link unstable_RSCPayload} for consumption by an [RSC](https://react.dev/reference/rsc/server-components)
2434* enabled client router.
2435*
2436* Treat every React Server Function as a public endpoint. Server Functions are
2437* not inherently associated with a route. Any route middleware that runs is
2438* selected from the URL used to call a Server Function, but the client controls
2439* both the Server Function identifier and the URL. Perform all access control
2440* checks within each Server Function, or use a route action for
2441* middleware-driven access control.
2442*
2443* @example
2444* import {
2445* createTemporaryReferenceSet,
2446* decodeAction,
2447* decodeReply,
2448* loadServerAction,
2449* renderToReadableStream,
2450* } from "@vitejs/plugin-rsc/rsc";
2451* import { unstable_matchRSCServerRequest as matchRSCServerRequest } from "react-router";
2452*
2453* matchRSCServerRequest({
2454* createTemporaryReferenceSet,
2455* decodeAction,
2456* decodeFormState,
2457* decodeReply,
2458* loadServerAction,
2459* request,
2460* routes: routes(),
2461* generateResponse(match) {
2462* return new Response(
2463* renderToReadableStream(match.payload),
2464* {
2465* status: match.statusCode,
2466* headers: match.headers,
2467* }
2468* );
2469* },
2470* });
2471*
2472* @name unstable_matchRSCServerRequest
2473* @public
2474* @category RSC
2475* @mode data
2476* @param opts Options
2477* @param opts.allowedActionOrigins Origin patterns that are allowed to execute actions.
2478* @param opts.basename The basename to use when matching the request.
2479* @param opts.createTemporaryReferenceSet A function that returns a temporary
2480* reference set for the request, used to track temporary references in the [RSC](https://react.dev/reference/rsc/server-components)
2481* stream.
2482* @param opts.decodeAction Your `react-server-dom-xyz/server`'s `decodeAction`
2483* function, responsible for loading a server action.
2484* @param opts.decodeFormState A function responsible for decoding form state for
2485* progressively enhanceable forms with React's [`useActionState`](https://react.dev/reference/react/useActionState)
2486* using your `react-server-dom-xyz/server`'s `decodeFormState`.
2487* @param opts.decodeReply Your `react-server-dom-xyz/server`'s `decodeReply`
2488* function, used to decode the server function's arguments and bind them to the
2489* implementation for invocation by the router.
2490* @param opts.generateResponse A function responsible for using your
2491* `renderToReadableStream` to generate a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2492* encoding the {@link unstable_RSCPayload}.
2493* @param opts.loadServerAction Your `react-server-dom-xyz/server`'s
2494* `loadServerAction` function, used to load a server action by ID.
2495* @param opts.clientVersion A version derived from the client build output used
2496* to detect stale clients during lazy route discovery.
2497* @param opts.onError An optional error handler that will be called with any
2498* errors that occur during the request processing.
2499* @param opts.request The [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
2500* to match against.
2501* @param opts.requestContext An instance of {@link RouterContextProvider}
2502* that should be created per request, to be passed to [`action`](../../start/data/route-object#action)s,
2503* [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
2504* @param opts.routeDiscovery The route discovery configuration, used to determine how the router should discover new routes during navigations.
2505* @param opts.routes Your {@link unstable_RSCRouteConfigEntry | route definitions}.
2506* @returns A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
2507* that contains the [RSC](https://react.dev/reference/rsc/server-components)
2508* data for hydration.
2509*/
2510async function matchRSCServerRequest({ allowedActionOrigins, createTemporaryReferenceSet, basename, decodeReply, requestContext, routeDiscovery, loadServerAction, decodeAction, decodeFormState, clientVersion, onError, request, routes, generateResponse: encodeResponse }) {
2511 let generateResponse = (match, options) => {
2512 let response = encodeResponse(match, options);
2513 response.headers.set("Content-Type", "text/x-component");
2514 return response;
2515 };
2516 let url = new URL(request.url);
2517 basename = basename || "/";
2518 let normalizedPath = url.pathname;
2519 if (url.pathname.endsWith("/_.rsc")) normalizedPath = url.pathname.replace(/_\.rsc$/, "");
2520 else if (url.pathname.endsWith(".rsc")) normalizedPath = url.pathname.replace(/\.rsc$/, "");
2521 if (stripBasename(normalizedPath, basename) !== "/" && normalizedPath.endsWith("/")) normalizedPath = normalizedPath.slice(0, -1);
2522 url.pathname = normalizedPath;
2523 basename = basename.length > normalizedPath.length ? normalizedPath : basename;
2524 let routerRequest = new Request(url.toString(), {
2525 method: request.method,
2526 headers: request.headers,
2527 body: request.body,
2528 signal: request.signal,
2529 duplex: request.body ? "half" : void 0
2530 });
2531 const temporaryReferences = createTemporaryReferenceSet();
2532 const requestUrl = new URL(request.url);
2533 if (isManifestRequest(requestUrl)) return await generateManifestResponse(routes, basename, request, generateResponse, temporaryReferences, routeDiscovery, clientVersion);
2534 let isDataRequest = isReactServerRequest(requestUrl);
2535 let staticHandler = createStaticHandler(routes, { basename });
2536 let matches = staticHandler.match(url.pathname);
2537 if (matches) await Promise.all(matches.map((m) => explodeLazyRoute(m.route)));
2538 const leafMatch = matches?.[matches.length - 1];
2539 if (!isDataRequest && leafMatch && !leafMatch.route.Component && !leafMatch.route.ErrorBoundary) return normalizeResourceResponse(request, await generateResourceResponse(routerRequest, staticHandler, leafMatch.route.id, requestContext, onError));
2540 let response = await generateRenderResponse(routerRequest, staticHandler, basename, isDataRequest, decodeReply, requestContext, loadServerAction, decodeAction, decodeFormState, onError, generateResponse, temporaryReferences, allowedActionOrigins, routeDiscovery, clientVersion);
2541 response.headers.set("X-Remix-Response", "yes");
2542 return normalizeResourceResponse(request, response);
2543}
2544function normalizeResourceResponse(request, response) {
2545 if (request.method === "HEAD" && response.headers.get("React-Router-Resource") === "true") {
2546 response.body?.cancel().catch(() => {});
2547 return new Response(null, {
2548 status: response.status,
2549 statusText: response.statusText,
2550 headers: response.headers
2551 });
2552 }
2553 return response;
2554}
2555async function generateManifestResponse(routes, basename, request, generateResponse, temporaryReferences, routeDiscovery, clientVersion) {
2556 let url = new URL(request.url);
2557 if (url.toString().length > 7680) return new Response(null, {
2558 statusText: "Bad Request",
2559 status: 400
2560 });
2561 if (clientVersion !== void 0 && clientVersion !== url.searchParams.get("version")) return new Response(null, {
2562 status: 204,
2563 headers: { "X-Remix-Reload-Document": "true" }
2564 });
2565 if (routeDiscovery?.mode === "initial") {
2566 let payload = {
2567 type: "manifest",
2568 patches: getAllRoutePatches(routes, basename)
2569 };
2570 return generateResponse({
2571 statusCode: 200,
2572 headers: new Headers({
2573 "Content-Type": "text/x-component",
2574 Vary: "Content-Type"
2575 }),
2576 payload
2577 }, {
2578 temporaryReferences,
2579 onError: defaultOnError
2580 });
2581 }
2582 let pathParam = url.searchParams.get("paths");
2583 let pathnames = pathParam ? pathParam.split(",").filter(Boolean) : [url.pathname.replace(/\.manifest$/, "")];
2584 let staticHandler = routes.length > 0 ? createStaticHandler(routes, { basename }) : void 0;
2585 let routeIds = /* @__PURE__ */ new Set();
2586 let matchedRoutes = staticHandler ? pathnames.flatMap((pathname) => {
2587 let pathnameMatches = staticHandler.match(pathname);
2588 return pathnameMatches?.map((m, i) => ({
2589 ...m.route,
2590 parentId: pathnameMatches[i - 1]?.route.id
2591 })) ?? [];
2592 }).filter((route) => {
2593 if (!routeIds.has(route.id)) {
2594 routeIds.add(route.id);
2595 return true;
2596 }
2597 return false;
2598 }) : [];
2599 let payload = {
2600 type: "manifest",
2601 patches: Promise.all([...matchedRoutes.map((route) => getManifestRoute(route)), staticHandler ? getAdditionalRoutePatches(pathnames, staticHandler, Array.from(routeIds)) : Promise.resolve([])]).then((r) => r.flat(1))
2602 };
2603 return generateResponse({
2604 statusCode: 200,
2605 headers: new Headers({ "Content-Type": "text/x-component" }),
2606 payload
2607 }, {
2608 temporaryReferences,
2609 onError: defaultOnError
2610 });
2611}
2612function prependBasenameToRedirectResponse(response, basename = "/") {
2613 if (basename === "/") return response;
2614 let redirect = response.headers.get("Location");
2615 if (!redirect || isAbsoluteUrl(redirect)) return response;
2616 response.headers.set("Location", prependBasename({
2617 basename,
2618 pathname: redirect
2619 }));
2620 return response;
2621}
2622async function processServerAction(request, basename, decodeReply, loadServerAction, decodeAction, decodeFormState, onError, temporaryReferences) {
2623 const getRevalidationRequest = () => new Request(request.url, {
2624 method: "GET",
2625 headers: request.headers,
2626 signal: request.signal
2627 });
2628 const isFormRequest = canDecodeWithFormData(request.headers.get("Content-Type"));
2629 const actionId = request.headers.get("rsc-action-id");
2630 if (actionId) {
2631 if (!decodeReply || !loadServerAction) throw new Error("Cannot handle enhanced server action without decodeReply and loadServerAction functions");
2632 const actionArgs = await decodeReply(isFormRequest ? await request.formData() : await request.text(), { temporaryReferences });
2633 const serverAction = (await loadServerAction(actionId)).bind(null, ...actionArgs);
2634 let actionResult = Promise.resolve(serverAction());
2635 try {
2636 await actionResult;
2637 } catch (error) {
2638 if (isResponse(error)) return error;
2639 onError?.(error);
2640 }
2641 let maybeFormData = actionArgs.length === 1 ? actionArgs[0] : actionArgs[1];
2642 let skipRevalidation = (maybeFormData && typeof maybeFormData === "object" && maybeFormData instanceof FormData ? maybeFormData : null)?.has("$SKIP_REVALIDATION") ?? false;
2643 return {
2644 actionResult,
2645 revalidationRequest: getRevalidationRequest(),
2646 skipRevalidation
2647 };
2648 } else if (isFormRequest) {
2649 const formData = await request.clone().formData();
2650 if (Array.from(formData.keys()).some((k) => k.startsWith("$ACTION_"))) {
2651 if (!decodeAction) throw new Error("Cannot handle form actions without a decodeAction function");
2652 const action = await decodeAction(formData);
2653 let formState = void 0;
2654 try {
2655 let result = await action();
2656 if (isRedirectResponse(result)) result = prependBasenameToRedirectResponse(result, basename);
2657 formState = await decodeFormState?.(result, formData);
2658 } catch (error) {
2659 if (isRedirectResponse(error)) return prependBasenameToRedirectResponse(error, basename);
2660 if (isResponse(error)) return error;
2661 onError?.(error);
2662 }
2663 return {
2664 formState,
2665 revalidationRequest: getRevalidationRequest(),
2666 skipRevalidation: false
2667 };
2668 }
2669 }
2670}
2671async function generateResourceResponse(request, staticHandler, routeId, requestContext, onError) {
2672 try {
2673 return tagResourceResponse(await staticHandler.queryRoute(request, {
2674 routeId,
2675 requestContext,
2676 async generateMiddlewareResponse(queryRoute) {
2677 try {
2678 return tagResourceResponse(await queryRoute(request));
2679 } catch (error) {
2680 return generateErrorResponse(error);
2681 }
2682 },
2683 normalizePath: (r) => getNormalizedPath(r)
2684 }));
2685 } catch (error) {
2686 return generateErrorResponse(error);
2687 }
2688 function generateErrorResponse(error) {
2689 let response;
2690 if (isResponse(error)) response = error;
2691 else if (isRouteErrorResponse(error)) {
2692 onError?.(error);
2693 const errorMessage = typeof error.data === "string" ? error.data : error.statusText;
2694 response = new Response(errorMessage, {
2695 status: error.status,
2696 statusText: error.statusText
2697 });
2698 } else {
2699 onError?.(error);
2700 response = new Response("Internal Server Error", { status: 500 });
2701 }
2702 return tagResourceResponse(response);
2703 }
2704}
2705function tagResourceResponse(response) {
2706 const headers = new Headers(response.headers);
2707 headers.set("React-Router-Resource", "true");
2708 return new Response(response.body, {
2709 status: response.status,
2710 statusText: response.statusText,
2711 headers
2712 });
2713}
2714async function generateRenderResponse(request, staticHandler, basename, isDataRequest, decodeReply, requestContext, loadServerAction, decodeAction, decodeFormState, onError, generateResponse, temporaryReferences, allowedActionOrigins, routeDiscovery, clientVersion) {
2715 let statusCode = 200;
2716 let url = new URL(request.url);
2717 let isSubmission = isMutationMethod(request.method);
2718 let routeIdsToLoad = !isSubmission && url.searchParams.has("_routes") ? url.searchParams.get("_routes").split(",") : null;
2719 let actionResult;
2720 const ctx = {
2721 request,
2722 runningAction: false
2723 };
2724 const result = await ServerStorage.run(ctx, () => staticHandler.query(request, {
2725 requestContext,
2726 skipLoaderErrorBubbling: isDataRequest,
2727 skipRevalidation: isSubmission,
2728 ...routeIdsToLoad ? { filterMatchesToLoad: (m) => routeIdsToLoad.includes(m.route.id) } : {},
2729 normalizePath: (r) => getNormalizedPath(r),
2730 async generateMiddlewareResponse(query) {
2731 let formState;
2732 let skipRevalidation = false;
2733 let potentialCSRFAttackError;
2734 if (isMutationMethod(request.method)) {
2735 try {
2736 throwIfPotentialCSRFAttack(request, allowedActionOrigins);
2737 } catch (error) {
2738 onError?.(error);
2739 potentialCSRFAttackError = error;
2740 request = new Request(request.url, {
2741 method: "GET",
2742 headers: request.headers,
2743 signal: request.signal
2744 });
2745 }
2746 if (!potentialCSRFAttackError) {
2747 ctx.runningAction = true;
2748 let result = await processServerAction(request, basename, decodeReply, loadServerAction, decodeAction, decodeFormState, onError, temporaryReferences).finally(() => {
2749 ctx.runningAction = false;
2750 });
2751 if (isResponse(result)) return generateRedirectResponse(result, actionResult, basename, isDataRequest, generateResponse, temporaryReferences, result === ctx.redirect ? void 0 : ctx.redirect?.headers);
2752 skipRevalidation = result?.skipRevalidation ?? false;
2753 actionResult = result?.actionResult;
2754 formState = result?.formState;
2755 request = result?.revalidationRequest ?? request;
2756 if (ctx.redirect) return generateRedirectResponse(ctx.redirect, actionResult, basename, isDataRequest, generateResponse, temporaryReferences, void 0);
2757 }
2758 }
2759 let staticContext = await query(request, skipRevalidation ? { filterMatchesToLoad: () => false } : void 0);
2760 if (isResponse(staticContext)) return generateRedirectResponse(staticContext, actionResult, basename, isDataRequest, generateResponse, temporaryReferences, ctx.redirect?.headers);
2761 if (potentialCSRFAttackError) {
2762 staticContext.errors ??= {};
2763 staticContext.errors[staticContext.matches[0].route.id] = potentialCSRFAttackError;
2764 staticContext.statusCode = 400;
2765 }
2766 return generateStaticContextResponse(staticHandler, basename, generateResponse, statusCode, routeIdsToLoad, isDataRequest, isSubmission, actionResult, formState, staticContext, temporaryReferences, skipRevalidation, ctx.redirect?.headers, routeDiscovery, clientVersion);
2767 }
2768 }));
2769 if (isRedirectResponse(result)) return generateRedirectResponse(result, actionResult, basename, isDataRequest, generateResponse, temporaryReferences, ctx.redirect?.headers);
2770 invariant(isResponse(result), "Expected a response from query");
2771 if (result.headers.get("Content-Type")?.split(";")[0].trim().toLowerCase() !== "text/x-component") return tagResourceResponse(result);
2772 return result;
2773}
2774function generateRedirectResponse(response, actionResult, basename, isDataRequest, generateResponse, temporaryReferences, sideEffectRedirectHeaders) {
2775 let redirect = response.headers.get("Location");
2776 if (isDataRequest && basename) redirect = stripBasename(redirect, basename) || redirect;
2777 let payload = {
2778 type: "redirect",
2779 location: redirect,
2780 reload: response.headers.get("X-Remix-Reload-Document") === "true",
2781 replace: response.headers.get("X-Remix-Replace") === "true",
2782 status: response.status,
2783 actionResult
2784 };
2785 let headers = new Headers(sideEffectRedirectHeaders === response.headers ? void 0 : sideEffectRedirectHeaders);
2786 for (const [key, value] of response.headers.entries()) headers.append(key, value);
2787 headers.delete("Location");
2788 headers.delete("X-Remix-Reload-Document");
2789 headers.delete("X-Remix-Replace");
2790 headers.delete("Content-Length");
2791 headers.set("Content-Type", "text/x-component");
2792 return generateResponse({
2793 statusCode: 202,
2794 headers,
2795 payload
2796 }, {
2797 temporaryReferences,
2798 onError: defaultOnError
2799 });
2800}
2801async function generateStaticContextResponse(staticHandler, basename, generateResponse, statusCode, routeIdsToLoad, isDataRequest, isSubmission, actionResult, formState, staticContext, temporaryReferences, skipRevalidation, sideEffectRedirectHeaders, routeDiscovery, clientVersion) {
2802 statusCode = staticContext.statusCode ?? statusCode;
2803 if (staticContext.errors) staticContext.errors = Object.fromEntries(Object.entries(staticContext.errors).map(([key, error]) => [key, isRouteErrorResponse(error) ? Object.fromEntries(Object.entries(error)) : error]));
2804 staticContext.matches.forEach((m) => {
2805 const routeHasNoLoaderData = staticContext.loaderData[m.route.id] === void 0;
2806 const routeHasError = Boolean(staticContext.errors && m.route.id in staticContext.errors);
2807 if (routeHasNoLoaderData && !routeHasError) staticContext.loaderData[m.route.id] = null;
2808 });
2809 let headers = getDocumentHeadersImpl(staticContext, (match) => match.route.headers, sideEffectRedirectHeaders);
2810 headers.delete("Content-Length");
2811 const baseRenderPayload = {
2812 type: "render",
2813 basename: staticContext.basename,
2814 clientVersion,
2815 routeDiscovery: routeDiscovery ?? { mode: "lazy" },
2816 actionData: staticContext.actionData,
2817 errors: staticContext.errors,
2818 loaderData: staticContext.loaderData,
2819 location: staticContext.location,
2820 formState
2821 };
2822 const renderPayloadPromise = () => getRenderPayload(baseRenderPayload, staticHandler, basename, routeIdsToLoad, isDataRequest, staticContext, routeDiscovery);
2823 let payload;
2824 if (actionResult) payload = {
2825 type: "action",
2826 actionResult,
2827 rerender: skipRevalidation ? void 0 : renderPayloadPromise()
2828 };
2829 else if (isSubmission && isDataRequest) payload = {
2830 ...baseRenderPayload,
2831 matches: [],
2832 patches: Promise.resolve([])
2833 };
2834 else payload = await renderPayloadPromise();
2835 return generateResponse({
2836 statusCode,
2837 headers,
2838 payload
2839 }, {
2840 temporaryReferences,
2841 onError: defaultOnError
2842 });
2843}
2844async function getRenderPayload(baseRenderPayload, staticHandler, basename, routeIdsToLoad, isDataRequest, staticContext, routeDiscovery) {
2845 let routes = staticHandler.dataRoutes;
2846 let deepestRenderedRouteIdx = staticContext.matches.length - 1;
2847 let parentIds = {};
2848 staticContext.matches.forEach((m, i) => {
2849 if (i > 0) parentIds[m.route.id] = staticContext.matches[i - 1].route.id;
2850 if (staticContext.errors && m.route.id in staticContext.errors && deepestRenderedRouteIdx > i) deepestRenderedRouteIdx = i;
2851 });
2852 let matchesPromise = Promise.all(staticContext.matches.map((match, i) => {
2853 let isBelowErrorBoundary = i > deepestRenderedRouteIdx;
2854 let parentId = parentIds[match.route.id];
2855 return getRSCRouteMatch({
2856 staticContext,
2857 match,
2858 routeIdsToLoad,
2859 isBelowErrorBoundary,
2860 parentId
2861 });
2862 }));
2863 let pathname = staticContext.location.pathname;
2864 let useInitialRouteDiscovery = routeDiscovery?.mode === "initial" && !isDataRequest || shouldUseInitialRouteDiscovery(pathname, staticHandler._matchCost);
2865 let patches;
2866 if (useInitialRouteDiscovery) patches = getAllRoutePatches(routes, basename).then((patches) => patches.filter((patch) => !staticContext.matches.some((m) => m.route.id === patch.id)));
2867 else patches = getAdditionalRoutePatches(getPathsWithAncestors([pathname]).slice(0, -1), staticHandler, staticContext.matches.map((m) => m.route.id));
2868 return {
2869 ...baseRenderPayload,
2870 routeDiscovery: useInitialRouteDiscovery ? { mode: "initial" } : baseRenderPayload.routeDiscovery,
2871 matches: await matchesPromise,
2872 patches
2873 };
2874}
2875async function getRSCRouteMatch({ staticContext, match, isBelowErrorBoundary, routeIdsToLoad, parentId }) {
2876 const route = match.route;
2877 await explodeLazyRoute(route);
2878 const Layout = route.Layout || React.Fragment;
2879 const Component = route.Component;
2880 const ErrorBoundary = route.ErrorBoundary;
2881 const HydrateFallback = route.HydrateFallback;
2882 const loaderData = staticContext.loaderData[route.id];
2883 const actionData = staticContext.actionData?.[route.id];
2884 const params = match.params;
2885 let element = void 0;
2886 let shouldLoadRoute = !routeIdsToLoad || routeIdsToLoad.includes(route.id);
2887 if (Component && shouldLoadRoute) element = !isBelowErrorBoundary ? React.createElement(Layout, null, isClientReference(Component) ? React.createElement(WithComponentProps, { children: React.createElement(Component) }) : React.createElement(Component, {
2888 loaderData,
2889 actionData,
2890 params,
2891 matches: staticContext.matches.map((match) => convertRouteMatchToUiMatch(match, staticContext.loaderData))
2892 })) : React.createElement(Outlet$2);
2893 let error = void 0;
2894 if (ErrorBoundary && staticContext.errors) error = staticContext.errors[route.id];
2895 const errorElement = ErrorBoundary ? React.createElement(Layout, null, isClientReference(ErrorBoundary) ? React.createElement(WithErrorBoundaryProps, { children: React.createElement(ErrorBoundary) }) : React.createElement(ErrorBoundary, {
2896 loaderData,
2897 actionData,
2898 params,
2899 error
2900 })) : void 0;
2901 const hydrateFallbackElement = HydrateFallback ? React.createElement(Layout, null, isClientReference(HydrateFallback) ? React.createElement(WithHydrateFallbackProps, { children: React.createElement(HydrateFallback) }) : React.createElement(HydrateFallback, {
2902 loaderData,
2903 actionData,
2904 params
2905 })) : void 0;
2906 const hmrRoute = route;
2907 return {
2908 clientAction: route.clientAction,
2909 clientLoader: route.clientLoader,
2910 clientMiddleware: route.clientMiddleware,
2911 element,
2912 errorElement,
2913 handle: route.handle,
2914 hasAction: !!route.action,
2915 hasComponent: !!Component,
2916 hasLoader: !!route.loader,
2917 hydrateFallbackElement,
2918 id: route.id,
2919 index: "index" in route ? route.index : void 0,
2920 links: route.links,
2921 meta: route.meta,
2922 params,
2923 parentId,
2924 path: route.path,
2925 pathname: match.pathname,
2926 pathnameBase: match.pathnameBase,
2927 shouldRevalidate: route.shouldRevalidate,
2928 ...hmrRoute.__ensureClientRouteModuleForHMR ? { __ensureClientRouteModuleForHMR: hmrRoute.__ensureClientRouteModuleForHMR } : {}
2929 };
2930}
2931async function getManifestRoute(route) {
2932 await explodeLazyRoute(route);
2933 const Layout = route.Layout || React.Fragment;
2934 const errorElement = route.ErrorBoundary ? React.createElement(Layout, null, React.createElement(route.ErrorBoundary)) : void 0;
2935 return {
2936 clientAction: route.clientAction,
2937 clientLoader: route.clientLoader,
2938 clientMiddleware: route.clientMiddleware,
2939 handle: route.handle,
2940 hasAction: !!route.action,
2941 hasComponent: !!route.Component,
2942 errorElement,
2943 hasLoader: !!route.loader,
2944 id: route.id,
2945 parentId: route.parentId,
2946 path: route.path,
2947 index: "index" in route ? route.index : void 0,
2948 links: route.links,
2949 meta: route.meta
2950 };
2951}
2952async function explodeLazyRoute(route) {
2953 if ("lazy" in route && route.lazy) {
2954 let { default: lazyDefaultExport, Component: lazyComponentExport, ...lazyProperties } = await route.lazy();
2955 let Component = lazyComponentExport || lazyDefaultExport;
2956 if (Component && !route.Component) route.Component = Component;
2957 for (let [k, v] of Object.entries(lazyProperties)) if (k !== "id" && k !== "path" && k !== "index" && k !== "children" && route[k] == null) route[k] = v;
2958 route.lazy = void 0;
2959 }
2960}
2961async function getAllRoutePatches(routes, basename) {
2962 let patches = [];
2963 async function traverse(route, parentId) {
2964 let manifestRoute = await getManifestRoute({
2965 ...route,
2966 parentId
2967 });
2968 patches.push(manifestRoute);
2969 if ("children" in route && route.children?.length) for (let child of route.children) await traverse(child, route.id);
2970 }
2971 for (let route of routes) await traverse(route, void 0);
2972 return patches.filter((p) => !!p.parentId);
2973}
2974async function getAdditionalRoutePatches(pathnames, staticHandler, matchedRouteIds) {
2975 let patchRouteMatches = /* @__PURE__ */ new Map();
2976 let matchedPaths = /* @__PURE__ */ new Set();
2977 for (const pathname of pathnames) {
2978 if (matchedPaths.has(pathname)) continue;
2979 matchedPaths.add(pathname);
2980 let matches = staticHandler.match(pathname) || [];
2981 matches.forEach((m, i) => {
2982 if (patchRouteMatches.get(m.route.id)) return;
2983 patchRouteMatches.set(m.route.id, {
2984 ...m.route,
2985 parentId: matches[i - 1]?.route.id
2986 });
2987 });
2988 }
2989 return await Promise.all([...patchRouteMatches.values()].filter((route) => !matchedRouteIds.some((id) => id === route.id)).map((route) => getManifestRoute(route)));
2990}
2991function isReactServerRequest(url) {
2992 return url.pathname.endsWith(".rsc");
2993}
2994function isManifestRequest(url) {
2995 return url.pathname.endsWith(".manifest");
2996}
2997function defaultOnError(error) {
2998 if (isRedirectResponse(error)) return createRedirectErrorDigest(error);
2999 if (isResponse(error) || isDataWithResponseInit(error)) return createRouteErrorResponseDigest(error);
3000}
3001function isClientReference(x) {
3002 try {
3003 return x.$$typeof === Symbol.for("react.client.reference");
3004 } catch {
3005 return false;
3006 }
3007}
3008function canDecodeWithFormData(contentType) {
3009 if (!contentType) return false;
3010 return contentType.match(/\bapplication\/x-www-form-urlencoded\b/) || contentType.match(/\bmultipart\/form-data\b/);
3011}
3012//#endregion
3013//#region lib/href.ts
3014function stringify(p) {
3015 return p == null ? "" : typeof p === "string" ? p : String(p);
3016}
3017/**
3018* Returns a resolved URL path for the specified route.
3019*
3020* Param values are percent-encoded for use in a path segment: characters that
3021* would change the URL structure (`/`, `?`, `#`, `%`, whitespace, non-ASCII)
3022* are escaped, while characters that RFC 3986 allows literally in a path
3023* segment (`$ & + , ; = : @`) are kept as-is. Note this differs from query-string
3024* encoding (`encodeURIComponent`/`URLSearchParams`), where those characters are
3025* delimiters and must be escaped. Splat (`*`) values are encoded per segment,
3026* preserving `/` separators.
3027*
3028* See [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3)
3029*
3030* @example
3031* const h = href("/:lang?/about", { lang: "en" })
3032* // -> `/en/about`
3033*
3034* <Link to={href("/products/:id", { id: "abc123" })} />
3035*
3036* @public
3037* @category Utils
3038* @mode framework
3039* @param path The route path to resolve
3040* @param args The route params to use when resolving the path
3041* @returns The resolved URL path
3042*/
3043function href(path, ...args) {
3044 let params = args[0];
3045 let result = trimTrailingSplat(path).replace(/\/:([\w-]+)(\?)?/g, (_, param, questionMark) => {
3046 const isRequired = questionMark === void 0;
3047 const value = params?.[param];
3048 if (isRequired && value == null) throw new Error(`Path '${path}' requires param '${param}' but it was not provided`);
3049 return value == null ? "" : "/" + encodePathParam(stringify(value));
3050 });
3051 if (path.endsWith("*")) {
3052 const value = params?.["*"];
3053 if (value != null) result += "/" + stringify(value).split("/").map(encodePathParam).join("/");
3054 }
3055 return result.replace(/^\/{2,}/, "/") || "/";
3056}
3057/**
3058* Removes a trailing splat and any number of slashes from the end of the path.
3059*
3060* Benchmarked to be faster than `path.replace(/\/*\*?$/, "")`, which backtracks.
3061*/
3062function trimTrailingSplat(path) {
3063 let i = path.length - 1;
3064 let char = path[i];
3065 if (char !== "*" && char !== "/") return path;
3066 i--;
3067 for (; i >= 0; i--) if (path[i] !== "/") break;
3068 return path.slice(0, i + 1);
3069}
3070//#endregion
3071//#region lib/server-runtime/crypto.ts
3072const encoder = /* @__PURE__ */ new TextEncoder();
3073const sign = async (value, secret) => {
3074 let data = encoder.encode(value);
3075 let key = await createKey(secret, ["sign"]);
3076 let signature = await crypto.subtle.sign("HMAC", key, data);
3077 let hash = btoa(String.fromCharCode(...new Uint8Array(signature))).replace(/=+$/, "");
3078 return value + "." + hash;
3079};
3080const unsign = async (cookie, secret) => {
3081 let index = cookie.lastIndexOf(".");
3082 let value = cookie.slice(0, index);
3083 let hash = cookie.slice(index + 1);
3084 let data = encoder.encode(value);
3085 let key = await createKey(secret, ["verify"]);
3086 try {
3087 let signature = byteStringToUint8Array(atob(hash));
3088 return await crypto.subtle.verify("HMAC", key, signature, data) ? value : false;
3089 } catch {
3090 return false;
3091 }
3092};
3093const createKey = async (secret, usages) => crypto.subtle.importKey("raw", encoder.encode(secret), {
3094 name: "HMAC",
3095 hash: "SHA-256"
3096}, false, usages);
3097function byteStringToUint8Array(byteString) {
3098 let array = new Uint8Array(byteString.length);
3099 for (let i = 0; i < byteString.length; i++) array[i] = byteString.charCodeAt(i);
3100 return array;
3101}
3102//#endregion
3103//#region lib/server-runtime/cookies.ts
3104/**
3105* Creates a logical container for managing a browser cookie from the server.
3106*
3107* @public
3108* @category Utils
3109* @mode framework
3110* @mode data
3111* @param name The name of the cookie.
3112* @param cookieOptions Options for parsing and serializing the cookie.
3113* @returns A {@link Cookie} object for parsing and serializing the cookie.
3114*/
3115const createCookie = (name, cookieOptions = {}) => {
3116 let { secrets = [], ...options } = {
3117 path: "/",
3118 sameSite: "lax",
3119 ...cookieOptions
3120 };
3121 warnOnceAboutExpiresCookie(name, options.expires);
3122 return {
3123 get name() {
3124 return name;
3125 },
3126 get isSigned() {
3127 return secrets.length > 0;
3128 },
3129 get expires() {
3130 return typeof options.maxAge !== "undefined" ? new Date(Date.now() + options.maxAge * 1e3) : options.expires;
3131 },
3132 async parse(cookieHeader, parseOptions) {
3133 if (!cookieHeader) return null;
3134 let cookies = parse(cookieHeader, {
3135 ...options,
3136 ...parseOptions
3137 });
3138 if (name in cookies) {
3139 let value = cookies[name];
3140 if (typeof value === "string" && value !== "") return await decodeCookieValue(value, secrets);
3141 else return "";
3142 } else return null;
3143 },
3144 async serialize(value, serializeOptions) {
3145 return serialize(name, value === "" ? "" : await encodeCookieValue(value, secrets), {
3146 ...options,
3147 ...serializeOptions
3148 });
3149 }
3150 };
3151};
3152/**
3153* Returns `true` if a value is a React Router {@link Cookie} object.
3154*
3155* @public
3156* @category Utils
3157* @mode framework
3158* @mode data
3159* @param object The value to check.
3160* @returns `true` if the value is a React Router {@link Cookie} object;
3161* otherwise, `false`.
3162*/
3163const isCookie = (object) => {
3164 return object != null && typeof object.name === "string" && typeof object.isSigned === "boolean" && typeof object.parse === "function" && typeof object.serialize === "function";
3165};
3166async function encodeCookieValue(value, secrets) {
3167 let encoded = encodeData(value);
3168 if (secrets.length > 0) encoded = await sign(encoded, secrets[0]);
3169 return encoded;
3170}
3171async function decodeCookieValue(value, secrets) {
3172 if (secrets.length > 0) {
3173 for (let secret of secrets) {
3174 let unsignedValue = await unsign(value, secret);
3175 if (unsignedValue !== false) return decodeData(unsignedValue);
3176 }
3177 return null;
3178 }
3179 return decodeData(value);
3180}
3181function encodeData(value) {
3182 return btoa(myUnescape(encodeURIComponent(JSON.stringify(value))));
3183}
3184function decodeData(value) {
3185 try {
3186 return JSON.parse(decodeURIComponent(myEscape(atob(value))));
3187 } catch {
3188 return {};
3189 }
3190}
3191function myEscape(value) {
3192 let str = value.toString();
3193 let result = "";
3194 let index = 0;
3195 let chr, code;
3196 while (index < str.length) {
3197 chr = str.charAt(index++);
3198 if (/[\w*+\-./@]/.exec(chr)) result += chr;
3199 else {
3200 code = chr.charCodeAt(0);
3201 if (code < 256) result += "%" + hex(code, 2);
3202 else result += "%u" + hex(code, 4).toUpperCase();
3203 }
3204 }
3205 return result;
3206}
3207function hex(code, length) {
3208 let result = code.toString(16);
3209 while (result.length < length) result = "0" + result;
3210 return result;
3211}
3212function myUnescape(value) {
3213 let str = value.toString();
3214 let result = "";
3215 let index = 0;
3216 let chr, part;
3217 while (index < str.length) {
3218 chr = str.charAt(index++);
3219 if (chr === "%") if (str.charAt(index) === "u") {
3220 part = str.slice(index + 1, index + 5);
3221 if (/^[\da-f]{4}$/i.exec(part)) {
3222 result += String.fromCharCode(parseInt(part, 16));
3223 index += 5;
3224 continue;
3225 }
3226 } else {
3227 part = str.slice(index, index + 2);
3228 if (/^[\da-f]{2}$/i.exec(part)) {
3229 result += String.fromCharCode(parseInt(part, 16));
3230 index += 2;
3231 continue;
3232 }
3233 }
3234 result += chr;
3235 }
3236 return result;
3237}
3238function warnOnceAboutExpiresCookie(name, expires) {
3239 warnOnce(!expires, `The "${name}" cookie has an "expires" property set. This will cause the expires value to not be updated when the session is committed. Instead, you should set the expires value when serializing the cookie. You can use \`commitSession(session, { expires })\` if using a session storage object, or \`cookie.serialize("value", { expires })\` if you're using the cookie directly.`);
3240}
3241//#endregion
3242//#region lib/server-runtime/sessions.ts
3243function flash(name) {
3244 return `__flash_${name}__`;
3245}
3246/**
3247* Creates a new Session object.
3248*
3249* Note: This function is typically not invoked directly by application code.
3250* Instead, use a `SessionStorage` object's `getSession` method.
3251*
3252* @category Utils
3253* @param initialData The initial data for the session.
3254* @param id The identifier for the session. Defaults to an empty string for a
3255* new session.
3256* @returns A new {@link Session} object.
3257*/
3258const createSession = (initialData = {}, id = "") => {
3259 let map = new Map(Object.entries(initialData));
3260 return {
3261 get id() {
3262 return id;
3263 },
3264 get data() {
3265 return Object.fromEntries(map);
3266 },
3267 has(name) {
3268 return map.has(name) || map.has(flash(name));
3269 },
3270 get(name) {
3271 if (map.has(name)) return map.get(name);
3272 let flashName = flash(name);
3273 if (map.has(flashName)) {
3274 let value = map.get(flashName);
3275 map.delete(flashName);
3276 return value;
3277 }
3278 },
3279 set(name, value) {
3280 map.set(name, value);
3281 },
3282 flash(name, value) {
3283 map.set(flash(name), value);
3284 },
3285 unset(name) {
3286 map.delete(name);
3287 }
3288 };
3289};
3290/**
3291* Returns `true` if a value is a React Router {@link Session} object.
3292*
3293* @public
3294* @category Utils
3295* @mode framework
3296* @mode data
3297* @param object The value to check.
3298* @returns `true` if the value is a React Router {@link Session} object;
3299* otherwise, `false`.
3300*/
3301const isSession = (object) => {
3302 return object != null && typeof object.id === "string" && typeof object.data !== "undefined" && typeof object.has === "function" && typeof object.get === "function" && typeof object.set === "function" && typeof object.flash === "function" && typeof object.unset === "function";
3303};
3304/**
3305* Creates a SessionStorage object using a SessionIdStorageStrategy.
3306*
3307* Note: This is a low-level API that should only be used if none of the
3308* existing session storage options meet your requirements.
3309*
3310* @category Utils
3311* @param strategy The strategy used to store session identifiers and data.
3312* @returns A {@link SessionStorage} object that persists session data using the
3313* provided strategy.
3314*/
3315function createSessionStorage({ cookie: cookieArg, createData, readData, updateData, deleteData }) {
3316 let cookie = isCookie(cookieArg) ? cookieArg : createCookie(cookieArg?.name || "__session", cookieArg);
3317 warnOnceAboutSigningSessionCookie(cookie);
3318 return {
3319 async getSession(cookieHeader, options) {
3320 let id = cookieHeader && await cookie.parse(cookieHeader, options);
3321 return createSession(id && await readData(id) || {}, id || "");
3322 },
3323 async commitSession(session, options) {
3324 let { id, data } = session;
3325 let expires = options?.maxAge != null ? new Date(Date.now() + options.maxAge * 1e3) : options?.expires != null ? options.expires : cookie.expires;
3326 if (id) await updateData(id, data, expires);
3327 else id = await createData(data, expires);
3328 return cookie.serialize(id, options);
3329 },
3330 async destroySession(session, options) {
3331 if (session.id) await deleteData(session.id);
3332 return cookie.serialize("", {
3333 ...options,
3334 maxAge: void 0,
3335 expires: /* @__PURE__ */ new Date(0)
3336 });
3337 }
3338 };
3339}
3340function warnOnceAboutSigningSessionCookie(cookie) {
3341 warnOnce(cookie.isSigned, `The "${cookie.name}" cookie is not signed, but session cookies should be signed to prevent tampering on the client before they are sent back to the server. See https://reactrouter.com/explanation/sessions-and-cookies#signing-cookies for more information.`);
3342}
3343//#endregion
3344//#region lib/server-runtime/sessions/cookieStorage.ts
3345/**
3346* Creates and returns a SessionStorage object that stores all session data
3347* directly in the session cookie itself.
3348*
3349* This has the advantage that no database or other backend services are
3350* needed, and can help to simplify some load-balanced scenarios. However, it
3351* also has the limitation that serialized session data may not exceed the
3352* browser's maximum cookie size. Trade-offs!
3353*
3354* @public
3355* @category Utils
3356* @mode framework
3357* @mode data
3358* @param options Options for creating the cookie-backed session storage.
3359* @returns A {@link SessionStorage} object that stores all session data in its
3360* cookie.
3361*/
3362function createCookieSessionStorage({ cookie: cookieArg } = {}) {
3363 let cookie = isCookie(cookieArg) ? cookieArg : createCookie(cookieArg?.name || "__session", cookieArg);
3364 warnOnceAboutSigningSessionCookie(cookie);
3365 return {
3366 async getSession(cookieHeader, options) {
3367 return createSession(cookieHeader && await cookie.parse(cookieHeader, options) || {});
3368 },
3369 async commitSession(session, options) {
3370 let serializedCookie = await cookie.serialize(session.data, options);
3371 if (serializedCookie.length > 4096) throw new Error("Cookie length will exceed browser maximum. Length: " + serializedCookie.length);
3372 return serializedCookie;
3373 },
3374 async destroySession(_session, options) {
3375 return cookie.serialize("", {
3376 ...options,
3377 maxAge: void 0,
3378 expires: /* @__PURE__ */ new Date(0)
3379 });
3380 }
3381 };
3382}
3383//#endregion
3384//#region lib/server-runtime/sessions/memoryStorage.ts
3385/**
3386* Creates and returns a simple in-memory SessionStorage object.
3387*
3388* Intended for local development and testing. It does not scale beyond a single
3389* process, and all session data is lost when the server process stops/restarts.
3390*
3391* @public
3392* @category Utils
3393* @mode framework
3394* @mode data
3395* @param options Options for creating the in-memory session storage.
3396* @returns A {@link SessionStorage} object that stores session data in memory.
3397*/
3398function createMemorySessionStorage({ cookie } = {}) {
3399 let map = /* @__PURE__ */ new Map();
3400 return createSessionStorage({
3401 cookie,
3402 async createData(data, expires) {
3403 let id = crypto.randomUUID();
3404 map.set(id, {
3405 data,
3406 expires
3407 });
3408 return id;
3409 },
3410 async readData(id) {
3411 if (map.has(id)) {
3412 let { data, expires } = map.get(id);
3413 if (!expires || expires > /* @__PURE__ */ new Date()) return data;
3414 if (expires) map.delete(id);
3415 }
3416 return null;
3417 },
3418 async updateData(id, data, expires) {
3419 map.set(id, {
3420 data,
3421 expires
3422 });
3423 },
3424 async deleteData(id) {
3425 map.delete(id);
3426 }
3427 });
3428}
3429//#endregion
3430export { Await, BrowserRouter, Form, HashRouter, Link, Links, MemoryRouter, Meta, NavLink, Navigate, Outlet, Route, Router, RouterContextProvider, RouterProvider, Routes, ScrollRestoration, StaticRouter, StaticRouterProvider, createContext, createCookie, createCookieSessionStorage, createMemorySessionStorage, createSession, createSessionStorage, createStaticHandler, data, href, isCookie, isRouteErrorResponse, isSession, matchRoutes, redirect, redirectDocument, replace, unstable_HistoryRouter, getRequest as unstable_getRequest, matchRSCServerRequest as unstable_matchRSCServerRequest };