react-router 0.0.0-experimental-a6d1d1d4e → 0.0.0-experimental-1d760f6a6

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