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

main
ts 132 lines 4.75 KB
Raw
1 import type * as runtime from "@cloudflare/workers-types";
2 import * as Output from "alchemy/Output";
3 import * as Effect from "effect/Effect";
4 import * as Stream from "effect/Stream";
5 import { Worker, WorkerEnvironment } from "../Workers/Worker.ts";
6 import type { Bucket } from "./Bucket.ts";
7 import type { R2Object, ObjectBody } from "./BucketTypes.ts";
8 import { R2Error } from "./BucketTypes.ts";
9
10 /**
11 * Shared scaffolding for the Worker-binding implementations of the R2 services.
12 *
13 * Resolves the {@link WorkerEnvironment} and host {@link Worker}, registers the
14 * `r2_bucket` binding at deploy time, then delegates to `makeClient` with the
15 * shared {@link Helpers} to build the read/write/read-write client.
16 */
17 export const makeBucketBinding = <Client>(options: {
18 makeClient: (helpers: ReturnType<typeof makeHelpers>) => Client;
19 }) =>
20 Effect.gen(function* () {
21 const env = yield* WorkerEnvironment;
22 const host = yield* Worker;
23
24 return Effect.fn(function* (bucket: Bucket) {
25 if (!globalThis.__ALCHEMY_RUNTIME__) {
26 yield* host.bind`${bucket}`({
27 bindings: [
28 {
29 type: "r2_bucket",
30 name: bucket.LogicalId,
31 bucketName: bucket.bucketName,
32 jurisdiction: bucket.jurisdiction.pipe(
33 Output.map((jurisdiction) =>
34 jurisdiction === "default" ? undefined : jurisdiction,
35 ),
36 ),
37 },
38 ],
39 });
40 }
41
42 return options.makeClient(makeHelpers(env, bucket));
43 });
44 });
45
46 /**
47 * Helpers shared by both the read and write halves of the binding client.
48 *
49 * Read-only (`wrapR2Objects`) and write-only (`wrapR2MultipartUpload`) wrappers
50 * live in {@link makeRead}/{@link makeWrite} respectively — only the primitives
51 * used by both sides are exposed here.
52 */
53 export const makeHelpers = (env: Record<string, any>, bucket: Bucket) => {
54 const raw = Effect.sync(() => (env as Record<string, runtime.R2Bucket>)[bucket.LogicalId]!);
55 const tryPromise = <T>(fn: () => Promise<T>): Effect.Effect<T, R2Error> =>
56 Effect.tryPromise({
57 try: fn,
58 catch: (error: any) =>
59 new R2Error({
60 message: error.message ?? "Unknown error",
61 cause: error,
62 }),
63 });
64
65 const use = <T>(fn: (raw: runtime.R2Bucket) => Promise<T>): Effect.Effect<T, R2Error> =>
66 raw.pipe(Effect.flatMap((raw) => tryPromise(() => fn(raw))));
67
68 return {
69 raw,
70 use,
71 tryPromise,
72 ...makeR2ObjectWrappers(tryPromise, true),
73 };
74 };
75
76 /**
77 * The `R2Object`/`R2ObjectBody` → Effect-client wrappers, shared by the
78 * Worker-binding helpers above and the local platform-proxy helpers
79 * (`LocalR2Gateway.ts`), which differ only in how `raw`/`use` obtain the
80 * native bucket. Only the Worker binding marks its body stream as native:
81 * the local platform proxy has different stream ownership/length semantics.
82 */
83 export const makeR2ObjectWrappers = (
84 tryPromise: <T>(fn: () => Promise<T>) => Effect.Effect<T, R2Error>,
85 nativeStreams = false,
86 ) => {
87 const wrapR2Object = (object: runtime.R2Object): R2Object => ({
88 // oxlint-disable-next-line typescript/no-misused-spread -- copies the runtime object's own data fields; its only method is replaced below
89 ...object,
90 writeHttpMetadata: (headers: Headers) => Effect.sync(() => object.writeHttpMetadata(headers)),
91 });
92 const wrapR2ObjectBody = (object: runtime.R2ObjectBody): ObjectBody => ({
93 ...wrapR2Object(object),
94 // Preserve the native stream only on this untouched wrapper. Stream
95 // transforms return a new Stream without `raw`, so put cannot bypass them.
96 body: Object.assign(
97 Stream.fromReadableStream({
98 evaluate: () => object.body as any as ReadableStream<Uint8Array<ArrayBufferLike>>,
99 onError: (error: any) =>
100 new R2Error({
101 message: error.message ?? "Unknown error",
102 cause: error,
103 }),
104 }),
105 nativeStreams ? { raw: object.body } : {},
106 ),
107 readable: object.body as any as ReadableStream<Uint8Array>,
108 bodyUsed: object.bodyUsed,
109 arrayBuffer: () => tryPromise(() => object.arrayBuffer()),
110 bytes: () => tryPromise(() => object.bytes()),
111 text: () => tryPromise(() => object.text()),
112 json: <T>() => tryPromise(() => object.json<T>()),
113 blob: () => tryPromise(() => object.blob()),
114 });
115
116 const isR2ObjectBody = (object: any): object is runtime.R2ObjectBody =>
117 object !== null && typeof object === "object" && "body" in object;
118
119 const wrapR2ObjectOrBody = (
120 object: runtime.R2Object | runtime.R2ObjectBody | null,
121 ): R2Object | ObjectBody | null =>
122 object === null
123 ? object
124 : isR2ObjectBody(object)
125 ? wrapR2ObjectBody(object)
126 : wrapR2Object(object);
127
128 return {
129 wrapR2Object,
130 wrapR2ObjectOrBody,
131 };
132 };