@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 78 lines 2.58 KB
Raw
1 /**
2 * Bun stream interoperability for Effect streams.
3 *
4 * This module is the Bun entry point for adapting runtime streams into Effect's
5 * streaming model. It re-exports the shared Node stream adapters for Bun's
6 * Node-compatible stream APIs and adds {@link fromReadableStream}, a Web
7 * `ReadableStream` adapter that uses Bun's `readMany` reader method to pull
8 * batches of values into an Effect `Stream`.
9 *
10 * @stability unstable
11 * @since 4.0.0
12 */
13 import * as Arr from "effect/Array"
14 import * as Cause from "effect/Cause"
15 import * as Channel from "effect/Channel"
16 import * as Effect from "effect/Effect"
17 import { constVoid, type LazyArg } from "effect/Function"
18 import type * as Pull from "effect/Pull"
19 import * as Scope from "effect/Scope"
20 import * as Stream from "effect/Stream"
21
22 /**
23 * @since 4.0.0
24 */
25 export * from "@effect/platform-node-shared/NodeStream"
26
27 /**
28 * Creates a stream from a `ReadableStream` using Bun's optimized `.readMany`
29 * API.
30 *
31 * @stability unstable
32 * @category constructors
33 * @since 4.0.0
34 */
35 export const fromReadableStream = <A, E>(
36 options: {
37 readonly evaluate: LazyArg<ReadableStream<A>>
38 readonly onError: (error: unknown) => E
39 readonly releaseLockOnEnd?: boolean | undefined
40 }
41 ): Stream.Stream<A, E> =>
42 Stream.fromChannel(Channel.fromTransform(Effect.fnUntraced(function*(_, scope) {
43 const reader = options.evaluate().getReader()
44 yield* Scope.addFinalizer(
45 scope,
46 options.releaseLockOnEnd
47 ? Effect.sync(() => reader.releaseLock())
48 : Effect.promise(() => reader.cancel().catch(constVoid))
49 )
50 function readMany(): Pull.Pull<Arr.NonEmptyReadonlyArray<A>, E> {
51 let result:
52 | Bun.ReadableStreamDefaultReadManyResult<A>
53 | Promise<Bun.ReadableStreamDefaultReadManyResult<A>>
54 try {
55 result = reader.readMany()
56 } catch (error) {
57 return Effect.fail(options.onError(error))
58 }
59 if ("then" in result) {
60 return Effect.callback<Arr.NonEmptyReadonlyArray<A>, E | Cause.Done>((resume) => {
61 result.then((_) => resume(handleResult(_)), (e) => resume(Effect.fail(options.onError(e))))
62 })
63 }
64 return handleResult(result)
65 }
66 function handleResult(
67 result: Bun.ReadableStreamDefaultReadManyResult<A>
68 ): Pull.Pull<Arr.NonEmptyReadonlyArray<A>, E> {
69 if (result.done) {
70 return Cause.done()
71 } else if (!Arr.isReadonlyArrayNonEmpty(result.value)) {
72 return readMany()
73 }
74 return Effect.succeed(result.value)
75 }
76 // @effect-diagnostics-next-line returnEffectInGen:off
77 return Effect.suspend(readMany)
78 })))