import { Suspense } from 'react'; import { createErrorBoundary } from '../shared/error-boundary'; import type { Options } from '../shared/options'; import { pretty } from '../shared/utils/pretty'; import { stripImagePreloadLinks } from '../shared/utils/strip-image-preload-links'; import { toPlainText } from '../shared/utils/to-plain-text'; import { unstableToPlainText } from '../shared/utils/unstable-to-plain-text'; import { readStream } from './read-stream'; export const render = async (node: React.ReactNode, options?: Options) => { const reactDOMServer = await import('react-dom/server').then((m) => { if ('default' in m) { return m.default; } return m; }); let html!: string; await new Promise((resolve, reject) => { if ( Object.hasOwn(reactDOMServer, 'renderToReadableStream') && typeof WritableStream !== 'undefined' ) { const ErrorBoundary = createErrorBoundary(reject); reactDOMServer .renderToReadableStream( {node} , { progressiveChunkSize: Number.POSITIVE_INFINITY, onError(error) { // Throw immediately when an error occurs to prevent CSR fallback reject(error); }, }, ) .then(async (stream) => { await stream.allReady; return readStream(stream); }) .then((result) => { html = result; resolve(); }) .catch(reject); } else { const ErrorBoundary = createErrorBoundary(reject); const stream = reactDOMServer.renderToPipeableStream( {node} , { async onAllReady() { html = await readStream(stream).then((s: string) => { // Workaround for https://github.com/facebook/react/pull/26228 // (fixed in React 19, not backported to 18) return s.replaceAll('\0', ''); }); resolve(); }, onError(error) { reject(error); }, progressiveChunkSize: Number.POSITIVE_INFINITY, }, ); } }); html = stripImagePreloadLinks(html); if (options?.plainText) { return options.unstableTextConversion ? unstableToPlainText(html) : toPlainText(html, options.htmlToTextOptions); } const doctype = ''; const document = `${doctype}${html.replace(//, '')}`; if (options?.pretty) { return pretty(document); } return document; };