|
| 1 | +/** |
| 2 | + * Builds a JSDoc comment string from OpenAPI schema metadata. |
| 3 | + * Returns an empty string if there is no relevant metadata. |
| 4 | + */ |
| 5 | +export function buildJsDoc(data: Record<string, unknown>): string { |
| 6 | + const lines: string[] = []; |
| 7 | + |
| 8 | + const description = data["description"] as string | undefined; |
| 9 | + const summary = data["summary"] as string | undefined; |
| 10 | + const example = data["example"]; |
| 11 | + const examples = data["examples"] as |
| 12 | + | Record<string, { value?: unknown }> |
| 13 | + | undefined; |
| 14 | + const defaultValue = data["default"]; |
| 15 | + const format = data["format"] as string | undefined; |
| 16 | + const deprecated = data["deprecated"] as boolean | undefined; |
| 17 | + |
| 18 | + const mainText = description ?? summary; |
| 19 | + |
| 20 | + if (mainText) { |
| 21 | + // Escape */ to prevent prematurely closing the JSDoc block |
| 22 | + const escaped = String(mainText).replace(/\*\//gu, "* /"); |
| 23 | + const textLines = escaped.split("\n"); |
| 24 | + |
| 25 | + for (const line of textLines) { |
| 26 | + lines.push(` * ${line}`); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + if (format !== undefined) { |
| 31 | + lines.push(` * @format ${format}`); |
| 32 | + } |
| 33 | + |
| 34 | + if (defaultValue !== undefined) { |
| 35 | + lines.push(` * @default ${JSON.stringify(defaultValue)}`); |
| 36 | + } |
| 37 | + |
| 38 | + // Use scalar `example`, or fall back to the first value from `examples` |
| 39 | + const exampleValue = |
| 40 | + example !== undefined |
| 41 | + ? example |
| 42 | + : examples !== undefined |
| 43 | + ? Object.values(examples)[0]?.value |
| 44 | + : undefined; |
| 45 | + |
| 46 | + if (exampleValue !== undefined) { |
| 47 | + lines.push(` * @example ${JSON.stringify(exampleValue)}`); |
| 48 | + } |
| 49 | + |
| 50 | + if (deprecated === true) { |
| 51 | + lines.push(` * @deprecated`); |
| 52 | + } |
| 53 | + |
| 54 | + if (lines.length === 0) { |
| 55 | + return ""; |
| 56 | + } |
| 57 | + |
| 58 | + return `/**\n${lines.join("\n")}\n */\n`; |
| 59 | +} |
0 commit comments