import { type ApiDocument, type ApiOperation, endpoint, errorBlock, failureResponses, metaBlock, operationBlock, referencedTypes, requiredSchemes, typeBlock, } from "@docspack/lapis"; import { codeSamples } from "./samples.js"; /** * The digest — everything needed to call one endpoint, and nothing else. * * This is the artifact the AI half of OpenAPI support comes down to. An agent that has decided it * needs `POST /v1/invoices` needs six things and no more: the base URL, how to authenticate, the * inputs with their types, the body shape, what comes back, and what can go wrong. A whole * OpenAPI document contains all six, surrounded by thousands of operations' worth of everything * else; a page of prose about invoicing usually contains two of them. * * So the digest is assembled per operation and carries exactly the types that operation reaches. * It is LAPIS notation, which is an existing open format for describing an API to a model — see * `lapis.ts` for why that rather than a notation invented here. * * The one thing included that is not strictly necessary is the cURL line. It is the difference * between a description of a request and a request, it costs around 40 tokens, and it is * generated by the same builder the console sends with, so it cannot be wrong in a way the page * is right. */ export interface DigestOptions { /** Include the cURL line. On by default. */ readonly example?: boolean; /** Token budget for the `[types]` section. Defaults to `DEFAULT_TYPE_TOKENS`. */ readonly maxTokens?: number; } export function operationDigest( document: ApiDocument, operation: ApiOperation, options: DigestOptions = {}, ): string { const sections: string[] = []; // The prose first, unfenced, because it is the part a ranker indexes: a reader asking "how do I // refund a payment" matches the sentence, and the notation answers them once it has. const prose = describe(operation); if (prose.length > 0) sections.push(prose); const schemes = requiredSchemes(document, operation); const { types, omitted } = referencedTypes(document, operation, options); const errors = errorBlock(failureResponses(operation)); const blocks = [ metaBlock(document, schemes), ["[ops]", operationBlock(document, operation)].join("\n"), ...(types.length === 0 ? [] : [ [ "[types]", types.map(typeBlock).join("\n\n"), // Naming what did not fit, because "there is more to this shape" and "this is the whole // shape" are different claims and a digest that made the wrong one would have an agent // confidently sending an object missing half its fields. ...(omitted.length === 0 ? [] : [`# not expanded here: ${omitted.join(", ")}`]), ].join("\n"), ]), ...(errors.length === 0 ? [] : [errors]), ]; // A fence, so that a model reading the answer can tell the notation from the prose around it, // and so the `lapis` tag names what it is reading. The notation is whitespace-significant and // an unfenced block is the kind of thing a renderer reflows. sections.push(["```lapis", blocks.join("\n\n"), "```"].join("\n")); if (options.example !== false) { const curl = codeSamples(document, operation).find((sample) => sample.language === "curl"); if (curl !== undefined) sections.push(["```bash", curl.code, "```"].join("\n")); } if (operation.deprecated) sections.push("DEPRECATED: this operation is marked deprecated."); return sections.join("\n\n"); } /** * The operation's prose, deduplicated. * * OpenAPI's convention is that `summary` is the short form of `description`, and generated * documents routinely set them to the same string. Printing both would spend the budget saying * one thing twice, and the notation block already carries the summary on its own line. */ function describe(operation: ApiOperation): string { const { summary, description } = operation; if (description.length === 0) return ""; if (summary.length > 0 && description.startsWith(summary)) { return description.slice(summary.length).trim(); } return description; } /** * What the chunk carrying a digest is called. * * The endpoint comes first because that is what an agent searches for — a method and a path are * how an API is referred to everywhere else — and the summary follows for a human reading a table * of contents. */ export function operationTitle(operation: ApiOperation): string { const summary = operation.summary.replace(/\s+/g, " ").trim(); return summary.length === 0 ? endpoint(operation) : `${endpoint(operation)} — ${summary}`; } /** * The names this operation answers to, for exact lookup rather than ranking. * * Both spellings are recorded because both are how someone refers to an endpoint: the method and * path from a network tab or a log line, the operation id from a generated client. Ranking either * one as prose is the mistake `search.ts` already documents for exported symbols — a path segment * like `/v1/charges` appears in every chunk about charges, so a query naming it matches the * overview page ahead of the operation. */ export function operationEntities(operation: ApiOperation): readonly string[] { return [...new Set([endpoint(operation), operation.id])]; } /** * Search terms for an operation's chunk. * * The method, its tags, and the non-template segments of the path. Template segments are dropped: * `{invoice_id}` is a placeholder name, and indexing it means a search for `invoice` ranks every * endpoint that takes one. */ export function operationTags(operation: ApiOperation): readonly string[] { return [ ...new Set([ operation.method.toLowerCase(), ...operation.tags, ...operation.path.split("/").filter((part) => part.length > 0 && !part.startsWith("{")), ]), ]; }