Open History to see the last commit
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 {
13 FetchHttpClient,
14 HttpClient,
15 HttpClientRequest,
16 HttpClientResponse,
17} from "effect/unstable/http";
18import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
19
20const UPSTREAM_REF = "678157acaa819d5510adfe359abb5d0392cfe461";
21const USER_AGENT = "effect-codex-app-server-generator";
22const GITHUB_API_BASE =
23 "https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol";
24
25const GithubContentEntries = Schema.Array(
26 Schema.Struct({
27 name: Schema.String,
28 path: Schema.String,
29 download_url: Schema.NullOr(Schema.String),
30 type: Schema.String,
31 }),
32);
33type GithubContentEntry = (typeof GithubContentEntries.Type)[number];
34
35const JsonSchemaDocument = Schema.StructWithRest(
36 Schema.Struct({
37 definitions: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),
38 }),
39 [Schema.Record(Schema.String, Schema.Json)],
40);
41const decodeGithubContentEntries = Schema.decodeEffect(Schema.fromJsonString(GithubContentEntries));
42const decodeJsonSchemaDocument = Schema.decodeEffect(Schema.fromJsonString(JsonSchemaDocument));
43
44interface GeneratedPaths {
45 readonly generatedDir: string;
46 readonly schemaOutputPath: string;
47 readonly metaOutputPath: string;
48 readonly namespacesOutputPath: string;
49}
50
51interface MethodEntry {
52 readonly method: string;
53 readonly paramsType?: string;
54}
55
56interface JsonSchemaFile {
57 readonly namespace?: string;
58 readonly exportName: string;
59 readonly fileName: string;
60 readonly downloadUrl: string;
61 readonly qualifiedName: string;
62}
63
64class GeneratorError extends Schema.TaggedErrorClass<GeneratorError>()("GeneratorError", {
65 detail: Schema.String,
66 cause: Schema.optional(Schema.Defect()),
67}) {
68 override get message() {
69 return this.detail;
70 }
71}
72
73const ManualSchemas: Record<string, Schema.Json> = {
74 GetAuthStatusParams: {
75 type: "object",
76 title: "GetAuthStatusParams",
77 properties: {
78 includeToken: {
79 anyOf: [{ type: "boolean" }, { type: "null" }],
80 },
81 refreshToken: {
82 anyOf: [{ type: "boolean" }, { type: "null" }],
83 },
84 },
85 },
86 GetConversationSummaryParams: {
87 title: "GetConversationSummaryParams",
88 oneOf: [
89 {
90 type: "object",
91 properties: {
92 rolloutPath: { type: "string" },
93 },
94 required: ["rolloutPath"],
95 },
96 {
97 type: "object",
98 properties: {
99 conversationId: { type: "string" },
100 },
101 required: ["conversationId"],
102 },
103 ],
104 },
105 GetConversationSummaryResponse: {
106 type: "object",
107 title: "GetConversationSummaryResponse",
108 properties: {
109 summary: {},
110 },
111 required: ["summary"],
112 },
113 GitDiffToRemoteParams: {
114 type: "object",
115 title: "GitDiffToRemoteParams",
116 properties: {
117 cwd: { type: "string" },
118 },
119 required: ["cwd"],
120 },
121 GitDiffToRemoteResponse: {
122 type: "object",
123 title: "GitDiffToRemoteResponse",
124 properties: {
125 sha: { type: "string" },
126 diff: { type: "string" },
127 },
128 required: ["sha", "diff"],
129 },
130 GetAuthStatusResponse: {
131 type: "object",
132 title: "GetAuthStatusResponse",
133 properties: {
134 authMethod: {
135 anyOf: [{}, { type: "null" }],
136 },
137 authToken: {
138 anyOf: [{ type: "string" }, { type: "null" }],
139 },
140 requiresOpenaiAuth: {
141 anyOf: [{ type: "boolean" }, { type: "null" }],
142 },
143 },
144 required: ["authMethod", "authToken", "requiresOpenaiAuth"],
145 },
146};
147
148// Codex 0.150 added these multi-agent values before our next full protocol
149// refresh. Keep every generated response namespace compatible with them.
150const Codex0150DefinitionSchemas: Record<string, Schema.Json> = {
151 CollabAgentTool: {
152 type: "string",
153 enum: [
154 "spawnAgent",
155 "sendInput",
156 "resumeAgent",
157 "wait",
158 "closeAgent",
159 "sendMessage",
160 "followupTask",
161 "interruptAgent",
162 "listAgents",
163 ],
164 },
165 CollabAgentToolCallStatus: {
166 type: "string",
167 enum: ["inProgress", "completed", "failed", "interrupted"],
168 },
169 SubAgentActivityKind: {
170 type: "string",
171 enum: ["started", "interacted", "interrupted", "completed"],
172 },
173};
174
175const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
176 const path = yield* Path.Path;
177 const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
178 return {
179 generatedDir,
180 schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
181 metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
182 namespacesOutputPath: path.join(generatedDir, "namespaces.gen.ts"),
183 } satisfies GeneratedPaths;
184});
185
186const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
187 const fs = yield* FileSystem.FileSystem;
188 const { generatedDir } = yield* getGeneratedPaths();
189 yield* fs.makeDirectory(generatedDir, { recursive: true });
190});
191
192const fetchText = Effect.fn("fetchText")(function* (url: string) {
193 return yield* HttpClientRequest.get(url).pipe(
194 HttpClientRequest.setHeader("user-agent", USER_AGENT),
195 HttpClient.execute,
196 Effect.flatMap(HttpClientResponse.filterStatusOk),
197 Effect.flatMap((okResponse) => okResponse.text),
198 Effect.mapError(
199 (cause) =>
200 new GeneratorError({
201 detail: `Failed to fetch ${url}`,
202 cause,
203 }),
204 ),
205 );
206});
207
208const fetchDirectoryEntries = Effect.fn("fetchDirectoryEntries")(function* (path: string) {
209 const raw = yield* fetchText(`${GITHUB_API_BASE}/${path}?ref=${UPSTREAM_REF}`);
210 return yield* decodeGithubContentEntries(raw);
211});
212
213function collectSchemaEntries(
214 chunk: string,
215): ReadonlyArray<{ readonly name: string; readonly code: string }> {
216 const lines = chunk
217 .split("\n")
218 .map((line) => line.trim())
219 .filter((line) => line.length > 0 && !line.startsWith("//"));
220 const entries: Array<{ name: string; code: string }> = [];
221
222 for (let index = 0; index < lines.length; index += 1) {
223 const typeLine = lines[index];
224 if (!typeLine?.startsWith("export type ")) {
225 continue;
226 }
227
228 const constLine = lines[index + 1];
229 if (!constLine?.startsWith("export const ")) {
230 throw new Error(`Malformed generator output near: ${typeLine}`);
231 }
232
233 const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
234 if (!match?.[1]) {
235 throw new Error(`Could not extract schema name from: ${typeLine}`);
236 }
237
238 entries.push({
239 name: match[1],
240 code: `${typeLine}\n${constLine}`,
241 });
242 index += 1;
243 }
244
245 return entries;
246}
247
248function normalizeNullableTypes(value: Schema.Json): Schema.Json {
249 if (Array.isArray(value)) {
250 return value.map(normalizeNullableTypes);
251 }
252 if (value === null || typeof value !== "object") {
253 return value;
254 }
255
256 const normalizedEntries = Object.entries(value).map(([key, child]) => [
257 key,
258 normalizeNullableTypes(child),
259 ]);
260 const normalizedObject = Object.fromEntries(normalizedEntries) as Record<string, Schema.Json>;
261 const typeValue = normalizedObject.type;
262
263 if (!Array.isArray(typeValue)) {
264 return normalizedObject;
265 }
266
267 const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
268 if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
269 return normalizedObject;
270 }
271
272 const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
273 if (nonNullTypes.length !== 1) {
274 return normalizedObject;
275 }
276 const nonNullType = nonNullTypes[0]!;
277
278 const nextObject: Record<string, Schema.Json> = {};
279 for (const [key, child] of Object.entries(normalizedObject)) {
280 if (key !== "type") {
281 nextObject[key] = child;
282 }
283 }
284
285 return {
286 anyOf: [
287 {
288 ...nextObject,
289 type: nonNullType,
290 },
291 { type: "null" },
292 ],
293 };
294}
295
296function stripNullDefaults(value: Schema.Json): Schema.Json {
297 if (Array.isArray(value)) {
298 return value.map(stripNullDefaults);
299 }
300 if (value === null || typeof value !== "object") {
301 return value;
302 }
303
304 return Object.fromEntries(
305 Object.entries(value)
306 .filter(([key, child]) => !(key === "default" && child === null))
307 .map(([key, child]) => [key, stripNullDefaults(child)]),
308 ) as Schema.Json;
309}
310
311function toPascalCaseMethod(method: string) {
312 return method
313 .split("/")
314 .flatMap((segment) => segment.split(/(?=[A-Z])/))
315 .flatMap((segment) => segment.split(/[-_]/))
316 .filter(Boolean)
317 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
318 .join("");
319}
320
321function parseRequestEntries(fileContents: string): ReadonlyArray<MethodEntry> {
322 const entryPattern = /\{\s*"method":\s*"([^"]+)",\s*id:\s*RequestId,\s*params:\s*([^,}]+)/g;
323 const entries: Array<MethodEntry> = [];
324 let match: RegExpExecArray | null;
325 while ((match = entryPattern.exec(fileContents)) !== null) {
326 entries.push({
327 method: match[1]!,
328 paramsType: match[2]!.trim(),
329 });
330 }
331 return entries;
332}
333
334function parseNotificationEntries(fileContents: string): ReadonlyArray<MethodEntry> {
335 const entryPattern = /\{\s*"method":\s*"([^"]+)"(?:,\s*"params":\s*([^ }]+))?\s*\}/g;
336 const entries: Array<MethodEntry> = [];
337 let match: RegExpExecArray | null;
338 while ((match = entryPattern.exec(fileContents)) !== null) {
339 entries.push({
340 method: match[1]!,
341 ...(match[2] ? { paramsType: match[2].trim() } : {}),
342 });
343 }
344 return entries;
345}
346
347function resolveSchemaTypeName(
348 rawTypeName: string,
349 generatedSchemaNames: ReadonlySet<string>,
350): string {
351 if (rawTypeName === "undefined") {
352 return "undefined";
353 }
354
355 const candidates = [
356 rawTypeName,
357 `V2${rawTypeName}`,
358 `V1${rawTypeName}`,
359 `SerdeJson${rawTypeName}`,
360 ];
361 for (const candidate of candidates) {
362 if (generatedSchemaNames.has(candidate)) {
363 return candidate;
364 }
365 }
366
367 throw new Error(`Unable to resolve schema type name: ${rawTypeName}`);
368}
369
370function resolveResponseTypeName(
371 method: string,
372 paramsType: string | undefined,
373 generatedSchemaNames: ReadonlySet<string>,
374): string {
375 const overrides: Record<string, string> = {
376 "account/logout": "LogoutAccountResponse",
377 "account/rateLimits/read": "GetAccountRateLimitsResponse",
378 "account/usage/read": "GetAccountTokenUsageResponse",
379 "account/workspaceMessages/read": "GetWorkspaceMessagesResponse",
380 "config/batchWrite": "ConfigWriteResponse",
381 "config/mcpServer/reload": "McpServerRefreshResponse",
382 "config/value/write": "ConfigWriteResponse",
383 "configRequirements/read": "ConfigRequirementsReadResponse",
384 "externalAgentConfig/import/readHistories": "ExternalAgentConfigImportHistoriesReadResponse",
385 };
386
387 const override = overrides[method];
388 if (override) {
389 return resolveSchemaTypeName(override, generatedSchemaNames);
390 }
391
392 if (paramsType && paramsType !== "undefined") {
393 const fromParams = paramsType.replace(/Params$/, "Response");
394 try {
395 return resolveSchemaTypeName(fromParams, generatedSchemaNames);
396 } catch {
397 // Fall through to method-based lookup.
398 }
399 }
400
401 return resolveSchemaTypeName(`${toPascalCaseMethod(method)}Response`, generatedSchemaNames);
402}
403
404function renderMethodConstants(constantName: string, entries: ReadonlyArray<MethodEntry>) {
405 return [
406 `export const ${constantName} = {`,
407 ...entries.map(
408 (entry) => ` ${JSON.stringify(entry.method)}: ${JSON.stringify(entry.method)},`,
409 ),
410 "} as const;",
411 "",
412 ].join("\n");
413}
414
415function renderTypeInterface(
416 interfaceName: string,
417 entries: ReadonlyArray<MethodEntry>,
418 typeName: (entry: MethodEntry) => string,
419) {
420 return [
421 `export interface ${interfaceName} {`,
422 ...entries.map((entry) => ` readonly ${JSON.stringify(entry.method)}: ${typeName(entry)};`),
423 "}",
424 "",
425 ].join("\n");
426}
427
428function renderSchemaMap(
429 constantName: string,
430 entries: ReadonlyArray<MethodEntry>,
431 typeName: (entry: MethodEntry) => string,
432) {
433 return [
434 `export const ${constantName} = {`,
435 ...entries.map((entry) => {
436 const schemaName = typeName(entry);
437 return ` ${JSON.stringify(entry.method)}: ${
438 schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`
439 },`;
440 }),
441 "} as const;",
442 "",
443 ].join("\n");
444}
445
446function renderSchemaTypeReference(schemaName: string) {
447 return schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`;
448}
449
450function exportNameForPath(filePath: string): string {
451 const relative = filePath.replace(/^schema\/json\//, "").replace(/\.json$/, "");
452 if (!relative.includes("/")) {
453 return relative;
454 }
455
456 const [namespace, name] = relative.split("/", 2) as [string, string];
457 const namespacePrefix = namespace
458 .split(/[^A-Za-z0-9]+/)
459 .filter(Boolean)
460 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
461 .join("");
462 return `${namespacePrefix}${name}`;
463}
464
465function buildJsonSchemaFiles(
466 entries: ReadonlyArray<GithubContentEntry>,
467): ReadonlyArray<JsonSchemaFile> {
468 return entries
469 .filter(
470 (entry) =>
471 entry.type === "file" &&
472 entry.name.endsWith(".json") &&
473 entry.download_url !== null &&
474 !entry.name.startsWith("codex_app_server_protocol."),
475 )
476 .map((entry) => {
477 const relative = entry.path.replace(/^codex-rs\/app-server-protocol\/schema\/json\//, "");
478 const parts = relative.split("/");
479 if (parts.length > 1) {
480 return {
481 namespace: parts[0]!,
482 exportName: exportNameForPath(relative),
483 fileName: entry.name,
484 downloadUrl: entry.download_url!,
485 qualifiedName: relative.replace(/\.json$/, ""),
486 } satisfies JsonSchemaFile;
487 }
488 return {
489 exportName: exportNameForPath(relative),
490 fileName: entry.name,
491 downloadUrl: entry.download_url!,
492 qualifiedName: relative.replace(/\.json$/, ""),
493 } satisfies JsonSchemaFile;
494 });
495}
496
497function rewriteExternalRefs(
498 value: Schema.Json,
499 localDefinitionNames: ReadonlyMap<string, string>,
500 currentNamespace: string | undefined,
501 exportNameByQualifiedName: ReadonlyMap<string, string>,
502): Schema.Json {
503 if (Array.isArray(value)) {
504 return value.map((entry) =>
505 rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName),
506 );
507 }
508 if (value === null || typeof value !== "object") {
509 return value;
510 }
511
512 return Object.fromEntries(
513 Object.entries(value).map(([key, child]) => {
514 if (key === "$ref" && typeof child === "string" && child.startsWith("#/definitions/")) {
515 const definitionName = child.slice("#/definitions/".length);
516 const localRewrite = localDefinitionNames.get(definitionName);
517 if (localRewrite) {
518 return [key, `#/definitions/${localRewrite}`];
519 }
520
521 const candidates = [
522 ...(currentNamespace ? [`${currentNamespace}/${definitionName}`] : []),
523 definitionName,
524 definitionName.replace(/^v[12]\//, ""),
525 definitionName.replace(/^serde_json\//, ""),
526 `v2/${definitionName}`,
527 `v1/${definitionName}`,
528 `serde_json/${definitionName}`,
529 ];
530
531 const rewritten = candidates
532 .map((candidate) => exportNameByQualifiedName.get(candidate))
533 .find((candidate) => candidate !== undefined);
534
535 if (!rewritten) {
536 throw new Error(`Missing rewritten definition for ref: ${child}`);
537 }
538
539 return [key, `#/definitions/${rewritten}`];
540 }
541
542 return [
543 key,
544 rewriteExternalRefs(
545 child,
546 localDefinitionNames,
547 currentNamespace,
548 exportNameByQualifiedName,
549 ),
550 ];
551 }),
552 ) as Schema.Json;
553}
554
555const generateFiles = Effect.fn("generateFiles")(function* () {
556 yield* ensureGeneratedDir();
557
558 const [rootJsonEntries, v1JsonEntries, v2JsonEntries] = yield* Effect.all([
559 fetchDirectoryEntries("schema/json"),
560 fetchDirectoryEntries("schema/json/v1"),
561 fetchDirectoryEntries("schema/json/v2"),
562 ]);
563
564 const jsonSchemaFiles = [
565 ...buildJsonSchemaFiles(rootJsonEntries),
566 ...buildJsonSchemaFiles(v1JsonEntries),
567 ...buildJsonSchemaFiles(v2JsonEntries),
568 ].toSorted((left, right) => left.exportName.localeCompare(right.exportName));
569
570 const exportNameByQualifiedName = new Map(
571 jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]),
572 );
573 const aggregateSchemas: Record<string, Schema.Json> = {};
574
575 for (const file of jsonSchemaFiles) {
576 const raw = yield* fetchText(file.downloadUrl);
577 const parsed = yield* decodeJsonSchemaDocument(raw);
578 const localDefinitionNames = new Map(
579 Object.keys(parsed.definitions ?? {}).map((definitionName) => [
580 definitionName,
581 `${file.exportName}__${definitionName.replace(/[^A-Za-z0-9]/g, "")}`,
582 ]),
583 );
584
585 for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) {
586 const compatibleDefinitionSchema =
587 Codex0150DefinitionSchemas[definitionName] ?? definitionSchema;
588 aggregateSchemas[localDefinitionNames.get(definitionName)!] = stripNullDefaults(
589 normalizeNullableTypes(
590 rewriteExternalRefs(
591 compatibleDefinitionSchema,
592 localDefinitionNames,
593 file.namespace,
594 exportNameByQualifiedName,
595 ),
596 ),
597 );
598 }
599
600 const topLevelSchema: Record<string, Schema.Json> = {};
601 for (const [key, value] of Object.entries(parsed)) {
602 if (key !== "definitions") {
603 topLevelSchema[key] = value;
604 }
605 }
606
607 aggregateSchemas[file.exportName] = stripNullDefaults(
608 normalizeNullableTypes(
609 rewriteExternalRefs(
610 topLevelSchema,
611 localDefinitionNames,
612 file.namespace,
613 exportNameByQualifiedName,
614 ),
615 ),
616 );
617 }
618
619 for (const [name, schema] of Object.entries(ManualSchemas)) {
620 if (!(name in aggregateSchemas)) {
621 aggregateSchemas[name] = stripNullDefaults(normalizeNullableTypes(schema));
622 }
623 }
624
625 const generator = makeJsonSchemaGenerator();
626 for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) =>
627 left.localeCompare(right),
628 )) {
629 generator.addSchema(name, schema as never);
630 }
631
632 const generatedEntries = new Map<string, string>();
633 const output = generator.generate("openapi-3.1", aggregateSchemas as never, false).trim();
634 if (output.length > 0) {
635 for (const entry of collectSchemaEntries(output)) {
636 if (!generatedEntries.has(entry.name)) {
637 generatedEntries.set(entry.name, entry.code);
638 }
639 }
640 }
641
642 const generatedSchemaNames = new Set(generatedEntries.keys());
643 const clientRequestRaw = yield* fetchText(
644 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts`,
645 );
646 const clientNotificationRaw = yield* fetchText(
647 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientNotification.ts`,
648 );
649 const serverRequestRaw = yield* fetchText(
650 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts`,
651 );
652 const serverNotificationRaw = yield* fetchText(
653 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`,
654 );
655
656 const clientRequestEntries = parseRequestEntries(clientRequestRaw);
657 const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw);
658 const serverRequestEntries = parseRequestEntries(serverRequestRaw);
659 const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw);
660
661 const prelude = [
662 "// This file is generated by the effect-codex-app-server package. Do not edit manually.",
663 `// Upstream protocol ref: ${UPSTREAM_REF}`,
664 "",
665 ];
666
667 const schemaOutput = [
668 ...prelude,
669 'import * as Schema from "effect/Schema";',
670 "",
671 [...generatedEntries.values()].join("\n\n"),
672 "",
673 ].join("\n");
674
675 const metaOutput = [
676 ...prelude,
677 'import * as CodexSchema from "./schema.gen.ts";',
678 "",
679 renderMethodConstants("CLIENT_REQUEST_METHODS", clientRequestEntries),
680 renderMethodConstants("CLIENT_NOTIFICATION_METHODS", clientNotificationEntries),
681 renderMethodConstants("SERVER_REQUEST_METHODS", serverRequestEntries),
682 renderMethodConstants("SERVER_NOTIFICATION_METHODS", serverNotificationEntries),
683 "export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;",
684 "export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;",
685 "export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;",
686 "export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;",
687 "",
688 renderTypeInterface("ClientRequestParamsByMethod", clientRequestEntries, (entry) =>
689 renderSchemaTypeReference(
690 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
691 ),
692 ),
693 renderTypeInterface("ClientRequestResponsesByMethod", clientRequestEntries, (entry) =>
694 renderSchemaTypeReference(
695 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
696 ),
697 ),
698 renderTypeInterface("ClientNotificationParamsByMethod", clientNotificationEntries, (entry) =>
699 renderSchemaTypeReference(
700 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
701 ),
702 ),
703 renderTypeInterface("ServerRequestParamsByMethod", serverRequestEntries, (entry) =>
704 renderSchemaTypeReference(
705 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
706 ),
707 ),
708 renderTypeInterface("ServerRequestResponsesByMethod", serverRequestEntries, (entry) =>
709 renderSchemaTypeReference(
710 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
711 ),
712 ),
713 renderTypeInterface("ServerNotificationParamsByMethod", serverNotificationEntries, (entry) =>
714 renderSchemaTypeReference(
715 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
716 ),
717 ),
718 renderSchemaMap("CLIENT_REQUEST_PARAMS", clientRequestEntries, (entry) =>
719 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
720 ),
721 renderSchemaMap("CLIENT_REQUEST_RESPONSES", clientRequestEntries, (entry) =>
722 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
723 ),
724 renderSchemaMap("CLIENT_NOTIFICATION_PARAMS", clientNotificationEntries, (entry) =>
725 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
726 ),
727 renderSchemaMap("SERVER_REQUEST_PARAMS", serverRequestEntries, (entry) =>
728 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
729 ),
730 renderSchemaMap("SERVER_REQUEST_RESPONSES", serverRequestEntries, (entry) =>
731 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
732 ),
733 renderSchemaMap("SERVER_NOTIFICATION_PARAMS", serverNotificationEntries, (entry) =>
734 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
735 ),
736 ].join("\n");
737
738 const namespaceGroups = new Map<string, Array<JsonSchemaFile>>();
739 for (const file of jsonSchemaFiles) {
740 if (!file.namespace) {
741 continue;
742 }
743 const current = namespaceGroups.get(file.namespace) ?? [];
744 current.push(file);
745 namespaceGroups.set(file.namespace, current);
746 }
747
748 const namespacesOutput = [
749 ...prelude,
750 'import * as CodexSchema from "./schema.gen.ts";',
751 "",
752 ...[...namespaceGroups.entries()]
753 .toSorted(([left], [right]) => left.localeCompare(right))
754 .map(([namespace, files]) => {
755 const constantName = namespace.replace(/[^A-Za-z0-9]/g, "");
756 return [
757 `export const ${constantName} = {`,
758 ...files
759 .toSorted((left, right) => left.fileName.localeCompare(right.fileName))
760 .map(
761 (file) =>
762 ` ${JSON.stringify(file.fileName.replace(/\.json$/, ""))}: CodexSchema.${file.exportName},`,
763 ),
764 "} as const;",
765 "",
766 ].join("\n");
767 }),
768 ].join("\n");
769
770 const fs = yield* FileSystem.FileSystem;
771 const { generatedDir, metaOutputPath, namespacesOutputPath, schemaOutputPath } =
772 yield* getGeneratedPaths();
773 yield* fs.writeFileString(schemaOutputPath, schemaOutput);
774 yield* fs.writeFileString(metaOutputPath, metaOutput);
775 yield* fs.writeFileString(namespacesOutputPath, namespacesOutput);
776
777 yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
778
779 yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
780 Effect.flatMap((spawner) =>
781 spawner.spawn(ChildProcess.make("vp", ["fmt", generatedDir, "--write"])),
782 ),
783 Effect.flatMap((child) => child.exitCode),
784 Effect.tap((code) =>
785 code === 0
786 ? Effect.void
787 : Effect.fail(
788 new GeneratorError({
789 detail: `vp fmt failed with exit code ${code}`,
790 }),
791 ),
792 ),
793 );
794});
795
796generateFiles().pipe(
797 Effect.scoped,
798 Effect.provide(
799 Layer.mergeAll(
800 Logger.layer([Logger.consolePretty()]),
801 NodeServices.layer,
802 FetchHttpClient.layer,
803 ),
804 ),
805 NodeRuntime.runMain,
806);