openapi.test.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. import { describe, expect, test } from "bun:test"
  2. import { Effect, Layer, Option } from "effect"
  3. import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
  4. import { CodeMode, OpenAPI, Tool } from "../src/index.js"
  5. import { inputTypeScript, outputTypeScript } from "../src/tool-schema.js"
  6. const baseUrl = "http://localhost:4096"
  7. type Document = OpenAPI.Document
  8. type Recorded = {
  9. readonly method: string
  10. readonly url: string
  11. readonly headers: Record<string, string>
  12. readonly body: unknown
  13. }
  14. const opencodeSpec = async (): Promise<Document> => {
  15. return Bun.file(new URL("./fixtures/opencode-v2-openapi.json", import.meta.url)).json() as Promise<Document>
  16. }
  17. const happyPathSpec = async (): Promise<Document> => {
  18. return Bun.file(new URL("./fixtures/openapi-happy-path.json", import.meta.url)).json() as Promise<Document>
  19. }
  20. const isRecord = (value: unknown): value is Record<string, unknown> =>
  21. typeof value === "object" && value !== null && !Array.isArray(value)
  22. const toolAt = (tools: unknown, name: string) =>
  23. name.split(".").reduce<unknown>((current, segment) => (isRecord(current) ? current[segment] : undefined), tools)
  24. const recordingClient = (respond: (request: HttpClientRequest.HttpClientRequest) => Response) => {
  25. const requests: Array<Recorded> = []
  26. const layer = Layer.succeed(HttpClient.HttpClient)(
  27. HttpClient.make((request) =>
  28. Effect.gen(function* () {
  29. const body =
  30. request.body._tag === "Uint8Array" ? JSON.parse(new TextDecoder().decode(request.body.body)) : undefined
  31. const url = Option.map(HttpClientRequest.toUrl(request), (resolved) => resolved.toString())
  32. requests.push({
  33. method: request.method,
  34. url: Option.getOrElse(url, () => request.url),
  35. headers: { ...request.headers },
  36. body,
  37. })
  38. return HttpClientResponse.fromWeb(request, respond(request))
  39. }),
  40. ),
  41. )
  42. return { requests, layer }
  43. }
  44. const json = (value: unknown, status = 200) =>
  45. new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json" } })
  46. const singleOperation = (operation: Record<string, unknown>, method = "get"): Document => ({
  47. openapi: "3.1.0",
  48. paths: {
  49. "/test": { [method]: { operationId: "test", responses: { 200: { description: "Success" } }, ...operation } },
  50. },
  51. })
  52. describe("OpenAPI.fromSpec", () => {
  53. test("covers a representative API from generation through execution", async () => {
  54. const resolutions: Array<string> = []
  55. const client = recordingClient((request) => {
  56. const url = Option.getOrElse(HttpClientRequest.toUrl(request), () => new URL(request.url))
  57. if (request.method === "POST") {
  58. return new Response(
  59. JSON.stringify({ id: "user-2", name: "Grace", email: "grace@example.test", role: "admin" }),
  60. { status: 201, headers: { "content-type": "application/vnd.example+json" } },
  61. )
  62. }
  63. if (request.method === "DELETE") return new Response(null, { status: 204 })
  64. if (url.pathname === "/search") {
  65. return new Response("2 matches", { headers: { "content-type": "text/plain" } })
  66. }
  67. return json({ id: "user-1", name: "Ada", email: "ada@example.test", role: "member" })
  68. })
  69. const api = OpenAPI.fromSpec({
  70. spec: await happyPathSpec(),
  71. baseUrl,
  72. auth: {
  73. resolve: ({ name }) => {
  74. resolutions.push(name)
  75. return Effect.succeed(
  76. name === "BearerAuth"
  77. ? { type: "bearer", token: "bearer-secret" }
  78. : { type: "apiKey", value: "api-secret" },
  79. )
  80. },
  81. },
  82. })
  83. const get = toolAt(api.tools, "users.get")
  84. const create = toolAt(api.tools, "users.create")
  85. const search = toolAt(api.tools, "search.run")
  86. const remove = toolAt(api.tools, "users.remove")
  87. expect(api.skipped).toEqual([])
  88. if (
  89. !Tool.isDefinition(get) ||
  90. !Tool.isDefinition(create) ||
  91. !Tool.isDefinition(search) ||
  92. !Tool.isDefinition(remove)
  93. ) {
  94. throw new Error("happy-path fixture did not generate every operation")
  95. }
  96. expect(inputTypeScript(get)).toBe(
  97. '{ userId: string; include?: Array<string>; verbose?: boolean; "X-Trace-ID"?: string }',
  98. )
  99. expect(inputTypeScript(create)).toBe('{ name: string; email: string; role?: "admin" | "member" }')
  100. expect(inputTypeScript(search)).toBe("{ filter?: { query: string; page?: number }; tags?: Array<string> }")
  101. expect(inputTypeScript(remove)).toBe("{ userId: string }")
  102. expect(outputTypeScript(get)).toContain("id: string")
  103. expect(outputTypeScript(create)).toContain('role?: "admin" | "member"')
  104. expect(outputTypeScript(search)).toBe("string")
  105. expect(outputTypeScript(remove)).toBe("null")
  106. const result = await Effect.runPromise(
  107. CodeMode.make({ tools: { api: api.tools } })
  108. .execute(
  109. `
  110. const user = await tools.api.users.get({
  111. userId: "user-1",
  112. include: ["profile", "permissions"],
  113. verbose: true,
  114. "X-Trace-ID": "trace-1",
  115. })
  116. const created = await tools.api.users.create({
  117. name: "Grace",
  118. email: "grace@example.test",
  119. role: "admin",
  120. })
  121. const summary = await tools.api.search.run({
  122. filter: { query: "effect", page: 2 },
  123. tags: ["typescript", "runtime"],
  124. })
  125. const removed = await tools.api.users.remove({ userId: "user-1" })
  126. return { user, created, summary, removed }
  127. `,
  128. )
  129. .pipe(Effect.provide(client.layer)),
  130. )
  131. expect(result).toMatchObject({
  132. ok: true,
  133. value: {
  134. user: { id: "user-1", name: "Ada" },
  135. created: { id: "user-2", name: "Grace" },
  136. summary: "2 matches",
  137. removed: null,
  138. },
  139. })
  140. expect(resolutions).toEqual(["BearerAuth", "ApiKey", "BearerAuth"])
  141. expect(client.requests).toHaveLength(4)
  142. const getUrl = new URL(client.requests[0]!.url)
  143. expect(getUrl.pathname).toBe("/users/user-1")
  144. expect(getUrl.searchParams.get("include")).toBe("profile,permissions")
  145. expect(getUrl.searchParams.get("verbose")).toBe("true")
  146. expect(client.requests[0]!.headers["x-trace-id"]).toBe("trace-1")
  147. expect(client.requests[0]!.headers.authorization).toBe("Bearer bearer-secret")
  148. const createUrl = new URL(client.requests[1]!.url)
  149. expect(createUrl.searchParams.get("api_key")).toBe("api-secret")
  150. expect(client.requests[1]!.body).toEqual({ name: "Grace", email: "grace@example.test", role: "admin" })
  151. const searchUrl = new URL(client.requests[2]!.url)
  152. expect(searchUrl.searchParams.get("filter[query]")).toBe("effect")
  153. expect(searchUrl.searchParams.get("filter[page]")).toBe("2")
  154. expect(searchUrl.searchParams.getAll("tags")).toEqual(["typescript", "runtime"])
  155. expect(client.requests[2]!.headers.authorization).toBeUndefined()
  156. expect(new URL(client.requests[3]!.url).pathname).toBe("/users/user-1")
  157. expect(client.requests[3]!.headers.authorization).toBe("Bearer bearer-secret")
  158. })
  159. test("converts representative opencode operations into the expected tool shape", async () => {
  160. const spec = await opencodeSpec()
  161. const result = OpenAPI.fromSpec({ spec, baseUrl })
  162. expect(result.skipped).toHaveLength(4)
  163. expect(result.skipped).toContainEqual({
  164. method: "GET",
  165. path: "/api/pty/{ptyID}/connect",
  166. reason: "WebSocket operations are not supported",
  167. })
  168. expect(result.skipped.filter((item) => item.reason === "SSE operations are not supported")).toHaveLength(2)
  169. expect(result.skipped).toContainEqual({
  170. method: "GET",
  171. path: "/api/fs/read/*",
  172. reason: "binary responses are not supported",
  173. })
  174. expect(toolAt(result.tools, "v2.health.get")).not.toBeUndefined()
  175. expect(toolAt(result.tools, "v2.session.get")).not.toBeUndefined()
  176. expect(toolAt(result.tools, "v2.session.create")).not.toBeUndefined()
  177. const sessionGet = toolAt(result.tools, "v2.session.get")
  178. expect(Tool.isDefinition(sessionGet)).toBe(true)
  179. if (!Tool.isDefinition(sessionGet)) throw new Error("v2.session.get was not generated")
  180. expect(inputTypeScript(sessionGet)).toBe("{ sessionID: string }")
  181. expect(outputTypeScript(sessionGet)).toContain("id: string")
  182. expect(outputTypeScript(sessionGet)).toContain("additions: number")
  183. const switchAgent = toolAt(result.tools, "v2.session.switchAgent")
  184. expect(Tool.isDefinition(switchAgent)).toBe(true)
  185. if (!Tool.isDefinition(switchAgent)) throw new Error("v2.session.switchAgent was not generated")
  186. expect(inputTypeScript(switchAgent)).toBe("{ sessionID: string; agent: string }")
  187. const instructionPut = toolAt(result.tools, "v2.session.instructions.entry.put")
  188. expect(Tool.isDefinition(instructionPut)).toBe(true)
  189. if (!Tool.isDefinition(instructionPut)) throw new Error("v2.session.instructions.entry.put was not generated")
  190. expect(inputTypeScript(instructionPut)).toBe("{ sessionID: string; key: string; value: unknown }")
  191. expect(toolAt(result.tools, "v2_session_instructions_entry_put_2")).toBeUndefined()
  192. expect(Tool.isDefinition(toolAt(result.tools, "v2.pty.connect"))).toBe(false)
  193. expect(toolAt(result.tools, "v2.session.log")).toBeUndefined()
  194. expect(toolAt(result.tools, "v2.event.subscribe")).toBeUndefined()
  195. expect(toolAt(result.tools, "v2.fs.read")).toBeUndefined()
  196. expect(toolAt(result.tools, "v2.pty.connect.token")).not.toBeUndefined()
  197. })
  198. test("preserves operation path sanitization and collision handling", () => {
  199. const response = { responses: { 200: { description: "Success" } } }
  200. const result = OpenAPI.fromSpec({
  201. baseUrl,
  202. spec: {
  203. openapi: "3.1.0",
  204. paths: {
  205. "/first": { get: { ...response, operationId: "group.item" } },
  206. "/second": { get: { ...response, operationId: "group.item" } },
  207. "/third": { get: { ...response, operationId: "group..other" } },
  208. },
  209. },
  210. })
  211. expect(Tool.isDefinition(toolAt(result.tools, "group.item"))).toBe(true)
  212. expect(Tool.isDefinition(toolAt(result.tools, "group_item_2"))).toBe(true)
  213. expect(Tool.isDefinition(toolAt(result.tools, "group.operation.other"))).toBe(true)
  214. })
  215. test("synthesizes flat operation IDs from methods and paths", () => {
  216. const response = { responses: { 200: { description: "Success" } } }
  217. const tools = OpenAPI.fromSpec({
  218. baseUrl,
  219. spec: {
  220. openapi: "3.1.0",
  221. paths: {
  222. "/users": { get: response, post: response },
  223. "/users/{id}": { get: response, patch: response, delete: response },
  224. "/organizations/{organizationId}/users/{id}": { get: response },
  225. },
  226. },
  227. }).tools
  228. for (const path of [
  229. "getUsers",
  230. "postUsers",
  231. "getUsersById",
  232. "patchUsersById",
  233. "deleteUsersById",
  234. "getOrganizationsByOrganizationidUsersById",
  235. ]) {
  236. expect(Tool.isDefinition(toolAt(tools, path))).toBe(true)
  237. }
  238. })
  239. test("lets operation parameters override matching path parameters", () => {
  240. const tool = toolAt(
  241. OpenAPI.fromSpec({
  242. baseUrl,
  243. spec: {
  244. openapi: "3.1.0",
  245. paths: {
  246. "/test": {
  247. parameters: [{ name: "limit", in: "query", schema: { type: "string" } }],
  248. get: {
  249. operationId: "test",
  250. parameters: [{ name: "limit", in: "query", required: true, schema: { type: "number" } }],
  251. responses: { 200: { description: "Success" } },
  252. },
  253. },
  254. },
  255. },
  256. }).tools,
  257. "test",
  258. )
  259. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  260. expect(inputTypeScript(tool)).toBe("{ limit: number }")
  261. })
  262. test("normalizes OpenAPI 3.0 schemas with Effect", () => {
  263. const result = OpenAPI.fromSpec({
  264. baseUrl,
  265. spec: {
  266. openapi: "3.0.3",
  267. paths: {
  268. "/search": {
  269. get: {
  270. operationId: "search",
  271. parameters: [
  272. {
  273. in: "query",
  274. name: "value",
  275. schema: { type: "string", nullable: true, minLength: 2 },
  276. },
  277. ],
  278. responses: { 200: { description: "Success" } },
  279. },
  280. },
  281. },
  282. },
  283. })
  284. const search = toolAt(result.tools, "search")
  285. expect(Tool.isDefinition(search)).toBe(true)
  286. if (!Tool.isDefinition(search)) throw new Error("search was not generated")
  287. expect(inputTypeScript(search)).toBe("{ value?: string | null }")
  288. const schema: unknown = search.input
  289. const input = isRecord(schema) ? schema : {}
  290. const properties = isRecord(input.properties) ? input.properties : {}
  291. const value = isRecord(properties.value) ? properties.value : {}
  292. expect(value.minLength).toBe(2)
  293. })
  294. test("preserves schema-local definitions alongside component definitions", () => {
  295. const tool = toolAt(
  296. OpenAPI.fromSpec({
  297. baseUrl,
  298. spec: {
  299. openapi: "3.1.0",
  300. paths: {
  301. "/test": {
  302. get: {
  303. operationId: "test",
  304. responses: {
  305. 200: {
  306. description: "Success",
  307. content: {
  308. "application/json": {
  309. schema: { $ref: "#/$defs/Local", $defs: { Local: { type: "string" } } },
  310. },
  311. },
  312. },
  313. },
  314. },
  315. },
  316. },
  317. components: { schemas: { Global: { type: "number" } } },
  318. },
  319. }).tools,
  320. "test",
  321. )
  322. if (!Tool.isDefinition(tool) || !isRecord(tool.output)) throw new Error("test output was not generated")
  323. expect(tool.output.$defs).toMatchObject({ Local: { type: "string" }, Global: { type: "number" } })
  324. })
  325. test("documents that the opencode fixture is unauthenticated", async () => {
  326. const spec = await opencodeSpec()
  327. const components = isRecord(spec.components) ? spec.components : {}
  328. const result = OpenAPI.fromSpec({ spec, baseUrl })
  329. expect(spec.security).toStrictEqual([])
  330. expect(isRecord(components.securitySchemes) ? Object.keys(components.securitySchemes) : []).toStrictEqual([])
  331. const health = toolAt(result.tools, "v2.health.get")
  332. const healthInput = isRecord(health) ? health.input : undefined
  333. expect(healthInput).toMatchObject({ type: "object", properties: {} })
  334. const input = isRecord(healthInput) ? healthInput : {}
  335. expect(Object.keys(isRecord(input.properties) ? input.properties : {})).toStrictEqual([])
  336. })
  337. test("exposes real opencode operations through CodeMode discovery", async () => {
  338. const { layer } = recordingClient(() => json({}))
  339. const runtime = CodeMode.make({
  340. tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools },
  341. })
  342. const result = await Effect.runPromise(
  343. runtime
  344. .execute(
  345. `
  346. return search({ query: "global health", namespace: "opencode", limit: 1 })
  347. `,
  348. )
  349. .pipe(Effect.provide(layer)),
  350. )
  351. expect(result).toMatchObject({ ok: true })
  352. if (!result.ok) return
  353. expect(result.value).toMatchObject({
  354. items: [
  355. {
  356. path: "tools.opencode.v2.health.get",
  357. description: "Check whether the API server is ready to accept requests.",
  358. },
  359. ],
  360. })
  361. expect(JSON.stringify(result.value)).toContain("healthy: true")
  362. })
  363. test("invokes real opencode path parameters and JSON request bodies", async () => {
  364. const { requests, layer } = recordingClient((request) => {
  365. if (request.method === "GET") return json({ id: "ses_123" })
  366. return json({ id: "ses_456" })
  367. })
  368. const runtime = CodeMode.make({
  369. tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools },
  370. })
  371. const result = await Effect.runPromise(
  372. runtime
  373. .execute(
  374. `
  375. const existing = await tools.opencode.v2.session.get({ sessionID: "ses_123" })
  376. const created = await tools.opencode.v2.session.create({ id: "ses_456" })
  377. return { existing, created }
  378. `,
  379. )
  380. .pipe(Effect.provide(layer)),
  381. )
  382. expect(result).toMatchObject({ ok: true })
  383. expect(requests).toHaveLength(2)
  384. expect(requests[0]).toMatchObject({ method: "GET", body: undefined })
  385. expect(new URL(requests[0]!.url).pathname).toBe("/api/session/ses_123")
  386. expect(requests[1]).toMatchObject({
  387. method: "POST",
  388. url: "http://localhost:4096/api/session",
  389. body: { id: "ses_456" },
  390. })
  391. })
  392. test("serializes deep-object query parameters from the opencode fixture", async () => {
  393. const client = recordingClient(() => json({ directory: "/tmp" }))
  394. const location = toolAt(OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools, "v2.location.get")
  395. if (!Tool.isDefinition(location)) throw new Error("v2.location.get was not generated")
  396. await Effect.runPromise(
  397. location.run({ location: { directory: "/tmp", workspace: "workspace-1" } }).pipe(Effect.provide(client.layer)),
  398. )
  399. const url = new URL(client.requests[0]!.url)
  400. expect(url.searchParams.get("location[directory]")).toBe("/tmp")
  401. expect(url.searchParams.get("location[workspace]")).toBe("workspace-1")
  402. })
  403. test("serializes supported simple and form parameter shapes", async () => {
  404. const client = recordingClient(() => json({ ok: true }))
  405. const result = OpenAPI.fromSpec({
  406. baseUrl,
  407. spec: {
  408. openapi: "3.1.0",
  409. paths: {
  410. "/items/{keys}": {
  411. get: {
  412. operationId: "items",
  413. parameters: [
  414. { name: "keys", in: "path", required: true, schema: { type: "array", items: { type: "string" } } },
  415. { name: "tags", in: "query", style: "form", explode: false, schema: { type: "array" } },
  416. { name: "filter", in: "query", style: "form", explode: true, schema: { type: "object" } },
  417. { name: "nullable", in: "query", required: true, schema: { type: ["string", "null"] } },
  418. { name: "constructor", in: "query", schema: { type: "string" } },
  419. { name: "meta", in: "header", style: "simple", explode: true, schema: { type: "object" } },
  420. ],
  421. responses: { 200: { description: "Success" } },
  422. },
  423. },
  424. },
  425. },
  426. })
  427. const tool = toolAt(result.tools, "items")
  428. if (!Tool.isDefinition(tool)) throw new Error("items was not generated")
  429. await Effect.runPromise(
  430. tool
  431. .run({
  432. keys: ["a!", "b*"],
  433. tags: ["x", "y"],
  434. filter: { state: "open", page: 2 },
  435. nullable: null,
  436. constructor_2: "safe",
  437. meta: { a: "b", c: "d" },
  438. })
  439. .pipe(Effect.provide(client.layer)),
  440. )
  441. const url = new URL(client.requests[0]!.url)
  442. expect(url.pathname).toBe("/items/a%21,b%2A")
  443. expect(url.searchParams.get("tags")).toBe("x,y")
  444. expect(url.searchParams.get("state")).toBe("open")
  445. expect(url.searchParams.get("page")).toBe("2")
  446. expect(url.searchParams.get("nullable")).toBe("null")
  447. expect(url.searchParams.get("constructor")).toBe("safe")
  448. expect(client.requests[0]!.headers.meta).toBe("a=b,c=d")
  449. await expect(Effect.runPromise(tool.run({ keys: [undefined] }).pipe(Effect.provide(client.layer)))).rejects.toThrow(
  450. "unsupported nested value",
  451. )
  452. })
  453. test("skips unsupported parameter encodings and malformed security", () => {
  454. const result = OpenAPI.fromSpec({
  455. baseUrl,
  456. spec: {
  457. openapi: "3.1.0",
  458. security: [{ bearer: [] }],
  459. paths: {
  460. "/cookie": {
  461. get: {
  462. operationId: "cookie",
  463. parameters: [{ name: "session", in: "cookie", schema: { type: "string" } }],
  464. responses: { 200: { description: "Success" } },
  465. },
  466. },
  467. "/reserved": {
  468. get: {
  469. operationId: "reserved",
  470. parameters: [{ name: "query", in: "query", allowReserved: true, schema: { type: "string" } }],
  471. responses: { 200: { description: "Success" } },
  472. },
  473. },
  474. "/invalid-style": {
  475. get: {
  476. operationId: "invalidStyle",
  477. parameters: [{ name: "query", in: "query", style: 42, schema: { type: "string" } }],
  478. responses: { 200: { description: "Success" } },
  479. },
  480. },
  481. "/security": {
  482. get: { operationId: "security", security: null, responses: { 200: { description: "Success" } } },
  483. },
  484. },
  485. },
  486. })
  487. expect(result.tools).toEqual({})
  488. expect(result.skipped.map((item) => item.reason)).toEqual([
  489. "cookie parameter 'session' is not supported",
  490. "parameter 'query' uses unsupported allowReserved encoding",
  491. "parameter 'query' has an invalid style",
  492. "security declaration is not an array",
  493. ])
  494. })
  495. test("fails closed on prototype-named missing security schemes", () => {
  496. const result = OpenAPI.fromSpec({
  497. baseUrl,
  498. spec: singleOperation({ security: [JSON.parse('{"__proto__":[]}')] }),
  499. })
  500. expect(result.tools).toEqual({})
  501. expect(result.skipped[0]?.reason).toBe("security requirement references missing or malformed scheme: __proto__")
  502. })
  503. test("resolves bearer authentication without exposing it as input", async () => {
  504. const contexts: Array<Parameters<OpenAPI.AuthResolver>[0]> = []
  505. const client = recordingClient(() => json({ ok: true }))
  506. const spec = {
  507. ...singleOperation({ operationId: undefined }),
  508. security: [{ bearer: [] }],
  509. components: { securitySchemes: { bearer: { type: "http", scheme: "bearer" } } },
  510. } satisfies Document
  511. const tool = toolAt(
  512. OpenAPI.fromSpec({
  513. baseUrl,
  514. spec,
  515. auth: {
  516. resolve: (context) => {
  517. contexts.push(context)
  518. return Effect.succeed({ type: "bearer", token: "secret" })
  519. },
  520. },
  521. }).tools,
  522. "getTest",
  523. )
  524. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  525. await Effect.runPromise(tool.run({}).pipe(Effect.provide(client.layer)))
  526. expect(inputTypeScript(tool)).toBe("{}")
  527. expect(client.requests[0]!.headers.authorization).toBe("Bearer secret")
  528. expect(contexts).toEqual([
  529. {
  530. name: "bearer",
  531. definition: { type: "http", scheme: "bearer" },
  532. scopes: [],
  533. operation: {
  534. operationId: undefined,
  535. method: "GET",
  536. path: "/test",
  537. summary: undefined,
  538. description: undefined,
  539. },
  540. },
  541. ])
  542. })
  543. test("applies authentication carriers without prototype or collision loss", async () => {
  544. const client = recordingClient(() => json({ ok: true }))
  545. const authenticated = (
  546. security: ReadonlyArray<Record<string, ReadonlyArray<string>>>,
  547. schemes: Record<string, unknown>,
  548. ) =>
  549. OpenAPI.fromSpec({
  550. baseUrl,
  551. spec: { ...singleOperation({}), security, components: { securitySchemes: schemes } },
  552. auth: { resolve: () => Effect.succeed({ type: "apiKey", value: "secret" }) },
  553. })
  554. const prototype = toolAt(
  555. authenticated([{ key: [] }], { key: { type: "apiKey", in: "query", name: "__proto__" } }).tools,
  556. "test",
  557. )
  558. if (!Tool.isDefinition(prototype)) throw new Error("prototype auth tool was not generated")
  559. await Effect.runPromise(prototype.run({}).pipe(Effect.provide(client.layer)))
  560. expect(new URL(client.requests[0]!.url).searchParams.get("__proto__")).toBe("secret")
  561. const duplicate = toolAt(
  562. authenticated([{ first: [], second: [] }], {
  563. first: { type: "apiKey", in: "header", name: "x-key" },
  564. second: { type: "apiKey", in: "header", name: "x-key" },
  565. }).tools,
  566. "test",
  567. )
  568. if (!Tool.isDefinition(duplicate)) throw new Error("duplicate auth tool was not generated")
  569. await expect(Effect.runPromise(duplicate.run({}).pipe(Effect.provide(client.layer)))).rejects.toThrow(
  570. "multiple credentials",
  571. )
  572. const cookie = authenticated([{ key: [] }], { key: { type: "apiKey", in: "cookie", name: "session" } })
  573. expect(cookie.tools).toEqual({})
  574. expect(cookie.skipped[0]?.reason).toBe("cookie authentication 'key' is not supported")
  575. const alternative = OpenAPI.fromSpec({
  576. baseUrl,
  577. spec: {
  578. ...singleOperation({}),
  579. security: [{ cookie: [] }, { bearer: [] }],
  580. components: {
  581. securitySchemes: {
  582. cookie: { type: "apiKey", in: "cookie", name: "session" },
  583. bearer: { type: "http", scheme: "bearer" },
  584. },
  585. },
  586. },
  587. auth: {
  588. resolve: ({ name }) => Effect.succeed(name === "bearer" ? { type: "bearer", token: "secret" } : undefined),
  589. },
  590. })
  591. const alternativeTool = toolAt(alternative.tools, "test")
  592. if (!Tool.isDefinition(alternativeTool)) throw new Error("supported auth alternative was not generated")
  593. await Effect.runPromise(alternativeTool.run({}).pipe(Effect.provide(client.layer)))
  594. expect(client.requests.at(-1)?.headers.authorization).toBe("Bearer secret")
  595. })
  596. test("honors server precedence and rejects ambiguous base URLs", async () => {
  597. const client = recordingClient(() => json({ ok: true }))
  598. const spec = {
  599. ...singleOperation({ servers: [{ url: "https://operation.example/v1" }] }),
  600. servers: [{ url: "https://document.example" }],
  601. } satisfies Document
  602. const tool = toolAt(OpenAPI.fromSpec({ spec }).tools, "test")
  603. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  604. await Effect.runPromise(tool.run({}).pipe(Effect.provide(client.layer)))
  605. expect(client.requests[0]?.url).toBe("https://operation.example/v1/test")
  606. const invalid = OpenAPI.fromSpec({ spec, baseUrl: "https://example.com/api?tenant=one" })
  607. expect(invalid.tools).toEqual({})
  608. expect(invalid.skipped[0]?.reason).toContain("unsupported query string or fragment")
  609. const malformed = OpenAPI.fromSpec({ spec, baseUrl: "https:/example.com" })
  610. expect(malformed.tools).toEqual({})
  611. expect(malformed.skipped[0]?.reason).toContain("not an absolute HTTP(S) URL")
  612. })
  613. test("resolves chained response refs before detecting unsupported transports", () => {
  614. const result = OpenAPI.fromSpec({
  615. baseUrl,
  616. spec: {
  617. ...singleOperation({ responses: { 200: { $ref: "#/components/responses/First" } } }),
  618. components: {
  619. responses: {
  620. First: { $ref: "#/components/responses/Stream" },
  621. Stream: { content: { "text/event-stream": { schema: { type: "string" } } } },
  622. },
  623. },
  624. },
  625. })
  626. expect(result.tools).toEqual({})
  627. expect(result.skipped[0]?.reason).toBe("SSE operations are not supported")
  628. })
  629. test("resolves response schemas before detecting binary output", () => {
  630. const result = OpenAPI.fromSpec({
  631. baseUrl,
  632. spec: {
  633. ...singleOperation({
  634. responses: {
  635. 200: {
  636. content: { "text/plain": { schema: { $ref: "#/components/schemas/File" } } },
  637. },
  638. },
  639. }),
  640. components: { schemas: { File: { type: "string", format: "binary" } } },
  641. },
  642. })
  643. expect(result.tools).toEqual({})
  644. expect(result.skipped[0]?.reason).toBe("binary responses are not supported")
  645. })
  646. test("validates composite parameters before resolving auth", async () => {
  647. const resolutions: Array<string> = []
  648. const client = recordingClient(() => json({ ok: true }))
  649. const tool = toolAt(
  650. OpenAPI.fromSpec({
  651. baseUrl,
  652. spec: {
  653. ...singleOperation({
  654. parameters: [{ name: "filter", in: "query", style: "form", explode: true, schema: { type: "object" } }],
  655. }),
  656. security: [{ bearer: [] }],
  657. components: { securitySchemes: { bearer: { type: "http", scheme: "bearer" } } },
  658. },
  659. auth: {
  660. resolve: ({ name }) => {
  661. resolutions.push(name)
  662. return Effect.succeed({ type: "bearer", token: "secret" })
  663. },
  664. },
  665. }).tools,
  666. "test",
  667. )
  668. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  669. await expect(
  670. Effect.runPromise(tool.run({ filter: { value: undefined } }).pipe(Effect.provide(client.layer))),
  671. ).rejects.toThrow("unsupported nested value")
  672. expect(resolutions).toEqual([])
  673. expect(client.requests).toEqual([])
  674. })
  675. test("preserves JSON media types and rejects unencodable bodies", async () => {
  676. const client = recordingClient(() => json({ ok: true }))
  677. const tool = toolAt(
  678. OpenAPI.fromSpec({
  679. baseUrl,
  680. spec: singleOperation(
  681. {
  682. requestBody: {
  683. required: true,
  684. content: { "application/merge-patch+json": { schema: { type: "object" } } },
  685. },
  686. },
  687. "post",
  688. ),
  689. }).tools,
  690. "test",
  691. )
  692. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  693. await Effect.runPromise(tool.run({ body: { name: "updated" } }).pipe(Effect.provide(client.layer)))
  694. expect(client.requests[0]!.headers["content-type"]).toBe("application/merge-patch+json")
  695. const cyclic: Record<string, unknown> = {}
  696. cyclic.self = cyclic
  697. await expect(Effect.runPromise(tool.run({ body: cyclic }).pipe(Effect.provide(client.layer)))).rejects.toThrow(
  698. "Invalid JSON body",
  699. )
  700. })
  701. test("rejects oversized and malformed JSON responses", async () => {
  702. const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec: singleOperation({}) }).tools, "test")
  703. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  704. const oversized = recordingClient(
  705. () => new Response(null, { headers: { "content-length": String(50 * 1024 * 1024 + 1) } }),
  706. )
  707. const malformed = recordingClient(() => new Response("{", { headers: { "content-type": "application/json" } }))
  708. const chunked = recordingClient(() => new Response(new Uint8Array(50 * 1024 * 1024 + 1)))
  709. await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(oversized.layer)))).rejects.toThrow(
  710. "response exceeds 50 MiB",
  711. )
  712. await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(malformed.layer)))).rejects.toThrow(
  713. "returned malformed JSON",
  714. )
  715. await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(chunked.layer)))).rejects.toThrow(
  716. "response exceeds 50 MiB",
  717. )
  718. })
  719. test("keeps non-JSON responses raw and unions every success output", async () => {
  720. const spec = singleOperation({
  721. responses: {
  722. 200: { description: "Text", content: { "text/plain": { schema: { type: "string" } } } },
  723. 204: { description: "Empty" },
  724. },
  725. })
  726. const tool = toolAt(OpenAPI.fromSpec({ baseUrl, spec }).tools, "test")
  727. if (!Tool.isDefinition(tool)) throw new Error("test was not generated")
  728. const client = recordingClient(() => new Response("123", { headers: { "content-type": "text/plain" } }))
  729. expect(outputTypeScript(tool)).toBe("string | null")
  730. await expect(Effect.runPromise(tool.run({}).pipe(Effect.provide(client.layer)))).resolves.toBe("123")
  731. })
  732. test("fails missing required parameters before auth and network", async () => {
  733. const { requests, layer } = recordingClient(() => json({}))
  734. const runtime = CodeMode.make({
  735. tools: { opencode: OpenAPI.fromSpec({ spec: await opencodeSpec(), baseUrl }).tools },
  736. })
  737. const result = await Effect.runPromise(
  738. runtime.execute("return await tools.opencode.v2.session.get({})").pipe(Effect.provide(layer)),
  739. )
  740. expect(result).toMatchObject({ ok: false })
  741. expect(JSON.stringify(result)).toContain("Missing required path parameter 'sessionID'")
  742. expect(requests).toHaveLength(0)
  743. })
  744. test("prefixes cross-location collisions and reconstructs the HTTP request", async () => {
  745. const spec = {
  746. openapi: "3.1.0",
  747. info: { title: "collision", version: "1.0.0" },
  748. paths: {
  749. "/echo": {
  750. post: {
  751. operationId: "echo",
  752. requestBody: {
  753. required: true,
  754. content: { "application/json": { schema: { type: "string" } } },
  755. },
  756. responses: { "204": { description: "Echoed" } },
  757. },
  758. },
  759. "/things/{id}": {
  760. post: {
  761. operationId: "things.update",
  762. parameters: [
  763. { name: "id", in: "path", required: true, schema: { type: "string" } },
  764. { name: "id", in: "query", required: true, schema: { type: "string" } },
  765. { name: "path_id", in: "query", schema: { type: "string" } },
  766. { name: "id", in: "header", required: true, schema: { type: "string" } },
  767. ],
  768. requestBody: {
  769. required: true,
  770. content: {
  771. "application/json": {
  772. schema: {
  773. type: "object",
  774. properties: { id: { type: "string" } },
  775. required: ["id"],
  776. additionalProperties: false,
  777. },
  778. },
  779. },
  780. },
  781. responses: { "204": { description: "Updated" } },
  782. },
  783. },
  784. },
  785. } satisfies Document
  786. const { requests, layer } = recordingClient(() => new Response(null, { status: 204 }))
  787. const tools = OpenAPI.fromSpec({ spec, baseUrl }).tools
  788. const update = toolAt(tools, "things.update")
  789. const echo = toolAt(tools, "echo")
  790. expect(Tool.isDefinition(update)).toBe(true)
  791. if (!Tool.isDefinition(update)) throw new Error("things.update was not generated")
  792. expect(inputTypeScript(update)).toBe(
  793. "{ path_id: string; query_id: string; path_id_2?: string; header_id: string; body_id: string }",
  794. )
  795. expect(Tool.isDefinition(echo)).toBe(true)
  796. if (!Tool.isDefinition(echo)) throw new Error("echo was not generated")
  797. expect(inputTypeScript(echo)).toBe("{ body: string }")
  798. const runtime = CodeMode.make({ tools })
  799. const result = await Effect.runPromise(
  800. runtime
  801. .execute(
  802. `
  803. const updated = await tools.things.update({ path_id: "path", query_id: "query", path_id_2: "literal", header_id: "header", body_id: "body" })
  804. const echoed = await tools.echo({ body: "hello" })
  805. return { updated, echoed }
  806. `,
  807. )
  808. .pipe(Effect.provide(layer)),
  809. )
  810. expect(result).toMatchObject({ ok: true })
  811. expect(requests).toHaveLength(2)
  812. expect(new URL(requests[0]!.url).pathname).toBe("/things/path")
  813. expect(new URL(requests[0]!.url).searchParams.get("id")).toBe("query")
  814. expect(new URL(requests[0]!.url).searchParams.get("path_id")).toBe("literal")
  815. expect(requests[0]!.headers.id).toBe("header")
  816. expect(requests[0]!.body).toStrictEqual({ id: "body" })
  817. expect(requests[1]!.body).toBe("hello")
  818. })
  819. test("keeps bodies nested when flattening would lose schema semantics", () => {
  820. const body = (schema: Record<string, unknown>, required = true) => ({
  821. required,
  822. content: { "application/json": { schema } },
  823. })
  824. const spec = {
  825. openapi: "3.1.0",
  826. info: { title: "bodies", version: "1.0.0" },
  827. paths: Object.fromEntries(
  828. [
  829. [
  830. "optional",
  831. body(
  832. {
  833. type: "object",
  834. properties: { name: { type: "string" } },
  835. required: ["name"],
  836. additionalProperties: false,
  837. },
  838. false,
  839. ),
  840. ],
  841. ["dictionary", body({ type: "object", additionalProperties: { type: "string" } })],
  842. [
  843. "composed",
  844. body({
  845. type: "object",
  846. allOf: [{ type: "object", properties: { name: { type: "string" } }, required: ["name"] }],
  847. additionalProperties: false,
  848. }),
  849. ],
  850. [
  851. "nullable",
  852. body({
  853. type: ["object", "null"],
  854. properties: { name: { type: "string" } },
  855. additionalProperties: false,
  856. }),
  857. ],
  858. ].map(([name, requestBody]) => [
  859. `/body/${name}`,
  860. {
  861. post: {
  862. operationId: `body.${name}`,
  863. requestBody,
  864. responses: { "204": { description: "Accepted" } },
  865. },
  866. },
  867. ]),
  868. ),
  869. } satisfies Document
  870. const tools = OpenAPI.fromSpec({ spec, baseUrl }).tools
  871. for (const name of ["optional", "dictionary", "composed", "nullable"]) {
  872. const tool = toolAt(tools, `body.${name}`)
  873. expect(Tool.isDefinition(tool)).toBe(true)
  874. if (!Tool.isDefinition(tool)) throw new Error(`body.${name} was not generated`)
  875. const input = isRecord(tool.input) ? tool.input : {}
  876. expect(Object.keys(isRecord(input.properties) ? input.properties : {})).toStrictEqual(["body"])
  877. }
  878. const optional = toolAt(tools, "body.optional")
  879. if (!Tool.isDefinition(optional)) throw new Error("body.optional was not generated")
  880. expect(inputTypeScript(optional)).toBe("{ body?: { name: string } }")
  881. })
  882. })