1 | export { pipe as combine } from 'ts-functional-pipe';
|
2 | import { ResolvablePromise } from '@worker-tools/resolvable-promise'
|
3 | import type { Awaitable } from "./utils/common-types.js";
|
4 | import type { Context } from "./index.js";
|
5 |
|
6 | class FlushCallbackStream<T> extends TransformStream<T, T> {
|
7 | constructor(flushCallback: () => void) {
|
8 | super({ flush() { flushCallback() } })
|
9 | }
|
10 | }
|
11 |
|
12 | export interface FlushedContext {
|
13 | |
14 |
|
15 |
|
16 |
|
17 |
|
18 | flushed: Promise<Response>
|
19 | }
|
20 |
|
21 | export 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 |