@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 177 lines 6.45 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import * as flagship from "@distilled.cloud/cloudflare/flagship";
3 import type { RuntimeContext } from "alchemy/RuntimeContext";
4 import * as Effect from "effect/Effect";
5 import type * as HttpClient from "effect/http/HttpClient";
6 import type { Credentials } from "../Credentials.ts";
7 import {
8 type EvaluationContext,
9 type EvaluationDetails,
10 FlagshipError,
11 type ReadFlagsClient,
12 } from "./ReadFlags.ts";
13
14 // Shared HTTP scaffolding for the Flagship `ReadFlags` binding. NOT
15 // re-exported from `index.ts` — only the contract and the impl layers are
16 // public. A future token-scoped `ReadFlagsHttp` layer reuses this builder with
17 // an auth minted from an `AccountApiToken`; `ReadFlagsLocal` builds the auth
18 // from the ambient current-credentials context.
19
20 /**
21 * Injectable auth shared by the Local (current-credentials) impl and a future
22 * Http (scoped-token) impl. `authorize` discharges the
23 * `Credentials | HttpClient` requirement of a distilled op; `accountId` is the
24 * Cloudflare account the ops run against.
25 */
26 export interface FlagshipAuth {
27 authorize: <A, E>(
28 eff: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
29 ) => Effect.Effect<A, E>;
30 accountId: Effect.Effect<string>;
31 }
32
33 /**
34 * The HTTP evaluate endpoint only supports a single `targetingKey` query
35 * param, not the full flat evaluation context the Worker binding accepts.
36 */
37 const targetingKeyOf = (context: EvaluationContext | undefined): string | undefined => {
38 const value = context?.["targetingKey"];
39 if (value === undefined) return undefined;
40 return typeof value === "string" ? value : JSON.stringify(value);
41 };
42
43 /**
44 * Build a {@link ReadFlagsClient} over the Flagship HTTP evaluate endpoint
45 * (`GET .../flagship/apps/{appId}/evaluate`).
46 *
47 * `appId` is an Effect so the resolution stays deferred to each call — inside
48 * an Action it resolves through the apply-time RuntimeContext. Mirrors the
49 * Worker binding's fall-back-to-default semantics: evaluation never fails the
50 * effect — an HTTP error or a value whose type does not match the requested
51 * method resolves to `defaultValue` instead. The `raw` runtime binding has no
52 * HTTP equivalent and dies if used.
53 */
54 export const makeHttpFlagshipClient = (
55 auth: FlagshipAuth,
56 appId: Effect.Effect<string>,
57 ): ReadFlagsClient => {
58 const evaluate = (flagKey: string, context?: EvaluationContext) =>
59 Effect.all([appId, auth.accountId]).pipe(
60 Effect.flatMap(([id, accountId]) =>
61 auth.authorize(
62 flagship.getAppEvaluate({
63 accountId,
64 appId: id,
65 flagKey,
66 targetingKey: targetingKeyOf(context),
67 }),
68 ),
69 ),
70 );
71
72 const details = <T>(
73 flagKey: string,
74 defaultValue: T,
75 match: (value: unknown) => value is T,
76 context?: EvaluationContext,
77 ): Effect.Effect<EvaluationDetails<T>, FlagshipError, RuntimeContext> =>
78 evaluate(flagKey, context).pipe(
79 Effect.map((r): EvaluationDetails<T> =>
80 match(r.value)
81 ? { flagKey, value: r.value, variant: r.variant, reason: r.reason }
82 : {
83 flagKey,
84 value: defaultValue,
85 variant: r.variant,
86 reason: r.reason,
87 errorCode: "TYPE_MISMATCH",
88 },
89 ),
90 Effect.catch((error) =>
91 Effect.succeed<EvaluationDetails<T>>({
92 flagKey,
93 value: defaultValue,
94 reason: "ERROR",
95 errorCode: error._tag,
96 }),
97 ),
98 );
99
100 const value = <T>(
101 flagKey: string,
102 defaultValue: T,
103 match: (value: unknown) => value is T,
104 context?: EvaluationContext,
105 ): Effect.Effect<T, FlagshipError, RuntimeContext> =>
106 evaluate(flagKey, context).pipe(
107 Effect.map((r) => (match(r.value) ? r.value : defaultValue)),
108 Effect.orElseSucceed(() => defaultValue),
109 );
110
111 const isBoolean = (v: unknown): v is boolean => typeof v === "boolean";
112 const isString = (v: unknown): v is string => typeof v === "string";
113 const isNumber = (v: unknown): v is number => typeof v === "number";
114 const isObjectLike = (v: unknown): boolean => v !== null && typeof v === "object";
115
116 return {
117 // The raw runtime binding is a workerd object with no HTTP surface.
118 raw: Effect.die(
119 new FlagshipError({
120 message:
121 "the raw Flagship runtime binding is unavailable over HTTP; use ReadFlagsBinding inside a Worker",
122 cause: undefined,
123 }),
124 ) as Effect.Effect<cf.Flagship, never, RuntimeContext>,
125 get: (flagKey, defaultValue, context) =>
126 evaluate(flagKey, context).pipe(
127 Effect.map((r) => r.value ?? defaultValue),
128 Effect.orElseSucceed(() => defaultValue),
129 ),
130 getBooleanValue: (flagKey, defaultValue, context) =>
131 value(flagKey, defaultValue, isBoolean, context),
132 getStringValue: (flagKey, defaultValue, context) =>
133 value(flagKey, defaultValue, isString, context),
134 getNumberValue: (flagKey, defaultValue, context) =>
135 value(flagKey, defaultValue, isNumber, context),
136 getObjectValue: (flagKey, defaultValue, context) =>
137 evaluate(flagKey, context).pipe(
138 Effect.map((r) =>
139 isObjectLike(r.value) ? (r.value as typeof defaultValue) : defaultValue,
140 ),
141 Effect.orElseSucceed(() => defaultValue),
142 ),
143 getBooleanDetails: (flagKey, defaultValue, context) =>
144 details(flagKey, defaultValue, isBoolean, context),
145 getStringDetails: (flagKey, defaultValue, context) =>
146 details(flagKey, defaultValue, isString, context),
147 getNumberDetails: (flagKey, defaultValue, context) =>
148 details(flagKey, defaultValue, isNumber, context),
149 getObjectDetails: (flagKey, defaultValue, context) =>
150 evaluate(flagKey, context).pipe(
151 Effect.map((r): EvaluationDetails<typeof defaultValue> =>
152 isObjectLike(r.value)
153 ? {
154 flagKey,
155 value: r.value as typeof defaultValue,
156 variant: r.variant,
157 reason: r.reason,
158 }
159 : {
160 flagKey,
161 value: defaultValue,
162 variant: r.variant,
163 reason: r.reason,
164 errorCode: "TYPE_MISMATCH",
165 },
166 ),
167 Effect.catch((error) =>
168 Effect.succeed<EvaluationDetails<typeof defaultValue>>({
169 flagKey,
170 value: defaultValue,
171 reason: "ERROR",
172 errorCode: error._tag,
173 }),
174 ),
175 ),
176 } satisfies ReadFlagsClient;
177 };