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

main
ts 67 lines 2.22 KB
Raw
1 import type * as runtime from "@cloudflare/workers-types";
2 import * as Effect from "effect/Effect";
3 import { Worker, WorkerEnvironment } from "../Workers/Worker.ts";
4 import type { InstantNamespace } from "./InstantNamespace.ts";
5 import type { Namespace } from "./Namespace.ts";
6 import { NamespaceError } from "./NamespaceTypes.ts";
7
8 /**
9 * Shared scaffolding for the Worker-binding implementations of the KV
10 * services.
11 *
12 * Resolves the {@link WorkerEnvironment} and host {@link Worker}, registers
13 * the `kv_namespace` binding at deploy time, then delegates to `makeClient`
14 * with the shared {@link makeKVNamespaceHelpers} to build the
15 * read/write/read-write client.
16 */
17 export const makeKVNamespaceBinding = <Client>(options: {
18 makeClient: (helpers: ReturnType<typeof makeKVNamespaceHelpers>) => Client;
19 }) =>
20 Effect.gen(function* () {
21 const env = yield* WorkerEnvironment;
22 const host = yield* Worker;
23
24 return Effect.fn(function* (namespace: Namespace | InstantNamespace) {
25 if (!globalThis.__ALCHEMY_RUNTIME__) {
26 yield* host.bind`${namespace}`({
27 bindings: [
28 {
29 type: "kv_namespace",
30 name: namespace.LogicalId,
31 namespaceId: namespace.namespaceId,
32 },
33 ],
34 });
35 }
36
37 return options.makeClient(makeKVNamespaceHelpers(env, namespace));
38 });
39 });
40
41 /** Primitives shared by the read and write halves of the binding client. */
42 export const makeKVNamespaceHelpers = (
43 env: Record<string, any>,
44 namespace: Namespace | InstantNamespace,
45 ) => {
46 const raw = Effect.sync(
47 // Lazy — the WorkerEnvironment binding is not populated until runtime.
48 () => (env as Record<string, runtime.KVNamespace>)[namespace.LogicalId]!,
49 );
50
51 const tryPromise = <T>(fn: () => Promise<T>): Effect.Effect<T, NamespaceError> =>
52 Effect.tryPromise({
53 try: fn,
54 catch: (error: any) =>
55 new NamespaceError({
56 message: error?.message ?? "Unknown error",
57 cause: error,
58 }),
59 });
60
61 const use = <T>(
62 fn: (raw: runtime.KVNamespace<string>) => Promise<T>,
63 ): Effect.Effect<T, NamespaceError> =>
64 raw.pipe(Effect.flatMap((raw) => tryPromise(() => fn(raw))));
65
66 return { raw, use, tryPromise };
67 };