Skip to content

Commit 80cfc59

Browse files
committed
Add documentation for resolveDeferredHead function, and reorder the code
1 parent e64e881 commit 80cfc59

1 file changed

Lines changed: 161 additions & 152 deletions

File tree

‎packages/router-core/src/defer.ts‎

Lines changed: 161 additions & 152 deletions
Original file line numberDiff line numberDiff line change
@@ -26,70 +26,49 @@ export type DeferredPromiseState<T> =
2626
error: unknown
2727
}
2828

29-
function processDeferredArr(
30-
matchId: string,
31-
arr: Array<unknown>,
32-
field: string,
33-
shouldAwait: boolean,
34-
): Array<unknown> | Promise<Array<unknown>> {
35-
for (let i = 0; i < arr.length; i++) {
36-
if (!(arr[i] instanceof Promise)) continue
37-
return shouldAwait
38-
? resolveAsyncTail(matchId, arr, field, i)
39-
: filterPromisesSync(matchId, arr, field, i)
40-
}
41-
return arr
29+
export type DeferredPromise<T> = Promise<T> & {
30+
[TSR_DEFERRED_PROMISE]: DeferredPromiseState<T>
4231
}
4332

44-
function filterPromisesSync(
45-
matchId: string,
46-
arr: Array<unknown>,
47-
field: string,
48-
start: number,
49-
): Array<unknown> {
50-
const result = arr.slice(0, start)
51-
for (let i = start; i < arr.length; i++) {
52-
const entry = arr[i]
53-
if (!(entry instanceof Promise)) {
54-
result.push(entry)
55-
continue
56-
}
57-
// .catch silences the unhandled-rejection warning on entries we drop here;
58-
// the re-eval pass picks up the resolved value from the next snapshot.
59-
entry.catch((err) => {
60-
console.error(
61-
`Deferred ${field} promise rejected for "${matchId}|${field}|${i}":`,
62-
err,
63-
)
64-
})
33+
/**
34+
* Wrap a promise with a deferred state for use with `<Await>` and `useAwaited`.
35+
*
36+
* The returned promise is augmented with internal state (status/data/error)
37+
* so UI can read progress or suspend until it settles.
38+
*
39+
* @param _promise The promise to wrap.
40+
* @param options Optional config. Provide `serializeError` to customize how
41+
* errors are serialized for transfer.
42+
* @returns The same promise with attached deferred metadata.
43+
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/deferFunction
44+
*/
45+
export function defer<T>(
46+
_promise: Promise<T>,
47+
options?: {
48+
serializeError?: typeof defaultSerializeError
49+
},
50+
) {
51+
const promise = _promise as DeferredPromise<T>
52+
// this is already deferred promise
53+
if ((promise as any)[TSR_DEFERRED_PROMISE]) {
54+
return promise
6555
}
66-
return result
67-
}
56+
promise[TSR_DEFERRED_PROMISE] = { status: 'pending' }
6857

69-
async function resolveAsyncTail(
70-
matchId: string,
71-
arr: Array<unknown>,
72-
field: string,
73-
start: number,
74-
): Promise<Array<unknown>> {
75-
const result = arr.slice(0, start)
76-
for (let i = start; i < arr.length; i++) {
77-
const entry = arr[i]
78-
if (!(entry instanceof Promise)) {
79-
result.push(entry)
80-
continue
81-
}
82-
try {
83-
pushResolved(result, await entry)
84-
} catch (err) {
85-
// Drop the entry on rejection so one bad deferred doesn't poison the rest of the head.
86-
console.error(
87-
`Deferred ${field} promise rejected for "${matchId}|${field}|${i}":`,
88-
err,
89-
)
90-
}
91-
}
92-
return result
58+
promise
59+
.then((data) => {
60+
promise[TSR_DEFERRED_PROMISE].status = 'success'
61+
promise[TSR_DEFERRED_PROMISE].data = data
62+
})
63+
.catch((error) => {
64+
promise[TSR_DEFERRED_PROMISE].status = 'error'
65+
;(promise[TSR_DEFERRED_PROMISE] as any).error = {
66+
data: (options?.serializeError ?? defaultSerializeError)(error),
67+
__isServerError: true,
68+
}
69+
})
70+
71+
return promise
9372
}
9473

9574
interface DeferrableFields {
@@ -108,11 +87,65 @@ interface ResolvedFields {
10887
scripts: Array<unknown> | undefined
10988
}
11089

111-
function arrayHasPromise(arr: Array<unknown>): boolean {
112-
for (const e of arr) {
113-
if (e instanceof Promise) return true
90+
/**
91+
* Resolve the deferred entries inside a route's `head()` and `scripts()` output
92+
* for a single match.
93+
*
94+
* Returns the synchronous entries immediately. On the server the result is
95+
* awaited only for bots; otherwise deferred promises are filtered out of the
96+
* initial response and a re-evaluation pass is scheduled to update the match
97+
* once they settle.
98+
*/
99+
export function resolveDeferredHead(
100+
router: RouterCore<any, any, any, any>,
101+
matchId: string,
102+
route: AnyRoute,
103+
matches: Array<AnyRouteMatch>,
104+
headFnContent:
105+
| { meta?: unknown; links?: unknown; scripts?: unknown; styles?: unknown }
106+
| undefined,
107+
scriptsRaw: unknown,
108+
source: 'load' | 'hydrate',
109+
): ResolvedFields | Promise<ResolvedFields> {
110+
const metaArr = asArray(headFnContent?.meta)
111+
const linksArr = asArray(headFnContent?.links)
112+
const headScriptsArr = asArray(headFnContent?.scripts)
113+
const stylesArr = asArray(headFnContent?.styles)
114+
const scriptsArr = asArray(scriptsRaw)
115+
116+
// Fast path: skip resolve + re-eval. Each is a no-op when no field has a
117+
// deferred entry, but they still allocate per match.
118+
if (
119+
!(metaArr && arrayHasPromise(metaArr)) &&
120+
!(linksArr && arrayHasPromise(linksArr)) &&
121+
!(headScriptsArr && arrayHasPromise(headScriptsArr)) &&
122+
!(stylesArr && arrayHasPromise(stylesArr)) &&
123+
!(scriptsArr && arrayHasPromise(scriptsArr))
124+
) {
125+
return {
126+
meta: metaArr,
127+
links: linksArr,
128+
headScripts: headScriptsArr,
129+
styles: stylesArr,
130+
scripts: scriptsArr,
131+
}
114132
}
115-
return false
133+
134+
// On non-bot SSR / client loads the deferred entries are filtered out of the
135+
// initial result and only surface via the client-side re-eval pass. Server
136+
// skips: the response is already in flight.
137+
const fields: DeferrableFields = {
138+
meta: metaArr,
139+
links: linksArr,
140+
headScripts: headScriptsArr,
141+
styles: stylesArr,
142+
scripts: scriptsArr,
143+
}
144+
if (!router.serverSsr) {
145+
scheduleDeferredReEval(router, matchId, route, matches, fields, source)
146+
}
147+
148+
return processAllDeferredFields(router, matchId, fields)
116149
}
117150

118151
// Returns sync when no field actually went async, so the common path skips the
@@ -228,56 +261,77 @@ function scheduleDeferredReEval(
228261
})
229262
}
230263

231-
export function resolveDeferredHead(
232-
router: RouterCore<any, any, any, any>,
264+
function processDeferredArr(
233265
matchId: string,
234-
route: AnyRoute,
235-
matches: Array<AnyRouteMatch>,
236-
headFnContent:
237-
| { meta?: unknown; links?: unknown; scripts?: unknown; styles?: unknown }
238-
| undefined,
239-
scriptsRaw: unknown,
240-
source: 'load' | 'hydrate',
241-
): ResolvedFields | Promise<ResolvedFields> {
242-
const metaArr = asArray(headFnContent?.meta)
243-
const linksArr = asArray(headFnContent?.links)
244-
const headScriptsArr = asArray(headFnContent?.scripts)
245-
const stylesArr = asArray(headFnContent?.styles)
246-
const scriptsArr = asArray(scriptsRaw)
266+
arr: Array<unknown>,
267+
field: string,
268+
shouldAwait: boolean,
269+
): Array<unknown> | Promise<Array<unknown>> {
270+
for (let i = 0; i < arr.length; i++) {
271+
if (!(arr[i] instanceof Promise)) continue
272+
return shouldAwait
273+
? resolveAsyncTail(matchId, arr, field, i)
274+
: filterPromisesSync(matchId, arr, field, i)
275+
}
276+
return arr
277+
}
247278

248-
// Fast path: skip resolve + re-eval. Each is a no-op when no field has a
249-
// deferred entry, but they still allocate per match.
250-
if (
251-
!(metaArr && arrayHasPromise(metaArr)) &&
252-
!(linksArr && arrayHasPromise(linksArr)) &&
253-
!(headScriptsArr && arrayHasPromise(headScriptsArr)) &&
254-
!(stylesArr && arrayHasPromise(stylesArr)) &&
255-
!(scriptsArr && arrayHasPromise(scriptsArr))
256-
) {
257-
return {
258-
meta: metaArr,
259-
links: linksArr,
260-
headScripts: headScriptsArr,
261-
styles: stylesArr,
262-
scripts: scriptsArr,
279+
function filterPromisesSync(
280+
matchId: string,
281+
arr: Array<unknown>,
282+
field: string,
283+
start: number,
284+
): Array<unknown> {
285+
const result = arr.slice(0, start)
286+
for (let i = start; i < arr.length; i++) {
287+
const entry = arr[i]
288+
if (!(entry instanceof Promise)) {
289+
result.push(entry)
290+
continue
263291
}
292+
// .catch silences the unhandled-rejection warning on entries we drop here;
293+
// the re-eval pass picks up the resolved value from the next snapshot.
294+
entry.catch((err) => {
295+
console.error(
296+
`Deferred ${field} promise rejected for "${matchId}|${field}|${i}":`,
297+
err,
298+
)
299+
})
264300
}
301+
return result
302+
}
265303

266-
// On non-bot SSR / client loads the deferred entries are filtered out of the
267-
// initial result and only surface via the client-side re-eval pass. Server
268-
// skips: the response is already in flight.
269-
const fields: DeferrableFields = {
270-
meta: metaArr,
271-
links: linksArr,
272-
headScripts: headScriptsArr,
273-
styles: stylesArr,
274-
scripts: scriptsArr,
275-
}
276-
if (!router.serverSsr) {
277-
scheduleDeferredReEval(router, matchId, route, matches, fields, source)
304+
async function resolveAsyncTail(
305+
matchId: string,
306+
arr: Array<unknown>,
307+
field: string,
308+
start: number,
309+
): Promise<Array<unknown>> {
310+
const result = arr.slice(0, start)
311+
for (let i = start; i < arr.length; i++) {
312+
const entry = arr[i]
313+
if (!(entry instanceof Promise)) {
314+
result.push(entry)
315+
continue
316+
}
317+
try {
318+
pushResolved(result, await entry)
319+
} catch (err) {
320+
// Drop the entry on rejection so one bad deferred doesn't poison the rest of the head.
321+
console.error(
322+
`Deferred ${field} promise rejected for "${matchId}|${field}|${i}":`,
323+
err,
324+
)
325+
}
278326
}
327+
return result
328+
}
279329

280-
return processAllDeferredFields(router, matchId, fields)
330+
function arrayHasPromise(arr: Array<unknown>): boolean {
331+
for (const e of arr) {
332+
if (e instanceof Promise) return true
333+
}
334+
return false
281335
}
282336

283337
function collectPromises(
@@ -304,48 +358,3 @@ function pushResolved(result: Array<unknown>, resolved: unknown): void {
304358
result.push(resolved)
305359
}
306360
}
307-
308-
export type DeferredPromise<T> = Promise<T> & {
309-
[TSR_DEFERRED_PROMISE]: DeferredPromiseState<T>
310-
}
311-
312-
/**
313-
* Wrap a promise with a deferred state for use with `<Await>` and `useAwaited`.
314-
*
315-
* The returned promise is augmented with internal state (status/data/error)
316-
* so UI can read progress or suspend until it settles.
317-
*
318-
* @param _promise The promise to wrap.
319-
* @param options Optional config. Provide `serializeError` to customize how
320-
* errors are serialized for transfer.
321-
* @returns The same promise with attached deferred metadata.
322-
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/deferFunction
323-
*/
324-
export function defer<T>(
325-
_promise: Promise<T>,
326-
options?: {
327-
serializeError?: typeof defaultSerializeError
328-
},
329-
) {
330-
const promise = _promise as DeferredPromise<T>
331-
// this is already deferred promise
332-
if ((promise as any)[TSR_DEFERRED_PROMISE]) {
333-
return promise
334-
}
335-
promise[TSR_DEFERRED_PROMISE] = { status: 'pending' }
336-
337-
promise
338-
.then((data) => {
339-
promise[TSR_DEFERRED_PROMISE].status = 'success'
340-
promise[TSR_DEFERRED_PROMISE].data = data
341-
})
342-
.catch((error) => {
343-
promise[TSR_DEFERRED_PROMISE].status = 'error'
344-
;(promise[TSR_DEFERRED_PROMISE] as any).error = {
345-
data: (options?.serializeError ?? defaultSerializeError)(error),
346-
__isServerError: true,
347-
}
348-
})
349-
350-
return promise
351-
}

0 commit comments

Comments
 (0)