Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

load-server.ts

964 lines26.8 KB

1// Keep this filename free of a secondary extension so declaration generation
2// can rewrite relative imports for both ESM and CJS.
3import { isNotFound } from './not-found'
4import { isRedirect, redirect } from './redirect'
5import { rootRouteId } from './root'
6import { loadRouteChunk } from './load-client'
7import { waitForReason } from './await-signal'
8import {
9 getLocationChangeInfo,
10 lifecycleEnd,
11 runRouteLifecycle,
12} from './router'
13import type { ParsedLocation } from './location'
14import type { AnyRouteMatch } from './Matches'
15import type { NotFoundError } from './not-found'
16import type {
17 AnyRoute,
18 BeforeLoadContextOptions,
19 LoaderFnContext,
20 RouteContextOptions,
21 SsrContextOptions,
22} from './route'
23import type { AnyRedirect } from './redirect'
24import type { AnyRouter, SSROption } from './router'
25​
26declare const serverLanePhase: unique symbol
27​
28type ServerLane<TPhase extends 'matched' | 'contextualized' | 'reduced'> = {
29 readonly [serverLanePhase]: TPhase
30 location: ParsedLocation
31 matches: Array<AnyRouteMatch>
33​
34type MatchedLane = ServerLane<'matched'>
35​
36type IndexedOutcome = [index: number, outcome: LoaderOutcome, boundary?: number]
37​
38type ContextualizedLane = ServerLane<'contextualized'> & {
39 end: number
40 failure?: IndexedOutcome
42​
43type ReducedLane = ServerLane<'reduced'>
44​
45const SUCCESS = 0
46const ERROR = 1
47const NOT_FOUND = 2
48const REDIRECTED = 3
49const SKIPPED = 4
50​
51const MATCH_SETTLED_ABORT_REASON = Object.freeze({
52 name: 'AbortError',
53 message: 'TanStack Router aborted this server match because it settled.',
54})
55​
56const REDIRECT_ABORT_REASON = Object.freeze({
57 name: 'AbortError',
58 message: 'TanStack Router aborted this server match because of a redirect.',
59})
60​
61type LoaderOutcome =
62 | [typeof SUCCESS, data: unknown]
63 | [typeof ERROR, error: unknown]
64 | [typeof NOT_FOUND, error: NotFoundError]
65 | [typeof REDIRECTED, redirect: AnyRedirect]
66 | [typeof SKIPPED]
67​
68type LoaderTask = {
69 index: number
70 outcome: Promise<LoaderOutcome>
71 match: Promise<AnyRouteMatch>
73​
74export type ServerLoadResult =
75 | {
76 type: 'render'
77 status: 200 | 404 | 500
78 matches: Array<AnyRouteMatch>
79 }
80 | { type: 'redirect'; redirect: AnyRedirect }
81​
82function getRoute(router: AnyRouter, match: AnyRouteMatch): AnyRoute {
83 return router.routesById[match.routeId]
85​
86function normalize(value: unknown, rejected: boolean): LoaderOutcome {
87 if (isRedirect(value)) {
88 return [REDIRECTED, value]
89 }
90 if (isNotFound(value)) {
91 return [NOT_FOUND, value]
92 }
93 if (rejected && typeof (value as any)?.then === 'function') {
94 value = new Error('A Promise was thrown', { cause: value })
95 }
96 return rejected ? [ERROR, value] : [SUCCESS, value]
98​
99function normalizeError(
100 router: AnyRouter,
101 lane: { location: ParsedLocation },
102 route: AnyRoute,
103 cause: unknown,
104 signal?: AbortSignal,
105 notify = true,
106): LoaderOutcome {
107 signal?.throwIfAborted()
108 let outcome = normalize(cause, true)
109 if (outcome[0] !== ERROR) {
110 return materializeRedirect(router, lane, route, outcome, signal, notify)
111 }
112 try {
113 route.options.onError?.(outcome[1])
114 } catch (onErrorCause) {
115 outcome = normalize(onErrorCause, true)
116 }
117 signal?.throwIfAborted()
118 return materializeRedirect(router, lane, route, outcome, signal, notify)
120​
121function materializeRedirect(
122 router: AnyRouter,
123 lane: { location: ParsedLocation },
124 route: AnyRoute,
125 outcome: LoaderOutcome,
126 signal?: AbortSignal,
127 notify = true,
128): LoaderOutcome {
129 if (outcome[0] !== REDIRECTED) {
130 return outcome
131 }
132 signal?.throwIfAborted()
133 try {
134 outcome[1].options._fromLocation = lane.location
135 router.resolveRedirect(outcome[1])
136 signal?.throwIfAborted()
137 return outcome
138 } catch (cause) {
139 signal?.throwIfAborted()
140 return notify
141 ? normalizeError(router, lane, route, cause, signal, false)
142 : [ERROR, cause]
143 }
145​
146function maybe<TValue>(
147 value: TValue,
148 cause: unknown,
149): { status: 'success'; value: TValue } | { status: 'error'; error: unknown } {
150 if (cause !== undefined) {
151 return { status: 'error', error: cause }
152 }
153 return { status: 'success', value }
155​
156function navigateFrom(router: AnyRouter, location: ParsedLocation) {
157 return (options: any) =>
158 router.navigate({
159 ...options,
160 _fromLocation: location,
161 })
163​
164function waitFor<T>(value: Promise<T>, signal?: AbortSignal): Promise<T> {
165 return signal ? waitForReason(value, signal) : value
167​
168function resolveSsr(
169 router: AnyRouter,
170 lane: MatchedLane,
171 index: number,
172): SSROption | Promise<SSROption> {
173 const match = lane.matches[index]!
174 const route = getRoute(router, match)
175 const parentSsr = lane.matches[index - 1]?.ssr
176​
177 if (router.isShell()) {
178 return route.id === rootRouteId
179 }
180 if (parentSsr === false) {
181 return false
182 }
183​
184 const inherit = (value: SSROption): SSROption => {
185 return value === true && parentSsr === 'data-only' ? 'data-only' : value
186 }
187 const defaultSsr = router.options.defaultSsr ?? true
188 const inheritedDefault = inherit(defaultSsr)
189 // A functional override can fail. Establish the inherited policy first so
190 // the selected error boundary retains the route's actual renderability.
191 match.ssr = inheritedDefault
192 const option = route.options.ssr
193 if (option === undefined) {
194 return inheritedDefault
195 }
196 if (typeof option !== 'function') {
197 return inherit(option)
198 }
199​
200 const context: SsrContextOptions<any, any, any> = {
201 search: maybe(match.search, match.searchError),
202 params: maybe(match.params, match.paramsError),
203 location: lane.location,
204 matches: lane.matches.map((candidate) => ({
205 index: candidate.index,
206 pathname: candidate.pathname,
207 fullPath: candidate.fullPath,
208 staticData: candidate.staticData,
209 id: candidate.id,
210 routeId: candidate.routeId,
211 search: maybe(candidate.search, candidate.searchError),
212 params: maybe(candidate.params, candidate.paramsError),
213 ssr: candidate.ssr,
214 })),
215 }
216 try {
217 return Promise.resolve(option(context)).then((value) =>
218 inherit(value ?? defaultSsr),
219 )
220 } catch (cause) {
221 // Functional failures keep their asynchronous cancellation checkpoint.
222 return Promise.reject(cause)
223 }
225​
226function stampNotFound(
227 match: AnyRouteMatch,
228 outcome: LoaderOutcome,
229): LoaderOutcome {
230 if (outcome[0] === NOT_FOUND && !outcome[1].routeId) {
231 outcome[1].routeId = match.routeId
232 }
233 return outcome
235​
236async function contextualize(
237 router: AnyRouter,
238 lane: MatchedLane,
239 signal?: AbortSignal,
240): Promise<ContextualizedLane> {
241 const globalBoundary = lane.matches.findIndex((match) => match._notFound)
242 let end = globalBoundary < 0 ? lane.matches.length : globalBoundary + 1
243 let failure: IndexedOutcome | undefined
244 let parentContext: Record<string, unknown> = {
245 ...(router.options.context ?? {}),
246 }
247​
248 for (let index = 0; index < end; index++) {
249 const match = lane.matches[index]!
250 const route = getRoute(router, match)
251 try {
252 const ssr = resolveSsr(router, lane, index)
253 // Functional policies are assimilated into a native Promise above.
254 match.ssr = ssr instanceof Promise ? await ssr : ssr
255 } catch (cause) {
256 signal?.throwIfAborted()
257 failure = [
258 index,
259 stampNotFound(
260 match,
261 normalizeError(router, lane, route, cause, signal),
262 ),
263 ]
264 end = index
265 }
266 signal?.throwIfAborted()
267 if (failure?.[1][0] === REDIRECTED) {
268 break
269 }
270​
271 match.__beforeLoadContext = undefined
272 let context = parentContext
273 try {
274 let routeContext
275 if (route.options.context) {
276 const routeContextOptions: RouteContextOptions<
277 any,
278 any,
279 any,
280 any,
281 any
282 > = {
283 deps: match.loaderDeps,
284 params: match.params,
285 context: parentContext,
286 location: lane.location,
287 navigate: navigateFrom(router, lane.location),
288 buildLocation: router.buildLocation,
289 cause: match.cause,
290 abortController: match.abortController,
291 preload: false,
292 matches: lane.matches,
293 routeId: route.id,
294 }
295 routeContext = route.options.context(routeContextOptions) ?? undefined
296 }
297 context = {
298 ...parentContext,
299 ...routeContext,
300 }
301 match.context = context
302 } catch (cause) {
303 signal?.throwIfAborted()
304 if (!failure) {
305 failure = [
306 index,
307 stampNotFound(
308 match,
309 normalizeError(router, lane, route, cause, signal),
310 ),
311 ]
312 }
313 end = index
314 break
315 }
316 signal?.throwIfAborted()
317 if (failure) {
318 break
319 }
320 const validationError = match.paramsError ?? match.searchError
321 if (validationError !== undefined) {
322 failure = [
323 index,
324 stampNotFound(
325 match,
326 normalizeError(router, lane, route, validationError, signal),
327 ),
328 ]
329 end = index
330 break
331 }
332 signal?.throwIfAborted()
333​
334 if (match.ssr === false || !route.options.beforeLoad) {
335 parentContext = context
336 continue
337 }
338​
339 const abortController = match.abortController
340 const options: BeforeLoadContextOptions<
341 any,
342 any,
343 any,
344 any,
345 any,
346 any,
347 any,
348 any,
349 any
350 > = {
351 search: match.search,
352 abortController,
353 params: match.params,
354 preload: false,
355 context,
356 location: lane.location,
357 navigate: navigateFrom(router, lane.location),
358 buildLocation: router.buildLocation,
359 cause: match.cause,
360 matches: lane.matches,
361 routeId: route.id,
362 ...router.options.additionalContext,
363 }
364​
365 try {
366 const beforeLoadContext = await route.options.beforeLoad(options)
367 signal?.throwIfAborted()
368 const outcome = stampNotFound(
369 match,
370 materializeRedirect(
371 router,
372 lane,
373 route,
374 normalize(beforeLoadContext, false),
375 signal,
376 ),
377 )
378 if (outcome[0] !== SUCCESS) {
379 failure = [index, outcome]
380 end = index
381 break
382 }
383 match.__beforeLoadContext = beforeLoadContext
384 match.context = {
385 ...context,
386 ...beforeLoadContext,
387 }
388 parentContext = match.context
389 } catch (cause) {
390 signal?.throwIfAborted()
391 failure = [
392 index,
393 stampNotFound(
394 match,
395 normalizeError(router, lane, route, cause, signal),
396 ),
397 ]
398 end = index
399 break
400 }
401 }
402​
403 return {
404 location: lane.location,
405 matches: lane.matches,
406 end,
407 failure,
408 } as ContextualizedLane
410​
411function getLoaderContext(
412 router: AnyRouter,
413 lane: ContextualizedLane,
414 match: AnyRouteMatch,
415 route: AnyRoute,
416 index: number,
417 tasks: Array<LoaderTask>,
418): LoaderFnContext {
419 return {
420 params: match.params,
421 deps: match.loaderDeps,
422 preload: false,
423 parentMatchPromise: tasks[index - 1]?.match,
424 abortController: match.abortController,
425 context: match.context,
426 location: lane.location,
427 navigate: navigateFrom(router, lane.location),
428 cause: match.cause,
429 route,
430 ...router.options.additionalContext,
431 }
433​
434function createLoaderTask(
435 router: AnyRouter,
436 lane: ContextualizedLane,
437 index: number,
438 tasks: Array<LoaderTask>,
439 signal?: AbortSignal,
440): LoaderTask {
441 const match = lane.matches[index]!
442 const route = getRoute(router, match)
443 let outcome: Promise<LoaderOutcome>
444​
445 if (match.ssr === false) {
446 outcome = Promise.resolve<LoaderOutcome>([SKIPPED])
447 } else {
448 const routeLoader = route.options.loader
449 const loader =
450 typeof routeLoader === 'function' ? routeLoader : routeLoader?.handler
451 if (!loader) {
452 outcome = Promise.resolve<LoaderOutcome>([SUCCESS, undefined])
453 } else {
454 outcome = Promise.resolve()
455 .then(() =>
456 loader(getLoaderContext(router, lane, match, route, index, tasks)),
457 )
458 .then(
459 (result) => normalize(result, false),
460 (cause) => normalize(cause, true),
461 )
462 .then((result): LoaderOutcome => {
463 if (
464 signal?.aborted ||
465 match.abortController.signal.reason === REDIRECT_ABORT_REASON
466 ) {
467 return [SKIPPED]
468 }
469 if (result[0] === ERROR) {
470 result = normalizeError(router, lane, route, result[1], signal)
471 } else {
472 result = materializeRedirect(router, lane, route, result, signal)
473 }
474 return stampNotFound(match, result)
475 })
476 }
477 }
478​
479 const parentMatch = outcome.then((result) => {
480 const snapshot = { ...match }
481 if (result[0] === SUCCESS) {
482 snapshot.loaderData = result[1]
483 snapshot.status = 'success'
484 snapshot.error = undefined
485 snapshot.invalid = false
486 snapshot.isFetching = false
487 } else if (result[0] === ERROR) {
488 snapshot.status = 'error'
489 snapshot.error = result[1]
490 } else if (result[0] === NOT_FOUND) {
491 snapshot.status = 'notFound'
492 snapshot.error = result[1]
493 }
494 return snapshot
495 })
496​
497 return { index, outcome, match: parentMatch }
499​
500async function getNotFoundBoundary(
501 router: AnyRouter,
502 matches: Array<AnyRouteMatch>,
503 indexed: IndexedOutcome | undefined,
504 signal?: AbortSignal,
505 fallback = 0,
506): Promise<number> {
507 const cause = indexed?.[1][1] as NotFoundError | undefined
508 let index = cause?.routeId
509 ? matches.findIndex((match) => match.routeId === cause.routeId)
510 : (indexed?.[0] ?? matches.length - 1)
511 if (index < 0) {
512 index = 0
513 }
514 for (let candidate = index; candidate >= 0; candidate--) {
515 const route = getRoute(router, matches[candidate]!)
516 try {
517 const loading = loadRouteChunk(route, false)
518 if (loading) {
519 await loading
520 }
521 } catch {
522 signal?.throwIfAborted()
523 }
524 signal?.throwIfAborted()
525 if (route.options.notFoundComponent) {
526 return candidate
527 }
528 }
529 return cause?.routeId ? index : fallback
531​
532function abortMatches(
533 matches: Array<AnyRouteMatch>,
534 start = 0,
535 reason: unknown = MATCH_SETTLED_ABORT_REASON,
536): void {
537 for (let index = start; index < matches.length; index++) {
538 matches[index]!.abortController.abort(reason)
539 }
541​
542async function applyFailure(
543 router: AnyRouter,
544 lane: ContextualizedLane,
545 indexed: IndexedOutcome | undefined,
546 signal?: AbortSignal,
547): Promise<{ status: 200 | 404 | 500; boundary?: number; kind?: number }> {
548 if (!indexed) {
549 const boundary = lane.matches.findIndex((match) => match._notFound)
550 if (boundary >= 0) {
551 abortMatches(lane.matches, boundary + 1)
552 return { status: 404, boundary, kind: NOT_FOUND }
553 }
554 return { status: 200 }
555 }
556​
557 const [index, outcome] = indexed
558 if (outcome[0] === ERROR) {
559 const match = lane.matches[index]!
560 match._notFound = undefined
561 match.status = 'error'
562 match.error = outcome[1]
563 match.isFetching = false
564 abortMatches(lane.matches, index + 1)
565 return { status: 500, boundary: index, kind: ERROR }
566 }
567​
568 const boundary =
569 indexed[2] ??
570 (await getNotFoundBoundary(router, lane.matches, indexed, signal))
571 const match = lane.matches[boundary]!
572 const cause = outcome[1] as NotFoundError
573 cause.routeId = match.routeId
574 match._notFound = undefined
575 if (match.routeId === router.routeTree.id) {
576 match.status = 'success'
577 match._notFound = true
578 match.error = cause
579 } else {
580 match.status = 'notFound'
581 match.error = cause
582 }
583 match.isFetching = false
584 abortMatches(lane.matches, boundary + 1)
585 return { status: 404, boundary, kind: NOT_FOUND }
587​
588async function loadNormalChunks(
589 router: AnyRouter,
590 lane: ContextualizedLane,
591 end: number,
592 signal?: AbortSignal,
593): Promise<IndexedOutcome | undefined> {
594 const chunks: Array<IndexedOutcome | Promise<IndexedOutcome | undefined>> = []
595 for (let index = 0; index < lane.matches.length; index++) {
596 const match = lane.matches[index]!
597 if (index >= end || match.ssr !== true || match.status !== 'success') {
598 continue
599 }
600 const route = getRoute(router, match)
601 try {
602 const loading = loadRouteChunk(route)
603 if (loading) {
604 const chunk = loading.then(
605 () => {
606 signal?.throwIfAborted()
607 return undefined
608 },
609 (cause) => {
610 signal?.throwIfAborted()
611 return [
612 index,
613 stampNotFound(
614 match,
615 normalizeError(router, lane, route, cause, signal),
616 ),
617 ] as IndexedOutcome
618 },
619 )
620 // Route-order reduction can return before later chunks settle.
621 void chunk.catch(() => {})
622 chunks.push(chunk)
623 }
624 } catch (cause) {
625 signal?.throwIfAborted()
626 chunks.push([
627 index,
628 stampNotFound(
629 match,
630 normalizeError(router, lane, route, cause, signal),
631 ),
632 ])
633 }
634 }
635 for (const chunk of chunks) {
636 const indexed = Array.isArray(chunk) ? chunk : await chunk
637 if (indexed) {
638 return indexed
639 }
640 }
641 return undefined
643​
644async function projectLane(
645 router: AnyRouter,
646 lane: ReducedLane,
647 signal?: AbortSignal,
648): Promise<void> {
649 for (const match of lane.matches) {
650 const routeOptions = getRoute(router, match).options
651 if (routeOptions.head || routeOptions.scripts || routeOptions.headers) {
652 const context = {
653 ssr: router.options.ssr,
654 matches: lane.matches,
655 match,
656 params: match.params,
657 loaderData: match.loaderData,
658 }
659 try {
660 const [head, scripts, headers] = await Promise.all([
661 routeOptions.head?.(context),
662 routeOptions.scripts?.(context),
663 routeOptions.headers?.(context),
664 ])
665 signal?.throwIfAborted()
666 match.meta = head?.meta
667 match.links = head?.links
668 match.headScripts = head?.scripts
669 match.styles = head?.styles
670 match.scripts = scripts
671 match.headers = headers
672 } catch (cause) {
673 signal?.throwIfAborted()
674 console.error(cause)
675 }
676 }
677 if (match.ssr === false || match.status !== 'success' || match._notFound) {
678 break
679 }
680 }
682​
683async function executeServerLane(
684 router: AnyRouter,
685 location: ParsedLocation,
686 matchedMatches: Array<AnyRouteMatch>,
687 signal?: AbortSignal,
688): Promise<ServerLoadResult> {
689 const matched = {
690 location,
691 matches: matchedMatches.map((match) => ({
692 ...match,
693 __beforeLoadContext: undefined,
694 context: {},
695 isFetching: false,
696 abortController: new AbortController(),
697 })),
698 } as MatchedLane
699 const abortLane = () =>
700 abortMatches(
701 matched.matches,
702 0,
703 signal?.reason ?? MATCH_SETTLED_ABORT_REASON,
704 )
705 if (signal?.aborted) {
706 abortLane()
707 signal.throwIfAborted()
708 }
709 signal?.addEventListener('abort', abortLane, { once: true })
710​
711 try {
712 const plannedGlobalBoundary = matched.matches.findIndex(
713 (match) => match._notFound,
714 )
715 if (router.options.notFoundMode !== 'root' && plannedGlobalBoundary >= 0) {
716 const boundary = await getNotFoundBoundary(
717 router,
718 matched.matches,
719 undefined,
720 signal,
721 plannedGlobalBoundary,
722 )
723 if (boundary !== plannedGlobalBoundary) {
724 matched.matches[plannedGlobalBoundary]!._notFound = undefined
725 matched.matches[boundary]!._notFound = true
726 }
727 }
728 const lane = await contextualize(router, matched, signal)
729 signal?.throwIfAborted()
730​
731 let loaderEnd = lane.end
732 if (lane.failure?.[1][0] === REDIRECTED) {
733 loaderEnd = 0
734 } else if (lane.failure?.[1][0] === NOT_FOUND) {
735 lane.failure[2] = await getNotFoundBoundary(
736 router,
737 lane.matches,
738 lane.failure,
739 signal,
740 )
741 loaderEnd = Math.min(loaderEnd, lane.failure[2] + 1)
742 }
743​
744 const tasks: Array<LoaderTask> = []
745 for (let index = 0; index < loaderEnd; index++) {
746 const task = createLoaderTask(router, lane, index, tasks, signal)
747 tasks.push(task)
748 }
749​
750 let loaderFailure: IndexedOutcome | undefined
751 let control = lane.failure?.[1][0] === REDIRECTED ? lane.failure : undefined
752 try {
753 await Promise.all(
754 tasks.map((task) =>
755 task.outcome.then((loadedOutcome) => {
756 const match = lane.matches[task.index]!
757 const outcome = loadedOutcome
758 if (outcome[0] === SUCCESS) {
759 match.loaderData = outcome[1]
760 match.status = 'success'
761 match.error = undefined
762 match.invalid = false
763 match.isFetching = false
764 match.updatedAt = Date.now()
765 } else if (outcome[0] === REDIRECTED) {
766 control = [task.index, outcome]
767 throw control
768 } else {
769 // A selective-SSR skip must stay pending for hydration. Every
770 // settled server attempt is otherwise renderable unless
771 // reduction selects it as the lane's terminal failure.
772 if (match.ssr !== false) {
773 match.status = 'success'
774 match.error = undefined
775 match.invalid = true
776 match.isFetching = false
777 }
778 if (!loaderFailure && outcome[0] !== SKIPPED) {
779 loaderFailure = [task.index, outcome]
780 }
781 }
782 }),
783 ),
784 )
785 } catch (cause) {
786 if (!Array.isArray(cause)) {
787 throw cause
788 }
789 control = cause as IndexedOutcome
790 }
791 signal?.throwIfAborted()
792​
793 if (control?.[1][0] === REDIRECTED) {
794 abortMatches(lane.matches, 0, REDIRECT_ABORT_REASON)
795 return { type: 'redirect', redirect: control[1][1] }
796 }
797​
798 let failure = lane.failure ?? loaderFailure
799 const plannedBoundary = lane.matches.findIndex((match) => match._notFound)
800 let readinessEnd: number
801 if (failure) {
802 const outcomeEnd = (failure[2] ??=
803 failure[1][0] === NOT_FOUND
804 ? await getNotFoundBoundary(router, lane.matches, failure, signal)
805 : failure[0])
806 for (const task of tasks) {
807 if (task.index >= outcomeEnd) {
808 break
809 }
810 const outcome = await task.outcome
811 // Presence means a loader previously succeeded, even with `undefined`.
812 if (
813 outcome[0] !== SUCCESS &&
814 outcome[0] < REDIRECTED &&
815 !('loaderData' in lane.matches[task.index]!)
816 ) {
817 failure = [task.index, outcome]
818 failure[2] =
819 outcome[0] === NOT_FOUND
820 ? await getNotFoundBoundary(router, lane.matches, failure, signal)
821 : task.index
822 break
823 }
824 }
825 readinessEnd = failure[2]
826 } else {
827 readinessEnd = plannedBoundary < 0 ? lane.matches.length : plannedBoundary
828 }
829 const requiredFailure = await loadNormalChunks(
830 router,
831 lane,
832 readinessEnd,
833 signal,
834 )
835 signal?.throwIfAborted()
836 if (requiredFailure) {
837 if (requiredFailure[1][0] === REDIRECTED) {
838 abortMatches(lane.matches, 0, REDIRECT_ABORT_REASON)
839 return { type: 'redirect', redirect: requiredFailure[1][1] }
840 }
841 failure = requiredFailure
842 }
843​
844 const terminal = await applyFailure(router, lane, failure, signal)
845 if (terminal.boundary !== undefined) {
846 const match = lane.matches[terminal.boundary]!
847 if (match.ssr === true) {
848 const route = getRoute(router, match)
849 try {
850 if (terminal.kind === ERROR) {
851 await loadRouteChunk(route, 'errorComponent')
852 } else if (match._notFound) {
853 await Promise.all([
854 loadRouteChunk(route),
855 loadRouteChunk(route, 'notFoundComponent'),
856 ])
857 } else {
858 await loadRouteChunk(route, 'notFoundComponent')
859 }
860 } catch {}
861 signal?.throwIfAborted()
862 }
863 }
864​
865 signal?.throwIfAborted()
866 await projectLane(
867 router,
868 {
869 location: lane.location,
870 matches: lane.matches,
871 } as ReducedLane,
872 signal,
873 )
874 signal?.throwIfAborted()
875 // Deferred loader work can outlive this lane, and the request signal above
876 // only covers one way a response ends. SSR cleanup covers them all:
877 //
878 // - client disconnected -> abort (work may be pending)
879 // - serialization or lifetime timeout -> abort (a deferred value hung)
880 // - body disposed server-side (HEAD strip,
881 // middleware replaced the response) -> abort (never delivered)
882 // - plain response / `hydrate: false`: the
883 // loader data was never dehydrated -> abort (never consumed)
884 // - stream completed: every dehydrated value
885 // already settled -> nothing left to abort
886 //
887 // `settled` is false in exactly the first four cases.
888 router.serverSsr?.onCleanup((settled) => {
889 if (!settled) {
890 abortLane()
891 }
892 })
893 return { type: 'render', status: terminal.status, matches: lane.matches }
894 } finally {
895 signal?.removeEventListener('abort', abortLane)
896 }
898​
899type ServerLoadOptions = NonNullable<Parameters<AnyRouter['load']>[0]> & {
900 _signal?: AbortSignal
902​
903export async function loadServerRoute(
904 router: AnyRouter,
905 opts?: ServerLoadOptions,
906): Promise<void> {
907 if (!opts?._skipLocationUpdate) {
908 router.updateLatestLocation()
909 }
910 const next = router.latestLocation
911 const previous = router._committed
912 const previousEnd = router._lifecycleEnd
913 let result: ServerLoadResult
914 try {
915 const canonical = router.buildLocation({
916 to: next.pathname,
917 search: true,
918 params: true,
919 hash: true,
920 state: true,
921 _includeValidateSearch: true,
922 })
923 if (next.publicHref !== canonical.publicHref) {
924 const href = canonical.publicHref || '/'
925 throw redirect({ href })
926 }
927​
928 const fromLocation = router.stores.resolvedLocation.get()
929 const changeInfo = getLocationChangeInfo(next, fromLocation)
930 router.emit({ type: 'onBeforeNavigate', ...changeInfo })
931 router.emit({ type: 'onBeforeLoad', ...changeInfo })
932 opts?._signal?.throwIfAborted()
933 result = await waitFor(
934 executeServerLane(router, next, router.matchRoutes(next), opts?._signal),
935 opts?._signal,
936 )
937 opts?._signal?.throwIfAborted()
938 } catch (cause) {
939 opts?._signal?.throwIfAborted()
940 if (!isRedirect(cause)) {
941 throw cause
942 }
943 cause.options._fromLocation = next
944 result = { type: 'redirect', redirect: router.resolveRedirect(cause) }
945 }
946​
947 router._serverResult = result
948 let nextEnd = 0
949 router.batch(() => {
950 router.stores.location.set(next)
951 router.stores.status.set('idle')
952 if (result.type === 'render') {
953 router._committed = result.matches
954 nextEnd = router._lifecycleEnd = lifecycleEnd(result.matches)
955 router.stores.setMatches(result.matches)
956 router.stores.resolvedLocation.set(next)
957 }
958 })
959 if (result.type === 'render') {
960 runRouteLifecycle(router, previous, result.matches, previousEnd, nextEnd)
961 }
962 router._commitPromise?.resolve()
963 router._commitPromise = undefined