@donghanh/hono 0.3.0 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/gpt.test.ts +51 -0
- package/src/gpt.ts +10 -0
- package/src/index.ts +6 -0
- package/src/openapi.test.ts +268 -0
- package/src/openapi.ts +384 -0
package/package.json
CHANGED
package/src/gpt.test.ts
CHANGED
|
@@ -69,6 +69,57 @@ async function req(
|
|
|
69
69
|
return { status: res.status, body };
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
describe("gptRoutes /operations/:name detail", () => {
|
|
73
|
+
test("by default returns only the op detail", async () => {
|
|
74
|
+
const app = gptRoutes({
|
|
75
|
+
registry: makeApp({
|
|
76
|
+
a: makeOp("a"),
|
|
77
|
+
b: makeOp("b"),
|
|
78
|
+
}),
|
|
79
|
+
executor: (async () => ({})) as Executor,
|
|
80
|
+
authenticate: async () => ({ userId: "x" }),
|
|
81
|
+
});
|
|
82
|
+
const { status, body } = await req(app, "/operations/a");
|
|
83
|
+
expect(status).toBe(200);
|
|
84
|
+
expect((body as { id: string }).id).toBe("a");
|
|
85
|
+
expect((body as { operations?: unknown }).operations).toBeUndefined();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("includeOperationsInDetail appends siblings list", async () => {
|
|
89
|
+
const app = gptRoutes({
|
|
90
|
+
registry: makeApp({
|
|
91
|
+
a: makeOp("a", { auth: "required" }),
|
|
92
|
+
b: makeOp("b", { auth: "none" }),
|
|
93
|
+
c: makeOp("c", { auth: "optional" }),
|
|
94
|
+
}),
|
|
95
|
+
executor: (async () => ({})) as Executor,
|
|
96
|
+
authenticate: async () => ({ userId: "x" }),
|
|
97
|
+
includeOperationsInDetail: true,
|
|
98
|
+
});
|
|
99
|
+
const { body } = await req(app, "/operations/a");
|
|
100
|
+
const b = body as {
|
|
101
|
+
id: string;
|
|
102
|
+
operations: Array<{
|
|
103
|
+
id: string;
|
|
104
|
+
type: string;
|
|
105
|
+
auth?: string;
|
|
106
|
+
description: string;
|
|
107
|
+
}>;
|
|
108
|
+
};
|
|
109
|
+
expect(b.id).toBe("a");
|
|
110
|
+
expect(b.operations).toHaveLength(3);
|
|
111
|
+
// Each entry has name, auth (when set), description, type
|
|
112
|
+
const byId = Object.fromEntries(b.operations.map((o) => [o.id, o]));
|
|
113
|
+
expect(byId.a.auth).toBe("required");
|
|
114
|
+
expect(byId.b.auth).toBe("none");
|
|
115
|
+
expect(byId.c.auth).toBe("optional");
|
|
116
|
+
for (const o of b.operations) {
|
|
117
|
+
expect(typeof o.description).toBe("string");
|
|
118
|
+
expect(typeof o.type).toBe("string");
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
72
123
|
describe("gptRoutes /operations listing", () => {
|
|
73
124
|
test("includes auth for each op when set", async () => {
|
|
74
125
|
const registry = makeApp({
|
package/src/gpt.ts
CHANGED
|
@@ -11,6 +11,12 @@ export interface GptRoutesConfig {
|
|
|
11
11
|
authenticate: Authenticate;
|
|
12
12
|
encodeVariables?: (vars: Record<string, unknown>) => string;
|
|
13
13
|
responseSchemas?: Record<string, object>;
|
|
14
|
+
/**
|
|
15
|
+
* Include the compact operations list in `GET /operations/:name` responses
|
|
16
|
+
* so the model sees siblings when inspecting a single op. Default `false` —
|
|
17
|
+
* opt in when you want detail lookups to be self-sufficient.
|
|
18
|
+
*/
|
|
19
|
+
includeOperationsInDetail?: boolean;
|
|
14
20
|
/** Hook to enrich the JSON response (e.g. inject display text) */
|
|
15
21
|
enrichResponse?: (
|
|
16
22
|
result: Record<string, unknown>,
|
|
@@ -44,6 +50,7 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
44
50
|
encodeVariables,
|
|
45
51
|
responseSchemas,
|
|
46
52
|
enrichResponse,
|
|
53
|
+
includeOperationsInDetail,
|
|
47
54
|
} = config;
|
|
48
55
|
|
|
49
56
|
const app = new Hono();
|
|
@@ -86,6 +93,9 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
86
93
|
);
|
|
87
94
|
}
|
|
88
95
|
|
|
96
|
+
if (includeOperationsInDetail) {
|
|
97
|
+
return c.json({ ...detail, operations: registry.list() });
|
|
98
|
+
}
|
|
89
99
|
return c.json(detail);
|
|
90
100
|
});
|
|
91
101
|
|
package/src/index.ts
CHANGED
|
@@ -6,6 +6,12 @@ export type { McpRoutesConfig, WidgetConfig } from "./mcp";
|
|
|
6
6
|
export { mcpRoutes } from "./mcp";
|
|
7
7
|
export type { AuthError, Authenticate, AuthResult } from "./middleware";
|
|
8
8
|
export { isAuthError } from "./middleware";
|
|
9
|
+
export type {
|
|
10
|
+
GenerateOpenApiConfig,
|
|
11
|
+
OpenApiInfo,
|
|
12
|
+
OpenApiServer,
|
|
13
|
+
} from "./openapi";
|
|
14
|
+
export { generateOpenApi } from "./openapi";
|
|
9
15
|
export type { ChatGptResult, SuggestedAction } from "./renderers/chatgpt";
|
|
10
16
|
export { renderForChatGpt } from "./renderers/chatgpt";
|
|
11
17
|
export type { LlmAction, LlmResult } from "./renderers/llm";
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import type { OperationComponent, OperationConfig } from "@donghanh/core";
|
|
3
|
+
import { App, Brief, buildRegistry, Message } from "@donghanh/core";
|
|
4
|
+
import { generateOpenApi } from "./openapi";
|
|
5
|
+
|
|
6
|
+
function makeOp(
|
|
7
|
+
id: string,
|
|
8
|
+
overrides: Partial<OperationConfig> = {},
|
|
9
|
+
): OperationComponent {
|
|
10
|
+
const op = ((_p: { data: unknown }) =>
|
|
11
|
+
Brief({
|
|
12
|
+
children: [Message({ children: "ok" })],
|
|
13
|
+
})) as unknown as OperationComponent;
|
|
14
|
+
op.operationConfig = {
|
|
15
|
+
id,
|
|
16
|
+
type: "query",
|
|
17
|
+
description: `${id} desc`,
|
|
18
|
+
instruction: `call ${id}`,
|
|
19
|
+
input: { type: "object", properties: {} },
|
|
20
|
+
responseKey: id,
|
|
21
|
+
...overrides,
|
|
22
|
+
};
|
|
23
|
+
return op;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function registry(ops: Record<string, OperationComponent>) {
|
|
27
|
+
return buildRegistry(App({ operations: ops }));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const info = { title: "Test API", version: "1.0.0" };
|
|
31
|
+
const servers = [{ url: "https://api.example.com" }];
|
|
32
|
+
const basePath = "/api/gpt";
|
|
33
|
+
|
|
34
|
+
describe("generateOpenApi common", () => {
|
|
35
|
+
test("emits 3.1.0 spec with info + servers + bearerAuth + empty schemas", () => {
|
|
36
|
+
const spec = generateOpenApi({
|
|
37
|
+
registry: registry({ a: makeOp("a") }),
|
|
38
|
+
info,
|
|
39
|
+
servers,
|
|
40
|
+
basePath,
|
|
41
|
+
}) as any;
|
|
42
|
+
expect(spec.openapi).toBe("3.1.0");
|
|
43
|
+
expect(spec.info).toEqual(info);
|
|
44
|
+
expect(spec.servers).toEqual(servers);
|
|
45
|
+
expect(spec.components.securitySchemes.bearerAuth).toEqual({
|
|
46
|
+
type: "http",
|
|
47
|
+
scheme: "bearer",
|
|
48
|
+
});
|
|
49
|
+
expect(spec.components.schemas).toEqual({});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("includeDescription is off by default — no description field", () => {
|
|
53
|
+
const spec = generateOpenApi({
|
|
54
|
+
registry: registry({ a: makeOp("a") }),
|
|
55
|
+
info,
|
|
56
|
+
servers,
|
|
57
|
+
basePath,
|
|
58
|
+
pathStyle: "per-op",
|
|
59
|
+
}) as any;
|
|
60
|
+
const entry = spec.paths["/api/gpt/query/a"].get;
|
|
61
|
+
expect(entry.description).toBeUndefined();
|
|
62
|
+
expect(entry.summary).toBe("a desc");
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("includeDescription: true emits description built from desc+instruction", () => {
|
|
66
|
+
const spec = generateOpenApi({
|
|
67
|
+
registry: registry({ a: makeOp("a") }),
|
|
68
|
+
info,
|
|
69
|
+
servers,
|
|
70
|
+
basePath,
|
|
71
|
+
pathStyle: "per-op",
|
|
72
|
+
includeDescription: true,
|
|
73
|
+
}) as any;
|
|
74
|
+
const d = spec.paths["/api/gpt/query/a"].get.description as string;
|
|
75
|
+
expect(d).toContain("a desc");
|
|
76
|
+
expect(d).toContain("call a");
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test("description truncated at maxDescriptionLength when included", () => {
|
|
80
|
+
const spec = generateOpenApi({
|
|
81
|
+
registry: registry({
|
|
82
|
+
a: makeOp("a", { instruction: "x".repeat(500) }),
|
|
83
|
+
}),
|
|
84
|
+
info,
|
|
85
|
+
servers,
|
|
86
|
+
basePath,
|
|
87
|
+
pathStyle: "per-op",
|
|
88
|
+
includeDescription: true,
|
|
89
|
+
}) as any;
|
|
90
|
+
const d = spec.paths["/api/gpt/query/a"].get.description as string;
|
|
91
|
+
expect(d.length).toBeLessThanOrEqual(300);
|
|
92
|
+
expect(d.endsWith("…")).toBe(true);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test("summary capped at 120 chars", () => {
|
|
96
|
+
const spec = generateOpenApi({
|
|
97
|
+
registry: registry({
|
|
98
|
+
a: makeOp("a", { description: "y".repeat(200) }),
|
|
99
|
+
}),
|
|
100
|
+
info,
|
|
101
|
+
servers,
|
|
102
|
+
basePath,
|
|
103
|
+
pathStyle: "per-op",
|
|
104
|
+
}) as any;
|
|
105
|
+
const s = spec.paths["/api/gpt/query/a"].get.summary as string;
|
|
106
|
+
expect(s.length).toBeLessThanOrEqual(120);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test("custom bearerSchemeName", () => {
|
|
110
|
+
const spec = generateOpenApi({
|
|
111
|
+
registry: registry({ a: makeOp("a") }),
|
|
112
|
+
info,
|
|
113
|
+
servers,
|
|
114
|
+
basePath,
|
|
115
|
+
pathStyle: "per-op",
|
|
116
|
+
bearerSchemeName: "oauthToken",
|
|
117
|
+
}) as any;
|
|
118
|
+
expect(spec.components.securitySchemes.oauthToken).toBeDefined();
|
|
119
|
+
expect(spec.paths["/api/gpt/query/a"].get.security).toEqual([
|
|
120
|
+
{ oauthToken: [] },
|
|
121
|
+
]);
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
describe("generateOpenApi pathStyle: 'per-op'", () => {
|
|
126
|
+
const opts = {
|
|
127
|
+
info,
|
|
128
|
+
servers,
|
|
129
|
+
basePath,
|
|
130
|
+
pathStyle: "per-op" as const,
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
test("auth=required emits default path only with bearerAuth", () => {
|
|
134
|
+
const spec = generateOpenApi({
|
|
135
|
+
...opts,
|
|
136
|
+
registry: registry({ a: makeOp("a", { auth: "required" }) }),
|
|
137
|
+
}) as any;
|
|
138
|
+
expect(Object.keys(spec.paths)).toEqual(["/api/gpt/query/a"]);
|
|
139
|
+
expect(spec.paths["/api/gpt/query/a"].get.security).toEqual([
|
|
140
|
+
{ bearerAuth: [] },
|
|
141
|
+
]);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test("auth=none emits /public path with empty security", () => {
|
|
145
|
+
const spec = generateOpenApi({
|
|
146
|
+
...opts,
|
|
147
|
+
registry: registry({ a: makeOp("a", { auth: "none" }) }),
|
|
148
|
+
}) as any;
|
|
149
|
+
expect(Object.keys(spec.paths)).toEqual(["/api/gpt/public/query/a"]);
|
|
150
|
+
expect(spec.paths["/api/gpt/public/query/a"].get.security).toEqual([]);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test("auth=optional emits both default and /public paths", () => {
|
|
154
|
+
const spec = generateOpenApi({
|
|
155
|
+
...opts,
|
|
156
|
+
registry: registry({ a: makeOp("a", { auth: "optional" }) }),
|
|
157
|
+
}) as any;
|
|
158
|
+
const ks = Object.keys(spec.paths).sort();
|
|
159
|
+
expect(ks).toEqual(["/api/gpt/public/query/a", "/api/gpt/query/a"]);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test("mutation emits POST with requestBody", () => {
|
|
163
|
+
const spec = generateOpenApi({
|
|
164
|
+
...opts,
|
|
165
|
+
registry: registry({ m: makeOp("m", { type: "mutation" }) }),
|
|
166
|
+
}) as any;
|
|
167
|
+
const entry = spec.paths["/api/gpt/mutate/m"];
|
|
168
|
+
expect(entry.post.requestBody).toBeDefined();
|
|
169
|
+
expect(entry.post.parameters).toBeUndefined();
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test("query has $variables parameter", () => {
|
|
173
|
+
const spec = generateOpenApi({
|
|
174
|
+
...opts,
|
|
175
|
+
registry: registry({ q: makeOp("q") }),
|
|
176
|
+
}) as any;
|
|
177
|
+
const p = spec.paths["/api/gpt/query/q"].get.parameters;
|
|
178
|
+
expect(p).toHaveLength(1);
|
|
179
|
+
expect(p[0].name).toBe("$variables");
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
describe("generateOpenApi pathStyle: 'parametric' (default)", () => {
|
|
184
|
+
test("collapses all query ops under one /query/{operation} path with enum", () => {
|
|
185
|
+
const spec = generateOpenApi({
|
|
186
|
+
registry: registry({
|
|
187
|
+
a: makeOp("a", { auth: "required" }),
|
|
188
|
+
b: makeOp("b", { auth: "required" }),
|
|
189
|
+
}),
|
|
190
|
+
info,
|
|
191
|
+
servers,
|
|
192
|
+
basePath,
|
|
193
|
+
}) as any;
|
|
194
|
+
const ks = Object.keys(spec.paths);
|
|
195
|
+
expect(ks).toEqual(["/api/gpt/query/{operation}"]);
|
|
196
|
+
const opParam = spec.paths["/api/gpt/query/{operation}"].get.parameters[0];
|
|
197
|
+
expect(opParam.name).toBe("operation");
|
|
198
|
+
expect(opParam.in).toBe("path");
|
|
199
|
+
expect(opParam.schema.enum).toEqual(["a", "b"]);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test("emits /public/{operation} when any op is auth=none or optional", () => {
|
|
203
|
+
const spec = generateOpenApi({
|
|
204
|
+
registry: registry({
|
|
205
|
+
priv: makeOp("priv", { auth: "required" }),
|
|
206
|
+
pub: makeOp("pub", { auth: "none" }),
|
|
207
|
+
both: makeOp("both", { auth: "optional" }),
|
|
208
|
+
}),
|
|
209
|
+
info,
|
|
210
|
+
servers,
|
|
211
|
+
basePath,
|
|
212
|
+
}) as any;
|
|
213
|
+
const ks = Object.keys(spec.paths).sort();
|
|
214
|
+
expect(ks).toEqual([
|
|
215
|
+
"/api/gpt/public/query/{operation}",
|
|
216
|
+
"/api/gpt/query/{operation}",
|
|
217
|
+
]);
|
|
218
|
+
// Default enum contains authed ops: required + optional (not "none")
|
|
219
|
+
expect(
|
|
220
|
+
spec.paths["/api/gpt/query/{operation}"].get.parameters[0].schema.enum,
|
|
221
|
+
).toEqual(["priv", "both"]);
|
|
222
|
+
// Public enum contains guest-callable ops: none + optional (not "required")
|
|
223
|
+
expect(
|
|
224
|
+
spec.paths["/api/gpt/public/query/{operation}"].get.parameters[0].schema
|
|
225
|
+
.enum,
|
|
226
|
+
).toEqual(["pub", "both"]);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
test("separate /mutate/{operation} path for mutations", () => {
|
|
230
|
+
const spec = generateOpenApi({
|
|
231
|
+
registry: registry({
|
|
232
|
+
m: makeOp("m", { type: "mutation" }),
|
|
233
|
+
}),
|
|
234
|
+
info,
|
|
235
|
+
servers,
|
|
236
|
+
basePath,
|
|
237
|
+
}) as any;
|
|
238
|
+
expect(spec.paths["/api/gpt/mutate/{operation}"]).toBeDefined();
|
|
239
|
+
expect(
|
|
240
|
+
spec.paths["/api/gpt/mutate/{operation}"].post.requestBody,
|
|
241
|
+
).toBeDefined();
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test("no description field by default (ChatGPT-safe)", () => {
|
|
245
|
+
const spec = generateOpenApi({
|
|
246
|
+
registry: registry({ a: makeOp("a") }),
|
|
247
|
+
info,
|
|
248
|
+
servers,
|
|
249
|
+
basePath,
|
|
250
|
+
}) as any;
|
|
251
|
+
const entry = spec.paths["/api/gpt/query/{operation}"].get;
|
|
252
|
+
expect(entry.description).toBeUndefined();
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
test("includeDescription: true emits a short description", () => {
|
|
256
|
+
const spec = generateOpenApi({
|
|
257
|
+
registry: registry({ a: makeOp("a") }),
|
|
258
|
+
info,
|
|
259
|
+
servers,
|
|
260
|
+
basePath,
|
|
261
|
+
includeDescription: true,
|
|
262
|
+
}) as any;
|
|
263
|
+
const d = spec.paths["/api/gpt/query/{operation}"].get
|
|
264
|
+
.description as string;
|
|
265
|
+
expect(typeof d).toBe("string");
|
|
266
|
+
expect(d.length).toBeLessThanOrEqual(300);
|
|
267
|
+
});
|
|
268
|
+
});
|
package/src/openapi.ts
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
import type { Registry } from "@donghanh/core";
|
|
2
|
+
|
|
3
|
+
export interface OpenApiInfo {
|
|
4
|
+
title: string;
|
|
5
|
+
description?: string;
|
|
6
|
+
version: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface OpenApiServer {
|
|
10
|
+
url: string;
|
|
11
|
+
description?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface GenerateOpenApiConfig {
|
|
15
|
+
registry: Registry;
|
|
16
|
+
info: OpenApiInfo;
|
|
17
|
+
servers: OpenApiServer[];
|
|
18
|
+
/** Mount path prefix, e.g. "/api/gpt". Omit trailing slash. Defaults to "". */
|
|
19
|
+
basePath?: string;
|
|
20
|
+
/** Name of the bearer security scheme. Defaults to "bearerAuth". */
|
|
21
|
+
bearerSchemeName?: string;
|
|
22
|
+
/** When true, adds an info note about the $variables encoding (default true). */
|
|
23
|
+
describeVariables?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* When true, each path emits a `description` built from the op's
|
|
26
|
+
* description + instruction. Default `false` — only `summary` is emitted,
|
|
27
|
+
* which keeps the spec compact and sidesteps ChatGPT Actions' 300-char
|
|
28
|
+
* description limit. Turn on when you want richer Action instructions in
|
|
29
|
+
* the OAS. (For listing sibling operations, prefer `includeOperationsInDetail`
|
|
30
|
+
* on `gptRoutes` — the GPT fetches `GET /operations/:name` to learn
|
|
31
|
+
* available ops, a cleaner channel than inlining them into OAS.)
|
|
32
|
+
*/
|
|
33
|
+
includeDescription?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Max length for each path's OpenAPI `description` when emitted. ChatGPT
|
|
36
|
+
* Actions rejects descriptions over 300 characters, so the default is 300.
|
|
37
|
+
* No effect when `includeDescription` is false.
|
|
38
|
+
*/
|
|
39
|
+
maxDescriptionLength?: number;
|
|
40
|
+
/**
|
|
41
|
+
* How to lay out paths:
|
|
42
|
+
* - "parametric" (default) — single path with `{operation}` as a path param,
|
|
43
|
+
* matching gptRoutes' route shape (`/query/:operation`). 2–4 paths total
|
|
44
|
+
* regardless of registry size; the model picks the op by filling the
|
|
45
|
+
* `operation` param. Mirrors the existing REST shape and matches the
|
|
46
|
+
* convention most donghanh apps already use in their ChatGPT Action config.
|
|
47
|
+
* - "per-op" — one OAS path per operation, e.g. `/query/start`,
|
|
48
|
+
* `/public/query/check-offer`. Each op gets its own summary + description,
|
|
49
|
+
* so ChatGPT Actions discovers them as separate actions. Larger spec;
|
|
50
|
+
* useful when you want each op to be a discrete ChatGPT Action.
|
|
51
|
+
*/
|
|
52
|
+
pathStyle?: "parametric" | "per-op";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function truncate(s: string, max: number): string {
|
|
56
|
+
if (s.length <= max) return s;
|
|
57
|
+
return `${s.slice(0, Math.max(0, max - 1))}…`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
type Sec = Array<Record<string, string[]>>;
|
|
61
|
+
|
|
62
|
+
type Operation = {
|
|
63
|
+
operationId: string;
|
|
64
|
+
summary: string;
|
|
65
|
+
description?: string;
|
|
66
|
+
security: Sec;
|
|
67
|
+
parameters?: Array<Record<string, unknown>>;
|
|
68
|
+
requestBody?: Record<string, unknown>;
|
|
69
|
+
responses: Record<string, unknown>;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
type PathItem = Partial<Record<"get" | "post", Operation>>;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Generate an OpenAPI 3.1 spec from a donghanh registry. Emits per-operation
|
|
76
|
+
* concrete paths so ChatGPT Actions can target each op independently.
|
|
77
|
+
*
|
|
78
|
+
* - `auth: "required"` (default) → path under `${basePath}/query/...` with bearerAuth
|
|
79
|
+
* - `auth: "optional"` → two entries: the default path with bearerAuth AND `/public/...` with no security
|
|
80
|
+
* - `auth: "none"` → single entry under `${basePath}/public/...` with no security
|
|
81
|
+
*/
|
|
82
|
+
export function generateOpenApi(config: GenerateOpenApiConfig): object {
|
|
83
|
+
const {
|
|
84
|
+
registry,
|
|
85
|
+
info,
|
|
86
|
+
servers,
|
|
87
|
+
basePath = "",
|
|
88
|
+
bearerSchemeName = "bearerAuth",
|
|
89
|
+
describeVariables = true,
|
|
90
|
+
includeDescription = false,
|
|
91
|
+
maxDescriptionLength = 300,
|
|
92
|
+
pathStyle = "parametric",
|
|
93
|
+
} = config;
|
|
94
|
+
|
|
95
|
+
const ops = registry.list();
|
|
96
|
+
const paths: Record<string, PathItem> = {};
|
|
97
|
+
|
|
98
|
+
const variablesParam = {
|
|
99
|
+
name: "$variables",
|
|
100
|
+
in: "query" as const,
|
|
101
|
+
required: false,
|
|
102
|
+
description: describeVariables
|
|
103
|
+
? "Variables encoded as JSON or TOON (one field per line), URI-encoded. See GET /operations/{name} for each op's input schema."
|
|
104
|
+
: undefined,
|
|
105
|
+
schema: { type: "string" },
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const variablesBody = {
|
|
109
|
+
required: false,
|
|
110
|
+
content: {
|
|
111
|
+
"application/json": {
|
|
112
|
+
schema: {
|
|
113
|
+
type: "object",
|
|
114
|
+
properties: {
|
|
115
|
+
$variables: {
|
|
116
|
+
type: "string",
|
|
117
|
+
description: describeVariables
|
|
118
|
+
? "Variables encoded as JSON string or TOON format."
|
|
119
|
+
: undefined,
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const successResponse = {
|
|
128
|
+
"200": {
|
|
129
|
+
description: "Successful response.",
|
|
130
|
+
content: {
|
|
131
|
+
"application/json": {
|
|
132
|
+
schema: {
|
|
133
|
+
type: "object",
|
|
134
|
+
properties: {
|
|
135
|
+
data: { type: "object" },
|
|
136
|
+
suggestedActions: {
|
|
137
|
+
type: "array",
|
|
138
|
+
items: { type: "object" },
|
|
139
|
+
},
|
|
140
|
+
nextSteps: { type: "string" },
|
|
141
|
+
operations: {
|
|
142
|
+
type: "array",
|
|
143
|
+
items: { type: "object" },
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
},
|
|
150
|
+
"400": {
|
|
151
|
+
description: "Validation or execution error.",
|
|
152
|
+
content: {
|
|
153
|
+
"application/json": {
|
|
154
|
+
schema: {
|
|
155
|
+
type: "object",
|
|
156
|
+
properties: {
|
|
157
|
+
errors: {
|
|
158
|
+
type: "array",
|
|
159
|
+
items: {
|
|
160
|
+
type: "object",
|
|
161
|
+
properties: { message: { type: "string" } },
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
operationDetail: { type: "object" },
|
|
165
|
+
},
|
|
166
|
+
},
|
|
167
|
+
},
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
"401": {
|
|
171
|
+
description: "Unauthenticated. Only emitted on paths that require auth.",
|
|
172
|
+
},
|
|
173
|
+
"404": {
|
|
174
|
+
description: "Operation not found (or requires auth on /public paths).",
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const emit = (
|
|
179
|
+
path: string,
|
|
180
|
+
method: "get" | "post",
|
|
181
|
+
op: (typeof ops)[number],
|
|
182
|
+
security: Sec,
|
|
183
|
+
) => {
|
|
184
|
+
const detail = registry.detail(op.id);
|
|
185
|
+
const entry: Operation = {
|
|
186
|
+
operationId: `${method}_${op.id}`.replace(/[^A-Za-z0-9_]/g, "_"),
|
|
187
|
+
summary: truncate(op.description, 120),
|
|
188
|
+
security,
|
|
189
|
+
responses: successResponse,
|
|
190
|
+
};
|
|
191
|
+
if (includeDescription) {
|
|
192
|
+
const full = detail?.instruction
|
|
193
|
+
? `${op.description}\n\n${detail.instruction}`
|
|
194
|
+
: op.description;
|
|
195
|
+
entry.description = truncate(full, maxDescriptionLength);
|
|
196
|
+
}
|
|
197
|
+
if (method === "get") {
|
|
198
|
+
entry.parameters = [variablesParam];
|
|
199
|
+
} else {
|
|
200
|
+
entry.requestBody = variablesBody;
|
|
201
|
+
}
|
|
202
|
+
(entry as Record<string, unknown>).tags = [op.type];
|
|
203
|
+
|
|
204
|
+
let item = paths[path];
|
|
205
|
+
if (!item) {
|
|
206
|
+
item = {};
|
|
207
|
+
paths[path] = item;
|
|
208
|
+
}
|
|
209
|
+
item[method] = entry;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
const authedSec: Sec = [{ [bearerSchemeName]: [] }];
|
|
213
|
+
const noSec: Sec = [];
|
|
214
|
+
|
|
215
|
+
if (pathStyle === "parametric") {
|
|
216
|
+
emitParametric(paths, basePath, authedSec, noSec, ops, {
|
|
217
|
+
includeDescription,
|
|
218
|
+
maxDescriptionLength,
|
|
219
|
+
variablesParam,
|
|
220
|
+
variablesBody,
|
|
221
|
+
successResponse,
|
|
222
|
+
});
|
|
223
|
+
} else {
|
|
224
|
+
for (const op of ops) {
|
|
225
|
+
const method: "get" | "post" = op.type === "query" ? "get" : "post";
|
|
226
|
+
const auth = op.auth ?? "required";
|
|
227
|
+
|
|
228
|
+
const methodPath = op.type === "query" ? "query" : "mutate";
|
|
229
|
+
const defaultPath = `${basePath}/${methodPath}/${op.id}`;
|
|
230
|
+
const publicPath = `${basePath}/public/${methodPath}/${op.id}`;
|
|
231
|
+
|
|
232
|
+
if (auth === "none") {
|
|
233
|
+
emit(publicPath, method, op, noSec);
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (auth === "required") {
|
|
237
|
+
emit(defaultPath, method, op, authedSec);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
// optional → expose both
|
|
241
|
+
emit(defaultPath, method, op, authedSec);
|
|
242
|
+
emit(publicPath, method, op, noSec);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
openapi: "3.1.0",
|
|
248
|
+
info,
|
|
249
|
+
servers,
|
|
250
|
+
paths,
|
|
251
|
+
components: {
|
|
252
|
+
schemas: {},
|
|
253
|
+
securitySchemes: {
|
|
254
|
+
[bearerSchemeName]: {
|
|
255
|
+
type: "http",
|
|
256
|
+
scheme: "bearer",
|
|
257
|
+
},
|
|
258
|
+
},
|
|
259
|
+
},
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function emitParametric(
|
|
264
|
+
paths: Record<string, PathItem>,
|
|
265
|
+
basePath: string,
|
|
266
|
+
authedSec: Sec,
|
|
267
|
+
noSec: Sec,
|
|
268
|
+
ops: ReturnType<Registry["list"]>,
|
|
269
|
+
ctx: {
|
|
270
|
+
includeDescription: boolean;
|
|
271
|
+
maxDescriptionLength: number;
|
|
272
|
+
variablesParam: Record<string, unknown>;
|
|
273
|
+
variablesBody: Record<string, unknown>;
|
|
274
|
+
successResponse: Record<string, unknown>;
|
|
275
|
+
},
|
|
276
|
+
): void {
|
|
277
|
+
const queryIds = ops.filter((o) => o.type === "query").map((o) => o.id);
|
|
278
|
+
const mutationIds = ops.filter((o) => o.type === "mutation").map((o) => o.id);
|
|
279
|
+
const authedQueryIds = ops
|
|
280
|
+
.filter((o) => o.type === "query" && (o.auth ?? "required") !== "none")
|
|
281
|
+
.map((o) => o.id);
|
|
282
|
+
const authedMutationIds = ops
|
|
283
|
+
.filter((o) => o.type === "mutation" && (o.auth ?? "required") !== "none")
|
|
284
|
+
.map((o) => o.id);
|
|
285
|
+
const publicQueryIds = ops
|
|
286
|
+
.filter((o) => o.type === "query" && (o.auth ?? "required") !== "required")
|
|
287
|
+
.map((o) => o.id);
|
|
288
|
+
const publicMutationIds = ops
|
|
289
|
+
.filter(
|
|
290
|
+
(o) => o.type === "mutation" && (o.auth ?? "required") !== "required",
|
|
291
|
+
)
|
|
292
|
+
.map((o) => o.id);
|
|
293
|
+
|
|
294
|
+
const opParam = (enumIds: string[]): Record<string, unknown> => ({
|
|
295
|
+
name: "operation",
|
|
296
|
+
in: "path",
|
|
297
|
+
required: true,
|
|
298
|
+
description: `Operation slug. One of: ${enumIds.join(", ")}.`,
|
|
299
|
+
schema: { type: "string", enum: enumIds },
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
const make = (
|
|
303
|
+
opName: string,
|
|
304
|
+
summary: string,
|
|
305
|
+
_method: "get" | "post",
|
|
306
|
+
security: Sec,
|
|
307
|
+
enumIds: string[],
|
|
308
|
+
bodyBased: boolean,
|
|
309
|
+
description: string,
|
|
310
|
+
): Operation => {
|
|
311
|
+
const entry: Operation = {
|
|
312
|
+
operationId: opName,
|
|
313
|
+
summary: truncate(summary, 120),
|
|
314
|
+
security,
|
|
315
|
+
responses: ctx.successResponse as Record<string, unknown>,
|
|
316
|
+
parameters: bodyBased
|
|
317
|
+
? [opParam(enumIds)]
|
|
318
|
+
: [opParam(enumIds), ctx.variablesParam],
|
|
319
|
+
};
|
|
320
|
+
if (ctx.includeDescription) {
|
|
321
|
+
entry.description = truncate(description, ctx.maxDescriptionLength);
|
|
322
|
+
}
|
|
323
|
+
if (bodyBased) entry.requestBody = ctx.variablesBody;
|
|
324
|
+
return entry;
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
if (queryIds.length) {
|
|
328
|
+
if (authedQueryIds.length) {
|
|
329
|
+
paths[`${basePath}/query/{operation}`] = {
|
|
330
|
+
get: make(
|
|
331
|
+
"queryOperation",
|
|
332
|
+
"Execute a query operation",
|
|
333
|
+
"get",
|
|
334
|
+
authedSec,
|
|
335
|
+
authedQueryIds,
|
|
336
|
+
false,
|
|
337
|
+
"Execute a read-only query by name. Pass variables as a JSON or TOON string in $variables.",
|
|
338
|
+
),
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
if (publicQueryIds.length) {
|
|
342
|
+
paths[`${basePath}/public/query/{operation}`] = {
|
|
343
|
+
get: make(
|
|
344
|
+
"publicQueryOperation",
|
|
345
|
+
"Execute a public query operation",
|
|
346
|
+
"get",
|
|
347
|
+
noSec,
|
|
348
|
+
publicQueryIds,
|
|
349
|
+
false,
|
|
350
|
+
"Execute a public query by name — no authentication required.",
|
|
351
|
+
),
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
if (mutationIds.length) {
|
|
357
|
+
if (authedMutationIds.length) {
|
|
358
|
+
paths[`${basePath}/mutate/{operation}`] = {
|
|
359
|
+
post: make(
|
|
360
|
+
"mutateOperation",
|
|
361
|
+
"Execute a mutation operation",
|
|
362
|
+
"post",
|
|
363
|
+
authedSec,
|
|
364
|
+
authedMutationIds,
|
|
365
|
+
true,
|
|
366
|
+
"Execute a mutation by name. Pass variables in the JSON body's $variables field.",
|
|
367
|
+
),
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
if (publicMutationIds.length) {
|
|
371
|
+
paths[`${basePath}/public/mutate/{operation}`] = {
|
|
372
|
+
post: make(
|
|
373
|
+
"publicMutateOperation",
|
|
374
|
+
"Execute a public mutation operation",
|
|
375
|
+
"post",
|
|
376
|
+
noSec,
|
|
377
|
+
publicMutationIds,
|
|
378
|
+
true,
|
|
379
|
+
"Execute a public mutation by name — no authentication required.",
|
|
380
|
+
),
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|