Open History to see the last commit
1import { AsyncLocalStorage } from 'node:async_hooks'
2import { createSerializationAdapter } from '@tanstack/react-router'
3import { RawStream } from '@tanstack/router-core'
4import { getStartContext } from '@tanstack/start-storage-context'
5import {
6 setOnClientReference,
7 createFromReadableStream as ssrDecode,
8} from 'virtual:tanstack-rsc-ssr-decode'
9import {
10 RENDERABLE_RSC,
11 RSC_SLOT_USAGES_STREAM,
12 SERVER_COMPONENT_CSS_HREFS,
13 SERVER_COMPONENT_JS_PRELOADS,
14 SERVER_COMPONENT_STREAM,
15 isServerComponent,
16} from './ServerComponentTypes'
17import { createRscProxy } from './createRscProxy'
18import { awaitLazyElements } from './awaitLazyElements'
19import { unwrapRscCssEnvelope } from './rscCssEnvelope'
20import type {
21 AnyCompositeComponent,
22 ServerComponentStream,
23} from './ServerComponentTypes'
24import type { RscDecodeResult, RscSsrHandler } from './rscSsrHandler'
25β
26// ===== SSR Handler Registration =====
27// This handler is registered on globalThis for the RSC environment to access.
28// The RSC env calls these functions during loader execution to pre-decode streams
29// and create renderable proxies.
30//
31// This MUST happen in a module without 'use client' directive.
32// Modules with 'use client' may be transformed to client references in the
33// SSR environment when RSC is enabled, preventing the side effect from running.
34β
35// AsyncLocalStorage for decode-scoped proxy asset collectors.
36// Client-reference deps stay on the decoded RSC proxy so unused streams don't
37// emit global request assets. CSS marker links are collected for all adapters
38// because the decoded envelope is unwrapped before SSR render.
39const proxyCssCollectorStorage = new AsyncLocalStorage<Set<string>>()
40const proxyJsCollectorStorage = new AsyncLocalStorage<Set<string>>()
41β
42setOnClientReference(
43 ({
44 deps,
45 runtime,
46 }: {
47 deps: { js: Array<string>; css: Array<string> }
48 runtime?: 'rsbuild'
49 }) => {
50 const cssCollector = proxyCssCollectorStorage.getStore()
51 if (cssCollector) {
52 for (const href of deps.css) {
53 cssCollector.add(href)
54 }
55 }
56β
57 const jsCollector = proxyJsCollectorStorage.getStore()
58 if (jsCollector) {
59 for (const href of deps.js) {
60 jsCollector.add(href)
61 }
62 }
63β
64 if (runtime === 'rsbuild' || cssCollector || jsCollector) {
65 return
66 }
67β
68 const ctx = getStartContext({ throwIfNotFound: false })
69β
70 // Non-Rsbuild adapters emit decoded client-reference assets through the
71 // request manifest.
72 if (!ctx || (!deps.js.length && !deps.css.length)) {
73 return
74 }
75β
76 if (!ctx.requestAssets) ctx.requestAssets = {}
77 const seenHrefs = new Set<string>()
78 for (const preload of ctx.requestAssets.preloads ?? []) {
79 seenHrefs.add(typeof preload === 'string' ? preload : preload.href)
80 }
81 for (const stylesheet of ctx.requestAssets.css ?? []) {
82 seenHrefs.add(
83 typeof stylesheet === 'string' ? stylesheet : stylesheet.href,
84 )
85 }
86β
87 let nextPreloads: typeof ctx.requestAssets.preloads | undefined
88 for (const href of deps.js) {
89 if (seenHrefs.has(href)) continue
90 seenHrefs.add(href)
91 if (!nextPreloads) {
92 nextPreloads = ctx.requestAssets.preloads
93 ? ctx.requestAssets.preloads.slice()
94 : []
95 }
96 nextPreloads.push(href)
97 }
98 if (nextPreloads) {
99 ctx.requestAssets.preloads = nextPreloads
100 }
101β
102 let nextCss: typeof ctx.requestAssets.css | undefined
103 for (const href of deps.css) {
104 if (seenHrefs.has(href)) continue
105 seenHrefs.add(href)
106 if (!nextCss) {
107 nextCss = ctx.requestAssets.css ? ctx.requestAssets.css.slice() : []
108 }
109 nextCss.push(href)
110 }
111 if (nextCss) {
112 ctx.requestAssets.css = nextCss
113 }
114 },
115)
116β
117const ssrHandler: RscSsrHandler = {
118 async decode(stream: ServerComponentStream): Promise<RscDecodeResult> {
119 const readableStream = stream.createReplayStream()
120β
121 // Create a collector for this decode operation.
122 // Run the decode in an AsyncLocalStorage context so the onClientReference
123 // callback can write to this specific collector even with parallel decodes.
124 const proxyCssCollector = new Set<string>()
125 const proxyJsCollector = new Set<string>()
126β
127 return proxyCssCollectorStorage.run(proxyCssCollector, async () => {
128 return proxyJsCollectorStorage.run(proxyJsCollector, async () => {
129 const decodedTree = await ssrDecode(readableStream)
130 await awaitLazyElements(decodedTree, (href) => {
131 proxyCssCollector.add(href)
132 })
133β
134 return {
135 tree: unwrapRscCssEnvelope(decodedTree),
136 cssHrefs: proxyCssCollector.size > 0 ? proxyCssCollector : undefined,
137 jsPreloads: proxyJsCollector.size > 0 ? proxyJsCollector : undefined,
138 }
139 })
140 })
141 },
142β
143 createRenderableProxy(stream, decoded): any {
144 return createRscProxy(() => decoded.tree, {
145 stream,
146 cssHrefs: decoded.cssHrefs,
147 jsPreloads: decoded.jsPreloads,
148 renderable: true,
149 })
150 },
151β
152 createCompositeProxy(
153 stream,
154 decoded,
155 slotUsagesStream,
156 ): AnyCompositeComponent {
157 const proxy = createRscProxy(() => decoded.tree, {
158 stream,
159 cssHrefs: decoded.cssHrefs,
160 jsPreloads: decoded.jsPreloads,
161 renderable: false,
162 slotUsagesStream,
163 })
164 return proxy
165 },
166}
167β
168// Register SSR handler on globalThis for RSC environment to access.
169globalThis.__RSC_SSR__ = ssrHandler
170β
171// ===== End SSR Handler Registration =====
172β
173/**
174 * Helper to check if a value is a renderable RSC (from renderServerComponent).
175 * The value can be either an object (proxy target) or a function (stub for server functions).
176 */
177function isRenderableRsc(value: unknown): boolean {
178 if (value === null || value === undefined) return false
179 if (typeof value !== 'object' && typeof value !== 'function') return false
180 return RENDERABLE_RSC in value && (value as any)[RENDERABLE_RSC] === true
181}
182β
183/**
184 * Server-side serialization adapter for RSC (renderable + composite).
185 */
186const adapter = createSerializationAdapter({
187 key: '$RSC',
188 test: (value: unknown): value is AnyCompositeComponent => {
189 return isServerComponent(value)
190 },
191 toSerializable: (component: AnyCompositeComponent) => {
192 const stream = component[SERVER_COMPONENT_STREAM]!.createReplayStream()
193β
194 const kind = isRenderableRsc(component) ? 'renderable' : 'composite'
195 const jsPreloads = component[SERVER_COMPONENT_JS_PRELOADS]
196 const cssHrefs = component[SERVER_COMPONENT_CSS_HREFS]
197 // `cssHrefs` can also come from loadCss() marker links. Client-reference
198 // collection fills `jsPreloads`, so that gates per-stream serialization.
199 const serializedAssetDeps = jsPreloads?.size
200 ? {
201 ...(cssHrefs?.size ? { cssHrefs: Array.from(cssHrefs) } : {}),
202 jsPreloads: Array.from(jsPreloads),
203 }
204 : {}
205β
206 const slotUsagesStream =
207 process.env.NODE_ENV === 'development' &&
208 kind === 'composite' &&
209 RSC_SLOT_USAGES_STREAM in component
210 ? ((component as any)[RSC_SLOT_USAGES_STREAM] as unknown as
211 | ReadableStream<any>
212 | undefined)
213 : undefined
214β
215 return {
216 kind,
217 stream: new RawStream(stream, { hint: 'text' }),
218 slotUsagesStream,
219 ...serializedAssetDeps,
220 }
221 },
222 fromSerializable: (): never => {
223 throw new Error('Server should never deserialize RSC data')
224 },
225})
226β
227/**
228 * Factory function for server-side RSC serialization adapter.
229 */
230export const rscSerializationAdapter = () => [adapter]