The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type * as runtime from "@cloudflare/workers-types"; |
| 2 | import * as Binding from "alchemy/Binding"; |
| 3 | import type { RuntimeContext } from "alchemy/RuntimeContext"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import type * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 6 | import * as Layer from "effect/Layer"; |
| 7 | import { fetchWithFetcher } from "../Workers/FetcherRequest.ts"; |
| 8 | import { isWorker, WorkerEnvironment } from "../Workers/Worker.ts"; |
| 9 | import { Fetch } from "./Fetch.ts"; |
| 10 | import type { MtlsCertificate } from "./MtlsCertificate.ts"; |
| 11 | |
| 12 | /** |
| 13 | * Implementation of {@link Fetch} over the native `mtls_certificate` Worker |
| 14 | * binding. Provide it on the Worker's Effect. |
| 15 | */ |
| 16 | export const FetchBinding = Layer.effect( |
| 17 | Fetch, |
| 18 | Effect.gen(function* () { |
| 19 | const env = yield* WorkerEnvironment; |
| 20 | |
| 21 | return Effect.fn(function* (certificate: MtlsCertificate) { |
| 22 | if (!globalThis.__ALCHEMY_RUNTIME__) { |
| 23 | // Deploy-time only: attach the certificate to the host Worker. |
| 24 | const host = yield* Binding.Host; |
| 25 | if (isWorker(host)) { |
| 26 | yield* host.bind`${certificate}`({ |
| 27 | bindings: [ |
| 28 | { |
| 29 | type: "mtls_certificate", |
| 30 | name: certificate.LogicalId, |
| 31 | certificateId: certificate.mtlsCertificateId, |
| 32 | }, |
| 33 | ], |
| 34 | }); |
| 35 | } |
| 36 | } |
| 37 | // Lazy: `WorkerEnvironment` bindings are only populated at runtime. |
| 38 | const fetcher = Effect.sync( |
| 39 | () => (env as Record<string, runtime.Fetcher>)[certificate.LogicalId]!, |
| 40 | ) as Effect.Effect<runtime.Fetcher, never, RuntimeContext>; |
| 41 | |
| 42 | return (request: HttpClientRequest.HttpClientRequest) => |
| 43 | Effect.flatMap(fetcher, (f) => |
| 44 | fetchWithFetcher(f, request, "mTLS certificate fetch failed"), |
| 45 | ); |
| 46 | }); |
| 47 | }), |
| 48 | ); |