UNPKG

2.83 kBJavaScriptView Raw
1/**
2 * react-router v8.0.0
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11import { redirect, redirectDocument, replace } from "../router/utils.js";
12import { SingleFetchRedirectSymbol, decodeViaTurboStream } from "../dom/ssr/single-fetch.js";
13import invariant from "./invariant.js";
14import { callRouteHandler } from "./data.js";
15import { getBuildTimeHeader } from "./dev.js";
16//#region lib/server-runtime/routes.ts
17function groupRoutesByParentId(manifest) {
18 let routes = {};
19 Object.values(manifest).forEach((route) => {
20 if (route) {
21 let parentId = route.parentId || "";
22 if (!routes[parentId]) routes[parentId] = [];
23 routes[parentId].push(route);
24 }
25 });
26 return routes;
27}
28function createStaticHandlerDataRoutes(manifest, parentId = "", routesByParentId = groupRoutesByParentId(manifest)) {
29 return (routesByParentId[parentId] || []).map((route) => {
30 let commonRoute = {
31 id: route.id,
32 path: route.path,
33 middleware: route.module.middleware,
34 loader: route.module.loader ? async (args) => {
35 let preRenderedData = getBuildTimeHeader(args.request, "X-React-Router-Prerender-Data");
36 if (preRenderedData != null) {
37 let encoded = preRenderedData ? decodeURI(preRenderedData) : preRenderedData;
38 invariant(encoded, "Missing prerendered data for route");
39 let uint8array = new TextEncoder().encode(encoded);
40 let data = (await decodeViaTurboStream(new ReadableStream({ start(controller) {
41 controller.enqueue(uint8array);
42 controller.close();
43 } }), global)).value;
44 if (data && SingleFetchRedirectSymbol in data) {
45 let result = data[SingleFetchRedirectSymbol];
46 let init = { status: result.status };
47 if (result.reload) throw redirectDocument(result.redirect, init);
48 else if (result.replace) throw replace(result.redirect, init);
49 else throw redirect(result.redirect, init);
50 } else {
51 invariant(data && route.id in data, "Unable to decode prerendered data");
52 let result = data[route.id];
53 invariant("data" in result, "Unable to process prerendered data");
54 return result.data;
55 }
56 }
57 return await callRouteHandler(route.module.loader, args);
58 } : void 0,
59 action: route.module.action ? (args) => callRouteHandler(route.module.action, args) : void 0,
60 ErrorBoundary: route.id === "root" || route.module.ErrorBoundary != null ? () => null : void 0,
61 handle: route.module.handle
62 };
63 return route.index ? {
64 index: true,
65 ...commonRoute
66 } : {
67 caseSensitive: route.caseSensitive,
68 children: createStaticHandlerDataRoutes(manifest, route.id, routesByParentId),
69 ...commonRoute
70 };
71 });
72}
73//#endregion
74export { createStaticHandlerDataRoutes };