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

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