@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, 06:00 UTC

main
ts 116 lines 4.59 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import type { RuntimeContext } from "alchemy";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import type * as Scope from "effect/Scope";
6 import { Database, type DatabaseService, type DirectDatabase } from "./Database.ts";
7 import type { BetterAuthMigrationError } from "./Errors.ts";
8
9 /**
10 * Cloudflare D1 database layer for Better Auth.
11 *
12 * At runtime the Worker reaches the database through its native D1 binding
13 * (the layer bakes in `QueryDatabaseBinding`). At deploy time, schema
14 * migrations run over the D1 HTTP query API — which also transparently
15 * targets the local D1 simulator under `alchemy dev`.
16 *
17 *
18 * ### Using D1 as the auth database
19 * Provide the layer on the Worker impl effect that yields `BetterAuth`.
20 * The database resource can be referenced from module scope — the layer
21 * accepts the resource or its Effect.
22 * **Example:** Worker with a D1-backed BetterAuth
23 * ```typescript
24 * import { BetterAuth } from "@alchemy.run/better-auth";
25 * import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1";
26 * import * as Cloudflare from "@alchemy.run/cloudflare";
27 *
28 * export const AuthDb = Cloudflare.D1.Database("AuthDb");
29 *
30 * export default class Api extends Cloudflare.Worker<Api>()(
31 * "Api",
32 * { main: import.meta.url, compatibility: { flags: ["nodejs_compat"] } },
33 * Effect.gen(function* () {
34 * const auth = yield* BetterAuth({
35 * basePath: "/auth",
36 * emailAndPassword: { enabled: true },
37 * });
38 * return {
39 * fetch: Effect.gen(function* () {
40 * const request = yield* HttpServerRequest;
41 * if (request.url.startsWith("/auth")) {
42 * return yield* auth.fetch;
43 * }
44 * const session = yield* auth.getSession();
45 * return yield* HttpServerResponse.json({ user: session?.user ?? null });
46 * }),
47 * };
48 * }).pipe(Effect.provide(CloudflareD1(AuthDb))),
49 * ) {}
50 * ```
51 *
52 * ### Migrations
53 * The schema migration Action connects over the D1 HTTP API at deploy
54 * time — the Worker's native binding is never used outside the deployed
55 * runtime, and no migration code ships in the Worker bundle.
56 * **Example:** Opting out of automatic migrations
57 * ```typescript
58 * const auth = yield* BetterAuth({
59 * migrate: false, // manage the schema yourself
60 * emailAndPassword: { enabled: true },
61 * });
62 * ```
63 *
64 * @layer
65 * @provides BetterAuth.Database
66 * @product D1
67 */
68 export const CloudflareD1 = (
69 database: Cloudflare.D1.Database | Effect.Effect<Cloudflare.D1.Database, never, any>,
70 ) =>
71 Layer.effect(
72 Database,
73 Effect.gen(function* () {
74 const db = Effect.isEffect(database)
75 ? yield* database as Effect.Effect<Cloudflare.D1.Database>
76 : database;
77 const client = yield* Cloudflare.D1.QueryDatabase(db);
78 const service: DatabaseService = {
79 provider: "sqlite",
80 runtime: client.raw,
81 };
82 // Migration support references the deploy-time HTTP/local D1 client
83 // (`QueryDatabaseLocal`), which must never reach a Worker bundle —
84 // this branch is dead-code-eliminated from deployed runtimes, which
85 // also tree-shakes the local-runtime machinery out of the bundle.
86 if (!globalThis.__ALCHEMY_RUNTIME__) {
87 return {
88 ...service,
89 migrate: {
90 identity: { databaseId: db.databaseId } as Record<string, unknown>,
91 connect: Effect.gen(function* () {
92 // Init half — runs under the migration Action's capture
93 // context: `QueryDatabase(database)` yields the databaseId
94 // Output, recording the dependency; the client's `raw` is a
95 // deferred accessor that resolves at apply.
96 const local = yield* Cloudflare.D1.QueryDatabase(db);
97 // Apply half — materialize the HTTP D1 facade.
98 return Effect.map(local.raw, (database) => database as DirectDatabase);
99 }).pipe(
100 Effect.provide(Cloudflare.D1.QueryDatabaseLocal),
101 (effect) =>
102 // The HTTP client's build requirements (Cloudflare
103 // credentials, HttpClient) are ambient during stack-eval
104 // where the init half runs.
105 effect as unknown as Effect.Effect<
106 Effect.Effect<DirectDatabase, BetterAuthMigrationError, Scope.Scope>,
107 never,
108 RuntimeContext
109 >,
110 ),
111 },
112 } satisfies DatabaseService;
113 }
114 return service;
115 }),
116 ).pipe(Layer.provide(Cloudflare.D1.QueryDatabaseBinding));