@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 183 lines 7.11 KB
Raw
1 import type * as runtime from "@cloudflare/workers-types";
2 import * as d1 from "@distilled.cloud/cloudflare/d1";
3 import * as Effect from "effect/Effect";
4 import type * as HttpClient from "effect/http/HttpClient";
5 import type { Credentials } from "../Credentials.ts";
6 import { type QueryDatabaseClient, PreparedStatement } from "./QueryDatabase.ts";
7
8 // Shared HTTP scaffolding for the D1 `QueryDatabase` binding. NOT re-exported
9 // from `index.ts` — only the contract and the impl layers are public. A future
10 // token-scoped `QueryDatabaseHttp` layer reuses this builder with an auth
11 // minted from an `AccountApiToken`; `QueryDatabaseLocal` builds the auth from
12 // the ambient current-credentials context.
13 //
14 // PreparedStatement (shared with QueryDatabaseBinding) drives a
15 // `runtime.D1Database` whose executors return Promises. The shim below
16 // implements the slice PreparedStatement uses (prepare/exec/batch + stmt
17 // bind/all/first/run/raw) by running `d1.queryDatabase` over HTTP.
18
19 /**
20 * Injectable auth shared by the Local (current-credentials) impl and a future
21 * Http (scoped-token) impl. `authorize` discharges the
22 * `Credentials | HttpClient` requirement of a distilled op; `accountId` is the
23 * Cloudflare account the ops run against.
24 */
25 export interface D1Auth {
26 authorize: <A, E>(
27 eff: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
28 ) => Effect.Effect<A, E>;
29 accountId: string;
30 }
31
32 /**
33 * Build a {@link QueryDatabaseClient} over the D1 HTTP query API.
34 *
35 * `databaseId` is an Effect so the resolution stays deferred to each call —
36 * inside an Action it resolves through the apply-time RuntimeContext. The
37 * credentials are provided ONLY around the distilled op (via `auth.authorize`),
38 * never around the id accessor, matching the KV / Vectorize Local variants.
39 */
40 export const makeHttpQueryDatabaseClient = (
41 auth: D1Auth,
42 databaseId: Effect.Effect<string>,
43 ): QueryDatabaseClient =>
44 makeQueryDatabaseClientFrom(Effect.map(databaseId, (id) => makeHttpD1Database(auth, id)));
45
46 /**
47 * Build a {@link QueryDatabaseClient} from a deferred `D1Database` — shared
48 * by the cloud HTTP transport above and the local-simulator gateway
49 * transport (`QueryDatabaseLocal` with a `dev:` id).
50 */
51 export const makeQueryDatabaseClientFrom = (
52 rawEff: Effect.Effect<runtime.D1Database>,
53 ): QueryDatabaseClient =>
54 ({
55 raw: rawEff,
56 prepare: (query: string) => new PreparedStatement(query, [], rawEff),
57 exec: (query: string) => Effect.flatMap(rawEff, (raw) => Effect.promise(() => raw.exec(query))),
58 batch: <T = unknown>(statements: PreparedStatement[]) =>
59 Effect.flatMap(rawEff, (raw) =>
60 Effect.promise(() => raw.batch<T>(statements.map((s) => s._build(raw)))),
61 ),
62 }) satisfies QueryDatabaseClient;
63
64 const runQuery = (
65 auth: D1Auth,
66 databaseId: string,
67 body: { sql: string; params?: unknown[] } | { batch: { sql: string; params?: unknown[] }[] },
68 ): Promise<d1.QueryDatabaseResponse> =>
69 auth
70 .authorize(
71 d1.queryDatabase({
72 accountId: auth.accountId,
73 databaseId,
74 ...(body as any),
75 }),
76 )
77 .pipe(Effect.runPromise);
78
79 const toResult = <T>(
80 r: { results?: unknown; success?: boolean | null; meta?: unknown } | undefined,
81 ): runtime.D1Result<T> =>
82 ({
83 results: (r?.results ?? []) as T[],
84 success: r?.success ?? true,
85 meta: (r?.meta ?? {}) as any,
86 }) as runtime.D1Result<T>;
87
88 /**
89 * Normalize a bound value the way the native D1 binding does before it reaches
90 * SQLite. Over the raw HTTP query API, unlike the Worker binding, values are
91 * bound verbatim — a JS `true` would arrive as the string `"true"`. Match the
92 * native semantics: booleans become integers (1/0) and binary becomes a byte
93 * array (BLOB). `null`, numbers, and strings pass through unchanged.
94 */
95 const normalizeBind = (value: unknown): unknown => {
96 if (typeof value === "boolean") return value ? 1 : 0;
97 if (value instanceof ArrayBuffer) {
98 return Array.from(new Uint8Array(value));
99 }
100 if (ArrayBuffer.isView(value)) {
101 return Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
102 }
103 return value;
104 };
105
106 /** A `D1Database` facade over the cloud HTTP query API. */
107 export const makeHttpD1Database = (auth: D1Auth, databaseId: string): runtime.D1Database =>
108 makeD1DatabaseFromTransport((body) => runQuery(auth, databaseId, body));
109
110 /**
111 * The transport a {@link runtime.D1Database} facade is built over: run one
112 * query (or batch) and return the D1 result envelope(s). Two transports
113 * exist — the cloud HTTP API (`runQuery`) and the local-simulator gateway
114 * (`withLocalD1Query`).
115 */
116 export type D1QueryTransport = (
117 body: { sql: string; params?: unknown[] } | { batch: { sql: string; params?: unknown[] }[] },
118 ) => Promise<{
119 result: Array<{
120 results?: unknown;
121 success?: boolean | null;
122 meta?: unknown;
123 }>;
124 }>;
125
126 export const makeD1DatabaseFromTransport = (transport: D1QueryTransport): runtime.D1Database => {
127 const makeStatement = (
128 query: string,
129 binds: ReadonlyArray<unknown>,
130 ): runtime.D1PreparedStatement => {
131 const exec = async () => {
132 const res = await transport({
133 sql: query,
134 params: binds.length ? binds.map(normalizeBind) : undefined,
135 });
136 return res.result[0];
137 };
138 return {
139 bind: (...values: unknown[]) => makeStatement(query, values),
140 first: (async (column?: string) => {
141 const first = ((await exec())?.results as Record<string, unknown>[] | undefined)?.[0];
142 if (first == null) return null;
143 return column !== undefined ? (first[column] ?? null) : first;
144 }) as runtime.D1PreparedStatement["first"],
145 all: (async () => toResult(await exec())) as runtime.D1PreparedStatement["all"],
146 run: (async () => toResult(await exec())) as runtime.D1PreparedStatement["run"],
147 raw: (async (options?: { columnNames?: boolean }) => {
148 const rows = ((await exec())?.results ?? []) as Record<string, unknown>[];
149 const arrays = rows.map((row) => Object.values(row));
150 if (options?.columnNames && rows[0]) {
151 return [Object.keys(rows[0]), ...arrays];
152 }
153 return arrays;
154 }) as runtime.D1PreparedStatement["raw"],
155 // Carry query + params so `batch` can reconstruct the request.
156 __query: query,
157 __params: binds,
158 } as unknown as runtime.D1PreparedStatement;
159 };
160
161 return {
162 prepare: (query: string) => makeStatement(query, []),
163 exec: async (query: string) => {
164 const res = await transport({ sql: query });
165 const meta = res.result[res.result.length - 1]?.meta as { duration?: number } | undefined;
166 return {
167 count: res.result.length,
168 duration: meta?.duration ?? 0,
169 } as runtime.D1ExecResult;
170 },
171 batch: async <T = unknown>(statements: runtime.D1PreparedStatement[]) => {
172 const res = await transport({
173 batch: statements.map((s) => ({
174 sql: (s as any).__query as string,
175 params: ((s as any).__params as unknown[]).length
176 ? ((s as any).__params as unknown[]).map(normalizeBind)
177 : undefined,
178 })),
179 });
180 return res.result.map((r) => toResult<T>(r));
181 },
182 } as unknown as runtime.D1Database;
183 };