react-router 0.0.0-experimental-e56aa53bc → 0.0.0-experimental-e6fb6e074

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