/** Composes native source contracts into package references while preserving existing heading anchors. */ import { readFile } from "node:fs/promises"; import { resolve } from "node:path"; import { packageDirectory, sourceDirectory, type apiPackageDefinitions, } from "./documentation-catalog.js"; import { authoringNames, referenceLinks } from "./api-related.js"; import { leadWithCommonApis } from "./api-curation.js"; import { withFrontendExample } from "./api-frontend.js"; import type { ReferenceSource } from "./public-api.types.js"; import { nativeDocgen } from "./docgen-process.js"; export { markdownFiles } from "./docgen-process.js"; const root = resolve(import.meta.dir, "../../.."); const examplesTsconfig = resolve(root, "apps/docs/docgen.examples.json"); /** Generates one package reference and checks every extracted example in its source context. * @param definition - Existing package catalog entry. * @param exampleConfiguration - Runtime-specific example compiler configuration. * @param supporting - Shared source modules exported through this supported package. * @param selected - Public source selection for a newly documented package. * @returns Rendered reference after native checks. * @remarks Temporary checker/example output is owned by this invocation and removed on every exit. */ export async function renderApi( definition: (typeof apiPackageDefinitions)[number], exampleConfiguration: string = examplesTsconfig, supporting: readonly ReferenceSource[] = [], selected?: readonly string[], ): Promise { const { directory, packageName, slug, title } = definition; const modules = [await renderSource(directory, exampleConfiguration, selected)]; for (const source of supporting) modules.push(await renderSource(source.directory, exampleConfiguration, source.files)); const labs = (await packageMaturity(directory)) === "labs" ? "labs: true\n" : ""; const { lead, rest } = leadWithCommonApis(modules.join("\n\n"), authoringNames(slug)); const curated = lead ? `## Most-used APIs\n\nThese entries carry each API's contract and example. The complete reference follows.\n\n${lead}\n\n## Complete reference\n\n` : ""; return `---\ntitle: ${title} API\ndescription: Generated public TypeScript reference for ${packageName}.\nsearch:\n exclude: true\nsidebar:\n icon: braces\n${labs}---\n\n{/* Generated by apps/docs/scripts/generate.ts. Do not edit. */}\n\n${referenceLinks(slug)}\n\n${curated}/_snippets/generated/exports/${slug}.mdx\n\n${rest}\n`; } /** Reads the Core or Labs tier a package declares in `relkit.maturity`. * @param directory - Owning workspace package. @returns The declared tier, if any. */ async function packageMaturity(directory: string): Promise { const manifest = JSON.parse( await readFile(resolve(root, packageDirectory(directory), "package.json"), "utf8"), ) as { relkit?: { maturity?: unknown; labs?: readonly string[] } }; const area = directory.slice(`${packageDirectory(directory)}/src/`.length); if (area && manifest.relkit?.labs?.includes(area)) return "labs"; return manifest.relkit?.maturity; } /** Runs native docgen with isolated output and the original source context for examples. * @param directory - Owning workspace package. @param exampleConfiguration - Checker configuration. * @param selected - Optional public implementation files in an otherwise internal package. * @returns Composable native contract sections, including JSX declarations. */ async function renderSource( directory: string, exampleConfiguration: string, selected?: readonly string[], ): Promise { return (await nativeDocgen(directory, exampleConfiguration, selected)) .map(({ markdown, sourcePath }) => withFrontendExample( cleanDocgen(markdown, sourcePath, sourceDirectory(directory)), `${sourceDirectory(directory)}/${sourcePath}`, ), ) .join("\n\n"); } /** Removes docgen page frontmatter before composing the package reference. * @param markdown - Generated module page. @param sourcePath - Original path below src; native docgen drops nested directories from source links. * @param sourceRoot - Repository-relative source folder, when it is not the package's only `src`. * @returns Package-embeddable Markdown with accurate source links. */ export function cleanDocgen(markdown: string, sourcePath?: string, sourceRoot?: string): string { const body = markdown .replace(/^---\n[\s\S]*?\n---\n+/, "") .replace(/\n---\n+## Exports Grouped by Category\n[\s\S]*?\n---\n/, "\n"); let fence = ""; const lines: string[] = []; for (let line of body.split("\n")) { const marker = line.match(/^(`{3,}|~{3,})/)?.[1]; if (fence) { lines.push(line); if ( marker && marker[0] === fence[0] && marker.length >= fence.length && line.trim() === marker ) fence = ""; continue; } if (marker) fence = marker; else if (/^# /.test(line)) continue; else if (/^## .+\.(?:ts|tsx|mts|cts) overview$/.test(line)) line = line.replace(/^## (.+) overview$/, "## `$1`"); else line = line.replace(/^## /, "### "); if (line || lines.at(-1)) lines.push(line); } const cleaned = lines.join("\n").trim(); if (!sourcePath) return cleaned; return sourceRoot ? cleaned.replace( /(\[Source\]\(https:\/\/github\.com\/rel-kit\/relkit\/blob\/main\/)[^#)]+(#L\d+\))/g, `$1${sourceRoot}/${sourcePath}$2`, ) : cleaned.replace( /(\[Source\]\(https:\/\/github\.com\/rel-kit\/relkit\/blob\/main\/[^\n)]+\/src\/)[^#)]+(#L\d+\))/g, `$1${sourcePath}$2`, ); }