From 658e7c0ff3d8fb4b0898a04fb54c3bc42aaa7138 Mon Sep 17 00:00:00 2001 From: Jordan Jensen Date: Tue, 10 Nov 2026 16:33:36 -0800 Subject: [PATCH 1/4] fix: keep field tables in llms-txt output and name composed types Quarto builds `.llms.md` with Pandoc's GFM writer, which writes `[TABLE]` for any table with block content in a cell. Description cells are now one paragraph: paragraphs and attributes are spans the stylesheet lays out as lines, and lists or code blocks move to a note under the table. `anyOf`/`oneOf` properties are typed by their alternatives (`Owner|null`) instead of `unknown`, and a nullable reference to an object lists the object's properties, with a guard against recursive schemas. Closes #24 Closes #37 Co-Authored-By: Claude Opus 5.5 --- README.md | 17 ++ _extensions/quarto-openapi/lib/fields.ts | 125 ++++++++ _extensions/quarto-openapi/lib/markdown.ts | 5 +- _extensions/quarto-openapi/lib/schema.ts | 268 +++++++++--------- _extensions/quarto-openapi/lib/sections.ts | 21 +- .../quarto-openapi/quarto-openapi-styles.css | 15 + .../posit-dev/quarto-openapi/lib/fields.ts | 125 ++++++++ .../posit-dev/quarto-openapi/lib/markdown.ts | 5 +- .../posit-dev/quarto-openapi/lib/schema.ts | 268 +++++++++--------- .../posit-dev/quarto-openapi/lib/sections.ts | 21 +- .../quarto-openapi/quarto-openapi-styles.css | 15 + tests/fields_test.ts | 127 +++++++++ tests/markdown_test.ts | 8 + tests/quarto_render_test.ts | 71 +++++ tests/schema_test.ts | 96 +++++++ 15 files changed, 903 insertions(+), 284 deletions(-) create mode 100644 _extensions/quarto-openapi/lib/fields.ts create mode 100644 example/_extensions/posit-dev/quarto-openapi/lib/fields.ts create mode 100644 tests/fields_test.ts diff --git a/README.md b/README.md index 62742c7..010dbb7 100644 --- a/README.md +++ b/README.md @@ -126,8 +126,24 @@ Schema tables handle: - Nested objects: flattened as indented dotted rows (e.g., `owner.guid`) - Arrays of objects: expanded inline with their properties - `allOf` composition: merged into a single property table +- `anyOf`/`oneOf` composition: typed by the alternatives' names joined with `|` + (`Owner|null`, `Cat|Dog`); a nullable reference to an object also lists the + object's properties - Property attributes: required, read-only, nullable, default, minimum/maximum, enum, example, format +### Field tables and `llms-txt` + +Quarto builds each `.llms.md` page from the rendered HTML with Pandoc's GFM +writer. A GFM table cell holds inline content only, so Pandoc writes `[TABLE]` +in place of any table with a paragraph break, list or line break in a cell. + +To keep every table, each Description cell is a single paragraph. A +description's paragraphs and the field's attributes become spans that the +extension's stylesheet lays out as separate lines, so the HTML reads as +paragraphs and the GFM conversion sees one. Content that cannot be inline, such +as a list or a code block, is listed under the table with the field's name, and +the cell says "Continued below the table." + ## Project structure ```text @@ -143,6 +159,7 @@ quarto-openapi/ refs.ts # $ref resolution sections.ts # path grouping and endpoint rendering schema.ts # schema-to-table conversion + fields.ts # Name/Type/Description field tables markdown.ts # list table and markdown utilities escape.ts # makes description prose safe as markdown tests/ # node:test suites for lib/ diff --git a/_extensions/quarto-openapi/lib/fields.ts b/_extensions/quarto-openapi/lib/fields.ts new file mode 100644 index 0000000..c3e89fe --- /dev/null +++ b/_extensions/quarto-openapi/lib/fields.ts @@ -0,0 +1,125 @@ +/** + * Field tables: the Name / Type / Description tables for parameters and schema + * properties. + * + * Every Description cell is a single paragraph of inline content. Quarto + * builds `.llms.md` from the rendered HTML with `pandoc -t gfm-raw_html`, and a + * GFM pipe table can only hold inline content. One cell with block content (a + * second paragraph, a list, a line break) makes Pandoc write `[TABLE]` in place + * of the whole table. + * + * So a description's paragraphs, and the field's attributes, become spans that + * the stylesheet displays as blocks: the HTML reads as before, and the GFM + * conversion sees one paragraph. Content that cannot be a span, such as a list + * or a code block, moves to a note under the table, which the cell points to. + */ + +import MarkdownIt from "markdown-it"; +import type { Token } from "markdown-it"; +import { listTable, type TableRow } from "./markdown.ts"; + +/** CommonMark, matching the parser that escapes descriptions. */ +const md = new MarkdownIt("commonmark"); + +export interface FieldRow { + /** The field's name, dotted for nested properties (`owner.guid`). */ + name: string; + /** Nesting level; 0 for top-level fields. */ + depth: number; + /** The type label, without code formatting. */ + type: string; + /** The field's description as markdown, possibly empty. */ + description: string; + /** Attribute sentences such as "Required. Example: `x`.", possibly empty. */ + attributes: string; +} + +/** A description split into what fits in a table cell and what does not. */ +interface SplitDescription { + /** Leading paragraphs, each as one line of inline markdown. */ + paragraphs: string[]; + /** Markdown source from the first block that cannot be inline, or "". */ + rest: string; +} + +/** Whether a top-level paragraph renders as inline content only. */ +function isInlineParagraph(inline: Token | undefined): boolean { + return !(inline?.children ?? []).some((t) => t.type === "hardbreak"); +} + +function splitDescription(description: string): SplitDescription { + const text = description.trim(); + const tokens = md.parse(text, {}); + const lines = text.split("\n"); + const paragraphs: string[] = []; + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + if (token.level !== 0 || token.nesting === -1) continue; + if (token.type === "paragraph_open" && isInlineParagraph(tokens[i + 1])) { + paragraphs.push( + tokens[i + 1].content + .split("\n") + .map((line) => line.trim()) + .join(" "), + ); + continue; + } + const start = token.map?.[0] ?? lines.length; + return { paragraphs, rest: lines.slice(start).join("\n").trim() }; + } + return { paragraphs, rest: "" }; +} + +function descriptionCell( + split: SplitDescription, + attributes: string, +): string { + const blocks = [...split.paragraphs]; + if (split.rest) blocks.push("Continued below the table."); + const parts = + blocks.length === 1 && !attributes + ? blocks + : blocks.map((p) => `[${p}]{.schema-para}`); + if (attributes) parts.push(`[${attributes}]{.schema-attrs}`); + return parts.join(" "); +} + +function nameCell(row: FieldRow): string { + return row.depth > 0 + ? `[\`${row.name}\`]{.schema-nest-${row.depth}}` + : `\`${row.name}\``; +} + +/** + * Render rows as a field table, followed by a note for each row whose + * description holds block content. + */ +export function fieldTable(rows: FieldRow[]): string[] { + if (rows.length === 0) return []; + + const notes: string[] = []; + const tableRows: TableRow[] = rows.map((row) => { + const split = splitDescription(row.description); + if (split.rest) { + notes.push(`- \`${row.name}\`:`, ""); + for (const line of split.rest.split("\n")) { + notes.push(line === "" ? "" : ` ${line}`); + } + notes.push(""); + } + return { + cells: [ + nameCell(row), + `\`${row.type}\``, + descriptionCell(split, row.attributes), + ], + }; + }); + + const lines = listTable(["Name", "Type", "Description"], tableRows); + if (notes.length > 0) { + lines.push("", "::: {.schema-notes}", "", ...notes, ":::"); + } + return lines; +} diff --git a/_extensions/quarto-openapi/lib/markdown.ts b/_extensions/quarto-openapi/lib/markdown.ts index 4c1bdbc..e03c71c 100644 --- a/_extensions/quarto-openapi/lib/markdown.ts +++ b/_extensions/quarto-openapi/lib/markdown.ts @@ -74,8 +74,9 @@ export function listTable(headers: string[], rows: TableRow[]): string[] { lines.push(""); const emitGroup = (cellLines: string[][]) => { - // Loose when any cell holds more than one block. - const loose = cellLines.some((cl) => cl.some((line) => line === "")); + // Loose when any cell holds more than one block. An empty cell is one + // empty line, not a block separator. + const loose = cellLines.some((cl) => cl.length > 1 && cl.includes("")); cellLines.forEach((cl, col) => { if (loose && col > 0) lines.push(""); lines.push((col === 0 ? "* * " : " * ") + cl[0]); diff --git a/_extensions/quarto-openapi/lib/schema.ts b/_extensions/quarto-openapi/lib/schema.ts index 68fb0a4..b3cee7c 100644 --- a/_extensions/quarto-openapi/lib/schema.ts +++ b/_extensions/quarto-openapi/lib/schema.ts @@ -9,13 +9,7 @@ import type { Schema, Reference } from "./types.ts"; import { isReference } from "./types.ts"; import type { OpenAPISpec } from "./types.ts"; import { resolve } from "./refs.ts"; -import { listTable, type TableRow } from "./markdown.ts"; - -interface PropertyRow { - name: string; - type: string; - description: string; -} +import { fieldTable, type FieldRow } from "./fields.ts"; /** * Render a schema as markdown lines (description + property table). @@ -56,7 +50,7 @@ export function renderSchema( // Primitive type if (type) { - lines.push(formatPrimitiveType(resolved)); + lines.push(formatPrimitiveType(spec, resolved)); } return lines; @@ -121,7 +115,7 @@ function renderArray( lines.push(""); lines.push(...renderSchema(spec, items)); } else { - const itemType = formatPrimitiveType(items); + const itemType = formatPrimitiveType(spec, items); lines.push(`Array of ${itemType}`); } @@ -150,7 +144,7 @@ function renderMap( lines.push(""); lines.push(...renderSchema(spec, valueSchema)); } else { - lines.push(`Map of string to ${formatPrimitiveType(valueSchema)}`); + lines.push(`Map of string to ${formatPrimitiveType(spec, valueSchema)}`); } return lines; } @@ -165,37 +159,74 @@ function renderObject( return lines; } - const rows = flattenProperties(spec, schema.properties, schema.required, ""); - if (rows.length === 0) return lines; + const rows = flattenProperties( + spec, + schema.properties, + schema.required, + "", + 0, + new Set([schema]), + ); + lines.push(...fieldTable(rows)); + return lines; +} - const tableRows: TableRow[] = rows.map((row) => ({ - cells: [row.name, row.type, row.description], - })); +/** Whether a schema describes an object whose properties can be listed. */ +function isObjectLike(schema: Schema): boolean { + return schema.type === "object" || !!schema.properties || !!schema.allOf; +} - lines.push(...listTable(["Name", "Type", "Description"], tableRows)); - return lines; +/** The properties of an object-like schema, with `allOf` merged. */ +function objectFields(spec: OpenAPISpec, schema: Schema): Schema { + return schema.allOf ? mergeAllOf(spec, schema.allOf) : schema; } /** * Flatten object properties into rows, recursing into nested objects - * with indented dotted path names. + * with dotted path names. + * + * `ancestors` holds the schemas being expanded on the way here. A property + * whose schema is already among them gets its own row but no child rows, so a + * recursive schema renders once instead of forever. */ function flattenProperties( spec: OpenAPISpec, properties: Record, - required?: string[], - prefix: string = "", - depth: number = 0, -): PropertyRow[] { - const rows: PropertyRow[] = []; + required: string[] | undefined, + prefix: string, + depth: number, + ancestors: ReadonlySet, +): FieldRow[] { + const rows: FieldRow[] = []; const requiredSet = new Set(required || []); + /** Rows for the properties of `schema`, nested under `path`. */ + const children = (schema: Schema, path: string): FieldRow[] => { + if (ancestors.has(schema)) return []; + const fields = objectFields(spec, schema); + if (!fields.properties) return []; + return flattenProperties( + spec, + fields.properties, + fields.required, + path, + depth + 1, + new Set([...ancestors, schema]), + ); + }; + for (const [name, prop] of Object.entries(properties)) { const resolved = isReference(prop) ? resolve(spec, prop) : prop; const displayName = prefix ? `${prefix}.${name}` : name; - const nameCell = depth > 0 - ? `[\`${displayName}\`]{.schema-nest-${depth}}` - : `\`${displayName}\``; + const row = (type: string, attributes: string): FieldRow => ({ + name: displayName, + depth, + type, + description: resolved.description?.trim() ?? "", + attributes, + }); + const attributes = attributesOf(resolved, requiredSet.has(name)); + const alternative = soleAlternative(spec, resolved); if ( (resolved.type === "object" || resolved.properties) && @@ -203,68 +234,31 @@ function flattenProperties( !resolved.allOf ) { // Nested object: emit a row for the object itself, then recurse - rows.push({ - name: nameCell, - type: "`object`", - description: resolved.description || "", - }); - rows.push( - ...flattenProperties( - spec, - resolved.properties, - resolved.required, - displayName, - depth + 1, - ), - ); + rows.push(row("object", "")); + rows.push(...children(resolved, displayName)); } else if (resolved.allOf) { const merged = mergeAllOf(spec, resolved.allOf); rows.push({ - name: nameCell, - type: "`object`", - description: resolved.description || merged.description || "", + ...row("object", ""), + description: + (resolved.description || merged.description || "").trim(), }); - if (merged.properties) { - rows.push( - ...flattenProperties( - spec, - merged.properties, - merged.required, - displayName, - depth + 1, - ), - ); - } + rows.push(...children(resolved, displayName)); + } else if (alternative && isObjectLike(alternative)) { + // A nullable reference, `anyOf: [{ $ref }, { nullable: true }]`: list + // the referenced object's properties as if it were a nested object. + rows.push(row(formatTypeString(spec, resolved), attributes)); + rows.push(...children(alternative, displayName)); } else if (resolved.type === "array" && resolved.items) { const items = isReference(resolved.items) ? resolve(spec, resolved.items) : resolved.items; - if (items.type === "object" || items.properties || items.allOf) { - rows.push({ - name: nameCell, - type: "`[object]`", - description: buildDescription(resolved, requiredSet.has(name)), - }); - const effective = items.allOf ? mergeAllOf(spec, items.allOf) : items; - if (effective.properties) { - rows.push( - ...flattenProperties( - spec, - effective.properties, - effective.required, - `${displayName}[]`, - depth + 1, - ), - ); - } + if (isObjectLike(items)) { + rows.push(row("[object]", attributes)); + rows.push(...children(items, `${displayName}[]`)); } else { - const itemType = items.type || "unknown"; - rows.push({ - name: nameCell, - type: `\`[${itemType}]\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); + rows.push(row(`[${typeLabel(spec, items)}]`, attributes)); } } else if ( !resolved.properties && @@ -274,40 +268,15 @@ function flattenProperties( // Typed map: additionalProperties is a schema, $ref, or `true`. const ap = resolved.additionalProperties; const valueType = mapValueTypeLabel(spec, ap); - rows.push({ - name: nameCell, - type: `\`map[string, ${valueType}]\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); + rows.push(row(`map[string, ${valueType}]`, attributes)); if (ap !== true) { const valueSchema = isReference(ap) ? resolve(spec, ap) : ap; - if ( - valueSchema.type === "object" || - valueSchema.properties || - valueSchema.allOf - ) { - const effective = valueSchema.allOf - ? mergeAllOf(spec, valueSchema.allOf) - : valueSchema; - if (effective.properties) { - rows.push( - ...flattenProperties( - spec, - effective.properties, - effective.required, - `${displayName}{}`, - depth + 1, - ), - ); - } + if (isObjectLike(valueSchema)) { + rows.push(...children(valueSchema, `${displayName}{}`)); } } } else { - rows.push({ - name: nameCell, - type: `\`${formatTypeString(resolved)}\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); + rows.push(row(formatTypeString(spec, resolved), attributes)); } } @@ -315,15 +284,10 @@ function flattenProperties( } /** - * Build a description string including property attributes. + * The attribute sentences shown after a field's description, such as + * "Required. Example: `x`.", or "" when the field has none. */ -function buildDescription(schema: Schema, isRequired: boolean): string { - const parts: string[] = []; - - if (schema.description) { - parts.push(schema.description.trim()); - } - +function attributesOf(schema: Schema, isRequired: boolean): string { const attrs: string[] = []; if (isRequired) attrs.push("Required"); if (schema.readOnly) attrs.push("Read-only"); @@ -339,12 +303,7 @@ function buildDescription(schema: Schema, isRequired: boolean): string { if (schema.example !== undefined) attrs.push(`Example: \`${formatValue(schema.example)}\``); - if (attrs.length > 0) { - if (parts.length > 0) parts.push(""); - parts.push(attrs.join(". ") + "."); - } - - return parts.join("\n"); + return attrs.length > 0 ? attrs.join(". ") + "." : ""; } const semanticFormats = new Set(["date-time", "date", "time", "duration", "uuid", "uri", "uri-reference", "email", "hostname", "ipv4", "ipv6", "byte", "binary", "password"]); @@ -356,27 +315,82 @@ function mapValueTypeLabel( if (value === true) return "any"; if (value === false) return "object"; if (isReference(value)) { - return value.$ref.split("/").pop() || "object"; + return refName(value); } if (value.type === "object" || value.properties || value.allOf) return "object"; return value.type || "object"; } -function formatTypeString(schema: Schema): string { - let type = schema.type || "unknown"; +function refName(ref: Reference): string { + return ref.$ref.split("/").pop() || "object"; +} + +/** + * Whether a schema only marks its parent as nullable, like the second member + * of `anyOf: [{ $ref }, { nullable: true }]`. + */ +function isNullMarker(schema: Schema | Reference): boolean { + if (isReference(schema)) return false; + if (schema.type === "null") return true; + return ( + schema.nullable === true && + Object.keys(schema).every((k) => k === "nullable" || k === "description") + ); +} + +/** + * The one schema an `anyOf` or `oneOf` allows besides null, or undefined when + * there is no such composition or it has more than one alternative. + */ +function soleAlternative(spec: OpenAPISpec, schema: Schema): Schema | undefined { + const members = schema.anyOf ?? schema.oneOf; + if (!members) return undefined; + const alternatives = members.filter((m) => !isNullMarker(m)); + if (alternatives.length !== 1) return undefined; + const [only] = alternatives; + return isReference(only) ? resolve(spec, only) : only; +} + +/** + * A short name for the type a schema allows: the schema name for a `$ref`, + * the alternatives joined by `|` for `anyOf`/`oneOf`, and `any` for a schema + * that does not constrain the type. + */ +function typeLabel(spec: OpenAPISpec, schema: Schema | Reference): string { + if (isReference(schema)) return refName(schema); + if (schema.type) return schema.type; + if (schema.allOf) { + return schema.allOf.length === 1 + ? typeLabel(spec, schema.allOf[0]) + : "object"; + } + const members = schema.anyOf ?? schema.oneOf; + if (members) { + const labels = members.map((m) => + isNullMarker(m) ? "null" : typeLabel(spec, m), + ); + return [...new Set(labels)].join("|"); + } + if (schema.properties || schema.additionalProperties) return "object"; + if (schema.items) return "array"; + return "any"; +} + +function formatTypeString(spec: OpenAPISpec, schema: Schema): string { + let type = typeLabel(spec, schema); if (schema.format && semanticFormats.has(schema.format)) { type = `${type} (${schema.format})`; } - if (schema.nullable) { + if (schema.nullable && !type.split("|").includes("null")) { type = `${type}|null`; } return type; } -function formatPrimitiveType(schema: Schema): string { - const parts = [schema.type || "unknown"]; +function formatPrimitiveType(spec: OpenAPISpec, schema: Schema): string { + const parts = [typeLabel(spec, schema)]; if (schema.format && semanticFormats.has(schema.format)) parts.push(`(${schema.format})`); return parts.join(" "); } diff --git a/_extensions/quarto-openapi/lib/sections.ts b/_extensions/quarto-openapi/lib/sections.ts index de10ce7..87054dd 100644 --- a/_extensions/quarto-openapi/lib/sections.ts +++ b/_extensions/quarto-openapi/lib/sections.ts @@ -23,9 +23,8 @@ import { heading, methodBadge, pathToAnchor, - listTable, - type TableRow, } from "./markdown.ts"; +import { fieldTable, type FieldRow } from "./fields.ts"; export interface Section { /** Resource name, e.g., "content", "bundles" */ @@ -523,7 +522,7 @@ function renderParameters( lines.push(""); } - const rows: TableRow[] = params.map((param) => { + const rows: FieldRow[] = params.map((param) => { const schema = param.schema ? resolve(spec, param.schema) : undefined; @@ -533,20 +532,16 @@ function renderParameters( if (schema?.format) typeParts.push(`(${schema.format})`); const typeStr = typeParts.length > 0 ? typeParts.join(" ") : "string"; - const descParts: string[] = []; - if (param.description) descParts.push(param.description.trim()); - if (param.required) descParts.push("Required."); - return { - cells: [ - `\`${param.name}\``, - `\`${typeStr}\``, - descParts.join(" "), - ], + name: param.name, + depth: 0, + type: typeStr, + description: param.description?.trim() ?? "", + attributes: param.required ? "Required." : "", }; }); - lines.push(...listTable(["Name", "Type", "Description"], rows)); + lines.push(...fieldTable(rows)); lines.push(""); } diff --git a/_extensions/quarto-openapi/quarto-openapi-styles.css b/_extensions/quarto-openapi/quarto-openapi-styles.css index ee9e97e..530a463 100644 --- a/_extensions/quarto-openapi/quarto-openapi-styles.css +++ b/_extensions/quarto-openapi/quarto-openapi-styles.css @@ -26,3 +26,18 @@ .schema-nest-2 { padding-left: 2em; } .schema-nest-3 { padding-left: 3em; } .schema-nest-4 { padding-left: 4em; } + +/* + * Field descriptions are one paragraph of spans, so that `.llms.md` can keep + * the table (see lib/fields.ts). These spans lay out as the paragraphs they + * stand for. + */ +.schema-para, +.schema-attrs { + display: block; +} + +.schema-para + .schema-para, +.schema-para + .schema-attrs { + margin-top: 0.5em; +} diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/fields.ts b/example/_extensions/posit-dev/quarto-openapi/lib/fields.ts new file mode 100644 index 0000000..c3e89fe --- /dev/null +++ b/example/_extensions/posit-dev/quarto-openapi/lib/fields.ts @@ -0,0 +1,125 @@ +/** + * Field tables: the Name / Type / Description tables for parameters and schema + * properties. + * + * Every Description cell is a single paragraph of inline content. Quarto + * builds `.llms.md` from the rendered HTML with `pandoc -t gfm-raw_html`, and a + * GFM pipe table can only hold inline content. One cell with block content (a + * second paragraph, a list, a line break) makes Pandoc write `[TABLE]` in place + * of the whole table. + * + * So a description's paragraphs, and the field's attributes, become spans that + * the stylesheet displays as blocks: the HTML reads as before, and the GFM + * conversion sees one paragraph. Content that cannot be a span, such as a list + * or a code block, moves to a note under the table, which the cell points to. + */ + +import MarkdownIt from "markdown-it"; +import type { Token } from "markdown-it"; +import { listTable, type TableRow } from "./markdown.ts"; + +/** CommonMark, matching the parser that escapes descriptions. */ +const md = new MarkdownIt("commonmark"); + +export interface FieldRow { + /** The field's name, dotted for nested properties (`owner.guid`). */ + name: string; + /** Nesting level; 0 for top-level fields. */ + depth: number; + /** The type label, without code formatting. */ + type: string; + /** The field's description as markdown, possibly empty. */ + description: string; + /** Attribute sentences such as "Required. Example: `x`.", possibly empty. */ + attributes: string; +} + +/** A description split into what fits in a table cell and what does not. */ +interface SplitDescription { + /** Leading paragraphs, each as one line of inline markdown. */ + paragraphs: string[]; + /** Markdown source from the first block that cannot be inline, or "". */ + rest: string; +} + +/** Whether a top-level paragraph renders as inline content only. */ +function isInlineParagraph(inline: Token | undefined): boolean { + return !(inline?.children ?? []).some((t) => t.type === "hardbreak"); +} + +function splitDescription(description: string): SplitDescription { + const text = description.trim(); + const tokens = md.parse(text, {}); + const lines = text.split("\n"); + const paragraphs: string[] = []; + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + if (token.level !== 0 || token.nesting === -1) continue; + if (token.type === "paragraph_open" && isInlineParagraph(tokens[i + 1])) { + paragraphs.push( + tokens[i + 1].content + .split("\n") + .map((line) => line.trim()) + .join(" "), + ); + continue; + } + const start = token.map?.[0] ?? lines.length; + return { paragraphs, rest: lines.slice(start).join("\n").trim() }; + } + return { paragraphs, rest: "" }; +} + +function descriptionCell( + split: SplitDescription, + attributes: string, +): string { + const blocks = [...split.paragraphs]; + if (split.rest) blocks.push("Continued below the table."); + const parts = + blocks.length === 1 && !attributes + ? blocks + : blocks.map((p) => `[${p}]{.schema-para}`); + if (attributes) parts.push(`[${attributes}]{.schema-attrs}`); + return parts.join(" "); +} + +function nameCell(row: FieldRow): string { + return row.depth > 0 + ? `[\`${row.name}\`]{.schema-nest-${row.depth}}` + : `\`${row.name}\``; +} + +/** + * Render rows as a field table, followed by a note for each row whose + * description holds block content. + */ +export function fieldTable(rows: FieldRow[]): string[] { + if (rows.length === 0) return []; + + const notes: string[] = []; + const tableRows: TableRow[] = rows.map((row) => { + const split = splitDescription(row.description); + if (split.rest) { + notes.push(`- \`${row.name}\`:`, ""); + for (const line of split.rest.split("\n")) { + notes.push(line === "" ? "" : ` ${line}`); + } + notes.push(""); + } + return { + cells: [ + nameCell(row), + `\`${row.type}\``, + descriptionCell(split, row.attributes), + ], + }; + }); + + const lines = listTable(["Name", "Type", "Description"], tableRows); + if (notes.length > 0) { + lines.push("", "::: {.schema-notes}", "", ...notes, ":::"); + } + return lines; +} diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/markdown.ts b/example/_extensions/posit-dev/quarto-openapi/lib/markdown.ts index 4c1bdbc..e03c71c 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/markdown.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/markdown.ts @@ -74,8 +74,9 @@ export function listTable(headers: string[], rows: TableRow[]): string[] { lines.push(""); const emitGroup = (cellLines: string[][]) => { - // Loose when any cell holds more than one block. - const loose = cellLines.some((cl) => cl.some((line) => line === "")); + // Loose when any cell holds more than one block. An empty cell is one + // empty line, not a block separator. + const loose = cellLines.some((cl) => cl.length > 1 && cl.includes("")); cellLines.forEach((cl, col) => { if (loose && col > 0) lines.push(""); lines.push((col === 0 ? "* * " : " * ") + cl[0]); diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts b/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts index 68fb0a4..b3cee7c 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts @@ -9,13 +9,7 @@ import type { Schema, Reference } from "./types.ts"; import { isReference } from "./types.ts"; import type { OpenAPISpec } from "./types.ts"; import { resolve } from "./refs.ts"; -import { listTable, type TableRow } from "./markdown.ts"; - -interface PropertyRow { - name: string; - type: string; - description: string; -} +import { fieldTable, type FieldRow } from "./fields.ts"; /** * Render a schema as markdown lines (description + property table). @@ -56,7 +50,7 @@ export function renderSchema( // Primitive type if (type) { - lines.push(formatPrimitiveType(resolved)); + lines.push(formatPrimitiveType(spec, resolved)); } return lines; @@ -121,7 +115,7 @@ function renderArray( lines.push(""); lines.push(...renderSchema(spec, items)); } else { - const itemType = formatPrimitiveType(items); + const itemType = formatPrimitiveType(spec, items); lines.push(`Array of ${itemType}`); } @@ -150,7 +144,7 @@ function renderMap( lines.push(""); lines.push(...renderSchema(spec, valueSchema)); } else { - lines.push(`Map of string to ${formatPrimitiveType(valueSchema)}`); + lines.push(`Map of string to ${formatPrimitiveType(spec, valueSchema)}`); } return lines; } @@ -165,37 +159,74 @@ function renderObject( return lines; } - const rows = flattenProperties(spec, schema.properties, schema.required, ""); - if (rows.length === 0) return lines; + const rows = flattenProperties( + spec, + schema.properties, + schema.required, + "", + 0, + new Set([schema]), + ); + lines.push(...fieldTable(rows)); + return lines; +} - const tableRows: TableRow[] = rows.map((row) => ({ - cells: [row.name, row.type, row.description], - })); +/** Whether a schema describes an object whose properties can be listed. */ +function isObjectLike(schema: Schema): boolean { + return schema.type === "object" || !!schema.properties || !!schema.allOf; +} - lines.push(...listTable(["Name", "Type", "Description"], tableRows)); - return lines; +/** The properties of an object-like schema, with `allOf` merged. */ +function objectFields(spec: OpenAPISpec, schema: Schema): Schema { + return schema.allOf ? mergeAllOf(spec, schema.allOf) : schema; } /** * Flatten object properties into rows, recursing into nested objects - * with indented dotted path names. + * with dotted path names. + * + * `ancestors` holds the schemas being expanded on the way here. A property + * whose schema is already among them gets its own row but no child rows, so a + * recursive schema renders once instead of forever. */ function flattenProperties( spec: OpenAPISpec, properties: Record, - required?: string[], - prefix: string = "", - depth: number = 0, -): PropertyRow[] { - const rows: PropertyRow[] = []; + required: string[] | undefined, + prefix: string, + depth: number, + ancestors: ReadonlySet, +): FieldRow[] { + const rows: FieldRow[] = []; const requiredSet = new Set(required || []); + /** Rows for the properties of `schema`, nested under `path`. */ + const children = (schema: Schema, path: string): FieldRow[] => { + if (ancestors.has(schema)) return []; + const fields = objectFields(spec, schema); + if (!fields.properties) return []; + return flattenProperties( + spec, + fields.properties, + fields.required, + path, + depth + 1, + new Set([...ancestors, schema]), + ); + }; + for (const [name, prop] of Object.entries(properties)) { const resolved = isReference(prop) ? resolve(spec, prop) : prop; const displayName = prefix ? `${prefix}.${name}` : name; - const nameCell = depth > 0 - ? `[\`${displayName}\`]{.schema-nest-${depth}}` - : `\`${displayName}\``; + const row = (type: string, attributes: string): FieldRow => ({ + name: displayName, + depth, + type, + description: resolved.description?.trim() ?? "", + attributes, + }); + const attributes = attributesOf(resolved, requiredSet.has(name)); + const alternative = soleAlternative(spec, resolved); if ( (resolved.type === "object" || resolved.properties) && @@ -203,68 +234,31 @@ function flattenProperties( !resolved.allOf ) { // Nested object: emit a row for the object itself, then recurse - rows.push({ - name: nameCell, - type: "`object`", - description: resolved.description || "", - }); - rows.push( - ...flattenProperties( - spec, - resolved.properties, - resolved.required, - displayName, - depth + 1, - ), - ); + rows.push(row("object", "")); + rows.push(...children(resolved, displayName)); } else if (resolved.allOf) { const merged = mergeAllOf(spec, resolved.allOf); rows.push({ - name: nameCell, - type: "`object`", - description: resolved.description || merged.description || "", + ...row("object", ""), + description: + (resolved.description || merged.description || "").trim(), }); - if (merged.properties) { - rows.push( - ...flattenProperties( - spec, - merged.properties, - merged.required, - displayName, - depth + 1, - ), - ); - } + rows.push(...children(resolved, displayName)); + } else if (alternative && isObjectLike(alternative)) { + // A nullable reference, `anyOf: [{ $ref }, { nullable: true }]`: list + // the referenced object's properties as if it were a nested object. + rows.push(row(formatTypeString(spec, resolved), attributes)); + rows.push(...children(alternative, displayName)); } else if (resolved.type === "array" && resolved.items) { const items = isReference(resolved.items) ? resolve(spec, resolved.items) : resolved.items; - if (items.type === "object" || items.properties || items.allOf) { - rows.push({ - name: nameCell, - type: "`[object]`", - description: buildDescription(resolved, requiredSet.has(name)), - }); - const effective = items.allOf ? mergeAllOf(spec, items.allOf) : items; - if (effective.properties) { - rows.push( - ...flattenProperties( - spec, - effective.properties, - effective.required, - `${displayName}[]`, - depth + 1, - ), - ); - } + if (isObjectLike(items)) { + rows.push(row("[object]", attributes)); + rows.push(...children(items, `${displayName}[]`)); } else { - const itemType = items.type || "unknown"; - rows.push({ - name: nameCell, - type: `\`[${itemType}]\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); + rows.push(row(`[${typeLabel(spec, items)}]`, attributes)); } } else if ( !resolved.properties && @@ -274,40 +268,15 @@ function flattenProperties( // Typed map: additionalProperties is a schema, $ref, or `true`. const ap = resolved.additionalProperties; const valueType = mapValueTypeLabel(spec, ap); - rows.push({ - name: nameCell, - type: `\`map[string, ${valueType}]\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); + rows.push(row(`map[string, ${valueType}]`, attributes)); if (ap !== true) { const valueSchema = isReference(ap) ? resolve(spec, ap) : ap; - if ( - valueSchema.type === "object" || - valueSchema.properties || - valueSchema.allOf - ) { - const effective = valueSchema.allOf - ? mergeAllOf(spec, valueSchema.allOf) - : valueSchema; - if (effective.properties) { - rows.push( - ...flattenProperties( - spec, - effective.properties, - effective.required, - `${displayName}{}`, - depth + 1, - ), - ); - } + if (isObjectLike(valueSchema)) { + rows.push(...children(valueSchema, `${displayName}{}`)); } } } else { - rows.push({ - name: nameCell, - type: `\`${formatTypeString(resolved)}\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); + rows.push(row(formatTypeString(spec, resolved), attributes)); } } @@ -315,15 +284,10 @@ function flattenProperties( } /** - * Build a description string including property attributes. + * The attribute sentences shown after a field's description, such as + * "Required. Example: `x`.", or "" when the field has none. */ -function buildDescription(schema: Schema, isRequired: boolean): string { - const parts: string[] = []; - - if (schema.description) { - parts.push(schema.description.trim()); - } - +function attributesOf(schema: Schema, isRequired: boolean): string { const attrs: string[] = []; if (isRequired) attrs.push("Required"); if (schema.readOnly) attrs.push("Read-only"); @@ -339,12 +303,7 @@ function buildDescription(schema: Schema, isRequired: boolean): string { if (schema.example !== undefined) attrs.push(`Example: \`${formatValue(schema.example)}\``); - if (attrs.length > 0) { - if (parts.length > 0) parts.push(""); - parts.push(attrs.join(". ") + "."); - } - - return parts.join("\n"); + return attrs.length > 0 ? attrs.join(". ") + "." : ""; } const semanticFormats = new Set(["date-time", "date", "time", "duration", "uuid", "uri", "uri-reference", "email", "hostname", "ipv4", "ipv6", "byte", "binary", "password"]); @@ -356,27 +315,82 @@ function mapValueTypeLabel( if (value === true) return "any"; if (value === false) return "object"; if (isReference(value)) { - return value.$ref.split("/").pop() || "object"; + return refName(value); } if (value.type === "object" || value.properties || value.allOf) return "object"; return value.type || "object"; } -function formatTypeString(schema: Schema): string { - let type = schema.type || "unknown"; +function refName(ref: Reference): string { + return ref.$ref.split("/").pop() || "object"; +} + +/** + * Whether a schema only marks its parent as nullable, like the second member + * of `anyOf: [{ $ref }, { nullable: true }]`. + */ +function isNullMarker(schema: Schema | Reference): boolean { + if (isReference(schema)) return false; + if (schema.type === "null") return true; + return ( + schema.nullable === true && + Object.keys(schema).every((k) => k === "nullable" || k === "description") + ); +} + +/** + * The one schema an `anyOf` or `oneOf` allows besides null, or undefined when + * there is no such composition or it has more than one alternative. + */ +function soleAlternative(spec: OpenAPISpec, schema: Schema): Schema | undefined { + const members = schema.anyOf ?? schema.oneOf; + if (!members) return undefined; + const alternatives = members.filter((m) => !isNullMarker(m)); + if (alternatives.length !== 1) return undefined; + const [only] = alternatives; + return isReference(only) ? resolve(spec, only) : only; +} + +/** + * A short name for the type a schema allows: the schema name for a `$ref`, + * the alternatives joined by `|` for `anyOf`/`oneOf`, and `any` for a schema + * that does not constrain the type. + */ +function typeLabel(spec: OpenAPISpec, schema: Schema | Reference): string { + if (isReference(schema)) return refName(schema); + if (schema.type) return schema.type; + if (schema.allOf) { + return schema.allOf.length === 1 + ? typeLabel(spec, schema.allOf[0]) + : "object"; + } + const members = schema.anyOf ?? schema.oneOf; + if (members) { + const labels = members.map((m) => + isNullMarker(m) ? "null" : typeLabel(spec, m), + ); + return [...new Set(labels)].join("|"); + } + if (schema.properties || schema.additionalProperties) return "object"; + if (schema.items) return "array"; + return "any"; +} + +function formatTypeString(spec: OpenAPISpec, schema: Schema): string { + let type = typeLabel(spec, schema); if (schema.format && semanticFormats.has(schema.format)) { type = `${type} (${schema.format})`; } - if (schema.nullable) { + if (schema.nullable && !type.split("|").includes("null")) { type = `${type}|null`; } return type; } -function formatPrimitiveType(schema: Schema): string { - const parts = [schema.type || "unknown"]; +function formatPrimitiveType(spec: OpenAPISpec, schema: Schema): string { + const parts = [typeLabel(spec, schema)]; if (schema.format && semanticFormats.has(schema.format)) parts.push(`(${schema.format})`); return parts.join(" "); } diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts b/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts index de10ce7..87054dd 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts @@ -23,9 +23,8 @@ import { heading, methodBadge, pathToAnchor, - listTable, - type TableRow, } from "./markdown.ts"; +import { fieldTable, type FieldRow } from "./fields.ts"; export interface Section { /** Resource name, e.g., "content", "bundles" */ @@ -523,7 +522,7 @@ function renderParameters( lines.push(""); } - const rows: TableRow[] = params.map((param) => { + const rows: FieldRow[] = params.map((param) => { const schema = param.schema ? resolve(spec, param.schema) : undefined; @@ -533,20 +532,16 @@ function renderParameters( if (schema?.format) typeParts.push(`(${schema.format})`); const typeStr = typeParts.length > 0 ? typeParts.join(" ") : "string"; - const descParts: string[] = []; - if (param.description) descParts.push(param.description.trim()); - if (param.required) descParts.push("Required."); - return { - cells: [ - `\`${param.name}\``, - `\`${typeStr}\``, - descParts.join(" "), - ], + name: param.name, + depth: 0, + type: typeStr, + description: param.description?.trim() ?? "", + attributes: param.required ? "Required." : "", }; }); - lines.push(...listTable(["Name", "Type", "Description"], rows)); + lines.push(...fieldTable(rows)); lines.push(""); } diff --git a/example/_extensions/posit-dev/quarto-openapi/quarto-openapi-styles.css b/example/_extensions/posit-dev/quarto-openapi/quarto-openapi-styles.css index ee9e97e..530a463 100644 --- a/example/_extensions/posit-dev/quarto-openapi/quarto-openapi-styles.css +++ b/example/_extensions/posit-dev/quarto-openapi/quarto-openapi-styles.css @@ -26,3 +26,18 @@ .schema-nest-2 { padding-left: 2em; } .schema-nest-3 { padding-left: 3em; } .schema-nest-4 { padding-left: 4em; } + +/* + * Field descriptions are one paragraph of spans, so that `.llms.md` can keep + * the table (see lib/fields.ts). These spans lay out as the paragraphs they + * stand for. + */ +.schema-para, +.schema-attrs { + display: block; +} + +.schema-para + .schema-para, +.schema-para + .schema-attrs { + margin-top: 0.5em; +} diff --git a/tests/fields_test.ts b/tests/fields_test.ts new file mode 100644 index 0000000..1d27bfd --- /dev/null +++ b/tests/fields_test.ts @@ -0,0 +1,127 @@ +import { test } from "node:test"; +import { assertEquals, assertStringIncludes } from "./assert.ts"; +import { + fieldTable, + type FieldRow, +} from "../_extensions/quarto-openapi/lib/fields.ts"; + +function field(overrides: Partial): FieldRow { + return { + name: "guid", + depth: 0, + type: "string", + description: "", + attributes: "", + ...overrides, + }; +} + +/** The Description cell of the only body row. */ +function descriptionCell(lines: string[]): string { + const start = lines.indexOf("* * `guid`"); + return lines[start + 2].replace(/^ {2}\* /, ""); +} + +test("fieldTable: a one-paragraph description is emitted as is", () => { + const lines = fieldTable([field({ description: "The identifier." })]); + assertEquals(descriptionCell(lines), "The identifier."); +}); + +test("fieldTable: attributes share the description's paragraph", () => { + const lines = fieldTable([ + field({ description: "The identifier.", attributes: "Required." }), + ]); + assertEquals( + descriptionCell(lines), + "[The identifier.]{.schema-para} [Required.]{.schema-attrs}", + ); + // No blank line anywhere in the row, so no cell holds a second block. + assertEquals(lines.slice(lines.indexOf("* * `guid`")).indexOf(""), 3); +}); + +test("fieldTable: attributes alone are one span", () => { + const lines = fieldTable([field({ attributes: "Read-only." })]); + assertEquals(descriptionCell(lines), "[Read-only.]{.schema-attrs}"); +}); + +test("fieldTable: paragraphs become spans on one line", () => { + const lines = fieldTable([ + field({ + description: "First paragraph\nwraps here.\n\nSecond `code` paragraph.", + }), + ]); + assertEquals( + descriptionCell(lines), + "[First paragraph wraps here.]{.schema-para} " + + "[Second `code` paragraph.]{.schema-para}", + ); +}); + +test("fieldTable: a list moves below the table, and the cell points to it", () => { + const lines = fieldTable([ + field({ + description: "Accepted values:\n\n- `a`: first\n- `b`: second", + attributes: "Required.", + }), + ]); + assertEquals( + descriptionCell(lines), + "[Accepted values:]{.schema-para} " + + "[Continued below the table.]{.schema-para} " + + "[Required.]{.schema-attrs}", + ); + const output = lines.join("\n"); + assertStringIncludes( + output, + [ + "::: {.schema-notes}", + "", + "- `guid`:", + "", + " - `a`: first", + " - `b`: second", + "", + ":::", + ].join("\n"), + ); + // The note follows the table rather than sitting inside it. + assertEquals( + output.indexOf("::: {.schema-notes}") > output.lastIndexOf(":::\n\n:::"), + true, + ); +}); + +test("fieldTable: everything from the first block on moves, in order", () => { + const lines = fieldTable([ + field({ + description: "Intro.\n\n```json\n{}\n```\n\nAfterword.", + }), + ]); + assertStringIncludes( + lines.join("\n"), + "- `guid`:\n\n ```json\n {}\n ```\n\n Afterword.", + ); +}); + +test("fieldTable: a hard line break moves with its paragraph", () => { + const lines = fieldTable([ + field({ description: "Intro.\n\nLine one\\\nline two." }), + ]); + assertEquals( + descriptionCell(lines), + "[Intro.]{.schema-para} [Continued below the table.]{.schema-para}", + ); + assertStringIncludes(lines.join("\n"), " Line one\\\n line two."); +}); + +test("fieldTable: nested names keep their indentation class", () => { + const lines = fieldTable([ + field({ name: "owner", type: "object" }), + field({ name: "owner.guid", depth: 1 }), + ]); + assertStringIncludes(lines.join("\n"), "* * [`owner.guid`]{.schema-nest-1}"); +}); + +test("fieldTable: no rows, no table", () => { + assertEquals(fieldTable([]), []); +}); diff --git a/tests/markdown_test.ts b/tests/markdown_test.ts index 304ebf7..e20ec5e 100644 --- a/tests/markdown_test.ts +++ b/tests/markdown_test.ts @@ -92,6 +92,14 @@ test("listTable: a cell holding two blocks emits a loose list", () => { assertStringIncludes(output, "* * `id`\n\n * `string`\n\n * First paragraph.\n\n Second paragraph."); }); +test("listTable: an empty cell keeps the row tight", () => { + const rows: TableRow[] = [{ cells: ["`id`", "`string`", ""] }]; + + const output = listTable(["Name", "Type", "Description"], rows).join("\n"); + + assertStringIncludes(output, "* * `id`\n * `string`\n * \n"); +}); + test("listTable: cell text is emitted verbatim, whatever its length", () => { const rows: TableRow[] = [ { cells: ["`temp_ticket`", "`string`", "See [ref](#get-/v1/some/path) for details."] }, diff --git a/tests/quarto_render_test.ts b/tests/quarto_render_test.ts index 3d6769e..71c767e 100644 --- a/tests/quarto_render_test.ts +++ b/tests/quarto_render_test.ts @@ -18,6 +18,7 @@ import { join } from "node:path"; import { promisify } from "node:util"; import { assert, assertEquals, assertStringIncludes } from "./assert.ts"; import { listTable } from "../_extensions/quarto-openapi/lib/markdown.ts"; +import { fieldTable } from "../_extensions/quarto-openapi/lib/fields.ts"; import { escapePathBracesOutsideCode } from "../_extensions/quarto-openapi/lib/escape.ts"; const execFileAsync = promisify(execFile); @@ -56,6 +57,25 @@ async function render(markdown: string): Promise { } } +/** + * Render `markdown` as the only page of a website with `llms-txt` on, and + * return the `.llms.md` Quarto derives from the page's HTML. + */ +async function renderLlms(markdown: string): Promise { + const dir = await mkdtemp(join(tmpdir(), "quarto-openapi-llms-")); + try { + await writeFile( + join(dir, "_quarto.yml"), + "project:\n type: website\nwebsite:\n title: Test\n llms-txt: true\n", + ); + await writeFile(join(dir, "index.qmd"), markdown); + await execFileAsync("quarto", ["render"], { cwd: dir }); + return await readFile(join(dir, "_site", "index.llms.md"), "utf8"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + /** The first `` element in `html`, which is the one under test. */ function tableOf(html: string): string { const table = html.match(//)?.[0]; @@ -149,3 +169,54 @@ test("Quarto renders a fenced cell and escaped braces verbatim", { skip }, async assertStringIncludes(table, "GET /v1/widgets/{widget-id}/keys/{key2}."); assertEquals(table.includes("\\{"), false, `braces left escaped:\n${table}`); }); + +test("A field table survives into llms-txt output", { skip }, async () => { + // Quarto converts the rendered HTML to GFM for `.llms.md`, and Pandoc writes + // `[TABLE]` for any table with block content in a cell. + const markdown = [ + "---", + "title: Fields", + "---", + "", + ...fieldTable([ + { + name: "guid", + depth: 0, + type: "string", + description: "The identifier.\n\nAssigned by the server.", + attributes: "Required. Example: `abc`.", + }, + { + name: "mode", + depth: 0, + type: "string", + description: "How it runs:\n\n- `fast`: skips checks\n- `safe`: checks first", + attributes: "", + }, + { + name: "owner.name", + depth: 1, + type: "string", + description: "", + attributes: "Read-only.", + }, + ]), + "", + ].join("\n"); + + const llms = await renderLlms(markdown); + + assertEquals(llms.includes("[TABLE]"), false, `table dropped:\n${llms}`); + assertStringIncludes( + llms, + "| `guid` | `string` | The identifier. Assigned by the server. " + + "Required. Example: `abc`. |", + ); + assertStringIncludes( + llms, + "| `mode` | `string` | How it runs: Continued below the table. |", + ); + assertStringIncludes(llms, "| `owner.name` | `string` | Read-only. |"); + assertStringIncludes(llms, "- `fast`: skips checks"); + assertStringIncludes(llms, "- `safe`: checks first"); +}); diff --git a/tests/schema_test.ts b/tests/schema_test.ts index e43d3b3..adb0bd7 100644 --- a/tests/schema_test.ts +++ b/tests/schema_test.ts @@ -1,6 +1,7 @@ import { test } from "node:test"; import { assert, + assertFalse, assertEquals, assertStringIncludes, } from "./assert.ts"; @@ -429,3 +430,98 @@ test("renderSchema: enum values go through the same formatter as defaults", () = assertStringIncludes(output, 'Enum: `""`, `fast`, `null`'); }); + +test("renderSchema: a nullable reference is named and expanded", () => { + const spec = specWithSchemas({ + Source: { + type: "object", + required: ["choice"], + properties: { + choice: { type: "string", enum: ["git", "none"] }, + gitUrl: { type: "string" }, + }, + }, + }); + const output = rendered(spec, { + type: "object", + required: ["source"], + properties: { + source: { + description: "Where the source lives.", + anyOf: [ + { $ref: "#/components/schemas/Source" } as unknown as Schema, + { nullable: true }, + ], + }, + }, + }); + + assertStringIncludes(output, "* * `source`\n * `Source|null`"); + assertStringIncludes(output, "[Where the source lives.]{.schema-para}"); + assertStringIncludes(output, "[Required.]{.schema-attrs}"); + assertStringIncludes(output, "* * [`source.choice`]{.schema-nest-1}"); + assertStringIncludes(output, "* * [`source.gitUrl`]{.schema-nest-1}"); + assertFalse(output.includes("unknown"), output); +}); + +test("renderSchema: alternatives are joined with |", () => { + const spec = specWithSchemas({ + Cat: { type: "object", properties: { purrs: { type: "boolean" } } }, + Dog: { type: "object", properties: { barks: { type: "boolean" } } }, + }); + const output = rendered(spec, { + type: "object", + properties: { + pet: { + oneOf: [ + { $ref: "#/components/schemas/Cat" } as unknown as Schema, + { $ref: "#/components/schemas/Dog" } as unknown as Schema, + ], + }, + id: { anyOf: [{ type: "string" }, { type: "integer" }] }, + }, + }); + + assertStringIncludes(output, "* * `pet`\n * `Cat|Dog`"); + assertStringIncludes(output, "* * `id`\n * `string|integer`"); + // Neither alternative is listed as if it were the only one. + assertFalse(output.includes("pet.purrs"), output); +}); + +test("renderSchema: a schema with no type constraint is any", () => { + const output = rendered(specWithSchemas(), { + type: "object", + properties: { value: { description: "Any JSON value." } }, + }); + assertStringIncludes(output, "* * `value`\n * `any`"); +}); + +test("renderSchema: a recursive nullable reference expands once", () => { + const spec = specWithSchemas({ + Expr: { + type: "object", + properties: { + operator: { type: "string" }, + operands: { + type: "array", + items: { $ref: "#/components/schemas/Expr" } as unknown as Schema, + }, + }, + }, + }); + const output = rendered(spec, { + type: "object", + properties: { + visible: { + anyOf: [ + { $ref: "#/components/schemas/Expr" } as unknown as Schema, + { nullable: true }, + ], + }, + }, + }); + + assertStringIncludes(output, "* * `visible`\n * `Expr|null`"); + assertStringIncludes(output, "[`visible.operands`]{.schema-nest-1}"); + assertFalse(output.includes("visible.operands[].operator"), output); +}); From 8e7c6cb941f390ff19f25a810a7bd4f477f4c03f Mon Sep 17 00:00:00 2001 From: Jordan Jensen Date: Tue, 10 Nov 2026 16:43:02 -0800 Subject: [PATCH 2/4] fix: label composed types by structure, since refs are expanded before rendering Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- _extensions/quarto-openapi/lib/schema.ts | 30 ++----- .../posit-dev/quarto-openapi/lib/schema.ts | 30 ++----- tests/schema_test.ts | 86 +++++++++++-------- 4 files changed, 64 insertions(+), 88 deletions(-) diff --git a/README.md b/README.md index 010dbb7..8d2f9ea 100644 --- a/README.md +++ b/README.md @@ -126,9 +126,9 @@ Schema tables handle: - Nested objects: flattened as indented dotted rows (e.g., `owner.guid`) - Arrays of objects: expanded inline with their properties - `allOf` composition: merged into a single property table -- `anyOf`/`oneOf` composition: typed by the alternatives' names joined with `|` - (`Owner|null`, `Cat|Dog`); a nullable reference to an object also lists the - object's properties +- `anyOf`/`oneOf` composition: typed by the alternatives joined with `|` + (`object|null`, `string|integer`); a nullable object also lists the object's + properties - Property attributes: required, read-only, nullable, default, minimum/maximum, enum, example, format ### Field tables and `llms-txt` diff --git a/_extensions/quarto-openapi/lib/schema.ts b/_extensions/quarto-openapi/lib/schema.ts index b3cee7c..30fb251 100644 --- a/_extensions/quarto-openapi/lib/schema.ts +++ b/_extensions/quarto-openapi/lib/schema.ts @@ -159,14 +159,7 @@ function renderObject( return lines; } - const rows = flattenProperties( - spec, - schema.properties, - schema.required, - "", - 0, - new Set([schema]), - ); + const rows = flattenProperties(spec, schema.properties, schema.required, "", 0); lines.push(...fieldTable(rows)); return lines; } @@ -184,10 +177,6 @@ function objectFields(spec: OpenAPISpec, schema: Schema): Schema { /** * Flatten object properties into rows, recursing into nested objects * with dotted path names. - * - * `ancestors` holds the schemas being expanded on the way here. A property - * whose schema is already among them gets its own row but no child rows, so a - * recursive schema renders once instead of forever. */ function flattenProperties( spec: OpenAPISpec, @@ -195,14 +184,12 @@ function flattenProperties( required: string[] | undefined, prefix: string, depth: number, - ancestors: ReadonlySet, ): FieldRow[] { const rows: FieldRow[] = []; const requiredSet = new Set(required || []); /** Rows for the properties of `schema`, nested under `path`. */ const children = (schema: Schema, path: string): FieldRow[] => { - if (ancestors.has(schema)) return []; const fields = objectFields(spec, schema); if (!fields.properties) return []; return flattenProperties( @@ -211,7 +198,6 @@ function flattenProperties( fields.required, path, depth + 1, - new Set([...ancestors, schema]), ); }; @@ -315,16 +301,12 @@ function mapValueTypeLabel( if (value === true) return "any"; if (value === false) return "object"; if (isReference(value)) { - return refName(value); + return value.$ref.split("/").pop() || "object"; } if (value.type === "object" || value.properties || value.allOf) return "object"; return value.type || "object"; } -function refName(ref: Reference): string { - return ref.$ref.split("/").pop() || "object"; -} - /** * Whether a schema only marks its parent as nullable, like the second member * of `anyOf: [{ $ref }, { nullable: true }]`. @@ -352,12 +334,12 @@ function soleAlternative(spec: OpenAPISpec, schema: Schema): Schema | undefined } /** - * A short name for the type a schema allows: the schema name for a `$ref`, - * the alternatives joined by `|` for `anyOf`/`oneOf`, and `any` for a schema - * that does not constrain the type. + * A short name for the type a schema allows: its `type`, `object` for an + * object, the alternatives joined by `|` for `anyOf`/`oneOf`, and `any` for a + * schema that does not constrain the type. */ function typeLabel(spec: OpenAPISpec, schema: Schema | Reference): string { - if (isReference(schema)) return refName(schema); + if (isReference(schema)) return typeLabel(spec, resolve(spec, schema)); if (schema.type) return schema.type; if (schema.allOf) { return schema.allOf.length === 1 diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts b/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts index b3cee7c..30fb251 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts @@ -159,14 +159,7 @@ function renderObject( return lines; } - const rows = flattenProperties( - spec, - schema.properties, - schema.required, - "", - 0, - new Set([schema]), - ); + const rows = flattenProperties(spec, schema.properties, schema.required, "", 0); lines.push(...fieldTable(rows)); return lines; } @@ -184,10 +177,6 @@ function objectFields(spec: OpenAPISpec, schema: Schema): Schema { /** * Flatten object properties into rows, recursing into nested objects * with dotted path names. - * - * `ancestors` holds the schemas being expanded on the way here. A property - * whose schema is already among them gets its own row but no child rows, so a - * recursive schema renders once instead of forever. */ function flattenProperties( spec: OpenAPISpec, @@ -195,14 +184,12 @@ function flattenProperties( required: string[] | undefined, prefix: string, depth: number, - ancestors: ReadonlySet, ): FieldRow[] { const rows: FieldRow[] = []; const requiredSet = new Set(required || []); /** Rows for the properties of `schema`, nested under `path`. */ const children = (schema: Schema, path: string): FieldRow[] => { - if (ancestors.has(schema)) return []; const fields = objectFields(spec, schema); if (!fields.properties) return []; return flattenProperties( @@ -211,7 +198,6 @@ function flattenProperties( fields.required, path, depth + 1, - new Set([...ancestors, schema]), ); }; @@ -315,16 +301,12 @@ function mapValueTypeLabel( if (value === true) return "any"; if (value === false) return "object"; if (isReference(value)) { - return refName(value); + return value.$ref.split("/").pop() || "object"; } if (value.type === "object" || value.properties || value.allOf) return "object"; return value.type || "object"; } -function refName(ref: Reference): string { - return ref.$ref.split("/").pop() || "object"; -} - /** * Whether a schema only marks its parent as nullable, like the second member * of `anyOf: [{ $ref }, { nullable: true }]`. @@ -352,12 +334,12 @@ function soleAlternative(spec: OpenAPISpec, schema: Schema): Schema | undefined } /** - * A short name for the type a schema allows: the schema name for a `$ref`, - * the alternatives joined by `|` for `anyOf`/`oneOf`, and `any` for a schema - * that does not constrain the type. + * A short name for the type a schema allows: its `type`, `object` for an + * object, the alternatives joined by `|` for `anyOf`/`oneOf`, and `any` for a + * schema that does not constrain the type. */ function typeLabel(spec: OpenAPISpec, schema: Schema | Reference): string { - if (isReference(schema)) return refName(schema); + if (isReference(schema)) return typeLabel(spec, resolve(spec, schema)); if (schema.type) return schema.type; if (schema.allOf) { return schema.allOf.length === 1 diff --git a/tests/schema_test.ts b/tests/schema_test.ts index adb0bd7..a99eaf4 100644 --- a/tests/schema_test.ts +++ b/tests/schema_test.ts @@ -431,7 +431,7 @@ test("renderSchema: enum values go through the same formatter as defaults", () = assertStringIncludes(output, 'Enum: `""`, `fast`, `null`'); }); -test("renderSchema: a nullable reference is named and expanded", () => { +test("renderSchema: a nullable reference is typed and expanded", () => { const spec = specWithSchemas({ Source: { type: "object", @@ -441,22 +441,28 @@ test("renderSchema: a nullable reference is named and expanded", () => { gitUrl: { type: "string" }, }, }, - }); - const output = rendered(spec, { - type: "object", - required: ["source"], - properties: { - source: { - description: "Where the source lives.", - anyOf: [ - { $ref: "#/components/schemas/Source" } as unknown as Schema, - { nullable: true }, - ], + Values: { + type: "object", + required: ["source"], + properties: { + source: { + description: "Where the source lives.", + anyOf: [ + { $ref: "#/components/schemas/Source" } as unknown as Schema, + { nullable: true }, + ], + }, }, }, }); - - assertStringIncludes(output, "* * `source`\n * `Source|null`"); + // Through a $ref, as request and response bodies usually are: every + // nested $ref is expanded before the table is built. + const output = rendered( + spec, + { $ref: "#/components/schemas/Values" } as unknown as Schema, + ); + + assertStringIncludes(output, "* * `source`\n * `object|null`"); assertStringIncludes(output, "[Where the source lives.]{.schema-para}"); assertStringIncludes(output, "[Required.]{.schema-attrs}"); assertStringIncludes(output, "* * [`source.choice`]{.schema-nest-1}"); @@ -465,25 +471,23 @@ test("renderSchema: a nullable reference is named and expanded", () => { }); test("renderSchema: alternatives are joined with |", () => { - const spec = specWithSchemas({ - Cat: { type: "object", properties: { purrs: { type: "boolean" } } }, - Dog: { type: "object", properties: { barks: { type: "boolean" } } }, - }); - const output = rendered(spec, { + const output = rendered(specWithSchemas(), { type: "object", properties: { + id: { anyOf: [{ type: "string" }, { type: "integer" }] }, + label: { oneOf: [{ type: "string" }, { nullable: true }] }, pet: { oneOf: [ - { $ref: "#/components/schemas/Cat" } as unknown as Schema, - { $ref: "#/components/schemas/Dog" } as unknown as Schema, + { type: "object", properties: { purrs: { type: "boolean" } } }, + { type: "object", properties: { barks: { type: "boolean" } } }, ], }, - id: { anyOf: [{ type: "string" }, { type: "integer" }] }, }, }); - assertStringIncludes(output, "* * `pet`\n * `Cat|Dog`"); assertStringIncludes(output, "* * `id`\n * `string|integer`"); + assertStringIncludes(output, "* * `label`\n * `string|null`"); + assertStringIncludes(output, "* * `pet`\n * `object`"); // Neither alternative is listed as if it were the only one. assertFalse(output.includes("pet.purrs"), output); }); @@ -496,7 +500,7 @@ test("renderSchema: a schema with no type constraint is any", () => { assertStringIncludes(output, "* * `value`\n * `any`"); }); -test("renderSchema: a recursive nullable reference expands once", () => { +test("renderSchema: a recursive nullable reference ends at the cycle", () => { const spec = specWithSchemas({ Expr: { type: "object", @@ -508,20 +512,28 @@ test("renderSchema: a recursive nullable reference expands once", () => { }, }, }, - }); - const output = rendered(spec, { - type: "object", - properties: { - visible: { - anyOf: [ - { $ref: "#/components/schemas/Expr" } as unknown as Schema, - { nullable: true }, - ], + Field: { + type: "object", + properties: { + visible: { + anyOf: [ + { $ref: "#/components/schemas/Expr" } as unknown as Schema, + { nullable: true }, + ], + }, }, }, }); - - assertStringIncludes(output, "* * `visible`\n * `Expr|null`"); - assertStringIncludes(output, "[`visible.operands`]{.schema-nest-1}"); - assertFalse(output.includes("visible.operands[].operator"), output); + const output = rendered( + spec, + { $ref: "#/components/schemas/Field" } as unknown as Schema, + ); + + assertStringIncludes(output, "* * `visible`\n * `object|null`"); + assertStringIncludes(output, "[`visible.operator`]{.schema-nest-1}"); + // The cycle ends where the reference repeats. + assertStringIncludes( + output, + "* * [`visible.operands`]{.schema-nest-1}\n * `[any]`", + ); }); From 51b768a442dd74785f33d582224181d9658dbda3 Mon Sep 17 00:00:00 2001 From: Jordan Jensen Date: Tue, 10 Nov 2026 17:43:21 -0800 Subject: [PATCH 3/4] fix: give llms-txt its own field list and type every schema through one path Field tables now come in two forms. The list table is wrapped in `content-hidden when-format="llms-txt"` and is unchanged in the HTML page, lists and code blocks included. A bullet list with one item per field is wrapped in `content-visible when-format="llms-txt"`, so `.llms.md` gets every description block without Pandoc's GFM writer turning the table into `[TABLE]`. This replaces the span rewrite of description cells, which needed the extension's stylesheet (loaded only with the extension's format) and still produced `[TABLE]` for a description with an inline `
`. Schema typing goes through one normalize step (resolve `$ref`, merge `allOf` including non-object members) and one type label function, so: - `allOf` around a primitive keeps its type and enum - nested object rows show their attributes and `|null` - arrays, maps and alternative members label consistently (`[string]|null`, `map[string, string|integer]`, a member's own `nullable`) - a circular reference is labelled by the schema it repeats - parameters use the same labels and attributes as properties - a request or response body that is `anyOf`/`oneOf` renders each alternative Co-Authored-By: Claude Opus 5.5 --- README.md | 13 +- _extensions/quarto-openapi/lib/fields.ts | 139 +++---- _extensions/quarto-openapi/lib/refs.ts | 7 +- _extensions/quarto-openapi/lib/schema.ts | 341 +++++++++--------- _extensions/quarto-openapi/lib/sections.ts | 14 +- _extensions/quarto-openapi/lib/types.ts | 2 + .../quarto-openapi/quarto-openapi-styles.css | 15 - .../posit-dev/quarto-openapi/lib/fields.ts | 139 +++---- .../posit-dev/quarto-openapi/lib/refs.ts | 7 +- .../posit-dev/quarto-openapi/lib/schema.ts | 341 +++++++++--------- .../posit-dev/quarto-openapi/lib/sections.ts | 14 +- .../posit-dev/quarto-openapi/lib/types.ts | 2 + .../quarto-openapi/quarto-openapi-styles.css | 15 - tests/fields_test.ts | 140 +++---- tests/quarto_render_test.ts | 38 +- tests/render_test.ts | 39 ++ tests/schema_test.ts | 112 +++++- 17 files changed, 680 insertions(+), 698 deletions(-) diff --git a/README.md b/README.md index 8d2f9ea..1d4ac39 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ Schema tables handle: - `allOf` composition: merged into a single property table - `anyOf`/`oneOf` composition: typed by the alternatives joined with `|` (`object|null`, `string|integer`); a nullable object also lists the object's - properties + properties, and a request or response body lists each alternative in turn - Property attributes: required, read-only, nullable, default, minimum/maximum, enum, example, format ### Field tables and `llms-txt` @@ -137,12 +137,11 @@ Quarto builds each `.llms.md` page from the rendered HTML with Pandoc's GFM writer. A GFM table cell holds inline content only, so Pandoc writes `[TABLE]` in place of any table with a paragraph break, list or line break in a cell. -To keep every table, each Description cell is a single paragraph. A -description's paragraphs and the field's attributes become spans that the -extension's stylesheet lays out as separate lines, so the HTML reads as -paragraphs and the GFM conversion sees one. Content that cannot be inline, such -as a list or a code block, is listed under the table with the field's name, and -the cell says "Continued below the table." +Each field table is therefore emitted twice, inside +`content-hidden`/`content-visible` blocks with `when-format="llms-txt"`: the +table for the HTML page, and a bullet list with one item per field for +`.llms.md`, where descriptions keep their paragraphs, lists and code blocks. +Quarto removes the list from the HTML page and its search index. ## Project structure diff --git a/_extensions/quarto-openapi/lib/fields.ts b/_extensions/quarto-openapi/lib/fields.ts index c3e89fe..b82daf0 100644 --- a/_extensions/quarto-openapi/lib/fields.ts +++ b/_extensions/quarto-openapi/lib/fields.ts @@ -2,24 +2,16 @@ * Field tables: the Name / Type / Description tables for parameters and schema * properties. * - * Every Description cell is a single paragraph of inline content. Quarto - * builds `.llms.md` from the rendered HTML with `pandoc -t gfm-raw_html`, and a - * GFM pipe table can only hold inline content. One cell with block content (a - * second paragraph, a list, a line break) makes Pandoc write `[TABLE]` in place - * of the whole table. - * - * So a description's paragraphs, and the field's attributes, become spans that - * the stylesheet displays as blocks: the HTML reads as before, and the GFM - * conversion sees one paragraph. Content that cannot be a span, such as a list - * or a code block, moves to a note under the table, which the cell points to. + * Quarto builds a page's `.llms.md` by converting its rendered HTML with + * Pandoc's GFM writer. A GFM table cell holds inline content only, so a + * description with a second paragraph, a list or a line break would turn the + * whole table into `[TABLE]`. Each field table therefore comes in two forms: + * the list table for every format but `llms-txt`, and for `llms-txt` a bullet + * list with one item per field, where any markdown fits. Quarto keeps the + * `llms-txt` form out of the HTML page and its search index. */ -import MarkdownIt from "markdown-it"; -import type { Token } from "markdown-it"; -import { listTable, type TableRow } from "./markdown.ts"; - -/** CommonMark, matching the parser that escapes descriptions. */ -const md = new MarkdownIt("commonmark"); +import { listTable } from "./markdown.ts"; export interface FieldRow { /** The field's name, dotted for nested properties (`owner.guid`). */ @@ -34,55 +26,11 @@ export interface FieldRow { attributes: string; } -/** A description split into what fits in a table cell and what does not. */ -interface SplitDescription { - /** Leading paragraphs, each as one line of inline markdown. */ - paragraphs: string[]; - /** Markdown source from the first block that cannot be inline, or "". */ - rest: string; -} - -/** Whether a top-level paragraph renders as inline content only. */ -function isInlineParagraph(inline: Token | undefined): boolean { - return !(inline?.children ?? []).some((t) => t.type === "hardbreak"); -} - -function splitDescription(description: string): SplitDescription { - const text = description.trim(); - const tokens = md.parse(text, {}); - const lines = text.split("\n"); - const paragraphs: string[] = []; - - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i]; - if (token.level !== 0 || token.nesting === -1) continue; - if (token.type === "paragraph_open" && isInlineParagraph(tokens[i + 1])) { - paragraphs.push( - tokens[i + 1].content - .split("\n") - .map((line) => line.trim()) - .join(" "), - ); - continue; - } - const start = token.map?.[0] ?? lines.length; - return { paragraphs, rest: lines.slice(start).join("\n").trim() }; - } - return { paragraphs, rest: "" }; -} - -function descriptionCell( - split: SplitDescription, - attributes: string, -): string { - const blocks = [...split.paragraphs]; - if (split.rest) blocks.push("Continued below the table."); - const parts = - blocks.length === 1 && !attributes - ? blocks - : blocks.map((p) => `[${p}]{.schema-para}`); - if (attributes) parts.push(`[${attributes}]{.schema-attrs}`); - return parts.join(" "); +/** The description followed by the attributes, as separate paragraphs. */ +function details(row: FieldRow): string { + return [row.description.trim(), row.attributes] + .filter((part) => part !== "") + .join("\n\n"); } function nameCell(row: FieldRow): string { @@ -92,34 +40,43 @@ function nameCell(row: FieldRow): string { } /** - * Render rows as a field table, followed by a note for each row whose - * description holds block content. + * The `llms-txt` form: one loose list item per field, headed by its name and + * type, with the details as the item's blocks. */ -export function fieldTable(rows: FieldRow[]): string[] { - if (rows.length === 0) return []; - - const notes: string[] = []; - const tableRows: TableRow[] = rows.map((row) => { - const split = splitDescription(row.description); - if (split.rest) { - notes.push(`- \`${row.name}\`:`, ""); - for (const line of split.rest.split("\n")) { - notes.push(line === "" ? "" : ` ${line}`); - } - notes.push(""); +function fieldList(rows: FieldRow[]): string[] { + const lines: string[] = []; + for (const row of rows) { + lines.push(`- \`${row.name}\` (\`${row.type}\`)`, ""); + const text = details(row); + if (text === "") continue; + for (const line of text.split("\n")) { + lines.push(line === "" ? "" : ` ${line}`); } - return { - cells: [ - nameCell(row), - `\`${row.type}\``, - descriptionCell(split, row.attributes), - ], - }; - }); - - const lines = listTable(["Name", "Type", "Description"], tableRows); - if (notes.length > 0) { - lines.push("", "::: {.schema-notes}", "", ...notes, ":::"); + lines.push(""); } return lines; } + +/** Render rows as a field table, plus its `llms-txt` form. */ +export function fieldTable(rows: FieldRow[]): string[] { + if (rows.length === 0) return []; + + const table = listTable( + ["Name", "Type", "Description"], + rows.map((row) => ({ + cells: [nameCell(row), `\`${row.type}\``, details(row)], + })), + ); + return [ + '::: {.content-hidden when-format="llms-txt"}', + "", + ...table, + "", + ":::", + "", + '::: {.content-visible when-format="llms-txt"}', + "", + ...fieldList(rows), + ":::", + ]; +} diff --git a/_extensions/quarto-openapi/lib/refs.ts b/_extensions/quarto-openapi/lib/refs.ts index bbdca5d..07e6739 100644 --- a/_extensions/quarto-openapi/lib/refs.ts +++ b/_extensions/quarto-openapi/lib/refs.ts @@ -41,8 +41,11 @@ export function expandRefs( if (isReference(obj)) { const ref = obj.$ref; if (seen.has(ref)) { - // Circular reference — return a stub to avoid infinite recursion - return { description: `(circular reference: ${ref})` } as T; + // Circular reference: a stub that names the schema it would repeat. + return { + description: `(circular reference: ${ref})`, + "x-circular-ref": ref, + } as T; } const resolved = resolveRef(spec, ref); if (resolved === undefined) { diff --git a/_extensions/quarto-openapi/lib/schema.ts b/_extensions/quarto-openapi/lib/schema.ts index 30fb251..49a2b5c 100644 --- a/_extensions/quarto-openapi/lib/schema.ts +++ b/_extensions/quarto-openapi/lib/schema.ts @@ -2,7 +2,7 @@ * Convert OpenAPI Schema objects to markdown property tables. * * Handles: primitives, objects (including nested via flattened rows), - * arrays, allOf composition, and property attributes. + * arrays, maps, allOf/anyOf/oneOf composition, and property attributes. */ import type { Schema, Reference } from "./types.ts"; @@ -18,7 +18,7 @@ export function renderSchema( spec: OpenAPISpec, schema: Schema | Reference, ): string[] { - const resolved = isReference(schema) ? resolve(spec, schema) : schema; + const resolved = normalize(spec, schema); const lines: string[] = []; if (resolved.description) { @@ -26,21 +26,13 @@ export function renderSchema( lines.push(""); } - if (resolved.allOf) { - return renderAllOf(spec, resolved, lines); - } - const type = resolved.type; if (type === "array") { return renderArray(spec, resolved, lines); } - if ( - !resolved.properties && - resolved.additionalProperties !== undefined && - resolved.additionalProperties !== false - ) { + if (isMap(resolved)) { return renderMap(spec, resolved, lines); } @@ -48,6 +40,11 @@ export function renderSchema( return renderObject(spec, resolved, lines); } + const alternatives = resolved.anyOf ?? resolved.oneOf; + if (!type && alternatives) { + return renderAlternatives(spec, alternatives, lines); + } + // Primitive type if (type) { lines.push(formatPrimitiveType(spec, resolved)); @@ -56,44 +53,63 @@ export function renderSchema( return lines; } -function renderAllOf( - spec: OpenAPISpec, - schema: Schema, - lines: string[], -): string[] { - // Merge all properties from allOf schemas into a single object - const merged = mergeAllOf(spec, schema.allOf!); - return renderObject(spec, merged, lines); -} - /** - * Merge allOf schemas into a single schema with combined properties. + * A schema with its `$ref` resolved and its `allOf` members merged into it. + * Properties and required lists combine; for any other keyword the schema's + * own value wins, then the first member that sets it. */ -function mergeAllOf( - spec: OpenAPISpec, - schemas: (Schema | Reference)[], -): Schema { - const merged: Schema = { type: "object", properties: {}, required: [] }; - - for (const s of schemas) { - const resolved = isReference(s) ? resolve(spec, s) : s; +function normalize(spec: OpenAPISpec, schema: Schema | Reference): Schema { + const resolved = isReference(schema) ? resolve(spec, schema) : schema; + if (!resolved.allOf) return resolved; + + const { allOf, ...own } = resolved; + const merged: Record & Schema = {}; + const add = (part: Schema, override: boolean) => { + for (const [key, value] of Object.entries(part)) { + if (key === "properties") { + merged.properties = { ...merged.properties, ...part.properties }; + } else if (key === "required") { + merged.required = [...(merged.required ?? []), ...part.required!]; + } else if (override || merged[key] === undefined) { + merged[key] = value; + } + } + }; + for (const member of allOf) add(normalize(spec, member), false); + add(own, true); + return merged; +} - // Recursively merge nested allOf - const effective = - resolved.allOf ? mergeAllOf(spec, resolved.allOf) : resolved; +/** Whether a schema is a map: `additionalProperties` and no fixed properties. */ +function isMap(schema: Schema): boolean { + return ( + !schema.properties && + schema.additionalProperties !== undefined && + schema.additionalProperties !== false + ); +} - if (effective.properties) { - merged.properties = { ...merged.properties, ...effective.properties }; - } - if (effective.required) { - merged.required = [...(merged.required || []), ...effective.required]; - } - if (effective.description && !merged.description) { - merged.description = effective.description; - } - } +/** Whether a schema describes an object whose properties can be listed. */ +function isObjectLike(schema: Schema): boolean { + return schema.type === "object" || !!schema.properties; +} - return merged; +/** + * Render each alternative of an `anyOf`/`oneOf` in turn, then say whether + * `null` is also allowed. + */ +function renderAlternatives( + spec: OpenAPISpec, + members: (Schema | Reference)[], + lines: string[], +): string[] { + const alternatives = members.filter((m) => !isNullMarker(m)); + alternatives.forEach((member, i) => { + if (i > 0) lines.push("", "Or:", ""); + lines.push(...renderSchema(spec, member)); + }); + if (alternatives.length < members.length) lines.push("", "Or `null`."); + return lines; } function renderArray( @@ -106,17 +122,18 @@ function renderArray( return lines; } - const items = isReference(schema.items) - ? resolve(spec, schema.items) - : schema.items; + const items = normalize(spec, schema.items); - if (items.type === "object" || items.properties || items.allOf) { + if (isObjectLike(items)) { lines.push("Array of objects:"); lines.push(""); lines.push(...renderSchema(spec, items)); + } else if (!items.type && (items.anyOf || items.oneOf)) { + lines.push("Array of:"); + lines.push(""); + lines.push(...renderSchema(spec, items)); } else { - const itemType = formatPrimitiveType(spec, items); - lines.push(`Array of ${itemType}`); + lines.push(`Array of ${formatPrimitiveType(spec, items)}`); } return lines; @@ -134,12 +151,8 @@ function renderMap( } return lines; } - const valueSchema = isReference(ap) ? resolve(spec, ap) : ap; - if ( - valueSchema.type === "object" || - valueSchema.properties || - valueSchema.allOf - ) { + const valueSchema = normalize(spec, ap); + if (isObjectLike(valueSchema)) { lines.push("Map of string to object:"); lines.push(""); lines.push(...renderSchema(spec, valueSchema)); @@ -159,21 +172,11 @@ function renderObject( return lines; } - const rows = flattenProperties(spec, schema.properties, schema.required, "", 0); + const rows = flattenProperties(spec, schema.properties, schema.required); lines.push(...fieldTable(rows)); return lines; } -/** Whether a schema describes an object whose properties can be listed. */ -function isObjectLike(schema: Schema): boolean { - return schema.type === "object" || !!schema.properties || !!schema.allOf; -} - -/** The properties of an object-like schema, with `allOf` merged. */ -function objectFields(spec: OpenAPISpec, schema: Schema): Schema { - return schema.allOf ? mergeAllOf(spec, schema.allOf) : schema; -} - /** * Flatten object properties into rows, recursing into nested objects * with dotted path names. @@ -181,99 +184,73 @@ function objectFields(spec: OpenAPISpec, schema: Schema): Schema { function flattenProperties( spec: OpenAPISpec, properties: Record, - required: string[] | undefined, - prefix: string, - depth: number, + required?: string[], + prefix: string = "", + depth: number = 0, ): FieldRow[] { const rows: FieldRow[] = []; const requiredSet = new Set(required || []); - /** Rows for the properties of `schema`, nested under `path`. */ - const children = (schema: Schema, path: string): FieldRow[] => { - const fields = objectFields(spec, schema); - if (!fields.properties) return []; - return flattenProperties( - spec, - fields.properties, - fields.required, - path, - depth + 1, - ); - }; - for (const [name, prop] of Object.entries(properties)) { - const resolved = isReference(prop) ? resolve(spec, prop) : prop; - const displayName = prefix ? `${prefix}.${name}` : name; - const row = (type: string, attributes: string): FieldRow => ({ - name: displayName, + const schema = normalize(spec, prop); + const path = prefix ? `${prefix}.${name}` : name; + rows.push({ + name: path, depth, - type, - description: resolved.description?.trim() ?? "", - attributes, + type: formatTypeString(spec, schema), + description: schema.description ?? "", + attributes: attributesOf(schema, requiredSet.has(name)), }); - const attributes = attributesOf(resolved, requiredSet.has(name)); - const alternative = soleAlternative(spec, resolved); - - if ( - (resolved.type === "object" || resolved.properties) && - resolved.properties && - !resolved.allOf - ) { - // Nested object: emit a row for the object itself, then recurse - rows.push(row("object", "")); - rows.push(...children(resolved, displayName)); - } else if (resolved.allOf) { - const merged = mergeAllOf(spec, resolved.allOf); - rows.push({ - ...row("object", ""), - description: - (resolved.description || merged.description || "").trim(), - }); - rows.push(...children(resolved, displayName)); - } else if (alternative && isObjectLike(alternative)) { - // A nullable reference, `anyOf: [{ $ref }, { nullable: true }]`: list - // the referenced object's properties as if it were a nested object. - rows.push(row(formatTypeString(spec, resolved), attributes)); - rows.push(...children(alternative, displayName)); - } else if (resolved.type === "array" && resolved.items) { - const items = isReference(resolved.items) - ? resolve(spec, resolved.items) - : resolved.items; - - if (isObjectLike(items)) { - rows.push(row("[object]", attributes)); - rows.push(...children(items, `${displayName}[]`)); - } else { - rows.push(row(`[${typeLabel(spec, items)}]`, attributes)); - } - } else if ( - !resolved.properties && - resolved.additionalProperties !== undefined && - resolved.additionalProperties !== false - ) { - // Typed map: additionalProperties is a schema, $ref, or `true`. - const ap = resolved.additionalProperties; - const valueType = mapValueTypeLabel(spec, ap); - rows.push(row(`map[string, ${valueType}]`, attributes)); - if (ap !== true) { - const valueSchema = isReference(ap) ? resolve(spec, ap) : ap; - if (isObjectLike(valueSchema)) { - rows.push(...children(valueSchema, `${displayName}{}`)); - } - } - } else { - rows.push(row(formatTypeString(spec, resolved), attributes)); + + const nested = nestedFields(spec, schema); + if (nested?.fields.properties) { + rows.push( + ...flattenProperties( + spec, + nested.fields.properties, + nested.fields.required, + path + nested.suffix, + depth + 1, + ), + ); } } return rows; } +/** + * The object whose properties a field's child rows list, and the suffix its + * child names take after the field's name: `[]` steps into array items, `{}` + * into map values. A nullable object (`anyOf: [{ $ref }, { nullable: true }]`) + * lists the object's properties. + */ +function nestedFields( + spec: OpenAPISpec, + schema: Schema, +): { fields: Schema; suffix: string } | undefined { + if (schema.properties) return { fields: schema, suffix: "" }; + + const inner = + schema.type === "array" && schema.items + ? { schema: schema.items, suffix: "[]" } + : isMap(schema) && typeof schema.additionalProperties === "object" + ? { schema: schema.additionalProperties, suffix: "{}" } + : undefined; + if (inner) { + const found = nestedFields(spec, normalize(spec, inner.schema)); + return found && { ...found, suffix: inner.suffix + found.suffix }; + } + + const alternative = soleAlternative(spec, schema); + return alternative && nestedFields(spec, alternative); +} + /** * The attribute sentences shown after a field's description, such as * "Required. Example: `x`.", or "" when the field has none. */ -function attributesOf(schema: Schema, isRequired: boolean): string { +export function attributesOf(schema: Schema, isRequired: boolean): string { const attrs: string[] = []; if (isRequired) attrs.push("Required"); if (schema.readOnly) attrs.push("Read-only"); @@ -294,19 +271,6 @@ function attributesOf(schema: Schema, isRequired: boolean): string { const semanticFormats = new Set(["date-time", "date", "time", "duration", "uuid", "uri", "uri-reference", "email", "hostname", "ipv4", "ipv6", "byte", "binary", "password"]); -function mapValueTypeLabel( - _spec: OpenAPISpec, - value: Schema | Reference | boolean, -): string { - if (value === true) return "any"; - if (value === false) return "object"; - if (isReference(value)) { - return value.$ref.split("/").pop() || "object"; - } - if (value.type === "object" || value.properties || value.allOf) return "object"; - return value.type || "object"; -} - /** * Whether a schema only marks its parent as nullable, like the second member * of `anyOf: [{ $ref }, { nullable: true }]`. @@ -328,40 +292,65 @@ function soleAlternative(spec: OpenAPISpec, schema: Schema): Schema | undefined const members = schema.anyOf ?? schema.oneOf; if (!members) return undefined; const alternatives = members.filter((m) => !isNullMarker(m)); - if (alternatives.length !== 1) return undefined; - const [only] = alternatives; - return isReference(only) ? resolve(spec, only) : only; + return alternatives.length === 1 + ? normalize(spec, alternatives[0]) + : undefined; +} + +/** The last segment of a `$ref`, which names the schema it points to. */ +function refName(ref: string): string { + return ref.split("/").pop() || "object"; } /** - * A short name for the type a schema allows: its `type`, `object` for an - * object, the alternatives joined by `|` for `anyOf`/`oneOf`, and `any` for a - * schema that does not constrain the type. + * A short name for the type a schema allows: its `type`; `[item]` for an + * array; `map[string, value]` for a map; the alternatives joined by `|` for + * `anyOf`/`oneOf`; the schema's name where a `$ref` would recurse; and `any` + * for a schema that does not constrain the type. */ function typeLabel(spec: OpenAPISpec, schema: Schema | Reference): string { - if (isReference(schema)) return typeLabel(spec, resolve(spec, schema)); - if (schema.type) return schema.type; - if (schema.allOf) { - return schema.allOf.length === 1 - ? typeLabel(spec, schema.allOf[0]) - : "object"; + const s = normalize(spec, schema); + if (s["x-circular-ref"]) return refName(s["x-circular-ref"]); + if (s.type === "array" || (!s.type && s.items)) { + return `[${s.items ? typeLabel(spec, s.items) : "any"}]`; } - const members = schema.anyOf ?? schema.oneOf; + if (isMap(s)) { + const ap = s.additionalProperties!; + const value = + ap === true + ? "any" + : isReference(ap) + ? refName(ap.$ref) + : typeLabel(spec, ap as Schema); + return `map[string, ${value}]`; + } + if (s.type) return s.type; + const members = s.anyOf ?? s.oneOf; if (members) { - const labels = members.map((m) => - isNullMarker(m) ? "null" : typeLabel(spec, m), - ); + const labels = members.flatMap((m) => { + if (isNullMarker(m)) return ["null"]; + const label = typeLabel(spec, m); + return !isReference(m) && m.nullable ? [label, "null"] : [label]; + }); return [...new Set(labels)].join("|"); } - if (schema.properties || schema.additionalProperties) return "object"; - if (schema.items) return "array"; + if (s.properties) return "object"; return "any"; } -function formatTypeString(spec: OpenAPISpec, schema: Schema): string { +/** + * The type label for a field: the type, its format when the format says + * something about the value (or any format, with `anyFormat`), and `|null` + * when nullable. + */ +export function formatTypeString( + spec: OpenAPISpec, + schema: Schema, + anyFormat = false, +): string { let type = typeLabel(spec, schema); - if (schema.format && semanticFormats.has(schema.format)) { + if (schema.format && (anyFormat || semanticFormats.has(schema.format))) { type = `${type} (${schema.format})`; } if (schema.nullable && !type.split("|").includes("null")) { diff --git a/_extensions/quarto-openapi/lib/sections.ts b/_extensions/quarto-openapi/lib/sections.ts index 87054dd..8e1be03 100644 --- a/_extensions/quarto-openapi/lib/sections.ts +++ b/_extensions/quarto-openapi/lib/sections.ts @@ -15,7 +15,7 @@ import type { } from "./types.ts"; import { HTTP_METHODS, isReference } from "./types.ts"; import { resolve } from "./refs.ts"; -import { renderSchema } from "./schema.ts"; +import { attributesOf, formatTypeString, renderSchema } from "./schema.ts"; import { stripCode } from "./escape.ts"; import { autoIdentifier, @@ -526,18 +526,12 @@ function renderParameters( const schema = param.schema ? resolve(spec, param.schema) : undefined; - - const typeParts: string[] = []; - if (schema?.type) typeParts.push(schema.type); - if (schema?.format) typeParts.push(`(${schema.format})`); - const typeStr = typeParts.length > 0 ? typeParts.join(" ") : "string"; - return { name: param.name, depth: 0, - type: typeStr, - description: param.description?.trim() ?? "", - attributes: param.required ? "Required." : "", + type: schema ? formatTypeString(spec, schema, true) : "string", + description: param.description ?? "", + attributes: attributesOf(schema ?? {}, !!param.required), }; }); diff --git a/_extensions/quarto-openapi/lib/types.ts b/_extensions/quarto-openapi/lib/types.ts index f091379..82b582d 100644 --- a/_extensions/quarto-openapi/lib/types.ts +++ b/_extensions/quarto-openapi/lib/types.ts @@ -112,6 +112,8 @@ export interface Schema { maxLength?: number; pattern?: string; additionalProperties?: boolean | Schema | Reference; + /** Set by expandRefs on the stub that ends a circular `$ref`. */ + "x-circular-ref"?: string; } export interface Reference { diff --git a/_extensions/quarto-openapi/quarto-openapi-styles.css b/_extensions/quarto-openapi/quarto-openapi-styles.css index 530a463..ee9e97e 100644 --- a/_extensions/quarto-openapi/quarto-openapi-styles.css +++ b/_extensions/quarto-openapi/quarto-openapi-styles.css @@ -26,18 +26,3 @@ .schema-nest-2 { padding-left: 2em; } .schema-nest-3 { padding-left: 3em; } .schema-nest-4 { padding-left: 4em; } - -/* - * Field descriptions are one paragraph of spans, so that `.llms.md` can keep - * the table (see lib/fields.ts). These spans lay out as the paragraphs they - * stand for. - */ -.schema-para, -.schema-attrs { - display: block; -} - -.schema-para + .schema-para, -.schema-para + .schema-attrs { - margin-top: 0.5em; -} diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/fields.ts b/example/_extensions/posit-dev/quarto-openapi/lib/fields.ts index c3e89fe..b82daf0 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/fields.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/fields.ts @@ -2,24 +2,16 @@ * Field tables: the Name / Type / Description tables for parameters and schema * properties. * - * Every Description cell is a single paragraph of inline content. Quarto - * builds `.llms.md` from the rendered HTML with `pandoc -t gfm-raw_html`, and a - * GFM pipe table can only hold inline content. One cell with block content (a - * second paragraph, a list, a line break) makes Pandoc write `[TABLE]` in place - * of the whole table. - * - * So a description's paragraphs, and the field's attributes, become spans that - * the stylesheet displays as blocks: the HTML reads as before, and the GFM - * conversion sees one paragraph. Content that cannot be a span, such as a list - * or a code block, moves to a note under the table, which the cell points to. + * Quarto builds a page's `.llms.md` by converting its rendered HTML with + * Pandoc's GFM writer. A GFM table cell holds inline content only, so a + * description with a second paragraph, a list or a line break would turn the + * whole table into `[TABLE]`. Each field table therefore comes in two forms: + * the list table for every format but `llms-txt`, and for `llms-txt` a bullet + * list with one item per field, where any markdown fits. Quarto keeps the + * `llms-txt` form out of the HTML page and its search index. */ -import MarkdownIt from "markdown-it"; -import type { Token } from "markdown-it"; -import { listTable, type TableRow } from "./markdown.ts"; - -/** CommonMark, matching the parser that escapes descriptions. */ -const md = new MarkdownIt("commonmark"); +import { listTable } from "./markdown.ts"; export interface FieldRow { /** The field's name, dotted for nested properties (`owner.guid`). */ @@ -34,55 +26,11 @@ export interface FieldRow { attributes: string; } -/** A description split into what fits in a table cell and what does not. */ -interface SplitDescription { - /** Leading paragraphs, each as one line of inline markdown. */ - paragraphs: string[]; - /** Markdown source from the first block that cannot be inline, or "". */ - rest: string; -} - -/** Whether a top-level paragraph renders as inline content only. */ -function isInlineParagraph(inline: Token | undefined): boolean { - return !(inline?.children ?? []).some((t) => t.type === "hardbreak"); -} - -function splitDescription(description: string): SplitDescription { - const text = description.trim(); - const tokens = md.parse(text, {}); - const lines = text.split("\n"); - const paragraphs: string[] = []; - - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i]; - if (token.level !== 0 || token.nesting === -1) continue; - if (token.type === "paragraph_open" && isInlineParagraph(tokens[i + 1])) { - paragraphs.push( - tokens[i + 1].content - .split("\n") - .map((line) => line.trim()) - .join(" "), - ); - continue; - } - const start = token.map?.[0] ?? lines.length; - return { paragraphs, rest: lines.slice(start).join("\n").trim() }; - } - return { paragraphs, rest: "" }; -} - -function descriptionCell( - split: SplitDescription, - attributes: string, -): string { - const blocks = [...split.paragraphs]; - if (split.rest) blocks.push("Continued below the table."); - const parts = - blocks.length === 1 && !attributes - ? blocks - : blocks.map((p) => `[${p}]{.schema-para}`); - if (attributes) parts.push(`[${attributes}]{.schema-attrs}`); - return parts.join(" "); +/** The description followed by the attributes, as separate paragraphs. */ +function details(row: FieldRow): string { + return [row.description.trim(), row.attributes] + .filter((part) => part !== "") + .join("\n\n"); } function nameCell(row: FieldRow): string { @@ -92,34 +40,43 @@ function nameCell(row: FieldRow): string { } /** - * Render rows as a field table, followed by a note for each row whose - * description holds block content. + * The `llms-txt` form: one loose list item per field, headed by its name and + * type, with the details as the item's blocks. */ -export function fieldTable(rows: FieldRow[]): string[] { - if (rows.length === 0) return []; - - const notes: string[] = []; - const tableRows: TableRow[] = rows.map((row) => { - const split = splitDescription(row.description); - if (split.rest) { - notes.push(`- \`${row.name}\`:`, ""); - for (const line of split.rest.split("\n")) { - notes.push(line === "" ? "" : ` ${line}`); - } - notes.push(""); +function fieldList(rows: FieldRow[]): string[] { + const lines: string[] = []; + for (const row of rows) { + lines.push(`- \`${row.name}\` (\`${row.type}\`)`, ""); + const text = details(row); + if (text === "") continue; + for (const line of text.split("\n")) { + lines.push(line === "" ? "" : ` ${line}`); } - return { - cells: [ - nameCell(row), - `\`${row.type}\``, - descriptionCell(split, row.attributes), - ], - }; - }); - - const lines = listTable(["Name", "Type", "Description"], tableRows); - if (notes.length > 0) { - lines.push("", "::: {.schema-notes}", "", ...notes, ":::"); + lines.push(""); } return lines; } + +/** Render rows as a field table, plus its `llms-txt` form. */ +export function fieldTable(rows: FieldRow[]): string[] { + if (rows.length === 0) return []; + + const table = listTable( + ["Name", "Type", "Description"], + rows.map((row) => ({ + cells: [nameCell(row), `\`${row.type}\``, details(row)], + })), + ); + return [ + '::: {.content-hidden when-format="llms-txt"}', + "", + ...table, + "", + ":::", + "", + '::: {.content-visible when-format="llms-txt"}', + "", + ...fieldList(rows), + ":::", + ]; +} diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/refs.ts b/example/_extensions/posit-dev/quarto-openapi/lib/refs.ts index bbdca5d..07e6739 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/refs.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/refs.ts @@ -41,8 +41,11 @@ export function expandRefs( if (isReference(obj)) { const ref = obj.$ref; if (seen.has(ref)) { - // Circular reference — return a stub to avoid infinite recursion - return { description: `(circular reference: ${ref})` } as T; + // Circular reference: a stub that names the schema it would repeat. + return { + description: `(circular reference: ${ref})`, + "x-circular-ref": ref, + } as T; } const resolved = resolveRef(spec, ref); if (resolved === undefined) { diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts b/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts index 30fb251..49a2b5c 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts @@ -2,7 +2,7 @@ * Convert OpenAPI Schema objects to markdown property tables. * * Handles: primitives, objects (including nested via flattened rows), - * arrays, allOf composition, and property attributes. + * arrays, maps, allOf/anyOf/oneOf composition, and property attributes. */ import type { Schema, Reference } from "./types.ts"; @@ -18,7 +18,7 @@ export function renderSchema( spec: OpenAPISpec, schema: Schema | Reference, ): string[] { - const resolved = isReference(schema) ? resolve(spec, schema) : schema; + const resolved = normalize(spec, schema); const lines: string[] = []; if (resolved.description) { @@ -26,21 +26,13 @@ export function renderSchema( lines.push(""); } - if (resolved.allOf) { - return renderAllOf(spec, resolved, lines); - } - const type = resolved.type; if (type === "array") { return renderArray(spec, resolved, lines); } - if ( - !resolved.properties && - resolved.additionalProperties !== undefined && - resolved.additionalProperties !== false - ) { + if (isMap(resolved)) { return renderMap(spec, resolved, lines); } @@ -48,6 +40,11 @@ export function renderSchema( return renderObject(spec, resolved, lines); } + const alternatives = resolved.anyOf ?? resolved.oneOf; + if (!type && alternatives) { + return renderAlternatives(spec, alternatives, lines); + } + // Primitive type if (type) { lines.push(formatPrimitiveType(spec, resolved)); @@ -56,44 +53,63 @@ export function renderSchema( return lines; } -function renderAllOf( - spec: OpenAPISpec, - schema: Schema, - lines: string[], -): string[] { - // Merge all properties from allOf schemas into a single object - const merged = mergeAllOf(spec, schema.allOf!); - return renderObject(spec, merged, lines); -} - /** - * Merge allOf schemas into a single schema with combined properties. + * A schema with its `$ref` resolved and its `allOf` members merged into it. + * Properties and required lists combine; for any other keyword the schema's + * own value wins, then the first member that sets it. */ -function mergeAllOf( - spec: OpenAPISpec, - schemas: (Schema | Reference)[], -): Schema { - const merged: Schema = { type: "object", properties: {}, required: [] }; - - for (const s of schemas) { - const resolved = isReference(s) ? resolve(spec, s) : s; +function normalize(spec: OpenAPISpec, schema: Schema | Reference): Schema { + const resolved = isReference(schema) ? resolve(spec, schema) : schema; + if (!resolved.allOf) return resolved; + + const { allOf, ...own } = resolved; + const merged: Record & Schema = {}; + const add = (part: Schema, override: boolean) => { + for (const [key, value] of Object.entries(part)) { + if (key === "properties") { + merged.properties = { ...merged.properties, ...part.properties }; + } else if (key === "required") { + merged.required = [...(merged.required ?? []), ...part.required!]; + } else if (override || merged[key] === undefined) { + merged[key] = value; + } + } + }; + for (const member of allOf) add(normalize(spec, member), false); + add(own, true); + return merged; +} - // Recursively merge nested allOf - const effective = - resolved.allOf ? mergeAllOf(spec, resolved.allOf) : resolved; +/** Whether a schema is a map: `additionalProperties` and no fixed properties. */ +function isMap(schema: Schema): boolean { + return ( + !schema.properties && + schema.additionalProperties !== undefined && + schema.additionalProperties !== false + ); +} - if (effective.properties) { - merged.properties = { ...merged.properties, ...effective.properties }; - } - if (effective.required) { - merged.required = [...(merged.required || []), ...effective.required]; - } - if (effective.description && !merged.description) { - merged.description = effective.description; - } - } +/** Whether a schema describes an object whose properties can be listed. */ +function isObjectLike(schema: Schema): boolean { + return schema.type === "object" || !!schema.properties; +} - return merged; +/** + * Render each alternative of an `anyOf`/`oneOf` in turn, then say whether + * `null` is also allowed. + */ +function renderAlternatives( + spec: OpenAPISpec, + members: (Schema | Reference)[], + lines: string[], +): string[] { + const alternatives = members.filter((m) => !isNullMarker(m)); + alternatives.forEach((member, i) => { + if (i > 0) lines.push("", "Or:", ""); + lines.push(...renderSchema(spec, member)); + }); + if (alternatives.length < members.length) lines.push("", "Or `null`."); + return lines; } function renderArray( @@ -106,17 +122,18 @@ function renderArray( return lines; } - const items = isReference(schema.items) - ? resolve(spec, schema.items) - : schema.items; + const items = normalize(spec, schema.items); - if (items.type === "object" || items.properties || items.allOf) { + if (isObjectLike(items)) { lines.push("Array of objects:"); lines.push(""); lines.push(...renderSchema(spec, items)); + } else if (!items.type && (items.anyOf || items.oneOf)) { + lines.push("Array of:"); + lines.push(""); + lines.push(...renderSchema(spec, items)); } else { - const itemType = formatPrimitiveType(spec, items); - lines.push(`Array of ${itemType}`); + lines.push(`Array of ${formatPrimitiveType(spec, items)}`); } return lines; @@ -134,12 +151,8 @@ function renderMap( } return lines; } - const valueSchema = isReference(ap) ? resolve(spec, ap) : ap; - if ( - valueSchema.type === "object" || - valueSchema.properties || - valueSchema.allOf - ) { + const valueSchema = normalize(spec, ap); + if (isObjectLike(valueSchema)) { lines.push("Map of string to object:"); lines.push(""); lines.push(...renderSchema(spec, valueSchema)); @@ -159,21 +172,11 @@ function renderObject( return lines; } - const rows = flattenProperties(spec, schema.properties, schema.required, "", 0); + const rows = flattenProperties(spec, schema.properties, schema.required); lines.push(...fieldTable(rows)); return lines; } -/** Whether a schema describes an object whose properties can be listed. */ -function isObjectLike(schema: Schema): boolean { - return schema.type === "object" || !!schema.properties || !!schema.allOf; -} - -/** The properties of an object-like schema, with `allOf` merged. */ -function objectFields(spec: OpenAPISpec, schema: Schema): Schema { - return schema.allOf ? mergeAllOf(spec, schema.allOf) : schema; -} - /** * Flatten object properties into rows, recursing into nested objects * with dotted path names. @@ -181,99 +184,73 @@ function objectFields(spec: OpenAPISpec, schema: Schema): Schema { function flattenProperties( spec: OpenAPISpec, properties: Record, - required: string[] | undefined, - prefix: string, - depth: number, + required?: string[], + prefix: string = "", + depth: number = 0, ): FieldRow[] { const rows: FieldRow[] = []; const requiredSet = new Set(required || []); - /** Rows for the properties of `schema`, nested under `path`. */ - const children = (schema: Schema, path: string): FieldRow[] => { - const fields = objectFields(spec, schema); - if (!fields.properties) return []; - return flattenProperties( - spec, - fields.properties, - fields.required, - path, - depth + 1, - ); - }; - for (const [name, prop] of Object.entries(properties)) { - const resolved = isReference(prop) ? resolve(spec, prop) : prop; - const displayName = prefix ? `${prefix}.${name}` : name; - const row = (type: string, attributes: string): FieldRow => ({ - name: displayName, + const schema = normalize(spec, prop); + const path = prefix ? `${prefix}.${name}` : name; + rows.push({ + name: path, depth, - type, - description: resolved.description?.trim() ?? "", - attributes, + type: formatTypeString(spec, schema), + description: schema.description ?? "", + attributes: attributesOf(schema, requiredSet.has(name)), }); - const attributes = attributesOf(resolved, requiredSet.has(name)); - const alternative = soleAlternative(spec, resolved); - - if ( - (resolved.type === "object" || resolved.properties) && - resolved.properties && - !resolved.allOf - ) { - // Nested object: emit a row for the object itself, then recurse - rows.push(row("object", "")); - rows.push(...children(resolved, displayName)); - } else if (resolved.allOf) { - const merged = mergeAllOf(spec, resolved.allOf); - rows.push({ - ...row("object", ""), - description: - (resolved.description || merged.description || "").trim(), - }); - rows.push(...children(resolved, displayName)); - } else if (alternative && isObjectLike(alternative)) { - // A nullable reference, `anyOf: [{ $ref }, { nullable: true }]`: list - // the referenced object's properties as if it were a nested object. - rows.push(row(formatTypeString(spec, resolved), attributes)); - rows.push(...children(alternative, displayName)); - } else if (resolved.type === "array" && resolved.items) { - const items = isReference(resolved.items) - ? resolve(spec, resolved.items) - : resolved.items; - - if (isObjectLike(items)) { - rows.push(row("[object]", attributes)); - rows.push(...children(items, `${displayName}[]`)); - } else { - rows.push(row(`[${typeLabel(spec, items)}]`, attributes)); - } - } else if ( - !resolved.properties && - resolved.additionalProperties !== undefined && - resolved.additionalProperties !== false - ) { - // Typed map: additionalProperties is a schema, $ref, or `true`. - const ap = resolved.additionalProperties; - const valueType = mapValueTypeLabel(spec, ap); - rows.push(row(`map[string, ${valueType}]`, attributes)); - if (ap !== true) { - const valueSchema = isReference(ap) ? resolve(spec, ap) : ap; - if (isObjectLike(valueSchema)) { - rows.push(...children(valueSchema, `${displayName}{}`)); - } - } - } else { - rows.push(row(formatTypeString(spec, resolved), attributes)); + + const nested = nestedFields(spec, schema); + if (nested?.fields.properties) { + rows.push( + ...flattenProperties( + spec, + nested.fields.properties, + nested.fields.required, + path + nested.suffix, + depth + 1, + ), + ); } } return rows; } +/** + * The object whose properties a field's child rows list, and the suffix its + * child names take after the field's name: `[]` steps into array items, `{}` + * into map values. A nullable object (`anyOf: [{ $ref }, { nullable: true }]`) + * lists the object's properties. + */ +function nestedFields( + spec: OpenAPISpec, + schema: Schema, +): { fields: Schema; suffix: string } | undefined { + if (schema.properties) return { fields: schema, suffix: "" }; + + const inner = + schema.type === "array" && schema.items + ? { schema: schema.items, suffix: "[]" } + : isMap(schema) && typeof schema.additionalProperties === "object" + ? { schema: schema.additionalProperties, suffix: "{}" } + : undefined; + if (inner) { + const found = nestedFields(spec, normalize(spec, inner.schema)); + return found && { ...found, suffix: inner.suffix + found.suffix }; + } + + const alternative = soleAlternative(spec, schema); + return alternative && nestedFields(spec, alternative); +} + /** * The attribute sentences shown after a field's description, such as * "Required. Example: `x`.", or "" when the field has none. */ -function attributesOf(schema: Schema, isRequired: boolean): string { +export function attributesOf(schema: Schema, isRequired: boolean): string { const attrs: string[] = []; if (isRequired) attrs.push("Required"); if (schema.readOnly) attrs.push("Read-only"); @@ -294,19 +271,6 @@ function attributesOf(schema: Schema, isRequired: boolean): string { const semanticFormats = new Set(["date-time", "date", "time", "duration", "uuid", "uri", "uri-reference", "email", "hostname", "ipv4", "ipv6", "byte", "binary", "password"]); -function mapValueTypeLabel( - _spec: OpenAPISpec, - value: Schema | Reference | boolean, -): string { - if (value === true) return "any"; - if (value === false) return "object"; - if (isReference(value)) { - return value.$ref.split("/").pop() || "object"; - } - if (value.type === "object" || value.properties || value.allOf) return "object"; - return value.type || "object"; -} - /** * Whether a schema only marks its parent as nullable, like the second member * of `anyOf: [{ $ref }, { nullable: true }]`. @@ -328,40 +292,65 @@ function soleAlternative(spec: OpenAPISpec, schema: Schema): Schema | undefined const members = schema.anyOf ?? schema.oneOf; if (!members) return undefined; const alternatives = members.filter((m) => !isNullMarker(m)); - if (alternatives.length !== 1) return undefined; - const [only] = alternatives; - return isReference(only) ? resolve(spec, only) : only; + return alternatives.length === 1 + ? normalize(spec, alternatives[0]) + : undefined; +} + +/** The last segment of a `$ref`, which names the schema it points to. */ +function refName(ref: string): string { + return ref.split("/").pop() || "object"; } /** - * A short name for the type a schema allows: its `type`, `object` for an - * object, the alternatives joined by `|` for `anyOf`/`oneOf`, and `any` for a - * schema that does not constrain the type. + * A short name for the type a schema allows: its `type`; `[item]` for an + * array; `map[string, value]` for a map; the alternatives joined by `|` for + * `anyOf`/`oneOf`; the schema's name where a `$ref` would recurse; and `any` + * for a schema that does not constrain the type. */ function typeLabel(spec: OpenAPISpec, schema: Schema | Reference): string { - if (isReference(schema)) return typeLabel(spec, resolve(spec, schema)); - if (schema.type) return schema.type; - if (schema.allOf) { - return schema.allOf.length === 1 - ? typeLabel(spec, schema.allOf[0]) - : "object"; + const s = normalize(spec, schema); + if (s["x-circular-ref"]) return refName(s["x-circular-ref"]); + if (s.type === "array" || (!s.type && s.items)) { + return `[${s.items ? typeLabel(spec, s.items) : "any"}]`; } - const members = schema.anyOf ?? schema.oneOf; + if (isMap(s)) { + const ap = s.additionalProperties!; + const value = + ap === true + ? "any" + : isReference(ap) + ? refName(ap.$ref) + : typeLabel(spec, ap as Schema); + return `map[string, ${value}]`; + } + if (s.type) return s.type; + const members = s.anyOf ?? s.oneOf; if (members) { - const labels = members.map((m) => - isNullMarker(m) ? "null" : typeLabel(spec, m), - ); + const labels = members.flatMap((m) => { + if (isNullMarker(m)) return ["null"]; + const label = typeLabel(spec, m); + return !isReference(m) && m.nullable ? [label, "null"] : [label]; + }); return [...new Set(labels)].join("|"); } - if (schema.properties || schema.additionalProperties) return "object"; - if (schema.items) return "array"; + if (s.properties) return "object"; return "any"; } -function formatTypeString(spec: OpenAPISpec, schema: Schema): string { +/** + * The type label for a field: the type, its format when the format says + * something about the value (or any format, with `anyFormat`), and `|null` + * when nullable. + */ +export function formatTypeString( + spec: OpenAPISpec, + schema: Schema, + anyFormat = false, +): string { let type = typeLabel(spec, schema); - if (schema.format && semanticFormats.has(schema.format)) { + if (schema.format && (anyFormat || semanticFormats.has(schema.format))) { type = `${type} (${schema.format})`; } if (schema.nullable && !type.split("|").includes("null")) { diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts b/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts index 87054dd..8e1be03 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts @@ -15,7 +15,7 @@ import type { } from "./types.ts"; import { HTTP_METHODS, isReference } from "./types.ts"; import { resolve } from "./refs.ts"; -import { renderSchema } from "./schema.ts"; +import { attributesOf, formatTypeString, renderSchema } from "./schema.ts"; import { stripCode } from "./escape.ts"; import { autoIdentifier, @@ -526,18 +526,12 @@ function renderParameters( const schema = param.schema ? resolve(spec, param.schema) : undefined; - - const typeParts: string[] = []; - if (schema?.type) typeParts.push(schema.type); - if (schema?.format) typeParts.push(`(${schema.format})`); - const typeStr = typeParts.length > 0 ? typeParts.join(" ") : "string"; - return { name: param.name, depth: 0, - type: typeStr, - description: param.description?.trim() ?? "", - attributes: param.required ? "Required." : "", + type: schema ? formatTypeString(spec, schema, true) : "string", + description: param.description ?? "", + attributes: attributesOf(schema ?? {}, !!param.required), }; }); diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/types.ts b/example/_extensions/posit-dev/quarto-openapi/lib/types.ts index f091379..82b582d 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/types.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/types.ts @@ -112,6 +112,8 @@ export interface Schema { maxLength?: number; pattern?: string; additionalProperties?: boolean | Schema | Reference; + /** Set by expandRefs on the stub that ends a circular `$ref`. */ + "x-circular-ref"?: string; } export interface Reference { diff --git a/example/_extensions/posit-dev/quarto-openapi/quarto-openapi-styles.css b/example/_extensions/posit-dev/quarto-openapi/quarto-openapi-styles.css index 530a463..ee9e97e 100644 --- a/example/_extensions/posit-dev/quarto-openapi/quarto-openapi-styles.css +++ b/example/_extensions/posit-dev/quarto-openapi/quarto-openapi-styles.css @@ -26,18 +26,3 @@ .schema-nest-2 { padding-left: 2em; } .schema-nest-3 { padding-left: 3em; } .schema-nest-4 { padding-left: 4em; } - -/* - * Field descriptions are one paragraph of spans, so that `.llms.md` can keep - * the table (see lib/fields.ts). These spans lay out as the paragraphs they - * stand for. - */ -.schema-para, -.schema-attrs { - display: block; -} - -.schema-para + .schema-para, -.schema-para + .schema-attrs { - margin-top: 0.5em; -} diff --git a/tests/fields_test.ts b/tests/fields_test.ts index 1d27bfd..f1af282 100644 --- a/tests/fields_test.ts +++ b/tests/fields_test.ts @@ -16,110 +16,74 @@ function field(overrides: Partial): FieldRow { }; } -/** The Description cell of the only body row. */ -function descriptionCell(lines: string[]): string { - const start = lines.indexOf("* * `guid`"); - return lines[start + 2].replace(/^ {2}\* /, ""); +const HIDDEN_OPEN = '::: {.content-hidden when-format="llms-txt"}'; +const VISIBLE_OPEN = '::: {.content-visible when-format="llms-txt"}'; + +/** The table form and the `llms-txt` form, as text. */ +function forms(lines: string[]): { table: string; list: string } { + const text = lines.join("\n"); + const split = text.indexOf(VISIBLE_OPEN); + return { table: text.slice(0, split), list: text.slice(split) }; } -test("fieldTable: a one-paragraph description is emitted as is", () => { +test("fieldTable: the table is hidden from llms-txt and a list stands in", () => { const lines = fieldTable([field({ description: "The identifier." })]); - assertEquals(descriptionCell(lines), "The identifier."); -}); - -test("fieldTable: attributes share the description's paragraph", () => { - const lines = fieldTable([ - field({ description: "The identifier.", attributes: "Required." }), - ]); - assertEquals( - descriptionCell(lines), - "[The identifier.]{.schema-para} [Required.]{.schema-attrs}", - ); - // No blank line anywhere in the row, so no cell holds a second block. - assertEquals(lines.slice(lines.indexOf("* * `guid`")).indexOf(""), 3); -}); - -test("fieldTable: attributes alone are one span", () => { - const lines = fieldTable([field({ attributes: "Read-only." })]); - assertEquals(descriptionCell(lines), "[Read-only.]{.schema-attrs}"); + assertEquals(lines[0], HIDDEN_OPEN); + assertEquals(lines.filter((l) => l === VISIBLE_OPEN).length, 1); + assertEquals(lines.at(-1), ":::"); + const { table, list } = forms(lines); + assertStringIncludes(table, "* * `guid`\n * `string`\n * The identifier."); + assertStringIncludes(list, "- `guid` (`string`)\n\n The identifier."); }); -test("fieldTable: paragraphs become spans on one line", () => { - const lines = fieldTable([ - field({ - description: "First paragraph\nwraps here.\n\nSecond `code` paragraph.", - }), - ]); - assertEquals( - descriptionCell(lines), - "[First paragraph wraps here.]{.schema-para} " + - "[Second `code` paragraph.]{.schema-para}", +test("fieldTable: attributes follow the description as their own paragraph", () => { + const { table, list } = forms( + fieldTable([ + field({ description: "The identifier.", attributes: "Required." }), + ]), ); + assertStringIncludes(table, " * The identifier.\n\n Required."); + assertStringIncludes(list, " The identifier.\n\n Required."); }); -test("fieldTable: a list moves below the table, and the cell points to it", () => { - const lines = fieldTable([ - field({ - description: "Accepted values:\n\n- `a`: first\n- `b`: second", - attributes: "Required.", - }), - ]); - assertEquals( - descriptionCell(lines), - "[Accepted values:]{.schema-para} " + - "[Continued below the table.]{.schema-para} " + - "[Required.]{.schema-attrs}", - ); - const output = lines.join("\n"); +test("fieldTable: block content stays in the cell and in the list item", () => { + const description = [ + "Accepted values:", + "", + "- `a`: first", + "- `b`: second", + "", + "```json", + "{}", + "```", + ].join("\n"); + const { table, list } = forms(fieldTable([field({ description })])); assertStringIncludes( - output, - [ - "::: {.schema-notes}", - "", - "- `guid`:", - "", - " - `a`: first", - " - `b`: second", - "", - ":::", - ].join("\n"), - ); - // The note follows the table rather than sitting inside it. - assertEquals( - output.indexOf("::: {.schema-notes}") > output.lastIndexOf(":::\n\n:::"), - true, + table, + " * Accepted values:\n\n - `a`: first\n - `b`: second\n\n" + + " ```json\n {}\n ```", ); -}); - -test("fieldTable: everything from the first block on moves, in order", () => { - const lines = fieldTable([ - field({ - description: "Intro.\n\n```json\n{}\n```\n\nAfterword.", - }), - ]); assertStringIncludes( - lines.join("\n"), - "- `guid`:\n\n ```json\n {}\n ```\n\n Afterword.", + list, + "- `guid` (`string`)\n\n Accepted values:\n\n - `a`: first\n" + + " - `b`: second\n\n ```json\n {}\n ```", ); }); -test("fieldTable: a hard line break moves with its paragraph", () => { - const lines = fieldTable([ - field({ description: "Intro.\n\nLine one\\\nline two." }), - ]); - assertEquals( - descriptionCell(lines), - "[Intro.]{.schema-para} [Continued below the table.]{.schema-para}", - ); - assertStringIncludes(lines.join("\n"), " Line one\\\n line two."); +test("fieldTable: a field with no details is a bare list item", () => { + const { list } = forms(fieldTable([field({}), field({ name: "next" })])); + assertStringIncludes(list, "- `guid` (`string`)\n\n- `next` (`string`)"); }); -test("fieldTable: nested names keep their indentation class", () => { - const lines = fieldTable([ - field({ name: "owner", type: "object" }), - field({ name: "owner.guid", depth: 1 }), - ]); - assertStringIncludes(lines.join("\n"), "* * [`owner.guid`]{.schema-nest-1}"); +test("fieldTable: nested names keep their indentation class in the table", () => { + const { table, list } = forms( + fieldTable([ + field({ name: "owner", type: "object" }), + field({ name: "owner.guid", depth: 1 }), + ]), + ); + assertStringIncludes(table, "* * [`owner.guid`]{.schema-nest-1}"); + assertStringIncludes(list, "- `owner.guid` (`string`)"); }); test("fieldTable: no rows, no table", () => { diff --git a/tests/quarto_render_test.ts b/tests/quarto_render_test.ts index 71c767e..8c24862 100644 --- a/tests/quarto_render_test.ts +++ b/tests/quarto_render_test.ts @@ -59,9 +59,11 @@ async function render(markdown: string): Promise { /** * Render `markdown` as the only page of a website with `llms-txt` on, and - * return the `.llms.md` Quarto derives from the page's HTML. + * return the page's HTML and the `.llms.md` Quarto derives from it. */ -async function renderLlms(markdown: string): Promise { +async function renderSite( + markdown: string, +): Promise<{ html: string; llms: string }> { const dir = await mkdtemp(join(tmpdir(), "quarto-openapi-llms-")); try { await writeFile( @@ -70,7 +72,10 @@ async function renderLlms(markdown: string): Promise { ); await writeFile(join(dir, "index.qmd"), markdown); await execFileAsync("quarto", ["render"], { cwd: dir }); - return await readFile(join(dir, "_site", "index.llms.md"), "utf8"); + return { + html: await readFile(join(dir, "_site", "index.html"), "utf8"), + llms: await readFile(join(dir, "_site", "index.llms.md"), "utf8"), + }; } finally { await rm(dir, { recursive: true, force: true }); } @@ -193,6 +198,13 @@ test("A field table survives into llms-txt output", { skip }, async () => { description: "How it runs:\n\n- `fast`: skips checks\n- `safe`: checks first", attributes: "", }, + { + name: "note", + depth: 0, + type: "string", + description: "Line one`
`{=html}line two.", + attributes: "", + }, { name: "owner.name", depth: 1, @@ -204,19 +216,25 @@ test("A field table survives into llms-txt output", { skip }, async () => { "", ].join("\n"); - const llms = await renderLlms(markdown); + const { html, llms } = await renderSite(markdown); assertEquals(llms.includes("[TABLE]"), false, `table dropped:\n${llms}`); assertStringIncludes( llms, - "| `guid` | `string` | The identifier. Assigned by the server. " + - "Required. Example: `abc`. |", + "- `guid` (`string`)\n\n The identifier.\n\n Assigned by the server." + + "\n\n Required. Example: `abc`.", ); assertStringIncludes( llms, - "| `mode` | `string` | How it runs: Continued below the table. |", + "- `mode` (`string`)\n\n How it runs:\n\n - `fast`: skips checks\n" + + " - `safe`: checks first", ); - assertStringIncludes(llms, "| `owner.name` | `string` | Read-only. |"); - assertStringIncludes(llms, "- `fast`: skips checks"); - assertStringIncludes(llms, "- `safe`: checks first"); + assertStringIncludes(llms, "- `note` (`string`)\n\n Line one \n line two."); + assertStringIncludes(llms, "- `owner.name` (`string`)\n\n Read-only."); + + // The page keeps the table, with the list inside its row, and nothing of + // the llms-txt form. + const table = tableOf(html); + assertStringIncludes(table, "
  • fast: skips checks
  • "); + assertEquals(html.includes("(string)"), false, html); }); diff --git a/tests/render_test.ts b/tests/render_test.ts index c921f9b..c3b374d 100644 --- a/tests/render_test.ts +++ b/tests/render_test.ts @@ -170,6 +170,45 @@ test("renderSection: parameters rendered as grid table", () => { assertStringIncludes(output, "Max items"); }); +test("renderSection: parameter types and attributes come from the schema", () => { + const spec = minimalSpec({ + "/v1/pets": { + get: { + operationId: "listPets", + summary: "List pets", + parameters: [ + { + name: "id", + in: "query", + schema: { anyOf: [{ type: "integer" }, { type: "string" }] }, + }, + { + name: "tag", + in: "query", + required: true, + schema: { oneOf: [{ type: "string" }, { nullable: true }] }, + }, + { + name: "size", + in: "query", + schema: { type: "integer", format: "int64", enum: [1, 2], default: 1 }, + }, + ], + responses: { "200": { description: "OK" } }, + }, + }, + }); + + const output = renderedSection(spec); + + assertStringIncludes(output, "* * `id`\n * `integer|string`"); + assertStringIncludes(output, "* * `tag`\n * `string|null`\n * Required."); + assertStringIncludes( + output, + "* * `size`\n * `integer (int64)`\n * Default: `1`. Enum: `1`, `2`.", + ); +}); + test("renderSection: parameters heading has scoped anchor ID", () => { const spec = minimalSpec({ "/v1/pets": { diff --git a/tests/schema_test.ts b/tests/schema_test.ts index a99eaf4..4b099f0 100644 --- a/tests/schema_test.ts +++ b/tests/schema_test.ts @@ -462,9 +462,10 @@ test("renderSchema: a nullable reference is typed and expanded", () => { { $ref: "#/components/schemas/Values" } as unknown as Schema, ); - assertStringIncludes(output, "* * `source`\n * `object|null`"); - assertStringIncludes(output, "[Where the source lives.]{.schema-para}"); - assertStringIncludes(output, "[Required.]{.schema-attrs}"); + assertStringIncludes( + output, + "* * `source`\n\n * `object|null`\n\n * Where the source lives.\n\n Required.", + ); assertStringIncludes(output, "* * [`source.choice`]{.schema-nest-1}"); assertStringIncludes(output, "* * [`source.gitUrl`]{.schema-nest-1}"); assertFalse(output.includes("unknown"), output); @@ -531,9 +532,110 @@ test("renderSchema: a recursive nullable reference ends at the cycle", () => { assertStringIncludes(output, "* * `visible`\n * `object|null`"); assertStringIncludes(output, "[`visible.operator`]{.schema-nest-1}"); - // The cycle ends where the reference repeats. + // The cycle ends where the reference repeats, named by the schema. assertStringIncludes( output, - "* * [`visible.operands`]{.schema-nest-1}\n * `[any]`", + "* * [`visible.operands`]{.schema-nest-1}\n * `[Expr]`", ); }); + +test("renderSchema: allOf around a primitive keeps its type and enum", () => { + const spec = specWithSchemas({ + Status: { type: "string", enum: ["on", "off"] }, + }); + const output = rendered(spec, { + type: "object", + required: ["status"], + properties: { + status: { + description: "Current status.", + allOf: [{ $ref: "#/components/schemas/Status" } as unknown as Schema], + }, + }, + }); + + assertStringIncludes(output, "* * `status`\n\n * `string`"); + assertStringIncludes(output, "Current status.\n\n Required. Enum: `on`, `off`."); +}); + +test("renderSchema: object rows carry attributes and nullability", () => { + const spec = specWithSchemas({ + Owner: { type: "object", properties: { guid: { type: "string" } } }, + }); + const owner = { $ref: "#/components/schemas/Owner" } as unknown as Schema; + const output = rendered(spec, { + type: "object", + required: ["owner"], + properties: { + owner, + backup: { allOf: [owner], nullable: true }, + }, + }); + + assertStringIncludes(output, "* * `owner`\n * `object`\n * Required."); + assertStringIncludes(output, "* * `backup`\n * `object|null`"); + assertStringIncludes(output, "[`backup.guid`]{.schema-nest-1}"); +}); + +test("renderSchema: alternative members contribute their own null", () => { + const output = rendered(specWithSchemas(), { + type: "object", + properties: { + id: { anyOf: [{ type: "string", nullable: true }, { type: "integer" }] }, + tags: { + anyOf: [{ type: "array", items: { type: "string" } }, { nullable: true }], + }, + counts: { + type: "object", + additionalProperties: { anyOf: [{ type: "string" }, { type: "integer" }] }, + }, + }, + }); + + assertStringIncludes(output, "* * `id`\n * `string|null|integer`"); + assertStringIncludes(output, "* * `tags`\n * `[string]|null`"); + assertStringIncludes(output, "* * `counts`\n * `map[string, string|integer]`"); +}); + +test("renderSchema: a nullable array of references lists the item fields", () => { + const spec = specWithSchemas({ + Tag: { type: "object", properties: { label: { type: "string" } } }, + }); + const output = rendered(spec, { + type: "object", + properties: { + tags: { + anyOf: [ + { + type: "array", + items: { $ref: "#/components/schemas/Tag" } as unknown as Schema, + }, + { nullable: true }, + ], + }, + }, + }); + + assertStringIncludes(output, "* * `tags`\n * `[object]|null`"); + assertStringIncludes(output, "[`tags[].label`]{.schema-nest-1}"); +}); + +test("renderSchema: a top-level oneOf renders each alternative", () => { + const spec = specWithSchemas({ + Cat: { type: "object", properties: { purrs: { type: "boolean" } } }, + Dog: { type: "object", properties: { barks: { type: "boolean" } } }, + }); + const output = rendered(spec, { + oneOf: [ + { $ref: "#/components/schemas/Cat" } as unknown as Schema, + { $ref: "#/components/schemas/Dog" } as unknown as Schema, + { nullable: true }, + ], + }); + + const purrs = output.indexOf("`purrs`"); + const or = output.indexOf("\nOr:\n"); + const barks = output.indexOf("`barks`"); + assert(purrs > 0 && or > purrs && barks > or, output); + assertStringIncludes(output, "Or `null`."); +}); From 528baf637710522a5b8d4dd4aa5ca27c96ad0d57 Mon Sep 17 00:00:00 2001 From: Jordan Jensen Date: Thu, 12 Nov 2026 11:39:42 -0800 Subject: [PATCH 4/4] test: accept either GFM hard-break spelling in the llms-txt render test Pandoc 3.8 (Quarto 1.9) writes a hard line break as two trailing spaces, and Pandoc 3.10 (Quarto 1.11) writes it as a trailing backslash. Both are GFM hard breaks, so the test accepts either. Co-Authored-By: Claude Opus 5.5 --- tests/quarto_render_test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/quarto_render_test.ts b/tests/quarto_render_test.ts index 8c24862..51f4bfa 100644 --- a/tests/quarto_render_test.ts +++ b/tests/quarto_render_test.ts @@ -229,7 +229,12 @@ test("A field table survives into llms-txt output", { skip }, async () => { "- `mode` (`string`)\n\n How it runs:\n\n - `fast`: skips checks\n" + " - `safe`: checks first", ); - assertStringIncludes(llms, "- `note` (`string`)\n\n Line one \n line two."); + // Pandoc writes a hard line break as trailing spaces or as a backslash, + // depending on its version. + assert( + /- `note` \(`string`\)\n\n {2}Line one(?: {2,}|\\)\n {2}line two\./.test(llms), + `line break lost:\n${llms}`, + ); assertStringIncludes(llms, "- `owner.name` (`string`)\n\n Read-only."); // The page keeps the table, with the list inside its row, and nothing of