-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathroutes.tsx
638 lines (584 loc) · 19.4 KB
/
routes.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
import * as React from "react";
import type { HydrationState } from "@remix-run/router";
import { UNSAFE_ErrorResponseImpl as ErrorResponse } from "@remix-run/router";
import type {
ActionFunctionArgs,
LoaderFunctionArgs,
DataRouteObject,
ShouldRevalidateFunction,
} from "react-router-dom";
import { redirect, useRouteError } from "react-router-dom";
import type { RouteModule, RouteModules } from "./routeModules";
import { loadRouteModule } from "./routeModules";
import {
fetchData,
isCatchResponse,
isDeferredData,
isDeferredResponse,
isRedirectResponse,
isResponse,
parseDeferredReadableStream,
} from "./data";
import type { FutureConfig } from "./entry";
import { prefetchStyleLinks } from "./links";
import { RemixRootDefaultErrorBoundary } from "./errorBoundaries";
import { RemixRootDefaultHydrateFallback } from "./fallback";
import invariant from "./invariant";
export interface RouteManifest<Route> {
[routeId: string]: Route;
}
// NOTE: make sure to change the Route in server-runtime if you change this
interface Route {
index?: boolean;
caseSensitive?: boolean;
id: string;
parentId?: string;
path?: string;
}
// NOTE: make sure to change the EntryRoute in server-runtime if you change this
export interface EntryRoute extends Route {
hasAction: boolean;
hasLoader: boolean;
hasClientAction: boolean;
hasClientLoader: boolean;
hasErrorBoundary: boolean;
imports?: string[];
css?: string[];
module: string;
parentId?: string;
}
// Create a map of routes by parentId to use recursively instead of
// repeatedly filtering the manifest.
function groupRoutesByParentId(manifest: RouteManifest<EntryRoute>) {
let routes: Record<string, Omit<EntryRoute, "children">[]> = {};
Object.values(manifest).forEach((route) => {
let parentId = route.parentId || "";
if (!routes[parentId]) {
routes[parentId] = [];
}
routes[parentId].push(route);
});
return routes;
}
function getRouteComponents(
route: EntryRoute,
routeModule: RouteModule,
isSpaMode: boolean
) {
let Component = getRouteModuleComponent(routeModule);
// HydrateFallback can only exist on the root route in SPA Mode
let HydrateFallback =
routeModule.HydrateFallback && (!isSpaMode || route.id === "root")
? routeModule.HydrateFallback
: route.id === "root"
? RemixRootDefaultHydrateFallback
: undefined;
let ErrorBoundary = routeModule.ErrorBoundary
? routeModule.ErrorBoundary
: route.id === "root"
? () => <RemixRootDefaultErrorBoundary error={useRouteError()} />
: undefined;
if (route.id === "root" && routeModule.Layout) {
return {
...(Component
? {
element: (
<routeModule.Layout>
<Component />
</routeModule.Layout>
),
}
: { Component }),
...(ErrorBoundary
? {
errorElement: (
<routeModule.Layout>
<ErrorBoundary />
</routeModule.Layout>
),
}
: { ErrorBoundary }),
...(HydrateFallback
? {
hydrateFallbackElement: (
<routeModule.Layout>
<HydrateFallback />
</routeModule.Layout>
),
}
: { HydrateFallback }),
};
}
return { Component, ErrorBoundary, HydrateFallback };
}
export function createServerRoutes(
manifest: RouteManifest<EntryRoute>,
routeModules: RouteModules,
future: FutureConfig,
isSpaMode: boolean,
parentId: string = "",
routesByParentId: Record<
string,
Omit<EntryRoute, "children">[]
> = groupRoutesByParentId(manifest),
spaModeLazyPromise = Promise.resolve({ Component: () => null })
): DataRouteObject[] {
return (routesByParentId[parentId] || []).map((route) => {
let routeModule = routeModules[route.id];
invariant(
routeModule,
"No `routeModule` available to create server routes"
);
let dataRoute: DataRouteObject = {
...getRouteComponents(route, routeModule, isSpaMode),
caseSensitive: route.caseSensitive,
id: route.id,
index: route.index,
path: route.path,
handle: routeModule.handle,
// For SPA Mode, all routes are lazy except root. However we tell the
// router root is also lazy here too since we don't need a full
// implementation - we just need a `lazy` prop to tell the RR rendering
// where to stop which is always at the root route in SPA mode
lazy: isSpaMode ? () => spaModeLazyPromise : undefined,
// For partial hydration rendering, we need to indicate when the route
// has a loader/clientLoader, but it won't ever be called during the static
// render, so just give it a no-op function so we can render down to the
// proper fallback
loader: route.hasLoader || route.hasClientLoader ? () => null : undefined,
// We don't need action/shouldRevalidate on these routes since they're
// for a static render
};
let children = createServerRoutes(
manifest,
routeModules,
future,
isSpaMode,
route.id,
routesByParentId,
spaModeLazyPromise
);
if (children.length > 0) dataRoute.children = children;
return dataRoute;
});
}
export function createClientRoutesWithHMRRevalidationOptOut(
needsRevalidation: Set<string>,
manifest: RouteManifest<EntryRoute>,
routeModulesCache: RouteModules,
initialState: HydrationState,
future: FutureConfig,
isSpaMode: boolean
) {
return createClientRoutes(
manifest,
routeModulesCache,
initialState,
future,
isSpaMode,
"",
groupRoutesByParentId(manifest),
needsRevalidation
);
}
function preventInvalidServerHandlerCall(
type: "action" | "loader",
route: Omit<EntryRoute, "children">,
isSpaMode: boolean
) {
if (isSpaMode) {
let fn = type === "action" ? "serverAction()" : "serverLoader()";
let msg = `You cannot call ${fn} in SPA Mode (routeId: "${route.id}")`;
console.error(msg);
throw new ErrorResponse(400, "Bad Request", new Error(msg), true);
}
let fn = type === "action" ? "serverAction()" : "serverLoader()";
let msg =
`You are trying to call ${fn} on a route that does not have a server ` +
`${type} (routeId: "${route.id}")`;
if (
(type === "loader" && !route.hasLoader) ||
(type === "action" && !route.hasAction)
) {
console.error(msg);
throw new ErrorResponse(400, "Bad Request", new Error(msg), true);
}
}
function noActionDefinedError(
type: "action" | "clientAction",
routeId: string
) {
let article = type === "clientAction" ? "a" : "an";
let msg =
`Route "${routeId}" does not have ${article} ${type}, but you are trying to ` +
`submit to it. To fix this, please add ${article} \`${type}\` function to the route`;
console.error(msg);
throw new ErrorResponse(405, "Method Not Allowed", new Error(msg), true);
}
export function createClientRoutes(
manifest: RouteManifest<EntryRoute>,
routeModulesCache: RouteModules,
initialState: HydrationState | null,
future: FutureConfig,
isSpaMode: boolean,
parentId: string = "",
routesByParentId: Record<
string,
Omit<EntryRoute, "children">[]
> = groupRoutesByParentId(manifest),
needsRevalidation?: Set<string>
): DataRouteObject[] {
return (routesByParentId[parentId] || []).map((route) => {
let routeModule = routeModulesCache[route.id];
// Fetch data from the server either via single fetch or the standard `?_data`
// request. Unwrap it when called via `serverLoader`/`serverAction` in a
// client handler, otherwise return the raw response for the router to unwrap
async function fetchServerHandlerAndMaybeUnwrap(
request: Request,
unwrap: boolean,
singleFetch: unknown
) {
if (typeof singleFetch === "function") {
let result = await singleFetch();
return result;
}
let result = await fetchServerHandler(request, route);
return unwrap ? unwrapServerResponse(result) : result;
}
function fetchServerLoader(
request: Request,
unwrap: boolean,
singleFetch: unknown
) {
if (!route.hasLoader) return Promise.resolve(null);
return fetchServerHandlerAndMaybeUnwrap(request, unwrap, singleFetch);
}
function fetchServerAction(
request: Request,
unwrap: boolean,
singleFetch: unknown
) {
if (!route.hasAction) {
throw noActionDefinedError("action", route.id);
}
return fetchServerHandlerAndMaybeUnwrap(request, unwrap, singleFetch);
}
async function prefetchStylesAndCallHandler(
handler: () => Promise<unknown>
) {
// Only prefetch links if we exist in the routeModulesCache (critical modules
// and navigating back to pages previously loaded via route.lazy). Initial
// execution of route.lazy (when the module is not in the cache) will handle
// prefetching style links via loadRouteModuleWithBlockingLinks.
let cachedModule = routeModulesCache[route.id];
let linkPrefetchPromise = cachedModule
? prefetchStyleLinks(route, cachedModule)
: Promise.resolve();
try {
return handler();
} finally {
await linkPrefetchPromise;
}
}
let dataRoute: DataRouteObject = {
id: route.id,
index: route.index,
path: route.path,
};
if (routeModule) {
// Use critical path modules directly
Object.assign(dataRoute, {
...dataRoute,
...getRouteComponents(route, routeModule, isSpaMode),
handle: routeModule.handle,
shouldRevalidate: needsRevalidation
? wrapShouldRevalidateForHdr(
route.id,
routeModule.shouldRevalidate,
needsRevalidation
)
: routeModule.shouldRevalidate,
});
let initialData = initialState?.loaderData?.[route.id];
let initialError = initialState?.errors?.[route.id];
let isHydrationRequest =
needsRevalidation == null &&
(routeModule.clientLoader?.hydrate === true || !route.hasLoader);
dataRoute.loader = async (
{ request, params }: LoaderFunctionArgs,
singleFetch?: unknown
) => {
try {
let result = await prefetchStylesAndCallHandler(async () => {
invariant(
routeModule,
"No `routeModule` available for critical-route loader"
);
if (!routeModule.clientLoader) {
if (isSpaMode) return null;
// Call the server when no client loader exists
return fetchServerLoader(request, false, singleFetch);
}
return routeModule.clientLoader({
request,
params,
async serverLoader() {
preventInvalidServerHandlerCall("loader", route, isSpaMode);
// On the first call, resolve with the server result
if (isHydrationRequest) {
if (initialError !== undefined) {
throw initialError;
}
return initialData;
}
// Call the server loader for client-side navigations
return fetchServerLoader(request, true, singleFetch);
},
});
});
return result;
} finally {
// Whether or not the user calls `serverLoader`, we only let this
// stick around as true for one loader call
isHydrationRequest = false;
}
};
// Let React Router know whether to run this on hydration
dataRoute.loader.hydrate = shouldHydrateRouteLoader(
route,
routeModule,
isSpaMode
);
dataRoute.action = (
{ request, params }: ActionFunctionArgs,
singleFetch?: unknown
) => {
return prefetchStylesAndCallHandler(async () => {
invariant(
routeModule,
"No `routeModule` available for critical-route action"
);
if (!routeModule.clientAction) {
if (isSpaMode) {
throw noActionDefinedError("clientAction", route.id);
}
return fetchServerAction(request, false, singleFetch);
}
return routeModule.clientAction({
request,
params,
async serverAction() {
preventInvalidServerHandlerCall("action", route, isSpaMode);
return fetchServerAction(request, true, singleFetch);
},
});
});
};
} else {
// If the lazy route does not have a client loader/action we want to call
// the server loader/action in parallel with the module load so we add
// loader/action as static props on the route
if (!route.hasClientLoader) {
dataRoute.loader = (
{ request }: LoaderFunctionArgs,
singleFetch?: unknown
) =>
prefetchStylesAndCallHandler(() => {
if (isSpaMode) return Promise.resolve(null);
return fetchServerLoader(request, false, singleFetch);
});
}
if (!route.hasClientAction) {
dataRoute.action = (
{ request }: ActionFunctionArgs,
singleFetch?: unknown
) =>
prefetchStylesAndCallHandler(() => {
if (isSpaMode) {
throw noActionDefinedError("clientAction", route.id);
}
return fetchServerAction(request, false, singleFetch);
});
}
// Load all other modules via route.lazy()
dataRoute.lazy = async () => {
let mod = await loadRouteModuleWithBlockingLinks(
route,
routeModulesCache
);
let lazyRoute: Partial<DataRouteObject> = { ...mod };
if (mod.clientLoader) {
let clientLoader = mod.clientLoader;
lazyRoute.loader = (
args: LoaderFunctionArgs,
singleFetch?: unknown
) =>
clientLoader({
...args,
async serverLoader() {
preventInvalidServerHandlerCall("loader", route, isSpaMode);
return fetchServerLoader(args.request, true, singleFetch);
},
});
}
if (mod.clientAction) {
let clientAction = mod.clientAction;
lazyRoute.action = (
args: ActionFunctionArgs,
singleFetch?: unknown
) =>
clientAction({
...args,
async serverAction() {
preventInvalidServerHandlerCall("action", route, isSpaMode);
return fetchServerAction(args.request, true, singleFetch);
},
});
}
if (needsRevalidation) {
lazyRoute.shouldRevalidate = wrapShouldRevalidateForHdr(
route.id,
mod.shouldRevalidate,
needsRevalidation
);
}
return {
...(lazyRoute.loader ? { loader: lazyRoute.loader } : {}),
...(lazyRoute.action ? { action: lazyRoute.action } : {}),
hasErrorBoundary: lazyRoute.hasErrorBoundary,
shouldRevalidate: lazyRoute.shouldRevalidate,
handle: lazyRoute.handle,
// No need to wrap these in layout since the root route is never
// loaded via route.lazy()
Component: lazyRoute.Component,
ErrorBoundary: lazyRoute.ErrorBoundary,
};
};
}
let children = createClientRoutes(
manifest,
routeModulesCache,
initialState,
future,
isSpaMode,
route.id,
routesByParentId,
needsRevalidation
);
if (children.length > 0) dataRoute.children = children;
return dataRoute;
});
}
// When an HMR / HDR update happens we opt out of all user-defined
// revalidation logic and force a revalidation on the first call
function wrapShouldRevalidateForHdr(
routeId: string,
routeShouldRevalidate: ShouldRevalidateFunction | undefined,
needsRevalidation: Set<string>
): ShouldRevalidateFunction {
let handledRevalidation = false;
return (arg) => {
if (!handledRevalidation) {
handledRevalidation = true;
return needsRevalidation.has(routeId);
}
return routeShouldRevalidate
? routeShouldRevalidate(arg)
: arg.defaultShouldRevalidate;
};
}
async function loadRouteModuleWithBlockingLinks(
route: EntryRoute,
routeModules: RouteModules
) {
let routeModule = await loadRouteModule(route, routeModules);
await prefetchStyleLinks(route, routeModule);
// Include all `browserSafeRouteExports` fields, except `HydrateFallback`
// since those aren't used on lazily loaded routes
return {
Component: getRouteModuleComponent(routeModule),
ErrorBoundary: routeModule.ErrorBoundary,
clientAction: routeModule.clientAction,
clientLoader: routeModule.clientLoader,
handle: routeModule.handle,
links: routeModule.links,
meta: routeModule.meta,
shouldRevalidate: routeModule.shouldRevalidate,
};
}
async function fetchServerHandler(request: Request, route: EntryRoute) {
let result = await fetchData(request, route.id);
if (result instanceof Error) {
throw result;
}
if (isRedirectResponse(result)) {
throw getRedirect(result);
}
if (isCatchResponse(result)) {
throw result;
}
if (isDeferredResponse(result) && result.body) {
return await parseDeferredReadableStream(result.body);
}
return result;
}
function unwrapServerResponse(
result: Awaited<ReturnType<typeof fetchServerHandler>> | null
) {
if (isDeferredData(result)) {
return result.data;
}
if (isResponse(result)) {
let contentType = result.headers.get("Content-Type");
// Check between word boundaries instead of startsWith() due to the last
// paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type
if (contentType && /\bapplication\/json\b/.test(contentType)) {
return result.json();
} else {
return result.text();
}
}
return result;
}
function getRedirect(response: Response): Response {
let status = parseInt(response.headers.get("X-Remix-Status")!, 10) || 302;
let url = response.headers.get("X-Remix-Redirect")!;
let headers: Record<string, string> = {};
let revalidate = response.headers.get("X-Remix-Revalidate");
if (revalidate) {
headers["X-Remix-Revalidate"] = revalidate;
}
let reloadDocument = response.headers.get("X-Remix-Reload-Document");
if (reloadDocument) {
headers["X-Remix-Reload-Document"] = reloadDocument;
}
let replace = response.headers.get("X-Remix-Replace");
if (replace) {
headers["X-Remix-Replace"] = replace;
}
return redirect(url, { status, headers });
}
// Our compiler generates the default export as `{}` when no default is provided,
// which can lead us to trying to use that as a Component in RR and calling
// createElement on it. Patching here as a quick fix and hoping it's no longer
// an issue in Vite.
function getRouteModuleComponent(routeModule: RouteModule) {
if (routeModule.default == null) return undefined;
let isEmptyObject =
typeof routeModule.default === "object" &&
Object.keys(routeModule.default).length === 0;
if (!isEmptyObject) {
return routeModule.default;
}
}
export function shouldHydrateRouteLoader(
route: EntryRoute,
routeModule: RouteModule,
isSpaMode: boolean
) {
return (
(isSpaMode && route.id !== "root") ||
(routeModule.clientLoader != null &&
(routeModule.clientLoader.hydrate === true || route.hasLoader !== true))
);
}