import { hasAutomaticWidth, minimumUsageWidth, reportAutomaticWidth, } from "./terminal-width.ts"; import { messageRenderers } from "./message-registry.ts"; import { resolveMessageFormatter } from "./message-renderer.ts"; import { cacheTerminalTheme, renderTerminalTerm, styleCode, } from "./terminal-internal.ts"; import type { LabelTerm, SyntaxPunctuationTerm, TerminalStyle, TerminalTheme, } from "./terminal.ts"; import { type AnnotationLayout, measureAnnotation, measureText, placeText, spaceAfterLabel, trimLeadingSpace, } from "./text-layout.ts"; import { cloneMessage, commandLine, envVar, type Message, type MessageFormatOptions, type MessageFormatter, type MessageTerm, metavar, optionNames, text, } from "./message.ts"; import { cloneUsageTerm, formatUsage, formatUsageTerm, type HiddenVisibility, isDocHidden, type Usage, type UsageTerm, type UsageTermFormatOptions, } from "./usage.ts"; import { validateLabel, validateProgramName } from "./validate.ts"; /** * A documentation entry which describes a specific usage of a command or * option. It includes a subject (the usage), a description, and an optional * default value. */ export interface DocEntry { /** * The subject of the entry, which is typically a command or option * usage. */ readonly term: UsageTerm; /** * A description of the entry, which provides additional context or * information about the usage. */ readonly description?: Message; /** * An optional default value for the entry, which can be used to * indicate what the default behavior is if the command or option is not * specified. */ readonly default?: Message; /** * An optional list of valid choices for the entry, formatted as a * comma-separated {@link Message}. When present and the `showChoices` * formatting option is enabled, this is appended to the entry description. * * @since 0.10.0 */ readonly choices?: Message; /** * Declared environment bindings associated with this entry, outermost * first. These names do not guarantee that every binding is consulted * during parsing. Renderers can display them with `showEnvironment`. * @since 1.4.0 */ readonly envVars?: readonly string[]; /** * Per-entry override for showing the aliases of a command term. When * `true`, the term's `aliases` are shown even if the formatter's * `showAliases` option is off; when `false`, they are hidden even if it is * on. When omitted, the formatter's `showAliases` option decides. * Ignored for entries whose term is not a command. * @since 1.4.0 */ readonly showAliases?: boolean; } /** * A section in a document that groups related entries together. */ export interface DocSection { readonly title?: string; readonly entries: readonly DocEntry[]; } /** * A declared environment binding, independent of CLI documentation entries. * Names describe possible sources, not whether they are read during parsing. * @since 1.4.0 */ export interface EnvironmentBindingDoc { /** The full variable name, including any prefix. */ readonly name: string; /** Purpose text supplied by the binding author, without inferred values. */ readonly description?: Message; /** Visibility in documentation; `"usage"` remains visible. */ readonly hidden?: HiddenVisibility; } /** * A document page that contains multiple sections, each with its own brief * and a list of entries. This structure is used to organize documentation * for commands, options, and other related information. */ export interface DocPage { /** * Default visibility of the usage synopsis for this page. * Explicit formatter options override this value; omission defaults to true. * Runner-produced pages include the selected command or runner setting. * @since 1.4.0 */ readonly showUsage?: boolean; /** Independent environment documentation in this page's scope. @since 1.4.0 */ readonly environmentBindings?: readonly EnvironmentBindingDoc[]; readonly brief?: Message; readonly usage?: Usage; readonly description?: Message; readonly sections: readonly DocSection[]; /** * Usage examples for the program. * @since 0.10.0 */ readonly examples?: Message; /** * Author information. * @since 0.10.0 */ readonly author?: Message; /** * Information about where to report bugs. * @since 0.10.0 */ readonly bugs?: Message; readonly footer?: Message; } /** * A documentation fragment that can be either an entry or a section. * Fragments are building blocks used to construct documentation pages. */ export type DocFragment = | ({ readonly type: "entry" } & DocEntry) | ({ readonly type: "section" } & DocSection); /** * A collection of documentation fragments with an optional description. * This structure is used to gather fragments before organizing them into * a final document page. */ export interface DocFragments { /** Independent environment documentation in this scope. @since 1.4.0 */ readonly environmentBindings?: readonly EnvironmentBindingDoc[]; /** * Positive permission for source-only bindings to document this scope. * Empty fragments alone do not imply this capability. Custom combinators * must preserve it deliberately, respecting scope and hidden parents. * @since 1.4.0 */ readonly sourceOnly?: true; /** * An optional brief that provides a short summary for the collection * of fragments. * @since 0.7.12 */ readonly brief?: Message; /** * An optional description that applies to the entire collection of fragments. */ readonly description?: Message; /** * An array of documentation fragments that can be entries or sections. */ readonly fragments: readonly DocFragment[]; /** * An optional footer that appears at the bottom of the documentation. * @since 0.6.0 */ readonly footer?: Message; } /** * Returns whether a doc entry's term is hidden from documentation. * Only term types with a `hidden` field (argument, option, command, * passthrough) are checked; other types always return `false`. * * @param entry The doc entry to check. * @returns `true` if the entry should be hidden from documentation. * @since 1.0.0 */ export function isDocEntryHidden(entry: DocEntry): boolean { const term = entry.term; if ( term.type === "argument" || term.type === "option" || term.type === "command" || term.type === "passthrough" ) { return isDocHidden(term.hidden); } return false; } function getDocEntryKey(entry: DocEntry): string { const term = entry.term; switch (term.type) { case "command": return `command:${term.name}`; case "option": return `option:${[...term.names].sort().join(",")}:${term.metavar ?? ""}`; case "argument": return `argument:${term.metavar}`; default: return JSON.stringify(term); } } /** * Removes duplicate {@link DocEntry} values that share the same surface * syntax (same term type and identifying names). Doc-hidden entries are * filtered out first so they cannot influence the ordering of visible * entries. Among the remaining visible entries, the first occurrence is * kept and later duplicates are discarded. * * Positional argument entries are never deduplicated because they are * distinguished by position, not by metavar, and {@link DocEntry} does * not carry position information. * * @param entries The entries to deduplicate. * @returns A new array with hidden entries removed and duplicates * collapsed, preserving insertion order of visible entries. * @since 1.0.0 */ export function deduplicateDocEntries( entries: readonly DocEntry[], ): DocEntry[] { const seen = new Set(); const result: DocEntry[] = []; for (const entry of entries) { if (isDocEntryHidden(entry)) continue; if (entry.term.type === "argument") { result.push(entry); continue; } const key = getDocEntryKey(entry); if (!seen.has(key)) { seen.add(key); result.push(entry); } } return result; } /** * Removes duplicate entries from a list of {@link DocFragment} values. * Entry-type fragments are deduplicated by their surface syntax key. * Section-type fragments have their entries deduplicated internally. * * @param fragments The fragments to deduplicate. * @returns A new array with duplicate entries removed. * @since 1.0.0 */ export function deduplicateDocFragments( fragments: readonly DocFragment[], ): DocFragment[] { // Doc-hidden entries are skipped so they cannot influence the ordering // of visible entries. Among remaining visible entries, the first // occurrence is kept and later duplicates are discarded. // // Untitled entries/sections share a global dedup scope. // Titled sections are grouped by title and deduplicated within each group, // but entries in differently-titled sections remain independent. // Titled sections are emitted at the position of their first fragment // that contains visible entries, so hidden-only fragments do not // influence ordering. const untitledSeen = new Set(); const titledSectionMap = new Map(); const titledSectionPositioned = new Set(); // Each element is either a concrete DocFragment or a title placeholder // for a titled section whose entries are still being collected. const slots: (DocFragment | string)[] = []; for (const fragment of fragments) { if (fragment.type === "entry") { if (isDocEntryHidden(fragment)) continue; if (fragment.term.type === "argument") { slots.push(fragment); } else { const key = getDocEntryKey(fragment); if (!untitledSeen.has(key)) { untitledSeen.add(key); slots.push(fragment); } } } else if (fragment.title == null) { const dedupedEntries: DocEntry[] = []; for (const entry of fragment.entries) { if (isDocEntryHidden(entry)) continue; if (entry.term.type === "argument") { dedupedEntries.push(entry); continue; } const key = getDocEntryKey(entry); if (!untitledSeen.has(key)) { untitledSeen.add(key); dedupedEntries.push(entry); } } if (dedupedEntries.length > 0) { slots.push({ ...fragment, type: "section", entries: dedupedEntries, }); } } else { if (!titledSectionMap.has(fragment.title)) { titledSectionMap.set(fragment.title, []); } // Defer placeholder until we see a fragment with visible entries, // so the section's position reflects its first visible content. if ( !titledSectionPositioned.has(fragment.title) && fragment.entries.some((e) => !isDocEntryHidden(e)) ) { titledSectionPositioned.add(fragment.title); slots.push(fragment.title); } titledSectionMap.get(fragment.title)!.push(...fragment.entries); } } const result: DocFragment[] = []; for (const slot of slots) { if (typeof slot === "string") { const entries = deduplicateDocEntries(titledSectionMap.get(slot)!); if (entries.length > 0) { result.push({ type: "section", title: slot, entries }); } } else { result.push(slot); } } return result; } /** * Creates a deep clone of a {@link DocEntry}. The `term` is cloned via * {@link cloneUsageTerm}, and `description`, `default`, and `choices` * messages are cloned via {@link cloneMessage}. * * @param entry The documentation entry to clone. * @returns A structurally equal but referentially distinct copy. * @since 1.0.0 */ export function cloneDocEntry(entry: DocEntry): DocEntry { return { term: cloneUsageTerm(entry.term), ...(entry.envVars != null && { envVars: [...entry.envVars] }), ...(entry.description != null && { description: cloneMessage(entry.description), }), ...(entry.default != null && { default: cloneMessage(entry.default), }), ...(entry.choices != null && { choices: cloneMessage(entry.choices), }), ...(entry.showAliases != null && { showAliases: entry.showAliases }), }; } /** * Controls automatic environment documentation in help and man pages. * @since 1.4.0 */ export interface ShowEnvironmentOptions { /** The display layout. Defaults to `"inline"`. */ readonly placement?: "inline" | "section" | "both"; /** The generated section's heading. Defaults to `"Environment"`. */ readonly sectionTitle?: string; } /** * Derives an environment section from the visible entries on a help page. * Names are grouped in first-appearance order with references to their * associated entries. Empty names and hidden or empty terms are ignored. * This does not read environment values or modify the page. Entries without * CLI documentation are collected through `environmentBindings`. * * @param page The documentation page to inspect. * @param options A heading and optional filter for names without CLI references. * @returns A new section, or `undefined` when there are no visible names. * @throws {TypeError} If a used title is empty or contains control characters. * @since 1.4.0 */ export function deriveEnvironmentSection( page: DocPage, options: { readonly title?: string; readonly onlyUnreferenced?: boolean; } = {}, ): DocSection | undefined { const bindings = new Map>(); const purposes = new Map>(); for (const section of page.sections) { for (const entry of section.entries) { if (isDocEntryHidden(entry)) continue; const rendered = formatUsageTerm(entry.term, { context: "doc" }); if (rendered.trim() === "") continue; const term = entry.term; const reference: Message = term.type === "option" ? [ optionNames(term.names), ...(term.metavar == null ? [] : [text(" "), metavar(term.metavar)]), ] : term.type === "argument" ? [metavar(term.metavar)] : term.type === "command" ? [commandLine(term.name)] : [text(rendered)]; for (const name of entry.envVars ?? []) { if (name === "") continue; let references = bindings.get(name); if (references == null) { references = new Map(); bindings.set(name, references); } references.set(rendered, reference); } } } for (const binding of page.environmentBindings ?? []) { if (binding.name === "" || isDocHidden(binding.hidden)) continue; if (!bindings.has(binding.name)) bindings.set(binding.name, new Map()); const description = binding.description; if (description == null || description.length === 0) continue; let descriptions = purposes.get(binding.name); if (descriptions == null) { descriptions = new Map(); purposes.set(binding.name, descriptions); } // Compare only documented fields. Structurally compatible user terms may // carry unrelated metadata, including objects that cannot be serialized. const key = JSON.stringify( description.map((term) => { switch (term.type) { case "text": return [term.type, term.text]; case "optionName": return [term.type, term.optionName]; case "optionNames": return [term.type, term.optionNames]; case "metavar": return [term.type, term.metavar]; case "value": return [term.type, term.value]; case "values": return [term.type, term.values]; case "envVar": return [term.type, term.envVar]; case "commandLine": return [term.type, term.commandLine]; case "lineBreak": return [term.type]; case "url": return [term.type, term.url.href]; } }), ); descriptions.set(key, description); } const collected = Array.from(bindings).filter( ([, references]) => !options.onlyUnreferenced || references.size === 0, ); if (collected.length === 0) return undefined; const title = options.title ?? "Environment"; validateLabel(title); return { title, entries: collected.map(([name, references]) => { const purpose: Message = Array.from( purposes.get(name)?.values() ?? [], ).flatMap((description, i) => i === 0 ? description : [{ type: "lineBreak" }, ...description], ); const refs: Message = Array.from(references.values()).flatMap((ref, i) => i === 0 ? ref : [text(", "), ...ref], ); const description: Message = purpose.length === 0 ? refs : refs.length === 0 ? purpose : [...purpose, { type: "lineBreak" }, text("CLI: "), ...refs]; return { term: { type: "literal", value: name }, ...(description.length > 0 && { description }), }; }), }; } /** * Configuration for customizing default value display formatting. * * @since 0.4.0 */ export interface ShowDefaultOptions { /** * Text to display before the default value. * * @default `" ["` */ readonly prefix?: string; /** * Text to display after the default value. * * @default `"]"` */ readonly suffix?: string; } /** * Configuration for customizing choices display formatting. * * @since 0.10.0 */ export interface ShowChoicesOptions { /** * Text to display before the choices list. * * @default `" ("` */ readonly prefix?: string; /** * Text to display after the choices list. * * @default `")"` */ readonly suffix?: string; /** * Label text to display before the individual choice values. * * @default `"choices: "` */ readonly label?: string; /** * Maximum number of choice values to display before truncating with * `...`. Must be at least `1`. Set to `Infinity` to show all choices. * * @default `8` * @throws {RangeError} If the value is less than `1`. */ readonly maxItems?: number; } /** * Configuration for customizing how command aliases are displayed in help * output. * @since 1.4.0 */ export interface ShowAliasesOptions { /** * Text to display before the alias list. * @default `" ("` */ readonly prefix?: string; /** * Text to display after the alias list. * @default `")"` */ readonly suffix?: string; /** * Label text to display before the individual aliases. * @default `"aliases: "` */ readonly label?: string; } /** * Options for formatting a documentation page. */ export interface DocPageFormatOptions { /** * Displays declared environment bindings. `true` or `{}` selects inline * annotations; `placement` can select a section or both. Unreferenced names * get a fallback section in inline mode. Defaults to `false`. * Generated sections follow the regular sections, before examples, and are * not passed to `sectionOrder`. The original page is not modified. * @since 1.4.0 */ readonly showEnvironment?: boolean | ShowEnvironmentOptions; /** * Custom message renderer, taking precedence over theme for messages. * @since 1.3.0 */ readonly messageFormatter?: MessageFormatter; /** * Semantic terminal theme. * @since 1.3.0 */ readonly theme?: TerminalTheme; /** * Whether to include ANSI color codes in the output. * @default `false` */ colors?: boolean; /** * Number of spaces to indent terms in documentation entries. * @default `2` */ termIndent?: number; /** * Width allocated for terms before descriptions start. Set to `"auto"` * to align descriptions after the widest visible term that has content. * Terminal display width is used for automatic measurement. * * @default `26` * @since 1.3.0 Added automatic term width. */ termWidth?: number | "auto"; /** * Maximum width of the entire formatted output. */ maxWidth?: number; /** * Whether to include the usage synopsis in the output. Overrides the * page's `showUsage` default when supplied. * * @default The page default, or `true` when it is omitted. * @since 1.2.0 */ showUsage?: boolean; /** * Whether and how to display default values for options and arguments. * * - `boolean`: When `true`, displays defaults using format `[value]` * - `ShowDefaultOptions`: Custom formatting with configurable prefix and suffix * * Default values are automatically dimmed when `colors` is enabled. * * @default `false` * @since 0.4.0 * * @example * ```typescript * // Basic usage - shows "[3000]" * { showDefault: true } * * // Custom format - shows "(default: 3000)" * { showDefault: { prefix: " (default: ", suffix: ")" } } * * // Custom format - shows " - defaults to 3000" * { showDefault: { prefix: " - defaults to ", suffix: "" } } * ``` */ showDefault?: boolean | ShowDefaultOptions; /** * Whether and how to display valid choices for options and arguments * backed by enumerated value parsers (e.g., `choice()`). * * - `boolean`: When `true`, displays choices using format * `(choices: a, b, c)` * - `ShowChoicesOptions`: Custom formatting with configurable prefix, * suffix, label, and maximum number of items * * Choice values are automatically dimmed when `colors` is enabled. * * @default `false` * @since 0.10.0 * * @example * ```typescript * // Basic usage - shows "(choices: json, yaml, xml)" * { showChoices: true } * * // Custom format - shows "{json | yaml | xml}" * { showChoices: { prefix: " {", suffix: "}", label: "" } } * * // Limit displayed choices * { showChoices: { maxItems: 3 } } * ``` */ showChoices?: boolean | ShowChoicesOptions; /** * Whether and how to display the aliases of commands in command lists. * * - `boolean`: When `true`, displays aliases using format * `(aliases: i, add)` * - `ShowAliasesOptions`: Custom formatting with configurable prefix, * suffix, and label * * This is the fallback for entries that do not set * {@link DocEntry.showAliases}; an entry's own setting always wins. * Aliases are automatically dimmed when `colors` is enabled. * * @default `false` * @since 1.4.0 * * @example * ```typescript * // Basic usage - shows "(aliases: i, add)" * { showAliases: true } * * // Custom format - shows "[aka i, add]" * { showAliases: { prefix: " [", suffix: "]", label: "aka " } } * ``` */ readonly showAliases?: boolean | ShowAliasesOptions; /** * A custom comparator function to control the order of sections in the * help output. When provided, it is used instead of the default smart * sort (command-only sections first, then mixed, then option/argument-only * sections). Sections that compare equal (return `0`) preserve their * original relative order (stable sort). * * @param a The first section to compare. * @param b The second section to compare. * @returns A negative number if `a` should appear before `b`, a positive * number if `a` should appear after `b`, or `0` if they are equal. * @since 1.0.0 * * @example * ```typescript * // Sort sections alphabetically by title * { * sectionOrder: (a, b) => (a.title ?? "").localeCompare(b.title ?? "") * } * ``` */ sectionOrder?: (a: DocSection, b: DocSection) => number; } /** * Classifies a {@link DocSection} by its content type for use in the * default smart sort. * * @returns `0` for command-only sections, `1` for mixed sections, `2` for * option/argument/passthrough-only sections. */ function classifySection(section: DocSection): 0 | 1 | 2 { const hasCommand = section.entries.some((e) => e.term.type === "command"); const hasNonCommand = section.entries.some((e) => e.term.type !== "command"); if (hasCommand && !hasNonCommand) return 0; if (hasCommand && hasNonCommand) return 1; return 2; } /** * Scores a section for the default smart sort. Untitled sections receive * a bonus of `-1` so that the main (untitled) section appears before titled * sections of a similar classification. */ function scoreSection(section: DocSection): number { return classifySection(section) + (section.title == null ? -1 : 0); } /** * The default section comparator: command-only sections come first, then * mixed sections, then option/argument-only sections. Untitled sections * receive a score bonus of -1 via {@link scoreSection} so that untitled * command-only sections naturally sort before titled command-only sections. * Sections with the same score preserve their original relative order * (stable sort). */ function defaultSectionOrder(a: DocSection, b: DocSection): number { return scoreSection(a) - scoreSection(b); } /** * Formats a documentation page into a human-readable string. * * This function takes a structured {@link DocPage} and converts it into * a formatted string suitable for display in terminals or documentation. * The formatting includes proper indentation, alignment, and optional * color support. * * @param programName The name of the program, used in usage lines * @param page The documentation page to format * @param options Formatting options to customize the output * @returns A formatted string representation of the documentation page * @throws {TypeError} If `programName` is not a string, is empty, * whitespace-only, or contains control characters, if any non-empty * section's title is not a string, is empty, whitespace-only, or contains * control characters, or if `maxWidth` is not a finite integer. * @throws {RangeError} If any entry needs a description column and `maxWidth` * is too small to fit the minimum layout (less than `termIndent + 4`), or if * `showChoices.maxItems` is less than `1`, or if a theme color is invalid * (even when colors are disabled). * * @example * ```typescript * const page: DocPage = { * brief: "A CLI tool", * usage: [{ type: "literal", value: "myapp" }], * sections: [{ * title: "Options", * entries: [{ * term: { type: "option", short: "-v", long: "--verbose" }, * description: "Enable verbose output" * }] * }] * }; * * const formatted = formatDocPage("myapp", page, { colors: true }); * console.log(formatted); * ``` */ export function formatDocPage( programName: string, page: DocPage, options: DocPageFormatOptions = {}, ): string { options = { ...options, theme: cacheTerminalTheme(options.theme) }; const formatMessage = resolveMessageFormatter(options); const opaqueFormatter = options.messageFormatter != null && !messageRenderers.has(options.messageFormatter); const defaultAmbient = options.theme?.annotationStyles?.default ?? { dim: true, }; const choicesAmbient = options.theme?.annotationStyles?.choices ?? { dim: true, }; const environmentAmbient = options.theme?.annotationStyles?.environment ?? { dim: true, }; const environmentStyle = styleCode(environmentAmbient); const aliasesAmbient = options.theme?.annotationStyles?.aliases ?? { dim: true, }; const aliasesStyle = styleCode(aliasesAmbient); const showAliasesByDefault = options.showAliases != null && options.showAliases !== false; const aliasesContent = (entry: DocEntry): Message => { if (entry.term.type !== "command") return []; if (!(entry.showAliases ?? showAliasesByDefault)) return []; return (entry.term.aliases ?? []) .filter((alias) => alias !== "") .flatMap((alias, i) => i === 0 ? [text(alias)] : [text(", "), text(alias)], ); }; const environmentPlacement = typeof options.showEnvironment === "object" ? (options.showEnvironment.placement ?? "inline") : options.showEnvironment ? "inline" : undefined; const showInlineEnvironment = environmentPlacement === "inline" || environmentPlacement === "both"; const environmentContent = (entry: DocEntry): Message => [...new Set(entry.envVars ?? [])] .filter((name) => name !== "") .flatMap((name, i) => i === 0 ? [envVar(name)] : [text(", "), envVar(name)], ); const labelCache = new Map(); const label = (label: string, kind: LabelTerm["kind"]) => { const key = `${kind}:${label}`; let rendered = labelCache.get(key); if (rendered == null) { rendered = renderTerminalTerm( { type: "label", label, kind }, options.theme, options.colors, undefined, kind === "choices" ? choicesAmbient : kind === "aliases" ? aliasesAmbient : undefined, ); labelCache.set(key, rendered); } return rendered; }; const punctuationCache = new Map(); const punctuation = ( punctuation: string, kind: SyntaxPunctuationTerm["kind"], ) => { const key = `${kind}:${punctuation}`; let rendered = punctuationCache.get(key); if (rendered == null) { rendered = renderTerminalTerm( { type: "syntaxPunctuation", punctuation, kind }, options.theme, options.colors, undefined, kind.startsWith("default") ? defaultAmbient : kind.startsWith("choices") ? choicesAmbient : kind.startsWith("aliases") ? aliasesAmbient : undefined, ); punctuationCache.set(key, rendered); } return rendered; }; const showUsage = options.showUsage ?? page.showUsage ?? true; const usageLabel = page.usage != null && showUsage ? spaceAfterLabel(label("Usage:", "usage")) : ""; const usageLabelWidth = measureText(usageLabel).lastLineWidth; const defaultStyle = styleCode( options.theme?.annotationStyles?.default ?? { dim: true }, ); const choicesStyle = styleCode( options.theme?.annotationStyles?.choices ?? { dim: true }, ); validateProgramName(programName); const termIndent = options.termIndent ?? 2; if ( options.maxWidth != null && (!Number.isFinite(options.maxWidth) || !Number.isInteger(options.maxWidth)) ) { throw new TypeError( `maxWidth must be a finite integer, got ${options.maxWidth}.`, ); } // Pre-filter sections: remove entries whose terms are hidden in doc context // or structurally degenerate (e.g., option with no names, empty command). // This must happen before maxWidth validation so width checks reflect the // actual rendered output, and before rendering so empty sections (all // entries filtered) do not emit dangling section headers. const filteredSections: readonly DocSection[] = page.sections.map((s) => ({ ...s, entries: s.entries.filter((e) => { const rendered = formatUsageTerm(e.term, { context: "doc" }); return rendered.trim() !== ""; }), })); const environmentSection = environmentPlacement != null ? deriveEnvironmentSection( { ...page, sections: filteredSections }, { onlyUnreferenced: environmentPlacement === "inline", title: typeof options.showEnvironment === "object" ? options.showEnvironment.sectionTitle : undefined, }, ) : undefined; // Include the derived entries in all layout measurements, but keep their // section out of the user-supplied comparator below. page = { ...page, sections: environmentSection == null ? filteredSections : [...filteredSections, environmentSection], }; // Validate showChoices.maxItems before any per-entry rendering. if ( typeof options.showChoices === "object" && options.showChoices.maxItems != null ) { const maxItems = options.showChoices.maxItems; if (maxItems < 1) { throw new RangeError( `showChoices.maxItems must be at least 1, but got ${maxItems}.`, ); } } // Validate maxWidth against the minimum feasible layout. The minimum // depends on which page features are active: // - Entries with a description column need enough space for term + // gap + description, plus any showDefault/showChoices prefixes. // - Bare-term entries need termIndent + 1 (just 1 term char). // - "Usage: " (7 chars) + max(programName, capped widest visible term). // - Examples:/Author:/Bugs: labels are 9/7/5 chars on their own lines. const hasContent = (msg: unknown): msg is readonly unknown[] => Array.isArray(msg) && msg.length > 0; const needsDescriptionColumn = (entry: DocEntry): boolean => hasContent(entry.description) || ((options.showDefault === true || typeof options.showDefault === "object") && hasContent(entry.default)) || ((options.showChoices === true || typeof options.showChoices === "object") && hasContent(entry.choices)) || (showInlineEnvironment && hasContent(environmentContent(entry))) || hasContent(aliasesContent(entry)); const annotations = new Map< "default" | "choices" | "environment" | "aliases", AnnotationLayout >(); const annotation = ( kind: "default" | "choices" | "environment" | "aliases", ): AnnotationLayout => { const cached = annotations.get(kind); if (cached != null) return cached; if (kind === "environment") { const layout = measureAnnotation(" [env: ", "]"); annotations.set(kind, layout); return layout; } if (kind === "aliases") { const config = typeof options.showAliases === "object" ? options.showAliases : {}; const layout = measureAnnotation( punctuation(config.prefix ?? " (", "aliasesPrefix") + label(config.label ?? "aliases: ", "aliases"), punctuation(config.suffix ?? ")", "aliasesSuffix"), ); annotations.set(kind, layout); return layout; } const config = kind === "default" ? options.showDefault : options.showChoices; const prefix = punctuation( typeof config === "object" ? (config.prefix ?? (kind === "default" ? " [" : " (")) : kind === "default" ? " [" : " (", kind === "default" ? "defaultPrefix" : "choicesPrefix", ); const suffix = punctuation( typeof config === "object" ? (config.suffix ?? (kind === "default" ? "]" : ")")) : kind === "default" ? "]" : ")", kind === "default" ? "defaultSuffix" : "choicesSuffix", ); const choicesLabel = kind === "choices" ? label( typeof options.showChoices === "object" ? (options.showChoices.label ?? "choices: ") : "choices: ", "choices", ) : ""; const layout = measureAnnotation(prefix + choicesLabel, suffix); annotations.set(kind, layout); return layout; }; const automaticTermWidth = (): number | undefined => { let widest: number | undefined; for (const section of page.sections) { for (const entry of section.entries) { if (!needsDescriptionColumn(entry)) continue; const rendered = formatUsageTerm(entry.term, { colors: options.colors, theme: options.theme, optionsSeparator: ", ", context: "doc", }); const width = measureText(rendered).maxLineWidth; widest = widest == null ? width : Math.max(widest, width); } } return widest; }; const termWidth = options.termWidth === "auto" ? (automaticTermWidth() ?? 26) : (options.termWidth ?? 26); const hasEntries = page.sections.some((s) => s.entries.length > 0); const needsDescColumn = hasEntries && page.sections.some((s) => s.entries.some(needsDescriptionColumn)); // When maxWidth constrains the layout, shrink the term column so that // the description column gets a reasonable share of the available width. // Layout: <2-space gap> // Automatic sizing reserves at least half of the available space for the // description. Explicit numeric widths retain their existing behavior: // keep the requested width when it leaves >= 1 char for the description, // otherwise split the available space evenly between the two columns. let effectiveTermWidth: number; if (options.maxWidth == null) { effectiveTermWidth = termWidth; } else { const availableForColumns = options.maxWidth - termIndent - 2; const evenlySplitTermWidth = Math.max( 1, Math.floor(availableForColumns / 2), ); effectiveTermWidth = options.termWidth === "auto" && needsDescColumn ? Math.min(termWidth, evenlySplitTermWidth) : availableForColumns >= termWidth + 1 ? termWidth : evenlySplitTermWidth; } if (options.maxWidth != null) { // Validate the exact fixed text that rendering will use. Content arrays // with no terms do not render an annotation. The first suffix line is // reserved from the content budget; later suffix lines stand alone. let minDescWidth = 1; if (needsDescColumn) { for (const kind of [ "default", "choices", "environment", "aliases", ] as const) { const enabled = kind === "default" ? options.showDefault : kind === "choices" ? options.showChoices : kind === "environment" ? showInlineEnvironment : true; if ( enabled && page.sections.some((section) => section.entries.some((entry) => hasContent( kind === "environment" ? environmentContent(entry) : kind === "aliases" ? aliasesContent(entry) : entry[kind], ), ), ) ) { minDescWidth = Math.max(minDescWidth, annotation(kind).minWidth); } } } // Entry minimum: the layout needs enough space for the term column, // the 2-char gap, and at least minDescWidth for the description. // Two layout modes yield different minimums: // - Split layout (small maxWidth): descColumnWidth = ceil(a/2), // requires a >= max(2, 2*minDescWidth - 1). // - Fixed-term layout: descColumnWidth = maxWidth - termIndent - // termWidth - 2, requires maxWidth >= termIndent + termWidth + 2 + // minDescWidth. // The cheaper layout determines the true minimum. A second check // below catches values in the gap between the two valid ranges. const splitEntryMin = termIndent + 2 + Math.max(2, 2 * minDescWidth - 1); const fixedEntryMin = termIndent + 2 + termWidth + minDescWidth; const entryMin = needsDescColumn ? Math.min(splitEntryMin, fixedEntryMin) : hasEntries ? termIndent + 1 : 1; // The first line needs "Usage: " (7) + programName. Continuation // lines are indented by 7 chars and need enough room for the widest // atomic term segment. To avoid over-restricting for intentionally // long terms, the term width is capped at programNameWidth + 7; // the 7 matches the continuation indent, so terms fitting within // the first line's total width are guaranteed not to overflow. const usageMin = page.usage != null && showUsage ? minimumUsageWidth(programName, page.usage, usageLabel, options.theme) : 1; // Fixed labels cannot wrap. Examples/Author/Bugs also need two // indentation columns and at least one column for their content. let sectionMin = 1; for (const kind of ["examples", "author", "bugs"] as const) { if (!hasContent(page[kind])) continue; const title = kind === "examples" ? "Examples:" : kind === "author" ? "Author:" : "Bugs:"; sectionMin = Math.max( sectionMin, 3, measureText(label(title, kind)).maxLineWidth, ); } // User-supplied section titles, like indivisible usage leaves, may // overflow. Including them here would make existing narrow --help fail. const minWidth = Math.max(entryMin, usageMin, sectionMin); if (options.maxWidth < minWidth) { if (!hasAutomaticWidth(options)) { throw new RangeError( `maxWidth must be at least ${minWidth}, got ${options.maxWidth}.`, ); } options = { ...options, maxWidth: undefined }; effectiveTermWidth = termWidth; } // Second check: even if maxWidth passes the formula-based minimum, // the effective layout may leave too little room for fixed prefixes. if (options.maxWidth != null && needsDescColumn && minDescWidth > 1) { const avail = options.maxWidth - termIndent - 2; const descW = avail - effectiveTermWidth; if (descW < minDescWidth) { const needed = termIndent + effectiveTermWidth + 2 + minDescWidth; if (!hasAutomaticWidth(options)) { throw new RangeError( `maxWidth must be at least ${needed}, got ${options.maxWidth}.`, ); } options = { ...options, maxWidth: undefined }; effectiveTermWidth = termWidth; } } } reportAutomaticWidth(options, options.maxWidth); let output = ""; if (hasContent(page.brief)) { output += formatMessage(page.brief, { colors: options.colors, maxWidth: options.maxWidth, quotes: !options.colors, }); output += "\n"; } if (page.usage != null && showUsage) { output += usageLabel; output += indentLines( formatUsage(programName, page.usage, { colors: options.colors, theme: options.theme, maxWidth: options.maxWidth == null ? undefined : options.maxWidth - usageLabelWidth, expandCommands: true, }), usageLabelWidth, ); output += "\n"; } if (hasContent(page.description)) { output += "\n"; output += formatMessage(page.description, { colors: options.colors, maxWidth: options.maxWidth, quotes: !options.colors, }); output += "\n"; } const comparator = options.sectionOrder ?? defaultSectionOrder; // Stable sort with two-level tie-breaking: // 1. comparator result (primary) // 2. original index (secondary, preserves relative order) // // Note: previously a secondary "untitled before titled" rule was applied // here, but it caused ungrouped meta items (e.g. --help, --version) to // appear before the user's titled command sections in the output. The // correct ordering is now enforced in buildDocPage, which places titled // sections first and the untitled catch-all section last in the sections // array. const sections = filteredSections .map((s, i) => ({ section: s, index: i })) .toSorted((a, b) => { const cmp = comparator(a.section, b.section); if (cmp !== 0) return cmp; return a.index - b.index; }) .map(({ section }) => section); if (environmentSection != null) sections.push(environmentSection); for (const section of sections) { // Skip sections with no entries if (section.entries.length < 1) continue; output += "\n"; if (section.title != null) { validateLabel(section.title); const sectionLabel = label(`${section.title}:`, "section") + "\n"; output += sectionLabel; } for (const entry of section.entries) { const termOptions: UsageTermFormatOptions = { colors: options.colors, theme: options.theme, optionsSeparator: ", ", context: "doc", }; // Inspect the unwrapped replacement to distinguish explicit hard breaks // from the legacy automatic wrapping of ordinary single-line terms. // The page's theme cache avoids invoking callbacks again for layout. const unwrappedTerm = formatUsageTerm(entry.term, termOptions); const multilineReplacement = measureText(unwrappedTerm).lineCount > 1; const term = options.maxWidth == null ? unwrappedTerm : formatUsageTerm(entry.term, { ...termOptions, maxWidth: options.maxWidth - termIndent, }); const descColumnWidth = options.maxWidth == null ? undefined : options.maxWidth - termIndent - effectiveTermWidth - 2; // When the rendered term is physically wider than termWidth, the // description column starts further right on the first output line, // shrinking the first-line budget. extraTermOffset captures that // surplus so we can pass it as initialWidth to formatMessage, making // word-wrapping account for the narrower first-line space. const termVisibleWidth = measureText(term).lastLineWidth; const extraTermOffset = descColumnWidth != null ? Math.max(0, termVisibleWidth - effectiveTermWidth) : 0; const descFormatOptions: MessageFormatOptions = { colors: options.colors, quotes: section === environmentSection ? false : !options.colors, maxWidth: descColumnWidth, initialWidth: extraTermOffset > 0 ? extraTermOffset : undefined, }; let description = entry.description == null ? "" : formatMessage(entry.description, descFormatOptions); let cursor = placeText(description, { line: "", column: extraTermOffset, }).cursor; const appendAnnotation = ( content: Message, layout: AnnotationLayout, style: string, ambient: TerminalStyle, quotes: boolean, ) => { let prefixText = layout.prefix; let prefix = placeText(prefixText, cursor, descColumnWidth, 1); if ( prefix.text !== layout.prefix || (descColumnWidth != null && cursor.column === 0 && layout.prefixMetrics.firstLineWidth > descColumnWidth) ) { // Keep a layout-inserted break outside the ambient style, as before. // At column zero the heading can start here, even if placeText did // not request a break for an overflowing multiline first line. if (cursor.column > 0) description += "\n"; // The prefix (with any label) now starts a new line, so its leading // whitespace no longer separates it from anything; drop it. prefixText = trimLeadingSpace(layout.prefix); prefix = placeText(prefixText, { line: "", column: 0 }); } const rendered = formatMessage( content, { colors: options.colors ? { resetSuffix: style } : false, quotes, maxWidth: descColumnWidth == null ? undefined : descColumnWidth - layout.suffixMetrics.firstLineWidth, initialWidth: descColumnWidth != null || layout.prefixMetrics.lineCount > 1 ? prefix.cursor.column : undefined, }, ambient, ); // Content can be empty or an opaque formatter's unbreakable output. // Place the suffix at its boundary without reflowing that output. const suffix = placeText( layout.suffix, placeText(rendered, prefix.cursor).cursor, descColumnWidth, ); const annotationText = `${prefixText}${rendered}${ opaqueFormatter && options.colors ? style : "" }${suffix.text}`; description += options.colors ? `${style}${annotationText}${style ? "\x1b[0m" : ""}` : annotationText; cursor = suffix.cursor; }; const aliases = aliasesContent(entry); if (hasContent(aliases)) { appendAnnotation( aliases, annotation("aliases"), aliasesStyle, aliasesAmbient, false, ); } if (options.showDefault && hasContent(entry.default)) { appendAnnotation( entry.default, annotation("default"), defaultStyle, defaultAmbient, !options.colors, ); } // Append choices if showChoices is enabled and choices exist if (options.showChoices && hasContent(entry.choices)) { const maxItems = typeof options.showChoices === "object" ? (options.showChoices.maxItems ?? 8) : 8; // Truncate at the Message level by counting value terms const terms = Array.isArray(entry.choices) ? entry.choices : []; let truncatedTerms: readonly MessageTerm[] = terms; let truncated = false; if (maxItems < Infinity) { let valueCount = 0; let cutIndex = terms.length; for (let i = 0; i < terms.length; i++) { if (terms[i].type === "value") { valueCount++; if (valueCount > maxItems) { // Cut before the separator that precedes this value cutIndex = i > 0 && terms[i - 1].type === "text" ? i - 1 : i; truncated = true; break; } } } if (truncated) { truncatedTerms = [...terms.slice(0, cutIndex), text(", ...")]; } } appendAnnotation( truncatedTerms, annotation("choices"), choicesStyle, choicesAmbient, false, ); } if (showInlineEnvironment) { const content = environmentContent(entry); if (hasContent(content)) { appendAnnotation( content, annotation("environment"), environmentStyle, environmentAmbient, false, ); } } const paddedTerm = ansiAwareRightPad(term, effectiveTermWidth); output += `${" ".repeat(termIndent)}${ multilineReplacement ? indentLines(paddedTerm, termIndent) : paddedTerm }${ description === "" ? "" : ` ${indentLines(description, termIndent + effectiveTermWidth + 2)}` }\n`; } } if (hasContent(page.examples)) { output += "\n"; const examplesLabel = label("Examples:", "examples") + "\n"; output += examplesLabel; const examplesContent = formatMessage(page.examples, { colors: options.colors, maxWidth: options.maxWidth == null ? undefined : options.maxWidth - 2, quotes: !options.colors, }); output += " " + indentLines(examplesContent, 2); output += "\n"; } if (hasContent(page.author)) { output += "\n"; const authorLabel = label("Author:", "author") + "\n"; output += authorLabel; const authorContent = formatMessage(page.author, { colors: options.colors, maxWidth: options.maxWidth == null ? undefined : options.maxWidth - 2, quotes: !options.colors, }); output += " " + indentLines(authorContent, 2); output += "\n"; } if (hasContent(page.bugs)) { output += "\n"; const bugsLabel = label("Bugs:", "bugs") + "\n"; output += bugsLabel; const bugsContent = formatMessage(page.bugs, { colors: options.colors, maxWidth: options.maxWidth == null ? undefined : options.maxWidth - 2, quotes: !options.colors, }); output += " " + indentLines(bugsContent, 2); output += "\n"; } if (hasContent(page.footer)) { output += "\n"; output += formatMessage(page.footer, { colors: options.colors, maxWidth: options.maxWidth, quotes: !options.colors, }); } return output; } function indentLines(text: string, indent: number): string { return text.split("\n").join("\n" + " ".repeat(indent)); } function ansiAwareRightPad( text: string, length: number, char: string = " ", ): string { // Padding is appended at the end, so only the last line's width // matters for deciding how many spaces to add. const visibleWidth = measureText(text).lastLineWidth; if (visibleWidth >= length) { return text; } return text + char.repeat(length - visibleWidth); }