-
-
Notifications
You must be signed in to change notification settings - Fork 638
Separate streamServerRenderedReactComponent from ReactOnRails #1680
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
|
|
||
| import type { RegisteredComponent, RenderResult, RenderState, StreamRenderState } from './types'; | ||
|
|
||
| export function createResultObject(html: string | null, consoleReplayScript: string, renderState: RenderState | StreamRenderState): RenderResult { | ||
| return { | ||
| html, | ||
| consoleReplayScript, | ||
| hasErrors: renderState.hasErrors, | ||
| renderingError: renderState.error && { message: renderState.error.message, stack: renderState.error.stack }, | ||
| isShellReady: 'isShellReady' in renderState ? renderState.isShellReady : undefined, | ||
| }; | ||
| } | ||
|
|
||
| export function convertToError(e: unknown): Error { | ||
| return e instanceof Error ? e : new Error(String(e)); | ||
| } | ||
|
|
||
| export function validateComponent(componentObj: RegisteredComponent, componentName: string) { | ||
| if (componentObj.isRenderer) { | ||
| throw new Error(`Detected a renderer while server rendering component '${componentName}'. See https://github.com/shakacode/react_on_rails#renderer-functions`); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| import ReactDOMServer, { type PipeableStream } from 'react-dom/server'; | ||
| import { PassThrough, Readable } from 'stream'; | ||
| import type { ReactElement } from 'react'; | ||
|
|
||
| import ComponentRegistry from './ComponentRegistry'; | ||
| import createReactOutput from './createReactOutput'; | ||
| import { isPromise, isServerRenderHash } from './isServerRenderResult'; | ||
| import buildConsoleReplay from './buildConsoleReplay'; | ||
| import handleError from './handleError'; | ||
| import { createResultObject, convertToError, validateComponent } from './serverRenderUtils'; | ||
| import type { RenderParams, StreamRenderState } from './types'; | ||
|
|
||
| const stringToStream = (str: string): Readable => { | ||
| const stream = new PassThrough(); | ||
| stream.write(str); | ||
| stream.end(); | ||
| return stream; | ||
| }; | ||
|
|
||
| const transformRenderStreamChunksToResultObject = (renderState: StreamRenderState) => { | ||
| const consoleHistory = console.history; | ||
| let previouslyReplayedConsoleMessages = 0; | ||
|
|
||
| const transformStream = new PassThrough({ | ||
| transform(chunk, _, callback) { | ||
| const htmlChunk = chunk.toString(); | ||
| const consoleReplayScript = buildConsoleReplay(consoleHistory, previouslyReplayedConsoleMessages); | ||
| previouslyReplayedConsoleMessages = consoleHistory?.length || 0; | ||
|
|
||
| const jsonChunk = JSON.stringify(createResultObject(htmlChunk, consoleReplayScript, renderState)); | ||
|
|
||
| this.push(`${jsonChunk}\n`); | ||
| callback(); | ||
| } | ||
| }); | ||
|
|
||
| let pipedStream: PipeableStream | null = null; | ||
| const pipeToTransform = (pipeableStream: PipeableStream) => { | ||
| pipeableStream.pipe(transformStream); | ||
| pipedStream = pipeableStream; | ||
| }; | ||
| // We need to wrap the transformStream in a Readable stream to properly handle errors: | ||
| // 1. If we returned transformStream directly, we couldn't emit errors into it externally | ||
| // 2. If an error is emitted into the transformStream, it would cause the render to fail | ||
| // 3. By wrapping in Readable.from(), we can explicitly emit errors into the readableStream without affecting the transformStream | ||
| // Note: Readable.from can merge multiple chunks into a single chunk, so we need to ensure that we can separate them later | ||
| const readableStream = Readable.from(transformStream); | ||
|
|
||
| const writeChunk = (chunk: string) => transformStream.write(chunk); | ||
| const emitError = (error: unknown) => readableStream.emit('error', error); | ||
| const endStream = () => { | ||
| transformStream.end(); | ||
| pipedStream?.abort(); | ||
| } | ||
| return { readableStream, pipeToTransform, writeChunk, emitError, endStream }; | ||
| } | ||
|
|
||
| const streamRenderReactComponent = (reactRenderingResult: ReactElement, options: RenderParams) => { | ||
| const { name: componentName, throwJsErrors } = options; | ||
| const renderState: StreamRenderState = { | ||
| result: null, | ||
| hasErrors: false, | ||
| isShellReady: false | ||
| }; | ||
|
|
||
| const { | ||
| readableStream, | ||
| pipeToTransform, | ||
| writeChunk, | ||
| emitError, | ||
| endStream | ||
| } = transformRenderStreamChunksToResultObject(renderState); | ||
|
|
||
| const renderingStream = ReactDOMServer.renderToPipeableStream(reactRenderingResult, { | ||
| onShellError(e) { | ||
| const error = convertToError(e); | ||
| renderState.hasErrors = true; | ||
| renderState.error = error; | ||
|
|
||
| if (throwJsErrors) { | ||
| emitError(error); | ||
| } | ||
|
|
||
| const errorHtml = handleError({ e: error, name: componentName, serverSide: true }); | ||
| writeChunk(errorHtml); | ||
| endStream(); | ||
| }, | ||
| onShellReady() { | ||
| renderState.isShellReady = true; | ||
| pipeToTransform(renderingStream); | ||
| }, | ||
| onError(e) { | ||
| if (!renderState.isShellReady) { | ||
| return; | ||
| } | ||
| const error = convertToError(e); | ||
| if (throwJsErrors) { | ||
| emitError(error); | ||
| } | ||
| renderState.hasErrors = true; | ||
| renderState.error = error; | ||
| }, | ||
| }); | ||
|
|
||
| return readableStream; | ||
| } | ||
|
|
||
| const streamServerRenderedReactComponent = (options: RenderParams): Readable => { | ||
| const { name: componentName, domNodeId, trace, props, railsContext, throwJsErrors } = options; | ||
|
|
||
| try { | ||
| const componentObj = ComponentRegistry.get(componentName); | ||
| validateComponent(componentObj, componentName); | ||
|
|
||
| const reactRenderingResult = createReactOutput({ | ||
| componentObj, | ||
| domNodeId, | ||
| trace, | ||
| props, | ||
| railsContext, | ||
| }); | ||
|
|
||
| if (isServerRenderHash(reactRenderingResult) || isPromise(reactRenderingResult)) { | ||
| throw new Error('Server rendering of streams is not supported for server render hashes or promises.'); | ||
| } | ||
|
|
||
| return streamRenderReactComponent(reactRenderingResult, options); | ||
| } catch (e) { | ||
| if (throwJsErrors) { | ||
| throw e; | ||
| } | ||
|
|
||
| const error = convertToError(e); | ||
| const htmlResult = handleError({ e: error, name: componentName, serverSide: true }); | ||
| const jsonResult = JSON.stringify(createResultObject(htmlResult, buildConsoleReplay(), { hasErrors: true, error, result: null })); | ||
| return stringToStream(jsonResult); | ||
| } | ||
| }; | ||
|
|
||
| export default streamServerRenderedReactComponent; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use
Transforminstead ofPassThroughfor custom transform streamsWhen implementing a custom transform function, you should use the
Transformstream instead ofPassThrough. ThePassThroughstream is designed to pass data through without modification and does not support a customtransformmethod.Apply this diff to fix the issue:
Also applies to: 24-24