Skip to content
Myr

streaming.test.tsx

This file

Path

src/jsx/streaming.test.tsx

1,281 lines · 36.3 KiB · TypeScript

Last changed by

Merge commit from forkTaku Amanobefore adoption2b8ed40

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–6why, one step back
1/** @jsxImportSource ./ */
2/* eslint-disable @typescript-eslint/no-explicit-any */3import { JSDOM } from 'jsdom'4import { raw } from '../helper/html'5import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html'6import type { HtmlEscapedString } from '../utils/html'

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 7–8why, one step back
7import { createContext, useContext } from './context'
8import { buildDataStack } from './dom/render'

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 9–11why, one step back
9import { use } from './hooks'
10import { Suspense, renderToReadableStream, StreamingContext } from './streaming'11

Merge commit from forkTaku Amanobefore adoption2b8ed40

lines 12–14why, one step back
12const unsafeHtml = '<img src=x onerror=alert(1)>'
13const escapedUnsafeHtml = '&lt;img src=x onerror=alert(1)&gt;'14

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 15–20why, one step back
15function replacementResult(html: string) {
16 const document = new JSDOM(html, { runScripts: 'dangerously' }).window.document17 document.querySelectorAll('template, script').forEach((e) => e.remove())18 return document.body.innerHTML19}20

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 21–29why, one step back
21async function drainStream(stream: unknown): Promise<string> {
22 const textDecoder = new TextDecoder()23 let html = ''24 for await (const chunk of stream as any) {25 html += textDecoder.decode(chunk)26 }27 return html28}29

Merge commit from forkTaku Amanobefore adoption2b8ed40

lines 30–56why, one step back
30async function stringify(node: { toString(): string | Promise<string> }): Promise<string> {
31 return String(32 await resolveCallback(await node.toString(), HtmlEscapedCallbackPhase.Stringify, false, {})33 )34}3536async function readInitialSuspenseChunk(fallback: unknown): Promise<string> {37 let resolve!: () => void38 const promise = new Promise<void>((done) => (resolve = done))39 const Async = async () => {40 await promise41 return <span>done</span>42 }43 const reader = renderToReadableStream(44 <Suspense fallback={fallback}>45 <Async />46 </Suspense>47 ).getReader()4849 const first = await reader.read()50 resolve()51 while (!(await reader.read()).done) {52 // Drain the retry so it cannot outlive the test.53 }54 return new TextDecoder().decode(first.value)55}56

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 57–62why, one step back
57describe('Streaming', () => {
58 let suspenseCounter = 059 afterEach(() => {60 suspenseCounter++61 })62

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 63–102why, one step back
63 it('Suspense / async component returning an array', async () => {
64 const Content = async () => {65 await new Promise((resolve) => setTimeout(resolve, 10))66 return [<h1>Hello</h1>, <h2>World</h2>]67 }6869 const stream = renderToReadableStream(70 <Suspense fallback={<p>Loading...</p>}>71 <Content />72 </Suspense>73 )7475 const chunks = []76 const textDecoder = new TextDecoder()77 for await (const chunk of stream as any) {78 chunks.push(textDecoder.decode(chunk))79 }8081 expect(chunks[0]).toBe(82 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`83 )84 expect(chunks[1]).toContain(85 `<template data-hono-target="H:${suspenseCounter}"><h1>Hello</h1><h2>World</h2></template>`86 )87 })8889 it('preserves callbacks in a streamed async component array', async () => {90 const phases: number[] = []91 const Content = async () => [92 raw('Hello', [({ phase }) => void phases.push(phase)]),93 <span>World</span>,94 ]9596 const html = await drainStream(renderToReadableStream(<Content />))9798 expect(html).toBe('Hello<span>World</span>')99 expect(phases).toEqual([HtmlEscapedCallbackPhase.BeforeStream, HtmlEscapedCallbackPhase.Stream])100 suspenseCounter--101 })102

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 103–721why, one step back
103 it('Suspense / renderToReadableStream', async () => {
104 let contentEvaluatedCount = 0105 const Content = () => {106 contentEvaluatedCount++107 const content = new Promise<HtmlEscapedString>((resolve) =>108 setTimeout(() => resolve(<h1>Hello</h1>), 10)109 )110 return content111 }112113 const stream = renderToReadableStream(114 <Suspense fallback={<p>Loading...</p>}>115 <Content />116 </Suspense>117 )118119 const chunks = []120 const textDecoder = new TextDecoder()121 for await (const chunk of stream as any) {122 chunks.push(textDecoder.decode(chunk))123 }124125 expect(chunks).toEqual([126 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,127 `<template data-hono-target="H:${suspenseCounter}"><h1>Hello</h1></template><script>128((d,c,n) => {129c=d.currentScript.previousSibling130d=d.getElementById('H:${suspenseCounter}')131if(!d)return132do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')133d.replaceWith(c.content)134})(document)135</script>`,136 ])137138 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(139 '<h1>Hello</h1>'140 )141142 expect(contentEvaluatedCount).toEqual(1)143 })144145 it('Suspense with StreamingContext', async () => {146 let contentEvaluatedCount = 0147 const Content = () => {148 contentEvaluatedCount++149 const content = new Promise<HtmlEscapedString>((resolve) =>150 setTimeout(() => resolve(<h1>Hello</h1>), 10)151 )152 return content153 }154155 const stream = renderToReadableStream(156 <StreamingContext value={{ scriptNonce: 'test-nonce' }}>157 <Suspense fallback={<p>Loading...</p>}>158 <Content />159 </Suspense>160 </StreamingContext>161 )162163 const chunks = []164 const textDecoder = new TextDecoder()165 for await (const chunk of stream as any) {166 chunks.push(textDecoder.decode(chunk))167 }168169 expect(chunks).toEqual([170 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,171 `<template data-hono-target="H:${suspenseCounter}"><h1>Hello</h1></template><script nonce="test-nonce">172((d,c,n) => {173c=d.currentScript.previousSibling174d=d.getElementById('H:${suspenseCounter}')175if(!d)return176do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')177d.replaceWith(c.content)178})(document)179</script>`,180 ])181182 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(183 '<h1>Hello</h1>'184 )185186 expect(contentEvaluatedCount).toEqual(1)187 })188189 it('`throw promise` inside Suspense', async () => {190 let contentEvaluatedCount = 0191 let resolvedContent: HtmlEscapedString | undefined = undefined192 const Content = () => {193 contentEvaluatedCount++194 if (!resolvedContent) {195 throw new Promise<void>((resolve) =>196 setTimeout(() => {197 resolvedContent = (<p>thrown a promise then resolved</p>) as HtmlEscapedString198 resolve()199 }, 10)200 )201 }202 return resolvedContent203 }204205 const stream = renderToReadableStream(206 <Suspense fallback={<p>Loading...</p>}>207 <Content />208 </Suspense>209 )210211 const chunks = []212 const textDecoder = new TextDecoder()213 for await (const chunk of stream as any) {214 chunks.push(textDecoder.decode(chunk))215 }216217 expect(chunks).toEqual([218 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,219 `<template data-hono-target="H:${suspenseCounter}"><p>thrown a promise then resolved</p></template><script>220((d,c,n) => {221c=d.currentScript.previousSibling222d=d.getElementById('H:${suspenseCounter}')223if(!d)return224do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')225d.replaceWith(c.content)226})(document)227</script>`,228 ])229230 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(231 '<p>thrown a promise then resolved</p>'232 )233234 expect(contentEvaluatedCount).toEqual(2)235 })236237 it('simple content inside Suspense', async () => {238 const Content = () => {239 return <h1>Hello</h1>240 }241242 const stream = renderToReadableStream(243 <Suspense fallback={<p>Loading...</p>}>244 <Content />245 </Suspense>246 )247248 const chunks = []249 const textDecoder = new TextDecoder()250 for await (const chunk of stream as any) {251 chunks.push(textDecoder.decode(chunk))252 }253254 expect(chunks).toEqual(['<h1>Hello</h1>'])255256 suspenseCounter -= 1 // fallback is not rendered257 })258259 it('nullish children', async () => {260 const stream = renderToReadableStream(261 <div>262 <Suspense fallback={<p>Loading...</p>}>{[null, undefined]}</Suspense>263 </div>264 )265266 const chunks = []267 const textDecoder = new TextDecoder()268 for await (const chunk of stream as any) {269 chunks.push(textDecoder.decode(chunk))270 }271272 expect(chunks).toEqual(['<div></div>'])273274 suspenseCounter -= 1 // fallback is not rendered275 })276277 it('without children', async () => {278 const stream = renderToReadableStream(279 <div>280 <Suspense fallback={<p>Loading...</p>}></Suspense>281 </div>282 )283284 const chunks = []285 const textDecoder = new TextDecoder()286 for await (const chunk of stream as any) {287 chunks.push(textDecoder.decode(chunk))288 }289290 expect(chunks).toEqual(['<div></div>'])291292 suspenseCounter -= 1 // fallback is not rendered293 })294295 it('only a "false" child', async () => {296 const stream = renderToReadableStream(297 <div>298 <Suspense fallback={<p>Loading...</p>}>{false}</Suspense>299 </div>300 )301302 const chunks = []303 const textDecoder = new TextDecoder()304 for await (const chunk of stream as any) {305 chunks.push(textDecoder.decode(chunk))306 }307308 expect(chunks).toEqual(['<div></div>'])309310 suspenseCounter -= 1 // fallback is not rendered311 })312313 it('async nullish children', async () => {314 let resolved = false315 const Content = () => {316 if (!resolved) {317 resolved = true318 throw new Promise<void>((r) =>319 setTimeout(() => {320 resolved = true321 r()322 }, 10)323 )324 }325 return <h1>Hello</h1>326 }327328 const stream = renderToReadableStream(329 <Suspense fallback={<p>Loading...</p>}>330 <Content />331 {[null, undefined]}332 </Suspense>333 )334335 const chunks = []336 const textDecoder = new TextDecoder()337 for await (const chunk of stream as any) {338 chunks.push(textDecoder.decode(chunk))339 }340341 expect(chunks).toEqual([342 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,343 `<template data-hono-target="H:${suspenseCounter}"><h1>Hello</h1></template><script>344((d,c,n) => {345c=d.currentScript.previousSibling346d=d.getElementById('H:${suspenseCounter}')347if(!d)return348do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')349d.replaceWith(c.content)350})(document)351</script>`,352 ])353354 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(355 '<h1>Hello</h1>'356 )357 })358359 it('boolean children', async () => {360 const stream = renderToReadableStream(361 <div>362 <Suspense fallback={<p>Loading...</p>}>{[true, false]}</Suspense>363 </div>364 )365366 const chunks = []367 const textDecoder = new TextDecoder()368 for await (const chunk of stream as any) {369 chunks.push(textDecoder.decode(chunk))370 }371372 expect(chunks).toEqual(['<div></div>'])373374 suspenseCounter -= 1 // fallback is not rendered375 })376377 it('async boolean children', async () => {378 let resolved = false379 const Content = () => {380 if (!resolved) {381 resolved = true382 throw new Promise<void>((r) =>383 setTimeout(() => {384 resolved = true385 r()386 }, 10)387 )388 }389 return <h1>Hello</h1>390 }391392 const stream = renderToReadableStream(393 <Suspense fallback={<p>Loading...</p>}>394 <Content />395 {[true, false]}396 </Suspense>397 )398399 const chunks = []400 const textDecoder = new TextDecoder()401 for await (const chunk of stream as any) {402 chunks.push(textDecoder.decode(chunk))403 }404405 expect(chunks).toEqual([406 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,407 `<template data-hono-target="H:${suspenseCounter}"><h1>Hello</h1></template><script>408((d,c,n) => {409c=d.currentScript.previousSibling410d=d.getElementById('H:${suspenseCounter}')411if(!d)return412do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')413d.replaceWith(c.content)414})(document)415</script>`,416 ])417418 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(419 '<h1>Hello</h1>'420 )421 })422423 it('children Suspense', async () => {424 const Content1 = () =>425 new Promise<HtmlEscapedString>((resolve) => setTimeout(() => resolve(<h1>Hello</h1>), 10))426 const Content2 = () =>427 new Promise<HtmlEscapedString>((resolve) => setTimeout(() => resolve(<h2>Hono</h2>), 10))428429 const stream = renderToReadableStream(430 <Suspense fallback={<p>Loading...</p>}>431 <Suspense fallback={<p>Loading sub content1...</p>}>432 <Content1 />433 </Suspense>434 <Suspense fallback={<p>Loading sub content2...</p>}>435 <Content2 />436 </Suspense>437 </Suspense>438 )439440 const chunks = []441 const textDecoder = new TextDecoder()442 for await (const chunk of stream as any) {443 chunks.push(textDecoder.decode(chunk))444 }445446 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(447 '<h1>Hello</h1><h2>Hono</h2>'448 )449450 suspenseCounter += 2451 })452453 it('children Suspense: Suspense and string', async () => {454 const Content1 = () =>455 new Promise<HtmlEscapedString>((resolve) => setTimeout(() => resolve(<h1>Hello</h1>), 10))456457 const stream = renderToReadableStream(458 <Suspense fallback={<p>Loading...</p>}>459 <Suspense fallback={<p>Loading sub content1...</p>}>460 <Content1 />461 </Suspense>462 Hono463 </Suspense>464 )465466 const chunks = []467 const textDecoder = new TextDecoder()468 for await (const chunk of stream as any) {469 chunks.push(textDecoder.decode(chunk))470 }471472 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(473 '<h1>Hello</h1>Hono'474 )475476 suspenseCounter += 1477 })478479 it('resolve(undefined)', async () => {480 const Content = async () => {481 const content = await Promise.resolve(undefined)482 return <p>{content}</p>483 }484485 const stream = renderToReadableStream(486 <Suspense fallback={<p>Loading...</p>}>487 <Content />488 </Suspense>489 )490491 const chunks = []492 const textDecoder = new TextDecoder()493 for await (const chunk of stream as any) {494 chunks.push(textDecoder.decode(chunk))495 }496497 expect(chunks).toEqual([498 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,499 `<template data-hono-target="H:${suspenseCounter}"><p></p></template><script>500((d,c,n) => {501c=d.currentScript.previousSibling502d=d.getElementById('H:${suspenseCounter}')503if(!d)return504do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')505d.replaceWith(c.content)506})(document)507</script>`,508 ])509510 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual('<p></p>')511 })512513 it('resolve(null)', async () => {514 const Content = async () => {515 const content = await Promise.resolve(null)516 return <p>{content}</p>517 }518519 const stream = renderToReadableStream(520 <Suspense fallback={<p>Loading...</p>}>521 <Content />522 </Suspense>523 )524525 const chunks = []526 const textDecoder = new TextDecoder()527 for await (const chunk of stream as any) {528 chunks.push(textDecoder.decode(chunk))529 }530531 expect(chunks).toEqual([532 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,533 `<template data-hono-target="H:${suspenseCounter}"><p></p></template><script>534((d,c,n) => {535c=d.currentScript.previousSibling536d=d.getElementById('H:${suspenseCounter}')537if(!d)return538do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')539d.replaceWith(c.content)540})(document)541</script>`,542 ])543544 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual('<p></p>')545 })546547 it('reject()', async () => {548 const Content = async () => {549 const content = await Promise.reject()550 return <p>{content}</p>551 }552553 const onError = vi.fn()554 const stream = renderToReadableStream(555 <Suspense fallback={<p>Loading...</p>}>556 <Content />557 </Suspense>,558 onError559 )560561 const chunks = []562 const textDecoder = new TextDecoder()563 for await (const chunk of stream as any) {564 chunks.push(textDecoder.decode(chunk))565 }566567 expect(onError).toBeCalledTimes(1)568569 expect(chunks).toEqual([570 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,571 '',572 ])573574 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(575 '<p>Loading...</p><!--/$-->'576 )577 })578579 it('closed()', async () => {580 const Content = async () => {581 await new Promise<void>((resolve) =>582 setTimeout(() => {583 vi.spyOn(ReadableStreamDefaultController.prototype, 'enqueue').mockImplementation(() => {584 throw new Error('closed')585 })586 resolve()587 }, 10)588 )589 return <p>content</p>590 }591592 const onError = vi.fn()593 const stream = renderToReadableStream(594 <>595 <Suspense fallback={<p>Loading...</p>}>596 <Content />597 </Suspense>598 <Suspense fallback={<p>Loading...</p>}>599 <Content />600 </Suspense>601 </>,602 onError603 )604605 const chunks = []606 const textDecoder = new TextDecoder()607 for await (const chunk of stream as any) {608 chunks.push(textDecoder.decode(chunk))609 }610611 expect(onError).toBeCalledTimes(1)612613 expect(chunks).toEqual([614 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$--><template id="H:${615 suspenseCounter + 1616 }"></template><p>Loading...</p><!--/$-->`,617 ])618619 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(620 '<p>Loading...</p><!--/$--><p>Loading...</p><!--/$-->'621 )622623 suspenseCounter++624 await new Promise((resolve) => setTimeout(resolve, 10))625 vi.restoreAllMocks()626 })627628 it('Multiple "await" call', async () => {629 const delayedContent = new Promise<HtmlEscapedString>((resolve) =>630 setTimeout(() => resolve(<h1>Hello</h1>), 10)631 )632 const delayedContent2 = new Promise<HtmlEscapedString>((resolve) =>633 setTimeout(() => resolve(<h2>World</h2>), 10)634 )635 const Content = async () => {636 const content = await delayedContent637 const content2 = await delayedContent2638 return (639 <>640 {content}641 {content2}642 </>643 )644 }645646 const stream = renderToReadableStream(647 <Suspense fallback={<p>Loading...</p>}>648 <Content />649 </Suspense>650 )651652 const chunks = []653 const textDecoder = new TextDecoder()654 for await (const chunk of stream as any) {655 chunks.push(textDecoder.decode(chunk))656 }657658 expect(chunks).toEqual([659 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,660 `<template data-hono-target="H:${suspenseCounter}"><h1>Hello</h1><h2>World</h2></template><script>661((d,c,n) => {662c=d.currentScript.previousSibling663d=d.getElementById('H:${suspenseCounter}')664if(!d)return665do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')666d.replaceWith(c.content)667})(document)668</script>`,669 ])670671 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(672 '<h1>Hello</h1><h2>World</h2>'673 )674 })675676 it('Complex fallback content', async () => {677 const delayedContent = new Promise<HtmlEscapedString>((resolve) =>678 setTimeout(() => resolve(<h1>Hello</h1>), 10)679 )680681 const Content = async () => {682 const content = await delayedContent683 return content684 }685686 const stream = renderToReadableStream(687 <Suspense688 fallback={689 <>690 Loading<span>...</span>691 </>692 }693 >694 <Content />695 </Suspense>696 )697698 const chunks = []699 const textDecoder = new TextDecoder()700 for await (const chunk of stream as any) {701 chunks.push(textDecoder.decode(chunk))702 }703704 expect(chunks).toEqual([705 `<template id="H:${suspenseCounter}"></template>Loading<span>...</span><!--/$-->`,706 `<template data-hono-target="H:${suspenseCounter}"><h1>Hello</h1></template><script>707((d,c,n) => {708c=d.currentScript.previousSibling709d=d.getElementById('H:${suspenseCounter}')710if(!d)return711do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')712d.replaceWith(c.content)713})(document)714</script>`,715 ])716717 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(718 '<h1>Hello</h1>'719 )720 })721

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 722–748why, one step back
722 it('renders Suspense fallback with outer context values', async () => {
723 const ThemeContext = createContext('default')724 const Fallback = () => <p>Loading {useContext(ThemeContext)}</p>725 const Content = () =>726 new Promise<HtmlEscapedString>((resolve) => setTimeout(() => resolve(<h1>Done</h1>), 10))727728 const stream = renderToReadableStream(729 <ThemeContext.Provider value='outer'>730 <Suspense fallback={<Fallback />}>731 <Content />732 </Suspense>733 </ThemeContext.Provider>734 )735736 const chunks = []737 const textDecoder = new TextDecoder()738 for await (const chunk of stream as any) {739 chunks.push(textDecoder.decode(chunk))740 }741742 expect(chunks[0]).toBe(743 `<template id="H:${suspenseCounter}"></template><p>Loading outer</p><!--/$-->`744 )745 expect(chunks.join('')).toContain('<h1>Done</h1>')746 expect(chunks.join('')).not.toContain('default')747 })748

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 749–1094why, one step back
749 it('nested Suspense', async () => {
750 const SubContent = () => {751 const content = new Promise<HtmlEscapedString>((resolve) =>752 setTimeout(() => resolve(<h2>World</h2>), 10)753 )754 return content755 }756757 const Content = () => {758 const content = new Promise<HtmlEscapedString>((resolve) =>759 setTimeout(760 () =>761 resolve(762 <>763 <h1>Hello</h1>764 <Suspense fallback={<p>Loading sub content...</p>}>765 <SubContent />766 </Suspense>767 </>768 ),769 10770 )771 )772 return content773 }774775 const stream = renderToReadableStream(776 <Suspense fallback={<p>Loading...</p>}>777 <Content />778 </Suspense>779 )780781 const chunks = []782 const textDecoder = new TextDecoder()783 for await (const chunk of stream as any) {784 chunks.push(textDecoder.decode(chunk))785 }786787 expect(chunks).toEqual([788 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,789 `<template data-hono-target="H:${suspenseCounter}"><h1>Hello</h1><template id=\"H:${790 suspenseCounter + 1791 }\"></template><p>Loading sub content...</p><!--/$--></template><script>792((d,c,n) => {793c=d.currentScript.previousSibling794d=d.getElementById('H:${suspenseCounter}')795if(!d)return796do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')797d.replaceWith(c.content)798})(document)799</script>`,800 `<template data-hono-target="H:${suspenseCounter + 1}"><h2>World</h2></template><script>801((d,c,n) => {802c=d.currentScript.previousSibling803d=d.getElementById('H:${suspenseCounter + 1}')804if(!d)return805do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')806d.replaceWith(c.content)807})(document)808</script>`,809 ])810811 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(812 '<h1>Hello</h1><h2>World</h2>'813 )814 suspenseCounter++815 })816817 it('In multiple Suspense, go ahead in the order of resolved', async () => {818 const SubContent2 = () => {819 const content = new Promise<HtmlEscapedString>((resolve) =>820 setTimeout(() => resolve(<p>first</p>), 20)821 )822 return content823 }824 const SubContent1 = () => {825 const content = new Promise<HtmlEscapedString>((resolve) =>826 setTimeout(827 () =>828 resolve(829 <Suspense fallback={<p>Loading content2...</p>}>830 <SubContent2 />831 </Suspense>832 ),833 10834 )835 )836 return content837 }838 const SubContent3 = () => {839 const content = new Promise<HtmlEscapedString>((resolve) =>840 setTimeout(() => resolve(<p>last</p>), 40)841 )842 return content843 }844845 const Content = () => {846 const content = new Promise<HtmlEscapedString>((resolve) =>847 setTimeout(848 () =>849 resolve(850 <>851 <Suspense fallback={<p>Loading content1...</p>}>852 <SubContent1 />853 </Suspense>854 <Suspense fallback={<p>Loading content3...</p>}>855 <SubContent3 />856 </Suspense>857 </>858 ),859 10860 )861 )862 return content863 }864865 const stream = renderToReadableStream(866 <Suspense fallback={<p>Loading...</p>}>867 <Content />868 </Suspense>869 )870871 const chunks = []872 const textDecoder = new TextDecoder()873 for await (const chunk of stream as any) {874 chunks.push(textDecoder.decode(chunk))875 }876877 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(878 '<p>first</p><p>last</p>'879 )880 })881882 it('Suspense with resolveStream', async () => {883 let contentEvaluatedCount = 0884 const Content = () => {885 contentEvaluatedCount++886 const content = new Promise<HtmlEscapedString>((resolve) =>887 setTimeout(() => resolve(<h1>Hello</h1>), 10)888 )889 return content890 }891892 const str = await resolveCallback(893 await (894 <Suspense fallback={<p>Loading...</p>}>895 <Content />896 </Suspense>897 ).toString(),898 HtmlEscapedCallbackPhase.Stream,899 false,900 {}901 )902903 expect(str).toEqual('<h1>Hello</h1>')904 expect(contentEvaluatedCount).toEqual(1)905 })906907 it('renderToReadableStream(str: string)', async () => {908 const str = '<h1>Hello</h1>'909 const stream = renderToReadableStream(raw(str))910911 const chunks = []912 const textDecoder = new TextDecoder()913 for await (const chunk of stream as any) {914 chunks.push(textDecoder.decode(chunk))915 }916917 expect(chunks).toEqual([str])918 })919920 it('renderToReadableStream(promise: Promise<HtmlEscapedString>)', async () => {921 const stream = renderToReadableStream(Promise.resolve(raw('<h1>Hello</h1>')))922923 const chunks = []924 const textDecoder = new TextDecoder()925 for await (const chunk of stream as any) {926 chunks.push(textDecoder.decode(chunk))927 }928929 expect(chunks).toEqual(['<h1>Hello</h1>'])930931 suspenseCounter++932 })933934 describe('use()', async () => {935 it('render to string', async () => {936 const promise = new Promise((resolve) => setTimeout(() => resolve('Hello from use()'), 0))937 const Content = () => {938 const message = use(promise)939 return <h1>{message}</h1>940 }941942 const str = await resolveCallback(943 await (944 <Suspense fallback={<p>Loading...</p>}>945 <Content />946 </Suspense>947 ).toString(),948 HtmlEscapedCallbackPhase.Stream,949 false,950 {}951 )952 expect(str).toEqual('<h1>Hello from use()</h1>')953 })954955 it('render to stream', async () => {956 const promise = new Promise((resolve) => setTimeout(() => resolve('Hello from use()'), 0))957 const Content = () => {958 const message = use(promise)959 return <h1>{message}</h1>960 }961962 const stream = renderToReadableStream(963 <Suspense fallback={<p>Loading...</p>}>964 <Content />965 </Suspense>966 )967968 const chunks = []969 const textDecoder = new TextDecoder()970 for await (const chunk of stream as any) {971 chunks.push(textDecoder.decode(chunk))972 }973974 expect(chunks).toEqual([975 `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`,976 `<template data-hono-target="H:${suspenseCounter}"><h1>Hello from use()</h1></template><script>977((d,c,n) => {978c=d.currentScript.previousSibling979d=d.getElementById('H:${suspenseCounter}')980if(!d)return981do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')982d.replaceWith(c.content)983})(document)984</script>`,985 ])986987 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(988 '<h1>Hello from use()</h1>'989 )990 })991 })992993 it('should not throw ERR_INVALID_STATE when reader is cancelled during nested Suspense streaming', async () => {994 const unhandled: unknown[] = []995 const onRejection = (e: unknown) => unhandled.push(e)996 process.on('unhandledRejection', onRejection)997998 const SubContent = async () => <h2>World</h2>999 const Content = async () => (1000 <>1001 <h1>Hello</h1>1002 <Suspense fallback={<p>Loading sub...</p>}>1003 <SubContent />1004 </Suspense>1005 </>1006 )10071008 const onError = vi.fn()1009 const stream = renderToReadableStream(1010 <Suspense fallback={<p>Loading...</p>}>1011 <Content />1012 </Suspense>,1013 onError1014 )10151016 const reader = stream.getReader()1017 const firstChunk = await reader.read()1018 expect(firstChunk.done).toBe(false)10191020 // Simulate client disconnect1021 await reader.cancel()10221023 // Wait for nested Suspense callbacks to fire against the closed controller1024 await new Promise((resolve) => setTimeout(resolve))10251026 expect(unhandled).toHaveLength(0)1027 expect(onError).not.toHaveBeenCalled()10281029 process.off('unhandledRejection', onRejection)1030 })10311032 it('should not call onError when reader is cancelled during a slow callback resolution', async () => {1033 const unhandled: unknown[] = []1034 const onRejection = (e: unknown) => unhandled.push(e)1035 process.on('unhandledRejection', onRejection)10361037 let signalCallbackStarted!: () => void1038 const callbackStarted = new Promise<void>((r) => {1039 signalCallbackStarted = r1040 })10411042 const Content = async () =>1043 raw('<p>content</p>', [1044 ((opts: any) => {1045 if (opts.phase === HtmlEscapedCallbackPhase.BeforeStream) {1046 signalCallbackStarted()1047 return new Promise<string>((r) => setTimeout(() => r('')))1048 }1049 return undefined1050 }) as any,1051 ])10521053 const onError = vi.fn()1054 const stream = renderToReadableStream(1055 <Suspense fallback={<p>Loading...</p>}>1056 <Content />1057 </Suspense>,1058 onError1059 )10601061 const reader = stream.getReader()1062 await reader.read()10631064 await callbackStarted1065 await reader.cancel()10661067 await new Promise((resolve) => setTimeout(resolve))10681069 expect(unhandled).toHaveLength(0)1070 expect(onError).not.toHaveBeenCalled()10711072 process.off('unhandledRejection', onRejection)1073 })10741075 it('should not throw when cancelled before initial content resolves', async () => {1076 const unhandled: unknown[] = []1077 const onRejection = (e: unknown) => unhandled.push(e)1078 process.on('unhandledRejection', onRejection)10791080 const onError = vi.fn()1081 const stream = renderToReadableStream(1082 Promise.resolve(raw('<p>slow content</p>') as HtmlEscapedString),1083 onError1084 )10851086 const reader = stream.getReader()1087 await reader.cancel()10881089 await new Promise((resolve) => setTimeout(resolve))10901091 expect(unhandled).toHaveLength(0)1092 expect(onError).not.toHaveBeenCalled()10931094 process.off('unhandledRejection', onRejection)

Merge commit from forkTaku Amanobefore adoptionfab3b13

lines 1095–1185why, one step back
1095 })
10961097 it('pops buildDataStack when a deferred re-render rejects', async () => {1098 const baseLength = buildDataStack.length10991100 const deferred = new Promise<string>((resolve) => setTimeout(() => resolve('x'), 10))1101 let first = true1102 const Content = () => {1103 if (first) {1104 // Suspend like use() does so Suspense defers the re-render.1105 first = false1106 throw deferred1107 }1108 throw new Error('boom')1109 }11101111 const onError = vi.fn(() => '')1112 const stream = renderToReadableStream(1113 <Suspense fallback={<p>Loading</p>}>1114 <Content />1115 </Suspense>,1116 onError1117 )1118 for await (const _ of stream as any) {1119 // drain1120 }11211122 expect(onError).toHaveBeenCalledTimes(1)1123 // The deferred re-render pushed a stack frame; rejecting must still pop it.1124 expect(buildDataStack.length).toBe(baseLength)1125 })11261127 it('isolates context between concurrent streaming renders', async () => {1128 // Default value is distinct from both requests so a cross-request leak1129 // (reading the other request's value) would be detectable.1130 const SessionContext = createContext('nobody')1131 const waits = new Map<string, Promise<void>>()1132 const entered = new Map<string, () => void>()11331134 const Dashboard = async ({ name }: { name: string }) => {1135 // Read context only after suspending, the pattern that previously leaked.1136 entered.get(name)?.()1137 await waits.get(name)1138 return <span>role:{useContext(SessionContext)}</span>1139 }11401141 const drain = async (value: string) => {1142 return drainStream(1143 renderToReadableStream(1144 <SessionContext.Provider value={value}>1145 <Dashboard name={value} />1146 </SessionContext.Provider>1147 )1148 )1149 }11501151 let resolveAdmin!: () => void1152 let resolveGuest!: () => void1153 waits.set(1154 'admin',1155 new Promise<void>((resolve) => {1156 resolveAdmin = resolve1157 })1158 )1159 waits.set(1160 'guest',1161 new Promise<void>((resolve) => {1162 resolveGuest = resolve1163 })1164 )1165 const adminEntered = new Promise<void>((resolve) => {1166 entered.set('admin', resolve)1167 })1168 const guestEntered = new Promise<void>((resolve) => {1169 entered.set('guest', resolve)1170 })11711172 const adminDrain = drain('admin')1173 const guestDrain = drain('guest')11741175 await Promise.all([adminEntered, guestEntered])1176 resolveGuest()1177 await Promise.resolve()1178 resolveAdmin()11791180 const [adminHtml, guestHtml] = await Promise.all([adminDrain, guestDrain])11811182 expect(adminHtml).toContain('role:admin')1183 expect(adminHtml).not.toContain('role:guest')1184 expect(guestHtml).toContain('role:guest')1185 expect(guestHtml).not.toContain('role:admin')

Merge commit from forkTaku Amanobefore adoption2b8ed40

lines 1186–1279why, one step back
1186 })
11871188 describe('escaping', () => {1189 it('escapes string children with an asynchronous sibling', async () => {1190 const Async = async () => <span>done</span>1191 const node = (1192 <Suspense fallback='loading'>1193 {unsafeHtml}1194 <Async />1195 </Suspense>1196 )11971198 expect(await stringify(node)).toBe(`${escapedUnsafeHtml}<span>done</span>`)1199 const streamed = await drainStream(renderToReadableStream(node))1200 expect(streamed).toContain(escapedUnsafeHtml)1201 expect(streamed).not.toContain(unsafeHtml)1202 })12031204 it('escapes nested array strings', async () => {1205 expect(await stringify(<Suspense fallback='loading'>{[[[unsafeHtml]]]}</Suspense>)).toBe(1206 escapedUnsafeHtml1207 )1208 })12091210 it('escapes a primitive fallback in the initial stream chunk', async () => {1211 const initialChunk = await readInitialSuspenseChunk(unsafeHtml)12121213 expect(initialChunk).toContain(escapedUnsafeHtml)1214 expect(initialChunk).not.toContain(unsafeHtml)1215 })12161217 it('escapes untrusted object fallbacks', async () => {1218 const object = { toString: () => unsafeHtml }1219 const asyncObject = { toString: async () => unsafeHtml }1220 const rawObject = { toString: () => raw(unsafeHtml) }12211222 for (const fallback of [object, asyncObject, rawObject]) {1223 const initialChunk = await readInitialSuspenseChunk(fallback)1224 expect(initialChunk).toContain(escapedUnsafeHtml)1225 expect(initialChunk).not.toContain(unsafeHtml)1226 }1227 })12281229 it('preserves an explicitly trusted fallback', async () => {1230 expect(await readInitialSuspenseChunk(raw('<strong>trusted</strong>'))).toContain(1231 '<strong>trusted</strong>'1232 )1233 })12341235 it('does not interpret replacement patterns in content', async () => {1236 const content = "literal $& $` $'"1237 const Async = async () => <span>done</span>12381239 expect(1240 await stringify(1241 <Suspense fallback='loading'>1242 {content}1243 <Async />1244 </Suspense>1245 )1246 ).toBe('literal $&amp; $` $&#39;<span>done</span>')1247 })12481249 it('escapes untrusted object children', async () => {1250 const object = { toString: () => unsafeHtml }1251 const asyncObject = { toString: async () => unsafeHtml }1252 const rawObject = { toString: () => raw(unsafeHtml) }12531254 for (const child of [object, asyncObject, rawObject]) {1255 const node = <Suspense fallback='loading'>{child as never}</Suspense>1256 expect(await stringify(node)).toBe(escapedUnsafeHtml)1257 const streamed = await drainStream(renderToReadableStream(node))1258 expect(streamed).toContain(escapedUnsafeHtml)1259 expect(streamed).not.toContain(unsafeHtml)1260 }1261 })12621263 it('preserves explicitly trusted children', async () => {1264 expect(1265 await stringify(<Suspense fallback='loading'>{raw('<strong>trusted</strong>')}</Suspense>)1266 ).toBe('<strong>trusted</strong>')1267 })12681269 it('keeps benign object stringification visible', async () => {1270 expect(await stringify(<Suspense fallback='loading'>{{} as never}</Suspense>)).toBe(1271 '[object Object]'1272 )1273 })12741275 it('keeps a direct Promise child unchanged', async () => {1276 expect(1277 await stringify(<Suspense fallback='loading'>{Promise.resolve('resolved')}</Suspense>)1278 ).toBe('[object Promise]')1279 })

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1280–1281why, one step back
1280 })
1281})