react-router 0.0.0-experimental-e5dac68cb → 0.0.0-experimental-59413d9ab

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