Unverified Commit 02103feb authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

onHeaders updates for App Pages (#58410)

This serves to address a few problems as it relates to headers handling within the App Page render pipeline.

1. During static generation, we should not write to the response directly as the revalidation for static responses is performed out of band from the actual request/response as a stale version can be served early. This is partially addressed by modifying the `onHeaders` to only write when there it is not during static generation, but long term I'd hope to see that we can instead pass a immutable request and `null` for the response to help indicate to the render pipeline that it should instead persist the data into the `RenderResult` objects. Alternatively, the response could use a mocked version that would then supersede the `RenderResult` and be used instead.

2. The types for rendering App Pages were merged incorrectly, so this additionally restructures the way that we initialize those renderers such that only the options that are applicable to each renderer is passed down.
parent 2b028891
...@@ -184,7 +184,7 @@ export async function exportAppPage( ...@@ -184,7 +184,7 @@ export async function exportAppPage(
) )
} }
const headers = { ...metadata.extraHeaders } const headers = { ...metadata.headers }
if (fetchTags) { if (fetchTags) {
headers[NEXT_CACHE_TAGS_HEADER] = fetchTags headers[NEXT_CACHE_TAGS_HEADER] = fetchTags
......
...@@ -2,9 +2,7 @@ import type { Dirent } from 'fs' ...@@ -2,9 +2,7 @@ import type { Dirent } from 'fs'
import { promises } from 'fs' import { promises } from 'fs'
import { join, isAbsolute, dirname } from 'path' import { join, isAbsolute, dirname } from 'path'
import isError from './is-error' import isError from './is-error'
import { wait } from './wait'
const sleep = (timeout: number) =>
new Promise((resolve) => setTimeout(resolve, timeout))
const unlinkPath = async (p: string, isDir = false, t = 1): Promise<void> => { const unlinkPath = async (p: string, isDir = false, t = 1): Promise<void> => {
try { try {
...@@ -22,7 +20,7 @@ const unlinkPath = async (p: string, isDir = false, t = 1): Promise<void> => { ...@@ -22,7 +20,7 @@ const unlinkPath = async (p: string, isDir = false, t = 1): Promise<void> => {
code === 'EMFILE') && code === 'EMFILE') &&
t < 3 t < 3
) { ) {
await sleep(t * 100) await wait(t * 100)
return unlinkPath(p, isDir, t++) return unlinkPath(p, isDir, t++)
} }
......
...@@ -6,6 +6,9 @@ import type { ...@@ -6,6 +6,9 @@ import type {
} from 'http' } from 'http'
import type { WebNextRequest } from '../base-http/web' import type { WebNextRequest } from '../base-http/web'
import type { SizeLimit } from '../../../types' import type { SizeLimit } from '../../../types'
import type { RequestStore } from '../../client/components/request-async-storage.external'
import type { AppRenderContext, GenerateFlight } from './app-render'
import type { AppPageModule } from '../../server/future/route-modules/app-page/module'
import { import {
ACTION, ACTION,
...@@ -20,7 +23,6 @@ import { ...@@ -20,7 +23,6 @@ import {
import RenderResult from '../render-result' import RenderResult from '../render-result'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import { FlightRenderResult } from './flight-render-result' import { FlightRenderResult } from './flight-render-result'
import type { ActionAsyncStorage } from '../../client/components/action-async-storage.external'
import { import {
filterReqHeaders, filterReqHeaders,
actionsForbiddenHeaders, actionsForbiddenHeaders,
...@@ -30,12 +32,10 @@ import { ...@@ -30,12 +32,10 @@ import {
getModifiedCookieValues, getModifiedCookieValues,
} from '../web/spec-extension/adapters/request-cookies' } from '../web/spec-extension/adapters/request-cookies'
import type { RequestStore } from '../../client/components/request-async-storage.external'
import { import {
NEXT_CACHE_REVALIDATED_TAGS_HEADER, NEXT_CACHE_REVALIDATED_TAGS_HEADER,
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER, NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
} from '../../lib/constants' } from '../../lib/constants'
import type { AppRenderContext, GenerateFlight } from './app-render'
function formDataFromSearchQueryString(query: string) { function formDataFromSearchQueryString(query: string) {
const searchParams = new URLSearchParams(query) const searchParams = new URLSearchParams(query)
...@@ -244,7 +244,7 @@ export async function handleAction({ ...@@ -244,7 +244,7 @@ export async function handleAction({
}: { }: {
req: IncomingMessage req: IncomingMessage
res: ServerResponse res: ServerResponse
ComponentMod: any ComponentMod: AppPageModule
serverModuleMap: { serverModuleMap: {
[id: string]: { [id: string]: {
id: string id: string
...@@ -288,6 +288,12 @@ export async function handleAction({ ...@@ -288,6 +288,12 @@ export async function handleAction({
return return
} }
if (staticGenerationStore.isStaticGeneration) {
throw new Error(
"Invariant: server actions can't be handled during static rendering"
)
}
const originDomain = const originDomain =
typeof req.headers['origin'] === 'string' typeof req.headers['origin'] === 'string'
? new URL(req.headers['origin']).host ? new URL(req.headers['origin']).host
...@@ -373,9 +379,7 @@ export async function handleAction({ ...@@ -373,9 +379,7 @@ export async function handleAction({
) )
let bound = [] let bound = []
const { actionAsyncStorage } = ComponentMod as { const { actionAsyncStorage } = ComponentMod
actionAsyncStorage: ActionAsyncStorage
}
let actionResult: RenderResult | undefined let actionResult: RenderResult | undefined
let formState: any | undefined let formState: any | undefined
......
...@@ -73,6 +73,7 @@ import { getAssetQueryString } from './get-asset-query-string' ...@@ -73,6 +73,7 @@ import { getAssetQueryString } from './get-asset-query-string'
import { setReferenceManifestsSingleton } from './action-encryption-utils' import { setReferenceManifestsSingleton } from './action-encryption-utils'
import { createStaticRenderer } from './static/static-renderer' import { createStaticRenderer } from './static/static-renderer'
import { MissingPostponeDataError } from './is-missing-postpone-error' import { MissingPostponeDataError } from './is-missing-postpone-error'
import { DetachedPromise } from '../../lib/detached-promise'
export type GetDynamicParamFromSegment = ( export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug] // [slug] / [[slug]] / [...slug]
...@@ -654,7 +655,13 @@ async function renderToHTMLOrFlightImpl( ...@@ -654,7 +655,13 @@ async function renderToHTMLOrFlightImpl(
createServerInsertedHTML() createServerInsertedHTML()
getTracer().getRootSpanAttributes()?.set('next.route', pagePath) getTracer().getRootSpanAttributes()?.set('next.route', pagePath)
const bodyResult = getTracer().wrap(
// Create a promise that will help us signal when the headers have been
// written to the metadata for static generation as they aren't written to the
// response directly.
const onHeadersFinished = new DetachedPromise<void>()
const renderToStream = getTracer().wrap(
AppRenderSpan.getBodyResult, AppRenderSpan.getBodyResult,
{ {
spanName: `render route (app) ${pagePath}`, spanName: `render route (app) ${pagePath}`,
...@@ -703,21 +710,13 @@ async function renderToHTMLOrFlightImpl( ...@@ -703,21 +710,13 @@ async function renderToHTMLOrFlightImpl(
nonce nonce
) )
const renderer = createStaticRenderer({
ppr: renderOpts.experimental.ppr,
isStaticGeneration: staticGenerationStore.isStaticGeneration,
postponed: renderOpts.postponed
? JSON.parse(renderOpts.postponed)
: null,
})
const ServerComponentsRenderer = createServerComponentsRenderer(tree, { const ServerComponentsRenderer = createServerComponentsRenderer(tree, {
ctx, ctx,
preinitScripts, preinitScripts,
options: serverComponentsRenderOpts, options: serverComponentsRenderOpts,
}) })
const content = ( const children = (
<HeadManagerContext.Provider <HeadManagerContext.Provider
value={{ value={{
appDir: true, appDir: true,
...@@ -736,34 +735,51 @@ async function renderToHTMLOrFlightImpl( ...@@ -736,34 +735,51 @@ async function renderToHTMLOrFlightImpl(
hasPostponed, hasPostponed,
}) })
function onHeaders(headers: Headers): void { const renderer = createStaticRenderer({
// Copy headers created by React into the response object. ppr: renderOpts.experimental.ppr,
headers.forEach((value: string, key: string) => { isStaticGeneration,
res.appendHeader(key, value) // If provided, the postpone state should be parsed as JSON so it can be
if (!extraRenderResultMeta.extraHeaders) { // provided to React.
extraRenderResultMeta.extraHeaders = {} postponed: renderOpts.postponed
} ? JSON.parse(renderOpts.postponed)
extraRenderResultMeta.extraHeaders[key] = value : null,
}) streamOptions: {
}
try {
const renderStream = await renderer.render(content, {
onError: htmlRendererErrorHandler, onError: htmlRendererErrorHandler,
onHeaders: onHeaders, onHeaders: (headers: Headers) => {
// If this is during static generation, we shouldn't write to the
// headers object directly, instead we should add to the render
// result.
if (isStaticGeneration) {
headers.forEach((value, key) => {
extraRenderResultMeta.headers ??= {}
extraRenderResultMeta.headers[key] = value
})
// Resolve the promise to continue the stream.
onHeadersFinished.resolve()
} else {
headers.forEach((value, key) => {
res.appendHeader(key, value)
})
}
},
maxHeadersLength: 600, maxHeadersLength: 600,
nonce, nonce,
bootstrapScripts: [bootstrapScript], bootstrapScripts: [bootstrapScript],
formState, formState,
}) },
})
const { stream, postponed } = renderStream try {
let { stream, postponed } = await renderer.render(children)
// If the stream was postponed, we need to add the result to the
// metadata so that it can be resumed later.
if (postponed) { if (postponed) {
extraRenderResultMeta.postponed = JSON.stringify(postponed) extraRenderResultMeta.postponed = JSON.stringify(postponed)
// If this render generated a postponed state, we don't want to add // We don't need to "continue" this stream now as it's continued when
// any other data to the response. // we resume the stream.
return stream return stream
} }
...@@ -786,10 +802,10 @@ async function renderToHTMLOrFlightImpl( ...@@ -786,10 +802,10 @@ async function renderToHTMLOrFlightImpl(
} }
if (renderOpts.postponed) { if (renderOpts.postponed) {
return continuePostponedFizzStream(stream, options) return await continuePostponedFizzStream(stream, options)
} }
return continueFizzStream(stream, options) return await continueFizzStream(stream, options)
} catch (err: any) { } catch (err: any) {
if ( if (
err.code === 'NEXT_STATIC_GEN_BAILOUT' || err.code === 'NEXT_STATIC_GEN_BAILOUT' ||
...@@ -967,8 +983,8 @@ async function renderToHTMLOrFlightImpl( ...@@ -967,8 +983,8 @@ async function renderToHTMLOrFlightImpl(
ComponentMod, ComponentMod,
serverModuleMap, serverModuleMap,
generateFlight, generateFlight,
staticGenerationStore: staticGenerationStore, staticGenerationStore,
requestStore: requestStore, requestStore,
serverActions, serverActions,
ctx, ctx,
}) })
...@@ -978,7 +994,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -978,7 +994,7 @@ async function renderToHTMLOrFlightImpl(
if (actionRequestResult.type === 'not-found') { if (actionRequestResult.type === 'not-found') {
const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree) const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree)
return new RenderResult( return new RenderResult(
await bodyResult({ await renderToStream({
asNotFound: true, asNotFound: true,
tree: notFoundLoaderTree, tree: notFoundLoaderTree,
formState, formState,
...@@ -996,15 +1012,20 @@ async function renderToHTMLOrFlightImpl( ...@@ -996,15 +1012,20 @@ async function renderToHTMLOrFlightImpl(
} }
const renderResult = new RenderResult( const renderResult = new RenderResult(
await bodyResult({ await renderToStream({
asNotFound: isNotFoundPath, asNotFound: isNotFoundPath,
tree: loaderTree, tree: loaderTree,
formState, formState,
}), }),
{ {
...extraRenderResultMeta, ...extraRenderResultMeta,
// Wait for and collect the flight payload data if we don't have it
// already.
pageData: await stringifiedFlightPayloadPromise, pageData: await stringifiedFlightPayloadPromise,
waitUntil: Promise.all(staticGenerationStore.pendingRevalidates || []), // If we have pending revalidates, wait until they are all resolved.
waitUntil: staticGenerationStore.pendingRevalidates
? Promise.all(staticGenerationStore.pendingRevalidates)
: undefined,
} }
) )
...@@ -1015,8 +1036,30 @@ async function renderToHTMLOrFlightImpl( ...@@ -1015,8 +1036,30 @@ async function renderToHTMLOrFlightImpl(
}) })
if (staticGenerationStore.isStaticGeneration) { if (staticGenerationStore.isStaticGeneration) {
// Collect the entire render result to a string (by streaming it to a
// string).
const htmlResult = await renderResult.toUnchunkedString(true) const htmlResult = await renderResult.toUnchunkedString(true)
// Timeout after 1.5 seconds for the headers to write. If it takes
// longer than this it's more likely that the stream has stalled and
// there is a React bug. The headers will then be updated in the render
// result below when the metadata is re-added to the new render result.
const onTimeout = new DetachedPromise<never>()
const timeout = setTimeout(() => {
onTimeout.reject(
new Error(
'Timeout waiting for headers to be emitted, this is a bug in Next.js'
)
)
}, 1500)
// Race against the timeout and the headers being written.
await Promise.race([onHeadersFinished.promise, onTimeout.promise])
// It got here, which means it did not reject, so clear the timeout to avoid
// it from rejecting again (which is a no-op anyways).
clearTimeout(timeout)
if ( if (
// if PPR is enabled // if PPR is enabled
renderOpts.experimental.ppr && renderOpts.experimental.ppr &&
......
type StreamOptions = { import type {
onError?: (error: Error) => void Options as RenderToReadableStreamOptions,
onHeaders?: (headers: Headers) => void ResumeOptions,
maxHeadersLength?: number } from 'react-dom/server.edge'
nonce?: string import type { Options as PrerenderOptions } from 'react-dom/static.edge'
bootstrapScripts?: {
src: string
integrity?: string
crossOrigin?: string
}[]
formState?: boolean
}
type RenderResult = { type RenderResult = {
stream: ReadableStream<Uint8Array> stream: ReadableStream<Uint8Array>
...@@ -17,7 +10,7 @@ type RenderResult = { ...@@ -17,7 +10,7 @@ type RenderResult = {
} }
export interface Renderer { export interface Renderer {
render(children: JSX.Element, options: StreamOptions): Promise<RenderResult> render(children: JSX.Element): Promise<RenderResult>
} }
class StaticRenderer implements Renderer { class StaticRenderer implements Renderer {
...@@ -26,8 +19,10 @@ class StaticRenderer implements Renderer { ...@@ -26,8 +19,10 @@ class StaticRenderer implements Renderer {
? require('react-dom/static.edge').prerender ? require('react-dom/static.edge').prerender
: null) as typeof import('react-dom/static.edge')['prerender'] : null) as typeof import('react-dom/static.edge')['prerender']
public async render(children: JSX.Element, streamOptions: StreamOptions) { constructor(private readonly options: PrerenderOptions) {}
const { prelude, postponed } = await this.prerender(children, streamOptions)
public async render(children: JSX.Element) {
const { prelude, postponed } = await this.prerender(children, this.options)
return { stream: prelude, postponed } return { stream: prelude, postponed }
} }
...@@ -37,14 +32,13 @@ class StaticResumeRenderer implements Renderer { ...@@ -37,14 +32,13 @@ class StaticResumeRenderer implements Renderer {
private readonly resume = require('react-dom/server.edge') private readonly resume = require('react-dom/server.edge')
.resume as typeof import('react-dom/server.edge')['resume'] .resume as typeof import('react-dom/server.edge')['resume']
constructor(private readonly postponed: object) {} constructor(
private readonly postponed: object,
private readonly options: ResumeOptions
) {}
public async render(children: JSX.Element, streamOptions: StreamOptions) { public async render(children: JSX.Element) {
// TODO: Refactor StreamOptions because not all options apply to all React const stream = await this.resume(children, this.postponed, this.options)
// functions so this factoring of trying to reuse a single render() doesn't
// make sense. This is passing multiple invalid options that React should
// error for.
const stream = await this.resume(children, this.postponed, streamOptions)
return { stream } return { stream }
} }
...@@ -54,35 +48,96 @@ export class ServerRenderer implements Renderer { ...@@ -54,35 +48,96 @@ export class ServerRenderer implements Renderer {
private readonly renderToReadableStream = require('react-dom/server.edge') private readonly renderToReadableStream = require('react-dom/server.edge')
.renderToReadableStream as typeof import('react-dom/server.edge')['renderToReadableStream'] .renderToReadableStream as typeof import('react-dom/server.edge')['renderToReadableStream']
public async render( constructor(private readonly options: RenderToReadableStreamOptions) {}
children: JSX.Element,
options: StreamOptions public async render(children: JSX.Element): Promise<RenderResult> {
): Promise<RenderResult> { const stream = await this.renderToReadableStream(children, this.options)
const stream = await this.renderToReadableStream(children, options)
return { stream } return { stream }
} }
} }
/**
* This represents all the possible configuration options for each of the
* available renderers. We pick the specific options we need for each renderer
* to help the `createStaticRenderer` function. If more options are added to
* this type they should be added to the `createStaticRenderer` function as
* well.
*/
type StreamOptions = Pick<
ResumeOptions & RenderToReadableStreamOptions & PrerenderOptions,
| 'onError'
| 'onHeaders'
| 'maxHeadersLength'
| 'nonce'
| 'bootstrapScripts'
| 'formState'
>
type Options = { type Options = {
/**
* Whether or not PPR is enabled. This is used to determine which renderer to
* use.
*/
ppr: boolean ppr: boolean
/**
* Whether or not this is a static generation render. This is used to
* determine which renderer to use.
*/
isStaticGeneration: boolean isStaticGeneration: boolean
/**
* The postponed state for the render. This is only used when resuming a
* prerender that has postponed.
*/
postponed: object | null postponed: object | null
/**
* The options for any of the renderers. This is a union of all the possible
* options for each renderer. If additional configuration options are required
* for a renderer, they should be added to the `StreamOptions` type and then
* added via the `createStaticRenderer` function.
*/
streamOptions: StreamOptions
} }
export function createStaticRenderer({ export function createStaticRenderer({
ppr, ppr,
isStaticGeneration, isStaticGeneration,
postponed, postponed,
streamOptions: {
onError,
onHeaders,
maxHeadersLength,
nonce,
bootstrapScripts,
formState,
},
}: Options): Renderer { }: Options): Renderer {
if (ppr) { if (ppr) {
if (isStaticGeneration) { if (isStaticGeneration) {
return new StaticRenderer() return new StaticRenderer({
onError,
onHeaders,
maxHeadersLength,
bootstrapScripts,
})
} }
if (postponed) { if (postponed) {
return new StaticResumeRenderer(postponed) return new StaticResumeRenderer(postponed, {
onError,
nonce,
})
} }
} }
return new ServerRenderer() return new ServerRenderer({
onError,
onHeaders,
maxHeadersLength,
nonce,
bootstrapScripts,
formState,
})
} }
...@@ -23,7 +23,6 @@ import { ...@@ -23,7 +23,6 @@ import {
} from '../shared/lib/utils' } from '../shared/lib/utils'
import type { PreviewData, ServerRuntime, SizeLimit } from 'next/types' import type { PreviewData, ServerRuntime, SizeLimit } from 'next/types'
import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin' import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import type { OutgoingHttpHeaders } from 'http'
import type { BaseNextRequest, BaseNextResponse } from './base-http' import type { BaseNextRequest, BaseNextResponse } from './base-http'
import type { import type {
ManifestRewriteRoute, ManifestRewriteRoute,
...@@ -2166,8 +2165,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2166,8 +2165,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// HTML (it's dynamic). // HTML (it's dynamic).
isDynamicRSCRequest isDynamicRSCRequest
let headers: OutgoingHttpHeaders | undefined
const origQuery = parseUrl(req.url || '', true).query const origQuery = parseUrl(req.url || '', true).query
// clear any dynamic route params so they aren't in // clear any dynamic route params so they aren't in
...@@ -2261,7 +2258,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2261,7 +2258,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const blob = await response.blob() const blob = await response.blob()
// Copy the headers from the response. // Copy the headers from the response.
headers = toNodeOutgoingHttpHeaders(response.headers) const headers = toNodeOutgoingHttpHeaders(response.headers)
if (cacheTags) { if (cacheTags) {
headers[NEXT_CACHE_TAGS_HEADER] = cacheTags headers[NEXT_CACHE_TAGS_HEADER] = cacheTags
...@@ -2371,10 +2368,11 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2371,10 +2368,11 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const { metadata } = result const { metadata } = result
// Add any fetch tags that were on the page to the response headers. const {
const cacheTags = metadata.fetchTags headers = {},
// Add any fetch tags that were on the page to the response headers.
headers = { ...metadata.extraHeaders } fetchTags: cacheTags,
} = metadata
if (cacheTags) { if (cacheTags) {
headers[NEXT_CACHE_TAGS_HEADER] = cacheTags headers[NEXT_CACHE_TAGS_HEADER] = cacheTags
...@@ -2776,18 +2774,24 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2776,18 +2774,24 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} }
if (cachedData.headers) { if (cachedData.headers) {
const resHeaders = cachedData.headers const headers = { ...cachedData.headers }
for (const key of Object.keys(resHeaders)) {
if (key === NEXT_CACHE_TAGS_HEADER) { if (!this.minimalMode || !isSSG) {
// Not sure if needs to be special. delete headers[NEXT_CACHE_TAGS_HEADER]
continue }
}
let v = resHeaders[key] for (let [key, value] of Object.entries(headers)) {
if (typeof v !== 'undefined') { if (typeof value === 'undefined') continue
if (typeof v === 'number') {
v = v.toString() if (Array.isArray(value)) {
for (const v of value) {
res.appendHeader(key, v)
} }
res.setHeader(key, v) } else if (typeof value === 'number') {
value = value.toString()
res.appendHeader(key, value)
} else {
res.appendHeader(key, value)
} }
} }
} }
......
...@@ -23,8 +23,16 @@ export type RenderResultMetadata = { ...@@ -23,8 +23,16 @@ export type RenderResultMetadata = {
isRedirect?: boolean isRedirect?: boolean
fetchMetrics?: StaticGenerationStore['fetchMetrics'] fetchMetrics?: StaticGenerationStore['fetchMetrics']
fetchTags?: string fetchTags?: string
extraHeaders?: OutgoingHttpHeaders
waitUntil?: Promise<any> waitUntil?: Promise<any>
/**
* The headers to set on the response that were added by the render.
*/
headers?: OutgoingHttpHeaders
/**
* The postponed state if the render had postponed and needs to be resumed.
*/
postponed?: string postponed?: string
} }
......
...@@ -2,6 +2,28 @@ declare module 'react-dom/server-rendering-stub' ...@@ -2,6 +2,28 @@ declare module 'react-dom/server-rendering-stub'
declare module 'react-dom/server.browser' declare module 'react-dom/server.browser'
declare module 'react-dom/server.edge' { declare module 'react-dom/server.edge' {
/**
* https://github.com/facebook/react/blob/aec521a96d3f1bebc2ba38553d14f4989c6e88e0/packages/react-dom-bindings/src/server/ReactFizzConfigDOM.js#L329-L333
*/
type BootstrapScriptDescriptor = {
src: string
integrity?: string
crossOrigin?: string
}
/**
* Options for `resume`.
*
* https://github.com/facebook/react/blob/aec521a96d3f1bebc2ba38553d14f4989c6e88e0/packages/react-dom/src/server/ReactDOMFizzServerEdge.js#L54-L60
*/
export type ResumeOptions = {
nonce?: string
signal?: AbortSignal
onError?: (error: unknown) => string | undefined
onPostpone?: (reason: string) => void
unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor
}
export function resume( export function resume(
children: JSX.Element, children: JSX.Element,
postponedState: object, postponedState: object,
...@@ -10,12 +32,41 @@ declare module 'react-dom/server.edge' { ...@@ -10,12 +32,41 @@ declare module 'react-dom/server.edge' {
} }
): Promise<ReadableStream<Uint8Array>> ): Promise<ReadableStream<Uint8Array>>
/**
* Options for `renderToReadableStream`.
*
* https://github.com/facebook/react/blob/aec521a96d3f1bebc2ba38553d14f4989c6e88e0/packages/react-dom/src/server/ReactDOMFizzServerEdge.js#L36-L52
*/
export type Options = {
identifierPrefix?: string
namespaceURI?: string
nonce?: string
bootstrapScriptContent?: string
bootstrapScripts?: Array<string | BootstrapScriptDescriptor>
bootstrapModules?: Array<string | BootstrapScriptDescriptor>
progressiveChunkSize?: number
signal?: AbortSignal
onError?: (error: unknown) => string | undefined
onPostpone?: (reason: string) => void
unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor
importMap?: {
imports?: {
[specifier: string]: string
}
scopes?: {
[scope: string]: {
[specifier: string]: string
}
}
}
formState?: unknown
onHeaders?: (headers: Headers) => void
maxHeadersLength?: number
}
export function renderToReadableStream( export function renderToReadableStream(
children: JSX.Element, children: JSX.Element,
options?: { options?: Options
onError?: (error: Error) => void
nonce?: string
}
): Promise< ): Promise<
ReadableStream<Uint8Array> & { ReadableStream<Uint8Array> & {
allReady: Promise<void> allReady: Promise<void>
...@@ -24,10 +75,50 @@ declare module 'react-dom/server.edge' { ...@@ -24,10 +75,50 @@ declare module 'react-dom/server.edge' {
} }
declare module 'react-dom/static.edge' { declare module 'react-dom/static.edge' {
/**
* https://github.com/facebook/react/blob/aec521a96d3f1bebc2ba38553d14f4989c6e88e0/packages/react-dom-bindings/src/server/ReactFizzConfigDOM.js#L329-L333
*/
type BootstrapScriptDescriptor = {
src: string
integrity?: string
crossOrigin?: string
}
/**
* Options for `prerender`.
*
* https://github.com/facebook/react/blob/aec521a96d3f1bebc2ba38553d14f4989c6e88e0/packages/react-dom/src/server/ReactDOMFizzStaticEdge.js#L35-L49
*/
export type Options = {
identifierPrefix?: string
namespaceURI?: string
bootstrapScriptContent?: string
bootstrapScripts?: Array<string | BootstrapScriptDescriptor>
bootstrapModules?: Array<string | BootstrapScriptDescriptor>
progressiveChunkSize?: number
signal?: AbortSignal
onError?: (error: unknown) => string | undefined
onPostpone?: (reason: string) => void
unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor
importMap?: {
imports?: {
[specifier: string]: string
}
scopes?: {
[scope: string]: {
[specifier: string]: string
}
}
}
onHeaders?: (headers: Headers) => void
maxHeadersLength?: number
}
export function prerender( export function prerender(
children: JSX.Element, children: JSX.Element,
options?: { options?: {
onError?: (error: Error) => void onError?: (error: Error) => void
onHeaders?: (headers: Headers) => void
} }
): Promise<{ ): Promise<{
prelude: ReadableStream<Uint8Array> prelude: ReadableStream<Uint8Array>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment