Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Introduce streaming API with Suspense and use. #1630

Merged
merged 31 commits into from
Nov 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
0ea80f5
feat(jsx): Support async component.
usualoma Oct 28, 2023
0d5e4e0
chore: denoify
usualoma Oct 28, 2023
31d59bb
feat: Support nested async components.
usualoma Oct 29, 2023
5d357fd
chore: denoify
usualoma Oct 29, 2023
35d7c4e
Remove unintended file from commit.
usualoma Oct 30, 2023
1f5d521
test(jsx): Add test for html tagged template strings.
usualoma Oct 30, 2023
405f729
feat: Introduce streaming API with `Suspense` and `use`.
usualoma Oct 30, 2023
2285b0d
chore: denoify
usualoma Oct 30, 2023
442538e
"use" receives only Promise.
usualoma Oct 30, 2023
b154592
feat: Support multiple calls and nested calls to "use".
usualoma Oct 30, 2023
d7efbab
refactor: tweaks replacement script.
usualoma Oct 30, 2023
2d15249
test: Add test for replacement result of streaming
usualoma Oct 30, 2023
04f1c24
chore: denoify
usualoma Oct 30, 2023
bd7d682
test: Add test "Complex fallback content"
usualoma Oct 30, 2023
3d36782
refactor: Add "typescript-eslint/no-explicit-any".
usualoma Oct 30, 2023
ec17ac9
Use jsdom instead of happy-dom due to ci failure.
usualoma Oct 30, 2023
4535cc1
test: update test data for suspense.
usualoma Oct 30, 2023
1ae15c7
refactor: Remove excessive exports
usualoma Oct 30, 2023
6ee8349
refactor: Changed initialization of `useContexts[]` to clarify intent.
usualoma Oct 30, 2023
6792acb
perf: improve `renderToReadableStream()` performance.
usualoma Oct 30, 2023
d25703d
chore: denoify
usualoma Oct 30, 2023
e4ba60b
pref: Shortened the output JS a bit.
usualoma Oct 31, 2023
582a6fa
pref: Delete unneeded condition
usualoma Oct 31, 2023
5bb7323
docs(jsx/streaming): Add `@experimental` flag to streaming API.
usualoma Nov 5, 2023
d156c4e
fix(jsx/streadming): fix loop when using fullfilled Promise with null…
usualoma Nov 5, 2023
b91a87d
fix(jsx/streaming): Catch unhandledRejection to avoid streaming not b…
usualoma Nov 5, 2023
fa9487b
chore(jsx/streaming): Add entries for jsx/streaming to package.json.
usualoma Nov 5, 2023
ec12034
chore: denoify
usualoma Nov 5, 2023
f4589b7
feat(jsx/streaming): Support the Async Component inside Suspense.
usualoma Nov 5, 2023
979be85
chore: denoify
usualoma Nov 5, 2023
1573ec1
feat(jsx/streaming): remove implementation of `use()`.
usualoma Nov 5, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 24 additions & 8 deletions deno_dist/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export interface ContextVariableMap {}

export interface ContextRenderer {}
interface DefaultRenderer {
(content: string): Response | Promise<Response>
(content: string | Promise<string>): Response | Promise<Response>
}
export type Renderer = ContextRenderer extends Function ? ContextRenderer : DefaultRenderer

Expand Down Expand Up @@ -75,8 +75,10 @@ interface JSONTRespond {
}

interface HTMLRespond {
(html: string, status?: StatusCode, headers?: HeaderRecord): Response
(html: string, init?: ResponseInit): Response
(html: string | Promise<string>, status?: StatusCode, headers?: HeaderRecord):
| Response
| Promise<Response>
(html: string | Promise<string>, init?: ResponseInit): Response | Promise<Response>
}

type ContextOptions<E extends Env> = {
Expand Down Expand Up @@ -106,7 +108,7 @@ export class Context<
private _pH: Record<string, string> | undefined = undefined // _preparedHeaders
private _res: Response | undefined
private _init = true
private _renderer: Renderer = (content: string) => this.html(content)
private _renderer: Renderer = (content: string | Promise<string>) => this.html(content)
private notFoundHandler: NotFoundHandler<E> = () => new Response()

constructor(req: HonoRequest<P, I['out']>, options?: ContextOptions<E>) {
Expand Down Expand Up @@ -356,15 +358,29 @@ export class Context<
}

html: HTMLRespond = (
html: string,
html: string | Promise<string>,
arg?: StatusCode | ResponseInit,
headers?: HeaderRecord
): Response => {
): Response | Promise<Response> => {
this._pH ??= {}
this._pH['content-type'] = 'text/html; charset=UTF-8'

if (typeof html === 'object') {
if (!(html instanceof Promise)) {
html = (html as string).toString() // HtmlEscapedString object to string
}
if ((html as string | Promise<string>) instanceof Promise) {
return (html as unknown as Promise<string>).then((html) => {
return typeof arg === 'number'
? this.newResponse(html, arg, headers)
: this.newResponse(html, arg)
})
}
}

return typeof arg === 'number'
? this.newResponse(html, arg, headers)
: this.newResponse(html, arg)
? this.newResponse(html as string, arg, headers)
: this.newResponse(html as string, arg)
}

redirect = (location: string, status: StatusCode = 302): Response => {
Expand Down
16 changes: 12 additions & 4 deletions deno_dist/helper/html/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { escapeToBuffer } from '../../utils/html.ts'
import { escapeToBuffer, stringBufferToString } from '../../utils/html.ts'
import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html.ts'

export const raw = (value: unknown): HtmlEscapedString => {
Expand All @@ -8,7 +8,10 @@ export const raw = (value: unknown): HtmlEscapedString => {
return escapedString
}

export const html = (strings: TemplateStringsArray, ...values: unknown[]): HtmlEscapedString => {
export const html = (
strings: TemplateStringsArray,
...values: unknown[]
): HtmlEscapedString | Promise<HtmlEscapedString> => {
const buffer: StringBuffer = ['']

for (let i = 0, len = strings.length - 1; i < len; i++) {
Expand All @@ -27,13 +30,18 @@ export const html = (strings: TemplateStringsArray, ...values: unknown[]): HtmlE
(typeof child === 'object' && (child as HtmlEscaped).isEscaped) ||
typeof child === 'number'
) {
buffer[0] += child
const tmp = child.toString()
if (tmp instanceof Promise) {
buffer.unshift('', tmp)
} else {
buffer[0] += tmp
}
} else {
escapeToBuffer(child.toString(), buffer)
}
}
}
buffer[0] += strings[strings.length - 1]

return raw(buffer[0])
return buffer.length === 1 ? raw(buffer[0]) : stringBufferToString(buffer).then((str) => raw(str))
}
22 changes: 14 additions & 8 deletions deno_dist/jsx/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { escapeToBuffer } from '../utils/html.ts'
import { escapeToBuffer, stringBufferToString } from '../utils/html.ts'
import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html.ts'
import type { IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements.ts'

Expand All @@ -8,7 +8,7 @@ type Props = Record<string, any>
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace JSX {
type Element = HtmlEscapedString
type Element = HtmlEscapedString | Promise<HtmlEscapedString>
interface ElementChildrenAttribute {
children: Child
}
Expand Down Expand Up @@ -76,15 +76,17 @@ const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void
typeof child === 'number' ||
(child as unknown as { isEscaped: boolean }).isEscaped
) {
buffer[0] += child
;(buffer[0] as string) += child
} else if (child instanceof Promise) {
buffer.unshift('', child)
} else {
// `child` type is `Child[]`, so stringify recursively
childrenToStringToBuffer(child, buffer)
}
}
}

type Child = string | number | JSXNode | Child[]
export type Child = string | Promise<string> | number | JSXNode | Child[]
export class JSXNode implements HtmlEscaped {
tag: string | Function
props: Props
Expand All @@ -96,10 +98,10 @@ export class JSXNode implements HtmlEscaped {
this.children = children
}

toString(): string {
toString(): string | Promise<string> {
const buffer: StringBuffer = ['']
this.toStringToBuffer(buffer)
return buffer[0]
return buffer.length === 1 ? buffer[0] : stringBufferToString(buffer)
}

toStringToBuffer(buffer: StringBuffer): void {
Expand Down Expand Up @@ -172,7 +174,9 @@ class JSXFunctionNode extends JSXNode {
children: children.length <= 1 ? children[0] : children,
})

if (res instanceof JSXNode) {
if (res instanceof Promise) {
buffer.unshift('', res)
} else if (res instanceof JSXNode) {
res.toStringToBuffer(buffer)
} else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {
buffer[0] += res
Expand Down Expand Up @@ -201,7 +205,9 @@ const jsxFn = (
}
}

export type FC<T = Props> = (props: T & { children?: Child }) => HtmlEscapedString
export type FC<T = Props> = (
props: T & { children?: Child }
) => HtmlEscapedString | Promise<HtmlEscapedString>

const shallowEqual = (a: Props, b: Props): boolean => {
if (a === b) {
Expand Down
100 changes: 100 additions & 0 deletions deno_dist/jsx/streaming.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import type { HtmlEscapedString } from '../utils/html.ts'
import type { FC, Child } from './index.ts'

let suspenseCounter = 0

async function childrenToString(children: Child): Promise<string> {
try {
return children.toString()
} catch (e) {
if (e instanceof Promise) {
await e
return childrenToString(children)
} else {
throw e
}
}
}

/**
* @experimental
* `Suspense` is an experimental feature.
* The API might be changed.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const Suspense: FC<{ fallback: any }> = async ({ children, fallback }) => {
if (!children) {
return fallback.toString()
}

let res
try {
res = children.toString()
} catch (e) {
if (e instanceof Promise) {
res = e
} else {
throw e
}
} finally {
const index = suspenseCounter++
if (res instanceof Promise) {
const promise = res
res = new String(
`<template id="H:${index}"></template>${fallback.toString()}<!--/$-->`
) as HtmlEscapedString
res.isEscaped = true
res.promises = [
promise.then(async () => {
return `<template>${await childrenToString(children)}</template><script>
((d,c,n) => {
c=d.currentScript.previousSibling
d=d.getElementById('H:${index}')
do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')
d.replaceWith(c.content)
})(document)
</script>`
}),
]
}
}
return res as HtmlEscapedString
}

const textEncoder = new TextEncoder()
/**
* @experimental
* `renderToReadableStream()` is an experimental feature.
* The API might be changed.
*/
export const renderToReadableStream = (
str: HtmlEscapedString | Promise<HtmlEscapedString>
): ReadableStream<Uint8Array> => {
const reader = new ReadableStream<Uint8Array>({
async start(controller) {
const resolved = await str.toString()
controller.enqueue(textEncoder.encode(resolved))

let unresolvedCount = (resolved as HtmlEscapedString).promises?.length || 0
if (!unresolvedCount) {
controller.close()
return
}

for (let i = 0; i < unresolvedCount; i++) {
;((resolved as HtmlEscapedString).promises as Promise<string>[])[i]
.catch((err) => {
console.trace(err)
return ''
})
.then((res) => {
controller.enqueue(textEncoder.encode(res))
if (!--unresolvedCount) {
controller.close()
}
})
}
},
})
return reader
}
25 changes: 23 additions & 2 deletions deno_dist/utils/html.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,33 @@
export type HtmlEscaped = { isEscaped: true }
export type HtmlEscaped = { isEscaped: true; promises?: Promise<string>[] }
export type HtmlEscapedString = string & HtmlEscaped
export type StringBuffer = [string]
export type StringBuffer = (string | Promise<string>)[]

// The `escapeToBuffer` implementation is based on code from the MIT licensed `react-dom` package.
// https://github.com/facebook/react/blob/main/packages/react-dom-bindings/src/server/escapeTextForBrowser.js

const escapeRe = /[&<>'"]/

export const stringBufferToString = async (buffer: StringBuffer): Promise<HtmlEscapedString> => {
let str = ''
const promises: Promise<string>[] = []
for (let i = buffer.length - 1; i >= 0; i--) {
let r = await buffer[i]
if (typeof r === 'object') {
promises.push(...((r as HtmlEscapedString).promises || []))
}
r = await (typeof r === 'object' ? (r as HtmlEscapedString).toString() : r)
if (typeof r === 'object') {
promises.push(...((r as HtmlEscapedString).promises || []))
}
str += r
}

const res = new String(str) as HtmlEscapedString
res.isEscaped = true
res.promises = promises
return res
}

export const escapeToBuffer = (str: string, buffer: StringBuffer): void => {
const match = str.search(escapeRe)
if (match === -1) {
Expand Down
10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@
"import": "./dist/jsx/jsx-runtime.js",
"require": "./dist/cjs/jsx/jsx-runtime.js"
},
"./jsx/streaming": {
"types": "./dist/types/jsx/streaming.d.ts",
"import": "./dist/jsx/streaming.js",
"require": "./dist/cjs/jsx/streaming.js"
},
"./jsx-renderer": {
"types": "./dist/types/middleware/jsx-renderer/index.d.ts",
"import": "./dist/middleware/jsx-renderer/index.js",
Expand Down Expand Up @@ -304,6 +309,9 @@
"jsx/jsx-dev-runtime": [
"./dist/types/jsx/jsx-dev-runtime.d.ts"
],
"jsx/streaming": [
"./dist/types/jsx/streaming.d.ts"
],
"jsx-renderer": [
"./dist/types/middleware/jsx-renderer"
],
Expand Down Expand Up @@ -424,6 +432,7 @@
"@types/crypto-js": "^4.1.1",
"@types/glob": "^8.0.0",
"@types/jest": "^29.4.0",
"@types/jsdom": "^21.1.4",
"@types/node": "^20.8.2",
"@types/node-fetch": "^2.6.2",
"@types/supertest": "^2.0.12",
Expand All @@ -445,6 +454,7 @@
"form-data": "^4.0.0",
"jest": "^29.6.4",
"jest-preset-fastly-js-compute": "^1.3.0",
"jsdom": "^22.1.0",
"msw": "^1.0.0",
"node-fetch": "2",
"np": "^7.7.0",
Expand Down
Loading
Loading