type JsonSchema = { $ref?: string type?: string title?: string description?: string enum?: Array const?: unknown default?: unknown format?: string items?: JsonSchema properties?: Record additionalProperties?: boolean | JsonSchema propertyNames?: JsonSchema required?: Array allOf?: Array anyOf?: Array oneOf?: Array deprecated?: boolean nullable?: boolean minimum?: number maximum?: number exclusiveMinimum?: number | boolean exclusiveMaximum?: number | boolean minLength?: number maxLength?: number minItems?: number maxItems?: number pattern?: string } export type RequestBody = { required?: boolean content?: Record } const INDENT = ' ' function asArray(value: unknown): Array { if (Array.isArray(value)) return value if (value && typeof value === 'object') return [value as JsonSchema] return [] } function isNullType(schema: JsonSchema): boolean { return schema.type === 'null' } function combinator( schema: JsonSchema ): { label: string; options: Array; nullable: boolean } | null { const found = schema.allOf ? { label: 'All of the following', options: asArray(schema.allOf) } : schema.anyOf ? { label: 'Any of the following', options: asArray(schema.anyOf) } : schema.oneOf ? { label: 'One of the following', options: asArray(schema.oneOf) } : null if (!found) return null const options = found.options.filter((option) => !isNullType(option)) return { ...found, options, nullable: options.length < found.options.length } } function withSingleOption(schema: JsonSchema): JsonSchema { const options = combinator(schema) if (options?.options.length !== 1) return schema return { ...options.options[0], ...schema, allOf: undefined, anyOf: undefined, oneOf: undefined } } function mapValueSchema(schema: JsonSchema): JsonSchema | null { const value = schema.additionalProperties return value && typeof value === 'object' && Object.keys(value).length ? value : null } function isNullable(schema: JsonSchema): boolean { return Boolean(schema.nullable || combinator(schema)?.nullable) } function typeName(schema: JsonSchema): string { if (schema.$ref) return schema.$ref.split('/').pop() || 'object' const options = combinator(schema) if (options) { return Array.from(new Set(options.options.map(typeName))).join(' or ') } if (schema.type === 'array') { return schema.items ? `array of ${typeName(schema.items)}` : 'array' } const mapValue = mapValueSchema(schema) if (mapValue && !schema.properties) return `object of ${typeName(mapValue)}` return schema.type ?? (schema.properties || mapValue ? 'object' : 'any') } function inlineCode(text: string): string { const longestRun = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length)) const fence = '`'.repeat(longestRun + 1) const padding = longestRun ? ' ' : '' return `${fence}${padding}${text}${padding}${fence}` } function formatValue(value: unknown): string { return inlineCode(typeof value === 'string' && value !== '' ? value : JSON.stringify(value)) } function isRealBound(value: number | undefined): value is number { return value !== undefined && Math.abs(value) < Number.MAX_SAFE_INTEGER } function bounds(schema: JsonSchema): Array { const notes: Array = [] if (isRealBound(schema.minimum)) { notes.push(`${schema.exclusiveMinimum === true ? 'greater than' : 'minimum'} ${schema.minimum}`) } if (typeof schema.exclusiveMinimum === 'number') { notes.push(`greater than ${schema.exclusiveMinimum}`) } if (isRealBound(schema.maximum)) { notes.push(`${schema.exclusiveMaximum === true ? 'less than' : 'maximum'} ${schema.maximum}`) } if (typeof schema.exclusiveMaximum === 'number') { notes.push(`less than ${schema.exclusiveMaximum}`) } return notes } function constraints(schema: JsonSchema): Array { const notes: Array = [] if (schema.format) notes.push(`format ${inlineCode(schema.format)}`) notes.push(...bounds(schema)) if (schema.minLength !== undefined) notes.push(`min length ${schema.minLength}`) if (schema.maxLength !== undefined) notes.push(`max length ${schema.maxLength}`) if (schema.minItems !== undefined) notes.push(`min items ${schema.minItems}`) if (schema.maxItems !== undefined) notes.push(`max items ${schema.maxItems}`) if (schema.pattern) notes.push(`pattern ${inlineCode(schema.pattern)}`) if (schema.propertyNames?.pattern) { notes.push(`key pattern ${inlineCode(schema.propertyNames.pattern)}`) } if (schema.propertyNames?.enum) { notes.push(`keys ${schema.propertyNames.enum.map(formatValue).join(', ')}`) } if (schema.additionalProperties === false) notes.push('no other keys') if (schema.type === 'array' && schema.items) { const itemLimits = constraints(schema.items) if (itemLimits.length) notes.push(`each item: ${itemLimits.join(', ')}`) } return notes } function enumValues(schema: JsonSchema): Array | undefined { if (schema.enum) return schema.enum if (schema.const !== undefined) return [schema.const] if (schema.type === 'array' && schema.items) return enumValues(schema.items) return undefined } function indentContinuation(text: string, indent: string): string { return text .trim() .split('\n') .map((line, index) => (index === 0 || !line.trim() ? line : `${indent}${line}`)) .join('\n') } function renderChildren(rawSchema: JsonSchema, depth: number): Array { const schema = withSingleOption(rawSchema) const options = combinator(schema) if (options) { return [ `${INDENT.repeat(depth)}- ${options.label}:`, ...options.options.flatMap((option, index) => [ `${INDENT.repeat(depth + 1)}- Option ${index + 1}${option.title ? `: ${option.title}` : ''} (${typeName(option)})${notesFor(option, INDENT.repeat(depth + 2))}`, ...renderChildren(option, depth + 2), ]), ] } if (schema.type === 'array' && schema.items) { return renderChildren(schema.items, depth) } const lines = Object.entries(schema.properties ?? {}).flatMap(([name, property]) => [ renderProperty(name, property, schema.required?.includes(name) ?? false, depth), ...renderChildren(property, depth + 1), ]) const mapValue = mapValueSchema(schema) if (mapValue) { lines.push( `${INDENT.repeat(depth)}- Any other key (${typeName(mapValue)}${ isNullable(mapValue) ? ', nullable' : '' })${notesFor(mapValue, INDENT.repeat(depth + 1))}`, ...renderChildren(mapValue, depth + 1) ) } return lines } function notesFor(rawSchema: JsonSchema, continuationIndent: string): string { const schema = withSingleOption(rawSchema) const notes: Array = [] const values = enumValues(schema) if (values?.length) notes.push(`Accepted values: ${values.map(formatValue).join(', ')}.`) if (schema.default !== undefined) notes.push(`Default: ${formatValue(schema.default)}.`) const limits = constraints(schema) if (limits.length) notes.push(`Constraints: ${limits.join(', ')}.`) const description = schema.description?.trim() ? indentContinuation(schema.description, continuationIndent) : '' const separator = description.includes('\n') ? `\n\n${continuationIndent}` : /[.!?:]$/.test(description) ? ' ' : '. ' const text = [description, notes.join(' ')].filter(Boolean).join(separator) return text ? `: ${text}` : '' } function renderProperty( name: string, schema: JsonSchema, required: boolean, depth: number ): string { const details = [typeName(schema), required ? 'required' : 'optional'] if (schema.deprecated) details.push('deprecated') if (isNullable(schema)) details.push('nullable') return `${INDENT.repeat(depth)}- ${inlineCode(name)} (${details.join(', ')})${notesFor(schema, INDENT.repeat(depth + 1))}` } export function renderRequestBodyMarkdown(requestBody: RequestBody | undefined): string | null { const bodies = Object.entries(requestBody?.content ?? {}).flatMap(([contentType, value]) => value?.schema ? [{ contentType, schema: value.schema }] : [] ) if (!bodies.length) return null const blocks = bodies.map(({ contentType, schema }) => { const summary = `Content type ${inlineCode(contentType)} (${typeName(schema)}${ requestBody?.required ? ', required' : '' })${notesFor(schema, '')}` return [summary, renderChildren(schema, 0).join('\n')].filter(Boolean).join('\n\n') }) return `### Request body\n\n${blocks.join('\n\n')}` }