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

main
ts 150 lines 5.13 KB
Raw
1 import { DurableObject } from "cloudflare:workers";
2 import type { AsyncWorkerEnv } from "../alchemy.run.ts";
3 import wasm from "./modules/wasm-example.wasm";
4
5 interface AddInstance {
6 exports: {
7 add(a: number, b: number): number;
8 };
9 }
10
11 export default {
12 async fetch(request, env) {
13 const url = new URL(request.url);
14 switch (url.pathname) {
15 case "/env":
16 return Response.json(env);
17 case "/wasm":
18 const instance = (await WebAssembly.instantiate(wasm)) as AddInstance;
19 return Response.json({ result: instance.exports.add(3, 4) });
20 case "/queue/send": {
21 const body = await request.json<Message["body"]>();
22 const queue = await env.QUEUE.send(body);
23 return Response.json({ queue });
24 }
25 case "/queue/messages": {
26 const storage = env.MESSAGES.getByName("global");
27 const messages = await storage.list();
28 return Response.json(messages);
29 }
30 case "/counter": {
31 const counter = env.COUNTER.getByName("my-counter");
32 const count = await counter.increment();
33 return new Response(`Hello, world! ${count}`);
34 }
35 case "/r2": {
36 await env.BUCKET.put("hello.txt", "hello from r2");
37 const object = await env.BUCKET.get("hello.txt");
38 const text = object === null ? null : await object.text();
39 const list = await env.BUCKET.list();
40 return Response.json({
41 text,
42 keys: list.objects.map((o) => o.key),
43 });
44 }
45 case "/d1": {
46 // The `greetings` table comes from ./migrations — no DDL here, so a
47 // failing migration apply fails this route loudly.
48 await env.DB.prepare("INSERT INTO greetings (text) VALUES (?)").bind("hello from d1").run();
49 const row = await env.DB.prepare(
50 "SELECT text FROM greetings ORDER BY id DESC LIMIT 1",
51 ).first<{ text: string }>();
52 return Response.json({ text: row?.text ?? null });
53 }
54 case "/cache": {
55 // The local runtime ships an always-on Cache API simulator
56 // (persisted under `.alchemy/local`), so `caches.default` works
57 // exactly like in production. The caller supplies a key to keep
58 // "first fetch misses" deterministic across runs.
59 const keyName = url.searchParams.get("key") ?? "cached-resource";
60 const key = new Request(`https://example.com/${keyName}`);
61 let hit = true;
62 let cached = await caches.default.match(key);
63 if (!cached) {
64 hit = false;
65 cached = new Response("cached-body", {
66 headers: { "Cache-Control": "public, max-age=60" },
67 });
68 await caches.default.put(key, cached.clone());
69 }
70 return Response.json({ hit, body: await cached.text() });
71 }
72 case "/ratelimit": {
73 // THROTTLE allows 2 requests per 10s per key — the third call with
74 // the same key observes `success: false`.
75 const key = url.searchParams.get("key") ?? "default";
76 const { success } = await env.THROTTLE.limit({ key });
77 return Response.json({ success });
78 }
79 case "/version": {
80 // Version metadata binding; locally stubbed with a random `id`.
81 return Response.json(env.CF_VERSION_METADATA);
82 }
83 case "/service": {
84 // Service binding: call the Effect-native worker's `/url` route
85 // (worker → worker, no public hop).
86 const response = await env.SERVICE.fetch("http://effect-worker/url");
87 return Response.json(await response.json());
88 }
89 case "/kv-live": {
90 // LIVE_KV opted out of local emulation via `Alchemy.remote()` — the
91 // roundtrip below lands in the REAL cloud namespace even in dev.
92 const key = url.searchParams.get("key") ?? "hello";
93 const value = url.searchParams.get("value");
94 if (value !== null) {
95 await env.LIVE_KV.put(key, value);
96 }
97 return Response.json({ value: await env.LIVE_KV.get(key) });
98 }
99 case "/tail-ping": {
100 // Logged marker rides the trace batch delivered to the tail worker.
101 console.log("cloudflare-dev-tail-marker");
102 return new Response("pinged");
103 }
104 default:
105 return env.ASSETS.fetch(request);
106 }
107 },
108 async queue(batch, env) {
109 const storage = env.MESSAGES.getByName("global");
110 for (const message of batch.messages) {
111 await storage.put({
112 id: message.id,
113 body: message.body as Message["body"],
114 });
115 }
116 },
117 } satisfies ExportedHandler<AsyncWorkerEnv>;
118
119 export class Counter extends DurableObject {
120 async increment() {
121 return ++this.counter;
122 }
123
124 get counter() {
125 return this.ctx.storage.kv.get<number>("counter") ?? 0;
126 }
127
128 set counter(value: number) {
129 this.ctx.storage.kv.put("counter", value);
130 }
131 }
132
133 export interface Message {
134 id: string;
135 body: {
136 text: string;
137 sentAt: number;
138 };
139 }
140
141 export class QueueMessages extends DurableObject {
142 async put(message: Message) {
143 this.ctx.storage.kv.put(message.id, message);
144 }
145
146 async list(): Promise<Message[]> {
147 const messages = new Map(this.ctx.storage.kv.list<Message>());
148 return Array.from(messages.values());
149 }
150 }