@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 215 lines 5.68 KB
Raw
1 /**
2 * Node.js streams adapter for the low-level multipart parser.
3 *
4 * @stability unstable
5 * @since 4.0.0
6 */
7 // oxlint-disable typescript/no-unsafe-declaration-merging
8 /// <reference types="node" />
9 import { constVoid } from "effect/Function"
10 import type { BaseConfig, MultipartError, Parser, PartInfo } from "effect/http/MultipartParser"
11 import { make as makeParser } from "effect/http/MultipartParser"
12 import type { IncomingHttpHeaders } from "node:http"
13 import { Duplex, Readable } from "node:stream"
14
15 /**
16 * A part emitted by the Node.js multipart parser.
17 *
18 * @stability unstable
19 * @category models
20 * @since 4.0.0
21 */
22 export type Part = Field | FileStream
23
24 /**
25 * A parsed multipart field.
26 *
27 * @stability unstable
28 * @category models
29 * @since 4.0.0
30 */
31 export interface Field {
32 readonly _tag: "Field"
33 readonly info: PartInfo
34 readonly value: Uint8Array
35 }
36
37 /**
38 * A Node.js duplex stream that emits parsed multipart parts.
39 *
40 * @stability unstable
41 * @category models
42 * @since 4.0.0
43 */
44 export interface MultipartStream extends Duplex {
45 [Symbol.asyncIterator](): NodeJS.AsyncIterator<Part>
46
47 on(event: "field", listener: (field: Field) => void): this
48 on(event: "file", listener: (file: FileStream) => void): this
49 on(event: "close", listener: () => void): this
50 on(event: "data", listener: (part: Part) => void): this
51 on(event: "drain", listener: () => void): this
52 on(event: "end", listener: () => void): this
53 on(event: "error", listener: (err: MultipartError) => void): this
54 on(event: "finish", listener: () => void): this
55 on(event: "pause", listener: () => void): this
56 on(event: "pipe", listener: (src: Readable) => void): this
57 on(event: "readable", listener: () => void): this
58 on(event: "resume", listener: () => void): this
59 on(event: "unpipe", listener: (src: Readable) => void): this
60 on(event: string | symbol, listener: (...args: Array<any>) => void): this
61
62 read(size?: number): Part | null
63 }
64
65 /**
66 * Configuration for the Node.js multipart parser.
67 *
68 * @stability unstable
69 * @category models
70 * @since 4.0.0
71 */
72 export type NodeConfig = Omit<BaseConfig, "headers"> & {
73 readonly headers: IncomingHttpHeaders
74 }
75
76 /**
77 * A Node.js duplex stream that parses multipart input.
78 *
79 * @stability unstable
80 * @category models
81 * @since 4.0.0
82 */
83 export class MultipartStream extends Duplex {
84 private _parser: Parser
85 _canWrite = true
86 private _writeCallback: (() => void) | undefined
87 private _currentFile: FileStream | undefined
88
89 constructor(config: NodeConfig) {
90 super({ readableObjectMode: true })
91 let currentError: MultipartError | undefined
92 let initialized = false
93 this._parser = makeParser({
94 ...(config as any),
95 onField: (info, value) => {
96 if (currentError !== undefined) return
97 const field: Field = { _tag: "Field", info, value }
98 this.push(field)
99 this.emit("field", field)
100 },
101 onFile: (info) => {
102 if (currentError !== undefined) return (_) => {}
103 const file = new FileStream(info, this)
104 this._currentFile = file
105 this.push(file)
106 this.emit("file", file)
107 return (chunk) => {
108 if (currentError !== undefined) return
109 this._canWrite = file.push(chunk)
110 if (chunk === null && !this._canWrite) {
111 this._currentFile = undefined
112 this._resume()
113 }
114 }
115 },
116 onError: (error) => {
117 currentError = error
118 if (!initialized) return
119 this.emit("error", error)
120 this._failCurrentFile(error)
121 },
122 onDone: () => {
123 this.push(null)
124 }
125 })
126 initialized = true
127 if (currentError !== undefined) {
128 // destroy defers the error event so callers can attach their listeners.
129 this.destroy(currentError as any)
130 }
131 }
132
133 _resume() {
134 this._canWrite = true
135 if (this._writeCallback !== undefined) {
136 const callback = this._writeCallback
137 this._writeCallback = undefined
138 callback()
139 }
140 }
141
142 override _read(_size: number) {}
143
144 override _destroy(error: Error | null, callback: (error?: Error | null) => void): void {
145 if (error) this._failCurrentFile(error)
146 callback(error)
147 }
148
149 private _failCurrentFile(error: unknown) {
150 const file = this._currentFile
151 if (file === undefined) return
152 this._currentFile = undefined
153 // The file keeps the error for a late reader; the listener stops it from
154 // being thrown while nobody is reading yet.
155 file.on("error", constVoid)
156 file.destroy(error as any)
157 }
158
159 override _write(
160 chunk: any,
161 encoding: BufferEncoding,
162 callback: (error?: Error | null | undefined) => void
163 ): void {
164 this._parser.write(
165 chunk instanceof Uint8Array ? chunk : Buffer.from(chunk, encoding)
166 )
167 if (this._canWrite) {
168 callback()
169 } else {
170 this._writeCallback = callback
171 }
172 }
173
174 override _final(callback: (error?: Error | null | undefined) => void): void {
175 this._parser.end()
176 callback()
177 }
178 }
179
180 /**
181 * Creates a Node.js multipart parser stream.
182 *
183 * @stability unstable
184 * @category constructors
185 * @since 4.0.0
186 */
187 export const make = (config: NodeConfig): MultipartStream => new MultipartStream(config)
188
189 /**
190 * A readable stream containing a parsed multipart file.
191 *
192 * @stability unstable
193 * @category models
194 * @since 4.0.0
195 */
196 export class FileStream extends Readable {
197 readonly _tag = "File"
198 readonly filename: string | undefined
199 readonly info: PartInfo
200 private _parent: MultipartStream
201 constructor(
202 info: PartInfo,
203 parent: MultipartStream
204 ) {
205 super()
206 this.info = info
207 this._parent = parent
208 this.filename = info.filename
209 }
210 override _read(_size: number) {
211 if (this._parent._canWrite === false) {
212 this._parent._resume()
213 }
214 }
215 }