UNPKG

1.29 kBPlain TextView Raw
1export { pipe as combine } from 'ts-functional-pipe';
2import { ResolvablePromise } from '@worker-tools/resolvable-promise'
3import type { Awaitable } from "./utils/common-types.js";
4import type { Context } from "./index.js";
5
6class FlushCallbackStream<T> extends TransformStream<T, T> {
7 constructor(flushCallback: () => void) {
8 super({ flush() { flushCallback() } })
9 }
10}
11
12export interface FlushedContext {
13 /**
14 * A promise that resolves when the entire response body has been written to the wire,
15 * or if the stream has been closed for any other reason.
16 * Most likely useful when combined with streaming responses.
17 */
18 flushed: Promise<Response>
19}
20
21export const flushed = () => async <X extends Context>(ax: Awaitable<X>): Promise<X & FlushedContext> => {
22 const x = await ax;
23 const flush = new ResolvablePromise<Response>()
24 const flushed = Promise.resolve(flush)
25 x.effects.push(res => {
26 const ref: { res?: Response } = {}
27 const cb = () => flush.resolve(ref.res!)
28 const { status, statusText, headers, body } = res;
29 ref.res = new Response(body != null
30 ? body.pipeThrough(new FlushCallbackStream(cb))
31 : (x.handled.then(cb), null), { status, statusText, headers })
32 return ref.res;
33 })
34 return Object.assign(x, { flushed })
35}
\No newline at end of file