Files
hose-use/src/cli/commands/openapi.ts
T

118 lines
3.3 KiB
TypeScript

import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../packaging/embedded-openapi.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printKeyValue, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { handleKeysCommand } from "./keys.js";
export async function handleOpenApiCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action?.toLowerCase();
if (action === "keys" || action === "key") {
return handleKeysCommand(parsed, runtime);
}
const isRaw =
booleanOption(parsed.options, ["raw"]) ||
parsed.action === "raw" ||
parsed.args[0] === "raw";
const type: OpenApiType = isRaw ? "raw" : "wrapped";
switch (action) {
case "paths":
case "list":
case "ls": {
const paths = listOpenApiPaths(type);
if (runtime.jsonMode) {
return {
stdout: printJson({ type, count: paths.length, paths }),
stderr: "",
exitCode: 0,
};
}
const rows = paths.map((p) => [
p.method,
p.path,
p.summary || "-",
p.tags.join(", ") || "-",
]);
const table = printTable(["Method", "Path", "Summary", "Tags"], rows);
const title = isRaw
? "====== 合思/易快报 原生下游 OpenAPI 接口列表 ======"
: "====== hose-use 包装层 OpenAPI 接口列表 ======";
return {
stdout: `${title}\n\n${table}\n\n提示: 运行 hose-use openapi ${isRaw ? "--raw " : ""}可直接输出完整 OpenAPI 3.1.0 JSON\n`,
stderr: "",
exitCode: 0,
};
}
case "info":
case "summary": {
const schema = getOpenApiSchema(type);
const info = (schema.info as Record<string, unknown>) || {};
const servers = ((schema.servers as Array<{ url: string; description?: string }>) || []).map(
(s) => `${s.url} (${s.description || "-"})`
);
const tags = ((schema.tags as Array<{ name: string; description?: string }>) || []).map(
(t) => `${t.name}: ${t.description || ""}`
);
const paths = listOpenApiPaths(type);
const infoObj = {
title: info.title,
version: info.version,
description: info.description,
type,
totalEndpoints: paths.length,
servers,
tags,
};
if (runtime.jsonMode) {
return {
stdout: printJson(infoObj),
stderr: "",
exitCode: 0,
};
}
const out = printKeyValue({
"规范标题": info.title,
"规范版本": info.version,
"规范类型": isRaw ? "原始下游原生 API (Raw Spec)" : "包装层工具 API (Wrapped Spec)",
"接口总数": paths.length,
"描述信息": info.description,
"服务器列表": servers.join("\n "),
"标签分组": tags.join("\n "),
});
return {
stdout: `====== OpenAPI 规范概览 ======\n${out}\n`,
stderr: "",
exitCode: 0,
};
}
case "dump":
case "export":
case "raw":
case undefined:
default: {
const schema = getOpenApiSchema(type);
return {
stdout: `${JSON.stringify(schema, null, 2)}\n`,
stderr: "",
exitCode: 0,
};
}
}
}