streaming.ts
This file
Path
src/jsx/streaming.ts
231 lines 路 7.3 KiB 路 TypeScript
Last changed by
chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232/** * @module * This module enables JSX to supports streaming Response. */
import { raw } from '../helper/html'import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'import type { HtmlEscapedString } from '../utils/html'import type { Child, FC, PropsWithChildren, Context as JSXContext } from './'import { isUntrustedObject, JSXNode, renderChildren, renderUntrustedObject } from './base'import { childrenToString } from './components'import { DOM_RENDERER, DOM_STASH } from './constants'import { captureRenderContext, createContext, useContext } from './context'import { Suspense as SuspenseDomRenderer } from './dom/components'import { buildDataStack } from './dom/render'import type { HasRenderToDom, NodeObject } from './dom/render'
/** * Used to specify nonce for scripts generated by `Suspense` and `ErrorBoundary`. * * @example * ```tsx * <StreamingContext.Provider value={{ scriptNonce: 'test-nonce' }}> * <Suspense fallback={<p>Loading...</p>}> * <Content /> * </Suspense> * </StreamingContext.Provider> * ``` */export const StreamingContext: JSXContext<{ scriptNonce: string } | null> = createContext<{ scriptNonce: string} | null>(null)
let suspenseCounter = 0
const serializeBoundaryChild = (child: Child): string | Promise<string> => typeof child === 'string' || Array.isArray(child) ? renderChildren([child]) : child == null || typeof child === 'boolean' ? '' : isUntrustedObject(child) ? renderUntrustedObject(child) : child.toString()
/** * @experimental * `Suspense` is an experimental feature. * The API might be changed. */// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Suspense: FC<PropsWithChildren<{ fallback: any }>> = async ({ children, fallback,}) => { if (!Array.isArray(children)) { children = [children] }
const nonce = useContext(StreamingContext)?.scriptNonce
let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []
// for use() hook const stackNode = { [DOM_STASH]: [0, []] } as unknown as NodeObject const popNodeStack = () => { buildDataStack.pop() }
try { stackNode[DOM_STASH][0] = 0 buildDataStack.push([[], stackNode]) resArray = children.map(serializeBoundaryChild) as HtmlEscapedString[] } catch (e) { if (e instanceof Promise) { // Capture before deferring: on the fallback path the render context is // observable here but not in the `.then()` below. const resume = captureRenderContext() resArray = [ e.then(() => resume(() => { stackNode[DOM_STASH][0] = 0 buildDataStack.push([[], stackNode]) return childrenToString(children as Child[]).finally(popNodeStack) }) ), ] as Promise<HtmlEscapedString[]>[] } else { throw e } } finally { popNodeStack() }
if (resArray.some((res) => (res as {}) instanceof Promise)) { const index = suspenseCounter++ const fallbackStr = await (typeof fallback === 'string' || Array.isArray(fallback) ? renderChildren([fallback]) : isUntrustedObject(fallback) ? renderUntrustedObject(fallback) : fallback.toString()) return raw(`<template id="H:${index}"></template>${fallbackStr}<!--/$-->`, [ ...(fallbackStr.callbacks || []), ({ phase, buffer, context }) => { if (phase === HtmlEscapedCallbackPhase.BeforeStream) { return } return Promise.all(resArray).then(async (htmlArray) => { htmlArray = htmlArray.flat() const content = htmlArray.join('') if (buffer) { buffer[0] = buffer[0].replace( new RegExp(`<template id="H:${index}"></template>.*?<!--/\\$-->`, 's'), () => content ) } let html = buffer ? '' : `<template data-hono-target="H:${index}">${content}</template><script${ nonce ? ` nonce="${nonce}"` : '' }>((d,c,n) => {c=d.currentScript.previousSiblingd=d.getElementById('H:${index}')if(!d)returndo{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')d.replaceWith(c.content)})(document)</script>`
const callbacks = htmlArray .map((html) => (html as HtmlEscapedString).callbacks || []) .flat() if (!callbacks.length) { return html }
if (phase === HtmlEscapedCallbackPhase.Stream) { html = await resolveCallback(html, HtmlEscapedCallbackPhase.BeforeStream, true, context) }
return raw(html, callbacks) }) }, ]) } else { return raw(resArray.join('')) }};(Suspense as HasRenderToDom)[DOM_RENDERER] = SuspenseDomRenderer
const textEncoder = new TextEncoder()/** * @experimental * `renderToReadableStream()` is an experimental feature. * The API might be changed. */export const renderToReadableStream = ( content: HtmlEscapedString | JSXNode | Promise<HtmlEscapedString>, onError: (e: unknown) => string | void = console.trace): ReadableStream<Uint8Array> => { let cancelled = false const reader = new ReadableStream<Uint8Array>({ async start(controller) { try { if (content instanceof JSXNode) { // aJSXNode.toString() returns a string or Promise<string> and string is already escaped content = content.toString() as HtmlEscapedString | Promise<HtmlEscapedString> } const context = typeof content === 'object' ? content : {} const resolved = await resolveCallback( content, HtmlEscapedCallbackPhase.BeforeStream, true, context ) if (!cancelled) { controller.enqueue(textEncoder.encode(resolved)) }
let resolvedCount = 0 const callbacks: Promise<void>[] = [] const then = (promise: Promise<string>) => { callbacks.push( promise .catch((err) => { console.log(err) onError(err) return '' }) .then(async (res) => { res = await resolveCallback( res, HtmlEscapedCallbackPhase.BeforeStream, true, context ) ;(res as HtmlEscapedString).callbacks ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context })) // eslint-disable-next-line @typescript-eslint/no-explicit-any .filter<Promise<string>>(Boolean as any) .forEach(then) resolvedCount++ if (!cancelled) { controller.enqueue(textEncoder.encode(res)) } }) ) } ;(resolved as HtmlEscapedString).callbacks ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context })) // eslint-disable-next-line @typescript-eslint/no-explicit-any .filter<Promise<string>>(Boolean as any) .forEach(then) while (resolvedCount !== callbacks.length) { await Promise.all(callbacks) } } catch (e) { // maybe the connection was closed onError(e) }
if (!cancelled) { controller.close() } }, cancel() { cancelled = true }, }) return reader}