react-router 7.6.3 → 7.7.0-pre.0

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