Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

generate.ts

302 lines9.7 KB

1#!/usr/bin/env node
2​
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Logger from "effect/Logger";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import { Command, Flag } from "effect/unstable/cli";
13import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/unstable/http";
14import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
15​
16const CURRENT_SCHEMA_RELEASE = "v0.11.3";
17​
18interface GenerateCommandError {
19 readonly _tag: "GenerateCommandError";
20 readonly message: string;
22​
23interface GeneratedPaths {
24 readonly generatedDir: string;
25 readonly upstreamSchemaPath: string;
26 readonly upstreamMetaPath: string;
27 readonly schemaOutputPath: string;
28 readonly metaOutputPath: string;
30​
31const UpstreamJsonSchemaSchema = Schema.Struct({
32 $defs: Schema.Record(Schema.String, Schema.Json),
33});
34const MetaJsonSchema = Schema.Struct({
35 agentMethods: Schema.Record(Schema.String, Schema.String),
36 clientMethods: Schema.Record(Schema.String, Schema.String),
37 version: Schema.Union([Schema.Number, Schema.String]),
38});
39const encodeAgentMethods = Schema.encodeEffect(
40 Schema.fromJsonString(MetaJsonSchema.fields.agentMethods),
41);
42const encodeClientMethods = Schema.encodeEffect(
43 Schema.fromJsonString(MetaJsonSchema.fields.clientMethods),
44);
45const encodeVersion = Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.version));
46​
47const decodeUpstreamSchema = Schema.decodeEffect(Schema.fromJsonString(UpstreamJsonSchemaSchema));
48const decodeMetaJson = Schema.decodeEffect(Schema.fromJsonString(MetaJsonSchema));
49​
50const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
51 const path = yield* Path.Path;
52 const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
53 return {
54 generatedDir,
55 upstreamSchemaPath: path.join(generatedDir, "upstream-schema.json"),
56 upstreamMetaPath: path.join(generatedDir, "upstream-meta.json"),
57 schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
58 metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
59 } satisfies GeneratedPaths;
60});
61​
62const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
63 const fs = yield* FileSystem.FileSystem;
64 const { generatedDir } = yield* getGeneratedPaths();
65​
66 yield* fs.makeDirectory(generatedDir, { recursive: true });
67});
68​
69const downloadFile = Effect.fn("downloadFile")(function* (url: string, outputPath: string) {
70 const fs = yield* FileSystem.FileSystem;
71 const path = yield* Path.Path;
72​
73 yield* fs.makeDirectory(path.dirname(outputPath), { recursive: true });
74​
75 const text = yield* HttpClient.get(url).pipe(
76 Effect.flatMap(HttpClientResponse.filterStatusOk),
77 Effect.flatMap((response) => response.text),
78 );
79​
80 yield* fs.writeFileString(outputPath, text);
81});
82​
83const downloadSchemas = Effect.fn("downloadSchemas")(function* (tag: string) {
84 const { upstreamMetaPath, upstreamSchemaPath } = yield* getGeneratedPaths();
85 const fs = yield* FileSystem.FileSystem;
86 const baseUrl = `https://github.com/agentclientprotocol/agent-client-protocol/releases/download/${tag}`;
87​
88 yield* downloadFile(`${baseUrl}/schema.unstable.json`, upstreamSchemaPath);
89 yield* downloadFile(`${baseUrl}/meta.unstable.json`, upstreamMetaPath);
90​
91 yield* Effect.addFinalizer(() =>
92 Effect.all([fs.remove(upstreamSchemaPath), fs.remove(upstreamMetaPath)]).pipe(
93 Effect.ignoreCause({ log: true }),
94 ),
95 );
96});
97​
98const readFileString = Effect.fn("readJsonFile")(function* (filePath: string) {
99 const fs = yield* FileSystem.FileSystem;
100 return yield* fs.readFileString(filePath);
101});
102​
103const writeGeneratedFiles = Effect.fn("writeGeneratedFiles")(function* (
104 schemaOutput: string,
105 metaOutput: string,
106) {
107 const fs = yield* FileSystem.FileSystem;
108 const { metaOutputPath, schemaOutputPath } = yield* getGeneratedPaths();
109​
110 yield* fs.writeFileString(schemaOutputPath, schemaOutput);
111 yield* fs.writeFileString(metaOutputPath, metaOutput);
112});
113​
114function collectSchemaEntries(
115 chunk: string,
116): ReadonlyArray<{ readonly name: string; readonly code: string }> {
117 const lines = chunk
118 .split("\n")
119 .map((line) => line.trim())
120 .filter((line) => line.length > 0 && !line.startsWith("//"));
121 const entries: Array<{ name: string; code: string }> = [];
122​
123 for (let index = 0; index < lines.length; index += 1) {
124 const typeLine = lines[index];
125 if (!typeLine?.startsWith("export type ")) {
126 continue;
127 }
128​
129 const constLine = lines[index + 1];
130 if (!constLine?.startsWith("export const ")) {
131 throw new Error(`Malformed generator output near: ${typeLine}`);
132 }
133​
134 const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
135 if (!match?.[1]) {
136 throw new Error(`Could not extract schema name from: ${typeLine}`);
137 }
138​
139 entries.push({
140 name: match[1],
141 code: `${typeLine}\n${constLine}`,
142 });
143 index += 1;
144 }
145​
146 return entries;
148​
149function normalizeNullableTypes(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
150 if (Array.isArray(value)) {
151 return value.map(normalizeNullableTypes);
152 }
153 if (value === null || typeof value !== "object") {
154 return value;
155 }
156​
157 const normalizedEntries = Object.entries(value).map(([key, child]) => [
158 key,
159 normalizeNullableTypes(child),
160 ]);
161 const normalizedObject = Object.fromEntries(normalizedEntries) as Record<
162 string,
163 typeof Schema.Json.Type
164 >;
165 const typeValue = normalizedObject.type;
166​
167 if (!Array.isArray(typeValue)) {
168 return normalizedObject;
169 }
170​
171 const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
172 if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
173 return normalizedObject;
174 }
175​
176 const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
177 if (nonNullTypes.length !== 1) {
178 return normalizedObject;
179 }
180 const nonNullType = nonNullTypes[0]!;
181​
182 const nextObject: Record<string, typeof Schema.Json.Type> = {};
183 for (const [key, child] of Object.entries(normalizedObject)) {
184 if (key !== "type") {
185 nextObject[key] = child;
186 }
187 }
188​
189 return {
190 anyOf: [
191 {
192 ...nextObject,
193 type: nonNullType,
194 },
195 { type: "null" },
196 ],
197 };
199​
200const generateSchemas = Effect.fn("generateSchemas")(function* (skipDownload: boolean) {
201 const { upstreamMetaPath, upstreamSchemaPath } = yield* getGeneratedPaths();
202​
203 yield* ensureGeneratedDir();
204​
205 if (!skipDownload) {
206 yield* Effect.log(`Downloading ACP schema assets for ${CURRENT_SCHEMA_RELEASE}`);
207 yield* downloadSchemas(CURRENT_SCHEMA_RELEASE);
208 }
209​
210 const upstreamSchema = yield* readFileString(upstreamSchemaPath).pipe(
211 Effect.flatMap(decodeUpstreamSchema),
212 );
213 const upstreamMeta = yield* readFileString(upstreamMetaPath).pipe(Effect.flatMap(decodeMetaJson));
214 const normalizedDefinitions = Object.fromEntries(
215 Object.entries(upstreamSchema.$defs).map(([name, schema]) => [
216 name,
217 normalizeNullableTypes(schema),
218 ]),
219 );
220​
221 const sortedEntries = Object.entries(normalizedDefinitions).toSorted(([left], [right]) =>
222 left.localeCompare(right),
223 );
224 const generatedEntries = new Map<string, string>();
225 const generator = makeJsonSchemaGenerator();
226​
227 for (const [name, schema] of sortedEntries) {
228 generator.addSchema(name, schema as never);
229 }
230​
231 const output = generator.generate("openapi-3.1", normalizedDefinitions as never, false).trim();
232 if (output.length > 0) {
233 for (const entry of collectSchemaEntries(output)) {
234 if (!generatedEntries.has(entry.name)) {
235 generatedEntries.set(entry.name, entry.code);
236 }
237 }
238 }
239​
240 const prelude = [
241 `// This file is generated by the effect-acp package. Do not edit manually.`,
242 `// Current ACP schema release: ${CURRENT_SCHEMA_RELEASE}`,
243 "",
244 ];
245​
246 const schemaOutput = [
247 ...prelude,
248 'import * as Schema from "effect/Schema";',
249 "",
250 [...generatedEntries.values()].join("\n\n"),
251 "",
252 ].join("\n");
253​
254 const metaOutput = [
255 ...prelude,
256 `export const AGENT_METHODS = ${yield* encodeAgentMethods(upstreamMeta.agentMethods)} as const;`,
257 "",
258 `export const CLIENT_METHODS = ${yield* encodeClientMethods(upstreamMeta.clientMethods)} as const;`,
259 "",
260 `export const PROTOCOL_VERSION = ${yield* encodeVersion(upstreamMeta.version)} as const;`,
261 "",
262 ].join("\n");
263​
264 yield* writeGeneratedFiles(schemaOutput, metaOutput);
265 yield* Effect.log(
266 `Generated ${generatedEntries.size} ACP schemas from ${CURRENT_SCHEMA_RELEASE}`,
267 );
268​
269 const { generatedDir } = yield* getGeneratedPaths();
270 yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
271 Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))),
272 Effect.flatMap((child) => child.exitCode),
273 Effect.tap((code) =>
274 code === 0
275 ? Effect.void
276 : Effect.fail<GenerateCommandError>({
277 _tag: "GenerateCommandError",
278 message: `oxfmt failed with exit code ${code}`,
279 }),
280 ),
281 );
282});
283​
284const generateCommand = Command.make(
285 "generate",
286 {
287 skipDownload: Flag.boolean("skip-download").pipe(Flag.withDefault(false)),
288 },
289 ({ skipDownload }) => generateSchemas(skipDownload),
290).pipe(Command.withDescription("Generate Effect ACP schemas from the pinned ACP release assets."));
291​
292const runtimeLayer = Layer.mergeAll(
293 Logger.layer([Logger.consolePretty()]),
294 NodeServices.layer,
295 FetchHttpClient.layer,
296);
297​
298Command.run(generateCommand, { version: "0.0.0" }).pipe(
299 Effect.scoped,
300 Effect.provide(runtimeLayer),
301 NodeRuntime.runMain,
302);