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

main
ts 368 lines 12.5 KB
Raw
1 import * as LocalFlagship from "@alchemy.run/cloudflare-runtime/core/bindings/flagship";
2 import * as flagship from "@distilled.cloud/cloudflare/flagship";
3 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { isResourceOfType, Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import { localAccountId } from "../LocalAccount.ts";
11 import { generateLocalId } from "../LocalRuntime.ts";
12 import type { Providers } from "../Providers.ts";
13 import { localFlagshipStore } from "./Flag.ts";
14
15 const TypeId = "Cloudflare.Flagship.App" as const;
16 type TypeId = typeof TypeId;
17
18 export type AppProps = {
19 /**
20 * Human readable app name. Apps group flags by project or service. If
21 * omitted, a unique name is generated from the app, stage, and logical ID.
22 * @default ${app}-${stage}-${id}
23 */
24 name?: string;
25 };
26
27 export type AppAttributes = {
28 /**
29 * Server-generated app identifier. Stable across updates; used as the
30 * `appId` for flags, the Worker binding, and all evaluation calls.
31 */
32 appId: string;
33 /**
34 * The Cloudflare account the app belongs to.
35 */
36 accountId: string;
37 /**
38 * Human readable app name.
39 */
40 name: string;
41 /**
42 * When the app was created.
43 */
44 createdAt: string;
45 /**
46 * When the app was last modified.
47 */
48 updatedAt: string;
49 /**
50 * Email of the actor who last modified the app, or `edge-gateway` for
51 * gateway-authenticated changes.
52 */
53 updatedBy: string;
54 };
55
56 export type App = Resource<TypeId, AppProps, AppAttributes, never, Providers>;
57
58 /**
59 * A Cloudflare Flagship app — a container for feature flags.
60 *
61 * Flagship is Cloudflare's feature flag service. Flags are organized into
62 * apps that map to your projects or services; the app's `appId` is what a
63 * Worker's `Flagship` binding points at and what every evaluation call is
64 * scoped to. The name is mutable in place; the app id never changes.
65 * ### Creating an App
66 * **Example:** App with a generated name
67 * ```typescript
68 * const app = yield* Cloudflare.Flagship.App("Flags", {});
69 * ```
70 *
71 * **Example:** App with an explicit name
72 * ```typescript
73 * const app = yield* Cloudflare.Flagship.App("Flags", {
74 * name: "my-service-flags",
75 * });
76 * ```
77 *
78 * ### Using the App
79 * **Example:** Define flags in the app
80 * ```typescript
81 * const app = yield* Cloudflare.Flagship.App("Flags", {});
82 *
83 * const flag = yield* Cloudflare.Flagship.Flag("NewCheckout", {
84 * appId: app.appId,
85 * key: "new-checkout",
86 * defaultVariation: "off",
87 * variations: { off: false, on: true },
88 * });
89 * ```
90 *
91 * ### Binding to a Worker
92 * **Example:** Effect-style Worker (recommended)
93 * `Cloudflare.Flagship.ReadFlags(app)` attaches the binding to the surrounding
94 * Worker and returns the runtime client for evaluating flags. Every `Flagship`
95 * method is mirrored as an Effect, so no `Effect.tryPromise` wrapping is needed.
96 * ```typescript
97 * export const App = Cloudflare.Flagship.App("Flags", {});
98 *
99 * Cloudflare.Worker(
100 * "FlagsWorker",
101 * { main: import.meta.url },
102 * Effect.gen(function* () {
103 * const flags = yield* Cloudflare.Flagship.ReadFlags(App);
104 * return {
105 * fetch: Effect.gen(function* () {
106 * const enabled = yield* flags.getBooleanValue("new-checkout", false, {
107 * userId: "user-42",
108 * });
109 * return HttpServerResponse.text(enabled ? "on" : "off");
110 * }),
111 * };
112 * }).pipe(Effect.provide(Cloudflare.Flagship.ReadFlagsBinding)),
113 * );
114 * ```
115 *
116 * **Example:** Declare the binding on `env`
117 * Declaring the app on a Worker's `env` maps it to the native `Flagship`
118 * runtime binding via `InferEnv`.
119 * ```typescript
120 * export const App = Cloudflare.Flagship.App("Flags", {});
121 *
122 * export const Worker = Cloudflare.Worker("Worker", {
123 * main: "./src/worker.ts",
124 * env: { FLAGS: App },
125 * });
126 *
127 * export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>;
128 * // { FLAGS: Flagship }
129 * ```
130 *
131 * **Example:** Async-style worker with the raw runtime binding
132 * ```typescript
133 * import type { WorkerEnv } from "../alchemy.run.ts";
134 *
135 * export default {
136 * async fetch(request: Request, env: WorkerEnv) {
137 * const enabled = await env.FLAGS.getBooleanValue("new-checkout", false, {
138 * userId: "user-42",
139 * });
140 * return new Response(enabled ? "on" : "off");
141 * },
142 * };
143 * ```
144 *
145 * ### Local Development
146 * **Example:** Flags evaluate locally under `alchemy dev`
147 * In `alchemy dev` the app and its flags are emulated on your machine: no
148 * Cloudflare API calls, and the Worker's binding evaluates flags locally with
149 * the same targeting rules, rollouts, and evaluation reasons. Changing a flag
150 * and saving applies to the running Worker without a restart.
151 * ```typescript
152 * const app = yield* Cloudflare.Flagship.App("Flags", {});
153 *
154 * yield* Cloudflare.Flagship.Flag("NewCheckout", {
155 * appId: app.appId,
156 * key: "new-checkout",
157 * defaultVariation: "off",
158 * variations: { off: false, on: true },
159 * rules: [
160 * {
161 * priority: 1,
162 * conditions: [{ attribute: "country", operator: "equals", value: "US" }],
163 * serveVariation: "on",
164 * },
165 * ],
166 * });
167 *
168 * yield* Cloudflare.Worker("Worker", {
169 * main: "./src/worker.ts",
170 * env: { FLAGS: app },
171 * });
172 * ```
173 *
174 * **Example:** Use the real app during `alchemy dev`
175 * Pipe the app and its flags through `Alchemy.remote()` to create them on
176 * Cloudflare; the local Worker's binding then evaluates the live flags.
177 * ```typescript
178 * const app = yield* Cloudflare.Flagship.App("Flags", {}).pipe(Alchemy.remote());
179 *
180 * yield* Cloudflare.Flagship.Flag("NewCheckout", {
181 * appId: app.appId,
182 * key: "new-checkout",
183 * defaultVariation: "off",
184 * variations: { off: false, on: true },
185 * }).pipe(Alchemy.remote());
186 * ```
187 *
188 * @see https://developers.cloudflare.com/flagship/
189 * @see https://developers.cloudflare.com/api/resources/flagship/
190 *
191 * @resource
192 * @product Flagship
193 * @category Developer Platform
194 */
195 export const App = Resource<App>(TypeId);
196
197 /**
198 * Returns true if the given value is a Flagship App resource.
199 */
200 export const isApp = (value: unknown): value is App => isResourceOfType(value, TypeId);
201
202 export const AppProviderLive = () =>
203 Provider.succeed(App, {
204 stables: ["appId", "accountId", "createdAt"],
205 diff: Effect.fn(function* ({ output }) {
206 const { accountId } = yield* yield* CloudflareEnvironment;
207 if ((output?.accountId ?? accountId) !== accountId) {
208 return { action: "replace" } as const;
209 }
210 return undefined;
211 }),
212 read: Effect.fn(function* ({ id, olds, output }) {
213 const { accountId } = yield* yield* CloudflareEnvironment;
214 const acct = output?.accountId ?? accountId;
215
216 if (output?.appId) {
217 const observed = yield* getApp(acct, output.appId);
218 return observed ? toAttributes(observed, acct) : undefined;
219 }
220 // Cold read — recover from lost state by matching the deterministic
221 // physical name. App names are not unique on Cloudflare's side; an
222 // exact match on our generated/explicit name is the best identity we
223 // have. Pick the oldest match for determinism.
224 const name = yield* createAppName(id, olds?.name);
225 const match = yield* findByName(acct, name);
226 return match ? toAttributes(match, acct) : undefined;
227 }),
228 reconcile: Effect.fn(function* ({ id, news, output }) {
229 const { accountId } = yield* yield* CloudflareEnvironment;
230 const name = yield* createAppName(id, news.name);
231
232 // Observe — the appId cached on `output` is a hint, not a guarantee:
233 // a missing app falls through and we recreate.
234 const observed = output?.appId
235 ? yield* getApp(output.accountId ?? accountId, output.appId)
236 : undefined;
237
238 if (!observed) {
239 // Ensure — greenfield (or out-of-band delete). App names are not
240 // unique so there is no AlreadyExists race to tolerate.
241 const created = yield* flagship.createApp({ accountId, name });
242 return toAttributes(created, accountId);
243 }
244
245 // Sync — the only mutable aspect is the name; skip the API on a no-op.
246 if (observed.name === name) {
247 return toAttributes(observed, accountId);
248 }
249 const updated = yield* flagship.updateApp({
250 accountId,
251 appId: observed.id,
252 name,
253 });
254 return toAttributes(updated, accountId);
255 }),
256 delete: Effect.fn(function* ({ output }) {
257 yield* flagship
258 .deleteApp({ accountId: output.accountId, appId: output.appId })
259 .pipe(Effect.catchTag("FlagshipAppNotFound", () => Effect.void));
260 }),
261 // Account-scoped collection (pattern b): enumerate every app in the
262 // ambient account via the paginated listApps op. Cloudflare's list
263 // index can contain ghost rows — apps that were deleted but survive in
264 // the listing while GET/DELETE both return "App not found" — so each
265 // row is validated via getApp and ghosts are dropped (otherwise census
266 // tooling re-discovers an undeletable app forever).
267 list: Effect.fn(function* () {
268 const { accountId } = yield* yield* CloudflareEnvironment;
269 const listed = yield* flagship.listApps.pages({ accountId }).pipe(
270 Stream.runCollect,
271 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.result ?? [])),
272 );
273 const rows = yield* Effect.forEach(
274 listed,
275 (app) =>
276 getApp(accountId, app.id).pipe(
277 Effect.map((observed) => (observed ? toAttributes(observed, accountId) : undefined)),
278 ),
279 { concurrency: 10 },
280 );
281 return rows.filter((row): row is AppAttributes => row !== undefined);
282 }),
283 });
284
285 /**
286 * Local (dev) provider — the app is purely virtual: a `dev:` id keyed into
287 * the local workerd Flagship simulator. The local `Flag` provider seeds
288 * definitions under that id, and `toRuntimeBinding` lowers a `flagship`
289 * binding whose app id is `dev:`-prefixed onto the local evaluator; data
290 * persists under `.alchemy/local/flagship`.
291 */
292 export const AppProviderLocal = () =>
293 Provider.succeed(App, {
294 stables: ["appId", "accountId", "createdAt"],
295 diff: Effect.fn(function* ({ output }) {
296 if (!output?.appId) return { action: "update" } as const;
297 if (output.accountId !== (yield* localAccountId)) {
298 return { action: "replace" } as const;
299 }
300 return undefined;
301 }),
302 read: Effect.fn(function* ({ output }) {
303 // Purely virtual — the persisted state row is the source of truth.
304 return output ?? undefined;
305 }),
306 reconcile: Effect.fn(function* ({ id, news, output }) {
307 const now = yield* Effect.sync(() => new Date().toISOString());
308 return {
309 appId: output?.appId ?? generateLocalId(),
310 accountId: output?.accountId ?? (yield* localAccountId),
311 name: yield* createAppName(id, news.name),
312 createdAt: output?.createdAt ?? now,
313 updatedAt: now,
314 updatedBy: "local",
315 };
316 }),
317 delete: Effect.fn(function* ({ output }) {
318 // Flags delete their own definitions first; this sweeps anything left
319 // in the app's store (idempotent).
320 yield* LocalFlagship.deleteApp(yield* localFlagshipStore(output.appId));
321 }),
322 });
323
324 export const AppProvider = () =>
325 ProviderLayer.dual(App, {
326 local: () => AppProviderLocal(),
327 live: () => AppProviderLive(),
328 });
329
330 /**
331 * Read an app by id, mapping "gone" (`FlagshipAppNotFound`) to `undefined`.
332 */
333 const getApp = (accountId: string, appId: string) =>
334 flagship
335 .getApp({ accountId, appId })
336 .pipe(Effect.catchTag("FlagshipAppNotFound", () => Effect.undefined));
337
338 /**
339 * Find an app by exact name. If several apps carry the same name, pick the
340 * oldest for determinism.
341 */
342 const findByName = (accountId: string, name: string) =>
343 flagship.listApps.items({ accountId }).pipe(
344 Stream.filter((a) => a.name === name),
345 Stream.runCollect,
346 Effect.map((chunk) =>
347 Array.from(chunk)
348 .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
349 .at(0),
350 ),
351 );
352
353 const createAppName = (id: string, name: string | undefined) =>
354 Effect.gen(function* () {
355 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
356 });
357
358 const toAttributes = (
359 app: flagship.GetAppResponse | flagship.CreateAppResponse | flagship.UpdateAppResponse,
360 accountId: string,
361 ): AppAttributes => ({
362 appId: app.id,
363 accountId,
364 name: app.name,
365 createdAt: app.createdAt,
366 updatedAt: app.updatedAt,
367 updatedBy: app.updatedBy,
368 });