#!/usr/bin/env node import { mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs'; import { dirname, relative } from 'node:path'; import { collectOperations, readOpenApi, repositoryRootFrom } from './sdk-snippets.mjs'; const GENERATED_MARKER = 'Generated by scripts/generate-api-reference.mjs. Do not edit.'; const repositoryRoot = repositoryRootFrom(import.meta.url); const contentRoot = `${repositoryRoot}/cloudpdf/website/src/content/docs/api-reference`; const openapi = readOpenApi(repositoryRoot); // All editorial content (operation titles, group titles, slugs) lives in the // contract registry and arrives here as x-docs-* extensions — this script is // a pure projection of openapi.json into MDX pages and nav metadata. const docsGroups = openapi['x-docs-groups']; if (!docsGroups) { throw new Error('openapi.json has no x-docs-groups — regenerate it from @cloudpdf/contract.'); } /** URL segments for a fern group path, honouring per-group slug overrides. */ function groupSegments(groups) { return groups.map((name, index) => { const key = groups.slice(0, index + 1).join('.'); const entry = docsGroups[key]; if (!entry) throw new Error(`No x-docs-groups entry for "${key}" — add it to the contract.`); return entry.slug ?? name; }); } export function buildGeneratedFiles() { const operations = collectOperations(openapi); const files = new Map(); const entriesByDirectory = new Map(); for (const operation of operations) { const slug = kebabCase(operation.sdkMethod); const directory = groupSegments(operation.groups).join('/'); const path = `${directory}/${slug}.mdx`; if (files.has(path)) throw new Error(`Duplicate generated API reference path: ${path}`); const title = operation.title; if (!title) throw new Error(`No x-docs-title for ${operation.operationId} in openapi.json.`); files.set( path, `---\n` + `title: ${yamlString(title)}\n` + `description: ${yamlString(operation.summary)}\n` + // Frontmatter rides the Nextra pageMap into the client, so the // sidebar badges each operation from here — no parallel nav file. `method: ${operation.method.toUpperCase()}\n` + (operation.operatorOnly ? `audience: operator\n` : '') + `---\n\n` + `{/* ${GENERATED_MARKER} */}\n\n` + `# ${title}\n\n` + `\n`, ); const entries = entriesByDirectory.get(directory) ?? []; entries.push({ slug, title: sidebarTitle(operation.sdkMethod) }); entriesByDirectory.set(directory, entries); } // x-docs-groups key order is sidebar order, at every level of the tree. const groupList = Object.entries(docsGroups).map(([key, entry]) => { const parts = key.split('.'); return { parentDirectory: groupSegments(parts.slice(0, -1)).join('/'), slug: entry.slug ?? parts.at(-1), title: entry.title, depth: parts.length, }; }); for (const [directory, entries] of entriesByDirectory) { const childGroups = groupList.filter((group) => group.parentDirectory === directory); const metaEntries = [ ...entries.map(({ slug, title }) => ` ${objectKey(slug)}: ${jsString(title)},`), ...childGroups.map(({ slug, title }) => ` ${objectKey(slug)}: ${jsString(title)},`), ]; files.set( `${directory}/_meta.ts`, `// ${GENERATED_MARKER}\nexport default {\n${metaEntries.join('\n')}\n};\n`, ); } // The reference's own hand-written pages. Their titles are the // website's editorial call (unlike operations and groups, which the // contract owns), but their nav order lives here because this script // owns the generated _meta.ts they share with the resource groups. const staticPages = [ { slug: 'index', title: 'Overview' }, { slug: 'authentication', title: 'Authentication' }, ]; const topGroups = groupList.filter((group) => group.depth === 1); files.set( '_meta.ts', `// ${GENERATED_MARKER}\nexport default {\n` + [...staticPages, ...topGroups.map((group) => ({ slug: group.slug, title: group.title }))] .map(({ slug, title }) => ` ${objectKey(slug)}: ${jsString(title)},`) .join('\n') + `\n};\n`, ); return files; } function generatedFilesOnDisk(directory) { const found = []; let entries = []; try { entries = readdirSync(directory); } catch { return found; } for (const entry of entries) { const absolute = `${directory}/${entry}`; if (statSync(absolute).isDirectory()) { found.push(...generatedFilesOnDisk(absolute)); continue; } if (readFileSync(absolute, 'utf8').includes(GENERATED_MARKER)) found.push(absolute); } return found; } const expected = buildGeneratedFiles(); if (process.argv.includes('--check')) { const stale = []; for (const [path, contents] of expected) { try { if (readFileSync(`${contentRoot}/${path}`, 'utf8') !== contents) stale.push(path); } catch { stale.push(path); } } for (const absolute of generatedFilesOnDisk(contentRoot)) { const path = relative(contentRoot, absolute); if (!expected.has(path)) stale.push(path); } if (stale.length) { console.error( `Generated API reference pages are stale:\n${[...new Set(stale)].map((path) => `- ${path}`).join('\n')}`, ); console.error('Run: pnpm --filter @cloudpdf/website api:pages'); process.exit(1); } console.log(`API reference pages are current (${openapi.info.version}, ${expected.size} files).`); process.exit(0); } for (const absolute of generatedFilesOnDisk(contentRoot)) { const path = relative(contentRoot, absolute); if (!expected.has(path)) unlinkSync(absolute); } for (const [path, contents] of expected) { const absolute = `${contentRoot}/${path}`; mkdirSync(dirname(absolute), { recursive: true }); writeFileSync(absolute, contents); } console.log(`Wrote ${expected.size} generated API reference files.`); function kebabCase(value) { return value .replace(/([a-z0-9])([A-Z])/g, '$1-$2') .replace(/_/g, '-') .toLowerCase(); } function sidebarTitle(value) { return value .replace(/([a-z0-9])([A-Z])/g, '$1 $2') .replace(/_/g, ' ') .replace(/^./, (character) => character.toUpperCase()); } function yamlString(value) { const normalized = String(value).replace(/\r?\n/g, ' '); return normalized.includes("'") ? JSON.stringify(normalized) : `'${normalized}'`; } function jsString(value) { return `'${String(value) .replace(/\\/g, '\\\\') .replace(/'/g, "\\'") .replace(/\r/g, '\\r') .replace(/\n/g, '\\n')}'`; } function objectKey(value) { return /^[A-Za-z_$][\w$]*$/.test(value) ? value : jsString(value); }