UNPKG

102 kBJavaScriptView Raw
1'use strict';
2
3var node_async_hooks = require('node:async_hooks');
4var React2 = require('react');
5var setCookieParser = require('set-cookie-parser');
6var reactServerClient = require('react-router/internal/react-server-client');
7var cookie = require('cookie');
8
9function _interopNamespace(e) {
10 if (e && e.__esModule) return e;
11 var n = Object.create(null);
12 if (e) {
13 Object.keys(e).forEach(function (k) {
14 if (k !== 'default') {
15 var d = Object.getOwnPropertyDescriptor(e, k);
16 Object.defineProperty(n, k, d.get ? d : {
17 enumerable: true,
18 get: function () { return e[k]; }
19 });
20 }
21 });
22 }
23 n.default = e;
24 return Object.freeze(n);
25}
26
27var React2__namespace = /*#__PURE__*/_interopNamespace(React2);
28
29/**
30 * react-router v7.7.1
31 *
32 * Copyright (c) Remix Software Inc.
33 *
34 * This source code is licensed under the MIT license found in the
35 * LICENSE.md file in the root directory of this source tree.
36 *
37 * @license MIT
38 */
39var __typeError = (msg) => {
40 throw TypeError(msg);
41};
42var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
43var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
44var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
45
46// lib/router/history.ts
47function invariant(value, message) {
48 if (value === false || value === null || typeof value === "undefined") {
49 throw new Error(message);
50 }
51}
52function warning(cond, message) {
53 if (!cond) {
54 if (typeof console !== "undefined") console.warn(message);
55 try {
56 throw new Error(message);
57 } catch (e) {
58 }
59 }
60}
61function createKey() {
62 return Math.random().toString(36).substring(2, 10);
63}
64function createLocation(current, to, state = null, key) {
65 let location = {
66 pathname: typeof current === "string" ? current : current.pathname,
67 search: "",
68 hash: "",
69 ...typeof to === "string" ? parsePath(to) : to,
70 state,
71 // TODO: This could be cleaned up. push/replace should probably just take
72 // full Locations now and avoid the need to run through this flow at all
73 // But that's a pretty big refactor to the current test suite so going to
74 // keep as is for the time being and just let any incoming keys take precedence
75 key: to && to.key || key || createKey()
76 };
77 return location;
78}
79function createPath({
80 pathname = "/",
81 search = "",
82 hash = ""
83}) {
84 if (search && search !== "?")
85 pathname += search.charAt(0) === "?" ? search : "?" + search;
86 if (hash && hash !== "#")
87 pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
88 return pathname;
89}
90function parsePath(path) {
91 let parsedPath = {};
92 if (path) {
93 let hashIndex = path.indexOf("#");
94 if (hashIndex >= 0) {
95 parsedPath.hash = path.substring(hashIndex);
96 path = path.substring(0, hashIndex);
97 }
98 let searchIndex = path.indexOf("?");
99 if (searchIndex >= 0) {
100 parsedPath.search = path.substring(searchIndex);
101 path = path.substring(0, searchIndex);
102 }
103 if (path) {
104 parsedPath.pathname = path;
105 }
106 }
107 return parsedPath;
108}
109
110// lib/router/utils.ts
111function unstable_createContext(defaultValue) {
112 return { defaultValue };
113}
114var _map;
115var unstable_RouterContextProvider = class {
116 constructor(init) {
117 __privateAdd(this, _map, /* @__PURE__ */ new Map());
118 if (init) {
119 for (let [context, value] of init) {
120 this.set(context, value);
121 }
122 }
123 }
124 get(context) {
125 if (__privateGet(this, _map).has(context)) {
126 return __privateGet(this, _map).get(context);
127 }
128 if (context.defaultValue !== void 0) {
129 return context.defaultValue;
130 }
131 throw new Error("No value found for context");
132 }
133 set(context, value) {
134 __privateGet(this, _map).set(context, value);
135 }
136};
137_map = new WeakMap();
138var unsupportedLazyRouteObjectKeys = /* @__PURE__ */ new Set([
139 "lazy",
140 "caseSensitive",
141 "path",
142 "id",
143 "index",
144 "children"
145]);
146function isUnsupportedLazyRouteObjectKey(key) {
147 return unsupportedLazyRouteObjectKeys.has(
148 key
149 );
150}
151var unsupportedLazyRouteFunctionKeys = /* @__PURE__ */ new Set([
152 "lazy",
153 "caseSensitive",
154 "path",
155 "id",
156 "index",
157 "unstable_middleware",
158 "children"
159]);
160function isUnsupportedLazyRouteFunctionKey(key) {
161 return unsupportedLazyRouteFunctionKeys.has(
162 key
163 );
164}
165function isIndexRoute(route) {
166 return route.index === true;
167}
168function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
169 return routes.map((route, index) => {
170 let treePath = [...parentPath, String(index)];
171 let id = typeof route.id === "string" ? route.id : treePath.join("-");
172 invariant(
173 route.index !== true || !route.children,
174 `Cannot specify children on an index route`
175 );
176 invariant(
177 allowInPlaceMutations || !manifest[id],
178 `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
179 );
180 if (isIndexRoute(route)) {
181 let indexRoute = {
182 ...route,
183 ...mapRouteProperties(route),
184 id
185 };
186 manifest[id] = indexRoute;
187 return indexRoute;
188 } else {
189 let pathOrLayoutRoute = {
190 ...route,
191 ...mapRouteProperties(route),
192 id,
193 children: void 0
194 };
195 manifest[id] = pathOrLayoutRoute;
196 if (route.children) {
197 pathOrLayoutRoute.children = convertRoutesToDataRoutes(
198 route.children,
199 mapRouteProperties,
200 treePath,
201 manifest,
202 allowInPlaceMutations
203 );
204 }
205 return pathOrLayoutRoute;
206 }
207 });
208}
209function matchRoutes(routes, locationArg, basename = "/") {
210 return matchRoutesImpl(routes, locationArg, basename, false);
211}
212function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
213 let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
214 let pathname = stripBasename(location.pathname || "/", basename);
215 if (pathname == null) {
216 return null;
217 }
218 let branches = flattenRoutes(routes);
219 rankRouteBranches(branches);
220 let matches = null;
221 for (let i = 0; matches == null && i < branches.length; ++i) {
222 let decoded = decodePath(pathname);
223 matches = matchRouteBranch(
224 branches[i],
225 decoded,
226 allowPartial
227 );
228 }
229 return matches;
230}
231function convertRouteMatchToUiMatch(match, loaderData) {
232 let { route, pathname, params } = match;
233 return {
234 id: route.id,
235 pathname,
236 params,
237 data: loaderData[route.id],
238 handle: route.handle
239 };
240}
241function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "") {
242 let flattenRoute = (route, index, relativePath) => {
243 let meta = {
244 relativePath: relativePath === void 0 ? route.path || "" : relativePath,
245 caseSensitive: route.caseSensitive === true,
246 childrenIndex: index,
247 route
248 };
249 if (meta.relativePath.startsWith("/")) {
250 invariant(
251 meta.relativePath.startsWith(parentPath),
252 `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.`
253 );
254 meta.relativePath = meta.relativePath.slice(parentPath.length);
255 }
256 let path = joinPaths([parentPath, meta.relativePath]);
257 let routesMeta = parentsMeta.concat(meta);
258 if (route.children && route.children.length > 0) {
259 invariant(
260 // Our types know better, but runtime JS may not!
261 // @ts-expect-error
262 route.index !== true,
263 `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
264 );
265 flattenRoutes(route.children, branches, routesMeta, path);
266 }
267 if (route.path == null && !route.index) {
268 return;
269 }
270 branches.push({
271 path,
272 score: computeScore(path, route.index),
273 routesMeta
274 });
275 };
276 routes.forEach((route, index) => {
277 if (route.path === "" || !route.path?.includes("?")) {
278 flattenRoute(route, index);
279 } else {
280 for (let exploded of explodeOptionalSegments(route.path)) {
281 flattenRoute(route, index, exploded);
282 }
283 }
284 });
285 return branches;
286}
287function explodeOptionalSegments(path) {
288 let segments = path.split("/");
289 if (segments.length === 0) return [];
290 let [first, ...rest] = segments;
291 let isOptional = first.endsWith("?");
292 let required = first.replace(/\?$/, "");
293 if (rest.length === 0) {
294 return isOptional ? [required, ""] : [required];
295 }
296 let restExploded = explodeOptionalSegments(rest.join("/"));
297 let result = [];
298 result.push(
299 ...restExploded.map(
300 (subpath) => subpath === "" ? required : [required, subpath].join("/")
301 )
302 );
303 if (isOptional) {
304 result.push(...restExploded);
305 }
306 return result.map(
307 (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
308 );
309}
310function rankRouteBranches(branches) {
311 branches.sort(
312 (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
313 a.routesMeta.map((meta) => meta.childrenIndex),
314 b.routesMeta.map((meta) => meta.childrenIndex)
315 )
316 );
317}
318var paramRe = /^:[\w-]+$/;
319var dynamicSegmentValue = 3;
320var indexRouteValue = 2;
321var emptySegmentValue = 1;
322var staticSegmentValue = 10;
323var splatPenalty = -2;
324var isSplat = (s) => s === "*";
325function computeScore(path, index) {
326 let segments = path.split("/");
327 let initialScore = segments.length;
328 if (segments.some(isSplat)) {
329 initialScore += splatPenalty;
330 }
331 if (index) {
332 initialScore += indexRouteValue;
333 }
334 return segments.filter((s) => !isSplat(s)).reduce(
335 (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
336 initialScore
337 );
338}
339function compareIndexes(a, b) {
340 let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
341 return siblings ? (
342 // If two routes are siblings, we should try to match the earlier sibling
343 // first. This allows people to have fine-grained control over the matching
344 // behavior by simply putting routes with identical paths in the order they
345 // want them tried.
346 a[a.length - 1] - b[b.length - 1]
347 ) : (
348 // Otherwise, it doesn't really make sense to rank non-siblings by index,
349 // so they sort equally.
350 0
351 );
352}
353function matchRouteBranch(branch, pathname, allowPartial = false) {
354 let { routesMeta } = branch;
355 let matchedParams = {};
356 let matchedPathname = "/";
357 let matches = [];
358 for (let i = 0; i < routesMeta.length; ++i) {
359 let meta = routesMeta[i];
360 let end = i === routesMeta.length - 1;
361 let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
362 let match = matchPath(
363 { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
364 remainingPathname
365 );
366 let route = meta.route;
367 if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
368 match = matchPath(
369 {
370 path: meta.relativePath,
371 caseSensitive: meta.caseSensitive,
372 end: false
373 },
374 remainingPathname
375 );
376 }
377 if (!match) {
378 return null;
379 }
380 Object.assign(matchedParams, match.params);
381 matches.push({
382 // TODO: Can this as be avoided?
383 params: matchedParams,
384 pathname: joinPaths([matchedPathname, match.pathname]),
385 pathnameBase: normalizePathname(
386 joinPaths([matchedPathname, match.pathnameBase])
387 ),
388 route
389 });
390 if (match.pathnameBase !== "/") {
391 matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
392 }
393 }
394 return matches;
395}
396function matchPath(pattern, pathname) {
397 if (typeof pattern === "string") {
398 pattern = { path: pattern, caseSensitive: false, end: true };
399 }
400 let [matcher, compiledParams] = compilePath(
401 pattern.path,
402 pattern.caseSensitive,
403 pattern.end
404 );
405 let match = pathname.match(matcher);
406 if (!match) return null;
407 let matchedPathname = match[0];
408 let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
409 let captureGroups = match.slice(1);
410 let params = compiledParams.reduce(
411 (memo, { paramName, isOptional }, index) => {
412 if (paramName === "*") {
413 let splatValue = captureGroups[index] || "";
414 pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
415 }
416 const value = captureGroups[index];
417 if (isOptional && !value) {
418 memo[paramName] = void 0;
419 } else {
420 memo[paramName] = (value || "").replace(/%2F/g, "/");
421 }
422 return memo;
423 },
424 {}
425 );
426 return {
427 params,
428 pathname: matchedPathname,
429 pathnameBase,
430 pattern
431 };
432}
433function compilePath(path, caseSensitive = false, end = true) {
434 warning(
435 path === "*" || !path.endsWith("*") || path.endsWith("/*"),
436 `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(/\*$/, "/*")}".`
437 );
438 let params = [];
439 let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
440 /\/:([\w-]+)(\?)?/g,
441 (_, paramName, isOptional) => {
442 params.push({ paramName, isOptional: isOptional != null });
443 return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
444 }
445 );
446 if (path.endsWith("*")) {
447 params.push({ paramName: "*" });
448 regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
449 } else if (end) {
450 regexpSource += "\\/*$";
451 } else if (path !== "" && path !== "/") {
452 regexpSource += "(?:(?=\\/|$))";
453 } else ;
454 let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
455 return [matcher, params];
456}
457function decodePath(value) {
458 try {
459 return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
460 } catch (error) {
461 warning(
462 false,
463 `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}).`
464 );
465 return value;
466 }
467}
468function stripBasename(pathname, basename) {
469 if (basename === "/") return pathname;
470 if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
471 return null;
472 }
473 let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
474 let nextChar = pathname.charAt(startIndex);
475 if (nextChar && nextChar !== "/") {
476 return null;
477 }
478 return pathname.slice(startIndex) || "/";
479}
480function prependBasename({
481 basename,
482 pathname
483}) {
484 return pathname === "/" ? basename : joinPaths([basename, pathname]);
485}
486function resolvePath(to, fromPathname = "/") {
487 let {
488 pathname: toPathname,
489 search = "",
490 hash = ""
491 } = typeof to === "string" ? parsePath(to) : to;
492 let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
493 return {
494 pathname,
495 search: normalizeSearch(search),
496 hash: normalizeHash(hash)
497 };
498}
499function resolvePathname(relativePath, fromPathname) {
500 let segments = fromPathname.replace(/\/+$/, "").split("/");
501 let relativeSegments = relativePath.split("/");
502 relativeSegments.forEach((segment) => {
503 if (segment === "..") {
504 if (segments.length > 1) segments.pop();
505 } else if (segment !== ".") {
506 segments.push(segment);
507 }
508 });
509 return segments.length > 1 ? segments.join("/") : "/";
510}
511function getInvalidPathError(char, field, dest, path) {
512 return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
513 path
514 )}]. 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.`;
515}
516function getPathContributingMatches(matches) {
517 return matches.filter(
518 (match, index) => index === 0 || match.route.path && match.route.path.length > 0
519 );
520}
521function getResolveToMatches(matches) {
522 let pathMatches = getPathContributingMatches(matches);
523 return pathMatches.map(
524 (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
525 );
526}
527function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
528 let to;
529 if (typeof toArg === "string") {
530 to = parsePath(toArg);
531 } else {
532 to = { ...toArg };
533 invariant(
534 !to.pathname || !to.pathname.includes("?"),
535 getInvalidPathError("?", "pathname", "search", to)
536 );
537 invariant(
538 !to.pathname || !to.pathname.includes("#"),
539 getInvalidPathError("#", "pathname", "hash", to)
540 );
541 invariant(
542 !to.search || !to.search.includes("#"),
543 getInvalidPathError("#", "search", "hash", to)
544 );
545 }
546 let isEmptyPath = toArg === "" || to.pathname === "";
547 let toPathname = isEmptyPath ? "/" : to.pathname;
548 let from;
549 if (toPathname == null) {
550 from = locationPathname;
551 } else {
552 let routePathnameIndex = routePathnames.length - 1;
553 if (!isPathRelative && toPathname.startsWith("..")) {
554 let toSegments = toPathname.split("/");
555 while (toSegments[0] === "..") {
556 toSegments.shift();
557 routePathnameIndex -= 1;
558 }
559 to.pathname = toSegments.join("/");
560 }
561 from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
562 }
563 let path = resolvePath(to, from);
564 let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
565 let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
566 if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
567 path.pathname += "/";
568 }
569 return path;
570}
571var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
572var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
573var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
574var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
575var DataWithResponseInit = class {
576 constructor(data2, init) {
577 this.type = "DataWithResponseInit";
578 this.data = data2;
579 this.init = init || null;
580 }
581};
582function data(data2, init) {
583 return new DataWithResponseInit(
584 data2,
585 typeof init === "number" ? { status: init } : init
586 );
587}
588var redirect = (url, init = 302) => {
589 let responseInit = init;
590 if (typeof responseInit === "number") {
591 responseInit = { status: responseInit };
592 } else if (typeof responseInit.status === "undefined") {
593 responseInit.status = 302;
594 }
595 let headers = new Headers(responseInit.headers);
596 headers.set("Location", url);
597 return new Response(null, { ...responseInit, headers });
598};
599var redirectDocument = (url, init) => {
600 let response = redirect(url, init);
601 response.headers.set("X-Remix-Reload-Document", "true");
602 return response;
603};
604var replace = (url, init) => {
605 let response = redirect(url, init);
606 response.headers.set("X-Remix-Replace", "true");
607 return response;
608};
609var ErrorResponseImpl = class {
610 constructor(status, statusText, data2, internal = false) {
611 this.status = status;
612 this.statusText = statusText || "";
613 this.internal = internal;
614 if (data2 instanceof Error) {
615 this.data = data2.toString();
616 this.error = data2;
617 } else {
618 this.data = data2;
619 }
620 }
621};
622function isRouteErrorResponse(error) {
623 return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
624}
625
626// lib/router/router.ts
627var validMutationMethodsArr = [
628 "POST",
629 "PUT",
630 "PATCH",
631 "DELETE"
632];
633var validMutationMethods = new Set(
634 validMutationMethodsArr
635);
636var validRequestMethodsArr = [
637 "GET",
638 ...validMutationMethodsArr
639];
640var validRequestMethods = new Set(validRequestMethodsArr);
641var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
642var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
643var isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
644var defaultMapRouteProperties = (route) => ({
645 hasErrorBoundary: Boolean(route.hasErrorBoundary)
646});
647var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
648function createStaticHandler(routes, opts) {
649 invariant(
650 routes.length > 0,
651 "You must provide a non-empty routes array to createStaticHandler"
652 );
653 let manifest = {};
654 let basename = (opts ? opts.basename : null) || "/";
655 let mapRouteProperties = opts?.mapRouteProperties || defaultMapRouteProperties;
656 let dataRoutes = convertRoutesToDataRoutes(
657 routes,
658 mapRouteProperties,
659 void 0,
660 manifest
661 );
662 async function query(request, {
663 requestContext,
664 filterMatchesToLoad,
665 skipLoaderErrorBubbling,
666 skipRevalidation,
667 dataStrategy,
668 unstable_stream: stream,
669 unstable_respond: respond
670 } = {}) {
671 let url = new URL(request.url);
672 let method = request.method;
673 let location = createLocation("", createPath(url), null, "default");
674 let matches = matchRoutes(dataRoutes, location, basename);
675 requestContext = requestContext != null ? requestContext : new unstable_RouterContextProvider();
676 let respondOrStreamStaticContext = (ctx) => {
677 return stream ? stream(
678 requestContext,
679 () => Promise.resolve(ctx)
680 ) : respond ? respond(ctx) : ctx;
681 };
682 if (!isValidMethod(method) && method !== "HEAD") {
683 let error = getInternalRouterError(405, { method });
684 let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
685 let staticContext = {
686 basename,
687 location,
688 matches: methodNotAllowedMatches,
689 loaderData: {},
690 actionData: null,
691 errors: {
692 [route.id]: error
693 },
694 statusCode: error.status,
695 loaderHeaders: {},
696 actionHeaders: {}
697 };
698 return respondOrStreamStaticContext(staticContext);
699 } else if (!matches) {
700 let error = getInternalRouterError(404, { pathname: location.pathname });
701 let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
702 let staticContext = {
703 basename,
704 location,
705 matches: notFoundMatches,
706 loaderData: {},
707 actionData: null,
708 errors: {
709 [route.id]: error
710 },
711 statusCode: error.status,
712 loaderHeaders: {},
713 actionHeaders: {}
714 };
715 return respondOrStreamStaticContext(staticContext);
716 }
717 if (stream || respond && matches.some(
718 (m) => m.route.unstable_middleware || typeof m.route.lazy === "object" && m.route.lazy.unstable_middleware
719 )) {
720 invariant(
721 requestContext instanceof unstable_RouterContextProvider,
722 "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `unstable_RouterContextProvider`"
723 );
724 try {
725 await loadLazyMiddlewareForMatches(
726 matches,
727 manifest,
728 mapRouteProperties
729 );
730 let renderedStaticContext;
731 let response = await runMiddlewarePipeline(
732 {
733 request,
734 matches,
735 params: matches[0].params,
736 // If we're calling middleware then it must be enabled so we can cast
737 // this to the proper type knowing it's not an `AppLoadContext`
738 context: requestContext
739 },
740 true,
741 async () => {
742 if (stream) {
743 let res2 = await stream(
744 requestContext,
745 async (revalidationRequest) => {
746 let result3 = await queryImpl(
747 revalidationRequest,
748 location,
749 matches,
750 requestContext,
751 dataStrategy || null,
752 skipLoaderErrorBubbling === true,
753 null,
754 filterMatchesToLoad || null,
755 skipRevalidation === true
756 );
757 return isResponse(result3) ? result3 : { location, basename, ...result3 };
758 }
759 );
760 return res2;
761 }
762 invariant(respond, "Expected respond to be defined");
763 let result2 = await queryImpl(
764 request,
765 location,
766 matches,
767 requestContext,
768 dataStrategy || null,
769 skipLoaderErrorBubbling === true,
770 null,
771 filterMatchesToLoad || null,
772 skipRevalidation === true
773 );
774 if (isResponse(result2)) {
775 return result2;
776 }
777 renderedStaticContext = { location, basename, ...result2 };
778 let res = await respond(renderedStaticContext);
779 return res;
780 },
781 async (error, routeId) => {
782 if (isResponse(error)) {
783 return error;
784 }
785 if (renderedStaticContext) {
786 if (routeId in renderedStaticContext.loaderData) {
787 renderedStaticContext.loaderData[routeId] = void 0;
788 }
789 let staticContext = getStaticContextFromError(
790 dataRoutes,
791 renderedStaticContext,
792 error,
793 skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id
794 );
795 return respondOrStreamStaticContext(staticContext);
796 } else {
797 let boundaryRouteId = skipLoaderErrorBubbling ? routeId : findNearestBoundary(
798 matches,
799 matches.find(
800 (m) => m.route.id === routeId || m.route.loader
801 )?.route.id || routeId
802 ).route.id;
803 let staticContext = {
804 matches,
805 location,
806 basename,
807 loaderData: {},
808 actionData: null,
809 errors: {
810 [boundaryRouteId]: error
811 },
812 statusCode: isRouteErrorResponse(error) ? error.status : 500,
813 actionHeaders: {},
814 loaderHeaders: {}
815 };
816 return respondOrStreamStaticContext(staticContext);
817 }
818 }
819 );
820 invariant(isResponse(response), "Expected a response in query()");
821 return response;
822 } catch (e) {
823 if (isResponse(e)) {
824 return e;
825 }
826 throw e;
827 }
828 }
829 let result = await queryImpl(
830 request,
831 location,
832 matches,
833 requestContext,
834 dataStrategy || null,
835 skipLoaderErrorBubbling === true,
836 null,
837 filterMatchesToLoad || null,
838 skipRevalidation === true
839 );
840 if (isResponse(result)) {
841 return result;
842 }
843 return { location, basename, ...result };
844 }
845 async function queryRoute(request, {
846 routeId,
847 requestContext,
848 dataStrategy,
849 unstable_respond: respond
850 } = {}) {
851 let url = new URL(request.url);
852 let method = request.method;
853 let location = createLocation("", createPath(url), null, "default");
854 let matches = matchRoutes(dataRoutes, location, basename);
855 requestContext = requestContext != null ? requestContext : new unstable_RouterContextProvider();
856 if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
857 throw getInternalRouterError(405, { method });
858 } else if (!matches) {
859 throw getInternalRouterError(404, { pathname: location.pathname });
860 }
861 let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
862 if (routeId && !match) {
863 throw getInternalRouterError(403, {
864 pathname: location.pathname,
865 routeId
866 });
867 } else if (!match) {
868 throw getInternalRouterError(404, { pathname: location.pathname });
869 }
870 if (respond && matches.some(
871 (m) => m.route.unstable_middleware || typeof m.route.lazy === "object" && m.route.lazy.unstable_middleware
872 )) {
873 invariant(
874 requestContext instanceof unstable_RouterContextProvider,
875 "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `unstable_RouterContextProvider`"
876 );
877 await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties);
878 let response = await runMiddlewarePipeline(
879 {
880 request,
881 matches,
882 params: matches[0].params,
883 // If we're calling middleware then it must be enabled so we can cast
884 // this to the proper type knowing it's not an `AppLoadContext`
885 context: requestContext
886 },
887 true,
888 async () => {
889 let result2 = await queryImpl(
890 request,
891 location,
892 matches,
893 requestContext,
894 dataStrategy || null,
895 false,
896 match,
897 null,
898 false
899 );
900 if (isResponse(result2)) {
901 return respond(result2);
902 }
903 let error2 = result2.errors ? Object.values(result2.errors)[0] : void 0;
904 if (error2 !== void 0) {
905 throw error2;
906 }
907 let value = result2.actionData ? Object.values(result2.actionData)[0] : Object.values(result2.loaderData)[0];
908 return typeof value === "string" ? new Response(value) : Response.json(value);
909 },
910 (error2) => {
911 if (isResponse(error2)) {
912 return respond(error2);
913 }
914 return new Response(String(error2), {
915 status: 500,
916 statusText: "Unexpected Server Error"
917 });
918 }
919 );
920 return response;
921 }
922 let result = await queryImpl(
923 request,
924 location,
925 matches,
926 requestContext,
927 dataStrategy || null,
928 false,
929 match,
930 null,
931 false
932 );
933 if (isResponse(result)) {
934 return result;
935 }
936 let error = result.errors ? Object.values(result.errors)[0] : void 0;
937 if (error !== void 0) {
938 throw error;
939 }
940 if (result.actionData) {
941 return Object.values(result.actionData)[0];
942 }
943 if (result.loaderData) {
944 return Object.values(result.loaderData)[0];
945 }
946 return void 0;
947 }
948 async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
949 invariant(
950 request.signal,
951 "query()/queryRoute() requests must contain an AbortController signal"
952 );
953 try {
954 if (isMutationMethod(request.method)) {
955 let result2 = await submit(
956 request,
957 matches,
958 routeMatch || getTargetMatch(matches, location),
959 requestContext,
960 dataStrategy,
961 skipLoaderErrorBubbling,
962 routeMatch != null,
963 filterMatchesToLoad,
964 skipRevalidation
965 );
966 return result2;
967 }
968 let result = await loadRouteData(
969 request,
970 matches,
971 requestContext,
972 dataStrategy,
973 skipLoaderErrorBubbling,
974 routeMatch,
975 filterMatchesToLoad
976 );
977 return isResponse(result) ? result : {
978 ...result,
979 actionData: null,
980 actionHeaders: {}
981 };
982 } catch (e) {
983 if (isDataStrategyResult(e) && isResponse(e.result)) {
984 if (e.type === "error" /* error */) {
985 throw e.result;
986 }
987 return e.result;
988 }
989 if (isRedirectResponse(e)) {
990 return e;
991 }
992 throw e;
993 }
994 }
995 async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
996 let result;
997 if (!actionMatch.route.action && !actionMatch.route.lazy) {
998 let error = getInternalRouterError(405, {
999 method: request.method,
1000 pathname: new URL(request.url).pathname,
1001 routeId: actionMatch.route.id
1002 });
1003 if (isRouteRequest) {
1004 throw error;
1005 }
1006 result = {
1007 type: "error" /* error */,
1008 error
1009 };
1010 } else {
1011 let dsMatches = getTargetedDataStrategyMatches(
1012 mapRouteProperties,
1013 manifest,
1014 request,
1015 matches,
1016 actionMatch,
1017 [],
1018 requestContext
1019 );
1020 let results = await callDataStrategy(
1021 request,
1022 dsMatches,
1023 isRouteRequest,
1024 requestContext,
1025 dataStrategy
1026 );
1027 result = results[actionMatch.route.id];
1028 if (request.signal.aborted) {
1029 throwStaticHandlerAbortedError(request, isRouteRequest);
1030 }
1031 }
1032 if (isRedirectResult(result)) {
1033 throw new Response(null, {
1034 status: result.response.status,
1035 headers: {
1036 Location: result.response.headers.get("Location")
1037 }
1038 });
1039 }
1040 if (isRouteRequest) {
1041 if (isErrorResult(result)) {
1042 throw result.error;
1043 }
1044 return {
1045 matches: [actionMatch],
1046 loaderData: {},
1047 actionData: { [actionMatch.route.id]: result.data },
1048 errors: null,
1049 // Note: statusCode + headers are unused here since queryRoute will
1050 // return the raw Response or value
1051 statusCode: 200,
1052 loaderHeaders: {},
1053 actionHeaders: {}
1054 };
1055 }
1056 if (skipRevalidation) {
1057 if (isErrorResult(result)) {
1058 let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
1059 return {
1060 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1061 actionData: null,
1062 actionHeaders: {
1063 ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
1064 },
1065 matches,
1066 loaderData: {},
1067 errors: {
1068 [boundaryMatch.route.id]: result.error
1069 },
1070 loaderHeaders: {}
1071 };
1072 } else {
1073 return {
1074 actionData: {
1075 [actionMatch.route.id]: result.data
1076 },
1077 actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
1078 matches,
1079 loaderData: {},
1080 errors: null,
1081 statusCode: result.statusCode || 200,
1082 loaderHeaders: {}
1083 };
1084 }
1085 }
1086 let loaderRequest = new Request(request.url, {
1087 headers: request.headers,
1088 redirect: request.redirect,
1089 signal: request.signal
1090 });
1091 if (isErrorResult(result)) {
1092 let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
1093 let handlerContext2 = await loadRouteData(
1094 loaderRequest,
1095 matches,
1096 requestContext,
1097 dataStrategy,
1098 skipLoaderErrorBubbling,
1099 null,
1100 filterMatchesToLoad,
1101 [boundaryMatch.route.id, result]
1102 );
1103 return {
1104 ...handlerContext2,
1105 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1106 actionData: null,
1107 actionHeaders: {
1108 ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
1109 }
1110 };
1111 }
1112 let handlerContext = await loadRouteData(
1113 loaderRequest,
1114 matches,
1115 requestContext,
1116 dataStrategy,
1117 skipLoaderErrorBubbling,
1118 null,
1119 filterMatchesToLoad
1120 );
1121 return {
1122 ...handlerContext,
1123 actionData: {
1124 [actionMatch.route.id]: result.data
1125 },
1126 // action status codes take precedence over loader status codes
1127 ...result.statusCode ? { statusCode: result.statusCode } : {},
1128 actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
1129 };
1130 }
1131 async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
1132 let isRouteRequest = routeMatch != null;
1133 if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) {
1134 throw getInternalRouterError(400, {
1135 method: request.method,
1136 pathname: new URL(request.url).pathname,
1137 routeId: routeMatch?.route.id
1138 });
1139 }
1140 let dsMatches;
1141 if (routeMatch) {
1142 dsMatches = getTargetedDataStrategyMatches(
1143 mapRouteProperties,
1144 manifest,
1145 request,
1146 matches,
1147 routeMatch,
1148 [],
1149 requestContext
1150 );
1151 } else {
1152 let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? (
1153 // Up to but not including the boundary
1154 matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1
1155 ) : void 0;
1156 dsMatches = matches.map((match, index) => {
1157 if (maxIdx != null && index > maxIdx) {
1158 return getDataStrategyMatch(
1159 mapRouteProperties,
1160 manifest,
1161 request,
1162 match,
1163 [],
1164 requestContext,
1165 false
1166 );
1167 }
1168 return getDataStrategyMatch(
1169 mapRouteProperties,
1170 manifest,
1171 request,
1172 match,
1173 [],
1174 requestContext,
1175 (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match))
1176 );
1177 });
1178 }
1179 if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) {
1180 return {
1181 matches,
1182 loaderData: {},
1183 errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
1184 [pendingActionResult[0]]: pendingActionResult[1].error
1185 } : null,
1186 statusCode: 200,
1187 loaderHeaders: {}
1188 };
1189 }
1190 let results = await callDataStrategy(
1191 request,
1192 dsMatches,
1193 isRouteRequest,
1194 requestContext,
1195 dataStrategy
1196 );
1197 if (request.signal.aborted) {
1198 throwStaticHandlerAbortedError(request, isRouteRequest);
1199 }
1200 let handlerContext = processRouteLoaderData(
1201 matches,
1202 results,
1203 pendingActionResult,
1204 true,
1205 skipLoaderErrorBubbling
1206 );
1207 return {
1208 ...handlerContext,
1209 matches
1210 };
1211 }
1212 async function callDataStrategy(request, matches, isRouteRequest, requestContext, dataStrategy) {
1213 let results = await callDataStrategyImpl(
1214 dataStrategy || defaultDataStrategy,
1215 request,
1216 matches,
1217 null,
1218 requestContext);
1219 let dataResults = {};
1220 await Promise.all(
1221 matches.map(async (match) => {
1222 if (!(match.route.id in results)) {
1223 return;
1224 }
1225 let result = results[match.route.id];
1226 if (isRedirectDataStrategyResult(result)) {
1227 let response = result.result;
1228 throw normalizeRelativeRoutingRedirectResponse(
1229 response,
1230 request,
1231 match.route.id,
1232 matches,
1233 basename
1234 );
1235 }
1236 if (isResponse(result.result) && isRouteRequest) {
1237 throw result;
1238 }
1239 dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
1240 })
1241 );
1242 return dataResults;
1243 }
1244 return {
1245 dataRoutes,
1246 query,
1247 queryRoute
1248 };
1249}
1250function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
1251 let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
1252 return {
1253 ...handlerContext,
1254 statusCode: isRouteErrorResponse(error) ? error.status : 500,
1255 errors: {
1256 [errorBoundaryId]: error
1257 }
1258 };
1259}
1260function throwStaticHandlerAbortedError(request, isRouteRequest) {
1261 if (request.signal.reason !== void 0) {
1262 throw request.signal.reason;
1263 }
1264 let method = isRouteRequest ? "queryRoute" : "query";
1265 throw new Error(
1266 `${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
1267 );
1268}
1269function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
1270 let contextualMatches;
1271 let activeRouteMatch;
1272 {
1273 contextualMatches = matches;
1274 activeRouteMatch = matches[matches.length - 1];
1275 }
1276 let path = resolveTo(
1277 to ? to : ".",
1278 getResolveToMatches(contextualMatches),
1279 stripBasename(location.pathname, basename) || location.pathname,
1280 relative === "path"
1281 );
1282 if (to == null) {
1283 path.search = location.search;
1284 path.hash = location.hash;
1285 }
1286 if ((to == null || to === "" || to === ".") && activeRouteMatch) {
1287 let nakedIndex = hasNakedIndexQuery(path.search);
1288 if (activeRouteMatch.route.index && !nakedIndex) {
1289 path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
1290 } else if (!activeRouteMatch.route.index && nakedIndex) {
1291 let params = new URLSearchParams(path.search);
1292 let indexValues = params.getAll("index");
1293 params.delete("index");
1294 indexValues.filter((v) => v).forEach((v) => params.append("index", v));
1295 let qs = params.toString();
1296 path.search = qs ? `?${qs}` : "";
1297 }
1298 }
1299 if (basename !== "/") {
1300 path.pathname = prependBasename({ basename, pathname: path.pathname });
1301 }
1302 return createPath(path);
1303}
1304function shouldRevalidateLoader(loaderMatch, arg) {
1305 if (loaderMatch.route.shouldRevalidate) {
1306 let routeChoice = loaderMatch.route.shouldRevalidate(arg);
1307 if (typeof routeChoice === "boolean") {
1308 return routeChoice;
1309 }
1310 }
1311 return arg.defaultShouldRevalidate;
1312}
1313var lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
1314var loadLazyRouteProperty = ({
1315 key,
1316 route,
1317 manifest,
1318 mapRouteProperties
1319}) => {
1320 let routeToUpdate = manifest[route.id];
1321 invariant(routeToUpdate, "No route found in manifest");
1322 if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") {
1323 return;
1324 }
1325 let lazyFn = routeToUpdate.lazy[key];
1326 if (!lazyFn) {
1327 return;
1328 }
1329 let cache = lazyRoutePropertyCache.get(routeToUpdate);
1330 if (!cache) {
1331 cache = {};
1332 lazyRoutePropertyCache.set(routeToUpdate, cache);
1333 }
1334 let cachedPromise = cache[key];
1335 if (cachedPromise) {
1336 return cachedPromise;
1337 }
1338 let propertyPromise = (async () => {
1339 let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
1340 let staticRouteValue = routeToUpdate[key];
1341 let isStaticallyDefined = staticRouteValue !== void 0 && key !== "hasErrorBoundary";
1342 if (isUnsupported) {
1343 warning(
1344 !isUnsupported,
1345 "Route property " + key + " is not a supported lazy route property. This property will be ignored."
1346 );
1347 cache[key] = Promise.resolve();
1348 } else if (isStaticallyDefined) {
1349 warning(
1350 false,
1351 `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`
1352 );
1353 } else {
1354 let value = await lazyFn();
1355 if (value != null) {
1356 Object.assign(routeToUpdate, { [key]: value });
1357 Object.assign(routeToUpdate, mapRouteProperties(routeToUpdate));
1358 }
1359 }
1360 if (typeof routeToUpdate.lazy === "object") {
1361 routeToUpdate.lazy[key] = void 0;
1362 if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) {
1363 routeToUpdate.lazy = void 0;
1364 }
1365 }
1366 })();
1367 cache[key] = propertyPromise;
1368 return propertyPromise;
1369};
1370var lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
1371function loadLazyRoute(route, type, manifest, mapRouteProperties, lazyRoutePropertiesToSkip) {
1372 let routeToUpdate = manifest[route.id];
1373 invariant(routeToUpdate, "No route found in manifest");
1374 if (!route.lazy) {
1375 return {
1376 lazyRoutePromise: void 0,
1377 lazyHandlerPromise: void 0
1378 };
1379 }
1380 if (typeof route.lazy === "function") {
1381 let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
1382 if (cachedPromise) {
1383 return {
1384 lazyRoutePromise: cachedPromise,
1385 lazyHandlerPromise: cachedPromise
1386 };
1387 }
1388 let lazyRoutePromise2 = (async () => {
1389 invariant(
1390 typeof route.lazy === "function",
1391 "No lazy route function found"
1392 );
1393 let lazyRoute = await route.lazy();
1394 let routeUpdates = {};
1395 for (let lazyRouteProperty in lazyRoute) {
1396 let lazyValue = lazyRoute[lazyRouteProperty];
1397 if (lazyValue === void 0) {
1398 continue;
1399 }
1400 let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
1401 let staticRouteValue = routeToUpdate[lazyRouteProperty];
1402 let isStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
1403 // on the route updates
1404 lazyRouteProperty !== "hasErrorBoundary";
1405 if (isUnsupported) {
1406 warning(
1407 !isUnsupported,
1408 "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored."
1409 );
1410 } else if (isStaticallyDefined) {
1411 warning(
1412 !isStaticallyDefined,
1413 `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.`
1414 );
1415 } else {
1416 routeUpdates[lazyRouteProperty] = lazyValue;
1417 }
1418 }
1419 Object.assign(routeToUpdate, routeUpdates);
1420 Object.assign(routeToUpdate, {
1421 // To keep things framework agnostic, we use the provided `mapRouteProperties`
1422 // function to set the framework-aware properties (`element`/`hasErrorBoundary`)
1423 // since the logic will differ between frameworks.
1424 ...mapRouteProperties(routeToUpdate),
1425 lazy: void 0
1426 });
1427 })();
1428 lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise2);
1429 lazyRoutePromise2.catch(() => {
1430 });
1431 return {
1432 lazyRoutePromise: lazyRoutePromise2,
1433 lazyHandlerPromise: lazyRoutePromise2
1434 };
1435 }
1436 let lazyKeys = Object.keys(route.lazy);
1437 let lazyPropertyPromises = [];
1438 let lazyHandlerPromise = void 0;
1439 for (let key of lazyKeys) {
1440 if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) {
1441 continue;
1442 }
1443 let promise = loadLazyRouteProperty({
1444 key,
1445 route,
1446 manifest,
1447 mapRouteProperties
1448 });
1449 if (promise) {
1450 lazyPropertyPromises.push(promise);
1451 if (key === type) {
1452 lazyHandlerPromise = promise;
1453 }
1454 }
1455 }
1456 let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {
1457 }) : void 0;
1458 lazyRoutePromise?.catch(() => {
1459 });
1460 lazyHandlerPromise?.catch(() => {
1461 });
1462 return {
1463 lazyRoutePromise,
1464 lazyHandlerPromise
1465 };
1466}
1467function isNonNullable(value) {
1468 return value !== void 0;
1469}
1470function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties) {
1471 let promises = matches.map(({ route }) => {
1472 if (typeof route.lazy !== "object" || !route.lazy.unstable_middleware) {
1473 return void 0;
1474 }
1475 return loadLazyRouteProperty({
1476 key: "unstable_middleware",
1477 route,
1478 manifest,
1479 mapRouteProperties
1480 });
1481 }).filter(isNonNullable);
1482 return promises.length > 0 ? Promise.all(promises) : void 0;
1483}
1484async function defaultDataStrategy(args) {
1485 let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
1486 let keyedResults = {};
1487 let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
1488 results.forEach((result, i) => {
1489 keyedResults[matchesToLoad[i].route.id] = result;
1490 });
1491 return keyedResults;
1492}
1493async function runMiddlewarePipeline(args, propagateResult, handler, errorHandler) {
1494 let { matches, request, params, context } = args;
1495 let middlewareState = {
1496 handlerResult: void 0
1497 };
1498 try {
1499 let tuples = matches.flatMap(
1500 (m) => m.route.unstable_middleware ? m.route.unstable_middleware.map((fn) => [m.route.id, fn]) : []
1501 );
1502 let result = await callRouteMiddleware(
1503 { request, params, context },
1504 tuples,
1505 propagateResult,
1506 middlewareState,
1507 handler
1508 );
1509 return propagateResult ? result : middlewareState.handlerResult;
1510 } catch (e) {
1511 if (!middlewareState.middlewareError) {
1512 throw e;
1513 }
1514 let result = await errorHandler(
1515 middlewareState.middlewareError.error,
1516 middlewareState.middlewareError.routeId
1517 );
1518 {
1519 return result;
1520 }
1521 }
1522}
1523async function callRouteMiddleware(args, middlewares, propagateResult, middlewareState, handler, idx = 0) {
1524 let { request } = args;
1525 if (request.signal.aborted) {
1526 if (request.signal.reason) {
1527 throw request.signal.reason;
1528 }
1529 throw new Error(
1530 `Request aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
1531 );
1532 }
1533 let tuple = middlewares[idx];
1534 if (!tuple) {
1535 middlewareState.handlerResult = await handler();
1536 return middlewareState.handlerResult;
1537 }
1538 let [routeId, middleware] = tuple;
1539 let nextCalled = false;
1540 let nextResult = void 0;
1541 let next = async () => {
1542 if (nextCalled) {
1543 throw new Error("You may only call `next()` once per middleware");
1544 }
1545 nextCalled = true;
1546 let result = await callRouteMiddleware(
1547 args,
1548 middlewares,
1549 propagateResult,
1550 middlewareState,
1551 handler,
1552 idx + 1
1553 );
1554 {
1555 nextResult = result;
1556 return nextResult;
1557 }
1558 };
1559 try {
1560 let result = await middleware(
1561 {
1562 request: args.request,
1563 params: args.params,
1564 context: args.context
1565 },
1566 next
1567 );
1568 if (nextCalled) {
1569 if (result === void 0) {
1570 return nextResult;
1571 } else {
1572 return result;
1573 }
1574 } else {
1575 return next();
1576 }
1577 } catch (error) {
1578 if (!middlewareState.middlewareError) {
1579 middlewareState.middlewareError = { routeId, error };
1580 } else if (middlewareState.middlewareError.error !== error) {
1581 middlewareState.middlewareError = { routeId, error };
1582 }
1583 throw error;
1584 }
1585}
1586function getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip) {
1587 let lazyMiddlewarePromise = loadLazyRouteProperty({
1588 key: "unstable_middleware",
1589 route: match.route,
1590 manifest,
1591 mapRouteProperties
1592 });
1593 let lazyRoutePromises = loadLazyRoute(
1594 match.route,
1595 isMutationMethod(request.method) ? "action" : "loader",
1596 manifest,
1597 mapRouteProperties,
1598 lazyRoutePropertiesToSkip
1599 );
1600 return {
1601 middleware: lazyMiddlewarePromise,
1602 route: lazyRoutePromises.lazyRoutePromise,
1603 handler: lazyRoutePromises.lazyHandlerPromise
1604 };
1605}
1606function getDataStrategyMatch(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, unstable_shouldRevalidateArgs = null) {
1607 let isUsingNewApi = false;
1608 let _lazyPromises = getDataStrategyMatchLazyPromises(
1609 mapRouteProperties,
1610 manifest,
1611 request,
1612 match,
1613 lazyRoutePropertiesToSkip
1614 );
1615 return {
1616 ...match,
1617 _lazyPromises,
1618 shouldLoad,
1619 unstable_shouldRevalidateArgs,
1620 unstable_shouldCallHandler(defaultShouldRevalidate) {
1621 isUsingNewApi = true;
1622 if (!unstable_shouldRevalidateArgs) {
1623 return shouldLoad;
1624 }
1625 if (typeof defaultShouldRevalidate === "boolean") {
1626 return shouldRevalidateLoader(match, {
1627 ...unstable_shouldRevalidateArgs,
1628 defaultShouldRevalidate
1629 });
1630 }
1631 return shouldRevalidateLoader(match, unstable_shouldRevalidateArgs);
1632 },
1633 resolve(handlerOverride) {
1634 if (isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (match.route.lazy || match.route.loader)) {
1635 return callLoaderOrAction({
1636 request,
1637 match,
1638 lazyHandlerPromise: _lazyPromises?.handler,
1639 lazyRoutePromise: _lazyPromises?.route,
1640 handlerOverride,
1641 scopedContext
1642 });
1643 }
1644 return Promise.resolve({ type: "data" /* data */, result: void 0 });
1645 }
1646 };
1647}
1648function getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
1649 return matches.map((match) => {
1650 if (match.route.id !== targetMatch.route.id) {
1651 return {
1652 ...match,
1653 shouldLoad: false,
1654 unstable_shouldRevalidateArgs: shouldRevalidateArgs,
1655 unstable_shouldCallHandler: () => false,
1656 _lazyPromises: getDataStrategyMatchLazyPromises(
1657 mapRouteProperties,
1658 manifest,
1659 request,
1660 match,
1661 lazyRoutePropertiesToSkip
1662 ),
1663 resolve: () => Promise.resolve({ type: "data", result: void 0 })
1664 };
1665 }
1666 return getDataStrategyMatch(
1667 mapRouteProperties,
1668 manifest,
1669 request,
1670 match,
1671 lazyRoutePropertiesToSkip,
1672 scopedContext,
1673 true,
1674 shouldRevalidateArgs
1675 );
1676 });
1677}
1678async function callDataStrategyImpl(dataStrategyImpl, request, matches, fetcherKey, scopedContext, isStaticHandler) {
1679 if (matches.some((m) => m._lazyPromises?.middleware)) {
1680 await Promise.all(matches.map((m) => m._lazyPromises?.middleware));
1681 }
1682 let dataStrategyArgs = {
1683 request,
1684 params: matches[0].params,
1685 context: scopedContext,
1686 matches
1687 };
1688 let unstable_runClientMiddleware = () => {
1689 throw new Error(
1690 "You cannot call `unstable_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`"
1691 );
1692 } ;
1693 let results = await dataStrategyImpl({
1694 ...dataStrategyArgs,
1695 fetcherKey,
1696 unstable_runClientMiddleware
1697 });
1698 try {
1699 await Promise.all(
1700 matches.flatMap((m) => [
1701 m._lazyPromises?.handler,
1702 m._lazyPromises?.route
1703 ])
1704 );
1705 } catch (e) {
1706 }
1707 return results;
1708}
1709async function callLoaderOrAction({
1710 request,
1711 match,
1712 lazyHandlerPromise,
1713 lazyRoutePromise,
1714 handlerOverride,
1715 scopedContext
1716}) {
1717 let result;
1718 let onReject;
1719 let isAction = isMutationMethod(request.method);
1720 let type = isAction ? "action" : "loader";
1721 let runHandler = (handler) => {
1722 let reject;
1723 let abortPromise = new Promise((_, r) => reject = r);
1724 onReject = () => reject();
1725 request.signal.addEventListener("abort", onReject);
1726 let actualHandler = (ctx) => {
1727 if (typeof handler !== "function") {
1728 return Promise.reject(
1729 new Error(
1730 `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`
1731 )
1732 );
1733 }
1734 return handler(
1735 {
1736 request,
1737 params: match.params,
1738 context: scopedContext
1739 },
1740 ...ctx !== void 0 ? [ctx] : []
1741 );
1742 };
1743 let handlerPromise = (async () => {
1744 try {
1745 let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
1746 return { type: "data", result: val };
1747 } catch (e) {
1748 return { type: "error", result: e };
1749 }
1750 })();
1751 return Promise.race([handlerPromise, abortPromise]);
1752 };
1753 try {
1754 let handler = isAction ? match.route.action : match.route.loader;
1755 if (lazyHandlerPromise || lazyRoutePromise) {
1756 if (handler) {
1757 let handlerError;
1758 let [value] = await Promise.all([
1759 // If the handler throws, don't let it immediately bubble out,
1760 // since we need to let the lazy() execution finish so we know if this
1761 // route has a boundary that can handle the error
1762 runHandler(handler).catch((e) => {
1763 handlerError = e;
1764 }),
1765 // Ensure all lazy route promises are resolved before continuing
1766 lazyHandlerPromise,
1767 lazyRoutePromise
1768 ]);
1769 if (handlerError !== void 0) {
1770 throw handlerError;
1771 }
1772 result = value;
1773 } else {
1774 await lazyHandlerPromise;
1775 let handler2 = isAction ? match.route.action : match.route.loader;
1776 if (handler2) {
1777 [result] = await Promise.all([runHandler(handler2), lazyRoutePromise]);
1778 } else if (type === "action") {
1779 let url = new URL(request.url);
1780 let pathname = url.pathname + url.search;
1781 throw getInternalRouterError(405, {
1782 method: request.method,
1783 pathname,
1784 routeId: match.route.id
1785 });
1786 } else {
1787 return { type: "data" /* data */, result: void 0 };
1788 }
1789 }
1790 } else if (!handler) {
1791 let url = new URL(request.url);
1792 let pathname = url.pathname + url.search;
1793 throw getInternalRouterError(404, {
1794 pathname
1795 });
1796 } else {
1797 result = await runHandler(handler);
1798 }
1799 } catch (e) {
1800 return { type: "error" /* error */, result: e };
1801 } finally {
1802 if (onReject) {
1803 request.signal.removeEventListener("abort", onReject);
1804 }
1805 }
1806 return result;
1807}
1808async function convertDataStrategyResultToDataResult(dataStrategyResult) {
1809 let { result, type } = dataStrategyResult;
1810 if (isResponse(result)) {
1811 let data2;
1812 try {
1813 let contentType = result.headers.get("Content-Type");
1814 if (contentType && /\bapplication\/json\b/.test(contentType)) {
1815 if (result.body == null) {
1816 data2 = null;
1817 } else {
1818 data2 = await result.json();
1819 }
1820 } else {
1821 data2 = await result.text();
1822 }
1823 } catch (e) {
1824 return { type: "error" /* error */, error: e };
1825 }
1826 if (type === "error" /* error */) {
1827 return {
1828 type: "error" /* error */,
1829 error: new ErrorResponseImpl(result.status, result.statusText, data2),
1830 statusCode: result.status,
1831 headers: result.headers
1832 };
1833 }
1834 return {
1835 type: "data" /* data */,
1836 data: data2,
1837 statusCode: result.status,
1838 headers: result.headers
1839 };
1840 }
1841 if (type === "error" /* error */) {
1842 if (isDataWithResponseInit(result)) {
1843 if (result.data instanceof Error) {
1844 return {
1845 type: "error" /* error */,
1846 error: result.data,
1847 statusCode: result.init?.status,
1848 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
1849 };
1850 }
1851 return {
1852 type: "error" /* error */,
1853 error: new ErrorResponseImpl(
1854 result.init?.status || 500,
1855 void 0,
1856 result.data
1857 ),
1858 statusCode: isRouteErrorResponse(result) ? result.status : void 0,
1859 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
1860 };
1861 }
1862 return {
1863 type: "error" /* error */,
1864 error: result,
1865 statusCode: isRouteErrorResponse(result) ? result.status : void 0
1866 };
1867 }
1868 if (isDataWithResponseInit(result)) {
1869 return {
1870 type: "data" /* data */,
1871 data: result.data,
1872 statusCode: result.init?.status,
1873 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
1874 };
1875 }
1876 return { type: "data" /* data */, data: result };
1877}
1878function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
1879 let location = response.headers.get("Location");
1880 invariant(
1881 location,
1882 "Redirects returned/thrown from loaders/actions must have a Location header"
1883 );
1884 if (!isAbsoluteUrl(location)) {
1885 let trimmedMatches = matches.slice(
1886 0,
1887 matches.findIndex((m) => m.route.id === routeId) + 1
1888 );
1889 location = normalizeTo(
1890 new URL(request.url),
1891 trimmedMatches,
1892 basename,
1893 location
1894 );
1895 response.headers.set("Location", location);
1896 }
1897 return response;
1898}
1899function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
1900 let loaderData = {};
1901 let errors = null;
1902 let statusCode;
1903 let foundError = false;
1904 let loaderHeaders = {};
1905 let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
1906 matches.forEach((match) => {
1907 if (!(match.route.id in results)) {
1908 return;
1909 }
1910 let id = match.route.id;
1911 let result = results[id];
1912 invariant(
1913 !isRedirectResult(result),
1914 "Cannot handle redirect results in processLoaderData"
1915 );
1916 if (isErrorResult(result)) {
1917 let error = result.error;
1918 if (pendingError !== void 0) {
1919 error = pendingError;
1920 pendingError = void 0;
1921 }
1922 errors = errors || {};
1923 if (skipLoaderErrorBubbling) {
1924 errors[id] = error;
1925 } else {
1926 let boundaryMatch = findNearestBoundary(matches, id);
1927 if (errors[boundaryMatch.route.id] == null) {
1928 errors[boundaryMatch.route.id] = error;
1929 }
1930 }
1931 if (!isStaticHandler) {
1932 loaderData[id] = ResetLoaderDataSymbol;
1933 }
1934 if (!foundError) {
1935 foundError = true;
1936 statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
1937 }
1938 if (result.headers) {
1939 loaderHeaders[id] = result.headers;
1940 }
1941 } else {
1942 loaderData[id] = result.data;
1943 if (result.statusCode && result.statusCode !== 200 && !foundError) {
1944 statusCode = result.statusCode;
1945 }
1946 if (result.headers) {
1947 loaderHeaders[id] = result.headers;
1948 }
1949 }
1950 });
1951 if (pendingError !== void 0 && pendingActionResult) {
1952 errors = { [pendingActionResult[0]]: pendingError };
1953 if (pendingActionResult[2]) {
1954 loaderData[pendingActionResult[2]] = void 0;
1955 }
1956 }
1957 return {
1958 loaderData,
1959 errors,
1960 statusCode: statusCode || 200,
1961 loaderHeaders
1962 };
1963}
1964function findNearestBoundary(matches, routeId) {
1965 let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
1966 return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
1967}
1968function getShortCircuitMatches(routes) {
1969 let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
1970 id: `__shim-error-route__`
1971 };
1972 return {
1973 matches: [
1974 {
1975 params: {},
1976 pathname: "",
1977 pathnameBase: "",
1978 route
1979 }
1980 ],
1981 route
1982 };
1983}
1984function getInternalRouterError(status, {
1985 pathname,
1986 routeId,
1987 method,
1988 type,
1989 message
1990} = {}) {
1991 let statusText = "Unknown Server Error";
1992 let errorMessage = "Unknown @remix-run/router error";
1993 if (status === 400) {
1994 statusText = "Bad Request";
1995 if (method && pathname && routeId) {
1996 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.`;
1997 } else if (type === "invalid-body") {
1998 errorMessage = "Unable to encode submission body";
1999 }
2000 } else if (status === 403) {
2001 statusText = "Forbidden";
2002 errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
2003 } else if (status === 404) {
2004 statusText = "Not Found";
2005 errorMessage = `No route matches URL "${pathname}"`;
2006 } else if (status === 405) {
2007 statusText = "Method Not Allowed";
2008 if (method && pathname && routeId) {
2009 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.`;
2010 } else if (method) {
2011 errorMessage = `Invalid request method "${method.toUpperCase()}"`;
2012 }
2013 }
2014 return new ErrorResponseImpl(
2015 status || 500,
2016 statusText,
2017 new Error(errorMessage),
2018 true
2019 );
2020}
2021function isDataStrategyResult(result) {
2022 return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" /* data */ || result.type === "error" /* error */);
2023}
2024function isRedirectDataStrategyResult(result) {
2025 return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
2026}
2027function isErrorResult(result) {
2028 return result.type === "error" /* error */;
2029}
2030function isRedirectResult(result) {
2031 return (result && result.type) === "redirect" /* redirect */;
2032}
2033function isDataWithResponseInit(value) {
2034 return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
2035}
2036function isResponse(value) {
2037 return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
2038}
2039function isRedirectStatusCode(statusCode) {
2040 return redirectStatusCodes.has(statusCode);
2041}
2042function isRedirectResponse(result) {
2043 return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
2044}
2045function isValidMethod(method) {
2046 return validRequestMethods.has(method.toUpperCase());
2047}
2048function isMutationMethod(method) {
2049 return validMutationMethods.has(method.toUpperCase());
2050}
2051function hasNakedIndexQuery(search) {
2052 return new URLSearchParams(search).getAll("index").some((v) => v === "");
2053}
2054function getTargetMatch(matches, location) {
2055 let search = typeof location === "string" ? parsePath(location).search : location.search;
2056 if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
2057 return matches[matches.length - 1];
2058 }
2059 let pathMatches = getPathContributingMatches(matches);
2060 return pathMatches[pathMatches.length - 1];
2061}
2062
2063// lib/server-runtime/invariant.ts
2064function invariant2(value, message) {
2065 if (value === false || value === null || typeof value === "undefined") {
2066 console.error(
2067 "The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose"
2068 );
2069 throw new Error(message);
2070 }
2071}
2072
2073// lib/server-runtime/headers.ts
2074function getDocumentHeadersImpl(context, getRouteHeadersFn) {
2075 let boundaryIdx = context.errors ? context.matches.findIndex((m) => context.errors[m.route.id]) : -1;
2076 let matches = boundaryIdx >= 0 ? context.matches.slice(0, boundaryIdx + 1) : context.matches;
2077 let errorHeaders;
2078 if (boundaryIdx >= 0) {
2079 let { actionHeaders, actionData, loaderHeaders, loaderData } = context;
2080 context.matches.slice(boundaryIdx).some((match) => {
2081 let id = match.route.id;
2082 if (actionHeaders[id] && (!actionData || !actionData.hasOwnProperty(id))) {
2083 errorHeaders = actionHeaders[id];
2084 } else if (loaderHeaders[id] && !loaderData.hasOwnProperty(id)) {
2085 errorHeaders = loaderHeaders[id];
2086 }
2087 return errorHeaders != null;
2088 });
2089 }
2090 return matches.reduce((parentHeaders, match, idx) => {
2091 let { id } = match.route;
2092 let loaderHeaders = context.loaderHeaders[id] || new Headers();
2093 let actionHeaders = context.actionHeaders[id] || new Headers();
2094 let includeErrorHeaders = errorHeaders != null && idx === matches.length - 1;
2095 let includeErrorCookies = includeErrorHeaders && errorHeaders !== loaderHeaders && errorHeaders !== actionHeaders;
2096 let headersFn = getRouteHeadersFn(match);
2097 if (headersFn == null) {
2098 let headers2 = new Headers(parentHeaders);
2099 if (includeErrorCookies) {
2100 prependCookies(errorHeaders, headers2);
2101 }
2102 prependCookies(actionHeaders, headers2);
2103 prependCookies(loaderHeaders, headers2);
2104 return headers2;
2105 }
2106 let headers = new Headers(
2107 typeof headersFn === "function" ? headersFn({
2108 loaderHeaders,
2109 parentHeaders,
2110 actionHeaders,
2111 errorHeaders: includeErrorHeaders ? errorHeaders : void 0
2112 }) : headersFn
2113 );
2114 if (includeErrorCookies) {
2115 prependCookies(errorHeaders, headers);
2116 }
2117 prependCookies(actionHeaders, headers);
2118 prependCookies(loaderHeaders, headers);
2119 prependCookies(parentHeaders, headers);
2120 return headers;
2121 }, new Headers());
2122}
2123function prependCookies(parentHeaders, childHeaders) {
2124 let parentSetCookieString = parentHeaders.get("Set-Cookie");
2125 if (parentSetCookieString) {
2126 let cookies = setCookieParser.splitCookiesString(parentSetCookieString);
2127 let childCookies = new Set(childHeaders.getSetCookie());
2128 cookies.forEach((cookie) => {
2129 if (!childCookies.has(cookie)) {
2130 childHeaders.append("Set-Cookie", cookie);
2131 }
2132 });
2133 }
2134}
2135var SINGLE_FETCH_REDIRECT_STATUS = 202;
2136var Outlet = reactServerClient.Outlet;
2137var WithComponentProps = reactServerClient.UNSAFE_WithComponentProps;
2138var WithErrorBoundaryProps = reactServerClient.UNSAFE_WithErrorBoundaryProps;
2139var WithHydrateFallbackProps = reactServerClient.UNSAFE_WithHydrateFallbackProps;
2140var globalVar = typeof globalThis !== "undefined" ? globalThis : global;
2141var ServerStorage = globalVar.___reactRouterServerStorage___ ?? (globalVar.___reactRouterServerStorage___ = new node_async_hooks.AsyncLocalStorage());
2142var redirect2 = (...args) => {
2143 const response = redirect(...args);
2144 const ctx = ServerStorage.getStore();
2145 if (ctx) {
2146 ctx.redirect = response;
2147 }
2148 return response;
2149};
2150var redirectDocument2 = (...args) => {
2151 const response = redirectDocument(...args);
2152 const ctx = ServerStorage.getStore();
2153 if (ctx) {
2154 ctx.redirect = response;
2155 }
2156 return response;
2157};
2158var replace2 = (...args) => {
2159 const response = replace(...args);
2160 const ctx = ServerStorage.getStore();
2161 if (ctx) {
2162 ctx.redirect = response;
2163 }
2164 return response;
2165};
2166async function matchRSCServerRequest({
2167 createTemporaryReferenceSet,
2168 basename,
2169 decodeReply,
2170 requestContext,
2171 loadServerAction,
2172 decodeAction,
2173 decodeFormState,
2174 onError,
2175 request,
2176 routes,
2177 generateResponse
2178}) {
2179 let requestUrl = new URL(request.url);
2180 const temporaryReferences = createTemporaryReferenceSet();
2181 if (isManifestRequest(requestUrl)) {
2182 let response2 = await generateManifestResponse(
2183 routes,
2184 basename,
2185 request,
2186 generateResponse,
2187 temporaryReferences
2188 );
2189 return response2;
2190 }
2191 let isDataRequest = isReactServerRequest(requestUrl);
2192 const url = new URL(request.url);
2193 let routerRequest = request;
2194 if (isDataRequest) {
2195 url.pathname = url.pathname.replace(/(_root)?\.rsc$/, "");
2196 routerRequest = new Request(url.toString(), {
2197 method: request.method,
2198 headers: request.headers,
2199 body: request.body,
2200 signal: request.signal,
2201 duplex: request.body ? "half" : void 0
2202 });
2203 }
2204 let matches = matchRoutes(routes, url.pathname, basename);
2205 if (matches) {
2206 await Promise.all(matches.map((m) => explodeLazyRoute(m.route)));
2207 }
2208 const leafMatch = matches?.[matches.length - 1];
2209 if (!isDataRequest && leafMatch && !leafMatch.route.Component && !leafMatch.route.ErrorBoundary) {
2210 return generateResourceResponse(
2211 routerRequest,
2212 routes,
2213 basename,
2214 leafMatch.route.id,
2215 requestContext,
2216 onError
2217 );
2218 }
2219 let response = await generateRenderResponse(
2220 routerRequest,
2221 routes,
2222 basename,
2223 isDataRequest,
2224 decodeReply,
2225 requestContext,
2226 loadServerAction,
2227 decodeAction,
2228 decodeFormState,
2229 onError,
2230 generateResponse,
2231 temporaryReferences
2232 );
2233 response.headers.set("X-Remix-Response", "yes");
2234 return response;
2235}
2236async function generateManifestResponse(routes, basename, request, generateResponse, temporaryReferences) {
2237 let url = new URL(request.url);
2238 let pathnameParams = url.searchParams.getAll("p");
2239 let pathnames = pathnameParams.length ? pathnameParams : [url.pathname.replace(/\.manifest$/, "")];
2240 let routeIds = /* @__PURE__ */ new Set();
2241 let matchedRoutes = pathnames.flatMap((pathname) => {
2242 let pathnameMatches = matchRoutes(routes, pathname, basename);
2243 return pathnameMatches?.map((m, i) => ({
2244 ...m.route,
2245 parentId: pathnameMatches[i - 1]?.route.id
2246 })) ?? [];
2247 }).filter((route) => {
2248 if (!routeIds.has(route.id)) {
2249 routeIds.add(route.id);
2250 return true;
2251 }
2252 return false;
2253 });
2254 let payload = {
2255 type: "manifest",
2256 patches: (await Promise.all([
2257 ...matchedRoutes.map((route) => getManifestRoute(route)),
2258 getAdditionalRoutePatches(
2259 pathnames,
2260 routes,
2261 basename,
2262 Array.from(routeIds)
2263 )
2264 ])).flat(1)
2265 };
2266 return generateResponse(
2267 {
2268 statusCode: 200,
2269 headers: new Headers({
2270 "Content-Type": "text/x-component",
2271 Vary: "Content-Type"
2272 }),
2273 payload
2274 },
2275 { temporaryReferences }
2276 );
2277}
2278function prependBasenameToRedirectResponse(response, basename = "/") {
2279 if (basename === "/") {
2280 return response;
2281 }
2282 let redirect3 = response.headers.get("Location");
2283 if (!redirect3 || isAbsoluteUrl(redirect3)) {
2284 return response;
2285 }
2286 response.headers.set(
2287 "Location",
2288 prependBasename({ basename, pathname: redirect3 })
2289 );
2290 return response;
2291}
2292async function processServerAction(request, basename, decodeReply, loadServerAction, decodeAction, decodeFormState, onError, temporaryReferences) {
2293 const getRevalidationRequest = () => new Request(request.url, {
2294 method: "GET",
2295 headers: request.headers,
2296 signal: request.signal
2297 });
2298 const isFormRequest = canDecodeWithFormData(
2299 request.headers.get("Content-Type")
2300 );
2301 const actionId = request.headers.get("rsc-action-id");
2302 if (actionId) {
2303 if (!decodeReply || !loadServerAction) {
2304 throw new Error(
2305 "Cannot handle enhanced server action without decodeReply and loadServerAction functions"
2306 );
2307 }
2308 const reply = isFormRequest ? await request.formData() : await request.text();
2309 const actionArgs = await decodeReply(reply, { temporaryReferences });
2310 const action = await loadServerAction(actionId);
2311 const serverAction = action.bind(null, ...actionArgs);
2312 let actionResult = Promise.resolve(serverAction());
2313 try {
2314 await actionResult;
2315 } catch (error) {
2316 if (isResponse(error)) {
2317 return error;
2318 }
2319 onError?.(error);
2320 }
2321 return {
2322 actionResult,
2323 revalidationRequest: getRevalidationRequest()
2324 };
2325 } else if (isFormRequest) {
2326 const formData = await request.clone().formData();
2327 if (Array.from(formData.keys()).some((k) => k.startsWith("$ACTION_"))) {
2328 if (!decodeAction) {
2329 throw new Error(
2330 "Cannot handle form actions without a decodeAction function"
2331 );
2332 }
2333 const action = await decodeAction(formData);
2334 let formState = void 0;
2335 try {
2336 let result = await action();
2337 if (isRedirectResponse(result)) {
2338 result = prependBasenameToRedirectResponse(result, basename);
2339 }
2340 formState = decodeFormState?.(result, formData);
2341 } catch (error) {
2342 if (isRedirectResponse(error)) {
2343 return prependBasenameToRedirectResponse(error, basename);
2344 }
2345 if (isResponse(error)) {
2346 return error;
2347 }
2348 onError?.(error);
2349 }
2350 return {
2351 formState,
2352 revalidationRequest: getRevalidationRequest()
2353 };
2354 }
2355 }
2356}
2357async function generateResourceResponse(request, routes, basename, routeId, requestContext, onError) {
2358 let result;
2359 try {
2360 const staticHandler = createStaticHandler(routes, {
2361 basename
2362 });
2363 let response = await staticHandler.queryRoute(request, {
2364 routeId,
2365 requestContext,
2366 unstable_respond: (ctx) => ctx
2367 });
2368 if (isResponse(response)) {
2369 result = response;
2370 } else {
2371 if (typeof response === "string") {
2372 result = new Response(response);
2373 } else {
2374 result = Response.json(response);
2375 }
2376 }
2377 } catch (error) {
2378 if (isResponse(error)) {
2379 result = error;
2380 } else if (isRouteErrorResponse(error)) {
2381 onError?.(error);
2382 const errorMessage = typeof error.data === "string" ? error.data : error.statusText;
2383 result = new Response(errorMessage, {
2384 status: error.status,
2385 statusText: error.statusText
2386 });
2387 } else {
2388 onError?.(error);
2389 result = new Response("Internal Server Error", {
2390 status: 500
2391 });
2392 }
2393 }
2394 const headers = new Headers(result.headers);
2395 headers.set("React-Router-Resource", "true");
2396 return new Response(result.body, {
2397 status: result.status,
2398 statusText: result.statusText,
2399 headers
2400 });
2401}
2402async function generateRenderResponse(request, routes, basename, isDataRequest, decodeReply, requestContext, loadServerAction, decodeAction, decodeFormState, onError, generateResponse, temporaryReferences) {
2403 let statusCode = 200;
2404 let url = new URL(request.url);
2405 let isSubmission = isMutationMethod(request.method);
2406 let routeIdsToLoad = !isSubmission && url.searchParams.has("_routes") ? url.searchParams.get("_routes").split(",") : null;
2407 const staticHandler = createStaticHandler(routes, {
2408 basename,
2409 mapRouteProperties: (r) => ({
2410 hasErrorBoundary: r.ErrorBoundary != null
2411 })
2412 });
2413 let actionResult;
2414 const ctx = {};
2415 const result = await ServerStorage.run(
2416 ctx,
2417 () => staticHandler.query(request, {
2418 requestContext,
2419 skipLoaderErrorBubbling: isDataRequest,
2420 skipRevalidation: isSubmission,
2421 ...routeIdsToLoad ? { filterMatchesToLoad: (m) => routeIdsToLoad.includes(m.route.id) } : null,
2422 async unstable_stream(_, query) {
2423 let formState;
2424 if (request.method === "POST") {
2425 let result2 = await processServerAction(
2426 request,
2427 basename,
2428 decodeReply,
2429 loadServerAction,
2430 decodeAction,
2431 decodeFormState,
2432 onError,
2433 temporaryReferences
2434 );
2435 if (isResponse(result2)) {
2436 return generateRedirectResponse(
2437 result2,
2438 actionResult,
2439 basename,
2440 isDataRequest,
2441 generateResponse,
2442 temporaryReferences
2443 );
2444 }
2445 actionResult = result2?.actionResult;
2446 formState = result2?.formState;
2447 request = result2?.revalidationRequest ?? request;
2448 }
2449 if (ctx.redirect) {
2450 return generateRedirectResponse(
2451 ctx.redirect,
2452 actionResult,
2453 basename,
2454 isDataRequest,
2455 generateResponse,
2456 temporaryReferences
2457 );
2458 }
2459 let staticContext = await query(request);
2460 if (isResponse(staticContext)) {
2461 return generateRedirectResponse(
2462 staticContext,
2463 actionResult,
2464 basename,
2465 isDataRequest,
2466 generateResponse,
2467 temporaryReferences
2468 );
2469 }
2470 return generateStaticContextResponse(
2471 routes,
2472 basename,
2473 generateResponse,
2474 statusCode,
2475 routeIdsToLoad,
2476 isDataRequest,
2477 isSubmission,
2478 actionResult,
2479 formState,
2480 staticContext,
2481 temporaryReferences
2482 );
2483 }
2484 })
2485 );
2486 if (isRedirectResponse(result)) {
2487 return generateRedirectResponse(
2488 result,
2489 actionResult,
2490 basename,
2491 isDataRequest,
2492 generateResponse,
2493 temporaryReferences
2494 );
2495 }
2496 invariant2(isResponse(result), "Expected a response from query");
2497 return result;
2498}
2499function generateRedirectResponse(response, actionResult, basename, isDataRequest, generateResponse, temporaryReferences) {
2500 let redirect3 = response.headers.get("Location");
2501 if (isDataRequest && basename) {
2502 redirect3 = stripBasename(redirect3, basename) || redirect3;
2503 }
2504 let payload = {
2505 type: "redirect",
2506 location: redirect3,
2507 reload: response.headers.get("X-Remix-Reload-Document") === "true",
2508 replace: response.headers.get("X-Remix-Replace") === "true",
2509 status: response.status,
2510 actionResult
2511 };
2512 let headers = new Headers(response.headers);
2513 headers.delete("Location");
2514 headers.delete("X-Remix-Reload-Document");
2515 headers.delete("X-Remix-Replace");
2516 headers.delete("Content-Length");
2517 headers.set("Content-Type", "text/x-component");
2518 headers.set("Vary", "Content-Type");
2519 return generateResponse(
2520 {
2521 statusCode: SINGLE_FETCH_REDIRECT_STATUS,
2522 headers,
2523 payload
2524 },
2525 { temporaryReferences }
2526 );
2527}
2528async function generateStaticContextResponse(routes, basename, generateResponse, statusCode, routeIdsToLoad, isDataRequest, isSubmission, actionResult, formState, staticContext, temporaryReferences) {
2529 statusCode = staticContext.statusCode ?? statusCode;
2530 if (staticContext.errors) {
2531 staticContext.errors = Object.fromEntries(
2532 Object.entries(staticContext.errors).map(([key, error]) => [
2533 key,
2534 isRouteErrorResponse(error) ? Object.fromEntries(Object.entries(error)) : error
2535 ])
2536 );
2537 }
2538 staticContext.matches.forEach((m) => {
2539 const routeHasNoLoaderData = staticContext.loaderData[m.route.id] === void 0;
2540 const routeHasError = Boolean(
2541 staticContext.errors && m.route.id in staticContext.errors
2542 );
2543 if (routeHasNoLoaderData && !routeHasError) {
2544 staticContext.loaderData[m.route.id] = null;
2545 }
2546 });
2547 let headers = getDocumentHeadersImpl(
2548 staticContext,
2549 (match) => match.route.headers
2550 );
2551 headers.delete("Content-Length");
2552 const baseRenderPayload = {
2553 type: "render",
2554 basename,
2555 actionData: staticContext.actionData,
2556 errors: staticContext.errors,
2557 loaderData: staticContext.loaderData,
2558 location: staticContext.location,
2559 formState
2560 };
2561 const renderPayloadPromise = () => getRenderPayload(
2562 baseRenderPayload,
2563 routes,
2564 basename,
2565 routeIdsToLoad,
2566 isDataRequest,
2567 staticContext
2568 );
2569 let payload;
2570 if (actionResult) {
2571 payload = {
2572 type: "action",
2573 actionResult,
2574 rerender: renderPayloadPromise()
2575 };
2576 } else if (isSubmission && isDataRequest) {
2577 payload = {
2578 ...baseRenderPayload,
2579 matches: [],
2580 patches: []
2581 };
2582 } else {
2583 payload = await renderPayloadPromise();
2584 }
2585 return generateResponse(
2586 {
2587 statusCode,
2588 headers,
2589 payload
2590 },
2591 { temporaryReferences }
2592 );
2593}
2594async function getRenderPayload(baseRenderPayload, routes, basename, routeIdsToLoad, isDataRequest, staticContext) {
2595 let deepestRenderedRouteIdx = staticContext.matches.length - 1;
2596 let parentIds = {};
2597 staticContext.matches.forEach((m, i) => {
2598 if (i > 0) {
2599 parentIds[m.route.id] = staticContext.matches[i - 1].route.id;
2600 }
2601 if (staticContext.errors && m.route.id in staticContext.errors && deepestRenderedRouteIdx > i) {
2602 deepestRenderedRouteIdx = i;
2603 }
2604 });
2605 let matchesPromise = Promise.all(
2606 staticContext.matches.map((match, i) => {
2607 let shouldRenderComponent = i <= deepestRenderedRouteIdx && (!routeIdsToLoad || routeIdsToLoad.includes(match.route.id)) && (!staticContext.errors || !(match.route.id in staticContext.errors));
2608 return getRSCRouteMatch(
2609 staticContext,
2610 match,
2611 shouldRenderComponent,
2612 parentIds[match.route.id]
2613 );
2614 })
2615 );
2616 let patchesPromise = getAdditionalRoutePatches(
2617 [staticContext.location.pathname],
2618 routes,
2619 basename,
2620 staticContext.matches.map((m) => m.route.id)
2621 );
2622 let [matches, patches] = await Promise.all([matchesPromise, patchesPromise]);
2623 return {
2624 ...baseRenderPayload,
2625 matches,
2626 patches
2627 };
2628}
2629async function getRSCRouteMatch(staticContext, match, shouldRenderComponent, parentId) {
2630 await explodeLazyRoute(match.route);
2631 const Layout = match.route.Layout || React2__namespace.Fragment;
2632 const Component = match.route.Component;
2633 const ErrorBoundary = match.route.ErrorBoundary;
2634 const HydrateFallback = match.route.HydrateFallback;
2635 const loaderData = staticContext.loaderData[match.route.id];
2636 const actionData = staticContext.actionData?.[match.route.id];
2637 const params = match.params;
2638 let element = void 0;
2639 if (Component) {
2640 element = shouldRenderComponent ? React2__namespace.createElement(
2641 Layout,
2642 null,
2643 isClientReference(Component) ? React2__namespace.createElement(WithComponentProps, {
2644 children: React2__namespace.createElement(Component)
2645 }) : React2__namespace.createElement(Component, {
2646 loaderData,
2647 actionData,
2648 params,
2649 matches: staticContext.matches.map(
2650 (match2) => convertRouteMatchToUiMatch(match2, staticContext.loaderData)
2651 )
2652 })
2653 ) : React2__namespace.createElement(Outlet);
2654 }
2655 let error = void 0;
2656 if (ErrorBoundary && staticContext.errors) {
2657 error = staticContext.errors[match.route.id];
2658 }
2659 const errorElement = ErrorBoundary ? React2__namespace.createElement(
2660 Layout,
2661 null,
2662 isClientReference(ErrorBoundary) ? React2__namespace.createElement(WithErrorBoundaryProps, {
2663 children: React2__namespace.createElement(ErrorBoundary)
2664 }) : React2__namespace.createElement(ErrorBoundary, {
2665 loaderData,
2666 actionData,
2667 params,
2668 error
2669 })
2670 ) : void 0;
2671 const hydrateFallbackElement = HydrateFallback ? React2__namespace.createElement(
2672 Layout,
2673 null,
2674 isClientReference(HydrateFallback) ? React2__namespace.createElement(WithHydrateFallbackProps, {
2675 children: React2__namespace.createElement(HydrateFallback)
2676 }) : React2__namespace.createElement(HydrateFallback, {
2677 loaderData,
2678 actionData,
2679 params
2680 })
2681 ) : void 0;
2682 return {
2683 clientAction: match.route.clientAction,
2684 clientLoader: match.route.clientLoader,
2685 element,
2686 errorElement,
2687 handle: match.route.handle,
2688 hasAction: !!match.route.action,
2689 hasComponent: !!Component,
2690 hasErrorBoundary: !!ErrorBoundary,
2691 hasLoader: !!match.route.loader,
2692 hydrateFallbackElement,
2693 id: match.route.id,
2694 index: match.route.index,
2695 links: match.route.links,
2696 meta: match.route.meta,
2697 params,
2698 parentId,
2699 path: match.route.path,
2700 pathname: match.pathname,
2701 pathnameBase: match.pathnameBase,
2702 shouldRevalidate: match.route.shouldRevalidate
2703 };
2704}
2705async function getManifestRoute(route) {
2706 await explodeLazyRoute(route);
2707 const Layout = route.Layout || React2__namespace.Fragment;
2708 const errorElement = route.ErrorBoundary ? React2__namespace.createElement(
2709 Layout,
2710 null,
2711 React2__namespace.createElement(route.ErrorBoundary)
2712 ) : void 0;
2713 return {
2714 clientAction: route.clientAction,
2715 clientLoader: route.clientLoader,
2716 handle: route.handle,
2717 hasAction: !!route.action,
2718 hasComponent: !!route.Component,
2719 hasErrorBoundary: !!route.ErrorBoundary,
2720 errorElement,
2721 hasLoader: !!route.loader,
2722 id: route.id,
2723 parentId: route.parentId,
2724 path: route.path,
2725 index: "index" in route ? route.index : void 0,
2726 links: route.links,
2727 meta: route.meta
2728 };
2729}
2730async function explodeLazyRoute(route) {
2731 if ("lazy" in route && route.lazy) {
2732 let {
2733 default: lazyDefaultExport,
2734 Component: lazyComponentExport,
2735 ...lazyProperties
2736 } = await route.lazy();
2737 let Component = lazyComponentExport || lazyDefaultExport;
2738 if (Component && !route.Component) {
2739 route.Component = Component;
2740 }
2741 for (let [k, v] of Object.entries(lazyProperties)) {
2742 if (k !== "id" && k !== "path" && k !== "index" && k !== "children" && route[k] == null) {
2743 route[k] = v;
2744 }
2745 }
2746 route.lazy = void 0;
2747 }
2748}
2749async function getAdditionalRoutePatches(pathnames, routes, basename, matchedRouteIds) {
2750 let patchRouteMatches = /* @__PURE__ */ new Map();
2751 let matchedPaths = /* @__PURE__ */ new Set();
2752 for (const pathname of pathnames) {
2753 let segments = pathname.split("/").filter(Boolean);
2754 let paths = ["/"];
2755 segments.pop();
2756 while (segments.length > 0) {
2757 paths.push(`/${segments.join("/")}`);
2758 segments.pop();
2759 }
2760 paths.forEach((path) => {
2761 if (matchedPaths.has(path)) {
2762 return;
2763 }
2764 matchedPaths.add(path);
2765 let matches = matchRoutes(routes, path, basename) || [];
2766 matches.forEach((m, i) => {
2767 if (patchRouteMatches.get(m.route.id)) {
2768 return;
2769 }
2770 patchRouteMatches.set(m.route.id, {
2771 ...m.route,
2772 parentId: matches[i - 1]?.route.id
2773 });
2774 });
2775 });
2776 }
2777 let patches = await Promise.all(
2778 [...patchRouteMatches.values()].filter((route) => !matchedRouteIds.some((id) => id === route.id)).map((route) => getManifestRoute(route))
2779 );
2780 return patches;
2781}
2782function isReactServerRequest(url) {
2783 return url.pathname.endsWith(".rsc");
2784}
2785function isManifestRequest(url) {
2786 return url.pathname.endsWith(".manifest");
2787}
2788function isClientReference(x) {
2789 try {
2790 return x.$$typeof === Symbol.for("react.client.reference");
2791 } catch {
2792 return false;
2793 }
2794}
2795function canDecodeWithFormData(contentType) {
2796 if (!contentType) return false;
2797 return contentType.match(/\bapplication\/x-www-form-urlencoded\b/) || contentType.match(/\bmultipart\/form-data\b/);
2798}
2799
2800// lib/server-runtime/crypto.ts
2801var encoder = /* @__PURE__ */ new TextEncoder();
2802var sign = async (value, secret) => {
2803 let data2 = encoder.encode(value);
2804 let key = await createKey2(secret, ["sign"]);
2805 let signature = await crypto.subtle.sign("HMAC", key, data2);
2806 let hash = btoa(String.fromCharCode(...new Uint8Array(signature))).replace(
2807 /=+$/,
2808 ""
2809 );
2810 return value + "." + hash;
2811};
2812var unsign = async (cookie, secret) => {
2813 let index = cookie.lastIndexOf(".");
2814 let value = cookie.slice(0, index);
2815 let hash = cookie.slice(index + 1);
2816 let data2 = encoder.encode(value);
2817 let key = await createKey2(secret, ["verify"]);
2818 try {
2819 let signature = byteStringToUint8Array(atob(hash));
2820 let valid = await crypto.subtle.verify("HMAC", key, signature, data2);
2821 return valid ? value : false;
2822 } catch (error) {
2823 return false;
2824 }
2825};
2826var createKey2 = async (secret, usages) => crypto.subtle.importKey(
2827 "raw",
2828 encoder.encode(secret),
2829 { name: "HMAC", hash: "SHA-256" },
2830 false,
2831 usages
2832);
2833function byteStringToUint8Array(byteString) {
2834 let array = new Uint8Array(byteString.length);
2835 for (let i = 0; i < byteString.length; i++) {
2836 array[i] = byteString.charCodeAt(i);
2837 }
2838 return array;
2839}
2840
2841// lib/server-runtime/warnings.ts
2842var alreadyWarned = {};
2843function warnOnce(condition, message) {
2844 if (!condition && !alreadyWarned[message]) {
2845 alreadyWarned[message] = true;
2846 console.warn(message);
2847 }
2848}
2849
2850// lib/server-runtime/cookies.ts
2851var createCookie = (name, cookieOptions = {}) => {
2852 let { secrets = [], ...options } = {
2853 path: "/",
2854 sameSite: "lax",
2855 ...cookieOptions
2856 };
2857 warnOnceAboutExpiresCookie(name, options.expires);
2858 return {
2859 get name() {
2860 return name;
2861 },
2862 get isSigned() {
2863 return secrets.length > 0;
2864 },
2865 get expires() {
2866 return typeof options.maxAge !== "undefined" ? new Date(Date.now() + options.maxAge * 1e3) : options.expires;
2867 },
2868 async parse(cookieHeader, parseOptions) {
2869 if (!cookieHeader) return null;
2870 let cookies = cookie.parse(cookieHeader, { ...options, ...parseOptions });
2871 if (name in cookies) {
2872 let value = cookies[name];
2873 if (typeof value === "string" && value !== "") {
2874 let decoded = await decodeCookieValue(value, secrets);
2875 return decoded;
2876 } else {
2877 return "";
2878 }
2879 } else {
2880 return null;
2881 }
2882 },
2883 async serialize(value, serializeOptions) {
2884 return cookie.serialize(
2885 name,
2886 value === "" ? "" : await encodeCookieValue(value, secrets),
2887 {
2888 ...options,
2889 ...serializeOptions
2890 }
2891 );
2892 }
2893 };
2894};
2895var isCookie = (object) => {
2896 return object != null && typeof object.name === "string" && typeof object.isSigned === "boolean" && typeof object.parse === "function" && typeof object.serialize === "function";
2897};
2898async function encodeCookieValue(value, secrets) {
2899 let encoded = encodeData(value);
2900 if (secrets.length > 0) {
2901 encoded = await sign(encoded, secrets[0]);
2902 }
2903 return encoded;
2904}
2905async function decodeCookieValue(value, secrets) {
2906 if (secrets.length > 0) {
2907 for (let secret of secrets) {
2908 let unsignedValue = await unsign(value, secret);
2909 if (unsignedValue !== false) {
2910 return decodeData(unsignedValue);
2911 }
2912 }
2913 return null;
2914 }
2915 return decodeData(value);
2916}
2917function encodeData(value) {
2918 return btoa(myUnescape(encodeURIComponent(JSON.stringify(value))));
2919}
2920function decodeData(value) {
2921 try {
2922 return JSON.parse(decodeURIComponent(myEscape(atob(value))));
2923 } catch (error) {
2924 return {};
2925 }
2926}
2927function myEscape(value) {
2928 let str = value.toString();
2929 let result = "";
2930 let index = 0;
2931 let chr, code;
2932 while (index < str.length) {
2933 chr = str.charAt(index++);
2934 if (/[\w*+\-./@]/.exec(chr)) {
2935 result += chr;
2936 } else {
2937 code = chr.charCodeAt(0);
2938 if (code < 256) {
2939 result += "%" + hex(code, 2);
2940 } else {
2941 result += "%u" + hex(code, 4).toUpperCase();
2942 }
2943 }
2944 }
2945 return result;
2946}
2947function hex(code, length) {
2948 let result = code.toString(16);
2949 while (result.length < length) result = "0" + result;
2950 return result;
2951}
2952function myUnescape(value) {
2953 let str = value.toString();
2954 let result = "";
2955 let index = 0;
2956 let chr, part;
2957 while (index < str.length) {
2958 chr = str.charAt(index++);
2959 if (chr === "%") {
2960 if (str.charAt(index) === "u") {
2961 part = str.slice(index + 1, index + 5);
2962 if (/^[\da-f]{4}$/i.exec(part)) {
2963 result += String.fromCharCode(parseInt(part, 16));
2964 index += 5;
2965 continue;
2966 }
2967 } else {
2968 part = str.slice(index, index + 2);
2969 if (/^[\da-f]{2}$/i.exec(part)) {
2970 result += String.fromCharCode(parseInt(part, 16));
2971 index += 2;
2972 continue;
2973 }
2974 }
2975 }
2976 result += chr;
2977 }
2978 return result;
2979}
2980function warnOnceAboutExpiresCookie(name, expires) {
2981 warnOnce(
2982 !expires,
2983 `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.`
2984 );
2985}
2986
2987// lib/server-runtime/sessions.ts
2988function flash(name) {
2989 return `__flash_${name}__`;
2990}
2991var createSession = (initialData = {}, id = "") => {
2992 let map = new Map(Object.entries(initialData));
2993 return {
2994 get id() {
2995 return id;
2996 },
2997 get data() {
2998 return Object.fromEntries(map);
2999 },
3000 has(name) {
3001 return map.has(name) || map.has(flash(name));
3002 },
3003 get(name) {
3004 if (map.has(name)) return map.get(name);
3005 let flashName = flash(name);
3006 if (map.has(flashName)) {
3007 let value = map.get(flashName);
3008 map.delete(flashName);
3009 return value;
3010 }
3011 return void 0;
3012 },
3013 set(name, value) {
3014 map.set(name, value);
3015 },
3016 flash(name, value) {
3017 map.set(flash(name), value);
3018 },
3019 unset(name) {
3020 map.delete(name);
3021 }
3022 };
3023};
3024var isSession = (object) => {
3025 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";
3026};
3027function createSessionStorage({
3028 cookie: cookieArg,
3029 createData,
3030 readData,
3031 updateData,
3032 deleteData
3033}) {
3034 let cookie = isCookie(cookieArg) ? cookieArg : createCookie(cookieArg?.name || "__session", cookieArg);
3035 warnOnceAboutSigningSessionCookie(cookie);
3036 return {
3037 async getSession(cookieHeader, options) {
3038 let id = cookieHeader && await cookie.parse(cookieHeader, options);
3039 let data2 = id && await readData(id);
3040 return createSession(data2 || {}, id || "");
3041 },
3042 async commitSession(session, options) {
3043 let { id, data: data2 } = session;
3044 let expires = options?.maxAge != null ? new Date(Date.now() + options.maxAge * 1e3) : options?.expires != null ? options.expires : cookie.expires;
3045 if (id) {
3046 await updateData(id, data2, expires);
3047 } else {
3048 id = await createData(data2, expires);
3049 }
3050 return cookie.serialize(id, options);
3051 },
3052 async destroySession(session, options) {
3053 await deleteData(session.id);
3054 return cookie.serialize("", {
3055 ...options,
3056 maxAge: void 0,
3057 expires: /* @__PURE__ */ new Date(0)
3058 });
3059 }
3060 };
3061}
3062function warnOnceAboutSigningSessionCookie(cookie) {
3063 warnOnce(
3064 cookie.isSigned,
3065 `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.`
3066 );
3067}
3068
3069// lib/server-runtime/sessions/cookieStorage.ts
3070function createCookieSessionStorage({ cookie: cookieArg } = {}) {
3071 let cookie = isCookie(cookieArg) ? cookieArg : createCookie(cookieArg?.name || "__session", cookieArg);
3072 warnOnceAboutSigningSessionCookie(cookie);
3073 return {
3074 async getSession(cookieHeader, options) {
3075 return createSession(
3076 cookieHeader && await cookie.parse(cookieHeader, options) || {}
3077 );
3078 },
3079 async commitSession(session, options) {
3080 let serializedCookie = await cookie.serialize(session.data, options);
3081 if (serializedCookie.length > 4096) {
3082 throw new Error(
3083 "Cookie length will exceed browser maximum. Length: " + serializedCookie.length
3084 );
3085 }
3086 return serializedCookie;
3087 },
3088 async destroySession(_session, options) {
3089 return cookie.serialize("", {
3090 ...options,
3091 maxAge: void 0,
3092 expires: /* @__PURE__ */ new Date(0)
3093 });
3094 }
3095 };
3096}
3097
3098// lib/server-runtime/sessions/memoryStorage.ts
3099function createMemorySessionStorage({ cookie } = {}) {
3100 let map = /* @__PURE__ */ new Map();
3101 return createSessionStorage({
3102 cookie,
3103 async createData(data2, expires) {
3104 let id = Math.random().toString(36).substring(2, 10);
3105 map.set(id, { data: data2, expires });
3106 return id;
3107 },
3108 async readData(id) {
3109 if (map.has(id)) {
3110 let { data: data2, expires } = map.get(id);
3111 if (!expires || expires > /* @__PURE__ */ new Date()) {
3112 return data2;
3113 }
3114 if (expires) map.delete(id);
3115 }
3116 return null;
3117 },
3118 async updateData(id, data2, expires) {
3119 map.set(id, { data: data2, expires });
3120 },
3121 async deleteData(id) {
3122 map.delete(id);
3123 }
3124 });
3125}
3126
3127Object.defineProperty(exports, "Await", {
3128 enumerable: true,
3129 get: function () { return reactServerClient.Await; }
3130});
3131Object.defineProperty(exports, "BrowserRouter", {
3132 enumerable: true,
3133 get: function () { return reactServerClient.BrowserRouter; }
3134});
3135Object.defineProperty(exports, "Form", {
3136 enumerable: true,
3137 get: function () { return reactServerClient.Form; }
3138});
3139Object.defineProperty(exports, "HashRouter", {
3140 enumerable: true,
3141 get: function () { return reactServerClient.HashRouter; }
3142});
3143Object.defineProperty(exports, "Link", {
3144 enumerable: true,
3145 get: function () { return reactServerClient.Link; }
3146});
3147Object.defineProperty(exports, "Links", {
3148 enumerable: true,
3149 get: function () { return reactServerClient.Links; }
3150});
3151Object.defineProperty(exports, "MemoryRouter", {
3152 enumerable: true,
3153 get: function () { return reactServerClient.MemoryRouter; }
3154});
3155Object.defineProperty(exports, "Meta", {
3156 enumerable: true,
3157 get: function () { return reactServerClient.Meta; }
3158});
3159Object.defineProperty(exports, "NavLink", {
3160 enumerable: true,
3161 get: function () { return reactServerClient.NavLink; }
3162});
3163Object.defineProperty(exports, "Navigate", {
3164 enumerable: true,
3165 get: function () { return reactServerClient.Navigate; }
3166});
3167Object.defineProperty(exports, "Outlet", {
3168 enumerable: true,
3169 get: function () { return reactServerClient.Outlet; }
3170});
3171Object.defineProperty(exports, "Route", {
3172 enumerable: true,
3173 get: function () { return reactServerClient.Route; }
3174});
3175Object.defineProperty(exports, "Router", {
3176 enumerable: true,
3177 get: function () { return reactServerClient.Router; }
3178});
3179Object.defineProperty(exports, "RouterProvider", {
3180 enumerable: true,
3181 get: function () { return reactServerClient.RouterProvider; }
3182});
3183Object.defineProperty(exports, "Routes", {
3184 enumerable: true,
3185 get: function () { return reactServerClient.Routes; }
3186});
3187Object.defineProperty(exports, "ScrollRestoration", {
3188 enumerable: true,
3189 get: function () { return reactServerClient.ScrollRestoration; }
3190});
3191Object.defineProperty(exports, "StaticRouter", {
3192 enumerable: true,
3193 get: function () { return reactServerClient.StaticRouter; }
3194});
3195Object.defineProperty(exports, "StaticRouterProvider", {
3196 enumerable: true,
3197 get: function () { return reactServerClient.StaticRouterProvider; }
3198});
3199Object.defineProperty(exports, "unstable_HistoryRouter", {
3200 enumerable: true,
3201 get: function () { return reactServerClient.unstable_HistoryRouter; }
3202});
3203exports.createCookie = createCookie;
3204exports.createCookieSessionStorage = createCookieSessionStorage;
3205exports.createMemorySessionStorage = createMemorySessionStorage;
3206exports.createSession = createSession;
3207exports.createSessionStorage = createSessionStorage;
3208exports.createStaticHandler = createStaticHandler;
3209exports.data = data;
3210exports.isCookie = isCookie;
3211exports.isSession = isSession;
3212exports.matchRoutes = matchRoutes;
3213exports.redirect = redirect2;
3214exports.redirectDocument = redirectDocument2;
3215exports.replace = replace2;
3216exports.unstable_RouterContextProvider = unstable_RouterContextProvider;
3217exports.unstable_createContext = unstable_createContext;
3218exports.unstable_matchRSCServerRequest = matchRSCServerRequest;