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

main
ts 74 lines 2.63 KB
Raw
1 import type { RuntimeContext } from "alchemy";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import { BetterAuthApiError, isAPIErrorLike } from "./Errors.ts";
5
6 /** A non-`APIError` throw from an endpoint; immediately turned into a defect. */
7 class NonApiThrow extends Data.TaggedError("NonApiThrow")<{ readonly cause: unknown }> {}
8
9 /**
10 * Every `auth.api.*` endpoint mirrored as an Effect: same arguments, same
11 * success type, with the thrown `APIError` surfaced as a typed
12 * {@link BetterAuthApiError} failure. Non-`APIError` throws become defects.
13 *
14 * Known (accepted) lossage vs the raw promise API: conditional-type
15 * inference collapses overload sets to their last signature, so the
16 * `asResponse`/`returnHeaders` return-type refinements degrade on some
17 * endpoints. Use the raw `auth` escape hatch for those.
18 */
19 export type BetterAuthApi<Api> = {
20 readonly [K in keyof Api]: Api[K] extends (...args: infer Args) => Promise<infer A>
21 ? (...args: Args) => Effect.Effect<A, BetterAuthApiError, RuntimeContext>
22 : never;
23 };
24
25 /**
26 * Build the effectified `api` Proxy over the per-execution auth instance.
27 *
28 * @internal
29 */
30 export const makeApiProxy = <A extends { api: unknown }>(
31 makeAuth: Effect.Effect<A, never, RuntimeContext>,
32 ): BetterAuthApi<A["api"]> => {
33 const wrappers = new Map<
34 PropertyKey,
35 (...args: unknown[]) => Effect.Effect<unknown, BetterAuthApiError, RuntimeContext>
36 >();
37 return new Proxy(
38 {},
39 {
40 get(_target, key) {
41 // Never look like a thenable / iterable — the proxy is a plain
42 // record of endpoint wrappers.
43 if (typeof key !== "string" || key === "then") {
44 return undefined;
45 }
46 let wrapper = wrappers.get(key);
47 if (wrapper === undefined) {
48 wrapper = (...args: unknown[]) =>
49 Effect.flatMap(makeAuth, (auth) =>
50 Effect.catchTag(
51 Effect.tryPromise({
52 try: () =>
53 (auth.api as Record<string, (...args: unknown[]) => Promise<unknown>>)[key]!(
54 ...args,
55 ),
56 catch: (error) =>
57 isAPIErrorLike(error)
58 ? BetterAuthApiError.fromAPIError(error)
59 : new NonApiThrow({ cause: error }),
60 }),
61 "NonApiThrow",
62 (error) => Effect.die(error.cause),
63 ),
64 );
65 wrappers.set(key, wrapper);
66 }
67 return wrapper;
68 },
69 has(_target, key) {
70 return typeof key === "string" && key !== "then";
71 },
72 },
73 ) as BetterAuthApi<A["api"]>;
74 };