deno.land / x / hono@v4.2.5 / jsx / streaming.ts

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import { raw } from '../helper/html/index.ts'import { HtmlEscapedCallbackPhase, resolveCallback } from '../utils/html.ts'import type { HtmlEscapedString } from '../utils/html.ts'import { childrenToString } from './components.ts'import { DOM_RENDERER, DOM_STASH } from './constants.ts'import { Suspense as SuspenseDomRenderer } from './dom/components.ts'import { buildDataStack } from './dom/render.ts'import type { HasRenderToDom, NodeObject } from './dom/render.ts'import type { FC, PropsWithChildren, Child } from './index.ts'
let suspenseCounter = 0
/** * @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 (!children) { return fallback.toString() } if (!Array.isArray(children)) { children = [children] }
let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []
// for use() hook const stackNode = { [DOM_STASH]: [0, []] } as unknown as NodeObject const popNodeStack = (value?: unknown) => { buildDataStack.pop() return value }
try { stackNode[DOM_STASH][0] = 0 buildDataStack.push([[], stackNode]) resArray = children.map((c) => c == null || typeof c === 'boolean' ? '' : c.toString() ) as HtmlEscapedString[] } catch (e) { if (e instanceof Promise) { resArray = [ e.then(() => { stackNode[DOM_STASH][0] = 0 buildDataStack.push([[], stackNode]) return childrenToString(children as Child[]).then(popNodeStack) }), ] as Promise<HtmlEscapedString[]>[] } else { throw e } } finally { popNodeStack() }
if (resArray.some((res) => (res as {}) instanceof Promise)) { const index = suspenseCounter++ const fallbackStr = await 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>.*?<!--/\\$-->`), content ) } let html = buffer ? '' : `<template data-hono-target="H:${index}">${content}</template><script>((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 = ( str: HtmlEscapedString | Promise<HtmlEscapedString>, onError: (e: unknown) => void = console.trace): ReadableStream<Uint8Array> => { const reader = new ReadableStream<Uint8Array>({ async start(controller) { try { const tmp = str instanceof Promise ? await str : await str.toString() const context = typeof tmp === 'object' ? tmp : {} const resolved = await resolveCallback( tmp, HtmlEscapedCallbackPhase.BeforeStream, true, context ) 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++ 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) }
controller.close() }, }) return reader}
hono

Version Info

Tagged at
a month ago