chore(cli-rs): format the API generator and type the oracle's fetch

Prettier over script/gen/api.ts and script/rust; the oracle's fake fetch no
longer casts to typeof fetch, so bun check passes. Output is unchanged.
This commit is contained in:
Simon Klee 2026-11-04 18:19:43 +01:00
parent b826557733
commit 0f63e545d7
No known key found for this signature in database
GPG key ID: B91696044D47BEA3
4 changed files with 84 additions and 33 deletions

View file

@ -18,19 +18,22 @@ let current = ""
const client = make({
baseUrl: "http://127.0.0.1:4096/prefix",
headers: { authorization: "Basic b3BlbmNvZGU6c2VjcmV0" },
fetch: (async (url: URL, init: RequestInit) => {
const headers = Object.fromEntries(new Headers(init.headers))
const body = init.body
recorded.push({
name: current,
method: init.method ?? "GET",
url: String(url),
headers,
...(typeof body === "string" ? { body } : {}),
...(body instanceof Uint8Array ? { bodyBase64: Buffer.from(body).toString("base64") } : {}),
})
throw new Error("recorded")
}) as typeof fetch,
fetch: Object.assign(
async (url: RequestInfo | URL, init: RequestInit = {}): Promise<Response> => {
const headers = Object.fromEntries(new Headers(init.headers))
const body = init.body
recorded.push({
name: current,
method: init.method ?? "GET",
url: String(url),
headers,
...(typeof body === "string" ? { body } : {}),
...(body instanceof Uint8Array ? { bodyBase64: Buffer.from(body).toString("base64") } : {}),
})
throw new Error("recorded")
},
{ preconnect: fetch.preconnect },
),
})
const call = async (name: string, run: () => Promise<unknown> | AsyncIterable<unknown>) => {

View file

@ -25,24 +25,39 @@ const add = (ast: SchemaAST.AST) => {
const plans = contract.groups.flatMap((group) =>
group.endpoints.map((endpoint) => {
const opaque = endpoint.payloads[0] !== undefined && !flattenable(endpoint.payloads[0])
const binaryBody = endpoint.payloads[0] !== undefined && resolveEncoding(endpoint.payloads[0].ast)?._tag === "Uint8Array"
const sources = { params: endpoint.params, query: endpoint.query, headers: endpoint.headers, payload: endpoint.payloads[0] }
const binaryBody =
endpoint.payloads[0] !== undefined && resolveEncoding(endpoint.payloads[0].ast)?._tag === "Uint8Array"
const sources = {
params: endpoint.params,
query: endpoint.query,
headers: endpoint.headers,
payload: endpoint.payloads[0],
}
const fields = endpoint.input.map((field) => {
const schema = sources[field.source]!
if (opaque && field.source === "payload") return { ...field, root: binaryBody ? undefined : add(Schema.toEncoded(schema).ast) }
if (opaque && field.source === "payload")
return { ...field, root: binaryBody ? undefined : add(Schema.toEncoded(schema).ast) }
const ast = (field.source === "query" ? Schema.toType(schema) : Schema.toEncoded(schema)).ast
if (!SchemaAST.isObjects(ast)) throw new Error(`Input schema must be a struct: ${endpoint.operation.name}`)
const property = ast.propertySignatures.find((item) => item.name === field.name)!
return { ...field, root: add(property.type) }
})
const wildcard = endpoint.endpoint.path.endsWith("*")
? [{ name: endpoint.input.some((field) => field.name === "path") ? "wildcard" : "path", source: "wildcard" as const, optional: false, root: undefined }]
? [
{
name: endpoint.input.some((field) => field.name === "path") ? "wildcard" : "path",
source: "wildcard" as const,
optional: false,
root: undefined,
},
]
: []
const success = endpoint.successes[0]
const kind = streamKind(success)
const output = (() => {
if (kind === "sse") return add(sseData(success))
if (HttpApiSchema.isNoContent(success.ast) || resolveEncoding(success.ast)?._tag === "Uint8Array") return undefined
if (HttpApiSchema.isNoContent(success.ast) || resolveEncoding(success.ast)?._tag === "Uint8Array")
return undefined
const ast = Schema.toEncoded(success).ast
if (!endpoint.unwrapData) return add(ast)
if (!SchemaAST.isObjects(ast)) throw new Error(`Invalid data envelope: ${endpoint.operation.name}`)
@ -108,7 +123,10 @@ await Bun.write(
`${directory}/mod.rs`,
`${header}//! Types and methods generated from \`ClientApi\` by \`script/gen/api.ts\` (F.2).\n\nmod methods;\npub mod types;\n\npub use types::*;\n\n/// Endpoints in the generated client.\npub const ENDPOINTS: usize = ${plans.length};\n`,
)
const format = Bun.spawnSync(["rustfmt", "--edition", "2024", `${directory}/mod.rs`], { stdout: "inherit", stderr: "inherit" })
const format = Bun.spawnSync(["rustfmt", "--edition", "2024", `${directory}/mod.rs`], {
stdout: "inherit",
stderr: "inherit",
})
if (format.exitCode !== 0) process.exit(format.exitCode ?? 1)
console.log(`api: ${plans.length} endpoints, ${types.items.length} items`)
@ -130,7 +148,10 @@ function sseData(schema: Endpoint["successes"][number]) {
if (!SchemaAST.isObjects(events)) throw new Error("Invalid SSE data schema")
const data = events.propertySignatures.find((field) => field.name === "data")!.type
// oxlint-disable-next-line no-restricted-globals -- Effect exposes this runtime helper without a public type.
const replaceEncoding = Reflect.get(SchemaAST, "replaceEncoding") as (ast: SchemaAST.AST, encoding: undefined) => SchemaAST.AST
const replaceEncoding = Reflect.get(SchemaAST, "replaceEncoding") as (
ast: SchemaAST.AST,
encoding: undefined,
) => SchemaAST.AST
return Schema.toEncoded(Schema.make<Schema.Top>(replaceEncoding(data, undefined))).ast
}
@ -160,7 +181,12 @@ function normalize(input: ReadonlyArray<SchemaAST.AST>) {
const step = (ast: SchemaAST.AST): SchemaAST.AST => {
if (SchemaAST.isDeclaration(ast) && ast.annotations?.toCode === undefined) {
const representation = ast.annotations?.representation
if (typeof representation === "object" && representation !== null && "id" in representation && representation.id === "effect/schema/Json") {
if (
typeof representation === "object" &&
representation !== null &&
"id" in representation &&
representation.id === "effect/schema/Json"
) {
return Schema.Json.ast
}
if (ast.annotations?.["~constructor"] !== undefined && ast.typeParameters[0] !== undefined) {

View file

@ -24,7 +24,9 @@ export type Method = {
}
export function emitMethod(types: Types, method: Method) {
const name = snake([...method.group.path, ...method.endpoint.clientPath].map((part) => snake(part).replace(/^r#/, "")).join("_"))
const name = snake(
[...method.group.path, ...method.endpoint.clientPath].map((part) => snake(part).replace(/^r#/, "")).join("_"),
)
const idents = new Map<Field, string>()
for (const field of method.fields) {
let ident = snake(field.name)
@ -81,7 +83,8 @@ export function emitMethod(types: Types, method: Method) {
: `call.field(${JSON.stringify(field.name)}, VALUE)?;`
: undefined
if (call === undefined) return []
if (field.optional) return [`if let Some(value) = &${access(field)} {\n ${call.replace("VALUE", "value")}\n }`]
if (field.optional)
return [`if let Some(value) = &${access(field)} {\n ${call.replace("VALUE", "value")}\n }`]
return [call.replace("VALUE", `&${access(field)}`)]
})
if (method.endpoint.payloads.length > 0 && !method.binaryBody && !method.opaque) statements.unshift("call.object();")

View file

@ -90,7 +90,8 @@ export class Types {
return "()"
case "Objects":
// An empty object says nothing about its role, so it keeps its own name instead of sharing one.
if (r.propertySignatures.length === 0 && r.indexSignatures.length === 0) return this.objects(r, this.name(hint), hint)
if (r.propertySignatures.length === 0 && r.indexSignatures.length === 0)
return this.objects(r, this.name(hint), hint)
return this.shaped(r, () => this.objects(r, this.name(hint), hint))
case "Arrays":
return this.arrays(r, hint)
@ -207,7 +208,7 @@ export class Types {
if (optional && nullable) {
return {
type: `Option<Option<${inner}>>`,
attrs: ['default', 'deserialize_with = "crate::de::double_option"', 'skip_serializing_if = "Option::is_none"'],
attrs: ["default", 'deserialize_with = "crate::de::double_option"', 'skip_serializing_if = "Option::is_none"'],
}
}
if (optional) return { type: `Option<${inner}>`, attrs: ["default", 'skip_serializing_if = "Option::is_none"'] }
@ -217,7 +218,9 @@ export class Types {
/** A union. `ref` names the reference it defines, if any. */
union(r: SchemaRepresentation.Union, hint: string, ref: string | undefined): string {
const members = flatten(r.types).filter((member) => !["Undefined", "Never", "Void"].includes(this.deref(member)._tag))
const members = flatten(r.types).filter(
(member) => !["Undefined", "Never", "Void"].includes(this.deref(member)._tag),
)
const nullable = members.some((member) => this.deref(member)._tag === "Null")
const rest = members.filter((member) => this.deref(member)._tag !== "Null")
const wrap = (type: string) => (nullable ? `Option<${type}>` : type)
@ -234,7 +237,8 @@ export class Types {
return wrap(values.every(Number.isInteger) ? "i64" : "f64")
return wrap("serde_json::Value")
}
if (resolved.every((member) => ["Literal", "String", "TemplateLiteral"].includes(member._tag))) return wrap("String")
if (resolved.every((member) => ["Literal", "String", "TemplateLiteral"].includes(member._tag)))
return wrap("String")
if (resolved.every((member) => member._tag === "Objects")) {
const tagged = this.discriminator(resolved as Array<Objects>)
if (tagged !== undefined) return wrap(this.tagged(rest, tagged, ref ?? hint, ref))
@ -260,7 +264,10 @@ export class Types {
return this.tagValues(property.type)
}
const keys = members[0].propertySignatures.map((p) => String(p.name))
const ordered = [...keys.filter((key) => key === "type" || key === "_tag"), ...keys.filter((key) => key !== "type" && key !== "_tag")]
const ordered = [
...keys.filter((key) => key === "type" || key === "_tag"),
...keys.filter((key) => key !== "type" && key !== "_tag"),
]
for (const key of ordered) {
const values = members.map((member) => tags(member, key))
if (values.some((value) => value === undefined)) continue
@ -319,13 +326,18 @@ export class Types {
const arms = tag.values.flatMap((value, index) => [
...(value.exact.length === 0
? []
: [` ${value.exact.map((item) => `Some(${JSON.stringify(item)})`).join(" | ")} => crate::de::variant(value).map(Self::${variants[index]}),`]),
: [
` ${value.exact.map((item) => `Some(${JSON.stringify(item)})`).join(" | ")} => crate::de::variant(value).map(Self::${variants[index]}),`,
]),
...value.prefixes.map(
(prefix) =>
` Some(tag) if tag.starts_with(${JSON.stringify(prefix)}) => crate::de::variant(value).map(Self::${variants[index]}),`,
),
])
const ordered = [...arms.filter((arm) => !arm.includes("starts_with")), ...arms.filter((arm) => arm.includes("starts_with"))]
const ordered = [
...arms.filter((arm) => !arm.includes("starts_with")),
...arms.filter((arm) => arm.includes("starts_with")),
]
const tagMethod =
kind === "boolean"
? ""
@ -351,9 +363,16 @@ export class Types {
: typeof resolved.literal === "boolean"
? "Bool"
: "Number"
: ({ String: "String", TemplateLiteral: "String", Boolean: "Bool", Number: "Number", Arrays: "Array", Objects: "Object" } as Record<string, string>)[
resolved._tag
] ?? "Value"
: ((
{
String: "String",
TemplateLiteral: "String",
Boolean: "Bool",
Number: "Number",
Arrays: "Array",
Objects: "Object",
} as Record<string, string>
)[resolved._tag] ?? "Value")
const type =
resolved._tag === "Literal"
? typeof resolved.literal === "string"