@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 489 lines 15.6 KB
Raw
1 /**
2 * Browser implementations of the Effect `HttpClient`.
3 *
4 * This module exposes HTTP client layers for code that runs in a browser. It
5 * re-exports the fetch-based `Fetch`, `RequestInit`, and `layerFetch` APIs for
6 * the common case where requests use the platform `fetch` implementation. It
7 * also provides an `XMLHttpRequest`-backed client, including controls for the
8 * XHR response type, an overridable `XMLHttpRequest` constructor service, and
9 * the `layerXMLHttpRequest` layer.
10 *
11 * Requests with an `Upgrade` header fail with `TransportError` before anything
12 * is sent because neither fetch nor XMLHttpRequest can hand over the connection.
13 *
14 * @stability unstable
15 * @since 4.0.0
16 */
17 import * as Cause from "effect/Cause"
18 import * as Context from "effect/Context"
19 import * as Effect from "effect/Effect"
20 import type { LazyArg } from "effect/Function"
21 import * as Cookies from "effect/http/Cookies"
22 import * as Headers from "effect/http/Headers"
23 import * as HttpClient from "effect/http/HttpClient"
24 import * as HttpClientError from "effect/http/HttpClientError"
25 import type * as HttpClientRequest from "effect/http/HttpClientRequest"
26 import * as HttpClientResponse from "effect/http/HttpClientResponse"
27 import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"
28 import * as HeaderParser from "effect/http/MultipartParser/HeadersParser"
29 import * as UrlParams from "effect/http/UrlParams"
30 import * as Inspectable from "effect/Inspectable"
31 import type * as Layer from "effect/Layer"
32 import * as Option from "effect/Option"
33 import { type Pipeable, pipeArguments } from "effect/Pipeable"
34 import * as Queue from "effect/Queue"
35 import type * as Schema from "effect/Schema"
36 import type * as Socket from "effect/socket/Socket"
37 import * as Stream from "effect/Stream"
38
39 // =============================================================================
40 // Fetch
41 // =============================================================================
42
43 export {
44 /**
45 * Context reference for the `fetch` implementation used by the fetch-based HTTP client.
46 *
47 * @stability unstable
48 * @category services
49 * @since 4.0.0
50 */
51 Fetch,
52 /**
53 * Layer that provides an `HttpClient` implementation backed by the configured `Fetch` function.
54 *
55 * @stability unstable
56 * @category layers
57 * @since 4.0.0
58 */
59 layer as layerFetch,
60 /**
61 * Service that contains default fetch options for the browser fetch client.
62 *
63 * **When to use**
64 *
65 * Use to provide default credentials, cache, redirect, integrity, or other
66 * fetch options for browser HTTP requests.
67 *
68 * @stability unstable
69 * @category services
70 * @since 4.0.0
71 */
72 RequestInit
73 } from "effect/http/FetchHttpClient"
74
75 // =============================================================================
76 // XML Http Request
77 // =============================================================================
78
79 /**
80 * Allowed response body modes for the browser XHR HTTP client.
81 *
82 * @stability unstable
83 * @category models
84 * @since 4.0.0
85 */
86 export type XHRResponseType = "arraybuffer" | "text"
87
88 /**
89 * Context reference for the `XMLHttpRequest.responseType` used by the browser XHR HTTP client, defaulting to `"text"`.
90 *
91 * **When to use**
92 *
93 * Use when you need XHR-backed HTTP requests to receive response bodies as text
94 * or raw `ArrayBuffer` values.
95 *
96 * @see {@link XHRResponseType} for the allowed response body modes
97 * @see {@link withXHRArrayBuffer} for scoping XHR response handling to `ArrayBuffer`
98 *
99 * @stability unstable
100 * @category services
101 * @since 4.0.0
102 */
103 export const CurrentXHRResponseType: Context.Reference<XHRResponseType> = Context.Reference(
104 "@effect/platform-browser/BrowserHttpClient/CurrentXHRResponseType",
105 { defaultValue: (): XHRResponseType => "text" }
106 )
107
108 /**
109 * Runs an effect with `CurrentXHRResponseType` set to `"arraybuffer"` so the XHR HTTP client receives response bodies as `ArrayBuffer` values.
110 *
111 * @stability unstable
112 * @category providing services
113 * @since 4.0.0
114 */
115 export const withXHRArrayBuffer = <A, E, R>(
116 self: Effect.Effect<A, E, R>
117 ): Effect.Effect<A, E, R> =>
118 Effect.provideService(
119 self,
120 CurrentXHRResponseType,
121 "arraybuffer"
122 )
123
124 /**
125 * Service tag for the `XMLHttpRequest` constructor used by the browser XHR HTTP client.
126 *
127 * @stability unstable
128 * @category services
129 * @since 4.0.0
130 */
131 export class XMLHttpRequest extends Context.Service<
132 XMLHttpRequest,
133 LazyArg<globalThis.XMLHttpRequest>
134 >()("@effect/platform-browser/BrowserHttpClient/XMLHttpRequest") {}
135
136 const makeXhrRequest = () => new globalThis.XMLHttpRequest()
137
138 const makeXmlHttpRequest = HttpClient.make(
139 (request, url, signal, fiber) =>
140 Effect.suspend(() => {
141 if (request.headers.upgrade !== undefined) {
142 return Effect.fail(
143 new HttpClientError.HttpClientError({
144 reason: new HttpClientError.TransportError({
145 request,
146 description: "XMLHttpRequest cannot send an HTTP upgrade request"
147 })
148 })
149 )
150 }
151 const xhr = Context.getOrElse(
152 fiber.context,
153 XMLHttpRequest,
154 () => makeXhrRequest
155 )()
156 signal.addEventListener("abort", () => {
157 xhr.abort()
158 xhr.onreadystatechange = null
159 }, { once: true })
160 xhr.open(request.method, url.toString(), true)
161 xhr.responseType = fiber.getRef(CurrentXHRResponseType)
162 Object.entries(request.headers).forEach(([k, v]) => {
163 xhr.setRequestHeader(k, v)
164 })
165 return Effect.andThen(
166 sendBody(xhr, request),
167 Effect.callback<ClientResponseImpl, HttpClientError.HttpClientError>((resume) => {
168 let sent = false
169 const onChange = () => {
170 if (!sent && xhr.readyState >= 2) {
171 sent = true
172 resume(Effect.succeed(new ClientResponseImpl(request, xhr, url.href)))
173 }
174 }
175 xhr.onreadystatechange = onChange
176 xhr.onerror = (_event) => {
177 resume(Effect.fail(
178 new HttpClientError.HttpClientError({
179 reason: new HttpClientError.TransportError({
180 request,
181 cause: xhr.statusText
182 })
183 })
184 ))
185 }
186 onChange()
187 return Effect.void
188 })
189 )
190 })
191 )
192
193 const sendBody = (
194 xhr: globalThis.XMLHttpRequest,
195 request: HttpClientRequest.HttpClientRequest
196 ): Effect.Effect<void, HttpClientError.HttpClientError> => {
197 const body = request.body
198 switch (body._tag) {
199 case "Empty":
200 return Effect.sync(() => xhr.send())
201 case "Raw":
202 return Effect.sync(() => xhr.send(body.body as any))
203 case "Uint8Array":
204 return Effect.sync(() => xhr.send(body.body as any))
205 case "FormData":
206 return Effect.sync(() => xhr.send(body.formData))
207 case "Stream":
208 return Effect.matchEffect(
209 Stream.mkUint8Array(body.stream),
210 {
211 onFailure: (cause) =>
212 Effect.fail(
213 new HttpClientError.HttpClientError({
214 reason: new HttpClientError.EncodeError({
215 request,
216 cause
217 })
218 })
219 ),
220 onSuccess: (body) => Effect.sync(() => xhr.send(body))
221 }
222 )
223 }
224 }
225
226 const encoder = new TextEncoder()
227
228 const formDecoder = new TextDecoder("utf-8", { ignoreBOM: true })
229
230 abstract class IncomingMessageImpl<E> extends Inspectable.Class implements HttpIncomingMessage.HttpIncomingMessage<E> {
231 readonly [HttpIncomingMessage.TypeId]: typeof HttpIncomingMessage.TypeId
232 readonly source: globalThis.XMLHttpRequest
233 readonly onError: (error: unknown) => E
234
235 constructor(source: globalThis.XMLHttpRequest, onError: (error: unknown) => E) {
236 super()
237 this[HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId
238 this.source = source
239 this.onError = onError
240 this._rawHeaderString = source.getAllResponseHeaders()
241 }
242
243 private _rawHeaderString: string
244 private _rawHeaders: Record<string, string | Array<string>> | undefined
245 private _headers: Headers.Headers | undefined
246 get headers() {
247 if (this._headers) {
248 return this._headers
249 }
250 if (this._rawHeaderString === "") {
251 return this._headers = Headers.empty
252 }
253 const parser = HeaderParser.make()
254 const result = parser(encoder.encode(this._rawHeaderString + "\r\n"), 0)
255 this._rawHeaders = result._tag === "Headers" ? result.headers : undefined
256 const parsed = result._tag === "Headers" ? Headers.fromInput(result.headers) : Headers.empty
257 return this._headers = parsed
258 }
259
260 cachedCookies: Cookies.Cookies | undefined
261 get cookies() {
262 if (this.cachedCookies) {
263 return this.cachedCookies
264 }
265 if (this._rawHeaders === undefined) {
266 return Cookies.empty
267 } else if (this._rawHeaders["set-cookie"] === undefined) {
268 return this.cachedCookies = Cookies.empty
269 }
270 return this.cachedCookies = Cookies.fromSetCookie(this._rawHeaders["set-cookie"])
271 }
272
273 get remoteAddress() {
274 return Option.none()
275 }
276
277 _textEffect: Effect.Effect<string, E> | undefined
278 get text(): Effect.Effect<string, E> {
279 if (this._textEffect) {
280 return this._textEffect
281 }
282 if (this.source.responseType === "arraybuffer") {
283 return this._textEffect = this.arrayBuffer.pipe(
284 Effect.map((buffer) => new TextDecoder().decode(buffer)),
285 Effect.cached,
286 Effect.runSync
287 )
288 }
289 return this._textEffect = Effect.callback<string, E>((resume) => {
290 if (this.source.readyState === 4) {
291 resume(Effect.succeed(this.source.responseText))
292 return
293 }
294
295 const onReadyStateChange = () => {
296 if (this.source.readyState === 4) {
297 resume(Effect.succeed(this.source.responseText))
298 }
299 }
300 const onError = () => {
301 resume(Effect.fail(this.onError(this.source.statusText)))
302 }
303 this.source.addEventListener("readystatechange", onReadyStateChange)
304 this.source.addEventListener("error", onError)
305 return Effect.sync(() => {
306 this.source.removeEventListener("readystatechange", onReadyStateChange)
307 this.source.removeEventListener("error", onError)
308 })
309 }).pipe(
310 Effect.cached,
311 Effect.runSync
312 )
313 }
314
315 get json(): Effect.Effect<Schema.Json, E> {
316 return Effect.flatMap(this.text, (text) =>
317 Effect.try({
318 try: () => text === "" ? null : JSON.parse(text),
319 catch: this.onError
320 }))
321 }
322
323 get urlParamsBody(): Effect.Effect<UrlParams.UrlParams, E> {
324 const text = this.source.responseType === "arraybuffer"
325 ? Effect.map(this.arrayBuffer, (buffer) => formDecoder.decode(buffer))
326 : this.text
327 return Effect.flatMap(text, (text) =>
328 Effect.try({
329 // A leading "?" is form data; URLSearchParams would drop it as a query prefix.
330 try: () => UrlParams.fromInput(new URLSearchParams(text.replace(/^\?/, "%3F"))),
331 catch: this.onError
332 }))
333 }
334
335 get stream(): Stream.Stream<Uint8Array, E> {
336 if (this.source.responseType === "arraybuffer") {
337 return Stream.fromEffect(Effect.map(this.arrayBuffer, (buffer) => new Uint8Array(buffer)))
338 }
339 return Stream.callback<Uint8Array, E>((queue) => {
340 let offset = 0
341 const onReadyStateChange = () => {
342 if (this.source.readyState === 3) {
343 const encoded = encoder.encode(this.source.responseText.slice(offset))
344 Queue.offerUnsafe(queue, encoded)
345 offset = this.source.responseText.length
346 } else if (this.source.readyState === 4) {
347 const encoded = encoder.encode(this.source.responseText.slice(offset))
348 if (offset < this.source.responseText.length) {
349 Queue.offerUnsafe(queue, encoded)
350 }
351 Queue.endUnsafe(queue)
352 }
353 }
354 const onError = () => {
355 Queue.failCauseUnsafe(queue, Cause.fail(this.onError(this.source.statusText)))
356 }
357 this.source.addEventListener("readystatechange", onReadyStateChange)
358 this.source.addEventListener("error", onError)
359 onReadyStateChange()
360 return Effect.addFinalizer(() =>
361 Effect.sync(() => {
362 this.source.removeEventListener("readystatechange", onReadyStateChange)
363 this.source.removeEventListener("error", onError)
364 })
365 )
366 })
367 }
368
369 _arrayBufferEffect: Effect.Effect<ArrayBuffer, E> | undefined
370 get arrayBuffer(): Effect.Effect<ArrayBuffer, E> {
371 if (this._arrayBufferEffect) {
372 return this._arrayBufferEffect
373 }
374 return this._arrayBufferEffect = Effect.callback<ArrayBuffer, E>((resume) => {
375 if (this.source.readyState === 4) {
376 resume(Effect.succeed(this.source.response))
377 return
378 }
379
380 const onReadyStateChange = () => {
381 if (this.source.readyState === 4) {
382 resume(Effect.succeed(this.source.response))
383 }
384 }
385 const onError = () => {
386 resume(Effect.fail(this.onError(this.source.statusText)))
387 }
388 this.source.addEventListener("readystatechange", onReadyStateChange)
389 this.source.addEventListener("error", onError)
390 return Effect.sync(() => {
391 this.source.removeEventListener("readystatechange", onReadyStateChange)
392 this.source.removeEventListener("error", onError)
393 })
394 }).pipe(
395 Effect.map((response) => {
396 if (typeof response === "string") {
397 const arr = encoder.encode(response)
398 return arr.byteLength !== arr.buffer.byteLength
399 ? arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength)
400 : arr.buffer
401 }
402 return response
403 }),
404 Effect.cached,
405 Effect.runSync
406 )
407 }
408 }
409
410 class ClientResponseImpl extends IncomingMessageImpl<HttpClientError.HttpClientError>
411 implements HttpClientResponse.HttpClientResponse, Pipeable
412 {
413 readonly [HttpClientResponse.TypeId]: typeof HttpClientResponse.TypeId
414 readonly request: HttpClientRequest.HttpClientRequest
415 private readonly requestUrl: string
416
417 constructor(
418 request: HttpClientRequest.HttpClientRequest,
419 source: globalThis.XMLHttpRequest,
420 requestUrl: string
421 ) {
422 super(source, (cause) =>
423 new HttpClientError.HttpClientError({
424 reason: new HttpClientError.DecodeError({
425 request,
426 response: this,
427 cause
428 })
429 }))
430 this.request = request
431 this.requestUrl = requestUrl
432 this[HttpClientResponse.TypeId] = HttpClientResponse.TypeId
433 }
434
435 get status() {
436 return this.source.status
437 }
438
439 get url() {
440 return (this.source.responseURL || this.requestUrl).split("#")[0]
441 }
442
443 get formData(): Effect.Effect<FormData, HttpClientError.HttpClientError> {
444 return Effect.flatMap(this.arrayBuffer, (body) =>
445 Effect.tryPromise({
446 try: () => new globalThis.Response(body, { headers: this.headers }).formData(),
447 catch: this.onError
448 }))
449 }
450
451 get upgrade(): Effect.Effect<Socket.Socket, HttpClientError.HttpClientError> {
452 return Effect.fail(
453 new HttpClientError.HttpClientError({
454 reason: new HttpClientError.StatusCodeError({
455 request: this.request,
456 response: this,
457 description: "XMLHttpRequest cannot hand over the connection of an HTTP upgrade"
458 })
459 })
460 )
461 }
462
463 override toString(): string {
464 return `ClientResponse(${this.status})`
465 }
466
467 toJSON(): unknown {
468 return HttpIncomingMessage.inspect(this, {
469 _id: "@effect/platform/HttpClientResponse",
470 request: this.request.toJSON(),
471 status: this.status
472 })
473 }
474
475 pipe() {
476 return pipeArguments(this, arguments)
477 }
478 }
479
480 /**
481 * Layer that provides an `HttpClient` implementation backed by the browser `XMLHttpRequest` API.
482 *
483 * @stability unstable
484 * @category layers
485 * @since 4.0.0
486 */
487 export const layerXMLHttpRequest: Layer.Layer<HttpClient.HttpClient> = HttpClient.layerMergedContext(
488 Effect.succeed(makeXmlHttpRequest)
489 )