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