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

main
ts 158 lines 5.03 KB
Raw
1 /**
2 * HTTP response compression backed by `node:zlib`, shared by the Node.js, Bun,
3 * and Deno platforms.
4 *
5 * Byte-array bodies are compressed in one shot with the asynchronous
6 * `node:zlib` APIs, preserving an exact `Content-Length`. Streaming bodies go
7 * through `node:zlib` transform streams that flush each input chunk.
8 *
9 * @stability unstable
10 * @since 4.0.0
11 */
12 import * as Effect from "effect/Effect"
13 import * as HttpBody from "effect/http/HttpBody"
14 import type * as Platform from "effect/http/HttpPlatform"
15 import * as Response from "effect/http/HttpServerResponse"
16 import type { Duplex } from "node:stream"
17 import { Readable } from "node:stream"
18 import * as Zlib from "node:zlib"
19
20 /**
21 * The compression algorithms supported by the runtime's `node:zlib`. `zstd`
22 * requires Node.js 22.15 or newer.
23 *
24 * @stability unstable
25 * @category constants
26 * @since 4.0.0
27 */
28 export const algorithms: ReadonlySet<Platform.CompressionAlgorithm> = new Set(
29 typeof Zlib.zstdCompress === "function"
30 ? ["gzip", "deflate", "br", "zstd"]
31 : ["gzip", "deflate", "br"]
32 )
33
34 const brotliParams = (level: number | undefined, sizeHint?: number): Zlib.BrotliOptions => {
35 const params: Record<number, number> = {}
36 if (level !== undefined) {
37 params[Zlib.constants.BROTLI_PARAM_QUALITY] = level
38 }
39 if (sizeHint !== undefined) {
40 params[Zlib.constants.BROTLI_PARAM_SIZE_HINT] = sizeHint
41 }
42 return { params }
43 }
44
45 const zstdParams = (level: number | undefined): Zlib.ZstdOptions | undefined =>
46 level === undefined || level === 3 ? undefined : { params: { [Zlib.constants.ZSTD_c_compressionLevel]: level } }
47
48 const compress = (
49 data: Uint8Array,
50 algorithm: Platform.CompressionAlgorithm,
51 options?: Platform.CompressionOptions | undefined
52 ): Effect.Effect<Uint8Array> =>
53 Effect.callback((resume) => {
54 const complete = (error: Error | null, result: Uint8Array) =>
55 resume(error === null ? Effect.succeed(result) : Effect.die(error))
56 switch (algorithm) {
57 case "gzip": {
58 Zlib.gzip(data, { level: options?.level }, complete)
59 break
60 }
61 case "deflate": {
62 Zlib.deflate(data, { level: options?.level }, complete)
63 break
64 }
65 case "br": {
66 Zlib.brotliCompress(data, brotliParams(options?.level, data.byteLength), complete)
67 break
68 }
69 case "zstd": {
70 const params = zstdParams(options?.level)
71 if (params === undefined) {
72 Zlib.zstdCompress(data, complete)
73 } else {
74 Zlib.zstdCompress(data, params, complete)
75 }
76 break
77 }
78 }
79 })
80
81 /**
82 * Creates a `Compression` that compresses byte-array bodies in one shot with
83 * the asynchronous `node:zlib` APIs, setting the exact `Content-Length` of the
84 * compressed body. All other bodies are delegated to `fallback`.
85 *
86 * @stability unstable
87 * @category constructors
88 * @since 4.0.0
89 */
90 export const make = (fallback: Platform.Compression): Platform.Compression => ({
91 algorithms: fallback.algorithms,
92 compressResponse(response, algorithm, options) {
93 const body = response.body
94 if (body._tag !== "Uint8Array") {
95 return fallback.compressResponse(response, algorithm, options)
96 }
97 return Effect.map(compress(body.body, algorithm, options), (result) =>
98 Response.setHeader(
99 Response.setBody(response, HttpBody.uint8Array(result, response.headers["content-type"] ?? body.contentType)),
100 "content-length",
101 result.byteLength.toString()
102 ))
103 }
104 })
105
106 /**
107 * Creates a `node:zlib` compression transform stream that flushes each input
108 * chunk, for streaming response bodies.
109 *
110 * @stability unstable
111 * @category constructors
112 * @since 4.0.0
113 */
114 export const compressTransform = (
115 algorithm: Platform.CompressionAlgorithm,
116 options?: Platform.CompressionOptions | undefined
117 ): Duplex => {
118 switch (algorithm) {
119 case "gzip": {
120 return Zlib.createGzip({ level: options?.level, flush: Zlib.constants.Z_SYNC_FLUSH })
121 }
122 case "deflate": {
123 return Zlib.createDeflate({ level: options?.level, flush: Zlib.constants.Z_SYNC_FLUSH })
124 }
125 case "br": {
126 return Zlib.createBrotliCompress({
127 ...brotliParams(options?.level),
128 flush: Zlib.constants.BROTLI_OPERATION_FLUSH
129 })
130 }
131 case "zstd": {
132 return Zlib.createZstdCompress({
133 ...zstdParams(options?.level),
134 flush: Zlib.constants.ZSTD_e_flush
135 })
136 }
137 }
138 }
139
140 /**
141 * A Web `ReadableStream` version of `compressTransform`, for platforms that
142 * stream response bodies as Web streams.
143 *
144 * @stability unstable
145 * @category constructors
146 * @since 4.0.0
147 */
148 export const compressTransformWeb = (
149 algorithm: Platform.CompressionAlgorithm,
150 options?: Platform.CompressionOptions | undefined
151 ) =>
152 (stream: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> => {
153 const transform = compressTransform(algorithm, options)
154 const source = Readable.fromWeb(stream as any)
155 source.on("error", (cause) => transform.destroy(cause))
156 transform.on("close", () => source.destroy())
157 return Readable.toWeb(source.pipe(transform)) as unknown as ReadableStream<Uint8Array>
158 }