/*! * Copyright (c) Microsoft Corporation and contributors. All rights reserved. * Licensed under the MIT License. */ //@ts-check /** @typedef {import("@fluid-tools/api-markdown-documenter").ApiItem} ApiItem */ /** @typedef {import("@fluid-tools/api-markdown-documenter").ApiItemTransformationConfiguration} ApiItemTransformationConfiguration */ /** @typedef {import("@fluid-tools/api-markdown-documenter").ApiPackage} ApiPackage */ import { ApiItemKind, ApiItemUtilities, getApiItemTransformationConfigurationWithDefaults, HierarchyKind, loadModel, MarkdownRenderer, ReleaseTag, transformApiModel, } from "@fluid-tools/api-markdown-documenter"; import { PackageName } from "@rushstack/node-core-library"; import chalk from "chalk"; import fs from "fs-extra"; import { directiveToMarkdown } from "mdast-util-directive"; import path from "path"; import { cleanIgnored } from "../clean-ignored.mjs"; import { createApiLinkManifest } from "./api-link-manifest.mjs"; import { layoutContent } from "./api-documentation-layout.mjs"; const generatedContentNotice = ""; /** * Type guard for identifying a package API item. * * @param {ApiItem} apiItem - The API item being type-checked. * @returns {apiItem is ApiPackage} Whether the API item is a package. */ function isPackage(apiItem) { return apiItem.kind === ApiItemKind.Package; } /** * Generates the Markdown documentation suite and API link manifest for an API model. * * The documentation suite mirrors the configured document hierarchy. Each generated Markdown file includes * Docusaurus front matter and uses `uriRootDir` for links to other API items. Existing generated Markdown under * `outputDir` is removed before rendering, while manually authored files excluded by the cleanup rules are * preserved. Package filters and the other transformation settings in this function determine which API items * appear in the suite. * * The link manifest is generated from the same loaded model and normalized transformation configuration as the * Markdown. It maps each included API item's unscoped package name and qualified API name to its extension-less * document path and, for items rendered as sections, its heading ID. Candidate entries retain the API item kind * and one-based overload index when applicable so callers can resolve declarations that share a name. The * manifest contains relative document targets only; consumers are responsible for applying the version-specific * URI root. * * @param {string} inputDir - The directory containing the API model files to process. * @param {string} outputDir - The directory where the generated Markdown documentation suite will be written. * @param {string} uriRootDir - The version-specific URI root used for links between generated API documents. * @param {string} apiVersion - The API model version, such as "1", "2", or "local". Used for version-specific * generation policy and progress logging. * @param {string} manifestPath - The file path where the generated API link manifest JSON will be written. */ export async function renderApiDocumentation( inputDir, outputDir, uriRootDir, apiVersion, manifestPath, ) { /** * Logs a progress message, prefaced with the API version number to help differentiate parallel logging output. * @param {string} message - The progress message to log. */ function logProgress(message) { console.log(`(v${apiVersion}) ${message}`); } /** * Logs the error with the specified message, prefaced with the API version number to help differentiate parallel * logging output, and re-throws the error. * * @param {string} message - The progress message to log. * @param {unknown} error - The error to log and re-throw. * * @returns {never} This function always throws an error. */ function logErrorAndRethrow(message, error) { console.error(chalk.red(`(v${apiVersion}) ${message}:`)); console.error(error); throw error; } // Delete existing documentation output logProgress("Removing existing generated API docs..."); await fs.ensureDir(outputDir); // Clean existing generated API documentation files, skipping any manually authored files under the same parent directory. await cleanIgnored(outputDir); // Process API reports logProgress("Loading API model..."); const apiModel = await loadModel({ modelDirectoryPath: inputDir }); const config = getApiItemTransformationConfigurationWithDefaults({ apiModel, hierarchy: { [ApiItemKind.Model]: HierarchyKind.Document, [ApiItemKind.Namespace]: HierarchyKind.Folder, [ApiItemKind.Package]: HierarchyKind.Folder, getDocumentName: (apiItem, hierarchyConfig) => { switch (apiItem.kind) { case ApiItemKind.Model: // We inject a custom landing page ("index.mdx") for a curated package reference. // So we will give the auto-generated / complete model page its own separate document. return "package-reference"; case ApiItemKind.Namespace: case ApiItemKind.Package: // Namespace and package items generate documents within their own folder. return "index"; default: let documentName = ApiItemUtilities.createQualifiedDocumentNameForApiItem( apiItem, hierarchyConfig, ); // Docusaurus treats any document name starting with "_" as a "partial" document, which // will not be included in the site output. // See: // To work around this, while (hopefully) preventing name collisions, we will prefix // The filename with "u". E.g. `_foo.md` -> `u_foo.md`. // This doesn't affect displayed contents, strictly changes the resulting filenames and any // links to them. if (documentName.startsWith("_")) { documentName = `u${documentName}`; } return documentName; } }, }, uriRoot: uriRootDir, includeBreadcrumb: false, // Docusaurus includes this by default based on file hierarchy includeTopLevelDocumentHeading: false, // We inject `title` front-matter metadata instead startingHeadingLevel: 2, defaultSectionLayout: layoutContent, getAlertsForItem: (apiItem) => { const alerts = []; if (ApiItemUtilities.hasModifierTag(apiItem, "@system")) { alerts.push("System"); } else { if (ApiItemUtilities.isDeprecated(apiItem)) { alerts.push("Deprecated"); } // If an item is `@legacy`, ignore its release tag (we use `@alpha`+`@legacy` to mean something // entirely different from `@alpha`, so displaying the release tag would be misleading). if (ApiItemUtilities.hasModifierTag(apiItem, "@legacy")) { alerts.push("Legacy"); } else { const releaseTag = ApiItemUtilities.getEffectiveReleaseLevel(apiItem); if (releaseTag === ReleaseTag.Alpha) { alerts.push("Alpha"); } else if (releaseTag === ReleaseTag.Beta) { alerts.push("Beta"); } } } return alerts; }, exclude: (apiItem) => { // Exclude packages that aren't intended for public consumption. if (isPackage(apiItem)) { const packageName = apiItem.name; const packageScope = PackageName.getScope(packageName); // Skip packages that are published, but are not intended for direct public consumption. // TODO: Also skip `@fluid-internal` packages once we no longer have public, user-facing APIs that reference their contents. if ( ["@fluid-example", "@fluid-experimental", "@fluid-private"].includes( packageScope, ) ) { return true; } } // TODO: exclude alpha+legacy APIs, which are not intended for public consumption. return false; }, }); logProgress("Generating API documentation..."); let documents; try { documents = transformApiModel(config); } catch (error) { logErrorAndRethrow("Encountered error while processing API model", error); } // Generate API link manifest for the API model. // This is later written to disk to ensure the Docusaurus build has sufficient information to resolve API links. const apiLinkManifest = createApiLinkManifest(apiModel, config); logProgress("Writing API documents to disk..."); await Promise.all( documents.map(async (document) => { const documentApiItem = document.apiItem; if (documentApiItem === undefined) { throw new Error("Document does not have an associated API item."); } // #region Filter documents based on site-specific requirements if (apiVersion === "1") { // Skip `fluid-framework` package landing page for v1. // Custom contents for this package's landing page are maintained via a checked-in file: // `versioned_docs/version-1/fluid-framework.mdx`. if ( documentApiItem.kind === ApiItemKind.Package && documentApiItem.displayName === "fluid-framework" ) { logProgress("Skipping document generation for `fluid-framework` package."); return; } } // #endregion let fileContents; try { const documentBody = MarkdownRenderer.renderDocument(document, { mdastToMarkdownOptions: { // Ensure the `mdast-util-directive` plugin is included so we can render admonitions. extensions: [directiveToMarkdown()], }, }).contents; const frontMatter = createFrontMatter(documentApiItem, config); fileContents = [frontMatter, generatedContentNotice, documentBody] .join("\n\n") .trim(); } catch (error) { logErrorAndRethrow( `Encountered error while rendering Markdown contents for "${documentApiItem.displayName}"`, error, ); } const filePath = path.join(outputDir, `${document.documentPath}.md`); try { await fs.ensureFile(filePath); await fs.writeFile(filePath, fileContents); } catch (error) { logErrorAndRethrow( `Encountered error while writing file output for "${documentApiItem.displayName}"`, error, ); } }), ); // Write API link manifest to disk. logProgress("Writing API link manifest to disk..."); await fs.ensureFile(manifestPath); await fs.writeFile(manifestPath, `${JSON.stringify(apiLinkManifest, undefined, 2)}\n`); } /** * Generate `yaml`-formatted front-matter for the API item. For use by Docusaurus. * * @param {ApiItem} documentApiItem - The item for which front-matter is being generated. * @param {ApiItemTransformationConfiguration} config - The transformation configuration. * * @returns {string} The front-matter, formatted as a string. */ function createFrontMatter(documentApiItem, config) { let title, sidebarLabel; if (documentApiItem.kind === ApiItemKind.Model) { sidebarLabel = "Package Reference"; title = sidebarLabel; } else { sidebarLabel = documentApiItem.displayName.replace(/"/g, "").replace(/!/g, ""); title = `${sidebarLabel} ${documentApiItem.kind}`; } const frontMatter = [ "---", `title: "${title}"`, `sidebar_label: "${sidebarLabel}"`, // Associate the document with the "docs" sidebar to ensure the navigation is displayed when viewing this document. // Also ensures that Docusaurus generates a breadcrumb for this document. 'displayed_sidebar: "docsSidebar"', "---", ]; return frontMatter.join("\n"); }