forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
root-render.tsx
355 lines (316 loc) · 10.1 KB
/
root-render.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
import type { IncomingMessage, ServerResponse } from 'http'
import type { LoadComponentsReturnType } from './load-components'
import React from 'react'
import { stringify as stringifyQuery } from 'querystring'
import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-webpack'
import { renderToReadableStream } from 'next/dist/compiled/react-server-dom-webpack/writer.browser.server'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
import { NextParsedUrlQuery } from './request-meta'
import RenderResult from './render-result'
import {
readableStreamTee,
encodeText,
decodeText,
pipeThrough,
streamFromArray,
streamToString,
chainStreams,
createBufferedTransformStream,
renderToStream,
} from './node-web-streams-helper'
import { FlushEffectsContext } from '../shared/lib/flush-effects'
const DOCTYPE = '<!DOCTYPE html>'
export type RenderOptsPartial = {
err?: Error | null
dev?: boolean
serverComponentManifest?: any
renderServerComponentData?: boolean
serverComponentProps?: any
supportsDynamicHTML?: boolean
runtime?: 'nodejs' | 'edge'
serverComponents?: boolean
reactRoot: boolean
}
export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
const rscCache = new Map()
function createRSCHook() {
return (
writable: WritableStream<Uint8Array>,
id: string,
req: ReadableStream<Uint8Array>,
bootstrap: boolean
) => {
let entry = rscCache.get(id)
if (!entry) {
const [renderStream, forwardStream] = readableStreamTee(req)
entry = createFromReadableStream(renderStream)
rscCache.set(id, entry)
let bootstrapped = false
const forwardReader = forwardStream.getReader()
const writer = writable.getWriter()
function process() {
forwardReader.read().then(({ done, value }) => {
if (bootstrap && !bootstrapped) {
bootstrapped = true
writer.write(
encodeText(
`<script>(self.__next_s=self.__next_s||[]).push(${JSON.stringify(
[0, id]
)})</script>`
)
)
}
if (done) {
rscCache.delete(id)
writer.close()
} else {
writer.write(
encodeText(
`<script>(self.__next_s=self.__next_s||[]).push(${JSON.stringify(
[1, id, decodeText(value)]
)})</script>`
)
)
process()
}
})
}
process()
}
return entry
}
}
const useRSCResponse = createRSCHook()
// Create the wrapper component for a Flight stream.
function createServerComponentRenderer(
OriginalComponent: React.ComponentType,
ComponentMod: any,
{
cachePrefix,
transformStream,
serverComponentManifest,
}: {
cachePrefix: string
transformStream: TransformStream<Uint8Array, Uint8Array>
serverComponentManifest: NonNullable<RenderOpts['serverComponentManifest']>
}
) {
// We need to expose the `__webpack_require__` API globally for
// react-server-dom-webpack. This is a hack until we find a better way.
// @ts-ignore
globalThis.__webpack_require__ = ComponentMod.__next_rsc__.__webpack_require__
const writable = transformStream.writable
const ServerComponentWrapper = (props: any) => {
const id = (React as any).useId()
const reqStream: ReadableStream<Uint8Array> = renderToReadableStream(
<OriginalComponent {...props} />,
serverComponentManifest
)
const response = useRSCResponse(
writable,
cachePrefix + ',' + id,
reqStream,
true
)
const root = response.readRoot()
rscCache.delete(id)
return root
}
const Component = (props: any) => {
return <ServerComponentWrapper {...props} />
}
// Although it's not allowed to attach some static methods to Component,
// we still re-assign all the component APIs to keep the behavior unchanged.
for (const methodName of [
'getInitialProps',
'getStaticProps',
'getServerSideProps',
'getStaticPaths',
]) {
const method = (OriginalComponent as any)[methodName]
if (method) {
;(Component as any)[methodName] = method
}
}
return Component
}
export async function renderToHTML(
req: IncomingMessage,
res: ServerResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: RenderOpts
): Promise<RenderResult | null> {
// don't modify original query object
query = Object.assign({}, query)
const {
dev = false,
serverComponentManifest,
serverComponentProps,
supportsDynamicHTML,
runtime,
ComponentMod,
isRootPath,
} = renderOpts
const hasConcurrentFeatures = !!runtime
const OriginalComponent = renderOpts.Component
// We don't need to opt-into the flight inlining logic if the page isn't a RSC.
const isServerComponent =
!!serverComponentManifest &&
hasConcurrentFeatures &&
(ComponentMod.__next_rsc__ || isRootPath)
let Component: React.ComponentType<{}> | ((props: any) => JSX.Element) =
renderOpts.Component
let serverComponentsInlinedTransformStream: TransformStream<
Uint8Array,
Uint8Array
> | null = null
if (isServerComponent) {
serverComponentsInlinedTransformStream = new TransformStream()
const search = stringifyQuery(query)
Component = createServerComponentRenderer(OriginalComponent, ComponentMod, {
cachePrefix: pathname + (search ? `?${search}` : ''),
transformStream: serverComponentsInlinedTransformStream,
serverComponentManifest,
})
}
let { renderServerComponentData } = renderOpts
if (isServerComponent && query.__flight__) {
renderServerComponentData = true
delete query.__flight__
}
const jsxStyleRegistry = createStyleRegistry()
const styledJsxFlushEffect = () => {
const styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush()
return <>{styles}</>
}
let flushEffects: Array<() => React.ReactNode> | null = null
function FlushEffectContainer({ children }: { children: JSX.Element }) {
// If the client tree suspends, this component will be rendered multiple
// times before we flush. To ensure we don't call old callbacks corresponding
// to a previous render, we clear any registered callbacks whenever we render.
flushEffects = null
const flushEffectsImpl = React.useCallback(
(callbacks: Array<() => React.ReactNode>) => {
if (flushEffects) {
throw new Error(
'The `useFlushEffects` hook cannot be used more than once.' +
'\nRead more: https://nextjs.org/docs/messages/multiple-flush-effects'
)
}
flushEffects = callbacks
},
[]
)
return (
<FlushEffectsContext.Provider value={flushEffectsImpl}>
{children}
</FlushEffectsContext.Provider>
)
}
const AppContainer = ({ children }: { children: JSX.Element }) => (
<FlushEffectContainer>
<StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>
</FlushEffectContainer>
)
// The `useId` API uses the path indexes to generate an ID for each node.
// To guarantee the match of hydration, we need to ensure that the structure
// of wrapper nodes is isomorphic in server and client.
// TODO: With `enhanceApp` and `enhanceComponents` options, this approach may
// not be useful.
// https://github.com/facebook/react/pull/22644
const Noop = () => null
const AppContainerWithIsomorphicFiberStructure: React.FC<{
children: JSX.Element
}> = ({ children }) => {
return (
<>
{/* <Head/> */}
<Noop />
<AppContainer>
<>
{/* <ReactDevOverlay/> */}
{dev ? (
<>
{children}
<Noop />
</>
) : (
children
)}
{/* <RouteAnnouncer/> */}
<Noop />
</>
</AppContainer>
</>
)
}
if (renderServerComponentData) {
const stream: ReadableStream<Uint8Array> = renderToReadableStream(
<OriginalComponent
{...{
...serverComponentProps,
}}
/>,
serverComponentManifest
)
return new RenderResult(
pipeThrough(stream, createBufferedTransformStream())
)
}
const Body = ({ children }: { children: JSX.Element }) => {
return <div id="__next">{children}</div>
}
const ReactDOMServer = require('react-dom/server.browser')
/**
* Rules of Static & Dynamic HTML:
*
* 1.) We must generate static HTML unless the caller explicitly opts
* in to dynamic HTML support.
*
* 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for an AMP page.
*
* These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended.
*/
const generateStaticHTML = supportsDynamicHTML !== true
const bodyResult = async () => {
const content = (
<Body>
<AppContainerWithIsomorphicFiberStructure>
<Component />
</AppContainerWithIsomorphicFiberStructure>
</Body>
)
const flushEffectHandler = async () => {
const allFlushEffects = [styledJsxFlushEffect, ...(flushEffects || [])]
const flushEffectStream = await renderToStream({
ReactDOMServer,
element: (
<>
{allFlushEffects.map((flushEffect, i) => (
<React.Fragment key={i}>{flushEffect()}</React.Fragment>
))}
</>
),
generateStaticHTML: true,
})
const flushed = await streamToString(flushEffectStream)
return flushed
}
return await renderToStream({
ReactDOMServer,
element: content,
dataStream: serverComponentsInlinedTransformStream?.readable,
generateStaticHTML: generateStaticHTML || !hasConcurrentFeatures,
flushEffectHandler,
})
}
const prefix: Array<string> = []
prefix.push(DOCTYPE)
let streams = [streamFromArray(prefix), await bodyResult()]
return new RenderResult(chainStreams(streams))
}