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

main
ts 183 lines 7.03 KB
Raw
1 import { readdir, readFile } from "node:fs/promises";
2 import path from "node:path";
3 import type { Graph, GraphEdge, GraphNode } from "../shared/types.ts";
4
5 /**
6 * Reads the architecture out of Alchemy's local state for one stage:
7 * every resource is a node, every binding a host holds is an edge labelled
8 * with what it granted, and output references (`downstream`) fill in the
9 * rest. Nothing here is hand-drawn, so the diagram cannot disagree with
10 * what was deployed.
11 */
12
13 interface StateRow {
14 logicalId: string;
15 fqn?: string;
16 resourceType: string;
17 providerMode?: string;
18 downstream?: string[];
19 attr?: Record<string, unknown>;
20 bindings?: { sid: string; data: Record<string, unknown> }[];
21 }
22
23 const KINDS: Record<string, { kind: string; provider: GraphNode["provider"]; tier: number }> = {
24 "Cloudflare.Website": { kind: "Vite Website", provider: "cloudflare", tier: 0 },
25 "Cloudflare.Worker": { kind: "Worker", provider: "cloudflare", tier: 1 },
26 "Cloudflare.D1Database": { kind: "D1 Database", provider: "cloudflare", tier: 2 },
27 "Cloudflare.D1.Database": { kind: "D1 Database", provider: "cloudflare", tier: 2 },
28 "Cloudflare.Queues.Queue": { kind: "Queue", provider: "cloudflare", tier: 2 },
29 "Cloudflare.Hyperdrive": { kind: "Hyperdrive", provider: "cloudflare", tier: 2 },
30 "Neon.Project": { kind: "Neon Postgres", provider: "neon", tier: 3 },
31 "Axiom.Dataset": { kind: "Axiom Dataset", provider: "axiom", tier: 3 },
32 "Axiom.ApiToken": { kind: "Ingest Token", provider: "axiom", tier: 3 },
33 "Axiom.Dashboard": { kind: "Axiom Dashboard", provider: "axiom", tier: 4 },
34 };
35
36 /** A binding's data, rendered as the grant shown in the diagram. */
37 const describeGrant = (data: Record<string, unknown>): { label: string; grant: string } => {
38 const bindings = (data.bindings as Record<string, unknown>[] | undefined) ?? [];
39 const first = bindings[0];
40 if (!first) {
41 const keys = Object.keys(data).join(", ");
42 return { label: keys || "binding", grant: keys };
43 }
44 const type = String(first.type);
45 const label =
46 {
47 d1: "D1 binding",
48 queue: "queue producer",
49 durable_object_namespace: "Durable Object namespace",
50 hyperdrive: "Hyperdrive binding",
51 plain_text: "env var",
52 secret_text: "secret",
53 }[type] ?? type;
54 // Physical ids differ per stage; show the shape of the grant.
55 const shown = Object.fromEntries(
56 Object.entries(first).filter(([key]) => !/id$|Id$|queueName|databaseName/.test(key)),
57 );
58 const extra = bindings.length > 1 ? ` + ${bindings.length - 1} more` : "";
59 const body = Object.entries(shown)
60 .map(([key, value]) => `${key}: ${JSON.stringify(value)}`)
61 .join(", ");
62 return { label, grant: `{ ${body} }${extra}` };
63 };
64
65 export const readGraph = async (stateDir: string, stage: string): Promise<Graph> => {
66 const dir = path.join(stateDir, stage);
67 const files = (await readdir(dir).catch(() => [] as string[])).filter(
68 (file) => file.endsWith(".json") && !file.startsWith("__"),
69 );
70 const rows: StateRow[] = [];
71 for (const file of files) {
72 const row = JSON.parse(await readFile(path.join(dir, file), "utf8")) as StateRow;
73 if (row.resourceType) rows.push(row);
74 }
75
76 const nodes = new Map<string, GraphNode>();
77 const edges = new Map<string, GraphEdge>();
78 const idOf = (row: StateRow) => row.logicalId;
79 const addEdge = (edge: Omit<GraphEdge, "id">) => {
80 const id = `${edge.from}->${edge.to}`;
81 if (!edges.has(id)) edges.set(id, { id, ...edge });
82 };
83
84 for (const row of rows) {
85 if (row.resourceType === "Cloudflare.Queues.Consumer") continue;
86 const known = KINDS[row.resourceType];
87 // Website.Vite is a Worker serving the built site; the demo names it "Web".
88 const isWebsite = row.resourceType === "Cloudflare.Worker" && row.logicalId === "Web";
89 const meta = isWebsite
90 ? KINDS["Cloudflare.Website"]!
91 : (known ?? {
92 kind: row.resourceType.split(".").pop()!,
93 provider: "other" as const,
94 tier: 2,
95 });
96 nodes.set(idOf(row), {
97 id: idOf(row),
98 kind: meta.kind,
99 provider: meta.provider,
100 location: row.providerMode === "local" ? "local" : "cloud",
101 tier: meta.tier,
102 });
103 }
104
105 for (const row of rows) {
106 const host = idOf(row);
107 for (const binding of row.bindings ?? []) {
108 const { label, grant } = describeGrant(binding.data);
109 const types = ((binding.data.bindings as { type?: string; className?: string }[]) ?? []).map(
110 (b) => b.type,
111 );
112 if (types.includes("durable_object_namespace")) {
113 // Durable Object classes live inside the Worker's script: draw them as their own node.
114 const node = nodes.get(host);
115 nodes.set(binding.sid, {
116 id: binding.sid,
117 kind: "Durable Object",
118 provider: "cloudflare",
119 location: node?.location ?? "cloud",
120 tier: 2,
121 });
122 }
123 if (types.includes("plain_text") && binding.sid.startsWith("VITE_")) {
124 const target = rows.find(
125 (r) => r.downstream?.includes(host) && r.resourceType === "Cloudflare.Worker",
126 );
127 if (target)
128 addEdge({ from: host, to: idOf(target), kind: "reference", label: binding.sid, grant });
129 continue;
130 }
131 if (nodes.has(binding.sid)) {
132 addEdge({ from: host, to: binding.sid, kind: "binding", label, grant });
133 }
134 }
135 if (row.resourceType === "Cloudflare.Queues.Consumer") {
136 const worker = row.fqn?.split("/")[0];
137 const queue = rows.find(
138 (r) =>
139 r.resourceType === "Cloudflare.Queues.Queue" && r.downstream?.includes(row.fqn ?? ""),
140 );
141 if (worker && queue) {
142 addEdge({
143 from: idOf(queue),
144 to: worker,
145 kind: "consumer",
146 label: "consumer",
147 grant: "delivers message batches",
148 });
149 }
150 }
151 }
152
153 // Output references not already covered by a binding (e.g. Neon → Hyperdrive origin, Axiom → Worker telemetry).
154 for (const row of rows) {
155 if (!nodes.has(idOf(row))) continue;
156 for (const down of row.downstream ?? []) {
157 if (down.includes("/") || !nodes.has(down)) continue;
158 const user = nodes.get(down)!;
159 if (user.kind === "Vite Website") continue;
160 if (edges.has(`${down}->${idOf(row)}`) || edges.has(`${idOf(row)}->${down}`)) continue;
161 const label =
162 row.resourceType === "Axiom.ApiToken"
163 ? "ingest token (secret)"
164 : row.resourceType === "Axiom.Dataset"
165 ? "OTLP export"
166 : row.resourceType === "Neon.Project"
167 ? "origin"
168 : "reference";
169 addEdge({ from: down, to: idOf(row), kind: "reference", label });
170 }
171 }
172
173 // Dashboards query the trace dataset.
174 for (const dashboard of rows.filter((r) => r.resourceType === "Axiom.Dashboard")) {
175 const traces = rows.find(
176 (r) => r.resourceType === "Axiom.Dataset" && String(r.attr?.kind ?? "").includes("traces"),
177 );
178 if (traces)
179 addEdge({ from: idOf(dashboard), to: idOf(traces), kind: "reference", label: "queries" });
180 }
181
182 return { stage, nodes: [...nodes.values()], edges: [...edges.values()] };
183 };