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
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–8why, one step back1/**2 * @module3 * This module enables JSX to supports streaming Response.4 */56import { raw } from '../helper/html'7import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'8import type { HtmlEscapedString } from '../utils/html'chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2
line 9why, one step back9import type { Child, FC, PropsWithChildren, Context as JSXContext } from './'Merge commit from forkTaku Amanobefore adoption2b8ed40
line 10why, one step back10import { isUntrustedObject, JSXNode, renderChildren, renderUntrustedObject } from './base'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 11–12why, one step back11import { childrenToString } from './components'12import { DOM_RENDERER, DOM_STASH } from './constants'Merge commit from forkTaku Amanobefore adoptionfab3b13
line 13why, one step back13import { captureRenderContext, createContext, useContext } from './context'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 14–35why, one step back14import { Suspense as SuspenseDomRenderer } from './dom/components'15import { buildDataStack } from './dom/render'16import type { HasRenderToDom, NodeObject } from './dom/render'1718/**19 * Used to specify nonce for scripts generated by `Suspense` and `ErrorBoundary`.20 *21 * @example22 * ```tsx23 * <StreamingContext.Provider value={{ scriptNonce: 'test-nonce' }}>24 * <Suspense fallback={<p>Loading...</p>}>25 * <Content />26 * </Suspense>27 * </StreamingContext.Provider>28 * ```29 */30export const StreamingContext: JSXContext<{ scriptNonce: string } | null> = createContext<{31 scriptNonce: string32} | null>(null)3334let suspenseCounter = 035Merge commit from forkTaku Amanobefore adoption2b8ed40
lines 36–44why, one step back36const serializeBoundaryChild = (child: Child): string | Promise<string> =>37 typeof child === 'string' || Array.isArray(child)38 ? renderChildren([child])39 : child == null || typeof child === 'boolean'40 ? ''41 : isUntrustedObject(child)42 ? renderUntrustedObject(child)43 : child.toString()44Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 45–64why, one step back45/**46 * @experimental47 * `Suspense` is an experimental feature.48 * The API might be changed.49 */50// eslint-disable-next-line @typescript-eslint/no-explicit-any51export const Suspense: FC<PropsWithChildren<{ fallback: any }>> = async ({52 children,53 fallback,54}) => {55 if (!Array.isArray(children)) {56 children = [children]57 }5859 const nonce = useContext(StreamingContext)?.scriptNonce6061 let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []6263 // for use() hook64 const stackNode = { [DOM_STASH]: [0, []] } as unknown as NodeObjectMerge commit from forkTaku Amanobefore adoptionfab3b13
line 65why, one step back65 const popNodeStack = () => {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 66–71why, one step back66 buildDataStack.pop()67 }6869 try {70 stackNode[DOM_STASH][0] = 071 buildDataStack.push([[], stackNode])Merge commit from forkTaku Amanobefore adoption2b8ed40
line 72why, one step back72 resArray = children.map(serializeBoundaryChild) as HtmlEscapedString[]Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 73–74why, one step back73 } catch (e) {74 if (e instanceof Promise) {Merge commit from forkTaku Amanobefore adoptionfab3b13
lines 75–77why, one step back75 // Capture before deferring: on the fallback path the render context is76 // observable here but not in the `.then()` below.77 const resume = captureRenderContext()Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 78why, one step back78 resArray = [Merge commit from forkTaku Amanobefore adoptionfab3b13
lines 79–85why, one step back79 e.then(() =>80 resume(() => {81 stackNode[DOM_STASH][0] = 082 buildDataStack.push([[], stackNode])83 return childrenToString(children as Child[]).finally(popNodeStack)84 })85 ),Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 86–95why, one step back86 ] as Promise<HtmlEscapedString[]>[]87 } else {88 throw e89 }90 } finally {91 popNodeStack()92 }9394 if (resArray.some((res) => (res as {}) instanceof Promise)) {95 const index = suspenseCounter++Merge commit from forkTaku Amanobefore adoption2b8ed40
lines 96–100why, one step back96 const fallbackStr = await (typeof fallback === 'string' || Array.isArray(fallback)97 ? renderChildren([fallback])98 : isUntrustedObject(fallback)99 ? renderUntrustedObject(fallback)100 : fallback.toString())Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 101–111why, one step back101 return raw(`<template id="H:${index}"></template>${fallbackStr}<!--/$-->`, [102 ...(fallbackStr.callbacks || []),103 ({ phase, buffer, context }) => {104 if (phase === HtmlEscapedCallbackPhase.BeforeStream) {105 return106 }107 return Promise.all(resArray).then(async (htmlArray) => {108 htmlArray = htmlArray.flat()109 const content = htmlArray.join('')110 if (buffer) {111 buffer[0] = buffer[0].replace(fix(jsx): replace Suspense and ErrorBoundary content across newlines (#5380)Neil Daquioagbefore adoptioncb5bea3
line 112why, one step back112 new RegExp(`<template id="H:${index}"></template>.*?<!--/\\$-->`, 's'),Merge commit from forkTaku Amanobefore adoption2b8ed40
line 113why, one step back113 () => contentMerge commit from forkYusuke Wadabefore adoptionf0b094d
lines 114–231why, one step back114 )115 }116 let html = buffer117 ? ''118 : `<template data-hono-target="H:${index}">${content}</template><script${119 nonce ? ` nonce="${nonce}"` : ''120 }>121((d,c,n) => {122c=d.currentScript.previousSibling123d=d.getElementById('H:${index}')124if(!d)return125do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')126d.replaceWith(c.content)127})(document)128</script>`129130 const callbacks = htmlArray131 .map((html) => (html as HtmlEscapedString).callbacks || [])132 .flat()133 if (!callbacks.length) {134 return html135 }136137 if (phase === HtmlEscapedCallbackPhase.Stream) {138 html = await resolveCallback(html, HtmlEscapedCallbackPhase.BeforeStream, true, context)139 }140141 return raw(html, callbacks)142 })143 },144 ])145 } else {146 return raw(resArray.join(''))147 }148}149;(Suspense as HasRenderToDom)[DOM_RENDERER] = SuspenseDomRenderer150151const textEncoder = new TextEncoder()152/**153 * @experimental154 * `renderToReadableStream()` is an experimental feature.155 * The API might be changed.156 */157export const renderToReadableStream = (158 content: HtmlEscapedString | JSXNode | Promise<HtmlEscapedString>,159 onError: (e: unknown) => string | void = console.trace160): ReadableStream<Uint8Array> => {161 let cancelled = false162 const reader = new ReadableStream<Uint8Array>({163 async start(controller) {164 try {165 if (content instanceof JSXNode) {166 // aJSXNode.toString() returns a string or Promise<string> and string is already escaped167 content = content.toString() as HtmlEscapedString | Promise<HtmlEscapedString>168 }169 const context = typeof content === 'object' ? content : {}170 const resolved = await resolveCallback(171 content,172 HtmlEscapedCallbackPhase.BeforeStream,173 true,174 context175 )176 if (!cancelled) {177 controller.enqueue(textEncoder.encode(resolved))178 }179180 let resolvedCount = 0181 const callbacks: Promise<void>[] = []182 const then = (promise: Promise<string>) => {183 callbacks.push(184 promise185 .catch((err) => {186 console.log(err)187 onError(err)188 return ''189 })190 .then(async (res) => {191 res = await resolveCallback(192 res,193 HtmlEscapedCallbackPhase.BeforeStream,194 true,195 context196 )197 ;(res as HtmlEscapedString).callbacks198 ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context }))199 // eslint-disable-next-line @typescript-eslint/no-explicit-any200 .filter<Promise<string>>(Boolean as any)201 .forEach(then)202 resolvedCount++203 if (!cancelled) {204 controller.enqueue(textEncoder.encode(res))205 }206 })207 )208 }209 ;(resolved as HtmlEscapedString).callbacks210 ?.map((c) => c({ phase: HtmlEscapedCallbackPhase.Stream, context }))211 // eslint-disable-next-line @typescript-eslint/no-explicit-any212 .filter<Promise<string>>(Boolean as any)213 .forEach(then)214 while (resolvedCount !== callbacks.length) {215 await Promise.all(callbacks)216 }217 } catch (e) {218 // maybe the connection was closed219 onError(e)220 }221222 if (!cancelled) {223 controller.close()224 }225 },226 cancel() {227 cancelled = true228 },229 })230 return reader231}