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

main
ts 104 lines 4.63 KB
Raw
1 import * as Effect from "effect/Effect";
2 import type * as HttpClient from "effect/http/HttpClient";
3 import * as Layer from "effect/Layer";
4 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
5 import type { Credentials } from "../Credentials.ts";
6 import { isLocalId } from "../LocalRuntime.ts";
7 import type { Database } from "./Database.ts";
8 import { localD1GatewayRuntime, withLocalD1Query } from "./LocalD1Gateway.ts";
9 import { QueryDatabase } from "./QueryDatabase.ts";
10 import {
11 makeD1DatabaseFromTransport,
12 makeHttpD1Database,
13 makeQueryDatabaseClientFrom,
14 } from "./QueryDatabaseHttpClient.ts";
15
16 /**
17 * Local implementation of the {@link QueryDatabase} binding — queries D1 over
18 * the Cloudflare HTTP API using the **current credentials** instead of a native
19 * Worker binding (`QueryDatabaseBinding`) or a scoped API token.
20 *
21 * Provide it on an {@link Action} (or any deploy-time Effect) so you can talk to
22 * a D1 database with the same `prepare`/`exec`/`batch` client you'd use inside a
23 * Worker:
24 *
25 * @example Seeding a database from an Action
26 * ```typescript
27 * const Seed = Alchemy.Action(
28 * "Seed",
29 * Effect.gen(function* () {
30 * const db = yield* Cloudflare.D1.QueryDatabase(database);
31 * return Effect.fn(function* () {
32 * yield* db.exec("CREATE TABLE IF NOT EXISTS users (id TEXT, name TEXT)");
33 * yield* db
34 * .prepare("INSERT INTO users (id, name) VALUES (?, ?)")
35 * .bind("1", "Ada")
36 * .run();
37 * });
38 * }).pipe(Effect.provide(Cloudflare.D1.QueryDatabaseLocal)),
39 * );
40 * ```
41 *
42 * The database id is resolved at apply time through the ambient
43 * {@link RuntimeContext} (in an Action, that's the resolve context the engine
44 * provides around the body), so `QueryDatabase(database)` works even though the
45 * database is created in the same deploy.
46 */
47 export const QueryDatabaseLocal = Layer.effect(
48 QueryDatabase,
49 Effect.gen(function* () {
50 // Capture the account resolver without authenticating. Only the HTTP
51 // branch evaluates it; native local clients need no cloud credentials.
52 // Credentials are ambient during stack-eval (the stack's
53 // providers layer). Capture the full context so the HTTP query ops run
54 // with the current credentials — no `host.bind`, no minted token.
55 const environment = yield* CloudflareEnvironment;
56 const context = yield* Effect.context<Credentials | HttpClient.HttpClient>();
57 // The FULL ambient context, for the dev-mode gateway: booting an
58 // ephemeral workerd needs the platform services (FileSystem, Path,
59 // spawner, HttpClient) and the Cloudflare environment, all of which are
60 // present during stack-eval but not statically enumerable here.
61 const ambient = yield* Effect.context<never>();
62
63 // Under `alchemy dev` the database may be a local simulator row (a
64 // `dev:` id). Queries then tunnel through an ephemeral workerd gateway
65 // into the simulator's DO SQLite (one gateway boot per query — slow but
66 // correct; Actions are deploy-time one-shots). Real ids keep the cloud
67 // HTTP query API.
68 const localTransport =
69 (databaseId: string) =>
70 (
71 body:
72 | { sql: string; params?: unknown[] }
73 | { batch: { sql: string; params?: unknown[] }[] },
74 ) =>
75 withLocalD1Query(databaseId, (query) => query(body)).pipe(
76 Effect.provide(localD1GatewayRuntime),
77 // The gateway layer's platform requirements are satisfied by the
78 // ambient stack-eval context captured above; `Context<never>`
79 // can't prove that statically, so erase the leftover R.
80 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- remaining requirements are satisfied by the captured ambient context
81 (eff) => Effect.runPromiseWith(ambient)(eff as Effect.Effect<never, never>),
82 ) as Promise<{
83 result: Array<{ results?: unknown; success?: boolean | null; meta?: unknown }>;
84 }>;
85
86 return Effect.fn(function* (database: Database) {
87 // Deferred accessor — resolves the databaseId against the tracker at
88 // apply time. No `host.bind`: the local variant registers no binding.
89 const databaseId = yield* database.databaseId;
90 return makeQueryDatabaseClientFrom(
91 Effect.flatMap(databaseId, (id) =>
92 isLocalId(id)
93 ? Effect.succeed(makeD1DatabaseFromTransport(localTransport(id)))
94 : Effect.map(environment, ({ accountId }) =>
95 makeHttpD1Database(
96 { accountId, authorize: (eff) => eff.pipe(Effect.provideContext(context)) },
97 id,
98 ),
99 ),
100 ),
101 );
102 });
103 }),
104 );