feat: complete TASK-WP0-03 browser gate

This commit is contained in:
suyx
2026-07-27 18:23:20 +08:00
parent dbe3e73b91
commit 878788b1e2
25 changed files with 3227 additions and 21 deletions
+13 -1
View File
@@ -40,6 +40,11 @@ function operationResult(operation) {
return response.schema ? schemaType(response.schema) : "unknown";
}
function operationBodyType(operation) {
const schema = operation.requestBody?.content?.["application/json"]?.schema;
return schema ? schemaType(schema) : undefined;
}
function operationMediaType(operation) {
const content = operation.responses?.["200"]?.content;
if (!content) return undefined;
@@ -68,16 +73,23 @@ export function generateClient(input, output) {
].join("\n\n");
const operationList = operations(document);
const importedTypes = [...new Set(operationList.map(({ operation }) => operationResult(operation)).filter((type) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(type)))];
const importedTypes = [...new Set(operationList.flatMap(({ operation }) => [
operationResult(operation),
operationBodyType(operation),
]).filter((type) => type && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(type)))];
const sdk = [
"// Generated from openapi/openapi.json. Do not edit by hand.",
importedTypes.length ? `import type { ${importedTypes.join(", ")} } from "./types.gen.js";` : "",
"export interface ClientOptions { baseUrl?: string; fetch?: typeof globalThis.fetch; headers?: HeadersInit; }",
...operationList.map(({ method, operation, path }) => {
const resultType = operationResult(operation);
const bodyType = operationBodyType(operation);
if (operationMediaType(operation) === "text/event-stream") {
return `export function ${identifier(operation.operationId)}(options: Pick<ClientOptions, "baseUrl"> = {}): string {\n return \`${"${options.baseUrl ?? \"\"}"}${path}\`;\n}`;
}
if (bodyType) {
return `export async function ${identifier(operation.operationId)}(body: ${bodyType}, options: ClientOptions = {}): Promise<${resultType}> {\n const request = options.fetch ?? globalThis.fetch;\n const headers = new Headers(options.headers);\n headers.set("Content-Type", "application/json");\n const response = await request(\`${"${options.baseUrl ?? \"\"}"}${path}\`, { body: JSON.stringify(body), method: "${method.toUpperCase()}", headers });\n if (!response.ok) throw new Error(\`HTTP ${"${response.status}"}\`);\n return response.json() as Promise<${resultType}>;\n}`;
}
return `export async function ${identifier(operation.operationId)}(options: ClientOptions = {}): Promise<${resultType}> {\n const request = options.fetch ?? globalThis.fetch;\n const response = await request(\`${"${options.baseUrl ?? \"\"}"}${path}\`, { method: "${method.toUpperCase()}", headers: options.headers ?? {} });\n if (!response.ok) throw new Error(\`HTTP ${"${response.status}"}\`);\n return response.json() as Promise<${resultType}>;\n}`;
}),
"",