UNPKG

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