react-router 0.0.0-experimental-1ebb6d403 → 0.0.0-experimental-e41ede670

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 +0 -10
  2. package/dist/development/{chunk-5XVYBMAF.mjs → chunk-H3OBLXFX.mjs} +767 -514
  3. package/dist/development/dom-export.d.mts +13 -3
  4. package/dist/development/dom-export.d.ts +13 -3
  5. package/dist/development/dom-export.js +272 -108
  6. package/dist/development/dom-export.mjs +9 -6
  7. package/dist/{production/fog-of-war-7V7BguJA.d.ts → development/fog-of-war-Bt7PejVF.d.ts} +91 -6
  8. package/dist/development/{fog-of-war-NQCW9yWR.d.mts → fog-of-war-Dz4n-TU-.d.mts} +91 -6
  9. package/dist/development/index.d.mts +10 -19
  10. package/dist/development/index.d.ts +10 -19
  11. package/dist/development/index.js +767 -514
  12. package/dist/development/index.mjs +2 -2
  13. package/dist/development/lib/types/route-module.d.mts +6 -2
  14. package/dist/development/lib/types/route-module.d.ts +6 -2
  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-JFOfNyPS.d.ts → route-data-C96IyGKo.d.mts} +37 -15
  18. package/dist/{production/route-data-JFOfNyPS.d.mts → development/route-data-C96IyGKo.d.ts} +37 -15
  19. package/dist/production/{chunk-CKFZHSMW.mjs → chunk-YBZNESR7.mjs} +767 -514
  20. package/dist/production/dom-export.d.mts +13 -3
  21. package/dist/production/dom-export.d.ts +13 -3
  22. package/dist/production/dom-export.js +272 -108
  23. package/dist/production/dom-export.mjs +9 -6
  24. package/dist/{development/fog-of-war-7V7BguJA.d.ts → production/fog-of-war-Bt7PejVF.d.ts} +91 -6
  25. package/dist/production/{fog-of-war-NQCW9yWR.d.mts → fog-of-war-Dz4n-TU-.d.mts} +91 -6
  26. package/dist/production/index.d.mts +10 -19
  27. package/dist/production/index.d.ts +10 -19
  28. package/dist/production/index.js +767 -514
  29. package/dist/production/index.mjs +2 -2
  30. package/dist/production/lib/types/route-module.d.mts +6 -2
  31. package/dist/production/lib/types/route-module.d.ts +6 -2
  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-JFOfNyPS.d.ts → route-data-C96IyGKo.d.mts} +37 -15
  35. package/dist/{development/route-data-JFOfNyPS.d.mts → production/route-data-C96IyGKo.d.ts} +37 -15
  36. package/package.json +2 -17
  37. package/dist/development/server.d.mts +0 -988
  38. package/dist/development/server.d.ts +0 -988
  39. package/dist/development/server.js +0 -1429
  40. package/dist/development/server.mjs +0 -1406
  41. package/dist/production/server.d.mts +0 -988
  42. package/dist/production/server.d.ts +0 -988
  43. package/dist/production/server.js +0 -1405
  44. package/dist/production/server.mjs +0 -1382
@@ -1,1382 +0,0 @@
1
- import * as React from 'react';
2
-
3
- /**
4
- * react-router v0.0.0-experimental-1ebb6d403
5
- *
6
- * Copyright (c) Remix Software Inc.
7
- *
8
- * This source code is licensed under the MIT license found in the
9
- * LICENSE.md file in the root directory of this source tree.
10
- *
11
- * @license MIT
12
- */
13
-
14
- // lib/router/history.ts
15
- function invariant(value, message) {
16
- if (value === false || value === null || typeof value === "undefined") {
17
- throw new Error(message);
18
- }
19
- }
20
- function warning(cond, message) {
21
- if (!cond) {
22
- if (typeof console !== "undefined") console.warn(message);
23
- try {
24
- throw new Error(message);
25
- } catch (e) {
26
- }
27
- }
28
- }
29
- function createKey() {
30
- return Math.random().toString(36).substring(2, 10);
31
- }
32
- function createLocation(current, to, state = null, key) {
33
- let location = {
34
- pathname: typeof current === "string" ? current : current.pathname,
35
- search: "",
36
- hash: "",
37
- ...typeof to === "string" ? parsePath(to) : to,
38
- state,
39
- // TODO: This could be cleaned up. push/replace should probably just take
40
- // full Locations now and avoid the need to run through this flow at all
41
- // But that's a pretty big refactor to the current test suite so going to
42
- // keep as is for the time being and just let any incoming keys take precedence
43
- key: to && to.key || key || createKey()
44
- };
45
- return location;
46
- }
47
- function createPath({
48
- pathname = "/",
49
- search = "",
50
- hash = ""
51
- }) {
52
- if (search && search !== "?")
53
- pathname += search.charAt(0) === "?" ? search : "?" + search;
54
- if (hash && hash !== "#")
55
- pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
56
- return pathname;
57
- }
58
- function parsePath(path) {
59
- let parsedPath = {};
60
- if (path) {
61
- let hashIndex = path.indexOf("#");
62
- if (hashIndex >= 0) {
63
- parsedPath.hash = path.substring(hashIndex);
64
- path = path.substring(0, hashIndex);
65
- }
66
- let searchIndex = path.indexOf("?");
67
- if (searchIndex >= 0) {
68
- parsedPath.search = path.substring(searchIndex);
69
- path = path.substring(0, searchIndex);
70
- }
71
- if (path) {
72
- parsedPath.pathname = path;
73
- }
74
- }
75
- return parsedPath;
76
- }
77
-
78
- // lib/router/utils.ts
79
- var immutableRouteKeys = /* @__PURE__ */ new Set([
80
- "lazy",
81
- "caseSensitive",
82
- "path",
83
- "id",
84
- "index",
85
- "children"
86
- ]);
87
- function isIndexRoute(route) {
88
- return route.index === true;
89
- }
90
- function convertRoutesToDataRoutes(routes, mapRouteProperties2, parentPath = [], manifest = {}) {
91
- return routes.map((route, index) => {
92
- let treePath = [...parentPath, String(index)];
93
- let id = typeof route.id === "string" ? route.id : treePath.join("-");
94
- invariant(
95
- route.index !== true || !route.children,
96
- `Cannot specify children on an index route`
97
- );
98
- invariant(
99
- !manifest[id],
100
- `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
101
- );
102
- if (isIndexRoute(route)) {
103
- let indexRoute = {
104
- ...route,
105
- ...mapRouteProperties2(route),
106
- id
107
- };
108
- manifest[id] = indexRoute;
109
- return indexRoute;
110
- } else {
111
- let pathOrLayoutRoute = {
112
- ...route,
113
- ...mapRouteProperties2(route),
114
- id,
115
- children: void 0
116
- };
117
- manifest[id] = pathOrLayoutRoute;
118
- if (route.children) {
119
- pathOrLayoutRoute.children = convertRoutesToDataRoutes(
120
- route.children,
121
- mapRouteProperties2,
122
- treePath,
123
- manifest
124
- );
125
- }
126
- return pathOrLayoutRoute;
127
- }
128
- });
129
- }
130
- function matchRoutes(routes, locationArg, basename = "/") {
131
- return matchRoutesImpl(routes, locationArg, basename, false);
132
- }
133
- function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
134
- let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
135
- let pathname = stripBasename(location.pathname || "/", basename);
136
- if (pathname == null) {
137
- return null;
138
- }
139
- let branches = flattenRoutes(routes);
140
- rankRouteBranches(branches);
141
- let matches = null;
142
- for (let i = 0; matches == null && i < branches.length; ++i) {
143
- let decoded = decodePath(pathname);
144
- matches = matchRouteBranch(
145
- branches[i],
146
- decoded,
147
- allowPartial
148
- );
149
- }
150
- return matches;
151
- }
152
- function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "") {
153
- let flattenRoute = (route, index, relativePath) => {
154
- let meta = {
155
- relativePath: relativePath === void 0 ? route.path || "" : relativePath,
156
- caseSensitive: route.caseSensitive === true,
157
- childrenIndex: index,
158
- route
159
- };
160
- if (meta.relativePath.startsWith("/")) {
161
- invariant(
162
- meta.relativePath.startsWith(parentPath),
163
- `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.`
164
- );
165
- meta.relativePath = meta.relativePath.slice(parentPath.length);
166
- }
167
- let path = joinPaths([parentPath, meta.relativePath]);
168
- let routesMeta = parentsMeta.concat(meta);
169
- if (route.children && route.children.length > 0) {
170
- invariant(
171
- // Our types know better, but runtime JS may not!
172
- // @ts-expect-error
173
- route.index !== true,
174
- `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
175
- );
176
- flattenRoutes(route.children, branches, routesMeta, path);
177
- }
178
- if (route.path == null && !route.index) {
179
- return;
180
- }
181
- branches.push({
182
- path,
183
- score: computeScore(path, route.index),
184
- routesMeta
185
- });
186
- };
187
- routes.forEach((route, index) => {
188
- if (route.path === "" || !route.path?.includes("?")) {
189
- flattenRoute(route, index);
190
- } else {
191
- for (let exploded of explodeOptionalSegments(route.path)) {
192
- flattenRoute(route, index, exploded);
193
- }
194
- }
195
- });
196
- return branches;
197
- }
198
- function explodeOptionalSegments(path) {
199
- let segments = path.split("/");
200
- if (segments.length === 0) return [];
201
- let [first, ...rest] = segments;
202
- let isOptional = first.endsWith("?");
203
- let required = first.replace(/\?$/, "");
204
- if (rest.length === 0) {
205
- return isOptional ? [required, ""] : [required];
206
- }
207
- let restExploded = explodeOptionalSegments(rest.join("/"));
208
- let result = [];
209
- result.push(
210
- ...restExploded.map(
211
- (subpath) => subpath === "" ? required : [required, subpath].join("/")
212
- )
213
- );
214
- if (isOptional) {
215
- result.push(...restExploded);
216
- }
217
- return result.map(
218
- (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
219
- );
220
- }
221
- function rankRouteBranches(branches) {
222
- branches.sort(
223
- (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
224
- a.routesMeta.map((meta) => meta.childrenIndex),
225
- b.routesMeta.map((meta) => meta.childrenIndex)
226
- )
227
- );
228
- }
229
- var paramRe = /^:[\w-]+$/;
230
- var dynamicSegmentValue = 3;
231
- var indexRouteValue = 2;
232
- var emptySegmentValue = 1;
233
- var staticSegmentValue = 10;
234
- var splatPenalty = -2;
235
- var isSplat = (s) => s === "*";
236
- function computeScore(path, index) {
237
- let segments = path.split("/");
238
- let initialScore = segments.length;
239
- if (segments.some(isSplat)) {
240
- initialScore += splatPenalty;
241
- }
242
- if (index) {
243
- initialScore += indexRouteValue;
244
- }
245
- return segments.filter((s) => !isSplat(s)).reduce(
246
- (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
247
- initialScore
248
- );
249
- }
250
- function compareIndexes(a, b) {
251
- let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
252
- return siblings ? (
253
- // If two routes are siblings, we should try to match the earlier sibling
254
- // first. This allows people to have fine-grained control over the matching
255
- // behavior by simply putting routes with identical paths in the order they
256
- // want them tried.
257
- a[a.length - 1] - b[b.length - 1]
258
- ) : (
259
- // Otherwise, it doesn't really make sense to rank non-siblings by index,
260
- // so they sort equally.
261
- 0
262
- );
263
- }
264
- function matchRouteBranch(branch, pathname, allowPartial = false) {
265
- let { routesMeta } = branch;
266
- let matchedParams = {};
267
- let matchedPathname = "/";
268
- let matches = [];
269
- for (let i = 0; i < routesMeta.length; ++i) {
270
- let meta = routesMeta[i];
271
- let end = i === routesMeta.length - 1;
272
- let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
273
- let match = matchPath(
274
- { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
275
- remainingPathname
276
- );
277
- let route = meta.route;
278
- if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
279
- match = matchPath(
280
- {
281
- path: meta.relativePath,
282
- caseSensitive: meta.caseSensitive,
283
- end: false
284
- },
285
- remainingPathname
286
- );
287
- }
288
- if (!match) {
289
- return null;
290
- }
291
- Object.assign(matchedParams, match.params);
292
- matches.push({
293
- // TODO: Can this as be avoided?
294
- params: matchedParams,
295
- pathname: joinPaths([matchedPathname, match.pathname]),
296
- pathnameBase: normalizePathname(
297
- joinPaths([matchedPathname, match.pathnameBase])
298
- ),
299
- route
300
- });
301
- if (match.pathnameBase !== "/") {
302
- matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
303
- }
304
- }
305
- return matches;
306
- }
307
- function matchPath(pattern, pathname) {
308
- if (typeof pattern === "string") {
309
- pattern = { path: pattern, caseSensitive: false, end: true };
310
- }
311
- let [matcher, compiledParams] = compilePath(
312
- pattern.path,
313
- pattern.caseSensitive,
314
- pattern.end
315
- );
316
- let match = pathname.match(matcher);
317
- if (!match) return null;
318
- let matchedPathname = match[0];
319
- let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
320
- let captureGroups = match.slice(1);
321
- let params = compiledParams.reduce(
322
- (memo, { paramName, isOptional }, index) => {
323
- if (paramName === "*") {
324
- let splatValue = captureGroups[index] || "";
325
- pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
326
- }
327
- const value = captureGroups[index];
328
- if (isOptional && !value) {
329
- memo[paramName] = void 0;
330
- } else {
331
- memo[paramName] = (value || "").replace(/%2F/g, "/");
332
- }
333
- return memo;
334
- },
335
- {}
336
- );
337
- return {
338
- params,
339
- pathname: matchedPathname,
340
- pathnameBase,
341
- pattern
342
- };
343
- }
344
- function compilePath(path, caseSensitive = false, end = true) {
345
- warning(
346
- path === "*" || !path.endsWith("*") || path.endsWith("/*"),
347
- `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(/\*$/, "/*")}".`
348
- );
349
- let params = [];
350
- let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
351
- /\/:([\w-]+)(\?)?/g,
352
- (_, paramName, isOptional) => {
353
- params.push({ paramName, isOptional: isOptional != null });
354
- return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
355
- }
356
- );
357
- if (path.endsWith("*")) {
358
- params.push({ paramName: "*" });
359
- regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
360
- } else if (end) {
361
- regexpSource += "\\/*$";
362
- } else if (path !== "" && path !== "/") {
363
- regexpSource += "(?:(?=\\/|$))";
364
- } else ;
365
- let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
366
- return [matcher, params];
367
- }
368
- function decodePath(value) {
369
- try {
370
- return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
371
- } catch (error) {
372
- warning(
373
- false,
374
- `The URL path "${value}" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`
375
- );
376
- return value;
377
- }
378
- }
379
- function stripBasename(pathname, basename) {
380
- if (basename === "/") return pathname;
381
- if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
382
- return null;
383
- }
384
- let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
385
- let nextChar = pathname.charAt(startIndex);
386
- if (nextChar && nextChar !== "/") {
387
- return null;
388
- }
389
- return pathname.slice(startIndex) || "/";
390
- }
391
- function resolvePath(to, fromPathname = "/") {
392
- let {
393
- pathname: toPathname,
394
- search = "",
395
- hash = ""
396
- } = typeof to === "string" ? parsePath(to) : to;
397
- let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
398
- return {
399
- pathname,
400
- search: normalizeSearch(search),
401
- hash: normalizeHash(hash)
402
- };
403
- }
404
- function resolvePathname(relativePath, fromPathname) {
405
- let segments = fromPathname.replace(/\/+$/, "").split("/");
406
- let relativeSegments = relativePath.split("/");
407
- relativeSegments.forEach((segment) => {
408
- if (segment === "..") {
409
- if (segments.length > 1) segments.pop();
410
- } else if (segment !== ".") {
411
- segments.push(segment);
412
- }
413
- });
414
- return segments.length > 1 ? segments.join("/") : "/";
415
- }
416
- function getInvalidPathError(char, field, dest, path) {
417
- return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
418
- path
419
- )}]. 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.`;
420
- }
421
- function getPathContributingMatches(matches) {
422
- return matches.filter(
423
- (match, index) => index === 0 || match.route.path && match.route.path.length > 0
424
- );
425
- }
426
- function getResolveToMatches(matches) {
427
- let pathMatches = getPathContributingMatches(matches);
428
- return pathMatches.map(
429
- (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
430
- );
431
- }
432
- function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
433
- let to;
434
- if (typeof toArg === "string") {
435
- to = parsePath(toArg);
436
- } else {
437
- to = { ...toArg };
438
- invariant(
439
- !to.pathname || !to.pathname.includes("?"),
440
- getInvalidPathError("?", "pathname", "search", to)
441
- );
442
- invariant(
443
- !to.pathname || !to.pathname.includes("#"),
444
- getInvalidPathError("#", "pathname", "hash", to)
445
- );
446
- invariant(
447
- !to.search || !to.search.includes("#"),
448
- getInvalidPathError("#", "search", "hash", to)
449
- );
450
- }
451
- let isEmptyPath = toArg === "" || to.pathname === "";
452
- let toPathname = isEmptyPath ? "/" : to.pathname;
453
- let from;
454
- if (toPathname == null) {
455
- from = locationPathname;
456
- } else {
457
- let routePathnameIndex = routePathnames.length - 1;
458
- if (!isPathRelative && toPathname.startsWith("..")) {
459
- let toSegments = toPathname.split("/");
460
- while (toSegments[0] === "..") {
461
- toSegments.shift();
462
- routePathnameIndex -= 1;
463
- }
464
- to.pathname = toSegments.join("/");
465
- }
466
- from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
467
- }
468
- let path = resolvePath(to, from);
469
- let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
470
- let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
471
- if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
472
- path.pathname += "/";
473
- }
474
- return path;
475
- }
476
- var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
477
- var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
478
- var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
479
- var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
480
- var ErrorResponseImpl = class {
481
- constructor(status, statusText, data, internal = false) {
482
- this.status = status;
483
- this.statusText = statusText || "";
484
- this.internal = internal;
485
- if (data instanceof Error) {
486
- this.data = data.toString();
487
- this.error = data;
488
- } else {
489
- this.data = data;
490
- }
491
- }
492
- };
493
- function isRouteErrorResponse(error) {
494
- return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
495
- }
496
-
497
- // lib/router/router.ts
498
- var validMutationMethodsArr = [
499
- "POST",
500
- "PUT",
501
- "PATCH",
502
- "DELETE"
503
- ];
504
- var validMutationMethods = new Set(
505
- validMutationMethodsArr
506
- );
507
- var validRequestMethodsArr = [
508
- "GET",
509
- ...validMutationMethodsArr
510
- ];
511
- var validRequestMethods = new Set(validRequestMethodsArr);
512
- var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
513
- var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
514
- var defaultMapRouteProperties = (route) => ({
515
- hasErrorBoundary: Boolean(route.hasErrorBoundary)
516
- });
517
- var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
518
- function createStaticHandler(routes, opts) {
519
- invariant(
520
- routes.length > 0,
521
- "You must provide a non-empty routes array to createStaticHandler"
522
- );
523
- let manifest = {};
524
- let basename = (opts ? opts.basename : null) || "/";
525
- let mapRouteProperties2 = opts?.mapRouteProperties || defaultMapRouteProperties;
526
- let dataRoutes = convertRoutesToDataRoutes(
527
- routes,
528
- mapRouteProperties2,
529
- void 0,
530
- manifest
531
- );
532
- async function query(request, {
533
- requestContext,
534
- skipLoaderErrorBubbling,
535
- dataStrategy
536
- } = {}) {
537
- let url = new URL(request.url);
538
- let method = request.method;
539
- let location = createLocation("", createPath(url), null, "default");
540
- let matches = matchRoutes(dataRoutes, location, basename);
541
- if (!isValidMethod(method) && method !== "HEAD") {
542
- let error = getInternalRouterError(405, { method });
543
- let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
544
- return {
545
- basename,
546
- location,
547
- matches: methodNotAllowedMatches,
548
- loaderData: {},
549
- actionData: null,
550
- errors: {
551
- [route.id]: error
552
- },
553
- statusCode: error.status,
554
- loaderHeaders: {},
555
- actionHeaders: {}
556
- };
557
- } else if (!matches) {
558
- let error = getInternalRouterError(404, { pathname: location.pathname });
559
- let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
560
- return {
561
- basename,
562
- location,
563
- matches: notFoundMatches,
564
- loaderData: {},
565
- actionData: null,
566
- errors: {
567
- [route.id]: error
568
- },
569
- statusCode: error.status,
570
- loaderHeaders: {},
571
- actionHeaders: {}
572
- };
573
- }
574
- let result = await queryImpl(
575
- request,
576
- location,
577
- matches,
578
- requestContext,
579
- dataStrategy || null,
580
- skipLoaderErrorBubbling === true,
581
- null
582
- );
583
- if (isResponse(result)) {
584
- return result;
585
- }
586
- return { location, basename, ...result };
587
- }
588
- async function queryRoute(request, {
589
- routeId,
590
- requestContext,
591
- dataStrategy
592
- } = {}) {
593
- let url = new URL(request.url);
594
- let method = request.method;
595
- let location = createLocation("", createPath(url), null, "default");
596
- let matches = matchRoutes(dataRoutes, location, basename);
597
- if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
598
- throw getInternalRouterError(405, { method });
599
- } else if (!matches) {
600
- throw getInternalRouterError(404, { pathname: location.pathname });
601
- }
602
- let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
603
- if (routeId && !match) {
604
- throw getInternalRouterError(403, {
605
- pathname: location.pathname,
606
- routeId
607
- });
608
- } else if (!match) {
609
- throw getInternalRouterError(404, { pathname: location.pathname });
610
- }
611
- let result = await queryImpl(
612
- request,
613
- location,
614
- matches,
615
- requestContext,
616
- dataStrategy || null,
617
- false,
618
- match
619
- );
620
- if (isResponse(result)) {
621
- return result;
622
- }
623
- let error = result.errors ? Object.values(result.errors)[0] : void 0;
624
- if (error !== void 0) {
625
- throw error;
626
- }
627
- if (result.actionData) {
628
- return Object.values(result.actionData)[0];
629
- }
630
- if (result.loaderData) {
631
- return Object.values(result.loaderData)[0];
632
- }
633
- return void 0;
634
- }
635
- async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch) {
636
- invariant(
637
- request.signal,
638
- "query()/queryRoute() requests must contain an AbortController signal"
639
- );
640
- try {
641
- if (isMutationMethod(request.method)) {
642
- let result2 = await submit(
643
- request,
644
- matches,
645
- routeMatch || getTargetMatch(matches, location),
646
- requestContext,
647
- dataStrategy,
648
- skipLoaderErrorBubbling,
649
- routeMatch != null
650
- );
651
- return result2;
652
- }
653
- let result = await loadRouteData(
654
- request,
655
- matches,
656
- requestContext,
657
- dataStrategy,
658
- skipLoaderErrorBubbling,
659
- routeMatch
660
- );
661
- return isResponse(result) ? result : {
662
- ...result,
663
- actionData: null,
664
- actionHeaders: {}
665
- };
666
- } catch (e) {
667
- if (isDataStrategyResult(e) && isResponse(e.result)) {
668
- if (e.type === "error" /* error */) {
669
- throw e.result;
670
- }
671
- return e.result;
672
- }
673
- if (isRedirectResponse(e)) {
674
- return e;
675
- }
676
- throw e;
677
- }
678
- }
679
- async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {
680
- let result;
681
- if (!actionMatch.route.action && !actionMatch.route.lazy) {
682
- let error = getInternalRouterError(405, {
683
- method: request.method,
684
- pathname: new URL(request.url).pathname,
685
- routeId: actionMatch.route.id
686
- });
687
- if (isRouteRequest) {
688
- throw error;
689
- }
690
- result = {
691
- type: "error" /* error */,
692
- error
693
- };
694
- } else {
695
- let results = await callDataStrategy(
696
- "action",
697
- request,
698
- [actionMatch],
699
- matches,
700
- isRouteRequest,
701
- requestContext,
702
- dataStrategy
703
- );
704
- result = results[actionMatch.route.id];
705
- if (request.signal.aborted) {
706
- throwStaticHandlerAbortedError(request, isRouteRequest);
707
- }
708
- }
709
- if (isRedirectResult(result)) {
710
- throw new Response(null, {
711
- status: result.response.status,
712
- headers: {
713
- Location: result.response.headers.get("Location")
714
- }
715
- });
716
- }
717
- if (isRouteRequest) {
718
- if (isErrorResult(result)) {
719
- throw result.error;
720
- }
721
- return {
722
- matches: [actionMatch],
723
- loaderData: {},
724
- actionData: { [actionMatch.route.id]: result.data },
725
- errors: null,
726
- // Note: statusCode + headers are unused here since queryRoute will
727
- // return the raw Response or value
728
- statusCode: 200,
729
- loaderHeaders: {},
730
- actionHeaders: {}
731
- };
732
- }
733
- let loaderRequest = new Request(request.url, {
734
- headers: request.headers,
735
- redirect: request.redirect,
736
- signal: request.signal
737
- });
738
- if (isErrorResult(result)) {
739
- let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
740
- let context2 = await loadRouteData(
741
- loaderRequest,
742
- matches,
743
- requestContext,
744
- dataStrategy,
745
- skipLoaderErrorBubbling,
746
- null,
747
- [boundaryMatch.route.id, result]
748
- );
749
- return {
750
- ...context2,
751
- statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
752
- actionData: null,
753
- actionHeaders: {
754
- ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
755
- }
756
- };
757
- }
758
- let context = await loadRouteData(
759
- loaderRequest,
760
- matches,
761
- requestContext,
762
- dataStrategy,
763
- skipLoaderErrorBubbling,
764
- null
765
- );
766
- return {
767
- ...context,
768
- actionData: {
769
- [actionMatch.route.id]: result.data
770
- },
771
- // action status codes take precedence over loader status codes
772
- ...result.statusCode ? { statusCode: result.statusCode } : {},
773
- actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
774
- };
775
- }
776
- async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {
777
- let isRouteRequest = routeMatch != null;
778
- if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) {
779
- throw getInternalRouterError(400, {
780
- method: request.method,
781
- pathname: new URL(request.url).pathname,
782
- routeId: routeMatch?.route.id
783
- });
784
- }
785
- let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;
786
- let matchesToLoad = requestMatches.filter(
787
- (m) => m.route.loader || m.route.lazy
788
- );
789
- if (matchesToLoad.length === 0) {
790
- return {
791
- matches,
792
- // Add a null for all matched routes for proper revalidation on the client
793
- loaderData: matches.reduce(
794
- (acc, m) => Object.assign(acc, { [m.route.id]: null }),
795
- {}
796
- ),
797
- errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
798
- [pendingActionResult[0]]: pendingActionResult[1].error
799
- } : null,
800
- statusCode: 200,
801
- loaderHeaders: {}
802
- };
803
- }
804
- let results = await callDataStrategy(
805
- "loader",
806
- request,
807
- matchesToLoad,
808
- matches,
809
- isRouteRequest,
810
- requestContext,
811
- dataStrategy
812
- );
813
- if (request.signal.aborted) {
814
- throwStaticHandlerAbortedError(request, isRouteRequest);
815
- }
816
- let context = processRouteLoaderData(
817
- matches,
818
- results,
819
- pendingActionResult,
820
- true,
821
- skipLoaderErrorBubbling
822
- );
823
- let executedLoaders = new Set(
824
- matchesToLoad.map((match) => match.route.id)
825
- );
826
- matches.forEach((match) => {
827
- if (!executedLoaders.has(match.route.id)) {
828
- context.loaderData[match.route.id] = null;
829
- }
830
- });
831
- return {
832
- ...context,
833
- matches
834
- };
835
- }
836
- async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy) {
837
- let results = await callDataStrategyImpl(
838
- dataStrategy || defaultDataStrategy,
839
- type,
840
- null,
841
- request,
842
- matchesToLoad,
843
- matches,
844
- null,
845
- manifest,
846
- mapRouteProperties2,
847
- requestContext
848
- );
849
- let dataResults = {};
850
- await Promise.all(
851
- matches.map(async (match) => {
852
- if (!(match.route.id in results)) {
853
- return;
854
- }
855
- let result = results[match.route.id];
856
- if (isRedirectDataStrategyResult(result)) {
857
- let response = result.result;
858
- throw normalizeRelativeRoutingRedirectResponse(
859
- response,
860
- request,
861
- match.route.id,
862
- matches,
863
- basename
864
- );
865
- }
866
- if (isResponse(result.result) && isRouteRequest) {
867
- throw result;
868
- }
869
- dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
870
- })
871
- );
872
- return dataResults;
873
- }
874
- return {
875
- dataRoutes,
876
- query,
877
- queryRoute
878
- };
879
- }
880
- function throwStaticHandlerAbortedError(request, isRouteRequest) {
881
- if (request.signal.reason !== void 0) {
882
- throw request.signal.reason;
883
- }
884
- let method = isRouteRequest ? "queryRoute" : "query";
885
- throw new Error(
886
- `${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
887
- );
888
- }
889
- function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
890
- let contextualMatches;
891
- let activeRouteMatch;
892
- {
893
- contextualMatches = matches;
894
- activeRouteMatch = matches[matches.length - 1];
895
- }
896
- let path = resolveTo(
897
- to ? to : ".",
898
- getResolveToMatches(contextualMatches),
899
- stripBasename(location.pathname, basename) || location.pathname,
900
- relative === "path"
901
- );
902
- if (to == null) {
903
- path.search = location.search;
904
- path.hash = location.hash;
905
- }
906
- if ((to == null || to === "" || to === ".") && activeRouteMatch) {
907
- let nakedIndex = hasNakedIndexQuery(path.search);
908
- if (activeRouteMatch.route.index && !nakedIndex) {
909
- path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
910
- } else if (!activeRouteMatch.route.index && nakedIndex) {
911
- let params = new URLSearchParams(path.search);
912
- let indexValues = params.getAll("index");
913
- params.delete("index");
914
- indexValues.filter((v) => v).forEach((v) => params.append("index", v));
915
- let qs = params.toString();
916
- path.search = qs ? `?${qs}` : "";
917
- }
918
- }
919
- if (basename !== "/") {
920
- path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
921
- }
922
- return createPath(path);
923
- }
924
- function getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary = false) {
925
- let index = matches.findIndex((m) => m.route.id === boundaryId);
926
- if (index >= 0) {
927
- return matches.slice(0, includeBoundary ? index + 1 : index);
928
- }
929
- return matches;
930
- }
931
- async function loadLazyRouteModule(route, mapRouteProperties2, manifest) {
932
- if (!route.lazy) {
933
- return;
934
- }
935
- let lazyRoute = await route.lazy();
936
- if (!route.lazy) {
937
- return;
938
- }
939
- let routeToUpdate = manifest[route.id];
940
- invariant(routeToUpdate, "No route found in manifest");
941
- let routeUpdates = {};
942
- for (let lazyRouteProperty in lazyRoute) {
943
- let staticRouteValue = routeToUpdate[lazyRouteProperty];
944
- let isPropertyStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
945
- // on the route updates
946
- lazyRouteProperty !== "hasErrorBoundary";
947
- warning(
948
- !isPropertyStaticallyDefined,
949
- `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.`
950
- );
951
- if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {
952
- routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];
953
- }
954
- }
955
- Object.assign(routeToUpdate, routeUpdates);
956
- Object.assign(routeToUpdate, {
957
- // To keep things framework agnostic, we use the provided `mapRouteProperties`
958
- // function to set the framework-aware properties (`element`/`hasErrorBoundary`)
959
- // since the logic will differ between frameworks.
960
- ...mapRouteProperties2(routeToUpdate),
961
- lazy: void 0
962
- });
963
- }
964
- async function defaultDataStrategy({
965
- matches
966
- }) {
967
- let matchesToLoad = matches.filter((m) => m.shouldLoad);
968
- let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
969
- return results.reduce(
970
- (acc, result, i) => Object.assign(acc, { [matchesToLoad[i].route.id]: result }),
971
- {}
972
- );
973
- }
974
- async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties2, requestContext) {
975
- let loadRouteDefinitionsPromises = matches.map(
976
- (m) => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties2, manifest) : void 0
977
- );
978
- let dsMatches = matches.map((match, i) => {
979
- let loadRoutePromise = loadRouteDefinitionsPromises[i];
980
- let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);
981
- let resolve = async (handlerOverride) => {
982
- if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) {
983
- shouldLoad = true;
984
- }
985
- return shouldLoad ? callLoaderOrAction(
986
- type,
987
- request,
988
- match,
989
- loadRoutePromise,
990
- handlerOverride,
991
- requestContext
992
- ) : Promise.resolve({ type: "data" /* data */, result: void 0 });
993
- };
994
- return {
995
- ...match,
996
- shouldLoad,
997
- resolve
998
- };
999
- });
1000
- let results = await dataStrategyImpl({
1001
- matches: dsMatches,
1002
- request,
1003
- params: matches[0].params,
1004
- fetcherKey,
1005
- context: requestContext
1006
- });
1007
- try {
1008
- await Promise.all(loadRouteDefinitionsPromises);
1009
- } catch (e) {
1010
- }
1011
- return results;
1012
- }
1013
- async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {
1014
- let result;
1015
- let onReject;
1016
- let runHandler = (handler) => {
1017
- let reject;
1018
- let abortPromise = new Promise((_, r) => reject = r);
1019
- onReject = () => reject();
1020
- request.signal.addEventListener("abort", onReject);
1021
- let actualHandler = (ctx) => {
1022
- if (typeof handler !== "function") {
1023
- return Promise.reject(
1024
- new Error(
1025
- `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`
1026
- )
1027
- );
1028
- }
1029
- return handler(
1030
- {
1031
- request,
1032
- params: match.params,
1033
- context: staticContext
1034
- },
1035
- ...ctx !== void 0 ? [ctx] : []
1036
- );
1037
- };
1038
- let handlerPromise = (async () => {
1039
- try {
1040
- let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
1041
- return { type: "data", result: val };
1042
- } catch (e) {
1043
- return { type: "error", result: e };
1044
- }
1045
- })();
1046
- return Promise.race([handlerPromise, abortPromise]);
1047
- };
1048
- try {
1049
- let handler = match.route[type];
1050
- if (loadRoutePromise) {
1051
- if (handler) {
1052
- let handlerError;
1053
- let [value] = await Promise.all([
1054
- // If the handler throws, don't let it immediately bubble out,
1055
- // since we need to let the lazy() execution finish so we know if this
1056
- // route has a boundary that can handle the error
1057
- runHandler(handler).catch((e) => {
1058
- handlerError = e;
1059
- }),
1060
- loadRoutePromise
1061
- ]);
1062
- if (handlerError !== void 0) {
1063
- throw handlerError;
1064
- }
1065
- result = value;
1066
- } else {
1067
- await loadRoutePromise;
1068
- handler = match.route[type];
1069
- if (handler) {
1070
- result = await runHandler(handler);
1071
- } else if (type === "action") {
1072
- let url = new URL(request.url);
1073
- let pathname = url.pathname + url.search;
1074
- throw getInternalRouterError(405, {
1075
- method: request.method,
1076
- pathname,
1077
- routeId: match.route.id
1078
- });
1079
- } else {
1080
- return { type: "data" /* data */, result: void 0 };
1081
- }
1082
- }
1083
- } else if (!handler) {
1084
- let url = new URL(request.url);
1085
- let pathname = url.pathname + url.search;
1086
- throw getInternalRouterError(404, {
1087
- pathname
1088
- });
1089
- } else {
1090
- result = await runHandler(handler);
1091
- }
1092
- } catch (e) {
1093
- return { type: "error" /* error */, result: e };
1094
- } finally {
1095
- if (onReject) {
1096
- request.signal.removeEventListener("abort", onReject);
1097
- }
1098
- }
1099
- return result;
1100
- }
1101
- async function convertDataStrategyResultToDataResult(dataStrategyResult) {
1102
- let { result, type } = dataStrategyResult;
1103
- if (isResponse(result)) {
1104
- let data;
1105
- try {
1106
- let contentType = result.headers.get("Content-Type");
1107
- if (contentType && /\bapplication\/json\b/.test(contentType)) {
1108
- if (result.body == null) {
1109
- data = null;
1110
- } else {
1111
- data = await result.json();
1112
- }
1113
- } else {
1114
- data = await result.text();
1115
- }
1116
- } catch (e) {
1117
- return { type: "error" /* error */, error: e };
1118
- }
1119
- if (type === "error" /* error */) {
1120
- return {
1121
- type: "error" /* error */,
1122
- error: new ErrorResponseImpl(result.status, result.statusText, data),
1123
- statusCode: result.status,
1124
- headers: result.headers
1125
- };
1126
- }
1127
- return {
1128
- type: "data" /* data */,
1129
- data,
1130
- statusCode: result.status,
1131
- headers: result.headers
1132
- };
1133
- }
1134
- if (type === "error" /* error */) {
1135
- if (isDataWithResponseInit(result)) {
1136
- if (result.data instanceof Error) {
1137
- return {
1138
- type: "error" /* error */,
1139
- error: result.data,
1140
- statusCode: result.init?.status
1141
- };
1142
- }
1143
- result = new ErrorResponseImpl(
1144
- result.init?.status || 500,
1145
- void 0,
1146
- result.data
1147
- );
1148
- }
1149
- return {
1150
- type: "error" /* error */,
1151
- error: result,
1152
- statusCode: isRouteErrorResponse(result) ? result.status : void 0
1153
- };
1154
- }
1155
- if (isDataWithResponseInit(result)) {
1156
- return {
1157
- type: "data" /* data */,
1158
- data: result.data,
1159
- statusCode: result.init?.status,
1160
- headers: result.init?.headers ? new Headers(result.init.headers) : void 0
1161
- };
1162
- }
1163
- return { type: "data" /* data */, data: result };
1164
- }
1165
- function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
1166
- let location = response.headers.get("Location");
1167
- invariant(
1168
- location,
1169
- "Redirects returned/thrown from loaders/actions must have a Location header"
1170
- );
1171
- if (!ABSOLUTE_URL_REGEX.test(location)) {
1172
- let trimmedMatches = matches.slice(
1173
- 0,
1174
- matches.findIndex((m) => m.route.id === routeId) + 1
1175
- );
1176
- location = normalizeTo(
1177
- new URL(request.url),
1178
- trimmedMatches,
1179
- basename,
1180
- location
1181
- );
1182
- response.headers.set("Location", location);
1183
- }
1184
- return response;
1185
- }
1186
- function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
1187
- let loaderData = {};
1188
- let errors = null;
1189
- let statusCode;
1190
- let foundError = false;
1191
- let loaderHeaders = {};
1192
- let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
1193
- matches.forEach((match) => {
1194
- if (!(match.route.id in results)) {
1195
- return;
1196
- }
1197
- let id = match.route.id;
1198
- let result = results[id];
1199
- invariant(
1200
- !isRedirectResult(result),
1201
- "Cannot handle redirect results in processLoaderData"
1202
- );
1203
- if (isErrorResult(result)) {
1204
- let error = result.error;
1205
- if (pendingError !== void 0) {
1206
- error = pendingError;
1207
- pendingError = void 0;
1208
- }
1209
- errors = errors || {};
1210
- if (skipLoaderErrorBubbling) {
1211
- errors[id] = error;
1212
- } else {
1213
- let boundaryMatch = findNearestBoundary(matches, id);
1214
- if (errors[boundaryMatch.route.id] == null) {
1215
- errors[boundaryMatch.route.id] = error;
1216
- }
1217
- }
1218
- if (!isStaticHandler) {
1219
- loaderData[id] = ResetLoaderDataSymbol;
1220
- }
1221
- if (!foundError) {
1222
- foundError = true;
1223
- statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
1224
- }
1225
- if (result.headers) {
1226
- loaderHeaders[id] = result.headers;
1227
- }
1228
- } else {
1229
- loaderData[id] = result.data;
1230
- if (result.statusCode && result.statusCode !== 200 && !foundError) {
1231
- statusCode = result.statusCode;
1232
- }
1233
- if (result.headers) {
1234
- loaderHeaders[id] = result.headers;
1235
- }
1236
- }
1237
- });
1238
- if (pendingError !== void 0 && pendingActionResult) {
1239
- errors = { [pendingActionResult[0]]: pendingError };
1240
- loaderData[pendingActionResult[0]] = void 0;
1241
- }
1242
- return {
1243
- loaderData,
1244
- errors,
1245
- statusCode: statusCode || 200,
1246
- loaderHeaders
1247
- };
1248
- }
1249
- function findNearestBoundary(matches, routeId) {
1250
- let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
1251
- return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
1252
- }
1253
- function getShortCircuitMatches(routes) {
1254
- let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
1255
- id: `__shim-error-route__`
1256
- };
1257
- return {
1258
- matches: [
1259
- {
1260
- params: {},
1261
- pathname: "",
1262
- pathnameBase: "",
1263
- route
1264
- }
1265
- ],
1266
- route
1267
- };
1268
- }
1269
- function getInternalRouterError(status, {
1270
- pathname,
1271
- routeId,
1272
- method,
1273
- type,
1274
- message
1275
- } = {}) {
1276
- let statusText = "Unknown Server Error";
1277
- let errorMessage = "Unknown @remix-run/router error";
1278
- if (status === 400) {
1279
- statusText = "Bad Request";
1280
- if (method && pathname && routeId) {
1281
- 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.`;
1282
- } else if (type === "invalid-body") {
1283
- errorMessage = "Unable to encode submission body";
1284
- }
1285
- } else if (status === 403) {
1286
- statusText = "Forbidden";
1287
- errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
1288
- } else if (status === 404) {
1289
- statusText = "Not Found";
1290
- errorMessage = `No route matches URL "${pathname}"`;
1291
- } else if (status === 405) {
1292
- statusText = "Method Not Allowed";
1293
- if (method && pathname && routeId) {
1294
- 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.`;
1295
- } else if (method) {
1296
- errorMessage = `Invalid request method "${method.toUpperCase()}"`;
1297
- }
1298
- }
1299
- return new ErrorResponseImpl(
1300
- status || 500,
1301
- statusText,
1302
- new Error(errorMessage),
1303
- true
1304
- );
1305
- }
1306
- function isDataStrategyResult(result) {
1307
- return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" /* data */ || result.type === "error" /* error */);
1308
- }
1309
- function isRedirectDataStrategyResult(result) {
1310
- return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
1311
- }
1312
- function isErrorResult(result) {
1313
- return result.type === "error" /* error */;
1314
- }
1315
- function isRedirectResult(result) {
1316
- return (result && result.type) === "redirect" /* redirect */;
1317
- }
1318
- function isDataWithResponseInit(value) {
1319
- return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
1320
- }
1321
- function isResponse(value) {
1322
- return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
1323
- }
1324
- function isRedirectStatusCode(statusCode) {
1325
- return redirectStatusCodes.has(statusCode);
1326
- }
1327
- function isRedirectResponse(result) {
1328
- return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
1329
- }
1330
- function isValidMethod(method) {
1331
- return validRequestMethods.has(method.toUpperCase());
1332
- }
1333
- function isMutationMethod(method) {
1334
- return validMutationMethods.has(method.toUpperCase());
1335
- }
1336
- function hasNakedIndexQuery(search) {
1337
- return new URLSearchParams(search).getAll("index").some((v) => v === "");
1338
- }
1339
- function getTargetMatch(matches, location) {
1340
- let search = typeof location === "string" ? parsePath(location).search : location.search;
1341
- if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
1342
- return matches[matches.length - 1];
1343
- }
1344
- let pathMatches = getPathContributingMatches(matches);
1345
- return pathMatches[pathMatches.length - 1];
1346
- }
1347
- function mapRouteProperties(route) {
1348
- let updates = {
1349
- // Note: this check also occurs in createRoutesFromChildren so update
1350
- // there if you change this -- please and thank you!
1351
- hasErrorBoundary: route.hasErrorBoundary || route.ErrorBoundary != null || route.errorElement != null
1352
- };
1353
- if (route.Component) {
1354
- Object.assign(updates, {
1355
- element: React.createElement(route.Component),
1356
- Component: void 0
1357
- });
1358
- }
1359
- if (route.HydrateFallback) {
1360
- Object.assign(updates, {
1361
- hydrateFallbackElement: React.createElement(route.HydrateFallback),
1362
- HydrateFallback: void 0
1363
- });
1364
- }
1365
- if (route.ErrorBoundary) {
1366
- Object.assign(updates, {
1367
- errorElement: React.createElement(route.ErrorBoundary),
1368
- ErrorBoundary: void 0
1369
- });
1370
- }
1371
- return updates;
1372
- }
1373
-
1374
- // lib/dom/server.tsx
1375
- function createStaticHandler2(routes, opts) {
1376
- return createStaticHandler(routes, {
1377
- ...opts,
1378
- mapRouteProperties
1379
- });
1380
- }
1381
-
1382
- export { createStaticHandler2 as createStaticHandler, matchRoutes };