@donghanh/hono 0.2.0 → 0.3.2
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 +2 -2
- package/src/gpt.test.ts +327 -0
- package/src/gpt.ts +118 -34
- package/src/index.ts +6 -0
- package/src/mcp.ts +1 -1
- package/src/openapi.test.ts +196 -0
- package/src/openapi.ts +234 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donghanh/hono",
|
|
3
|
-
"version": "0.2
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "Hono routes for GPT Store and LLM chat — renderers for ChatGPT and OpenAI-compatible APIs",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"directory": "packages/hono"
|
|
14
14
|
},
|
|
15
15
|
"peerDependencies": {
|
|
16
|
-
"@donghanh/core": "^0.
|
|
16
|
+
"@donghanh/core": "^0.3.0",
|
|
17
17
|
"hono": "^4.7.0"
|
|
18
18
|
}
|
|
19
19
|
}
|
package/src/gpt.test.ts
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import type {
|
|
3
|
+
Executor,
|
|
4
|
+
OperationComponent,
|
|
5
|
+
OperationConfig,
|
|
6
|
+
} from "@donghanh/core";
|
|
7
|
+
import { App, Brief, buildRegistry, Message } from "@donghanh/core";
|
|
8
|
+
import { gptRoutes } from "./gpt";
|
|
9
|
+
import type { Authenticate } from "./middleware";
|
|
10
|
+
|
|
11
|
+
function makeOp(
|
|
12
|
+
id: string,
|
|
13
|
+
overrides: Partial<OperationConfig> = {},
|
|
14
|
+
): OperationComponent {
|
|
15
|
+
const op = ((_props: { data: unknown }) =>
|
|
16
|
+
Brief({
|
|
17
|
+
children: [Message({ children: "ok" })],
|
|
18
|
+
})) as unknown as OperationComponent;
|
|
19
|
+
op.operationConfig = {
|
|
20
|
+
id,
|
|
21
|
+
type: "query",
|
|
22
|
+
description: `${id} desc`,
|
|
23
|
+
instruction: `call ${id}`,
|
|
24
|
+
input: { type: "object", properties: {} },
|
|
25
|
+
responseKey: id,
|
|
26
|
+
...overrides,
|
|
27
|
+
};
|
|
28
|
+
return op;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function makeApp(ops: Record<string, OperationComponent>) {
|
|
32
|
+
return buildRegistry(App({ operations: ops }));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function makeExecutor(capture: { userId?: string; opId?: string }): Executor {
|
|
36
|
+
return async (opId, _vars, ctx) => {
|
|
37
|
+
capture.opId = opId;
|
|
38
|
+
capture.userId = (ctx.userId ?? "") as string;
|
|
39
|
+
return { ok: true };
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function makeAuth(
|
|
44
|
+
mode: "valid" | "invalid",
|
|
45
|
+
flag: { called: boolean },
|
|
46
|
+
): Authenticate {
|
|
47
|
+
return async (request) => {
|
|
48
|
+
flag.called = true;
|
|
49
|
+
const token = request.headers
|
|
50
|
+
.get("Authorization")
|
|
51
|
+
?.replace(/^Bearer\s+/i, "");
|
|
52
|
+
if (mode === "valid" && token) return { userId: `user:${token}` };
|
|
53
|
+
return { error: new Response("unauth", { status: 401 }) };
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function req(
|
|
58
|
+
app: ReturnType<typeof gptRoutes>,
|
|
59
|
+
path: string,
|
|
60
|
+
init: RequestInit = {},
|
|
61
|
+
) {
|
|
62
|
+
const res = await app.request(path, init);
|
|
63
|
+
let body: unknown = null;
|
|
64
|
+
try {
|
|
65
|
+
body = await res.clone().json();
|
|
66
|
+
} catch {
|
|
67
|
+
body = await res.text();
|
|
68
|
+
}
|
|
69
|
+
return { status: res.status, body };
|
|
70
|
+
}
|
|
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
|
+
|
|
123
|
+
describe("gptRoutes /operations listing", () => {
|
|
124
|
+
test("includes auth for each op when set", async () => {
|
|
125
|
+
const registry = makeApp({
|
|
126
|
+
a: makeOp("a", { auth: "required" }),
|
|
127
|
+
b: makeOp("b", { auth: "optional" }),
|
|
128
|
+
c: makeOp("c", { auth: "none" }),
|
|
129
|
+
d: makeOp("d"), // no auth → omitted in compact form
|
|
130
|
+
});
|
|
131
|
+
const app = gptRoutes({
|
|
132
|
+
registry,
|
|
133
|
+
executor: (async () => ({})) as Executor,
|
|
134
|
+
authenticate: async () => ({ userId: "x" }),
|
|
135
|
+
});
|
|
136
|
+
const { status, body } = await req(app, "/operations");
|
|
137
|
+
expect(status).toBe(200);
|
|
138
|
+
const b = body as { operations: Array<{ id: string; auth?: string }> };
|
|
139
|
+
const authById = Object.fromEntries(
|
|
140
|
+
b.operations.map((o) => [o.id, o.auth]),
|
|
141
|
+
);
|
|
142
|
+
expect(authById).toEqual({
|
|
143
|
+
a: "required",
|
|
144
|
+
b: "optional",
|
|
145
|
+
c: "none",
|
|
146
|
+
d: undefined,
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
describe("gptRoutes default /query /mutate", () => {
|
|
152
|
+
test("auth=required + no token → 401", async () => {
|
|
153
|
+
const flag = { called: false };
|
|
154
|
+
const app = gptRoutes({
|
|
155
|
+
registry: makeApp({ op: makeOp("op", { auth: "required" }) }),
|
|
156
|
+
executor: (async () => ({})) as Executor,
|
|
157
|
+
authenticate: makeAuth("invalid", flag),
|
|
158
|
+
});
|
|
159
|
+
const r = await req(app, "/query/op");
|
|
160
|
+
expect(r.status).toBe(401);
|
|
161
|
+
expect(flag.called).toBe(true);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test("auth=required + valid token → 200 w/ userId", async () => {
|
|
165
|
+
const capture: { userId?: string; opId?: string } = {};
|
|
166
|
+
const flag = { called: false };
|
|
167
|
+
const app = gptRoutes({
|
|
168
|
+
registry: makeApp({ op: makeOp("op", { auth: "required" }) }),
|
|
169
|
+
executor: makeExecutor(capture),
|
|
170
|
+
authenticate: makeAuth("valid", flag),
|
|
171
|
+
});
|
|
172
|
+
const r = await req(app, "/query/op", {
|
|
173
|
+
headers: { Authorization: "Bearer tok1" },
|
|
174
|
+
});
|
|
175
|
+
expect(r.status).toBe(200);
|
|
176
|
+
expect(capture.userId).toBe("user:tok1");
|
|
177
|
+
expect(flag.called).toBe(true);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
test("auth=optional + no token → 200 anonymous", async () => {
|
|
181
|
+
const capture: { userId?: string } = {};
|
|
182
|
+
const flag = { called: false };
|
|
183
|
+
const app = gptRoutes({
|
|
184
|
+
registry: makeApp({ op: makeOp("op", { auth: "optional" }) }),
|
|
185
|
+
executor: makeExecutor(capture),
|
|
186
|
+
authenticate: makeAuth("invalid", flag),
|
|
187
|
+
});
|
|
188
|
+
const r = await req(app, "/query/op");
|
|
189
|
+
expect(r.status).toBe(200);
|
|
190
|
+
expect(capture.userId).toBe("anonymous");
|
|
191
|
+
expect(flag.called).toBe(true);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("auth=optional + valid token → 200 w/ real userId", async () => {
|
|
195
|
+
const capture: { userId?: string } = {};
|
|
196
|
+
const flag = { called: false };
|
|
197
|
+
const app = gptRoutes({
|
|
198
|
+
registry: makeApp({ op: makeOp("op", { auth: "optional" }) }),
|
|
199
|
+
executor: makeExecutor(capture),
|
|
200
|
+
authenticate: makeAuth("valid", flag),
|
|
201
|
+
});
|
|
202
|
+
const r = await req(app, "/query/op", {
|
|
203
|
+
headers: { Authorization: "Bearer tok2" },
|
|
204
|
+
});
|
|
205
|
+
expect(r.status).toBe(200);
|
|
206
|
+
expect(capture.userId).toBe("user:tok2");
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
test("auth=none + no token → 200 anonymous", async () => {
|
|
210
|
+
const capture: { userId?: string } = {};
|
|
211
|
+
const flag = { called: false };
|
|
212
|
+
const app = gptRoutes({
|
|
213
|
+
registry: makeApp({ op: makeOp("op", { auth: "none" }) }),
|
|
214
|
+
executor: makeExecutor(capture),
|
|
215
|
+
authenticate: makeAuth("invalid", flag),
|
|
216
|
+
});
|
|
217
|
+
const r = await req(app, "/query/op");
|
|
218
|
+
expect(r.status).toBe(200);
|
|
219
|
+
expect(capture.userId).toBe("anonymous");
|
|
220
|
+
expect(flag.called).toBe(false);
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
test("auth=none + valid token → 200 ANONYMOUS (authenticate not called)", async () => {
|
|
224
|
+
const capture: { userId?: string } = {};
|
|
225
|
+
const flag = { called: false };
|
|
226
|
+
const app = gptRoutes({
|
|
227
|
+
registry: makeApp({ op: makeOp("op", { auth: "none" }) }),
|
|
228
|
+
executor: makeExecutor(capture),
|
|
229
|
+
authenticate: makeAuth("valid", flag),
|
|
230
|
+
});
|
|
231
|
+
const r = await req(app, "/query/op", {
|
|
232
|
+
headers: { Authorization: "Bearer tok3" },
|
|
233
|
+
});
|
|
234
|
+
expect(r.status).toBe(200);
|
|
235
|
+
expect(capture.userId).toBe("anonymous");
|
|
236
|
+
expect(flag.called).toBe(false);
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
describe("gptRoutes /public sub-paths", () => {
|
|
241
|
+
test("unknown op → 404", async () => {
|
|
242
|
+
const app = gptRoutes({
|
|
243
|
+
registry: makeApp({}),
|
|
244
|
+
executor: (async () => ({})) as Executor,
|
|
245
|
+
authenticate: async () => ({ userId: "x" }),
|
|
246
|
+
});
|
|
247
|
+
const r = await req(app, "/public/query/nope");
|
|
248
|
+
expect(r.status).toBe(404);
|
|
249
|
+
const b = r.body as { error: string };
|
|
250
|
+
expect(b.error).toContain("requires auth");
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
test("auth=required op → 404 (does not leak existence)", async () => {
|
|
254
|
+
const app = gptRoutes({
|
|
255
|
+
registry: makeApp({ priv: makeOp("priv", { auth: "required" }) }),
|
|
256
|
+
executor: (async () => ({})) as Executor,
|
|
257
|
+
authenticate: async () => ({ userId: "x" }),
|
|
258
|
+
});
|
|
259
|
+
const r = await req(app, "/public/query/priv");
|
|
260
|
+
expect(r.status).toBe(404);
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
test("auth=none op → 200 anonymous", async () => {
|
|
264
|
+
const capture: { userId?: string } = {};
|
|
265
|
+
const flag = { called: false };
|
|
266
|
+
const app = gptRoutes({
|
|
267
|
+
registry: makeApp({ pub: makeOp("pub", { auth: "none" }) }),
|
|
268
|
+
executor: makeExecutor(capture),
|
|
269
|
+
authenticate: makeAuth("valid", flag),
|
|
270
|
+
});
|
|
271
|
+
const r = await req(app, "/public/query/pub");
|
|
272
|
+
expect(r.status).toBe(200);
|
|
273
|
+
expect(capture.userId).toBe("anonymous");
|
|
274
|
+
expect(flag.called).toBe(false);
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
test("auth=optional + valid token → 200 w/ real userId", async () => {
|
|
278
|
+
const capture: { userId?: string } = {};
|
|
279
|
+
const flag = { called: false };
|
|
280
|
+
const app = gptRoutes({
|
|
281
|
+
registry: makeApp({ start: makeOp("start", { auth: "optional" }) }),
|
|
282
|
+
executor: makeExecutor(capture),
|
|
283
|
+
authenticate: makeAuth("valid", flag),
|
|
284
|
+
});
|
|
285
|
+
const r = await req(app, "/public/query/start", {
|
|
286
|
+
headers: { Authorization: "Bearer tok4" },
|
|
287
|
+
});
|
|
288
|
+
expect(r.status).toBe(200);
|
|
289
|
+
expect(capture.userId).toBe("user:tok4");
|
|
290
|
+
expect(flag.called).toBe(true);
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
test("auth=optional + bad token → 200 anonymous (public swallows)", async () => {
|
|
294
|
+
const capture: { userId?: string } = {};
|
|
295
|
+
const flag = { called: false };
|
|
296
|
+
const app = gptRoutes({
|
|
297
|
+
registry: makeApp({ start: makeOp("start", { auth: "optional" }) }),
|
|
298
|
+
executor: makeExecutor(capture),
|
|
299
|
+
authenticate: makeAuth("invalid", flag),
|
|
300
|
+
});
|
|
301
|
+
const r = await req(app, "/public/query/start", {
|
|
302
|
+
headers: { Authorization: "Bearer badtok" },
|
|
303
|
+
});
|
|
304
|
+
expect(r.status).toBe(200);
|
|
305
|
+
expect(capture.userId).toBe("anonymous");
|
|
306
|
+
expect(flag.called).toBe(true);
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
test("public mutate routes", async () => {
|
|
310
|
+
const capture: { userId?: string; opId?: string } = {};
|
|
311
|
+
const app = gptRoutes({
|
|
312
|
+
registry: makeApp({
|
|
313
|
+
pubmut: makeOp("pubmut", { auth: "none", type: "mutation" }),
|
|
314
|
+
}),
|
|
315
|
+
executor: makeExecutor(capture),
|
|
316
|
+
authenticate: async () => ({ userId: "x" }),
|
|
317
|
+
});
|
|
318
|
+
const r = await req(app, "/public/mutate/pubmut", {
|
|
319
|
+
method: "POST",
|
|
320
|
+
headers: { "content-type": "application/json" },
|
|
321
|
+
body: JSON.stringify({ $variables: "{}" }),
|
|
322
|
+
});
|
|
323
|
+
expect(r.status).toBe(200);
|
|
324
|
+
expect(capture.opId).toBe("pubmut");
|
|
325
|
+
expect(capture.userId).toBe("anonymous");
|
|
326
|
+
});
|
|
327
|
+
});
|
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>,
|
|
@@ -24,6 +30,11 @@ export interface GptRoutesConfig {
|
|
|
24
30
|
) => Promise<void>;
|
|
25
31
|
}
|
|
26
32
|
|
|
33
|
+
/** Sentinel used when a request runs without an authenticated user. */
|
|
34
|
+
const ANONYMOUS: string = "anonymous";
|
|
35
|
+
|
|
36
|
+
type AuthMode = "none" | "optional" | "required";
|
|
37
|
+
|
|
27
38
|
function jsonError(message: string, status = 400): Response {
|
|
28
39
|
return new Response(JSON.stringify({ errors: [{ message }] }), {
|
|
29
40
|
status,
|
|
@@ -39,11 +50,12 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
39
50
|
encodeVariables,
|
|
40
51
|
responseSchemas,
|
|
41
52
|
enrichResponse,
|
|
53
|
+
includeOperationsInDetail,
|
|
42
54
|
} = config;
|
|
43
55
|
|
|
44
56
|
const app = new Hono();
|
|
45
57
|
|
|
46
|
-
// List operations
|
|
58
|
+
// List operations (auth advertised per-op)
|
|
47
59
|
app.get("/operations", (c) => {
|
|
48
60
|
const url = new URL(c.req.url);
|
|
49
61
|
const search = url.searchParams.get("search")?.toLowerCase();
|
|
@@ -81,14 +93,42 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
81
93
|
);
|
|
82
94
|
}
|
|
83
95
|
|
|
96
|
+
if (includeOperationsInDetail) {
|
|
97
|
+
return c.json({ ...detail, operations: registry.list() });
|
|
98
|
+
}
|
|
84
99
|
return c.json(detail);
|
|
85
100
|
});
|
|
86
101
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
102
|
+
/**
|
|
103
|
+
* Resolve the userId to execute with, given the op's auth posture and the
|
|
104
|
+
* inbound request. Returns either a string userId or a Response to short-circuit.
|
|
105
|
+
*/
|
|
106
|
+
async function resolveUser(
|
|
107
|
+
request: Request,
|
|
108
|
+
authMode: AuthMode,
|
|
109
|
+
public_: boolean,
|
|
110
|
+
): Promise<string | Response> {
|
|
111
|
+
// auth: "none" — always anonymous, never call authenticate
|
|
112
|
+
if (authMode === "none") return ANONYMOUS;
|
|
113
|
+
|
|
114
|
+
// Public sub-router: be lenient — swallow errors, fall back to anonymous
|
|
115
|
+
if (public_) {
|
|
116
|
+
const result = await authenticate(request);
|
|
117
|
+
if (isAuthError(result)) return ANONYMOUS;
|
|
118
|
+
return result.userId;
|
|
119
|
+
}
|
|
91
120
|
|
|
121
|
+
// Default path: propagate auth error when required; swallow when optional
|
|
122
|
+
const result = await authenticate(request);
|
|
123
|
+
if (isAuthError(result)) {
|
|
124
|
+
if (authMode === "optional") return ANONYMOUS;
|
|
125
|
+
return result.error;
|
|
126
|
+
}
|
|
127
|
+
return result.userId;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Execute query (default)
|
|
131
|
+
app.get("/query/:operation", async (c) => {
|
|
92
132
|
const operationId = c.req.param("operation");
|
|
93
133
|
const op = registry.get(operationId);
|
|
94
134
|
|
|
@@ -103,17 +143,18 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
103
143
|
);
|
|
104
144
|
}
|
|
105
145
|
|
|
106
|
-
|
|
146
|
+
const authMode: AuthMode = op.operationConfig.auth ?? "required";
|
|
147
|
+
const user = await resolveUser(c.req.raw, authMode, false);
|
|
148
|
+
if (user instanceof Response) return user;
|
|
149
|
+
|
|
150
|
+
return handleExecution(c.req.raw, user, operationId, () => {
|
|
107
151
|
const url = new URL(c.req.url);
|
|
108
152
|
return url.searchParams.get("$variables") ?? undefined;
|
|
109
153
|
});
|
|
110
154
|
});
|
|
111
155
|
|
|
112
|
-
// Execute mutation
|
|
156
|
+
// Execute mutation (default)
|
|
113
157
|
app.post("/mutate/:operation", async (c) => {
|
|
114
|
-
const authResult = await authenticate(c.req.raw);
|
|
115
|
-
if (isAuthError(authResult)) return authResult.error;
|
|
116
|
-
|
|
117
158
|
const operationId = c.req.param("operation");
|
|
118
159
|
const op = registry.get(operationId);
|
|
119
160
|
|
|
@@ -128,15 +169,73 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
128
169
|
);
|
|
129
170
|
}
|
|
130
171
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
172
|
+
const authMode: AuthMode = op.operationConfig.auth ?? "required";
|
|
173
|
+
const user = await resolveUser(c.req.raw, authMode, false);
|
|
174
|
+
if (user instanceof Response) return user;
|
|
175
|
+
|
|
176
|
+
return handleExecution(c.req.raw, user, operationId, async () => {
|
|
177
|
+
const body = await c.req.json();
|
|
178
|
+
return body.$variables;
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
// ---------- /public sub-paths ----------
|
|
183
|
+
// OAS-friendly no-auth surface. Rejects ops whose auth posture is "required".
|
|
184
|
+
|
|
185
|
+
const notFound404 = (body: { error: string }): Response =>
|
|
186
|
+
new Response(JSON.stringify(body), {
|
|
187
|
+
status: 404,
|
|
188
|
+
headers: { "content-type": "application/json" },
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
app.get("/public/query/:operation", async (c) => {
|
|
192
|
+
const operationId = c.req.param("operation");
|
|
193
|
+
const op = registry.get(operationId);
|
|
194
|
+
if (!op) {
|
|
195
|
+
return notFound404({ error: "Operation not found or requires auth." });
|
|
196
|
+
}
|
|
197
|
+
const authMode: AuthMode = op.operationConfig.auth ?? "required";
|
|
198
|
+
if (authMode === "required") {
|
|
199
|
+
return notFound404({ error: "Operation not found or requires auth." });
|
|
200
|
+
}
|
|
201
|
+
if (op.operationConfig.type !== "query") {
|
|
202
|
+
return jsonError(
|
|
203
|
+
`"${operationId}" is a mutation. Use POST /public/mutate/${operationId} instead.`,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const user = await resolveUser(c.req.raw, authMode, true);
|
|
208
|
+
if (user instanceof Response) return user;
|
|
209
|
+
|
|
210
|
+
return handleExecution(c.req.raw, user, operationId, () => {
|
|
211
|
+
const url = new URL(c.req.url);
|
|
212
|
+
return url.searchParams.get("$variables") ?? undefined;
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
app.post("/public/mutate/:operation", async (c) => {
|
|
217
|
+
const operationId = c.req.param("operation");
|
|
218
|
+
const op = registry.get(operationId);
|
|
219
|
+
if (!op) {
|
|
220
|
+
return notFound404({ error: "Operation not found or requires auth." });
|
|
221
|
+
}
|
|
222
|
+
const authMode: AuthMode = op.operationConfig.auth ?? "required";
|
|
223
|
+
if (authMode === "required") {
|
|
224
|
+
return notFound404({ error: "Operation not found or requires auth." });
|
|
225
|
+
}
|
|
226
|
+
if (op.operationConfig.type !== "mutation") {
|
|
227
|
+
return jsonError(
|
|
228
|
+
`"${operationId}" is a query. Use GET /public/query/${operationId} instead.`,
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const user = await resolveUser(c.req.raw, authMode, true);
|
|
233
|
+
if (user instanceof Response) return user;
|
|
234
|
+
|
|
235
|
+
return handleExecution(c.req.raw, user, operationId, async () => {
|
|
236
|
+
const body = await c.req.json();
|
|
237
|
+
return body.$variables;
|
|
238
|
+
});
|
|
140
239
|
});
|
|
141
240
|
|
|
142
241
|
async function handleExecution(
|
|
@@ -153,20 +252,11 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
153
252
|
}
|
|
154
253
|
|
|
155
254
|
let variables: Record<string, unknown> = {};
|
|
156
|
-
if (typeof rawVariables === "string" && encodeVariables) {
|
|
157
|
-
// Decode using the inverse - we expect TOON format
|
|
158
|
-
// The app provides its own decode in the executor or via a decode option
|
|
159
|
-
// For now, pass raw through and let the executor handle it
|
|
160
|
-
}
|
|
161
255
|
|
|
162
|
-
// We need a decode function. Let's accept raw variables as TOON or JSON.
|
|
163
256
|
if (typeof rawVariables === "string") {
|
|
164
257
|
try {
|
|
165
|
-
// Try JSON first
|
|
166
258
|
variables = JSON.parse(rawVariables);
|
|
167
259
|
} catch {
|
|
168
|
-
// Pass as-is, let the app's decode handle it
|
|
169
|
-
// Store raw so executor can decode
|
|
170
260
|
variables = { $raw: rawVariables };
|
|
171
261
|
}
|
|
172
262
|
}
|
|
@@ -180,7 +270,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
180
270
|
context: { userId, request },
|
|
181
271
|
});
|
|
182
272
|
|
|
183
|
-
// Render JSX tree through ChatGPT renderer
|
|
184
273
|
const rendered = renderForChatGpt(brief, {
|
|
185
274
|
encodeVariables,
|
|
186
275
|
getOperationInput: (id) => {
|
|
@@ -189,7 +278,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
189
278
|
},
|
|
190
279
|
});
|
|
191
280
|
|
|
192
|
-
// Build response
|
|
193
281
|
const result: Record<string, unknown> = {
|
|
194
282
|
data: {
|
|
195
283
|
[registry.get(operationId)!.operationConfig.responseKey]: data,
|
|
@@ -203,7 +291,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
203
291
|
result.nextSteps = rendered.nextSteps;
|
|
204
292
|
}
|
|
205
293
|
|
|
206
|
-
// Enrich response (inject display, etc)
|
|
207
294
|
if (enrichResponse) {
|
|
208
295
|
await enrichResponse(result, {
|
|
209
296
|
operationId,
|
|
@@ -214,12 +301,10 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
214
301
|
});
|
|
215
302
|
}
|
|
216
303
|
|
|
217
|
-
// Include response schema for start
|
|
218
304
|
if (operationId === "start" && responseSchemas?.start) {
|
|
219
305
|
result.responseSchema = responseSchemas.start;
|
|
220
306
|
}
|
|
221
307
|
|
|
222
|
-
// Always include operations list
|
|
223
308
|
result.operations = registry.list();
|
|
224
309
|
|
|
225
310
|
return new Response(JSON.stringify(result), {
|
|
@@ -232,7 +317,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
232
317
|
errors: [{ message }],
|
|
233
318
|
};
|
|
234
319
|
|
|
235
|
-
// Include operation detail for self-correction
|
|
236
320
|
const detail = registry.detail(operationId);
|
|
237
321
|
if (detail) {
|
|
238
322
|
errorResult.operationDetail = {
|
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";
|
package/src/mcp.ts
CHANGED
|
@@ -225,7 +225,7 @@ export function mcpRoutes(config: McpRoutesConfig): Hono {
|
|
|
225
225
|
}
|
|
226
226
|
|
|
227
227
|
case "resources/read": {
|
|
228
|
-
const uri =
|
|
228
|
+
const uri = body.params?.uri as string | undefined;
|
|
229
229
|
if (!uri) return c.json(failure(id, -32602, "Missing uri"), 400);
|
|
230
230
|
const widget = Object.values(widgets).find((w) => w.uri === uri);
|
|
231
231
|
if (!widget) {
|
|
@@ -0,0 +1,196 @@
|
|
|
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", () => {
|
|
35
|
+
test("emits 3.1.0 spec with info + servers + bearerAuth scheme", () => {
|
|
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
|
+
});
|
|
50
|
+
|
|
51
|
+
test("auth=required emits default path only with bearerAuth", () => {
|
|
52
|
+
const spec = generateOpenApi({
|
|
53
|
+
registry: registry({ a: makeOp("a", { auth: "required" }) }),
|
|
54
|
+
info,
|
|
55
|
+
servers,
|
|
56
|
+
basePath,
|
|
57
|
+
}) as any;
|
|
58
|
+
expect(Object.keys(spec.paths)).toEqual(["/api/gpt/query/a"]);
|
|
59
|
+
expect(spec.paths["/api/gpt/query/a"].get.security).toEqual([
|
|
60
|
+
{ bearerAuth: [] },
|
|
61
|
+
]);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("auth=none emits /public path with empty security", () => {
|
|
65
|
+
const spec = generateOpenApi({
|
|
66
|
+
registry: registry({ a: makeOp("a", { auth: "none" }) }),
|
|
67
|
+
info,
|
|
68
|
+
servers,
|
|
69
|
+
basePath,
|
|
70
|
+
}) as any;
|
|
71
|
+
expect(Object.keys(spec.paths)).toEqual(["/api/gpt/public/query/a"]);
|
|
72
|
+
expect(spec.paths["/api/gpt/public/query/a"].get.security).toEqual([]);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("auth=optional emits BOTH default and /public paths", () => {
|
|
76
|
+
const spec = generateOpenApi({
|
|
77
|
+
registry: registry({ a: makeOp("a", { auth: "optional" }) }),
|
|
78
|
+
info,
|
|
79
|
+
servers,
|
|
80
|
+
basePath,
|
|
81
|
+
}) as any;
|
|
82
|
+
const ks = Object.keys(spec.paths).sort();
|
|
83
|
+
expect(ks).toEqual(["/api/gpt/public/query/a", "/api/gpt/query/a"]);
|
|
84
|
+
expect(spec.paths["/api/gpt/query/a"].get.security).toEqual([
|
|
85
|
+
{ bearerAuth: [] },
|
|
86
|
+
]);
|
|
87
|
+
expect(spec.paths["/api/gpt/public/query/a"].get.security).toEqual([]);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test("mutation emits POST with requestBody", () => {
|
|
91
|
+
const spec = generateOpenApi({
|
|
92
|
+
registry: registry({ m: makeOp("m", { type: "mutation" }) }),
|
|
93
|
+
info,
|
|
94
|
+
servers,
|
|
95
|
+
basePath,
|
|
96
|
+
}) as any;
|
|
97
|
+
const entry = spec.paths["/api/gpt/mutate/m"];
|
|
98
|
+
expect(entry.post.requestBody).toBeDefined();
|
|
99
|
+
expect(entry.post.parameters).toBeUndefined();
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test("query has $variables parameter", () => {
|
|
103
|
+
const spec = generateOpenApi({
|
|
104
|
+
registry: registry({ q: makeOp("q") }),
|
|
105
|
+
info,
|
|
106
|
+
servers,
|
|
107
|
+
basePath,
|
|
108
|
+
}) as any;
|
|
109
|
+
const p = spec.paths["/api/gpt/query/q"].get.parameters;
|
|
110
|
+
expect(p).toHaveLength(1);
|
|
111
|
+
expect(p[0].name).toBe("$variables");
|
|
112
|
+
expect(p[0].in).toBe("query");
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("description combines op description + instruction", () => {
|
|
116
|
+
const spec = generateOpenApi({
|
|
117
|
+
registry: registry({ a: makeOp("a") }),
|
|
118
|
+
info,
|
|
119
|
+
servers,
|
|
120
|
+
basePath,
|
|
121
|
+
}) as any;
|
|
122
|
+
const op = spec.paths["/api/gpt/query/a"].get;
|
|
123
|
+
expect(op.summary).toBe("a desc");
|
|
124
|
+
expect(op.description).toContain("a desc");
|
|
125
|
+
expect(op.description).toContain("call a");
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test("operationId is unique per method+opId", () => {
|
|
129
|
+
const spec = generateOpenApi({
|
|
130
|
+
registry: registry({
|
|
131
|
+
a: makeOp("a", { auth: "optional" }),
|
|
132
|
+
}),
|
|
133
|
+
info,
|
|
134
|
+
servers,
|
|
135
|
+
basePath,
|
|
136
|
+
}) as any;
|
|
137
|
+
const authedId = spec.paths["/api/gpt/query/a"].get.operationId;
|
|
138
|
+
const publicId = spec.paths["/api/gpt/public/query/a"].get.operationId;
|
|
139
|
+
expect(authedId).toBe("get_a");
|
|
140
|
+
expect(publicId).toBe("get_a"); // Same handler, different path — OAS allows same operationId across paths
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test("mixed registry — three auth tiers coexist", () => {
|
|
144
|
+
const spec = generateOpenApi({
|
|
145
|
+
registry: registry({
|
|
146
|
+
priv: makeOp("priv", { auth: "required" }),
|
|
147
|
+
mixed: makeOp("mixed", { auth: "optional" }),
|
|
148
|
+
pub: makeOp("pub", { auth: "none" }),
|
|
149
|
+
}),
|
|
150
|
+
info,
|
|
151
|
+
servers,
|
|
152
|
+
basePath,
|
|
153
|
+
}) as any;
|
|
154
|
+
const ks = Object.keys(spec.paths).sort();
|
|
155
|
+
expect(ks).toEqual([
|
|
156
|
+
"/api/gpt/public/query/mixed",
|
|
157
|
+
"/api/gpt/public/query/pub",
|
|
158
|
+
"/api/gpt/query/mixed",
|
|
159
|
+
"/api/gpt/query/priv",
|
|
160
|
+
]);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test("includeSiblingsInDescription appends sibling list to each path description", () => {
|
|
164
|
+
const spec = generateOpenApi({
|
|
165
|
+
registry: registry({
|
|
166
|
+
a: makeOp("a", { auth: "required" }),
|
|
167
|
+
b: makeOp("b", { auth: "none", type: "mutation" }),
|
|
168
|
+
c: makeOp("c", { auth: "optional" }),
|
|
169
|
+
}),
|
|
170
|
+
info,
|
|
171
|
+
servers,
|
|
172
|
+
basePath,
|
|
173
|
+
includeSiblingsInDescription: true,
|
|
174
|
+
}) as any;
|
|
175
|
+
const description = spec.paths["/api/gpt/query/a"].get.description;
|
|
176
|
+
expect(description).toContain("Other operations");
|
|
177
|
+
// Contains id, type, auth, and description for each sibling
|
|
178
|
+
expect(description).toContain("`a` (query, auth: required) — a desc");
|
|
179
|
+
expect(description).toContain("`b` (mutation, auth: none) — b desc");
|
|
180
|
+
expect(description).toContain("`c` (query, auth: optional) — c desc");
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
test("custom bearerSchemeName", () => {
|
|
184
|
+
const spec = generateOpenApi({
|
|
185
|
+
registry: registry({ a: makeOp("a") }),
|
|
186
|
+
info,
|
|
187
|
+
servers,
|
|
188
|
+
basePath,
|
|
189
|
+
bearerSchemeName: "oauthToken",
|
|
190
|
+
}) as any;
|
|
191
|
+
expect(spec.components.securitySchemes.oauthToken).toBeDefined();
|
|
192
|
+
expect(spec.paths["/api/gpt/query/a"].get.security).toEqual([
|
|
193
|
+
{ oauthToken: [] },
|
|
194
|
+
]);
|
|
195
|
+
});
|
|
196
|
+
});
|
package/src/openapi.ts
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
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, append a "Other operations" section listing sibling op ids +
|
|
26
|
+
* descriptions to each path's OpenAPI `description`. Helps ChatGPT Actions
|
|
27
|
+
* learn the full surface from any single path. Default false.
|
|
28
|
+
*/
|
|
29
|
+
includeSiblingsInDescription?: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type Sec = Array<Record<string, string[]>>;
|
|
33
|
+
|
|
34
|
+
type Operation = {
|
|
35
|
+
operationId: string;
|
|
36
|
+
summary: string;
|
|
37
|
+
description?: string;
|
|
38
|
+
security: Sec;
|
|
39
|
+
parameters?: Array<Record<string, unknown>>;
|
|
40
|
+
requestBody?: Record<string, unknown>;
|
|
41
|
+
responses: Record<string, unknown>;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
type PathItem = Partial<Record<"get" | "post", Operation>>;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Generate an OpenAPI 3.1 spec from a donghanh registry. Emits per-operation
|
|
48
|
+
* concrete paths so ChatGPT Actions can target each op independently.
|
|
49
|
+
*
|
|
50
|
+
* - `auth: "required"` (default) → path under `${basePath}/query/...` with bearerAuth
|
|
51
|
+
* - `auth: "optional"` → two entries: the default path with bearerAuth AND `/public/...` with no security
|
|
52
|
+
* - `auth: "none"` → single entry under `${basePath}/public/...` with no security
|
|
53
|
+
*/
|
|
54
|
+
export function generateOpenApi(config: GenerateOpenApiConfig): object {
|
|
55
|
+
const {
|
|
56
|
+
registry,
|
|
57
|
+
info,
|
|
58
|
+
servers,
|
|
59
|
+
basePath = "",
|
|
60
|
+
bearerSchemeName = "bearerAuth",
|
|
61
|
+
describeVariables = true,
|
|
62
|
+
includeSiblingsInDescription = false,
|
|
63
|
+
} = config;
|
|
64
|
+
|
|
65
|
+
const ops = registry.list();
|
|
66
|
+
|
|
67
|
+
const siblingsBlock = includeSiblingsInDescription
|
|
68
|
+
? `\n\nOther operations:\n${ops
|
|
69
|
+
.map(
|
|
70
|
+
(o) =>
|
|
71
|
+
`- \`${o.id}\` (${o.type}, auth: ${o.auth ?? "required"}) — ${o.description}`,
|
|
72
|
+
)
|
|
73
|
+
.join("\n")}`
|
|
74
|
+
: "";
|
|
75
|
+
const paths: Record<string, PathItem> = {};
|
|
76
|
+
|
|
77
|
+
const variablesParam = {
|
|
78
|
+
name: "$variables",
|
|
79
|
+
in: "query" as const,
|
|
80
|
+
required: false,
|
|
81
|
+
description: describeVariables
|
|
82
|
+
? "Variables encoded as JSON or TOON (one field per line), URI-encoded. See GET /operations/{name} for each op's input schema."
|
|
83
|
+
: undefined,
|
|
84
|
+
schema: { type: "string" },
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const variablesBody = {
|
|
88
|
+
required: false,
|
|
89
|
+
content: {
|
|
90
|
+
"application/json": {
|
|
91
|
+
schema: {
|
|
92
|
+
type: "object",
|
|
93
|
+
properties: {
|
|
94
|
+
$variables: {
|
|
95
|
+
type: "string",
|
|
96
|
+
description: describeVariables
|
|
97
|
+
? "Variables encoded as JSON string or TOON format."
|
|
98
|
+
: undefined,
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const successResponse = {
|
|
107
|
+
"200": {
|
|
108
|
+
description: "Successful response.",
|
|
109
|
+
content: {
|
|
110
|
+
"application/json": {
|
|
111
|
+
schema: {
|
|
112
|
+
type: "object",
|
|
113
|
+
properties: {
|
|
114
|
+
data: { type: "object" },
|
|
115
|
+
suggestedActions: {
|
|
116
|
+
type: "array",
|
|
117
|
+
items: { type: "object" },
|
|
118
|
+
},
|
|
119
|
+
nextSteps: { type: "string" },
|
|
120
|
+
operations: {
|
|
121
|
+
type: "array",
|
|
122
|
+
items: { type: "object" },
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
"400": {
|
|
130
|
+
description: "Validation or execution error.",
|
|
131
|
+
content: {
|
|
132
|
+
"application/json": {
|
|
133
|
+
schema: {
|
|
134
|
+
type: "object",
|
|
135
|
+
properties: {
|
|
136
|
+
errors: {
|
|
137
|
+
type: "array",
|
|
138
|
+
items: {
|
|
139
|
+
type: "object",
|
|
140
|
+
properties: { message: { type: "string" } },
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
operationDetail: { type: "object" },
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
"401": {
|
|
150
|
+
description: "Unauthenticated. Only emitted on paths that require auth.",
|
|
151
|
+
},
|
|
152
|
+
"404": {
|
|
153
|
+
description: "Operation not found (or requires auth on /public paths).",
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const emit = (
|
|
158
|
+
path: string,
|
|
159
|
+
method: "get" | "post",
|
|
160
|
+
op: (typeof ops)[number],
|
|
161
|
+
security: Sec,
|
|
162
|
+
) => {
|
|
163
|
+
const detail = registry.detail(op.id);
|
|
164
|
+
const pascal = op.id
|
|
165
|
+
.split(/[-_]/)
|
|
166
|
+
.map((s) => (s ? s[0].toUpperCase() + s.slice(1) : ""))
|
|
167
|
+
.join("");
|
|
168
|
+
const entry: Operation = {
|
|
169
|
+
operationId: `${method}_${op.id}`.replace(/[^A-Za-z0-9_]/g, "_"),
|
|
170
|
+
summary: op.description,
|
|
171
|
+
description:
|
|
172
|
+
(detail?.instruction
|
|
173
|
+
? `${op.description}\n\n${detail.instruction}`
|
|
174
|
+
: op.description) + siblingsBlock,
|
|
175
|
+
security,
|
|
176
|
+
responses: successResponse,
|
|
177
|
+
};
|
|
178
|
+
if (method === "get") {
|
|
179
|
+
entry.parameters = [variablesParam];
|
|
180
|
+
} else {
|
|
181
|
+
entry.requestBody = variablesBody;
|
|
182
|
+
}
|
|
183
|
+
// Tag by op type to help OpenAPI UIs group them.
|
|
184
|
+
(entry as Record<string, unknown>).tags = [op.type];
|
|
185
|
+
// Hint: unused `pascal` to keep id stable if we later switch to camelCase.
|
|
186
|
+
void pascal;
|
|
187
|
+
|
|
188
|
+
let item = paths[path];
|
|
189
|
+
if (!item) {
|
|
190
|
+
item = {};
|
|
191
|
+
paths[path] = item;
|
|
192
|
+
}
|
|
193
|
+
item[method] = entry;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const authedSec: Sec = [{ [bearerSchemeName]: [] }];
|
|
197
|
+
const noSec: Sec = [];
|
|
198
|
+
|
|
199
|
+
for (const op of ops) {
|
|
200
|
+
const method: "get" | "post" = op.type === "query" ? "get" : "post";
|
|
201
|
+
const auth = op.auth ?? "required";
|
|
202
|
+
|
|
203
|
+
const methodPath = op.type === "query" ? "query" : "mutate";
|
|
204
|
+
const defaultPath = `${basePath}/${methodPath}/${op.id}`;
|
|
205
|
+
const publicPath = `${basePath}/public/${methodPath}/${op.id}`;
|
|
206
|
+
|
|
207
|
+
if (auth === "none") {
|
|
208
|
+
emit(publicPath, method, op, noSec);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (auth === "required") {
|
|
212
|
+
emit(defaultPath, method, op, authedSec);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
// optional → expose both
|
|
216
|
+
emit(defaultPath, method, op, authedSec);
|
|
217
|
+
emit(publicPath, method, op, noSec);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
openapi: "3.1.0",
|
|
222
|
+
info,
|
|
223
|
+
servers,
|
|
224
|
+
paths,
|
|
225
|
+
components: {
|
|
226
|
+
securitySchemes: {
|
|
227
|
+
[bearerSchemeName]: {
|
|
228
|
+
type: "http",
|
|
229
|
+
scheme: "bearer",
|
|
230
|
+
},
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
};
|
|
234
|
+
}
|