politty 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/{arg-registry-BoqVZRFO.d.ts → arg-registry-DDJpsUea.d.cts} +24 -2
  2. package/dist/arg-registry-DDJpsUea.d.cts.map +1 -0
  3. package/dist/{arg-registry-BoqVZRFO.d.cts → arg-registry-DDJpsUea.d.ts} +24 -2
  4. package/dist/arg-registry-DDJpsUea.d.ts.map +1 -0
  5. package/dist/augment.d.cts +1 -1
  6. package/dist/augment.d.ts +1 -1
  7. package/dist/cli.cjs +1 -1
  8. package/dist/cli.js +1 -1
  9. package/dist/completion/index.d.cts +2 -2
  10. package/dist/completion/index.d.ts +2 -2
  11. package/dist/docs/index.cjs +827 -43
  12. package/dist/docs/index.cjs.map +1 -1
  13. package/dist/docs/index.d.cts +45 -3
  14. package/dist/docs/index.d.cts.map +1 -1
  15. package/dist/docs/index.d.ts +45 -3
  16. package/dist/docs/index.d.ts.map +1 -1
  17. package/dist/docs/index.js +827 -43
  18. package/dist/docs/index.js.map +1 -1
  19. package/dist/{index-Csk1VFou.d.ts → index-DKGn3lIl.d.ts} +2 -2
  20. package/dist/{index-Csk1VFou.d.ts.map → index-DKGn3lIl.d.ts.map} +1 -1
  21. package/dist/{index-Ct48_myg.d.cts → index-WyViqW59.d.cts} +2 -2
  22. package/dist/{index-Ct48_myg.d.cts.map → index-WyViqW59.d.cts.map} +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.d.cts +3 -3
  25. package/dist/index.d.ts +3 -3
  26. package/dist/index.js +1 -1
  27. package/dist/prompt/clack/index.d.cts +1 -1
  28. package/dist/prompt/clack/index.d.ts +1 -1
  29. package/dist/prompt/index.d.cts +1 -1
  30. package/dist/prompt/index.d.ts +1 -1
  31. package/dist/prompt/inquirer/index.d.cts +1 -1
  32. package/dist/prompt/inquirer/index.d.ts +1 -1
  33. package/dist/{runner--Zn4KN9B.js → runner-D43SkHt5.js} +119 -18
  34. package/dist/runner-D43SkHt5.js.map +1 -0
  35. package/dist/{runner-BloFWJEB.cjs → runner-DvFvokV6.cjs} +119 -18
  36. package/dist/runner-DvFvokV6.cjs.map +1 -0
  37. package/package.json +6 -6
  38. package/dist/arg-registry-BoqVZRFO.d.cts.map +0 -1
  39. package/dist/arg-registry-BoqVZRFO.d.ts.map +0 -1
  40. package/dist/runner--Zn4KN9B.js.map +0 -1
  41. package/dist/runner-BloFWJEB.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["escapeTableCell","formatDefaultValue","generateAnchor","path","path","fs","getExtractedFields","resolveLazyCommand","createLogCollector","extractFields","z","escapeTableCell","z","extractFields","path"],"sources":["../../src/docs/types.ts","../../src/docs/default-renderers.ts","../../src/docs/doc-comparator.ts","../../src/docs/doc-generator.ts","../../src/docs/example-executor.ts","../../src/docs/render-args.ts","../../src/docs/render-index.ts","../../src/docs/golden-test.ts"],"sourcesContent":["import type { ExtractedFields, ResolvedFieldMeta } from \"../core/schema-extractor.js\";\nimport type { AnyCommand, ArgsSchema, Example } from \"../types.js\";\nimport type { ArgsShape, ArgsTableOptions } from \"./render-args.js\";\n\n/** Heading level for markdown headings (1-6) */\nexport type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;\n\n/**\n * Options for rendering command index\n */\nexport type CommandIndexOptions = {\n /** Base heading level (default: 3, which renders as ###) */\n headingLevel?: HeadingLevel;\n /** Only include leaf commands (commands without subcommands). Default: true */\n leafOnly?: boolean;\n};\n\n/**\n * Command information for rendering\n */\nexport interface CommandInfo {\n /** Command name */\n name: string;\n /** Command description */\n description?: string | undefined;\n /** Alternative names (aliases) for this command */\n aliases?: string[] | undefined;\n /** Full command path (e.g., \"my-cli config get\") */\n fullCommandPath: string;\n /** Command path relative to root (e.g., \"\" for root, \"config\" for subcommand) */\n commandPath: string;\n /** Command depth (1 for root commands, 2 for subcommands, etc.) */\n depth: number;\n /** Positional arguments */\n positionalArgs: ResolvedFieldMeta[];\n /** Options (non-positional arguments) */\n options: ResolvedFieldMeta[];\n /** Subcommand information */\n subCommands: SubCommandInfo[];\n /** Extracted field information from schema */\n extracted: ExtractedFields | null;\n /** Original command object */\n command: AnyCommand;\n /** Additional notes */\n notes?: string | undefined;\n /** File path where this command is rendered (for cross-file links) */\n filePath?: string | undefined;\n /** Map of command path to file path (for cross-file links) */\n fileMap?: Record<string, string> | undefined;\n /** Example definitions from command */\n examples?: Example[] | undefined;\n /** Example execution results (populated when examples are executed) */\n exampleResults?: ExampleExecutionResult[] | undefined;\n /** Path to root document file (for global options link generation) */\n rootDocPath?: string | undefined;\n /** Whether global options exist (for global options link generation) */\n hasGlobalOptions?: boolean;\n}\n\n/**\n * Subcommand information\n */\nexport interface SubCommandInfo {\n /** Subcommand name */\n name: string;\n /** Subcommand description */\n description?: string | undefined;\n /** Alternative names (aliases) for this subcommand */\n aliases?: string[] | undefined;\n /** Full command path */\n fullPath: string[];\n}\n\n/**\n * Example execution result\n */\nexport interface ExampleExecutionResult {\n /** Command arguments that were executed */\n cmd: string;\n /** Description of the example */\n desc: string;\n /** Expected output (if defined in example) */\n expectedOutput?: string | undefined;\n /** Captured stdout */\n stdout: string;\n /** Captured stderr */\n stderr: string;\n /** Whether execution was successful */\n success: boolean;\n}\n\n/**\n * Example execution config for a specific command path\n * If a command path is specified in ExampleConfig, its examples will be executed\n */\nexport interface ExampleCommandConfig {\n /** Mock setup before running examples */\n mock?: () => void | Promise<void>;\n /** Mock cleanup after running examples */\n cleanup?: () => void | Promise<void>;\n}\n\n/**\n * Example execution configuration\n * Key is command path (e.g., \"\", \"config\", \"config get\")\n * All specified command paths will have their examples executed\n *\n * @example\n * // With mock setup\n * { \"\": { mock: () => mockFs(), cleanup: () => restoreFs() } }\n *\n * // Without mock (just execute)\n * { \"user\": true }\n */\nexport type ExampleConfig = Record<string, ExampleCommandConfig | true>;\n\n/**\n * Render function type for custom markdown generation\n */\nexport type RenderFunction = (info: CommandInfo) => string;\n\n/**\n * Section render function type (legacy)\n * @param defaultContent - The default rendered content for this section\n * @param info - Command information\n * @returns The final content to render (return empty string to hide section)\n * @deprecated Use context-based render functions instead\n */\nexport type SectionRenderFunction = (defaultContent: string, info: CommandInfo) => string;\n\n/**\n * Render options for options/arguments\n */\nexport interface RenderContentOptions {\n /** Style for rendering */\n style?: \"table\" | \"list\";\n /** Include heading (default: true) */\n withHeading?: boolean;\n}\n\n/**\n * Options render context\n */\nexport interface OptionsRenderContext {\n /** Options to render */\n options: ResolvedFieldMeta[];\n /** Render function that accepts options and optional rendering options */\n render: (options: ResolvedFieldMeta[], opts?: RenderContentOptions) => string;\n /** Heading prefix (e.g., \"###\") */\n heading: string;\n /** Command information */\n info: CommandInfo;\n}\nexport type OptionsRenderFunction = (context: OptionsRenderContext) => string;\n\n/**\n * Arguments render context\n */\nexport interface ArgumentsRenderContext {\n /** Arguments to render */\n args: ResolvedFieldMeta[];\n /** Render function that accepts arguments and optional rendering options */\n render: (args: ResolvedFieldMeta[], opts?: RenderContentOptions) => string;\n /** Heading prefix (e.g., \"###\") */\n heading: string;\n /** Command information */\n info: CommandInfo;\n}\nexport type ArgumentsRenderFunction = (context: ArgumentsRenderContext) => string;\n\n/**\n * Subcommands render options\n */\nexport interface SubcommandsRenderOptions {\n /** Generate anchor links */\n generateAnchors?: boolean;\n /** Include heading (default: true) */\n withHeading?: boolean;\n}\n\n/**\n * Subcommands render context\n */\nexport interface SubcommandsRenderContext {\n /** Subcommands to render */\n subcommands: SubCommandInfo[];\n /** Render function that accepts subcommands and optional rendering options */\n render: (subcommands: SubCommandInfo[], opts?: SubcommandsRenderOptions) => string;\n /** Heading prefix (e.g., \"###\") */\n heading: string;\n /** Command information */\n info: CommandInfo;\n}\nexport type SubcommandsRenderFunction = (context: SubcommandsRenderContext) => string;\n\n/**\n * Examples render options\n */\nexport interface ExamplesRenderOptions {\n /** Include heading (default: true) */\n withHeading?: boolean;\n /** Show execution output (default: true when results available) */\n showOutput?: boolean;\n /** Command prefix to prepend to example commands (e.g., \"my-cli config get\") */\n commandPrefix?: string;\n}\n\n/**\n * Examples render context\n */\nexport interface ExamplesRenderContext {\n /** Examples to render */\n examples: Example[];\n /** Execution results (if examples were executed) */\n results?: ExampleExecutionResult[] | undefined;\n /** Render function that accepts examples, results, and optional rendering options */\n render: (\n examples: Example[],\n results?: ExampleExecutionResult[],\n opts?: ExamplesRenderOptions,\n ) => string;\n /** Heading prefix (e.g., \"###\") */\n heading: string;\n /** Command information */\n info: CommandInfo;\n}\nexport type ExamplesRenderFunction = (context: ExamplesRenderContext) => string;\n\n/**\n * Simple section render context (for description, usage, notes, footer)\n */\nexport interface SimpleRenderContext {\n /** Default content */\n content: string;\n /** Heading prefix (e.g., \"###\") */\n heading: string;\n /** Command information */\n info: CommandInfo;\n}\nexport type SimpleRenderFunction = (context: SimpleRenderContext) => string;\n\n/**\n * Default renderer customization options\n */\nexport interface DefaultRendererOptions {\n /** Heading level (default: 1) */\n headingLevel?: HeadingLevel;\n /** Option display style */\n optionStyle?: \"table\" | \"list\";\n /** Generate anchor links to subcommands */\n generateAnchors?: boolean;\n /** Include subcommand details */\n includeSubcommandDetails?: boolean;\n /** Custom renderer for description section */\n renderDescription?: SimpleRenderFunction;\n /** Custom renderer for usage section */\n renderUsage?: SimpleRenderFunction;\n /** Custom renderer for arguments section */\n renderArguments?: ArgumentsRenderFunction;\n /** Custom renderer for options section */\n renderOptions?: OptionsRenderFunction;\n /** Custom renderer for subcommands section */\n renderSubcommands?: SubcommandsRenderFunction;\n /** Custom renderer for notes section */\n renderNotes?: SimpleRenderFunction;\n /** Custom renderer for footer (default content is empty) */\n renderFooter?: SimpleRenderFunction;\n /** Custom renderer for examples section */\n renderExamples?: ExamplesRenderFunction;\n}\n\n/**\n * Root document configuration\n * The root document contains global options tables and command index sections.\n */\nexport interface RootDocConfig {\n /** Output file path */\n path: string;\n /**\n * Global options configuration.\n * ArgsShape directly, or { args, options } for render options.\n */\n globalOptions?: ArgsShape | { args: ArgsShape; options?: ArgsTableOptions };\n /** Heading level for the file header (default: 1) */\n headingLevel?: HeadingLevel;\n /** Index section rendering options */\n index?: CommandIndexOptions;\n}\n\n/**\n * Root command customization for the root document.\n * Controls the root document's title, description, header, and footer.\n */\nexport interface RootCommandInfo {\n /** Title (defaults to command.name) */\n title?: string;\n /** Description (defaults to command.description) */\n description?: string;\n /** Markdown placed after title/description */\n header?: string;\n /** Markdown placed at end of document */\n footer?: string;\n}\n\n/**\n * Path configuration for documentation output.\n * Simpler alternative to FileMapping for common patterns.\n *\n * @example\n * // All commands in one file\n * path: \"docs/CLI.md\"\n *\n * // Split files: root + specific commands in separate files\n * path: { root: \"docs/CLI.md\", commands: { \"build\": \"docs/build.md\" } }\n */\nexport type PathConfig = string | { root: string; commands?: Record<string, string> };\n\n/**\n * Per-file configuration with custom renderer\n */\nexport interface FileConfig {\n /** Command paths to include in this file (e.g., [\"\", \"user\", \"config get\"]) */\n commands: string[];\n /** Custom renderer for this file (optional) */\n render?: RenderFunction;\n /** File title (prepended to the file content) */\n title?: string;\n /** File description (added after title) */\n description?: string;\n /** Skip subcommand expansion (commands are used as-is). @internal */\n noExpand?: boolean;\n}\n\n/**\n * File mapping configuration\n * Key: output file path (e.g., \"docs/cli.md\")\n * Value: command paths array or FileConfig object\n *\n * @example\n * // Simple: single file with multiple commands\n * { \"docs/cli.md\": [\"\", \"user\", \"config\"] }\n *\n * // With custom renderer\n * { \"docs/cli.md\": { commands: [\"\"], render: customRenderer } }\n */\nexport type FileMapping = Record<string, string[] | FileConfig>;\n\n/**\n * generateDoc configuration\n */\nexport interface GenerateDocConfig {\n /** Command to generate documentation for */\n command: AnyCommand;\n /**\n * Root document configuration.\n * The root document contains global options tables and command index sections.\n * Title and description are derived from `command.name` and `command.description`.\n */\n rootDoc?: RootDocConfig;\n /**\n * Path configuration (simpler alternative to files).\n * Mutually exclusive with `files`.\n */\n path?: PathConfig;\n /** File output configuration (command path -> file mapping) */\n files?: FileMapping;\n /** Root command customization (title, description, header, footer) */\n rootInfo?: RootCommandInfo;\n /** Command paths to ignore (including their subcommands) */\n ignores?: string[];\n /** Default renderer options (used when render is not specified per file) */\n format?: DefaultRendererOptions;\n /** Formatter function to apply to generated content before comparison */\n formatter?: FormatterFunction;\n /** Example execution configuration (per command path) */\n examples?: ExampleConfig;\n /**\n * Target command paths to validate (e.g., [\"read\", \"config get\"])\n * When specified, only these commands' sections are validated.\n * The full document structure is used to maintain cross-file links.\n */\n targetCommands?: string[];\n /**\n * Global args schema (runtime schema alternative).\n * When provided, automatically derives `rootDoc.globalOptions` from this schema.\n */\n globalArgs?: ArgsSchema;\n}\n\n/**\n * generateDoc result\n */\nexport interface GenerateDocResult {\n /** Whether all files matched or were updated successfully */\n success: boolean;\n /** File processing results */\n files: Array<{\n /** File path */\n path: string;\n /** Status of this file */\n status: \"match\" | \"created\" | \"updated\" | \"diff\";\n /** Diff content (only when status is \"diff\") */\n diff?: string | undefined;\n }>;\n /** Error message (when success is false) */\n error?: string | undefined;\n}\n\n/**\n * Formatter function type\n * Formats generated content before comparison\n */\nexport type FormatterFunction = (content: string) => string | Promise<string>;\n\n/**\n * Environment variable name for update mode\n */\nexport const UPDATE_GOLDEN_ENV = \"POLITTY_DOCS_UPDATE\";\n\n/**\n * Environment variable name for doctor mode.\n * When enabled alone, detects and reports missing section markers (read-only).\n * When combined with POLITTY_DOCS_UPDATE=true, auto-inserts missing markers.\n */\nexport const DOCTOR_ENV = \"POLITTY_DOCS_DOCTOR\";\n\n/**\n * All section types in rendering order\n */\nexport const SECTION_TYPES = [\n \"heading\",\n \"description\",\n \"usage\",\n \"arguments\",\n \"options\",\n \"global-options-link\",\n \"subcommands\",\n \"examples\",\n \"notes\",\n] as const;\n\n/**\n * Section types for command documentation markers\n */\nexport type SectionType = (typeof SECTION_TYPES)[number];\n\n/**\n * Marker prefix for command section markers in generated documentation\n * Format: <!-- politty:command:<scope>:<type>:start --> ... <!-- politty:command:<scope>:<type>:end -->\n */\nexport const SECTION_MARKER_PREFIX = \"politty:command\";\n\n/**\n * Generate start marker for a command section\n */\nexport function sectionStartMarker(type: SectionType, scope: string): string {\n return `<!-- ${SECTION_MARKER_PREFIX}:${scope}:${type}:start -->`;\n}\n\n/**\n * Generate end marker for a command section\n */\nexport function sectionEndMarker(type: SectionType, scope: string): string {\n return `<!-- ${SECTION_MARKER_PREFIX}:${scope}:${type}:end -->`;\n}\n\n/**\n * Marker prefix for global options sections in generated documentation\n * Format: <!-- politty:global-options:start --> ... <!-- politty:global-options:end -->\n */\nexport const GLOBAL_OPTIONS_MARKER_PREFIX = \"politty:global-options\";\n\n/**\n * Generate start marker for a global options section\n */\nexport function globalOptionsStartMarker(): string {\n return `<!-- ${GLOBAL_OPTIONS_MARKER_PREFIX}:start -->`;\n}\n\n/**\n * Generate end marker for a global options section\n */\nexport function globalOptionsEndMarker(): string {\n return `<!-- ${GLOBAL_OPTIONS_MARKER_PREFIX}:end -->`;\n}\n\n/**\n * Marker prefix for root header sections in generated documentation\n */\nexport const ROOT_HEADER_MARKER_PREFIX = \"politty:root-header\";\n\nexport function rootHeaderStartMarker(): string {\n return `<!-- ${ROOT_HEADER_MARKER_PREFIX}:start -->`;\n}\n\nexport function rootHeaderEndMarker(): string {\n return `<!-- ${ROOT_HEADER_MARKER_PREFIX}:end -->`;\n}\n\n/**\n * Marker prefix for root footer sections in generated documentation\n */\nexport const ROOT_FOOTER_MARKER_PREFIX = \"politty:root-footer\";\n\nexport function rootFooterStartMarker(): string {\n return `<!-- ${ROOT_FOOTER_MARKER_PREFIX}:start -->`;\n}\n\nexport function rootFooterEndMarker(): string {\n return `<!-- ${ROOT_FOOTER_MARKER_PREFIX}:end -->`;\n}\n\n/**\n * Marker prefix for index sections in generated documentation\n * Format: <!-- politty:index:<scope>:start --> ... <!-- politty:index:<scope>:end -->\n */\nexport const INDEX_MARKER_PREFIX = \"politty:index\";\n\n/**\n * Generate start marker for an index section\n */\nexport function indexStartMarker(scope: string): string {\n return `<!-- ${INDEX_MARKER_PREFIX}:${scope}:start -->`;\n}\n\n/**\n * Generate end marker for an index section\n */\nexport function indexEndMarker(scope: string): string {\n return `<!-- ${INDEX_MARKER_PREFIX}:${scope}:end -->`;\n}\n","import path from \"node:path\";\nimport type { ExtractedFields, ResolvedFieldMeta } from \"../core/schema-extractor.js\";\nimport type { Example } from \"../types.js\";\nimport type {\n ArgumentsRenderContext,\n CommandInfo,\n DefaultRendererOptions,\n ExampleExecutionResult,\n ExamplesRenderContext,\n ExamplesRenderOptions,\n OptionsRenderContext,\n RenderContentOptions,\n RenderFunction,\n SectionType,\n SimpleRenderContext,\n SubCommandInfo,\n SubcommandsRenderContext,\n SubcommandsRenderOptions,\n} from \"./types.js\";\nimport { sectionEndMarker, sectionStartMarker } from \"./types.js\";\n\n/**\n * Escape markdown special characters in table cells\n */\nfunction escapeTableCell(str: string): string {\n return str.replace(/\\|/g, \"\\\\|\").replace(/\\n/g, \" \");\n}\n\n/**\n * Marker appended to a custom negation row/line so readers can see which\n * positive flag it negates (e.g. `--monochrome` → `(↔ \\`--color\\`)`).\n */\nexport function negationRelationMarker(opt: ResolvedFieldMeta): string {\n return `(↔ \\`--${opt.cliName}\\`)`;\n}\n\n/**\n * Format default value for display\n */\nfunction formatDefaultValue(value: unknown): string {\n if (value === undefined) {\n return \"-\";\n }\n return `\\`${JSON.stringify(value)}\\``;\n}\n\n/**\n * Render usage line\n */\nexport function renderUsage(info: CommandInfo): string {\n const parts: string[] = [info.fullCommandPath];\n\n if (info.options.length > 0) {\n parts.push(\"[options]\");\n }\n\n if (info.subCommands.length > 0) {\n parts.push(\"[command]\");\n }\n\n for (const arg of info.positionalArgs) {\n if (arg.required) {\n parts.push(`<${arg.name}>`);\n } else {\n parts.push(`[${arg.name}]`);\n }\n }\n\n return parts.join(\" \");\n}\n\n/**\n * Render arguments as table\n */\nexport function renderArgumentsTable(info: CommandInfo): string {\n if (info.positionalArgs.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n lines.push(\"| Argument | Description | Required |\");\n lines.push(\"|----------|-------------|----------|\");\n\n for (const arg of info.positionalArgs) {\n const desc = escapeTableCell(arg.description ?? \"\");\n const required = arg.required ? \"Yes\" : \"No\";\n lines.push(`| \\`${arg.name}\\` | ${desc} | ${required} |`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render arguments as list\n */\nexport function renderArgumentsList(info: CommandInfo): string {\n if (info.positionalArgs.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n for (const arg of info.positionalArgs) {\n const required = arg.required ? \"(required)\" : \"(optional)\";\n const desc = arg.description ? ` - ${arg.description}` : \"\";\n lines.push(`- \\`${arg.name}\\`${desc} ${required}`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Format environment variable info for display\n */\nfunction formatEnvInfo(env: string | string[] | undefined): string {\n if (!env) return \"\";\n const envNames = Array.isArray(env) ? env : [env];\n return ` [env: ${envNames.join(\", \")}]`;\n}\n\n/**\n * Resolve placeholder for an option (uses kebab-case cliName)\n */\nfunction resolvePlaceholder(opt: ResolvedFieldMeta): string {\n return opt.placeholder ?? opt.cliName.toUpperCase().replace(/-/g, \"_\");\n}\n\n/**\n * Format option name for table display (e.g., `--dry-run` or `--port <PORT>`)\n *\n * Boolean fields with a custom inline `negation` (no separate description) are\n * shown as `\\`--cache\\` / \\`--disable-cache\\``.\n */\nfunction formatOptionName(opt: ResolvedFieldMeta): string {\n const placeholder = resolvePlaceholder(opt);\n if (opt.type === \"boolean\") {\n const positive = `\\`--${opt.cliName}\\``;\n if (opt.negationDisplay && !opt.negationDescription) {\n return `${positive} / \\`--${opt.negationDisplay}\\``;\n }\n return positive;\n }\n return `\\`--${opt.cliName} <${placeholder}>\\``;\n}\n\n/**\n * Format option flags for list display (uses kebab-case cliName).\n * Aliases are joined with `, `; the inline negation (when no separate\n * `negationDescription` is set) is appended with ` / ` so it stays\n * visually distinct from aliases, matching help and table output.\n */\nfunction formatOptionFlags(opt: ResolvedFieldMeta): string {\n const placeholder = resolvePlaceholder(opt);\n const longFlag =\n opt.type === \"boolean\" ? `--${opt.cliName}` : `--${opt.cliName} <${placeholder}>`;\n\n const parts: string[] = [];\n if (opt.alias) {\n for (const a of opt.alias) {\n if (a.length === 1) parts.push(`\\`-${a}\\``);\n }\n }\n parts.push(`\\`${longFlag}\\``);\n if (opt.alias) {\n for (const a of opt.alias) {\n if (a.length > 1) parts.push(`\\`--${a}\\``);\n }\n }\n const aliasJoined = parts.join(\", \");\n if (opt.type === \"boolean\" && opt.negationDisplay && !opt.negationDescription) {\n return `${aliasJoined} / \\`--${opt.negationDisplay}\\``;\n }\n return aliasJoined;\n}\n\n/**\n * Format aliases for a markdown table cell\n */\nfunction formatAliasCell(alias: string[] | undefined): string {\n if (!alias || alias.length === 0) return \"-\";\n return alias.map((a) => `\\`${a.length === 1 ? `-${a}` : `--${a}`}\\``).join(\", \");\n}\n\n/**\n * Format env variable names for table display\n */\nfunction formatEnvNames(env: string | string[] | undefined): string {\n if (!env) return \"-\";\n if (Array.isArray(env)) {\n return env.map((e) => `\\`${e}\\``).join(\", \");\n }\n return `\\`${env}\\``;\n}\n\n/**\n * Render options as markdown table\n *\n * Features:\n * - Uses kebab-case (cliName) for option names (e.g., `--dry-run` instead of `--dryRun`)\n * - Automatically adds Env column when any option has env configured\n * - Displays multiple env vars as comma-separated list\n *\n * @example\n * | Option | Alias | Description | Required | Default | Env |\n * |--------|-------|-------------|----------|---------|-----|\n * | `--dry-run` | `-d` | Dry run mode | No | `false` | - |\n * | `--port <PORT>` | - | Server port | Yes | - | `PORT`, `SERVER_PORT` |\n */\nexport function renderOptionsTable(info: CommandInfo): string {\n if (info.options.length === 0) {\n return \"\";\n }\n\n // Check if any option has env configured\n const hasEnv = info.options.some((opt) => opt.env);\n\n const lines: string[] = [];\n if (hasEnv) {\n lines.push(\"| Option | Alias | Description | Required | Default | Env |\");\n lines.push(\"|--------|-------|-------------|----------|---------|-----|\");\n } else {\n lines.push(\"| Option | Alias | Description | Required | Default |\");\n lines.push(\"|--------|-------|-------------|----------|---------|\");\n }\n\n for (const opt of info.options) {\n const optionName = formatOptionName(opt);\n const alias = formatAliasCell(opt.alias);\n const desc = escapeTableCell(opt.description ?? \"\");\n const required = opt.required ? \"Yes\" : \"No\";\n const defaultVal = formatDefaultValue(opt.defaultValue);\n\n if (hasEnv) {\n const envNames = formatEnvNames(opt.env);\n lines.push(\n `| ${optionName} | ${alias} | ${desc} | ${required} | ${defaultVal} | ${envNames} |`,\n );\n } else {\n lines.push(`| ${optionName} | ${alias} | ${desc} | ${required} | ${defaultVal} |`);\n }\n\n // Add a separate row for the negation when a description is provided\n if (opt.type === \"boolean\" && opt.negationDisplay && opt.negationDescription) {\n const negName = `\\`--${opt.negationDisplay}\\``;\n const negDesc = `${escapeTableCell(opt.negationDescription)} ${negationRelationMarker(opt)}`;\n if (hasEnv) {\n lines.push(`| ${negName} | - | ${negDesc} | ${required} | - | - |`);\n } else {\n lines.push(`| ${negName} | - | ${negDesc} | ${required} | - |`);\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render options as markdown list\n *\n * Features:\n * - Uses kebab-case (cliName) for option names (e.g., `--dry-run` instead of `--dryRun`)\n * - Appends env info at the end of each option (e.g., `[env: PORT, SERVER_PORT]`)\n *\n * @example\n * - `-d`, `--dry-run` - Dry run mode (default: false)\n * - `--port <PORT>` - Server port (required) [env: PORT, SERVER_PORT]\n */\nexport function renderOptionsList(info: CommandInfo): string {\n if (info.options.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n for (const opt of info.options) {\n const flags = formatOptionFlags(opt);\n const desc = opt.description ? ` - ${opt.description}` : \"\";\n const required = opt.required ? \" (required)\" : \"\";\n const defaultVal =\n opt.defaultValue !== undefined ? ` (default: ${JSON.stringify(opt.defaultValue)})` : \"\";\n const envInfo = formatEnvInfo(opt.env);\n lines.push(`- ${flags}${desc}${required}${defaultVal}${envInfo}`);\n if (opt.type === \"boolean\" && opt.negationDisplay && opt.negationDescription) {\n lines.push(\n `- \\`--${opt.negationDisplay}\\` - ${opt.negationDescription} ${negationRelationMarker(opt)}`,\n );\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate anchor from command path\n */\nfunction generateAnchor(commandPath: string[]): string {\n return commandPath.join(\"-\").toLowerCase();\n}\n\n/**\n * Generate relative path from one file to another.\n * Always emits forward slashes so Markdown links remain portable across OSes.\n */\nfunction getRelativePath(from: string, to: string): string {\n const fromPosix = from.replace(/\\\\/g, \"/\");\n const toPosix = to.replace(/\\\\/g, \"/\");\n return path.posix.relative(path.posix.dirname(fromPosix), toPosix);\n}\n\n/**\n * Render subcommands as table\n */\nexport function renderSubcommandsTable(info: CommandInfo, generateAnchors = true): string {\n return renderSubcommandsTableFromArray(info.subCommands, info, generateAnchors);\n}\n\n/**\n * Render options from array as table\n */\nexport function renderOptionsTableFromArray(options: ResolvedFieldMeta[]): string {\n if (options.length === 0) {\n return \"\";\n }\n\n // Check if any option has env configured\n const hasEnv = options.some((opt) => opt.env);\n\n const lines: string[] = [];\n if (hasEnv) {\n lines.push(\"| Option | Alias | Description | Required | Default | Env |\");\n lines.push(\"|--------|-------|-------------|----------|---------|-----|\");\n } else {\n lines.push(\"| Option | Alias | Description | Required | Default |\");\n lines.push(\"|--------|-------|-------------|----------|---------|\");\n }\n\n for (const opt of options) {\n const optionName = formatOptionName(opt);\n const alias = formatAliasCell(opt.alias);\n const desc = escapeTableCell(opt.description ?? \"\");\n const required = opt.required ? \"Yes\" : \"No\";\n const defaultVal = formatDefaultValue(opt.defaultValue);\n\n if (hasEnv) {\n const envNames = formatEnvNames(opt.env);\n lines.push(\n `| ${optionName} | ${alias} | ${desc} | ${required} | ${defaultVal} | ${envNames} |`,\n );\n } else {\n lines.push(`| ${optionName} | ${alias} | ${desc} | ${required} | ${defaultVal} |`);\n }\n\n if (opt.type === \"boolean\" && opt.negationDisplay && opt.negationDescription) {\n const negName = `\\`--${opt.negationDisplay}\\``;\n const negDesc = `${escapeTableCell(opt.negationDescription)} ${negationRelationMarker(opt)}`;\n if (hasEnv) {\n lines.push(`| ${negName} | - | ${negDesc} | ${required} | - | - |`);\n } else {\n lines.push(`| ${negName} | - | ${negDesc} | ${required} | - |`);\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render union/xor options as markdown with variant grouping\n */\nexport function renderUnionOptionsMarkdown(\n extracted: ExtractedFields,\n style: \"table\" | \"list\" = \"table\",\n): string {\n const unionOptions = extracted.unionOptions ?? [];\n if (unionOptions.length === 0) return \"\";\n\n const sections: string[] = [];\n\n // Compute common fields (present in all variants)\n const allFieldNames = new Set<string>();\n for (const option of unionOptions) {\n for (const field of option.fields) {\n allFieldNames.add(field.name);\n }\n }\n const commonFieldNames = new Set<string>();\n for (const fieldName of allFieldNames) {\n if (unionOptions.every((o) => o.fields.some((f) => f.name === fieldName))) {\n commonFieldNames.add(fieldName);\n }\n }\n\n // Render common fields first\n const commonFields = extracted.fields.filter(\n (f) => commonFieldNames.has(f.name) && !f.positional,\n );\n if (commonFields.length > 0) {\n sections.push(\n style === \"table\"\n ? renderOptionsTableFromArray(commonFields)\n : renderOptionsListFromArray(commonFields),\n );\n }\n\n // Intro note\n sections.push(\"> One of the following option groups is required:\");\n\n // Render each variant\n for (let i = 0; i < unionOptions.length; i++) {\n const option = unionOptions[i];\n if (!option) continue;\n\n const uniqueFields = option.fields.filter(\n (f) => !commonFieldNames.has(f.name) && !f.positional,\n );\n\n const label = option.description ?? `Variant ${i + 1}`;\n if (uniqueFields.length === 0) {\n sections.push(`**${label}:**\\n\\n_no options_`);\n continue;\n }\n\n const rendered =\n style === \"table\"\n ? renderOptionsTableFromArray(uniqueFields)\n : renderOptionsListFromArray(uniqueFields);\n sections.push(`**${label}:**\\n\\n${rendered}`);\n }\n\n return sections.join(\"\\n\\n\");\n}\n\n/**\n * Render discriminatedUnion options as markdown with variant grouping\n */\nexport function renderDiscriminatedUnionOptionsMarkdown(\n extracted: ExtractedFields,\n style: \"table\" | \"list\" = \"table\",\n): string {\n const discriminator = extracted.discriminator;\n const variants = extracted.variants ?? [];\n if (!discriminator || variants.length === 0) return \"\";\n\n const sections: string[] = [];\n\n // Compute common fields (in all variants, excluding discriminator)\n const allFieldNames = new Set<string>();\n for (const variant of variants) {\n for (const field of variant.fields) {\n allFieldNames.add(field.name);\n }\n }\n const commonFieldNames = new Set<string>();\n for (const fieldName of allFieldNames) {\n if (fieldName === discriminator) continue;\n if (variants.every((v) => v.fields.some((f) => f.name === fieldName))) {\n commonFieldNames.add(fieldName);\n }\n }\n\n // Build discriminator field with aggregated values\n const discriminatorField = extracted.fields.find((f) => f.name === discriminator);\n const variantValues = variants.map((v) => v.discriminatorValue).join(\"\\\\|\");\n\n // Top-level table: discriminator + common fields\n const topFields: ResolvedFieldMeta[] = [];\n if (discriminatorField) {\n topFields.push({\n ...discriminatorField,\n placeholder: variantValues,\n });\n }\n for (const fieldName of commonFieldNames) {\n const field = extracted.fields.find((f) => f.name === fieldName);\n if (field && !field.positional) {\n topFields.push(field);\n }\n }\n\n if (topFields.length > 0) {\n sections.push(\n style === \"table\"\n ? renderOptionsTableFromArray(topFields)\n : renderOptionsListFromArray(topFields),\n );\n }\n\n // Render each variant's unique fields\n for (const variant of variants) {\n const uniqueFields = variant.fields.filter(\n (f) => f.name !== discriminator && !commonFieldNames.has(f.name) && !f.positional,\n );\n if (uniqueFields.length === 0) continue;\n\n const descSuffix = variant.description ? ` ${variant.description}` : \"\";\n const label = `**When \\`${discriminator}\\` = \\`${variant.discriminatorValue}\\`:**${descSuffix}`;\n const rendered =\n style === \"table\"\n ? renderOptionsTableFromArray(uniqueFields)\n : renderOptionsListFromArray(uniqueFields);\n sections.push(`${label}\\n\\n${rendered}`);\n }\n\n return sections.join(\"\\n\\n\");\n}\n\n/**\n * Render options from array as list\n */\nexport function renderOptionsListFromArray(options: ResolvedFieldMeta[]): string {\n if (options.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n for (const opt of options) {\n const flags = formatOptionFlags(opt);\n const desc = opt.description ? ` - ${opt.description}` : \"\";\n const required = opt.required ? \" (required)\" : \"\";\n const defaultVal =\n opt.defaultValue !== undefined ? ` (default: ${JSON.stringify(opt.defaultValue)})` : \"\";\n const envInfo = formatEnvInfo(opt.env);\n lines.push(`- ${flags}${desc}${required}${defaultVal}${envInfo}`);\n if (opt.type === \"boolean\" && opt.negationDisplay && opt.negationDescription) {\n lines.push(\n `- \\`--${opt.negationDisplay}\\` - ${opt.negationDescription} ${negationRelationMarker(opt)}`,\n );\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render arguments from array as table\n */\nexport function renderArgumentsTableFromArray(args: ResolvedFieldMeta[]): string {\n if (args.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n lines.push(\"| Argument | Description | Required |\");\n lines.push(\"|----------|-------------|----------|\");\n\n for (const arg of args) {\n const desc = escapeTableCell(arg.description ?? \"\");\n const required = arg.required ? \"Yes\" : \"No\";\n lines.push(`| \\`${arg.name}\\` | ${desc} | ${required} |`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render arguments from array as list\n */\nexport function renderArgumentsListFromArray(args: ResolvedFieldMeta[]): string {\n if (args.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n for (const arg of args) {\n const required = arg.required ? \"(required)\" : \"(optional)\";\n const desc = arg.description ? ` - ${arg.description}` : \"\";\n lines.push(`- \\`${arg.name}\\`${desc} ${required}`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render subcommands from array as table\n */\nexport function renderSubcommandsTableFromArray(\n subcommands: SubCommandInfo[],\n info: CommandInfo,\n generateAnchors = true,\n): string {\n if (subcommands.length === 0) {\n return \"\";\n }\n\n // Check if any subcommand has aliases\n const hasAliases = subcommands.some((s) => s.aliases && s.aliases.length > 0);\n\n const lines: string[] = [];\n if (hasAliases) {\n lines.push(\"| Command | Aliases | Description |\");\n lines.push(\"|---------|---------|-------------|\");\n } else {\n lines.push(\"| Command | Description |\");\n lines.push(\"|---------|-------------|\");\n }\n\n const currentFile = info.filePath;\n const fileMap = info.fileMap;\n\n for (const sub of subcommands) {\n const fullName = sub.fullPath.join(\" \");\n const desc = escapeTableCell(sub.description ?? \"\");\n const subCommandPath = sub.fullPath.join(\" \");\n const aliasCell = hasAliases\n ? sub.aliases && sub.aliases.length > 0\n ? sub.aliases.map((a) => `\\`${escapeTableCell(a)}\\``).join(\", \")\n : \"-\"\n : \"\";\n\n // Build command cell (with optional anchor link)\n let cmdCell: string;\n if (generateAnchors) {\n const anchor = generateAnchor(sub.fullPath);\n const subFile = fileMap?.[subCommandPath];\n\n if (currentFile && subFile && currentFile !== subFile) {\n const relativePath = getRelativePath(currentFile, subFile);\n cmdCell = `[\\`${fullName}\\`](${relativePath}#${anchor})`;\n } else {\n cmdCell = `[\\`${fullName}\\`](#${anchor})`;\n }\n } else {\n cmdCell = `\\`${fullName}\\``;\n }\n\n if (hasAliases) {\n lines.push(`| ${cmdCell} | ${aliasCell} | ${desc} |`);\n } else {\n lines.push(`| ${cmdCell} | ${desc} |`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render examples as markdown\n *\n * @example\n * **Basic usage**\n *\n * ```bash\n * $ greet World\n * ```\n *\n * Output:\n * ```\n * Hello, World!\n * ```\n */\nexport function renderExamplesDefault(\n examples: Example[],\n results?: ExampleExecutionResult[],\n opts?: ExamplesRenderOptions,\n): string {\n if (examples.length === 0) {\n return \"\";\n }\n\n const showOutput = opts?.showOutput ?? true;\n const prefix = opts?.commandPrefix ? `${opts.commandPrefix} ` : \"\";\n const lines: string[] = [];\n\n for (let i = 0; i < examples.length; i++) {\n const example = examples[i];\n if (!example) continue;\n\n const result = results?.[i];\n\n // Description as bold text\n lines.push(`**${example.desc}**`);\n lines.push(\"\");\n\n // Command and output in a single code block\n lines.push(\"```bash\");\n lines.push(`$ ${prefix}${example.cmd}`);\n\n // Output\n if (showOutput) {\n if (result) {\n // Use captured output from execution\n if (result.stdout) {\n lines.push(result.stdout);\n }\n if (result.stderr) {\n lines.push(`[stderr] ${result.stderr}`);\n }\n } else if (example.output) {\n // Use expected output from definition\n lines.push(example.output);\n }\n }\n\n lines.push(\"```\");\n lines.push(\"\");\n }\n\n // Remove trailing empty lines\n while (lines.length > 0 && lines[lines.length - 1] === \"\") {\n lines.pop();\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Wrap content with section markers\n */\nfunction wrapWithMarker(type: SectionType, scope: string, content: string): string {\n return `${sectionStartMarker(type, scope)}\\n${content}\\n${sectionEndMarker(type, scope)}`;\n}\n\n/**\n * Generate a \"See Global Options\" link for subcommand documentation.\n * Returns null for root command or when no global options exist.\n */\nfunction getGlobalOptionsLink(info: CommandInfo): string | null {\n if (!info.hasGlobalOptions || info.commandPath === \"\") {\n return null;\n }\n\n const isCrossFile = info.rootDocPath && info.filePath && info.filePath !== info.rootDocPath;\n const href = isCrossFile\n ? `${getRelativePath(info.filePath!, info.rootDocPath!)}#global-options`\n : \"#global-options\";\n return `See [Global Options](${href}) for options available to all commands.`;\n}\n\nexport function createCommandRenderer(options: DefaultRendererOptions = {}): RenderFunction {\n const {\n headingLevel = 1,\n optionStyle = \"table\",\n generateAnchors = true,\n includeSubcommandDetails = true,\n renderDescription: customRenderDescription,\n renderUsage: customRenderUsage,\n renderArguments: customRenderArguments,\n renderOptions: customRenderOptions,\n renderSubcommands: customRenderSubcommands,\n renderNotes: customRenderNotes,\n renderFooter: customRenderFooter,\n renderExamples: customRenderExamples,\n } = options;\n\n return (info: CommandInfo): string => {\n const sections: string[] = [];\n const scope = info.commandPath;\n // Calculate effective heading level based on command depth\n // depth=1 → headingLevel, depth=2 → headingLevel+1, etc.\n const effectiveLevel = Math.min(headingLevel + (info.depth - 1), 6);\n const h = \"#\".repeat(effectiveLevel);\n\n // Title - use commandPath for subcommands, name for root\n const title = info.commandPath || info.name;\n sections.push(wrapWithMarker(\"heading\", scope, `${h} ${title}`));\n\n // Description (includes aliases when present)\n {\n const parts: string[] = [];\n if (info.description) {\n parts.push(info.description);\n }\n if (info.aliases && info.aliases.length > 0) {\n parts.push(`**Aliases:** ${info.aliases.map((a) => `\\`${a}\\``).join(\", \")}`);\n }\n if (parts.length > 0) {\n const defaultContent = parts.join(\"\\n\\n\");\n const context: SimpleRenderContext = {\n content: defaultContent,\n heading: \"\",\n info,\n };\n const content = customRenderDescription\n ? customRenderDescription(context)\n : context.content;\n if (content) {\n sections.push(wrapWithMarker(\"description\", scope, content));\n }\n }\n }\n\n // Usage\n {\n const defaultUsage = `**Usage**\\n\\n\\`\\`\\`\\n${renderUsage(info)}\\n\\`\\`\\``;\n const context: SimpleRenderContext = {\n content: defaultUsage,\n heading: \"**Usage**\",\n info,\n };\n const content = customRenderUsage ? customRenderUsage(context) : context.content;\n if (content) {\n sections.push(wrapWithMarker(\"usage\", scope, content));\n }\n }\n\n // Arguments\n if (info.positionalArgs.length > 0) {\n const renderArgs = (args: ResolvedFieldMeta[], opts?: RenderContentOptions): string => {\n const style = opts?.style ?? optionStyle;\n const withHeading = opts?.withHeading ?? true;\n const content =\n style === \"table\"\n ? renderArgumentsTableFromArray(args)\n : renderArgumentsListFromArray(args);\n return withHeading ? `**Arguments**\\n\\n${content}` : content;\n };\n\n const context: ArgumentsRenderContext = {\n args: info.positionalArgs,\n render: renderArgs,\n heading: \"**Arguments**\",\n info,\n };\n\n const content = customRenderArguments\n ? customRenderArguments(context)\n : renderArgs(context.args);\n if (content) {\n sections.push(wrapWithMarker(\"arguments\", scope, content));\n }\n }\n\n // Options\n if (info.options.length > 0) {\n const renderOpts = (opts: ResolvedFieldMeta[], renderOpts?: RenderContentOptions): string => {\n const style = renderOpts?.style ?? optionStyle;\n const withHeading = renderOpts?.withHeading ?? true;\n const extracted = info.extracted;\n\n let content: string;\n if (\n extracted &&\n (extracted.schemaType === \"union\" || extracted.schemaType === \"xor\") &&\n extracted.unionOptions\n ) {\n content = renderUnionOptionsMarkdown(extracted, style);\n } else if (\n extracted &&\n extracted.schemaType === \"discriminatedUnion\" &&\n extracted.discriminator\n ) {\n content = renderDiscriminatedUnionOptionsMarkdown(extracted, style);\n } else {\n content =\n style === \"table\"\n ? renderOptionsTableFromArray(opts)\n : renderOptionsListFromArray(opts);\n }\n return withHeading ? `**Options**\\n\\n${content}` : content;\n };\n\n const context: OptionsRenderContext = {\n options: info.options,\n render: renderOpts,\n heading: \"**Options**\",\n info,\n };\n\n const content = customRenderOptions\n ? customRenderOptions(context)\n : renderOpts(context.options);\n if (content) {\n sections.push(wrapWithMarker(\"options\", scope, content));\n }\n }\n\n // Global Options link (for subcommands when global options exist)\n {\n const globalLink = getGlobalOptionsLink(info);\n if (globalLink) {\n sections.push(wrapWithMarker(\"global-options-link\", scope, globalLink));\n }\n }\n\n // Subcommands\n if (info.subCommands.length > 0) {\n const effectiveAnchors = generateAnchors && includeSubcommandDetails;\n\n const renderSubs = (subs: SubCommandInfo[], opts?: SubcommandsRenderOptions): string => {\n const anchors = opts?.generateAnchors ?? effectiveAnchors;\n const withHeading = opts?.withHeading ?? true;\n const content = renderSubcommandsTableFromArray(subs, info, anchors);\n return withHeading ? `**Commands**\\n\\n${content}` : content;\n };\n\n const context: SubcommandsRenderContext = {\n subcommands: info.subCommands,\n render: renderSubs,\n heading: \"**Commands**\",\n info,\n };\n\n const content = customRenderSubcommands\n ? customRenderSubcommands(context)\n : renderSubs(context.subcommands);\n if (content) {\n sections.push(wrapWithMarker(\"subcommands\", scope, content));\n }\n }\n\n // Examples\n if (info.examples && info.examples.length > 0) {\n const renderEx = (\n examples: Example[],\n results?: ExampleExecutionResult[],\n opts?: ExamplesRenderOptions,\n ): string => {\n const withHeading = opts?.withHeading ?? true;\n const mergedOpts: ExamplesRenderOptions = {\n commandPrefix: info.fullCommandPath,\n ...opts,\n };\n const content = renderExamplesDefault(examples, results, mergedOpts);\n return withHeading ? `**Examples**\\n\\n${content}` : content;\n };\n\n const context: ExamplesRenderContext = {\n examples: info.examples,\n results: info.exampleResults,\n render: renderEx,\n heading: \"**Examples**\",\n info,\n };\n\n const content = customRenderExamples\n ? customRenderExamples(context)\n : renderEx(context.examples, context.results);\n if (content) {\n sections.push(wrapWithMarker(\"examples\", scope, content));\n }\n }\n\n // Notes\n if (info.notes) {\n const context: SimpleRenderContext = {\n content: `**Notes**\\n\\n${info.notes}`,\n heading: \"**Notes**\",\n info,\n };\n const content = customRenderNotes ? customRenderNotes(context) : context.content;\n if (content) {\n sections.push(wrapWithMarker(\"notes\", scope, content));\n }\n }\n\n // Footer (default is empty, not wrapped with markers)\n {\n const context: SimpleRenderContext = {\n content: \"\",\n heading: \"\",\n info,\n };\n const content = customRenderFooter ? customRenderFooter(context) : context.content;\n if (content) {\n sections.push(content);\n }\n }\n\n return sections.join(\"\\n\\n\") + \"\\n\";\n };\n}\n\n/**\n * Default renderers presets\n */\nexport const defaultRenderers = {\n /** Standard command documentation */\n command: (options?: DefaultRendererOptions) => createCommandRenderer(options),\n /** Table style options (default) */\n tableStyle: createCommandRenderer({ optionStyle: \"table\" }),\n /** List style options */\n listStyle: createCommandRenderer({ optionStyle: \"list\" }),\n};\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/**\n * Comparison result\n */\nexport interface CompareResult {\n /** Whether the content matches */\n match: boolean;\n /** Diff content (only when match is false) */\n diff?: string;\n /** Whether the file exists */\n fileExists: boolean;\n}\n\n/**\n * Compare generated content with existing file\n */\nexport function compareWithExisting(generatedContent: string, filePath: string): CompareResult {\n const absolutePath = path.resolve(filePath);\n\n if (!fs.existsSync(absolutePath)) {\n return {\n match: false,\n fileExists: false,\n };\n }\n\n const existingContent = fs.readFileSync(absolutePath, \"utf-8\");\n\n if (generatedContent === existingContent) {\n return {\n match: true,\n fileExists: true,\n };\n }\n\n return {\n match: false,\n diff: formatDiff(existingContent, generatedContent),\n fileExists: true,\n };\n}\n\n/**\n * Format diff between two strings in unified diff format\n */\nexport function formatDiff(expected: string, actual: string): string {\n const expectedLines = expected.split(\"\\n\");\n const actualLines = actual.split(\"\\n\");\n\n const result: string[] = [];\n result.push(\"--- existing\");\n result.push(\"+++ generated\");\n result.push(\"\");\n\n // Simple line-by-line diff\n const maxLines = Math.max(expectedLines.length, actualLines.length);\n let inChunk = false;\n let chunkStart = 0;\n const chunk: string[] = [];\n\n const flushChunk = (): void => {\n if (chunk.length > 0) {\n result.push(`@@ -${chunkStart + 1},${chunk.length} @@`);\n result.push(...chunk);\n chunk.length = 0;\n }\n inChunk = false;\n };\n\n for (let i = 0; i < maxLines; i++) {\n const expectedLine = expectedLines[i];\n const actualLine = actualLines[i];\n\n if (expectedLine === actualLine) {\n if (inChunk) {\n // Add context line\n chunk.push(` ${expectedLine ?? \"\"}`);\n // If we have more than 3 context lines after a change, flush the chunk\n const lastChangeIndex = chunk.findIndex(\n (line, idx) =>\n (line.startsWith(\"-\") || line.startsWith(\"+\")) &&\n chunk.slice(idx + 1).every((l) => l.startsWith(\" \")),\n );\n if (lastChangeIndex !== -1 && chunk.length - lastChangeIndex > 3) {\n flushChunk();\n }\n }\n } else {\n if (!inChunk) {\n inChunk = true;\n chunkStart = i;\n // Add up to 3 lines of context before\n const contextStart = Math.max(0, i - 3);\n for (let j = contextStart; j < i; j++) {\n chunk.push(` ${expectedLines[j] ?? \"\"}`);\n }\n }\n\n if (expectedLine !== undefined && (actualLine === undefined || expectedLine !== actualLine)) {\n chunk.push(`-${expectedLine}`);\n }\n if (actualLine !== undefined && (expectedLine === undefined || expectedLine !== actualLine)) {\n chunk.push(`+${actualLine}`);\n }\n }\n }\n\n flushChunk();\n\n return result.join(\"\\n\");\n}\n\n/**\n * Write content to file, creating directories if needed\n */\nexport function writeFile(filePath: string, content: string): void {\n const absolutePath = path.resolve(filePath);\n const dir = path.dirname(absolutePath);\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n fs.writeFileSync(absolutePath, content, \"utf-8\");\n}\n\n/**\n * Read file content if it exists\n * Returns null if file does not exist\n */\nexport function readFile(filePath: string): string | null {\n const absolutePath = path.resolve(filePath);\n\n if (!fs.existsSync(absolutePath)) {\n return null;\n }\n\n return fs.readFileSync(absolutePath, \"utf-8\");\n}\n\n/**\n * Minimal fs interface for deleteFile\n */\nexport interface DeleteFileFs {\n existsSync: typeof fs.existsSync;\n unlinkSync: typeof fs.unlinkSync;\n}\n\n/**\n * Delete file if it exists\n * @param filePath - Path to the file to delete\n * @param fileSystem - Optional fs implementation (useful when fs is mocked)\n */\nexport function deleteFile(filePath: string, fileSystem: DeleteFileFs = fs): void {\n const absolutePath = path.resolve(filePath);\n\n if (fileSystem.existsSync(absolutePath)) {\n fileSystem.unlinkSync(absolutePath);\n }\n}\n","import { getExtractedFields } from \"../core/schema-extractor.js\";\nimport { resolveLazyCommand } from \"../executor/subcommand-router.js\";\nimport type { AnyCommand } from \"../types.js\";\nimport type { CommandInfo, SubCommandInfo } from \"./types.js\";\n\n/**\n * Build CommandInfo from a command\n */\nexport async function buildCommandInfo(\n command: AnyCommand,\n rootName: string,\n commandPath: string[] = [],\n): Promise<CommandInfo> {\n const extracted = getExtractedFields(command);\n\n const positionalArgs = extracted?.fields.filter((f) => f.positional) ?? [];\n const options = extracted?.fields.filter((f) => !f.positional) ?? [];\n\n const subCommands: SubCommandInfo[] = [];\n if (command.subCommands) {\n for (const [name, subCmd] of Object.entries(command.subCommands)) {\n const resolved = await resolveLazyCommand(subCmd);\n const fullPath = [...commandPath, name];\n subCommands.push({\n name,\n description: resolved.description,\n aliases: resolved.aliases,\n fullPath,\n });\n }\n }\n\n return {\n name: command.name ?? \"\",\n description: command.description,\n aliases: command.aliases,\n fullCommandPath: commandPath.length > 0 ? `${rootName} ${commandPath.join(\" \")}` : rootName,\n commandPath: commandPath.join(\" \"),\n depth: commandPath.length + 1,\n positionalArgs,\n options,\n subCommands,\n extracted,\n command,\n notes: command.notes,\n examples: command.examples,\n };\n}\n\n/**\n * Collect all commands with their paths\n * Returns a map of command path -> CommandInfo\n */\nexport async function collectAllCommands(\n command: AnyCommand,\n rootName?: string,\n): Promise<Map<string, CommandInfo>> {\n const root = rootName ?? command.name ?? \"command\";\n const result = new Map<string, CommandInfo>();\n\n async function traverse(cmd: AnyCommand, path: string[]): Promise<void> {\n const info = await buildCommandInfo(cmd, root, path);\n const pathKey = path.join(\" \");\n result.set(pathKey, info);\n\n if (cmd.subCommands) {\n for (const [name, subCmd] of Object.entries(cmd.subCommands)) {\n const resolved = await resolveLazyCommand(subCmd);\n await traverse(resolved, [...path, name]);\n }\n }\n }\n\n await traverse(command, []);\n return result;\n}\n","import { createLogCollector } from \"../executor/log-collector.js\";\nimport type { AnyCommand, Example } from \"../types.js\";\nimport type { ExampleCommandConfig, ExampleExecutionResult } from \"./types.js\";\n\n/**\n * Execute examples for a command and capture output\n *\n * @param examples - Examples to execute\n * @param config - Execution configuration (mock setup/cleanup)\n * @param rootCommand - Root command to execute against\n * @param commandPath - Command path for subcommands (e.g., [\"config\", \"get\"])\n * @returns Array of execution results with captured stdout/stderr\n */\nexport async function executeExamples(\n examples: Example[],\n config: ExampleCommandConfig,\n rootCommand: AnyCommand,\n commandPath: string[] = [],\n): Promise<ExampleExecutionResult[]> {\n const results: ExampleExecutionResult[] = [];\n\n // Setup mock if provided\n if (config.mock) {\n await config.mock();\n }\n\n try {\n for (const example of examples) {\n const result = await executeSingleExample(example, rootCommand, commandPath);\n results.push(result);\n }\n } finally {\n // Cleanup mock if provided\n if (config.cleanup) {\n await config.cleanup();\n }\n }\n\n return results;\n}\n\n/**\n * Execute a single example and capture output\n */\nasync function executeSingleExample(\n example: Example,\n rootCommand: AnyCommand,\n commandPath: string[],\n): Promise<ExampleExecutionResult> {\n // Parse command string into argv\n const exampleArgs = parseExampleCmd(example.cmd);\n\n // Build full argv: command path + example args\n const argv = [...commandPath, ...exampleArgs];\n\n // Use unified log collector (don't passthrough to console)\n const collector = createLogCollector({ passthrough: false });\n collector.start();\n\n let success = true;\n try {\n // Import runCommand dynamically to avoid circular dependency\n const { runCommand } = await import(\"../core/runner.js\");\n const result = await runCommand(rootCommand, argv);\n success = result.success;\n\n // Also capture any errors from the result\n if (!result.success && result.error) {\n console.error(result.error.message);\n }\n } catch (error) {\n success = false;\n console.error(error instanceof Error ? error.message : String(error));\n } finally {\n collector.stop();\n }\n\n // Convert entries to stdout/stderr strings\n const logs = collector.getLogs();\n const stdout = logs.entries\n .filter((e) => e.stream === \"stdout\")\n .map((e) => e.message)\n .join(\"\\n\");\n const stderr = logs.entries\n .filter((e) => e.stream === \"stderr\")\n .map((e) => e.message)\n .join(\"\\n\");\n\n return {\n cmd: example.cmd,\n desc: example.desc,\n expectedOutput: example.output,\n stdout,\n stderr,\n success,\n };\n}\n\n/**\n * Parse example command string into argv array\n * Handles quoted strings (single and double quotes)\n *\n * @example\n * parseExampleCmd('World') // ['World']\n * parseExampleCmd('--name \"John Doe\"') // ['--name', 'John Doe']\n * parseExampleCmd(\"--greeting 'Hello World'\") // ['--greeting', 'Hello World']\n */\nfunction parseExampleCmd(cmd: string): string[] {\n const args: string[] = [];\n let current = \"\";\n let inQuote = false;\n let quoteChar = \"\";\n\n for (let i = 0; i < cmd.length; i++) {\n const char = cmd[i]!;\n\n if ((char === '\"' || char === \"'\") && !inQuote) {\n inQuote = true;\n quoteChar = char;\n } else if (char === quoteChar && inQuote) {\n inQuote = false;\n quoteChar = \"\";\n } else if (char === \" \" && !inQuote) {\n if (current) {\n args.push(current);\n current = \"\";\n }\n } else {\n current += char;\n }\n }\n\n if (current) {\n args.push(current);\n }\n\n return args;\n}\n","import { z } from \"zod\";\nimport { extractFields, type ResolvedFieldMeta } from \"../core/schema-extractor.js\";\nimport { negationRelationMarker, renderOptionsTableFromArray } from \"./default-renderers.js\";\n\n/**\n * Args shape type (Record of string keys to Zod schemas)\n * This matches the typical structure of `commonArgs`, `workspaceArgs`, etc.\n */\nexport type ArgsShape = Record<string, z.ZodType>;\n\n/**\n * Options for rendering args table\n */\nexport type ArgsTableOptions = {\n /** Columns to include in the table (default: all columns) */\n columns?: (\"option\" | \"alias\" | \"description\" | \"required\" | \"default\" | \"env\")[];\n};\n\n/**\n * Extract ResolvedFieldMeta array from ArgsShape\n *\n * This converts a raw args shape (like `commonArgs`) into the\n * ResolvedFieldMeta format used by politty's rendering functions.\n */\nfunction extractArgsFields(args: ArgsShape): ResolvedFieldMeta[] {\n // Wrap in z.object to use extractFields\n const schema = z.object(args);\n const extracted = extractFields(schema);\n return extracted.fields;\n}\n\n/**\n * Render args definition as a markdown options table\n *\n * This function takes raw args definitions (like `commonArgs`) and\n * renders them as a markdown table suitable for documentation.\n *\n * @example\n * import { renderArgsTable } from \"politty/docs\";\n * import { commonArgs, workspaceArgs } from \"./args\";\n *\n * const table = renderArgsTable({\n * ...commonArgs,\n * ...workspaceArgs,\n * });\n * // | Option | Alias | Description | Default |\n * // |--------|-------|-------------|---------|\n * // | `--env-file <ENV_FILE>` | `-e` | Path to environment file | - |\n * // ...\n *\n * @param args - Args shape (Record of string keys to Zod schemas with arg() metadata)\n * @param options - Rendering options\n * @returns Rendered markdown table string\n */\nexport function renderArgsTable(args: ArgsShape, options?: ArgsTableOptions): string {\n const fields = extractArgsFields(args);\n\n // Filter to non-positional args only (options)\n const optionFields = fields.filter((f) => !f.positional);\n\n if (optionFields.length === 0) {\n return \"\";\n }\n\n // Use existing renderOptionsTableFromArray for consistency\n // Note: column filtering is not yet supported by renderOptionsTableFromArray\n // If columns option is needed, we would need to implement custom rendering\n if (options?.columns) {\n return renderFilteredTable(optionFields, options.columns);\n }\n\n return renderOptionsTableFromArray(optionFields);\n}\n\n/**\n * Escape markdown special characters in table cells\n */\nfunction escapeTableCell(str: string): string {\n return str.replace(/\\|/g, \"\\\\|\").replace(/\\n/g, \" \");\n}\n\n/**\n * Format default value for display\n */\nfunction formatDefaultValue(value: unknown): string {\n if (value === undefined) {\n return \"-\";\n }\n return `\\`${JSON.stringify(value)}\\``;\n}\n\n/**\n * Render table with filtered columns\n */\nfunction renderFilteredTable(\n options: ResolvedFieldMeta[],\n columns: (\"option\" | \"alias\" | \"description\" | \"required\" | \"default\" | \"env\")[],\n): string {\n const lines: string[] = [];\n\n // Build header\n const headerCells: string[] = [];\n const separatorCells: string[] = [];\n\n for (const col of columns) {\n switch (col) {\n case \"option\":\n headerCells.push(\"Option\");\n separatorCells.push(\"------\");\n break;\n case \"alias\":\n headerCells.push(\"Alias\");\n separatorCells.push(\"-----\");\n break;\n case \"description\":\n headerCells.push(\"Description\");\n separatorCells.push(\"-----------\");\n break;\n case \"required\":\n headerCells.push(\"Required\");\n separatorCells.push(\"--------\");\n break;\n case \"default\":\n headerCells.push(\"Default\");\n separatorCells.push(\"-------\");\n break;\n case \"env\":\n headerCells.push(\"Env\");\n separatorCells.push(\"---\");\n break;\n }\n }\n\n lines.push(`| ${headerCells.join(\" | \")} |`);\n lines.push(`| ${separatorCells.join(\" | \")} |`);\n\n // Build rows\n for (const opt of options) {\n const cells: string[] = [];\n\n for (const col of columns) {\n switch (col) {\n case \"option\": {\n const placeholder = opt.placeholder ?? opt.cliName.toUpperCase().replace(/-/g, \"_\");\n let optionName: string;\n if (opt.type === \"boolean\") {\n optionName = `\\`--${opt.cliName}\\``;\n if (opt.negationDisplay && !opt.negationDescription) {\n optionName += ` / \\`--${opt.negationDisplay}\\``;\n }\n } else {\n optionName = `\\`--${opt.cliName} <${placeholder}>\\``;\n }\n cells.push(optionName);\n break;\n }\n case \"alias\":\n cells.push(\n opt.alias && opt.alias.length > 0\n ? opt.alias.map((a) => `\\`${a.length === 1 ? `-${a}` : `--${a}`}\\``).join(\", \")\n : \"-\",\n );\n break;\n case \"description\":\n cells.push(escapeTableCell(opt.description ?? \"\"));\n break;\n case \"required\":\n cells.push(opt.required ? \"Yes\" : \"No\");\n break;\n case \"default\":\n cells.push(formatDefaultValue(opt.defaultValue));\n break;\n case \"env\": {\n const envNames = opt.env\n ? Array.isArray(opt.env)\n ? opt.env.map((e) => `\\`${e}\\``).join(\", \")\n : `\\`${opt.env}\\``\n : \"-\";\n cells.push(envNames);\n break;\n }\n }\n }\n\n lines.push(`| ${cells.join(\" | \")} |`);\n\n // Append a separate row for the negation when description is provided\n if (opt.type === \"boolean\" && opt.negationDisplay && opt.negationDescription) {\n const negCells: string[] = [];\n for (const col of columns) {\n switch (col) {\n case \"option\":\n negCells.push(`\\`--${opt.negationDisplay}\\``);\n break;\n case \"description\":\n negCells.push(\n `${escapeTableCell(opt.negationDescription)} ${negationRelationMarker(opt)}`,\n );\n break;\n case \"required\":\n negCells.push(opt.required ? \"Yes\" : \"No\");\n break;\n case \"alias\":\n case \"default\":\n case \"env\":\n negCells.push(\"-\");\n break;\n }\n }\n lines.push(`| ${negCells.join(\" | \")} |`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n","import type { AnyCommand } from \"../types.js\";\nimport { collectAllCommands } from \"./doc-generator.js\";\nimport type { CommandIndexOptions, CommandInfo } from \"./types.js\";\n\n/**\n * Escape markdown special characters in table cells\n */\nfunction escapeTableCell(str: string): string {\n return str.replace(/\\|/g, \"\\\\|\").replace(/\\n/g, \" \");\n}\n\n/**\n * Generate anchor from command path\n */\nfunction generateAnchor(commandPath: string): string {\n return commandPath.replace(/\\s+/g, \"-\").toLowerCase();\n}\n\n/**\n * Configuration for a command category\n */\nexport type CommandCategory = {\n /** Category title (e.g., \"Application Commands\") */\n title: string;\n /** Category description */\n description: string;\n /** Command paths to include (parent commands will auto-expand to leaf commands) */\n commands: string[];\n /** Path to documentation file for links (e.g., \"./cli/application.md\") */\n docPath: string;\n};\n\nexport type { CommandIndexOptions };\n\n/**\n * Check if a command is a leaf (has no subcommands)\n */\nfunction isLeafCommand(info: CommandInfo): boolean {\n return info.subCommands.length === 0;\n}\n\n/**\n * Expand commands to include their subcommands\n * If a command has subcommands, recursively find all commands under it\n *\n * @param commandPaths - Command paths to expand\n * @param allCommands - Map of all available commands\n * @param leafOnly - If true, only include leaf commands; if false, include all commands\n */\nfunction expandCommands(\n commandPaths: string[],\n allCommands: Map<string, CommandInfo>,\n leafOnly: boolean,\n): string[] {\n const result: string[] = [];\n\n for (const cmdPath of commandPaths) {\n const info = allCommands.get(cmdPath);\n if (!info) continue;\n\n if (isLeafCommand(info)) {\n // Already a leaf command\n result.push(cmdPath);\n } else {\n // Find all commands under this parent\n for (const [path, pathInfo] of allCommands) {\n // Check if this is a subcommand of the current command\n const isSubcommand =\n cmdPath === \"\" ? path.length > 0 : path.startsWith(cmdPath + \" \") || path === cmdPath;\n\n if (isSubcommand) {\n // Include if it's a leaf command, or if we're including all commands\n if (isLeafCommand(pathInfo) || !leafOnly) {\n result.push(path);\n }\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Render a single category section\n */\nfunction renderCategory(\n category: CommandCategory,\n allCommands: Map<string, CommandInfo>,\n headingLevel: number,\n leafOnly: boolean,\n): string {\n const h = \"#\".repeat(headingLevel);\n const lines: string[] = [];\n\n // Category title with link\n lines.push(`${h} [${category.title}](${category.docPath})`);\n lines.push(\"\");\n\n // Category description\n lines.push(category.description);\n lines.push(\"\");\n\n // Determine which commands to include (always expand, leafOnly controls filtering)\n const commandPaths = expandCommands(category.commands, allCommands, leafOnly);\n\n // Build command table\n lines.push(\"| Command | Description |\");\n lines.push(\"|---------|-------------|\");\n\n for (const cmdPath of commandPaths) {\n const info = allCommands.get(cmdPath);\n if (!info) continue;\n\n // Skip non-leaf commands if leafOnly is true\n if (leafOnly && !isLeafCommand(info)) continue;\n\n const displayName = cmdPath || info.name;\n const anchor = generateAnchor(displayName);\n const desc = escapeTableCell(info.description ?? \"\");\n\n lines.push(`| [${displayName}](${category.docPath}#${anchor}) | ${desc} |`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render command index from categories\n *\n * Generates a category-based index of commands with links to documentation.\n *\n * @example\n * const categories: CommandCategory[] = [\n * {\n * title: \"Application Commands\",\n * description: \"Commands for managing applications.\",\n * commands: [\"init\", \"generate\", \"apply\"],\n * docPath: \"./cli/application.md\",\n * },\n * ];\n *\n * const index = await renderCommandIndex(mainCommand, categories);\n * // ### [Application Commands](./cli/application.md)\n * //\n * // Commands for managing applications.\n * //\n * // | Command | Description |\n * // |---------|-------------|\n * // | [init](./cli/application.md#init) | Initialize a project |\n * // ...\n *\n * @param command - Root command to extract command information from\n * @param categories - Category definitions for grouping commands\n * @param options - Rendering options\n * @returns Rendered markdown string\n */\nexport async function renderCommandIndex(\n command: AnyCommand,\n categories: CommandCategory[],\n options?: CommandIndexOptions,\n): Promise<string> {\n const headingLevel = options?.headingLevel ?? 3;\n const leafOnly = options?.leafOnly ?? true;\n\n // Collect all commands\n const allCommands = await collectAllCommands(command);\n\n // Render each category\n const sections: string[] = [];\n for (const category of categories) {\n const section = renderCategory(category, allCommands, headingLevel, leafOnly);\n sections.push(section);\n }\n\n return sections.join(\"\\n\\n\");\n}\n","import * as path from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { z } from \"zod\";\nimport { extractFields, type ResolvedFieldMeta } from \"../core/schema-extractor.js\";\nimport type { AnyCommand } from \"../types.js\";\nimport { createCommandRenderer } from \"./default-renderers.js\";\nimport {\n compareWithExisting,\n deleteFile,\n formatDiff,\n readFile,\n writeFile,\n type DeleteFileFs,\n} from \"./doc-comparator.js\";\nimport { collectAllCommands } from \"./doc-generator.js\";\nimport { executeExamples } from \"./example-executor.js\";\nimport { renderArgsTable, type ArgsShape, type ArgsTableOptions } from \"./render-args.js\";\nimport { renderCommandIndex, type CommandCategory } from \"./render-index.js\";\nimport type {\n CommandIndexOptions,\n CommandInfo,\n ExampleConfig,\n FileConfig,\n FileMapping,\n FormatterFunction,\n GenerateDocConfig,\n GenerateDocResult,\n HeadingLevel,\n PathConfig,\n RenderFunction,\n RootDocConfig,\n} from \"./types.js\";\nimport {\n DOCTOR_ENV,\n globalOptionsEndMarker,\n globalOptionsStartMarker,\n indexEndMarker,\n indexStartMarker,\n rootFooterEndMarker,\n rootFooterStartMarker,\n rootHeaderEndMarker,\n rootHeaderStartMarker,\n SECTION_TYPES,\n sectionEndMarker,\n sectionStartMarker,\n UPDATE_GOLDEN_ENV,\n type SectionType,\n} from \"./types.js\";\n\n/**\n * Apply formatter to content if provided\n * Supports both sync and async formatters\n */\nasync function applyFormatter(\n content: string,\n formatter: FormatterFunction | undefined,\n): Promise<string> {\n if (!formatter) {\n return content;\n }\n const formatted = await formatter(content);\n // Preserve trailing newline behavior of input\n if (!content.endsWith(\"\\n\") && formatted.endsWith(\"\\n\")) {\n return formatted.slice(0, -1);\n }\n return formatted;\n}\n\nfunction isTruthyEnv(envKey: string): boolean {\n const value = process.env[envKey];\n return value === \"true\" || value === \"1\";\n}\n\n/**\n * Normalize file mapping entry to FileConfig\n */\nfunction normalizeFileConfig(config: string[] | FileConfig): FileConfig & { commands: string[] } {\n if (Array.isArray(config)) {\n return { commands: config };\n }\n if (!(\"commands\" in config) || !Array.isArray(config.commands)) {\n throw new Error(\n 'Invalid file config: object form must include a \"commands\" array. Use [] to skip generation intentionally.',\n );\n }\n return config;\n}\n\n/**\n * Check if a command path is a subcommand of another\n */\nfunction isSubcommandOf(childPath: string, parentPath: string): boolean {\n if (parentPath === \"\") return true; // Root is parent of everything\n if (childPath === parentPath) return true;\n return childPath.startsWith(parentPath + \" \");\n}\n\n/**\n * Check if a pattern contains wildcards\n */\nfunction containsWildcard(pattern: string): boolean {\n return pattern.includes(\"*\");\n}\n\n/**\n * Check if a command path matches a wildcard pattern\n * - `*` matches any single command segment\n * - Pattern segments are space-separated\n *\n * @example\n * matchesWildcard(\"config get\", \"* *\") // true\n * matchesWildcard(\"config\", \"* *\") // false\n * matchesWildcard(\"config get\", \"config *\") // true\n * matchesWildcard(\"greet\", \"*\") // true\n */\nfunction matchesWildcard(path: string, pattern: string): boolean {\n const pathSegments = path === \"\" ? [] : path.split(\" \");\n const patternSegments = pattern === \"\" ? [] : pattern.split(\" \");\n\n if (pathSegments.length !== patternSegments.length) {\n return false;\n }\n\n for (let i = 0; i < patternSegments.length; i++) {\n const patternSeg = patternSegments[i]!;\n const pathSeg = pathSegments[i]!;\n\n if (patternSeg !== \"*\" && patternSeg !== pathSeg) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Expand a wildcard pattern to matching command paths\n */\nfunction expandWildcardPattern(pattern: string, allCommands: Map<string, CommandInfo>): string[] {\n const matches: string[] = [];\n\n for (const cmdPath of allCommands.keys()) {\n if (matchesWildcard(cmdPath, pattern)) {\n matches.push(cmdPath);\n }\n }\n\n return matches;\n}\n\n/**\n * Check if a path matches any ignore pattern (with wildcard support)\n * For wildcard patterns, also ignores subcommands of matched commands\n */\nfunction matchesIgnorePattern(path: string, ignorePattern: string): boolean {\n if (containsWildcard(ignorePattern)) {\n // Check if path matches the wildcard pattern exactly\n if (matchesWildcard(path, ignorePattern)) {\n return true;\n }\n // Check if path is a subcommand of any command matching the pattern\n // e.g., \"config get\" is a subcommand of \"config\" which matches \"*\"\n const pathSegments = path === \"\" ? [] : path.split(\" \");\n const patternSegments = ignorePattern === \"\" ? [] : ignorePattern.split(\" \");\n\n // If path is deeper than pattern, check if prefix matches\n if (pathSegments.length > patternSegments.length) {\n const prefixPath = pathSegments.slice(0, patternSegments.length).join(\" \");\n return matchesWildcard(prefixPath, ignorePattern);\n }\n return false;\n }\n // For non-wildcards, use original subcommand logic\n return isSubcommandOf(path, ignorePattern);\n}\n\n/**\n * Expand command paths to include all subcommands (with wildcard support)\n */\nfunction expandCommandPaths(\n commandPaths: string[],\n allCommands: Map<string, CommandInfo>,\n): string[] {\n const expanded = new Set<string>();\n\n // Resolve wildcards to concrete command paths\n const resolved = commandPaths.flatMap((cmdPath) =>\n containsWildcard(cmdPath) ? expandWildcardPattern(cmdPath, allCommands) : [cmdPath],\n );\n\n // Add each resolved command and its subcommands\n for (const cmdPath of resolved) {\n for (const existingPath of allCommands.keys()) {\n if (isSubcommandOf(existingPath, cmdPath)) {\n expanded.add(existingPath);\n }\n }\n }\n\n return Array.from(expanded);\n}\n\n/**\n * Filter out ignored commands (with wildcard support)\n */\nfunction filterIgnoredCommands(commandPaths: string[], ignores: string[]): string[] {\n return commandPaths.filter((path) => {\n return !ignores.some((ignorePattern) => matchesIgnorePattern(path, ignorePattern));\n });\n}\n\n/**\n * Resolve wildcards to direct matches without subcommand expansion.\n * Returns the \"top-level\" commands for use in CommandCategory.commands,\n * where expandCommands in render-index handles subcommand expansion.\n */\nfunction resolveTopLevelCommands(\n specifiedCommands: string[],\n allCommands: Map<string, CommandInfo>,\n): string[] {\n const result: string[] = [];\n for (const cmdPath of specifiedCommands) {\n if (containsWildcard(cmdPath)) {\n result.push(...expandWildcardPattern(cmdPath, allCommands));\n } else if (allCommands.has(cmdPath)) {\n result.push(cmdPath);\n }\n }\n return result;\n}\n\n/**\n * Resolve file command configuration to concrete command paths.\n * This applies wildcard/subcommand expansion and ignore filtering.\n */\nfunction resolveConfiguredCommandPaths(\n fileConfigRaw: string[] | FileConfig,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): {\n fileConfig: FileConfig & { commands: string[] };\n specifiedCommands: string[];\n commandPaths: string[];\n topLevelCommands: string[];\n} {\n const fileConfig = normalizeFileConfig(fileConfigRaw);\n const specifiedCommands = fileConfig.commands;\n const expandedCommands = fileConfig.noExpand\n ? specifiedCommands.filter((p) => allCommands.has(p))\n : expandCommandPaths(specifiedCommands, allCommands);\n const commandPaths = filterIgnoredCommands(expandedCommands, ignores);\n const topLevelCommands = filterIgnoredCommands(\n resolveTopLevelCommands(specifiedCommands, allCommands),\n ignores,\n );\n\n return {\n fileConfig,\n specifiedCommands,\n commandPaths,\n topLevelCommands,\n };\n}\n\n/**\n * Validate that there are no conflicts between files and ignores (with wildcard support)\n */\nfunction validateNoConflicts(\n filesCommands: string[],\n ignores: string[],\n allCommands: Map<string, CommandInfo>,\n): void {\n const conflicts: string[] = [];\n\n for (const filePattern of filesCommands) {\n // Expand file pattern if it's a wildcard\n const filePaths = containsWildcard(filePattern)\n ? expandWildcardPattern(filePattern, allCommands)\n : [filePattern];\n\n for (const filePath of filePaths) {\n for (const ignorePattern of ignores) {\n if (containsWildcard(ignorePattern)) {\n // For wildcard ignores, check if file path matches the pattern\n if (matchesWildcard(filePath, ignorePattern)) {\n conflicts.push(`\"${filePath}\" is both in files and ignored by \"${ignorePattern}\"`);\n }\n } else {\n // For non-wildcard ignores, use original logic\n if (filePath === ignorePattern || isSubcommandOf(filePath, ignorePattern)) {\n conflicts.push(`\"${filePath}\" is both in files and ignored by \"${ignorePattern}\"`);\n }\n }\n }\n }\n }\n\n if (conflicts.length > 0) {\n throw new Error(`Conflict between files and ignores:\\n - ${conflicts.join(\"\\n - \")}`);\n }\n}\n\n/**\n * Validate that all ignored paths exist in the command tree (with wildcard support)\n */\nfunction validateIgnoresExist(ignores: string[], allCommands: Map<string, CommandInfo>): void {\n const nonExistent: string[] = [];\n\n for (const ignorePattern of ignores) {\n if (containsWildcard(ignorePattern)) {\n // For wildcard patterns, check if at least one command matches\n const matches = expandWildcardPattern(ignorePattern, allCommands);\n if (matches.length === 0) {\n nonExistent.push(`\"${ignorePattern}\"`);\n }\n } else {\n // For non-wildcard paths, check exact existence\n if (!allCommands.has(ignorePattern)) {\n nonExistent.push(`\"${ignorePattern}\"`);\n }\n }\n }\n\n if (nonExistent.length > 0) {\n throw new Error(`Ignored command paths do not exist: ${nonExistent.join(\", \")}`);\n }\n}\n\n/**\n * Sort command paths in depth-first order while preserving the specified command order\n * Parent commands are immediately followed by their subcommands\n */\nfunction sortDepthFirst(commandPaths: string[], specifiedOrder: string[]): string[] {\n // Build a set of all paths for quick lookup\n const pathSet = new Set(commandPaths);\n\n // Find top-level commands (those that match specified order or have no parent in the set)\n const topLevelPaths = specifiedOrder.filter((cmd) => pathSet.has(cmd));\n\n // Also include any commands not in specifiedOrder (for safety)\n for (const path of commandPaths) {\n const depth = path === \"\" ? 0 : path.split(\" \").length;\n if (depth === 1 && !topLevelPaths.includes(path)) {\n topLevelPaths.push(path);\n }\n }\n\n const result: string[] = [];\n const visited = new Set<string>();\n\n function addWithChildren(cmdPath: string): void {\n if (visited.has(cmdPath) || !pathSet.has(cmdPath)) return;\n visited.add(cmdPath);\n result.push(cmdPath);\n\n // Find and add direct children in alphabetical order\n const children = commandPaths\n .filter((p) => {\n if (p === cmdPath || visited.has(p)) return false;\n // Check if p is a direct child of cmdPath\n if (cmdPath === \"\") {\n return p.split(\" \").length === 1;\n }\n return p.startsWith(cmdPath + \" \") && p.split(\" \").length === cmdPath.split(\" \").length + 1;\n })\n .sort((a, b) => a.localeCompare(b));\n\n for (const child of children) {\n addWithChildren(child);\n }\n }\n\n // Start with top-level commands in specified order\n for (const topLevel of topLevelPaths) {\n addWithChildren(topLevel);\n }\n\n // Add any remaining paths (shouldn't happen normally)\n for (const path of commandPaths) {\n if (!visited.has(path)) {\n result.push(path);\n }\n }\n\n return result;\n}\n\n/**\n * Generate file header from FileConfig\n */\ntype FileHeaderConfig = Pick<FileConfig, \"title\" | \"description\"> & {\n headingLevel?: HeadingLevel;\n};\n\nfunction generateFileHeader(fileConfig: FileHeaderConfig): string | null {\n if (!fileConfig.title && !fileConfig.description) {\n return null;\n }\n\n const parts: string[] = [];\n if (fileConfig.title) {\n const heading = \"#\".repeat(fileConfig.headingLevel ?? 1);\n parts.push(`${heading} ${fileConfig.title}`);\n }\n if (fileConfig.description) {\n parts.push(\"\");\n parts.push(fileConfig.description);\n }\n parts.push(\"\");\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Extract a leading file header (title and optional description paragraph)\n */\nfunction extractFileHeader(content: string): string | null {\n if (!/^#{1,6} /.test(content)) {\n return null;\n }\n\n const titleEnd = content.indexOf(\"\\n\");\n if (titleEnd === -1) {\n return content;\n }\n\n let cursor = titleEnd + 1;\n\n // Skip an optional blank line between the title and description paragraph.\n if (content[cursor] === \"\\n\") {\n cursor += 1;\n }\n\n // Consume description paragraph lines until we hit a blank line, heading, or marker.\n while (cursor < content.length) {\n const lineEnd = content.indexOf(\"\\n\", cursor);\n const line = lineEnd === -1 ? content.slice(cursor) : content.slice(cursor, lineEnd);\n\n if (line.length === 0 || /^#{1,6}\\s/.test(line) || line.startsWith(\"<!-- politty:\")) {\n break;\n }\n\n cursor = lineEnd === -1 ? content.length : lineEnd + 1;\n }\n\n return content.slice(0, cursor);\n}\n\n/**\n * Validate and optionally update configured file header\n */\nfunction processFileHeader(\n existingContent: string,\n fileConfig: FileHeaderConfig,\n updateMode: boolean,\n): {\n content: string;\n diff?: string;\n hasError: boolean;\n wasUpdated: boolean;\n} {\n const generatedHeader = generateFileHeader(fileConfig);\n if (!generatedHeader) {\n return { content: existingContent, hasError: false, wasUpdated: false };\n }\n\n if (existingContent.startsWith(generatedHeader)) {\n return { content: existingContent, hasError: false, wasUpdated: false };\n }\n\n const existingHeader = extractFileHeader(existingContent) ?? \"\";\n\n if (!updateMode) {\n return {\n content: existingContent,\n diff: formatDiff(existingHeader, generatedHeader),\n hasError: true,\n wasUpdated: false,\n };\n }\n\n const contentWithoutHeader = existingHeader\n ? existingContent.slice(existingHeader.length)\n : existingContent;\n const normalizedBody = contentWithoutHeader.replace(/^\\n+/, \"\");\n\n return {\n content: `${generatedHeader}${normalizedBody}`,\n hasError: false,\n wasUpdated: true,\n };\n}\n\nfunction formatCommandPath(commandPath: string): string {\n return commandPath === \"\" ? \"<root>\" : commandPath;\n}\n\n/**\n * Extract a section marker's content from document content.\n * Returns the content between start and end markers (including markers).\n */\nfunction extractSectionMarker(content: string, type: SectionType, scope: string): string | null {\n const start = sectionStartMarker(type, scope);\n const end = sectionEndMarker(type, scope);\n return extractMarkerSection(content, start, end);\n}\n\n/**\n * Replace a section marker's content in document content.\n * Returns updated content, or null if marker not found.\n */\nfunction replaceSectionMarker(\n content: string,\n type: SectionType,\n scope: string,\n newContent: string,\n): string | null {\n const start = sectionStartMarker(type, scope);\n const end = sectionEndMarker(type, scope);\n return replaceMarkerSection(content, start, end, newContent);\n}\n\n/**\n * Insert a new section marker into existing content at the correct position\n * relative to other section markers for the same command, based on SECTION_TYPES order.\n * Preserves any existing content between adjacent markers by wrapping it with the new markers\n * instead of replacing it with generated content.\n * @throws If no adjacent marker is found (unreachable when at least one marker exists for the command)\n */\nfunction insertSectionMarkerAtOrder(\n content: string,\n type: SectionType,\n scope: string,\n generatedSection: string,\n): string {\n const typeIndex = SECTION_TYPES.indexOf(type);\n const startMarker = sectionStartMarker(type, scope);\n const endMarker = sectionEndMarker(type, scope);\n\n // Find the boundary: end of preceding marker and start of following marker\n let prevBoundary: number | null = null;\n for (let i = typeIndex - 1; i >= 0; i--) {\n const prevType = SECTION_TYPES[i]!;\n const prevEnd = sectionEndMarker(prevType, scope);\n const prevEndIdx = content.indexOf(prevEnd);\n if (prevEndIdx !== -1) {\n prevBoundary = prevEndIdx + prevEnd.length;\n break;\n }\n }\n\n let nextBoundary: number | null = null;\n for (let i = typeIndex + 1; i < SECTION_TYPES.length; i++) {\n const nextType = SECTION_TYPES[i]!;\n const nextStart = sectionStartMarker(nextType, scope);\n const nextStartIdx = content.indexOf(nextStart);\n if (nextStartIdx !== -1) {\n nextBoundary = nextStartIdx;\n break;\n }\n }\n\n if (prevBoundary != null && nextBoundary != null) {\n // Both boundaries found: wrap the existing content between them with markers\n // to preserve user customizations\n const between = content.slice(prevBoundary, nextBoundary);\n const innerContent = between.replace(/^\\n+/, \"\\n\").replace(/\\n+$/, \"\\n\");\n const wrapped = startMarker + innerContent + endMarker;\n return content.slice(0, prevBoundary) + \"\\n\\n\" + wrapped + \"\\n\\n\" + content.slice(nextBoundary);\n }\n\n // Only one boundary found: cannot safely determine the current command's content range\n // (wrapping could capture other commands). Insert generated content instead.\n if (prevBoundary != null) {\n let afterPos = prevBoundary;\n while (afterPos < content.length && content[afterPos] === \"\\n\") {\n afterPos++;\n }\n return (\n content.slice(0, prevBoundary) +\n \"\\n\\n\" +\n generatedSection +\n (afterPos < content.length ? \"\\n\\n\" : \"\\n\") +\n content.slice(afterPos)\n );\n }\n\n if (nextBoundary != null) {\n let beforePos = nextBoundary;\n while (beforePos > 0 && content[beforePos - 1] === \"\\n\") {\n beforePos--;\n }\n const prefix = beforePos === 0 ? \"\" : \"\\n\\n\";\n return (\n content.slice(0, beforePos) + prefix + generatedSection + \"\\n\\n\" + content.slice(nextBoundary)\n );\n }\n\n throw new Error(\n `No insertion point found for section \"${type}\" (scope=\"${scope}\"). This should be unreachable when at least one marker exists for the command.`,\n );\n}\n\n/**\n * Collect all section types that have markers for a given command path.\n */\nfunction collectSectionMarkers(content: string, commandPath: string): SectionType[] {\n const found: SectionType[] = [];\n for (const type of SECTION_TYPES) {\n if (extractSectionMarker(content, type, commandPath) !== null) {\n found.push(type);\n }\n }\n return found;\n}\n\n/**\n * Collect all command paths that have any section markers in the content.\n */\nfunction collectSectionMarkerPaths(content: string): string[] {\n // Match any section marker: <!-- politty:command:<scope>:<type>:start -->\n const sectionTypes = SECTION_TYPES.join(\"|\");\n const markerPattern = new RegExp(\n `<!--\\\\s*politty:command:(.*?):(?:${sectionTypes}):start\\\\s*-->`,\n \"g\",\n );\n const paths = new Set<string>();\n\n for (const match of content.matchAll(markerPattern)) {\n paths.add(match[1] ?? \"\");\n }\n\n return Array.from(paths);\n}\n\n/**\n * Insert command section markers at the correct position based on specified order.\n * Uses the heading marker of adjacent commands as reference points.\n */\nfunction insertCommandSections(\n content: string,\n commandPath: string,\n newSection: string,\n specifiedOrder: string[],\n): string {\n const targetIndex = specifiedOrder.indexOf(commandPath);\n if (targetIndex === -1) {\n return content.trimEnd() + \"\\n\\n\" + newSection + \"\\n\";\n }\n\n // Find the next command's heading marker in the content\n for (let i = targetIndex + 1; i < specifiedOrder.length; i++) {\n const nextCmd = specifiedOrder[i];\n if (nextCmd === undefined) continue;\n const nextMarker = sectionStartMarker(\"heading\", nextCmd);\n const nextIndex = content.indexOf(nextMarker);\n if (nextIndex !== -1) {\n let insertPos = nextIndex;\n while (insertPos > 0 && content[insertPos - 1] === \"\\n\") {\n insertPos--;\n }\n if (insertPos < nextIndex) {\n insertPos++;\n }\n return content.slice(0, insertPos) + newSection + \"\\n\" + content.slice(nextIndex);\n }\n }\n\n // Find the previous command's last marker in the content\n for (let i = targetIndex - 1; i >= 0; i--) {\n const prevCmd = specifiedOrder[i];\n if (prevCmd === undefined) continue;\n // Find the last section marker for the previous command\n const prevMarkers = collectSectionMarkers(content, prevCmd);\n if (prevMarkers.length > 0) {\n const lastType = prevMarkers[prevMarkers.length - 1]!;\n const prevEndMarker = sectionEndMarker(lastType, prevCmd);\n const prevEndIndex = content.indexOf(prevEndMarker);\n if (prevEndIndex !== -1) {\n const insertPos = prevEndIndex + prevEndMarker.length;\n return content.slice(0, insertPos) + \"\\n\" + newSection + content.slice(insertPos);\n }\n }\n }\n\n return content.trimEnd() + \"\\n\" + newSection + \"\\n\";\n}\n\n/**\n * Remove all section markers for a command from content.\n * Returns the content with all markers for the command removed and excess blank lines cleaned up.\n */\nfunction removeCommandSections(content: string, commandPath: string): string {\n const markers = collectSectionMarkers(content, commandPath);\n for (const type of markers) {\n const start = sectionStartMarker(type, commandPath);\n const end = sectionEndMarker(type, commandPath);\n let startIndex = content.indexOf(start);\n while (startIndex !== -1) {\n const endIndex = content.indexOf(end, startIndex);\n if (endIndex === -1) {\n break;\n }\n content = content.slice(0, startIndex) + content.slice(endIndex + end.length);\n startIndex = content.indexOf(start, startIndex);\n }\n }\n // Clean up excess blank lines (3+ consecutive newlines -> 2)\n content = content.replace(/\\n{3,}/g, \"\\n\\n\");\n return content;\n}\n\n/**\n * Extract a marker section from content\n * Returns the content between start and end markers (including markers)\n */\nfunction extractMarkerSection(\n content: string,\n startMarker: string,\n endMarker: string,\n): string | null {\n const startIndex = content.indexOf(startMarker);\n if (startIndex === -1) {\n return null;\n }\n\n const endIndex = content.indexOf(endMarker, startIndex);\n if (endIndex === -1) {\n return null;\n }\n\n return content.slice(startIndex, endIndex + endMarker.length);\n}\n\n/**\n * Replace a marker section in content\n * Returns the updated content with the new section\n */\nfunction replaceMarkerSection(\n content: string,\n startMarker: string,\n endMarker: string,\n newSection: string,\n): string | null {\n const startIndex = content.indexOf(startMarker);\n if (startIndex === -1) {\n return null;\n }\n\n const endIndex = content.indexOf(endMarker, startIndex);\n if (endIndex === -1) {\n return null;\n }\n\n return content.slice(0, startIndex) + newSection + content.slice(endIndex + endMarker.length);\n}\n\n/**\n * Check if config is the { args, options? } shape (not shorthand ArgsShape)\n *\n * Distinguishes between:\n * - { args: ArgsShape, options?: ArgsTableOptions } → returns true\n * - ArgsShape (e.g., { verbose: ZodType, args: ZodType }) → returns false\n *\n * The key insight is that in the { args, options? } shape, config.args is an ArgsShape\n * (Record of ZodTypes), while in shorthand, config itself is the ArgsShape and config.args\n * would be a single ZodType if user has an option named \"args\".\n */\nfunction isGlobalOptionsConfigWithOptions(\n config: NonNullable<RootDocConfig[\"globalOptions\"]>,\n): config is {\n args: ArgsShape;\n options?: ArgsTableOptions;\n} {\n if (typeof config !== \"object\" || config === null || !(\"args\" in config)) {\n return false;\n }\n // If config.args is a ZodType, this is shorthand with an option named \"args\"\n // If config.args is an object (ArgsShape), this is the { args, options? } shape\n return !(config.args instanceof z.ZodType);\n}\n\n/**\n * Collect option fields that are actually rendered by global options markers.\n * Positional args are not rendered in args tables, so they must not be excluded.\n */\nfunction collectRenderableGlobalOptionFields(argsShape: ArgsShape): ResolvedFieldMeta[] {\n const extracted = extractFields(z.object(argsShape));\n return extracted.fields.filter((field) => !field.positional);\n}\n\n/**\n * Compare option definitions for global-options compatibility.\n */\nfunction areGlobalOptionsEquivalent(a: ResolvedFieldMeta, b: ResolvedFieldMeta): boolean {\n const { schema: _aSchema, ...aRest } = a;\n const { schema: _bSchema, ...bRest } = b;\n return isDeepStrictEqual(aRest, bRest);\n}\n\n/**\n * Normalize rootDoc.globalOptions to { args, options? } form.\n */\nfunction normalizeGlobalOptions(\n config: RootDocConfig[\"globalOptions\"],\n): { args: ArgsShape; options?: ArgsTableOptions } | undefined {\n if (!config) return undefined;\n return isGlobalOptionsConfigWithOptions(config) ? config : { args: config };\n}\n\n/**\n * Collect global option definitions from rootDoc.\n * Global options are intentionally applied to all generated command sections.\n */\nfunction collectGlobalOptionDefinitions(\n rootDoc: RootDocConfig | undefined,\n): Map<string, ResolvedFieldMeta> {\n const globalOptions = new Map<string, ResolvedFieldMeta>();\n if (!rootDoc?.globalOptions) return globalOptions;\n\n const normalized = normalizeGlobalOptions(rootDoc.globalOptions);\n if (!normalized) return globalOptions;\n\n for (const field of collectRenderableGlobalOptionFields(normalized.args)) {\n globalOptions.set(field.name, field);\n }\n\n return globalOptions;\n}\n\n/**\n * Derive CommandCategory[] from files mapping.\n * Category title/description come from the first command in each file entry.\n */\nfunction deriveIndexFromFiles(\n files: FileMapping,\n rootDocPath: string,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): CommandCategory[] {\n const categories: CommandCategory[] = [];\n for (const [filePath, fileConfigRaw] of Object.entries(files)) {\n const { commandPaths, topLevelCommands } = resolveConfiguredCommandPaths(\n fileConfigRaw,\n allCommands,\n ignores,\n );\n if (commandPaths.length === 0) continue;\n\n const docPath = \"./\" + path.relative(path.dirname(rootDocPath), filePath).replace(/\\\\/g, \"/\");\n const firstCmdPath = commandPaths[0];\n const cmdInfo = firstCmdPath !== undefined ? allCommands.get(firstCmdPath) : undefined;\n const fileConfig = Array.isArray(fileConfigRaw) ? undefined : fileConfigRaw;\n categories.push({\n title: fileConfig?.title ?? cmdInfo?.name ?? path.basename(filePath, path.extname(filePath)),\n description: fileConfig?.description ?? cmdInfo?.description ?? \"\",\n commands: topLevelCommands,\n docPath,\n });\n }\n return categories;\n}\n\n/**\n * Collect command paths that are actually documented in configured files.\n */\nfunction collectDocumentedCommandPaths(\n files: FileMapping,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): Set<string> {\n const documentedCommandPaths = new Set<string>();\n\n for (const fileConfigRaw of Object.values(files)) {\n const { commandPaths } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);\n for (const commandPath of commandPaths) {\n documentedCommandPaths.add(commandPath);\n }\n }\n\n return documentedCommandPaths;\n}\n\n/**\n * Collect command paths that are targeted in configured files.\n */\nfunction collectTargetDocumentedCommandPaths(\n targetCommands: string[],\n files: FileMapping,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): Set<string> {\n const documentedTargetCommandPaths = new Set<string>();\n\n for (const filePath of Object.keys(files)) {\n const targetCommandsInFile = findTargetCommandsInFile(\n targetCommands,\n filePath,\n files,\n allCommands,\n ignores,\n );\n\n for (const commandPath of targetCommandsInFile) {\n documentedTargetCommandPaths.add(commandPath);\n }\n }\n\n return documentedTargetCommandPaths;\n}\n\n/**\n * Validate that excluded command options match globalOptions definitions.\n */\nfunction validateGlobalOptionCompatibility(\n documentedCommandPaths: Iterable<string>,\n allCommands: Map<string, CommandInfo>,\n globalOptions: Map<string, ResolvedFieldMeta>,\n): void {\n if (globalOptions.size === 0) {\n return;\n }\n\n const conflicts: string[] = [];\n\n for (const commandPath of documentedCommandPaths) {\n const info = allCommands.get(commandPath);\n if (!info) {\n continue;\n }\n\n for (const option of info.options) {\n const globalOption = globalOptions.get(option.name);\n if (!globalOption) {\n continue;\n }\n\n if (!areGlobalOptionsEquivalent(globalOption, option)) {\n conflicts.push(\n `Command \"${formatCommandPath(commandPath)}\" option \"--${option.cliName}\" does not match globalOptions definition for \"${option.name}\".`,\n );\n }\n }\n }\n\n if (conflicts.length > 0) {\n throw new Error(`Invalid globalOptions configuration:\\n - ${conflicts.join(\"\\n - \")}`);\n }\n}\n\n/**\n * Generate global options section content with markers\n */\nfunction generateGlobalOptionsSection(config: {\n args: ArgsShape;\n options?: ArgsTableOptions;\n}): string {\n const startMarker = globalOptionsStartMarker();\n const endMarker = globalOptionsEndMarker();\n\n const anchor = '<a id=\"global-options\"></a>';\n const table = renderArgsTable(config.args, config.options);\n\n return [startMarker, anchor, table, endMarker].join(\"\\n\");\n}\n\n/**\n * Generate index section content with markers\n */\nasync function generateIndexSection(\n categories: CommandCategory[],\n command: AnyCommand,\n scope: string,\n options?: CommandIndexOptions,\n): Promise<string> {\n const startMarker = indexStartMarker(scope);\n const endMarker = indexEndMarker(scope);\n\n const indexContent = await renderCommandIndex(command, categories, options);\n\n return [startMarker, indexContent, endMarker].join(\"\\n\");\n}\n\n/**\n * Normalize a doc file path for equivalence checks.\n */\nfunction normalizeDocPathForComparison(filePath: string): string {\n return path.resolve(filePath);\n}\n\n/**\n * Process global options marker in file content\n * Returns result with updated content and any diffs\n */\nasync function processGlobalOptionsMarker(\n existingContent: string,\n globalOptionsConfig: { args: ArgsShape; options?: ArgsTableOptions },\n updateMode: boolean,\n formatter: FormatterFunction | undefined,\n autoInsertIfMissing?: boolean,\n): Promise<{\n content: string;\n diffs: string[];\n hasError: boolean;\n wasUpdated: boolean;\n}> {\n let content = existingContent;\n const diffs: string[] = [];\n let hasError = false;\n let wasUpdated = false;\n\n const startMarker = globalOptionsStartMarker();\n const endMarker = globalOptionsEndMarker();\n\n // Generate new section\n const rawSection = generateGlobalOptionsSection(globalOptionsConfig);\n const generatedSection = await applyFormatter(rawSection, formatter);\n\n // Extract existing section\n const existingSection = extractMarkerSection(content, startMarker, endMarker);\n\n if (!existingSection) {\n if (updateMode && autoInsertIfMissing) {\n // Auto-insert markers with generated content (generatedSection already includes markers)\n content = content.trimEnd() + \"\\n\\n\" + generatedSection + \"\\n\";\n wasUpdated = true;\n return { content, diffs, hasError, wasUpdated };\n }\n hasError = true;\n diffs.push(\n `Global options marker not found in file. Expected markers:\\n${startMarker}\\n...\\n${endMarker}`,\n );\n return { content, diffs, hasError, wasUpdated };\n }\n\n // Compare sections\n if (existingSection !== generatedSection) {\n if (updateMode) {\n const updated = replaceMarkerSection(content, startMarker, endMarker, generatedSection);\n if (updated) {\n content = updated;\n wasUpdated = true;\n } else {\n hasError = true;\n diffs.push(\"Failed to replace global options section\");\n }\n } else {\n hasError = true;\n diffs.push(formatDiff(existingSection, generatedSection));\n }\n }\n\n return { content, diffs, hasError, wasUpdated };\n}\n\n/**\n * Process a static content marker (root-header or root-footer).\n * Inserts/updates the marker section with the given content.\n */\nasync function processStaticMarker(\n existingContent: string,\n markerLabel: string,\n startMarker: string,\n endMarker: string,\n rawContent: string,\n updateMode: boolean,\n formatter: FormatterFunction | undefined,\n autoInsertIfMissing: boolean,\n): Promise<{\n content: string;\n diffs: string[];\n hasError: boolean;\n wasUpdated: boolean;\n}> {\n let content = existingContent;\n const diffs: string[] = [];\n let hasError = false;\n let wasUpdated = false;\n\n const generatedInner = await applyFormatter(rawContent, formatter);\n const generatedSection = [startMarker, generatedInner, endMarker].join(\"\\n\");\n\n const existingSection = extractMarkerSection(content, startMarker, endMarker);\n\n if (!existingSection) {\n if (updateMode && autoInsertIfMissing) {\n content = content.trimEnd() + \"\\n\\n\" + generatedSection + \"\\n\";\n wasUpdated = true;\n return { content, diffs, hasError, wasUpdated };\n }\n hasError = true;\n diffs.push(\n `${markerLabel} marker not found in file. Expected markers:\\n${startMarker}\\n...\\n${endMarker}`,\n );\n return { content, diffs, hasError, wasUpdated };\n }\n\n if (existingSection !== generatedSection) {\n if (updateMode) {\n const updated = replaceMarkerSection(content, startMarker, endMarker, generatedSection);\n if (updated) {\n content = updated;\n wasUpdated = true;\n } else {\n hasError = true;\n diffs.push(`Failed to replace ${markerLabel} section`);\n }\n } else {\n hasError = true;\n diffs.push(formatDiff(existingSection, generatedSection));\n }\n }\n\n return { content, diffs, hasError, wasUpdated };\n}\n\n/**\n * Process index marker in file content\n * Returns result with updated content and any diffs.\n * If the marker is not present in the file, the section is silently skipped.\n */\nasync function processIndexMarker(\n existingContent: string,\n categories: CommandCategory[],\n command: AnyCommand,\n scope: string,\n updateMode: boolean,\n formatter: FormatterFunction | undefined,\n indexOptions?: CommandIndexOptions,\n): Promise<{\n content: string;\n diffs: string[];\n hasError: boolean;\n wasUpdated: boolean;\n}> {\n let content = existingContent;\n const diffs: string[] = [];\n let hasError = false;\n let wasUpdated = false;\n\n const startMarker = indexStartMarker(scope);\n const endMarker = indexEndMarker(scope);\n\n const hasStartMarker = content.includes(startMarker);\n const hasEndMarker = content.includes(endMarker);\n\n // Skip silently only when marker is completely absent\n if (!hasStartMarker && !hasEndMarker) {\n return { content, diffs, hasError, wasUpdated };\n }\n\n if (!hasStartMarker || !hasEndMarker) {\n hasError = true;\n diffs.push(\"Index marker section is malformed: both start and end markers are required.\");\n return { content, diffs, hasError, wasUpdated };\n }\n\n // Extract existing section. If extraction fails despite both markers existing,\n // marker placement/order is malformed.\n const existingSection = extractMarkerSection(content, startMarker, endMarker);\n if (!existingSection) {\n hasError = true;\n diffs.push(\"Index marker section is malformed: start marker must appear before end marker.\");\n return { content, diffs, hasError, wasUpdated };\n }\n\n // Generate new section\n const rawSection = await generateIndexSection(categories, command, scope, indexOptions);\n const generatedSection = await applyFormatter(rawSection, formatter);\n\n // Compare sections\n if (existingSection !== generatedSection) {\n if (updateMode) {\n const updated = replaceMarkerSection(content, startMarker, endMarker, generatedSection);\n if (updated) {\n content = updated;\n wasUpdated = true;\n } else {\n hasError = true;\n diffs.push(\"Failed to replace index section\");\n }\n } else {\n hasError = true;\n diffs.push(formatDiff(existingSection, generatedSection));\n }\n }\n\n return { content, diffs, hasError, wasUpdated };\n}\n\n/**\n * Find which file contains a specific command\n */\nfunction findFileForCommand(\n commandPath: string,\n files: FileMapping,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): string | null {\n for (const [filePath, fileConfigRaw] of Object.entries(files)) {\n const { commandPaths } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);\n\n if (commandPaths.includes(commandPath)) {\n return filePath;\n }\n }\n return null;\n}\n\n/**\n * Find which target commands are contained in a file\n * Also expands each target command to include subcommands that are NOT explicitly in specifiedCommands\n */\nfunction findTargetCommandsInFile(\n targetCommands: string[],\n filePath: string,\n files: FileMapping,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): string[] {\n const fileConfigRaw = files[filePath];\n if (!fileConfigRaw) return [];\n\n const { specifiedCommands, commandPaths } = resolveConfiguredCommandPaths(\n fileConfigRaw,\n allCommands,\n ignores,\n );\n\n // Expand targetCommands to include their subcommands,\n // but exclude subcommands that are explicitly in specifiedCommands\n const expandedTargets = new Set<string>();\n for (const targetCmd of targetCommands) {\n if (!commandPaths.includes(targetCmd)) continue;\n\n // Add the target command itself\n expandedTargets.add(targetCmd);\n\n // Add subcommands that are NOT explicitly specified\n for (const cmdPath of commandPaths) {\n if (isSubcommandOf(cmdPath, targetCmd) && !specifiedCommands.includes(cmdPath)) {\n expandedTargets.add(cmdPath);\n }\n }\n }\n\n return Array.from(expandedTargets);\n}\n\n/**\n * Generate a single command section (already contains section markers from renderer)\n */\nfunction generateCommandSection(\n cmdPath: string,\n allCommands: Map<string, CommandInfo>,\n render: RenderFunction,\n filePath?: string,\n fileMap?: Record<string, string>,\n rootDocPath?: string,\n hasGlobalOptions?: boolean,\n): string | null {\n const info = allCommands.get(cmdPath);\n if (!info) return null;\n\n // Add file context to CommandInfo for cross-file link generation\n const enriched: CommandInfo = { ...info, filePath, fileMap, rootDocPath };\n if (hasGlobalOptions !== undefined) {\n enriched.hasGlobalOptions = hasGlobalOptions;\n }\n return render(enriched);\n}\n\n/**\n * Generate markdown for a file containing multiple commands\n * Each command section is wrapped with markers for partial validation\n */\nfunction generateFileMarkdown(\n commandPaths: string[],\n allCommands: Map<string, CommandInfo>,\n render: RenderFunction,\n filePath?: string,\n fileMap?: Record<string, string>,\n specifiedOrder?: string[],\n fileConfig?: FileConfig,\n rootDocPath?: string,\n hasGlobalOptions?: boolean,\n): string {\n const sections: string[] = [];\n\n // Add file header if title or description is provided\n const header = fileConfig ? generateFileHeader(fileConfig) : null;\n if (header) {\n sections.push(header);\n }\n\n // Sort commands depth-first while preserving specified order\n const sortedPaths = sortDepthFirst(commandPaths, specifiedOrder ?? []);\n\n for (const cmdPath of sortedPaths) {\n const section = generateCommandSection(\n cmdPath,\n allCommands,\n render,\n filePath,\n fileMap,\n rootDocPath,\n hasGlobalOptions,\n );\n if (section) {\n sections.push(section);\n }\n }\n\n return `${sections.join(\"\\n\")}\\n`;\n}\n\n/**\n * Build a map of command path to file path\n */\nfunction buildFileMap(\n files: FileMapping,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): Record<string, string> {\n const fileMap: Record<string, string> = {};\n\n for (const [filePath, fileConfigRaw] of Object.entries(files)) {\n const { commandPaths } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);\n\n for (const cmdPath of commandPaths) {\n fileMap[cmdPath] = filePath;\n }\n }\n\n return fileMap;\n}\n\n/**\n * Execute examples for commands based on configuration\n */\nasync function executeConfiguredExamples(\n allCommands: Map<string, CommandInfo>,\n examplesConfig: ExampleConfig,\n rootCommand: AnyCommand,\n): Promise<void> {\n for (const [cmdPath, cmdConfig] of Object.entries(examplesConfig)) {\n const commandInfo = allCommands.get(cmdPath);\n if (!commandInfo?.examples?.length) {\n continue;\n }\n\n // Normalize config: true means no mock setup\n const config = cmdConfig === true ? {} : cmdConfig;\n\n // Parse command path into array\n const commandPath = cmdPath ? cmdPath.split(\" \") : [];\n\n // Execute examples and store results\n const results = await executeExamples(commandInfo.examples, config, rootCommand, commandPath);\n\n // Update CommandInfo with execution results\n commandInfo.exampleResults = results;\n }\n}\n\n/**\n * Convert PathConfig to FileMapping with explicit command paths.\n * Uses noExpand to prevent subcommand expansion since paths are pre-resolved.\n */\nfunction pathToFiles(\n pathConfig: PathConfig,\n allCommands: Map<string, CommandInfo>,\n): { files: FileMapping; rootDocPath: string } {\n if (typeof pathConfig === \"string\") {\n // All commands in one file\n return {\n files: { [pathConfig]: Array.from(allCommands.keys()) },\n rootDocPath: pathConfig,\n };\n }\n\n const { root, commands = {} } = pathConfig;\n const files: FileMapping = {};\n\n // Collect commands explicitly assigned to other files.\n // Sort by specificity (most specific first) so that e.g. 'config get' -> 'get.md'\n // takes priority over 'config' -> 'config.md' for that descendant.\n const assignedToOtherFiles = new Set<string>();\n const sortedEntries = Object.entries(commands).sort(\n ([a], [b]) => b.split(\" \").length - a.split(\" \").length,\n );\n\n for (const [cmdPath, filePath] of sortedEntries) {\n if (!files[filePath]) {\n files[filePath] = { commands: [], noExpand: true };\n }\n const fc = files[filePath] as FileConfig;\n // Add the command and all its descendants, skipping already-assigned commands\n for (const existingPath of allCommands.keys()) {\n if (\n (existingPath === cmdPath || existingPath.startsWith(cmdPath + \" \")) &&\n !assignedToOtherFiles.has(existingPath)\n ) {\n fc.commands.push(existingPath);\n assignedToOtherFiles.add(existingPath);\n }\n }\n }\n\n // Remaining commands go to root file\n const rootCommands = Array.from(allCommands.keys()).filter((p) => !assignedToOtherFiles.has(p));\n files[root] = { commands: rootCommands, noExpand: true };\n\n return { files, rootDocPath: root };\n}\n\n/**\n * Generate documentation from command definition\n */\nexport async function generateDoc(config: GenerateDocConfig): Promise<GenerateDocResult> {\n const {\n command,\n ignores = [],\n format = {},\n formatter,\n examples: examplesConfig,\n targetCommands,\n globalArgs,\n } = config;\n\n // Collect all commands early (needed for PathConfig conversion)\n const allCommands = await collectAllCommands(command);\n\n // Resolve files from PathConfig or direct FileMapping\n let files: FileMapping;\n let usingPathConfig = false;\n let resolvedRootDocPath: string | undefined;\n if (config.path !== undefined) {\n if (config.files !== undefined) {\n throw new Error('Cannot specify both \"path\" and \"files\". Use one or the other.');\n }\n const converted = pathToFiles(config.path, allCommands);\n files = converted.files;\n resolvedRootDocPath = converted.rootDocPath;\n usingPathConfig = true;\n } else if (config.files !== undefined) {\n files = config.files;\n } else {\n throw new Error('Either \"path\" or \"files\" must be specified.');\n }\n\n // Auto-derive rootDoc from PathConfig or globalArgs\n let rootDoc = config.rootDoc;\n if (!rootDoc && usingPathConfig && (globalArgs || config.rootInfo)) {\n rootDoc = { path: resolvedRootDocPath! };\n }\n\n // Auto-derive rootDoc.globalOptions from globalArgs schema if provided\n if (globalArgs && rootDoc && !rootDoc.globalOptions) {\n const optionFields = extractFields(globalArgs).fields.filter((f) => !f.positional);\n if (optionFields.length > 0) {\n const globalShape: ArgsShape = Object.fromEntries(\n optionFields.map((f) => [f.name, f.schema]),\n );\n rootDoc = { ...rootDoc, globalOptions: globalShape };\n }\n }\n const updateMode = isTruthyEnv(UPDATE_GOLDEN_ENV);\n const doctorMode = isTruthyEnv(DOCTOR_ENV);\n let hasDoctorIssues = false;\n\n // Validate rootDoc.path does not overlap with files keys (only for explicit files mode)\n if (rootDoc && !usingPathConfig) {\n const normalizedRootDocPath = normalizeDocPathForComparison(rootDoc.path);\n const hasOverlap = Object.keys(files).some(\n (filePath) => normalizeDocPathForComparison(filePath) === normalizedRootDocPath,\n );\n if (hasOverlap) {\n throw new Error(`rootDoc.path \"${rootDoc.path}\" must not also appear as a key in files.`);\n }\n }\n\n // Execute examples for all commands specified in examplesConfig\n if (examplesConfig) {\n await executeConfiguredExamples(allCommands, examplesConfig, command);\n }\n\n const hasTargetCommands = targetCommands !== undefined && targetCommands.length > 0;\n\n // Validate all targetCommands exist in files\n if (hasTargetCommands) {\n for (const targetCommand of targetCommands) {\n const targetFilePath = findFileForCommand(targetCommand, files, allCommands, ignores);\n if (!targetFilePath) {\n throw new Error(`Target command \"${targetCommand}\" not found in any file configuration`);\n }\n }\n }\n\n // Auto-exclude options defined in global options markers from command option tables.\n // These exclusions are intentionally global.\n const globalOptionDefinitions = collectGlobalOptionDefinitions(rootDoc);\n const documentedCommandPaths = hasTargetCommands\n ? collectTargetDocumentedCommandPaths(targetCommands, files, allCommands, ignores)\n : collectDocumentedCommandPaths(files, allCommands, ignores);\n validateGlobalOptionCompatibility(documentedCommandPaths, allCommands, globalOptionDefinitions);\n\n if (globalOptionDefinitions.size > 0) {\n for (const info of allCommands.values()) {\n info.options = info.options.filter((opt) => !globalOptionDefinitions.has(opt.name));\n }\n }\n\n // Collect all explicitly specified commands from files\n const allFilesCommands: string[] = [];\n for (const fileConfigRaw of Object.values(files)) {\n const fileConfig = normalizeFileConfig(fileConfigRaw);\n allFilesCommands.push(...fileConfig.commands);\n }\n\n // Validate ignores refer to existing commands\n validateIgnoresExist(ignores, allCommands);\n\n // Validate no conflicts between files and ignores\n validateNoConflicts(allFilesCommands, ignores, allCommands);\n\n // Build file map for cross-file links\n const fileMap = buildFileMap(files, allCommands, ignores);\n\n const results: GenerateDocResult[\"files\"] = [];\n let hasError = false;\n\n // Process each file\n for (const [filePath, fileConfigRaw] of Object.entries(files)) {\n const { fileConfig, specifiedCommands, commandPaths } = resolveConfiguredCommandPaths(\n fileConfigRaw,\n allCommands,\n ignores,\n );\n\n if (specifiedCommands.length === 0) {\n continue;\n }\n\n // Skip files where no commands resolved\n if (commandPaths.length === 0) {\n continue;\n }\n\n // In target mode, skip non-target files entirely\n const fileTargetCommands = hasTargetCommands\n ? findTargetCommandsInFile(targetCommands, filePath, files, allCommands, ignores)\n : [];\n if (hasTargetCommands && fileTargetCommands.length === 0) {\n continue;\n }\n\n let fileStatus: \"match\" | \"created\" | \"updated\" | \"diff\" = \"match\";\n const diffs: string[] = [];\n\n // Calculate minimum depth in this file for relative heading level\n const minDepth = Math.min(...commandPaths.map((p) => allCommands.get(p)?.depth ?? 1));\n\n // Adjust headingLevel so that minimum depth command gets the configured headingLevel\n const adjustedHeadingLevel = Math.max(\n 1,\n (format?.headingLevel ?? 1) - (minDepth - 1),\n ) as HeadingLevel;\n\n // Create file-specific renderer with adjusted headingLevel (if no custom renderer)\n const fileRenderer = createCommandRenderer({\n ...format,\n headingLevel: adjustedHeadingLevel,\n });\n\n // Use custom renderer if provided, otherwise use file-specific renderer\n const render = fileConfig.render ?? fileRenderer;\n\n // In PathConfig mode, the rootDoc file has extra content (header, global-options)\n // managed by rootDoc processing. Use marker-based comparison to avoid mismatch.\n const isRootDocFile =\n usingPathConfig &&\n rootDoc &&\n normalizeDocPathForComparison(filePath) === normalizeDocPathForComparison(rootDoc.path);\n const useMarkerBasedComparison = hasTargetCommands || isRootDocFile;\n\n // Handle partial validation when targetCommands are specified\n // or when the file is the rootDoc in PathConfig mode\n if (useMarkerBasedComparison) {\n // Read existing content once for all target commands in this file\n let existingContent = readFile(filePath);\n // Pre-compute sorted order once per file for insertCommandSections\n const sortedCommandPaths = sortDepthFirst(commandPaths, specifiedCommands);\n const effectiveTargetCommands = hasTargetCommands ? fileTargetCommands : commandPaths;\n\n for (const targetCommand of effectiveTargetCommands) {\n // Generate only the target command's section\n const rawSection = generateCommandSection(\n targetCommand,\n allCommands,\n render,\n filePath,\n fileMap,\n rootDoc?.path,\n globalOptionDefinitions.size > 0,\n );\n\n if (!rawSection) {\n throw new Error(`Target command \"${targetCommand}\" not found in commands`);\n }\n\n // Apply formatter to the section\n const generatedSection = await applyFormatter(rawSection, formatter);\n\n if (!existingContent) {\n // File doesn't exist yet, create it with the section only\n if (updateMode) {\n // For root command, include file header if configured\n const isRootCommand = targetCommand === \"\";\n const header = isRootCommand && fileConfig ? generateFileHeader(fileConfig) : null;\n const fullContent = header ? `${header}\\n${generatedSection}` : generatedSection;\n writeFile(filePath, fullContent);\n existingContent = fullContent;\n fileStatus = \"created\";\n } else {\n hasError = true;\n fileStatus = \"diff\";\n diffs.push(\n `File does not exist. Target command \"${targetCommand}\" section cannot be validated.`,\n );\n }\n continue;\n }\n\n // Check which section markers exist for this command in the existing content\n const existingMarkers = collectSectionMarkers(existingContent, targetCommand);\n\n if (existingMarkers.length === 0) {\n // No markers found — insert full template\n if (updateMode) {\n existingContent = insertCommandSections(\n existingContent,\n targetCommand,\n generatedSection,\n sortedCommandPaths,\n );\n writeFile(filePath, existingContent);\n if (fileStatus !== \"created\") {\n fileStatus = \"updated\";\n }\n } else {\n hasError = true;\n fileStatus = \"diff\";\n diffs.push(\n `Existing file does not contain section markers for command \"${targetCommand}\"`,\n );\n }\n continue;\n }\n\n // Validate/update only existing section markers\n for (const sectionType of existingMarkers) {\n const existingSection = extractSectionMarker(existingContent, sectionType, targetCommand);\n const generatedSectionPart = extractSectionMarker(\n generatedSection,\n sectionType,\n targetCommand,\n );\n\n if (!existingSection) {\n continue;\n }\n\n // Stale section: exists in document but not in generated output — replace with empty markers\n if (!generatedSectionPart) {\n const emptyMarker =\n sectionStartMarker(sectionType, targetCommand) +\n \"\\n\" +\n sectionEndMarker(sectionType, targetCommand);\n if (existingSection !== emptyMarker) {\n if (updateMode) {\n const updated = replaceSectionMarker(\n existingContent,\n sectionType,\n targetCommand,\n emptyMarker,\n );\n if (!updated) {\n throw new Error(\n `Failed to replace stale ${sectionType} section for command \"${targetCommand}\"`,\n );\n }\n existingContent = updated.replace(/\\n{3,}/g, \"\\n\\n\");\n writeFile(filePath, existingContent);\n if (fileStatus !== \"created\") {\n fileStatus = \"updated\";\n }\n } else {\n hasError = true;\n fileStatus = \"diff\";\n diffs.push(formatDiff(existingSection, emptyMarker));\n }\n }\n continue;\n }\n\n if (existingSection !== generatedSectionPart) {\n if (updateMode) {\n const updated = replaceSectionMarker(\n existingContent,\n sectionType,\n targetCommand,\n generatedSectionPart,\n );\n if (updated) {\n existingContent = updated;\n writeFile(filePath, existingContent);\n if (fileStatus !== \"created\") {\n fileStatus = \"updated\";\n }\n } else {\n throw new Error(\n `Failed to replace ${sectionType} section for command \"${targetCommand}\"`,\n );\n }\n } else {\n hasError = true;\n fileStatus = \"diff\";\n diffs.push(formatDiff(existingSection, generatedSectionPart));\n }\n }\n }\n\n // Doctor mode: detect and insert missing section markers\n if (doctorMode) {\n const generatedMarkers = collectSectionMarkers(generatedSection, targetCommand);\n const existingMarkerSet = new Set(existingMarkers);\n\n for (const sectionType of generatedMarkers) {\n if (existingMarkerSet.has(sectionType)) {\n continue;\n }\n\n const generatedSectionPart = extractSectionMarker(\n generatedSection,\n sectionType,\n targetCommand,\n );\n if (!generatedSectionPart) {\n continue;\n }\n\n if (updateMode) {\n existingContent = insertSectionMarkerAtOrder(\n existingContent,\n sectionType,\n targetCommand,\n generatedSectionPart,\n );\n writeFile(filePath, existingContent);\n if (fileStatus !== \"created\") {\n fileStatus = \"updated\";\n }\n } else {\n hasError = true;\n hasDoctorIssues = true;\n fileStatus = \"diff\";\n diffs.push(\n `[doctor] Missing section marker \"${sectionType}\" for command \"${formatCommandPath(targetCommand)}\". Run with ${DOCTOR_ENV}=true ${UPDATE_GOLDEN_ENV}=true to insert.\\n${generatedSectionPart}`,\n );\n }\n }\n }\n }\n\n // Remove orphaned section markers for commands no longer in this file\n if (existingContent) {\n const existingMarkerPaths = collectSectionMarkerPaths(existingContent);\n const commandPathSet = new Set(commandPaths);\n\n if (updateMode) {\n let removedAny = false;\n for (const markerPath of existingMarkerPaths) {\n if (!commandPathSet.has(markerPath)) {\n existingContent = removeCommandSections(existingContent, markerPath);\n removedAny = true;\n }\n }\n if (removedAny) {\n writeFile(filePath, existingContent);\n if (fileStatus !== \"created\") {\n fileStatus = \"updated\";\n }\n }\n } else {\n for (const markerPath of existingMarkerPaths) {\n if (!commandPathSet.has(markerPath)) {\n hasError = true;\n fileStatus = \"diff\";\n diffs.push(\n `Found orphaned section markers for deleted command \"${formatCommandPath(markerPath)}\"`,\n );\n }\n }\n }\n }\n } else {\n // Generate markdown with file context (pass specifiedCommands as order hint)\n const rawMarkdown = generateFileMarkdown(\n commandPaths,\n allCommands,\n render,\n filePath,\n fileMap,\n specifiedCommands,\n fileConfig,\n rootDoc?.path,\n globalOptionDefinitions.size > 0,\n );\n\n // Apply formatter if provided\n const generatedMarkdown = await applyFormatter(rawMarkdown, formatter);\n // Full file comparison (original behavior)\n const comparison = compareWithExisting(generatedMarkdown, filePath);\n\n if (comparison.match) {\n // fileStatus stays \"match\"\n } else if (updateMode) {\n writeFile(filePath, generatedMarkdown);\n fileStatus = comparison.fileExists ? \"updated\" : \"created\";\n } else {\n hasError = true;\n fileStatus = \"diff\";\n if (comparison.diff) {\n diffs.push(comparison.diff);\n }\n }\n }\n\n // Determine final status based on diffs\n if (diffs.length > 0) {\n fileStatus = \"diff\";\n }\n\n results.push({\n path: filePath,\n status: fileStatus,\n diff: diffs.length > 0 ? diffs.join(\"\\n\\n\") : undefined,\n });\n }\n\n // === Root document processing ===\n if (rootDoc) {\n const rootDocFilePath = rootDoc.path;\n let rootDocStatus: \"match\" | \"created\" | \"updated\" | \"diff\" = \"match\";\n const rootDocDiffs: string[] = [];\n\n const existingContent = readFile(rootDocFilePath);\n if (existingContent === null) {\n hasError = true;\n rootDocStatus = \"diff\";\n rootDocDiffs.push(\"File does not exist. Cannot validate rootDoc markers.\");\n } else {\n let content = existingContent;\n let markerUpdated = false;\n\n // Validate/update rootDoc file header derived from command.name/description\n // rootInfo overrides command defaults\n const rootInfo = config.rootInfo;\n const rootDocFileConfig: FileHeaderConfig = {\n title: rootInfo?.title ?? command.name,\n };\n if (rootDoc.headingLevel !== undefined) {\n rootDocFileConfig.headingLevel = rootDoc.headingLevel;\n }\n const rootDescription = rootInfo?.description ?? command.description;\n if (rootDescription !== undefined) {\n rootDocFileConfig.description = rootDescription;\n }\n const headerResult = processFileHeader(content, rootDocFileConfig, updateMode);\n content = headerResult.content;\n if (headerResult.diff) {\n rootDocDiffs.push(headerResult.diff);\n }\n if (headerResult.hasError) {\n hasError = true;\n }\n if (headerResult.wasUpdated) {\n markerUpdated = true;\n }\n\n // Process rootInfo.header marker (after title/description)\n if (rootInfo?.header) {\n const headerMarkerResult = await processStaticMarker(\n content,\n \"Root header\",\n rootHeaderStartMarker(),\n rootHeaderEndMarker(),\n rootInfo.header,\n updateMode,\n formatter,\n usingPathConfig,\n );\n content = headerMarkerResult.content;\n rootDocDiffs.push(...headerMarkerResult.diffs);\n if (headerMarkerResult.hasError) {\n hasError = true;\n }\n if (headerMarkerResult.wasUpdated) {\n markerUpdated = true;\n }\n }\n\n // Detect and clean up unexpected section markers in rootDoc\n // In PathConfig mode, section markers are expected (rootDoc overlaps with files)\n if (!usingPathConfig) {\n const unexpectedSectionPaths = collectSectionMarkerPaths(content);\n if (unexpectedSectionPaths.length > 0) {\n if (updateMode) {\n for (const commandPath of unexpectedSectionPaths) {\n content = removeCommandSections(content, commandPath);\n }\n markerUpdated = true;\n } else {\n hasError = true;\n rootDocDiffs.push(\n `Found unexpected section markers in rootDoc: ${unexpectedSectionPaths\n .map((commandPath) => `\"${formatCommandPath(commandPath)}\"`)\n .join(\", \")}.`,\n );\n }\n }\n }\n\n // Process global options marker\n const normalizedGlobalOptions = normalizeGlobalOptions(rootDoc.globalOptions);\n if (normalizedGlobalOptions) {\n const globalOptionsResult = await processGlobalOptionsMarker(\n content,\n normalizedGlobalOptions,\n updateMode,\n formatter,\n usingPathConfig,\n );\n content = globalOptionsResult.content;\n rootDocDiffs.push(...globalOptionsResult.diffs);\n if (globalOptionsResult.hasError) {\n hasError = true;\n }\n if (globalOptionsResult.wasUpdated) {\n markerUpdated = true;\n }\n }\n\n // Process index marker (auto-derived from files)\n const derivedCategories = deriveIndexFromFiles(files, rootDocFilePath, allCommands, ignores);\n // Forward slashes keep the marker stable when docs are regenerated on a different OS.\n const indexScope = path.relative(process.cwd(), rootDocFilePath).replace(/\\\\/g, \"/\");\n const indexResult = await processIndexMarker(\n content,\n derivedCategories,\n command,\n indexScope,\n updateMode,\n formatter,\n rootDoc.index,\n );\n content = indexResult.content;\n rootDocDiffs.push(...indexResult.diffs);\n if (indexResult.hasError) {\n hasError = true;\n }\n if (indexResult.wasUpdated) {\n markerUpdated = true;\n }\n\n // Process rootInfo.footer marker (at end of document)\n if (rootInfo?.footer) {\n const footerMarkerResult = await processStaticMarker(\n content,\n \"Root footer\",\n rootFooterStartMarker(),\n rootFooterEndMarker(),\n rootInfo.footer,\n updateMode,\n formatter,\n usingPathConfig,\n );\n content = footerMarkerResult.content;\n rootDocDiffs.push(...footerMarkerResult.diffs);\n if (footerMarkerResult.hasError) {\n hasError = true;\n }\n if (footerMarkerResult.wasUpdated) {\n markerUpdated = true;\n }\n }\n\n // Write updated content if markers were modified\n if (updateMode && markerUpdated) {\n writeFile(rootDocFilePath, content);\n if (rootDocStatus === \"match\") {\n rootDocStatus = \"updated\";\n }\n }\n }\n\n // Determine final status based on diffs\n if (rootDocDiffs.length > 0) {\n rootDocStatus = \"diff\";\n }\n\n results.push({\n path: rootDocFilePath,\n status: rootDocStatus,\n diff: rootDocDiffs.length > 0 ? rootDocDiffs.join(\"\\n\\n\") : undefined,\n });\n }\n\n const errorHint = hasDoctorIssues\n ? `Run with ${DOCTOR_ENV}=true ${UPDATE_GOLDEN_ENV}=true to fix missing markers.`\n : `Run with ${UPDATE_GOLDEN_ENV}=true to update.`;\n\n return {\n success: !hasError,\n files: results,\n error: hasError ? `Documentation is out of date. ${errorHint}` : undefined,\n };\n}\n\n/**\n * Assert that documentation matches golden files\n * Throws an error if there are differences and update mode is not enabled\n */\nexport async function assertDocMatch(config: GenerateDocConfig): Promise<void> {\n const result = await generateDoc(config);\n\n if (!result.success) {\n const diffMessages = result.files\n .filter((f) => f.status === \"diff\")\n .map((f) => {\n let msg = `File: ${f.path}\\n`;\n if (f.diff) {\n msg += f.diff;\n }\n return msg;\n })\n .join(\"\\n\\n\");\n\n throw new Error(\n `Documentation does not match golden files.\\n\\n${diffMessages}\\n\\n` +\n (result.error ?? `Run with ${UPDATE_GOLDEN_ENV}=true to update the documentation.`),\n );\n }\n}\n\n/**\n * Initialize documentation files by deleting them\n * Only deletes when update mode is enabled (POLITTY_DOCS_UPDATE=true)\n * Use this in beforeAll to ensure skipped tests don't leave stale sections\n * @param config - Config containing files to initialize, or a single file path\n * @param fileSystem - Optional fs implementation (useful when fs is mocked)\n */\nexport function initDocFile(\n config: Pick<GenerateDocConfig, \"files\"> | string,\n fileSystem?: DeleteFileFs,\n): void {\n if (!isTruthyEnv(UPDATE_GOLDEN_ENV)) {\n return;\n }\n\n if (typeof config === \"string\") {\n deleteFile(config, fileSystem);\n } else if (config.files) {\n // rootDoc is NOT deleted because generateDoc expects it to exist with markers.\n // Only generated files (which are fully regenerated) are deleted.\n for (const filePath of Object.keys(config.files)) {\n deleteFile(filePath, fileSystem);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAiaA,MAAa,oBAAoB;;;;;;AAOjC,MAAa,aAAa;;;;AAK1B,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAWA,MAAa,wBAAwB;;;;AAKrC,SAAgB,mBAAmB,MAAmB,OAAuB;CAC3E,OAAO,QAAQ,sB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OAAO;EACL,SAAS,CAAC;EACV,OAAO;EACP,OAAO,WAAW,iCAAiC,cAAc;CACnE;AACF;;;;;AAMA,eAAsB,eAAe,QAA0C;CAC7E,MAAM,SAAS,MAAM,YAAY,MAAM;CAEvC,IAAI,CAAC,OAAO,SAAS;EACnB,MAAM,eAAe,OAAO,MACzB,QAAQ,MAAM,EAAE,WAAW,MAAM,CAAC,CAClC,KAAK,MAAM;GACV,IAAI,MAAM,SAAS,EAAE,KAAK;GAC1B,IAAI,EAAE,MACJ,OAAO,EAAE;GAEX,OAAO;EACT,CAAC,CAAC,CACD,KAAK,MAAM;EAEd,MAAM,IAAI,MACR,iDAAiD,aAAa,SAC3D,OAAO,SAAS,kCAA8B,oCACnD;CACF;AACF;;;;;;;;AASA,SAAgB,YACd,QACA,YACM;CACN,IAAI,CAAC,iCAA6B,GAChC;CAGF,IAAI,OAAO,WAAW,UACpB,WAAW,QAAQ,UAAU;MACxB,IAAI,OAAO,OAGhB,KAAK,MAAM,YAAY,OAAO,KAAK,OAAO,KAAK,GAC7C,WAAW,UAAU,UAAU;AAGrC"}
1
+ {"version":3,"file":"index.cjs","names":["escapeTableCell","formatDefaultValue","generateAnchor","path","path","fs","getExtractedFields","resolveLazyCommand","createLogCollector","extractFields","z","escapeTableCell","isSubcommandOf","z","extractFields","path"],"sources":["../../src/docs/types.ts","../../src/docs/default-renderers.ts","../../src/docs/doc-comparator.ts","../../src/docs/doc-generator.ts","../../src/docs/example-executor.ts","../../src/docs/render-args.ts","../../src/docs/render-index.ts","../../src/docs/golden-test.ts"],"sourcesContent":["import type { ExtractedFields, ResolvedFieldMeta } from \"../core/schema-extractor.js\";\nimport type { AnyCommand, ArgsSchema, Example } from \"../types.js\";\nimport type { ArgsShape, ArgsTableOptions } from \"./render-args.js\";\n\n/** Heading level for markdown headings (1-6) */\nexport type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;\n\n/**\n * Options for rendering command index\n */\nexport type CommandIndexOptions = {\n /** Base heading level (default: 3, which renders as ###) */\n headingLevel?: HeadingLevel;\n /** Only include leaf commands (commands without subcommands). Default: true */\n leafOnly?: boolean;\n};\n\n/**\n * Command information for rendering\n */\nexport interface CommandInfo {\n /** Command name */\n name: string;\n /** Command description */\n description?: string | undefined;\n /** Alternative names (aliases) for this command */\n aliases?: string[] | undefined;\n /** Full command path (e.g., \"my-cli config get\") */\n fullCommandPath: string;\n /** Command path relative to root (e.g., \"\" for root, \"config\" for subcommand) */\n commandPath: string;\n /** Command depth (1 for root commands, 2 for subcommands, etc.) */\n depth: number;\n /** Positional arguments */\n positionalArgs: ResolvedFieldMeta[];\n /** Options (non-positional arguments) */\n options: ResolvedFieldMeta[];\n /** Subcommand information */\n subCommands: SubCommandInfo[];\n /** Extracted field information from schema */\n extracted: ExtractedFields | null;\n /** Original command object */\n command: AnyCommand;\n /** Additional notes */\n notes?: string | undefined;\n /** File path where this command is rendered (for cross-file links) */\n filePath?: string | undefined;\n /** Map of command path to file path (for cross-file links) */\n fileMap?: Record<string, string> | undefined;\n /** Example definitions from command */\n examples?: Example[] | undefined;\n /** Example execution results (populated when examples are executed) */\n exampleResults?: ExampleExecutionResult[] | undefined;\n /** Path to root document file (for global options link generation) */\n rootDocPath?: string | undefined;\n /** Whether global options exist (for global options link generation) */\n hasGlobalOptions?: boolean;\n}\n\n/**\n * Subcommand information\n */\nexport interface SubCommandInfo {\n /** Subcommand name */\n name: string;\n /** Subcommand description */\n description?: string | undefined;\n /** Alternative names (aliases) for this subcommand */\n aliases?: string[] | undefined;\n /** Full command path */\n fullPath: string[];\n}\n\n/**\n * Example execution result\n */\nexport interface ExampleExecutionResult {\n /** Command arguments that were executed */\n cmd: string;\n /** Description of the example */\n desc: string;\n /** Expected output (if defined in example) */\n expectedOutput?: string | undefined;\n /** Captured stdout */\n stdout: string;\n /** Captured stderr */\n stderr: string;\n /** Whether execution was successful */\n success: boolean;\n}\n\n/**\n * Example execution config for a specific command path\n * If a command path is specified in ExampleConfig, its examples will be executed\n */\nexport interface ExampleCommandConfig {\n /** Mock setup before running examples */\n mock?: () => void | Promise<void>;\n /** Mock cleanup after running examples */\n cleanup?: () => void | Promise<void>;\n}\n\n/**\n * Example execution configuration\n * Key is command path (e.g., \"\", \"config\", \"config get\")\n * All specified command paths will have their examples executed\n *\n * @example\n * // With mock setup\n * { \"\": { mock: () => mockFs(), cleanup: () => restoreFs() } }\n *\n * // Without mock (just execute)\n * { \"user\": true }\n */\nexport type ExampleConfig = Record<string, ExampleCommandConfig | true>;\n\n/**\n * Render function type for custom markdown generation\n */\nexport type RenderFunction = (info: CommandInfo) => string;\n\n/**\n * Section render function type (legacy)\n * @param defaultContent - The default rendered content for this section\n * @param info - Command information\n * @returns The final content to render (return empty string to hide section)\n * @deprecated Use context-based render functions instead\n */\nexport type SectionRenderFunction = (defaultContent: string, info: CommandInfo) => string;\n\n/**\n * Render options for options/arguments\n */\nexport interface RenderContentOptions {\n /** Style for rendering */\n style?: \"table\" | \"list\";\n /** Include heading (default: true) */\n withHeading?: boolean;\n}\n\n/**\n * Options render context\n */\nexport interface OptionsRenderContext {\n /** Options to render */\n options: ResolvedFieldMeta[];\n /** Render function that accepts options and optional rendering options */\n render: (options: ResolvedFieldMeta[], opts?: RenderContentOptions) => string;\n /** Heading prefix (e.g., \"###\") */\n heading: string;\n /** Command information */\n info: CommandInfo;\n}\nexport type OptionsRenderFunction = (context: OptionsRenderContext) => string;\n\n/**\n * Arguments render context\n */\nexport interface ArgumentsRenderContext {\n /** Arguments to render */\n args: ResolvedFieldMeta[];\n /** Render function that accepts arguments and optional rendering options */\n render: (args: ResolvedFieldMeta[], opts?: RenderContentOptions) => string;\n /** Heading prefix (e.g., \"###\") */\n heading: string;\n /** Command information */\n info: CommandInfo;\n}\nexport type ArgumentsRenderFunction = (context: ArgumentsRenderContext) => string;\n\n/**\n * Subcommands render options\n */\nexport interface SubcommandsRenderOptions {\n /** Generate anchor links */\n generateAnchors?: boolean;\n /** Include heading (default: true) */\n withHeading?: boolean;\n}\n\n/**\n * Subcommands render context\n */\nexport interface SubcommandsRenderContext {\n /** Subcommands to render */\n subcommands: SubCommandInfo[];\n /** Render function that accepts subcommands and optional rendering options */\n render: (subcommands: SubCommandInfo[], opts?: SubcommandsRenderOptions) => string;\n /** Heading prefix (e.g., \"###\") */\n heading: string;\n /** Command information */\n info: CommandInfo;\n}\nexport type SubcommandsRenderFunction = (context: SubcommandsRenderContext) => string;\n\n/**\n * Examples render options\n */\nexport interface ExamplesRenderOptions {\n /** Include heading (default: true) */\n withHeading?: boolean;\n /** Show execution output (default: true when results available) */\n showOutput?: boolean;\n /** Command prefix to prepend to example commands (e.g., \"my-cli config get\") */\n commandPrefix?: string;\n}\n\n/**\n * Examples render context\n */\nexport interface ExamplesRenderContext {\n /** Examples to render */\n examples: Example[];\n /** Execution results (if examples were executed) */\n results?: ExampleExecutionResult[] | undefined;\n /** Render function that accepts examples, results, and optional rendering options */\n render: (\n examples: Example[],\n results?: ExampleExecutionResult[],\n opts?: ExamplesRenderOptions,\n ) => string;\n /** Heading prefix (e.g., \"###\") */\n heading: string;\n /** Command information */\n info: CommandInfo;\n}\nexport type ExamplesRenderFunction = (context: ExamplesRenderContext) => string;\n\n/**\n * Simple section render context (for description, usage, notes, footer)\n */\nexport interface SimpleRenderContext {\n /** Default content */\n content: string;\n /** Heading prefix (e.g., \"###\") */\n heading: string;\n /** Command information */\n info: CommandInfo;\n}\nexport type SimpleRenderFunction = (context: SimpleRenderContext) => string;\n\n/**\n * Default renderer customization options\n */\nexport interface DefaultRendererOptions {\n /** Heading level (default: 1) */\n headingLevel?: HeadingLevel;\n /** Option display style */\n optionStyle?: \"table\" | \"list\";\n /** Generate anchor links to subcommands */\n generateAnchors?: boolean;\n /** Include subcommand details */\n includeSubcommandDetails?: boolean;\n /**\n * Omit the `<!-- politty:...:start/end -->` section markers from the rendered\n * output. Used by marker-free `files` generation. When markers are omitted the\n * output can only be regenerated wholesale (sections can no longer be located\n * and updated in place), which is exactly how marker-free `files` mode works.\n */\n markerless?: boolean;\n /** Custom renderer for description section */\n renderDescription?: SimpleRenderFunction;\n /** Custom renderer for usage section */\n renderUsage?: SimpleRenderFunction;\n /** Custom renderer for arguments section */\n renderArguments?: ArgumentsRenderFunction;\n /** Custom renderer for options section */\n renderOptions?: OptionsRenderFunction;\n /** Custom renderer for subcommands section */\n renderSubcommands?: SubcommandsRenderFunction;\n /** Custom renderer for notes section */\n renderNotes?: SimpleRenderFunction;\n /** Custom renderer for footer (default content is empty) */\n renderFooter?: SimpleRenderFunction;\n /** Custom renderer for examples section */\n renderExamples?: ExamplesRenderFunction;\n}\n\n/**\n * Root document configuration\n * The root document contains global options tables and command index sections.\n */\nexport interface RootDocConfig {\n /** Output file path */\n path: string;\n /**\n * Global options configuration.\n * ArgsShape directly, or { args, options } for render options.\n */\n globalOptions?: ArgsShape | { args: ArgsShape; options?: ArgsTableOptions };\n /** Heading level for the file header (default: 1) */\n headingLevel?: HeadingLevel;\n /** Index section rendering options */\n index?: CommandIndexOptions;\n}\n\n/**\n * Root command customization for the root document.\n * Controls the root document's title, description, header, and footer.\n */\nexport interface RootCommandInfo {\n /** Title (defaults to command.name) */\n title?: string;\n /** Description (defaults to command.description) */\n description?: string;\n /** Markdown placed after title/description */\n header?: string;\n /** Markdown placed at end of document */\n footer?: string;\n}\n\n/**\n * Path configuration for documentation output.\n * Simpler alternative to FileMapping for common patterns.\n *\n * @example\n * // All commands in one file\n * path: \"docs/CLI.md\"\n *\n * // Split files: root + specific commands in separate files\n * path: { root: \"docs/CLI.md\", commands: { \"build\": \"docs/build.md\" } }\n */\nexport type PathConfig = string | { root: string; commands?: Record<string, string> };\n\n/**\n * Per-file configuration with custom renderer\n */\nexport interface FileConfig {\n /** Command paths to include in this file (e.g., [\"\", \"user\", \"config get\"]) */\n commands: string[];\n /** Custom renderer for this file (optional) */\n render?: RenderFunction;\n /** File title (prepended to the file content) */\n title?: string;\n /** File description (added after title) */\n description?: string;\n /** Skip subcommand expansion (commands are used as-is). @internal */\n noExpand?: boolean;\n}\n\n/**\n * File mapping configuration\n * Key: output file path (e.g., \"docs/cli.md\")\n * Value: command paths array or FileConfig object\n *\n * @example\n * // Simple: single file with multiple commands\n * { \"docs/cli.md\": [\"\", \"user\", \"config\"] }\n *\n * // With custom renderer\n * { \"docs/cli.md\": { commands: [\"\"], render: customRenderer } }\n */\nexport type FileMapping = Record<string, string[] | FileConfig>;\n\n/**\n * generateDoc configuration\n */\nexport interface GenerateDocConfig {\n /** Command to generate documentation for */\n command: AnyCommand;\n /**\n * Root document configuration.\n * The root document contains global options tables and command index sections.\n * Title and description are derived from `command.name` and `command.description`.\n */\n rootDoc?: RootDocConfig;\n /**\n * Path configuration (simpler alternative to files).\n * Mutually exclusive with `files`.\n */\n path?: PathConfig;\n /** File output configuration (command path -> file mapping) */\n files?: FileMapping;\n /** Root command customization (title, description, header, footer) */\n rootInfo?: RootCommandInfo;\n /** Command paths to ignore (including their subcommands) */\n ignores?: string[];\n /** Default renderer options (used when render is not specified per file) */\n format?: DefaultRendererOptions;\n /** Formatter function to apply to generated content before comparison */\n formatter?: FormatterFunction;\n /** Example execution configuration (per command path) */\n examples?: ExampleConfig;\n /**\n * Target command paths to validate (e.g., [\"read\", \"config get\"])\n * When specified, only these commands' sections are validated.\n * The full document structure is used to maintain cross-file links.\n */\n targetCommands?: string[];\n /**\n * Global args schema (runtime schema alternative).\n * When provided, automatically derives `rootDoc.globalOptions` from this schema.\n */\n globalArgs?: ArgsSchema;\n /**\n * Template-based generation: output file path -> template file path.\n * The template mixes handwritten markdown with {{politty:...}} placeholders.\n * The output file is fully generated from the template and contains no\n * politty markers. Can be combined with `files` or `path`.\n */\n templates?: Record<string, string>;\n /**\n * Declare that you will hand-customize the `files` output.\n *\n * Default `false`: the output is fully generated and regenerated wholesale on\n * every run (with `targetCommands`, only files containing a target command are\n * regenerated, but each such file is rebuilt in full). The output carries no\n * `<!-- politty:...:start/end -->` markers — do not hand-edit it.\n *\n * Set to `true` when you want to hand-edit the output and have politty preserve\n * your edits: generated sections are wrapped in markers and updated in place\n * (with `targetCommands`), and handwritten content between them is kept. When a\n * command in the generated output gains a section the file does not yet have,\n * it is reported as a non-fatal warning (run with `POLITTY_DOCS_DOCTOR=true\n * POLITTY_DOCS_UPDATE=true` to insert it, or leave it removed to opt that\n * section out).\n *\n * This flag does not affect `path`/`rootDoc` output, which always uses markers\n * to inject generated sections into a handwritten file, nor `templates`, which\n * are always fully generated.\n */\n customizable?: boolean;\n}\n\n/**\n * generateDoc result\n */\nexport interface GenerateDocResult {\n /** Whether all files matched or were updated successfully */\n success: boolean;\n /** File processing results */\n files: Array<{\n /** File path */\n path: string;\n /** Status of this file */\n status: \"match\" | \"created\" | \"updated\" | \"diff\";\n /** Diff content (only when status is \"diff\") */\n diff?: string | undefined;\n }>;\n /** Error message (when success is false) */\n error?: string | undefined;\n}\n\n/**\n * Formatter function type\n * Formats generated content before comparison\n */\nexport type FormatterFunction = (content: string) => string | Promise<string>;\n\n/**\n * Environment variable name for update mode\n */\nexport const UPDATE_GOLDEN_ENV = \"POLITTY_DOCS_UPDATE\";\n\n/**\n * Environment variable name for doctor mode.\n * When enabled alone, detects and reports missing section markers (read-only).\n * When combined with POLITTY_DOCS_UPDATE=true, auto-inserts missing markers.\n */\nexport const DOCTOR_ENV = \"POLITTY_DOCS_DOCTOR\";\n\n/**\n * All section types in rendering order\n */\nexport const SECTION_TYPES = [\n \"heading\",\n \"description\",\n \"usage\",\n \"arguments\",\n \"options\",\n \"global-options-link\",\n \"subcommands\",\n \"examples\",\n \"notes\",\n] as const;\n\n/**\n * Section types for command documentation markers\n */\nexport type SectionType = (typeof SECTION_TYPES)[number];\n\n/**\n * Marker prefix for command section markers in generated documentation\n * Format: <!-- politty:command:<scope>:<type>:start --> ... <!-- politty:command:<scope>:<type>:end -->\n */\nexport const SECTION_MARKER_PREFIX = \"politty:command\";\n\n/**\n * Generate start marker for a command section\n */\nexport function sectionStartMarker(type: SectionType, scope: string): string {\n return `<!-- ${SECTION_MARKER_PREFIX}:${scope}:${type}:start -->`;\n}\n\n/**\n * Generate end marker for a command section\n */\nexport function sectionEndMarker(type: SectionType, scope: string): string {\n return `<!-- ${SECTION_MARKER_PREFIX}:${scope}:${type}:end -->`;\n}\n\n/**\n * Marker prefix for global options sections in generated documentation\n * Format: <!-- politty:global-options:start --> ... <!-- politty:global-options:end -->\n */\nexport const GLOBAL_OPTIONS_MARKER_PREFIX = \"politty:global-options\";\n\n/**\n * Generate start marker for a global options section\n */\nexport function globalOptionsStartMarker(): string {\n return `<!-- ${GLOBAL_OPTIONS_MARKER_PREFIX}:start -->`;\n}\n\n/**\n * Generate end marker for a global options section\n */\nexport function globalOptionsEndMarker(): string {\n return `<!-- ${GLOBAL_OPTIONS_MARKER_PREFIX}:end -->`;\n}\n\n/**\n * Marker prefix for root header sections in generated documentation\n */\nexport const ROOT_HEADER_MARKER_PREFIX = \"politty:root-header\";\n\nexport function rootHeaderStartMarker(): string {\n return `<!-- ${ROOT_HEADER_MARKER_PREFIX}:start -->`;\n}\n\nexport function rootHeaderEndMarker(): string {\n return `<!-- ${ROOT_HEADER_MARKER_PREFIX}:end -->`;\n}\n\n/**\n * Marker prefix for root footer sections in generated documentation\n */\nexport const ROOT_FOOTER_MARKER_PREFIX = \"politty:root-footer\";\n\nexport function rootFooterStartMarker(): string {\n return `<!-- ${ROOT_FOOTER_MARKER_PREFIX}:start -->`;\n}\n\nexport function rootFooterEndMarker(): string {\n return `<!-- ${ROOT_FOOTER_MARKER_PREFIX}:end -->`;\n}\n\n/**\n * Marker prefix for index sections in generated documentation\n * Format: <!-- politty:index:<scope>:start --> ... <!-- politty:index:<scope>:end -->\n */\nexport const INDEX_MARKER_PREFIX = \"politty:index\";\n\n/**\n * Generate start marker for an index section\n */\nexport function indexStartMarker(scope: string): string {\n return `<!-- ${INDEX_MARKER_PREFIX}:${scope}:start -->`;\n}\n\n/**\n * Generate end marker for an index section\n */\nexport function indexEndMarker(scope: string): string {\n return `<!-- ${INDEX_MARKER_PREFIX}:${scope}:end -->`;\n}\n","import path from \"node:path\";\nimport type { ExtractedFields, ResolvedFieldMeta } from \"../core/schema-extractor.js\";\nimport type { Example } from \"../types.js\";\nimport type {\n ArgumentsRenderContext,\n CommandInfo,\n DefaultRendererOptions,\n ExampleExecutionResult,\n ExamplesRenderContext,\n ExamplesRenderOptions,\n OptionsRenderContext,\n RenderContentOptions,\n RenderFunction,\n SectionType,\n SimpleRenderContext,\n SubCommandInfo,\n SubcommandsRenderContext,\n SubcommandsRenderOptions,\n} from \"./types.js\";\nimport { sectionEndMarker, sectionStartMarker } from \"./types.js\";\n\n/**\n * Escape markdown special characters in table cells\n */\nfunction escapeTableCell(str: string): string {\n return str.replace(/\\|/g, \"\\\\|\").replace(/\\n/g, \" \");\n}\n\n/**\n * Marker appended to a custom negation row/line so readers can see which\n * positive flag it negates (e.g. `--monochrome` → `(↔ \\`--color\\`)`).\n */\nexport function negationRelationMarker(opt: ResolvedFieldMeta): string {\n return `(↔ \\`--${opt.cliName}\\`)`;\n}\n\n/**\n * Format default value for display\n */\nfunction formatDefaultValue(value: unknown): string {\n if (value === undefined) {\n return \"-\";\n }\n return `\\`${JSON.stringify(value)}\\``;\n}\n\n/**\n * Render usage line\n */\nexport function renderUsage(info: CommandInfo): string {\n const parts: string[] = [info.fullCommandPath];\n\n if (info.options.length > 0) {\n parts.push(\"[options]\");\n }\n\n if (info.subCommands.length > 0) {\n parts.push(\"[command]\");\n }\n\n for (const arg of info.positionalArgs) {\n if (arg.required) {\n parts.push(`<${arg.name}>`);\n } else {\n parts.push(`[${arg.name}]`);\n }\n }\n\n return parts.join(\" \");\n}\n\n/**\n * Render arguments as table\n */\nexport function renderArgumentsTable(info: CommandInfo): string {\n if (info.positionalArgs.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n lines.push(\"| Argument | Description | Required |\");\n lines.push(\"|----------|-------------|----------|\");\n\n for (const arg of info.positionalArgs) {\n const desc = escapeTableCell(arg.description ?? \"\");\n const required = arg.required ? \"Yes\" : \"No\";\n lines.push(`| \\`${arg.name}\\` | ${desc} | ${required} |`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render arguments as list\n */\nexport function renderArgumentsList(info: CommandInfo): string {\n if (info.positionalArgs.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n for (const arg of info.positionalArgs) {\n const required = arg.required ? \"(required)\" : \"(optional)\";\n const desc = arg.description ? ` - ${arg.description}` : \"\";\n lines.push(`- \\`${arg.name}\\`${desc} ${required}`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Format environment variable info for display\n */\nfunction formatEnvInfo(env: string | string[] | undefined): string {\n if (!env) return \"\";\n const envNames = Array.isArray(env) ? env : [env];\n return ` [env: ${envNames.join(\", \")}]`;\n}\n\n/**\n * Resolve placeholder for an option (uses kebab-case cliName)\n */\nfunction resolvePlaceholder(opt: ResolvedFieldMeta): string {\n return opt.placeholder ?? opt.cliName.toUpperCase().replace(/-/g, \"_\");\n}\n\n/**\n * Format option name for table display (e.g., `--dry-run` or `--port <PORT>`)\n *\n * Boolean fields with a custom inline `negation` (no separate description) are\n * shown as `\\`--cache\\` / \\`--disable-cache\\``.\n */\nfunction formatOptionName(opt: ResolvedFieldMeta): string {\n const placeholder = resolvePlaceholder(opt);\n if (opt.type === \"boolean\") {\n const positive = `\\`--${opt.cliName}\\``;\n if (opt.negationDisplay && !opt.negationDescription) {\n return `${positive} / \\`--${opt.negationDisplay}\\``;\n }\n return positive;\n }\n return `\\`--${opt.cliName} <${placeholder}>\\``;\n}\n\n/**\n * Format option flags for list display (uses kebab-case cliName).\n * Aliases are joined with `, `; the inline negation (when no separate\n * `negationDescription` is set) is appended with ` / ` so it stays\n * visually distinct from aliases, matching help and table output.\n */\nfunction formatOptionFlags(opt: ResolvedFieldMeta): string {\n const placeholder = resolvePlaceholder(opt);\n const longFlag =\n opt.type === \"boolean\" ? `--${opt.cliName}` : `--${opt.cliName} <${placeholder}>`;\n\n const parts: string[] = [];\n if (opt.alias) {\n for (const a of opt.alias) {\n if (a.length === 1) parts.push(`\\`-${a}\\``);\n }\n }\n parts.push(`\\`${longFlag}\\``);\n if (opt.alias) {\n for (const a of opt.alias) {\n if (a.length > 1) parts.push(`\\`--${a}\\``);\n }\n }\n const aliasJoined = parts.join(\", \");\n if (opt.type === \"boolean\" && opt.negationDisplay && !opt.negationDescription) {\n return `${aliasJoined} / \\`--${opt.negationDisplay}\\``;\n }\n return aliasJoined;\n}\n\n/**\n * Format aliases for a markdown table cell\n */\nfunction formatAliasCell(alias: string[] | undefined): string {\n if (!alias || alias.length === 0) return \"-\";\n return alias.map((a) => `\\`${a.length === 1 ? `-${a}` : `--${a}`}\\``).join(\", \");\n}\n\n/**\n * Format env variable names for table display\n */\nfunction formatEnvNames(env: string | string[] | undefined): string {\n if (!env) return \"-\";\n if (Array.isArray(env)) {\n return env.map((e) => `\\`${e}\\``).join(\", \");\n }\n return `\\`${env}\\``;\n}\n\n/**\n * Render options as markdown table\n *\n * Features:\n * - Uses kebab-case (cliName) for option names (e.g., `--dry-run` instead of `--dryRun`)\n * - Automatically adds Env column when any option has env configured\n * - Displays multiple env vars as comma-separated list\n *\n * @example\n * | Option | Alias | Description | Required | Default | Env |\n * |--------|-------|-------------|----------|---------|-----|\n * | `--dry-run` | `-d` | Dry run mode | No | `false` | - |\n * | `--port <PORT>` | - | Server port | Yes | - | `PORT`, `SERVER_PORT` |\n */\nexport function renderOptionsTable(info: CommandInfo): string {\n if (info.options.length === 0) {\n return \"\";\n }\n\n // Check if any option has env configured\n const hasEnv = info.options.some((opt) => opt.env);\n\n const lines: string[] = [];\n if (hasEnv) {\n lines.push(\"| Option | Alias | Description | Required | Default | Env |\");\n lines.push(\"|--------|-------|-------------|----------|---------|-----|\");\n } else {\n lines.push(\"| Option | Alias | Description | Required | Default |\");\n lines.push(\"|--------|-------|-------------|----------|---------|\");\n }\n\n for (const opt of info.options) {\n const optionName = formatOptionName(opt);\n const alias = formatAliasCell(opt.alias);\n const desc = escapeTableCell(opt.description ?? \"\");\n const required = opt.required ? \"Yes\" : \"No\";\n const defaultVal = formatDefaultValue(opt.defaultValue);\n\n if (hasEnv) {\n const envNames = formatEnvNames(opt.env);\n lines.push(\n `| ${optionName} | ${alias} | ${desc} | ${required} | ${defaultVal} | ${envNames} |`,\n );\n } else {\n lines.push(`| ${optionName} | ${alias} | ${desc} | ${required} | ${defaultVal} |`);\n }\n\n // Add a separate row for the negation when a description is provided\n if (opt.type === \"boolean\" && opt.negationDisplay && opt.negationDescription) {\n const negName = `\\`--${opt.negationDisplay}\\``;\n const negDesc = `${escapeTableCell(opt.negationDescription)} ${negationRelationMarker(opt)}`;\n if (hasEnv) {\n lines.push(`| ${negName} | - | ${negDesc} | ${required} | - | - |`);\n } else {\n lines.push(`| ${negName} | - | ${negDesc} | ${required} | - |`);\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render options as markdown list\n *\n * Features:\n * - Uses kebab-case (cliName) for option names (e.g., `--dry-run` instead of `--dryRun`)\n * - Appends env info at the end of each option (e.g., `[env: PORT, SERVER_PORT]`)\n *\n * @example\n * - `-d`, `--dry-run` - Dry run mode (default: false)\n * - `--port <PORT>` - Server port (required) [env: PORT, SERVER_PORT]\n */\nexport function renderOptionsList(info: CommandInfo): string {\n if (info.options.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n for (const opt of info.options) {\n const flags = formatOptionFlags(opt);\n const desc = opt.description ? ` - ${opt.description}` : \"\";\n const required = opt.required ? \" (required)\" : \"\";\n const defaultVal =\n opt.defaultValue !== undefined ? ` (default: ${JSON.stringify(opt.defaultValue)})` : \"\";\n const envInfo = formatEnvInfo(opt.env);\n lines.push(`- ${flags}${desc}${required}${defaultVal}${envInfo}`);\n if (opt.type === \"boolean\" && opt.negationDisplay && opt.negationDescription) {\n lines.push(\n `- \\`--${opt.negationDisplay}\\` - ${opt.negationDescription} ${negationRelationMarker(opt)}`,\n );\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate anchor from command path\n */\nfunction generateAnchor(commandPath: string[]): string {\n return commandPath.join(\"-\").toLowerCase();\n}\n\n/**\n * Generate relative path from one file to another.\n * Always emits forward slashes so Markdown links remain portable across OSes.\n */\nfunction getRelativePath(from: string, to: string): string {\n const fromPosix = from.replace(/\\\\/g, \"/\");\n const toPosix = to.replace(/\\\\/g, \"/\");\n return path.posix.relative(path.posix.dirname(fromPosix), toPosix);\n}\n\n/**\n * Render subcommands as table\n */\nexport function renderSubcommandsTable(info: CommandInfo, generateAnchors = true): string {\n return renderSubcommandsTableFromArray(info.subCommands, info, generateAnchors);\n}\n\n/**\n * Render options from array as table\n */\nexport function renderOptionsTableFromArray(options: ResolvedFieldMeta[]): string {\n if (options.length === 0) {\n return \"\";\n }\n\n // Check if any option has env configured\n const hasEnv = options.some((opt) => opt.env);\n\n const lines: string[] = [];\n if (hasEnv) {\n lines.push(\"| Option | Alias | Description | Required | Default | Env |\");\n lines.push(\"|--------|-------|-------------|----------|---------|-----|\");\n } else {\n lines.push(\"| Option | Alias | Description | Required | Default |\");\n lines.push(\"|--------|-------|-------------|----------|---------|\");\n }\n\n for (const opt of options) {\n const optionName = formatOptionName(opt);\n const alias = formatAliasCell(opt.alias);\n const desc = escapeTableCell(opt.description ?? \"\");\n const required = opt.required ? \"Yes\" : \"No\";\n const defaultVal = formatDefaultValue(opt.defaultValue);\n\n if (hasEnv) {\n const envNames = formatEnvNames(opt.env);\n lines.push(\n `| ${optionName} | ${alias} | ${desc} | ${required} | ${defaultVal} | ${envNames} |`,\n );\n } else {\n lines.push(`| ${optionName} | ${alias} | ${desc} | ${required} | ${defaultVal} |`);\n }\n\n if (opt.type === \"boolean\" && opt.negationDisplay && opt.negationDescription) {\n const negName = `\\`--${opt.negationDisplay}\\``;\n const negDesc = `${escapeTableCell(opt.negationDescription)} ${negationRelationMarker(opt)}`;\n if (hasEnv) {\n lines.push(`| ${negName} | - | ${negDesc} | ${required} | - | - |`);\n } else {\n lines.push(`| ${negName} | - | ${negDesc} | ${required} | - |`);\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render union/xor options as markdown with variant grouping\n */\nexport function renderUnionOptionsMarkdown(\n extracted: ExtractedFields,\n style: \"table\" | \"list\" = \"table\",\n): string {\n const unionOptions = extracted.unionOptions ?? [];\n if (unionOptions.length === 0) return \"\";\n\n const sections: string[] = [];\n\n // Compute common fields (present in all variants)\n const allFieldNames = new Set<string>();\n for (const option of unionOptions) {\n for (const field of option.fields) {\n allFieldNames.add(field.name);\n }\n }\n const commonFieldNames = new Set<string>();\n for (const fieldName of allFieldNames) {\n if (unionOptions.every((o) => o.fields.some((f) => f.name === fieldName))) {\n commonFieldNames.add(fieldName);\n }\n }\n\n // Render common fields first\n const commonFields = extracted.fields.filter(\n (f) => commonFieldNames.has(f.name) && !f.positional,\n );\n if (commonFields.length > 0) {\n sections.push(\n style === \"table\"\n ? renderOptionsTableFromArray(commonFields)\n : renderOptionsListFromArray(commonFields),\n );\n }\n\n // Intro note\n sections.push(\"> One of the following option groups is required:\");\n\n // Render each variant\n for (let i = 0; i < unionOptions.length; i++) {\n const option = unionOptions[i];\n if (!option) continue;\n\n const uniqueFields = option.fields.filter(\n (f) => !commonFieldNames.has(f.name) && !f.positional,\n );\n\n const label = option.description ?? `Variant ${i + 1}`;\n if (uniqueFields.length === 0) {\n sections.push(`**${label}:**\\n\\n_no options_`);\n continue;\n }\n\n const rendered =\n style === \"table\"\n ? renderOptionsTableFromArray(uniqueFields)\n : renderOptionsListFromArray(uniqueFields);\n sections.push(`**${label}:**\\n\\n${rendered}`);\n }\n\n return sections.join(\"\\n\\n\");\n}\n\n/**\n * Render discriminatedUnion options as markdown with variant grouping\n */\nexport function renderDiscriminatedUnionOptionsMarkdown(\n extracted: ExtractedFields,\n style: \"table\" | \"list\" = \"table\",\n): string {\n const discriminator = extracted.discriminator;\n const variants = extracted.variants ?? [];\n if (!discriminator || variants.length === 0) return \"\";\n\n const sections: string[] = [];\n\n // Compute common fields (in all variants, excluding discriminator)\n const allFieldNames = new Set<string>();\n for (const variant of variants) {\n for (const field of variant.fields) {\n allFieldNames.add(field.name);\n }\n }\n const commonFieldNames = new Set<string>();\n for (const fieldName of allFieldNames) {\n if (fieldName === discriminator) continue;\n if (variants.every((v) => v.fields.some((f) => f.name === fieldName))) {\n commonFieldNames.add(fieldName);\n }\n }\n\n // Build discriminator field with aggregated values\n const discriminatorField = extracted.fields.find((f) => f.name === discriminator);\n const variantValues = variants.map((v) => v.discriminatorValue).join(\"\\\\|\");\n\n // Top-level table: discriminator + common fields\n const topFields: ResolvedFieldMeta[] = [];\n if (discriminatorField) {\n topFields.push({\n ...discriminatorField,\n placeholder: variantValues,\n });\n }\n for (const fieldName of commonFieldNames) {\n const field = extracted.fields.find((f) => f.name === fieldName);\n if (field && !field.positional) {\n topFields.push(field);\n }\n }\n\n if (topFields.length > 0) {\n sections.push(\n style === \"table\"\n ? renderOptionsTableFromArray(topFields)\n : renderOptionsListFromArray(topFields),\n );\n }\n\n // Render each variant's unique fields\n for (const variant of variants) {\n const uniqueFields = variant.fields.filter(\n (f) => f.name !== discriminator && !commonFieldNames.has(f.name) && !f.positional,\n );\n if (uniqueFields.length === 0) continue;\n\n const descSuffix = variant.description ? ` ${variant.description}` : \"\";\n const label = `**When \\`${discriminator}\\` = \\`${variant.discriminatorValue}\\`:**${descSuffix}`;\n const rendered =\n style === \"table\"\n ? renderOptionsTableFromArray(uniqueFields)\n : renderOptionsListFromArray(uniqueFields);\n sections.push(`${label}\\n\\n${rendered}`);\n }\n\n return sections.join(\"\\n\\n\");\n}\n\n/**\n * Render options from array as list\n */\nexport function renderOptionsListFromArray(options: ResolvedFieldMeta[]): string {\n if (options.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n for (const opt of options) {\n const flags = formatOptionFlags(opt);\n const desc = opt.description ? ` - ${opt.description}` : \"\";\n const required = opt.required ? \" (required)\" : \"\";\n const defaultVal =\n opt.defaultValue !== undefined ? ` (default: ${JSON.stringify(opt.defaultValue)})` : \"\";\n const envInfo = formatEnvInfo(opt.env);\n lines.push(`- ${flags}${desc}${required}${defaultVal}${envInfo}`);\n if (opt.type === \"boolean\" && opt.negationDisplay && opt.negationDescription) {\n lines.push(\n `- \\`--${opt.negationDisplay}\\` - ${opt.negationDescription} ${negationRelationMarker(opt)}`,\n );\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render arguments from array as table\n */\nexport function renderArgumentsTableFromArray(args: ResolvedFieldMeta[]): string {\n if (args.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n lines.push(\"| Argument | Description | Required |\");\n lines.push(\"|----------|-------------|----------|\");\n\n for (const arg of args) {\n const desc = escapeTableCell(arg.description ?? \"\");\n const required = arg.required ? \"Yes\" : \"No\";\n lines.push(`| \\`${arg.name}\\` | ${desc} | ${required} |`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render arguments from array as list\n */\nexport function renderArgumentsListFromArray(args: ResolvedFieldMeta[]): string {\n if (args.length === 0) {\n return \"\";\n }\n\n const lines: string[] = [];\n for (const arg of args) {\n const required = arg.required ? \"(required)\" : \"(optional)\";\n const desc = arg.description ? ` - ${arg.description}` : \"\";\n lines.push(`- \\`${arg.name}\\`${desc} ${required}`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render subcommands from array as table\n */\nexport function renderSubcommandsTableFromArray(\n subcommands: SubCommandInfo[],\n info: CommandInfo,\n generateAnchors = true,\n): string {\n if (subcommands.length === 0) {\n return \"\";\n }\n\n // Check if any subcommand has aliases\n const hasAliases = subcommands.some((s) => s.aliases && s.aliases.length > 0);\n\n const lines: string[] = [];\n if (hasAliases) {\n lines.push(\"| Command | Aliases | Description |\");\n lines.push(\"|---------|---------|-------------|\");\n } else {\n lines.push(\"| Command | Description |\");\n lines.push(\"|---------|-------------|\");\n }\n\n const currentFile = info.filePath;\n const fileMap = info.fileMap;\n\n for (const sub of subcommands) {\n const fullName = sub.fullPath.join(\" \");\n const desc = escapeTableCell(sub.description ?? \"\");\n const subCommandPath = sub.fullPath.join(\" \");\n const aliasCell = hasAliases\n ? sub.aliases && sub.aliases.length > 0\n ? sub.aliases.map((a) => `\\`${escapeTableCell(a)}\\``).join(\", \")\n : \"-\"\n : \"\";\n\n // Build command cell (with optional anchor link)\n let cmdCell: string;\n if (generateAnchors) {\n const anchor = generateAnchor(sub.fullPath);\n const hasSubFile =\n fileMap !== undefined && Object.prototype.hasOwnProperty.call(fileMap, subCommandPath);\n const subFile = hasSubFile ? fileMap[subCommandPath] : undefined;\n\n if (currentFile && subFile && currentFile !== subFile) {\n const relativePath = getRelativePath(currentFile, subFile);\n cmdCell = `[\\`${fullName}\\`](${relativePath}#${anchor})`;\n } else if (fileMap && !hasSubFile) {\n // A fileMap is present but this subcommand has no entry: in template mode this\n // means the child is not rendered as a heading anywhere, so a local #anchor link\n // would be dead. Render plain text instead. (Files mode populates an entry for\n // every documented command, so this branch is not reached there.)\n cmdCell = `\\`${fullName}\\``;\n } else {\n cmdCell = `[\\`${fullName}\\`](#${anchor})`;\n }\n } else {\n cmdCell = `\\`${fullName}\\``;\n }\n\n if (hasAliases) {\n lines.push(`| ${cmdCell} | ${aliasCell} | ${desc} |`);\n } else {\n lines.push(`| ${cmdCell} | ${desc} |`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render examples as markdown\n *\n * @example\n * **Basic usage**\n *\n * ```bash\n * $ greet World\n * ```\n *\n * Output:\n * ```\n * Hello, World!\n * ```\n */\nexport function renderExamplesDefault(\n examples: Example[],\n results?: ExampleExecutionResult[],\n opts?: ExamplesRenderOptions,\n): string {\n if (examples.length === 0) {\n return \"\";\n }\n\n const showOutput = opts?.showOutput ?? true;\n const prefix = opts?.commandPrefix ? `${opts.commandPrefix} ` : \"\";\n const lines: string[] = [];\n\n for (let i = 0; i < examples.length; i++) {\n const example = examples[i];\n if (!example) continue;\n\n const result = results?.[i];\n\n // Description as bold text\n lines.push(`**${example.desc}**`);\n lines.push(\"\");\n\n // Command and output in a single code block\n lines.push(\"```bash\");\n lines.push(`$ ${prefix}${example.cmd}`);\n\n // Output\n if (showOutput) {\n if (result) {\n // Use captured output from execution\n if (result.stdout) {\n lines.push(result.stdout);\n }\n if (result.stderr) {\n lines.push(`[stderr] ${result.stderr}`);\n }\n } else if (example.output) {\n // Use expected output from definition\n lines.push(example.output);\n }\n }\n\n lines.push(\"```\");\n lines.push(\"\");\n }\n\n // Remove trailing empty lines\n while (lines.length > 0 && lines[lines.length - 1] === \"\") {\n lines.pop();\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Wrap content with section markers\n */\nfunction wrapWithMarker(type: SectionType, scope: string, content: string): string {\n return `${sectionStartMarker(type, scope)}\\n${content}\\n${sectionEndMarker(type, scope)}`;\n}\n\n/**\n * Generate a \"See Global Options\" link for subcommand documentation.\n * Returns null for root command or when no global options exist.\n */\nfunction getGlobalOptionsLink(info: CommandInfo): string | null {\n if (!info.hasGlobalOptions || info.commandPath === \"\") {\n return null;\n }\n\n const isCrossFile = info.rootDocPath && info.filePath && info.filePath !== info.rootDocPath;\n const href = isCrossFile\n ? `${getRelativePath(info.filePath!, info.rootDocPath!)}#global-options`\n : \"#global-options\";\n return `See [Global Options](${href}) for options available to all commands.`;\n}\n\nexport function createCommandRenderer(options: DefaultRendererOptions = {}): RenderFunction {\n const {\n headingLevel = 1,\n optionStyle = \"table\",\n generateAnchors = true,\n includeSubcommandDetails = true,\n markerless = false,\n renderDescription: customRenderDescription,\n renderUsage: customRenderUsage,\n renderArguments: customRenderArguments,\n renderOptions: customRenderOptions,\n renderSubcommands: customRenderSubcommands,\n renderNotes: customRenderNotes,\n renderFooter: customRenderFooter,\n renderExamples: customRenderExamples,\n } = options;\n\n // When markerless, sections are emitted as plain content with no marker comments.\n const wrap = markerless\n ? (_type: SectionType, _scope: string, content: string): string => content\n : wrapWithMarker;\n\n return (info: CommandInfo): string => {\n const sections: string[] = [];\n const scope = info.commandPath;\n // Calculate effective heading level based on command depth\n // depth=1 → headingLevel, depth=2 → headingLevel+1, etc.\n const effectiveLevel = Math.min(headingLevel + (info.depth - 1), 6);\n const h = \"#\".repeat(effectiveLevel);\n\n // Title - use commandPath for subcommands, name for root\n const title = info.commandPath || info.name;\n sections.push(wrap(\"heading\", scope, `${h} ${title}`));\n\n // Description (includes aliases when present)\n {\n const parts: string[] = [];\n if (info.description) {\n parts.push(info.description);\n }\n if (info.aliases && info.aliases.length > 0) {\n parts.push(`**Aliases:** ${info.aliases.map((a) => `\\`${a}\\``).join(\", \")}`);\n }\n if (parts.length > 0) {\n const defaultContent = parts.join(\"\\n\\n\");\n const context: SimpleRenderContext = {\n content: defaultContent,\n heading: \"\",\n info,\n };\n const content = customRenderDescription\n ? customRenderDescription(context)\n : context.content;\n if (content) {\n sections.push(wrap(\"description\", scope, content));\n }\n }\n }\n\n // Usage\n {\n const defaultUsage = `**Usage**\\n\\n\\`\\`\\`\\n${renderUsage(info)}\\n\\`\\`\\``;\n const context: SimpleRenderContext = {\n content: defaultUsage,\n heading: \"**Usage**\",\n info,\n };\n const content = customRenderUsage ? customRenderUsage(context) : context.content;\n if (content) {\n sections.push(wrap(\"usage\", scope, content));\n }\n }\n\n // Arguments\n if (info.positionalArgs.length > 0) {\n const renderArgs = (args: ResolvedFieldMeta[], opts?: RenderContentOptions): string => {\n const style = opts?.style ?? optionStyle;\n const withHeading = opts?.withHeading ?? true;\n const content =\n style === \"table\"\n ? renderArgumentsTableFromArray(args)\n : renderArgumentsListFromArray(args);\n return withHeading ? `**Arguments**\\n\\n${content}` : content;\n };\n\n const context: ArgumentsRenderContext = {\n args: info.positionalArgs,\n render: renderArgs,\n heading: \"**Arguments**\",\n info,\n };\n\n const content = customRenderArguments\n ? customRenderArguments(context)\n : renderArgs(context.args);\n if (content) {\n sections.push(wrap(\"arguments\", scope, content));\n }\n }\n\n // Options\n if (info.options.length > 0) {\n const renderOpts = (opts: ResolvedFieldMeta[], renderOpts?: RenderContentOptions): string => {\n const style = renderOpts?.style ?? optionStyle;\n const withHeading = renderOpts?.withHeading ?? true;\n const extracted = info.extracted;\n\n let content: string;\n if (\n extracted &&\n (extracted.schemaType === \"union\" || extracted.schemaType === \"xor\") &&\n extracted.unionOptions\n ) {\n content = renderUnionOptionsMarkdown(extracted, style);\n } else if (\n extracted &&\n extracted.schemaType === \"discriminatedUnion\" &&\n extracted.discriminator\n ) {\n content = renderDiscriminatedUnionOptionsMarkdown(extracted, style);\n } else {\n content =\n style === \"table\"\n ? renderOptionsTableFromArray(opts)\n : renderOptionsListFromArray(opts);\n }\n return withHeading ? `**Options**\\n\\n${content}` : content;\n };\n\n const context: OptionsRenderContext = {\n options: info.options,\n render: renderOpts,\n heading: \"**Options**\",\n info,\n };\n\n const content = customRenderOptions\n ? customRenderOptions(context)\n : renderOpts(context.options);\n if (content) {\n sections.push(wrap(\"options\", scope, content));\n }\n }\n\n // Global Options link (for subcommands when global options exist)\n {\n const globalLink = getGlobalOptionsLink(info);\n if (globalLink) {\n sections.push(wrap(\"global-options-link\", scope, globalLink));\n }\n }\n\n // Subcommands\n if (info.subCommands.length > 0) {\n const effectiveAnchors = generateAnchors && includeSubcommandDetails;\n\n const renderSubs = (subs: SubCommandInfo[], opts?: SubcommandsRenderOptions): string => {\n const anchors = opts?.generateAnchors ?? effectiveAnchors;\n const withHeading = opts?.withHeading ?? true;\n const content = renderSubcommandsTableFromArray(subs, info, anchors);\n return withHeading ? `**Commands**\\n\\n${content}` : content;\n };\n\n const context: SubcommandsRenderContext = {\n subcommands: info.subCommands,\n render: renderSubs,\n heading: \"**Commands**\",\n info,\n };\n\n const content = customRenderSubcommands\n ? customRenderSubcommands(context)\n : renderSubs(context.subcommands);\n if (content) {\n sections.push(wrap(\"subcommands\", scope, content));\n }\n }\n\n // Examples\n if (info.examples && info.examples.length > 0) {\n const renderEx = (\n examples: Example[],\n results?: ExampleExecutionResult[],\n opts?: ExamplesRenderOptions,\n ): string => {\n const withHeading = opts?.withHeading ?? true;\n const mergedOpts: ExamplesRenderOptions = {\n commandPrefix: info.fullCommandPath,\n ...opts,\n };\n const content = renderExamplesDefault(examples, results, mergedOpts);\n return withHeading ? `**Examples**\\n\\n${content}` : content;\n };\n\n const context: ExamplesRenderContext = {\n examples: info.examples,\n results: info.exampleResults,\n render: renderEx,\n heading: \"**Examples**\",\n info,\n };\n\n const content = customRenderExamples\n ? customRenderExamples(context)\n : renderEx(context.examples, context.results);\n if (content) {\n sections.push(wrap(\"examples\", scope, content));\n }\n }\n\n // Notes\n if (info.notes) {\n const context: SimpleRenderContext = {\n content: `**Notes**\\n\\n${info.notes}`,\n heading: \"**Notes**\",\n info,\n };\n const content = customRenderNotes ? customRenderNotes(context) : context.content;\n if (content) {\n sections.push(wrap(\"notes\", scope, content));\n }\n }\n\n // Footer (default is empty, not wrapped with markers)\n {\n const context: SimpleRenderContext = {\n content: \"\",\n heading: \"\",\n info,\n };\n const content = customRenderFooter ? customRenderFooter(context) : context.content;\n if (content) {\n sections.push(content);\n }\n }\n\n return sections.join(\"\\n\\n\") + \"\\n\";\n };\n}\n\n/**\n * Default renderers presets\n */\nexport const defaultRenderers = {\n /** Standard command documentation */\n command: (options?: DefaultRendererOptions) => createCommandRenderer(options),\n /** Table style options (default) */\n tableStyle: createCommandRenderer({ optionStyle: \"table\" }),\n /** List style options */\n listStyle: createCommandRenderer({ optionStyle: \"list\" }),\n};\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/**\n * Comparison result\n */\nexport interface CompareResult {\n /** Whether the content matches */\n match: boolean;\n /** Diff content (only when match is false) */\n diff?: string;\n /** Whether the file exists */\n fileExists: boolean;\n}\n\n/**\n * Compare generated content with existing file\n */\nexport function compareWithExisting(generatedContent: string, filePath: string): CompareResult {\n const absolutePath = path.resolve(filePath);\n\n if (!fs.existsSync(absolutePath)) {\n return {\n match: false,\n fileExists: false,\n };\n }\n\n const existingContent = fs.readFileSync(absolutePath, \"utf-8\");\n\n if (generatedContent === existingContent) {\n return {\n match: true,\n fileExists: true,\n };\n }\n\n return {\n match: false,\n diff: formatDiff(existingContent, generatedContent),\n fileExists: true,\n };\n}\n\n/**\n * Format diff between two strings in unified diff format\n */\nexport function formatDiff(expected: string, actual: string): string {\n const expectedLines = expected.split(\"\\n\");\n const actualLines = actual.split(\"\\n\");\n\n const result: string[] = [];\n result.push(\"--- existing\");\n result.push(\"+++ generated\");\n result.push(\"\");\n\n // Simple line-by-line diff\n const maxLines = Math.max(expectedLines.length, actualLines.length);\n let inChunk = false;\n let chunkStart = 0;\n const chunk: string[] = [];\n\n const flushChunk = (): void => {\n if (chunk.length > 0) {\n result.push(`@@ -${chunkStart + 1},${chunk.length} @@`);\n result.push(...chunk);\n chunk.length = 0;\n }\n inChunk = false;\n };\n\n for (let i = 0; i < maxLines; i++) {\n const expectedLine = expectedLines[i];\n const actualLine = actualLines[i];\n\n if (expectedLine === actualLine) {\n if (inChunk) {\n // Add context line\n chunk.push(` ${expectedLine ?? \"\"}`);\n // If we have more than 3 context lines after a change, flush the chunk\n const lastChangeIndex = chunk.findIndex(\n (line, idx) =>\n (line.startsWith(\"-\") || line.startsWith(\"+\")) &&\n chunk.slice(idx + 1).every((l) => l.startsWith(\" \")),\n );\n if (lastChangeIndex !== -1 && chunk.length - lastChangeIndex > 3) {\n flushChunk();\n }\n }\n } else {\n if (!inChunk) {\n inChunk = true;\n chunkStart = i;\n // Add up to 3 lines of context before\n const contextStart = Math.max(0, i - 3);\n for (let j = contextStart; j < i; j++) {\n chunk.push(` ${expectedLines[j] ?? \"\"}`);\n }\n }\n\n if (expectedLine !== undefined && (actualLine === undefined || expectedLine !== actualLine)) {\n chunk.push(`-${expectedLine}`);\n }\n if (actualLine !== undefined && (expectedLine === undefined || expectedLine !== actualLine)) {\n chunk.push(`+${actualLine}`);\n }\n }\n }\n\n flushChunk();\n\n return result.join(\"\\n\");\n}\n\n/**\n * Write content to file, creating directories if needed\n */\nexport function writeFile(filePath: string, content: string): void {\n const absolutePath = path.resolve(filePath);\n const dir = path.dirname(absolutePath);\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n fs.writeFileSync(absolutePath, content, \"utf-8\");\n}\n\n/**\n * Read file content if it exists\n * Returns null if file does not exist\n */\nexport function readFile(filePath: string): string | null {\n const absolutePath = path.resolve(filePath);\n\n if (!fs.existsSync(absolutePath)) {\n return null;\n }\n\n return fs.readFileSync(absolutePath, \"utf-8\");\n}\n\n/**\n * Minimal fs interface for deleteFile\n */\nexport interface DeleteFileFs {\n existsSync: typeof fs.existsSync;\n unlinkSync: typeof fs.unlinkSync;\n}\n\n/**\n * Delete file if it exists\n * @param filePath - Path to the file to delete\n * @param fileSystem - Optional fs implementation (useful when fs is mocked)\n */\nexport function deleteFile(filePath: string, fileSystem: DeleteFileFs = fs): void {\n const absolutePath = path.resolve(filePath);\n\n if (fileSystem.existsSync(absolutePath)) {\n fileSystem.unlinkSync(absolutePath);\n }\n}\n","import { getExtractedFields } from \"../core/schema-extractor.js\";\nimport { resolveLazyCommand } from \"../executor/subcommand-router.js\";\nimport type { AnyCommand } from \"../types.js\";\nimport type { CommandInfo, SubCommandInfo } from \"./types.js\";\n\n/**\n * Build CommandInfo from a command\n */\nexport async function buildCommandInfo(\n command: AnyCommand,\n rootName: string,\n commandPath: string[] = [],\n): Promise<CommandInfo> {\n const extracted = getExtractedFields(command);\n\n const positionalArgs = extracted?.fields.filter((f) => f.positional) ?? [];\n const options = extracted?.fields.filter((f) => !f.positional) ?? [];\n\n const subCommands: SubCommandInfo[] = [];\n if (command.subCommands) {\n for (const [name, subCmd] of Object.entries(command.subCommands)) {\n const resolved = await resolveLazyCommand(subCmd);\n const fullPath = [...commandPath, name];\n subCommands.push({\n name,\n description: resolved.description,\n aliases: resolved.aliases,\n fullPath,\n });\n }\n }\n\n return {\n name: command.name ?? \"\",\n description: command.description,\n aliases: command.aliases,\n fullCommandPath: commandPath.length > 0 ? `${rootName} ${commandPath.join(\" \")}` : rootName,\n commandPath: commandPath.join(\" \"),\n depth: commandPath.length + 1,\n positionalArgs,\n options,\n subCommands,\n extracted,\n command,\n notes: command.notes,\n examples: command.examples,\n };\n}\n\n/**\n * Collect all commands with their paths\n * Returns a map of command path -> CommandInfo\n */\nexport async function collectAllCommands(\n command: AnyCommand,\n rootName?: string,\n): Promise<Map<string, CommandInfo>> {\n const root = rootName ?? command.name ?? \"command\";\n const result = new Map<string, CommandInfo>();\n\n async function traverse(cmd: AnyCommand, path: string[]): Promise<void> {\n const info = await buildCommandInfo(cmd, root, path);\n const pathKey = path.join(\" \");\n result.set(pathKey, info);\n\n if (cmd.subCommands) {\n for (const [name, subCmd] of Object.entries(cmd.subCommands)) {\n const resolved = await resolveLazyCommand(subCmd);\n await traverse(resolved, [...path, name]);\n }\n }\n }\n\n await traverse(command, []);\n return result;\n}\n","import { createLogCollector } from \"../executor/log-collector.js\";\nimport type { AnyCommand, Example } from \"../types.js\";\nimport type { ExampleCommandConfig, ExampleExecutionResult } from \"./types.js\";\n\n/**\n * Execute examples for a command and capture output\n *\n * @param examples - Examples to execute\n * @param config - Execution configuration (mock setup/cleanup)\n * @param rootCommand - Root command to execute against\n * @param commandPath - Command path for subcommands (e.g., [\"config\", \"get\"])\n * @returns Array of execution results with captured stdout/stderr\n */\nexport async function executeExamples(\n examples: Example[],\n config: ExampleCommandConfig,\n rootCommand: AnyCommand,\n commandPath: string[] = [],\n): Promise<ExampleExecutionResult[]> {\n const results: ExampleExecutionResult[] = [];\n\n // Setup mock if provided\n if (config.mock) {\n await config.mock();\n }\n\n try {\n for (const example of examples) {\n const result = await executeSingleExample(example, rootCommand, commandPath);\n results.push(result);\n }\n } finally {\n // Cleanup mock if provided\n if (config.cleanup) {\n await config.cleanup();\n }\n }\n\n return results;\n}\n\n/**\n * Execute a single example and capture output\n */\nasync function executeSingleExample(\n example: Example,\n rootCommand: AnyCommand,\n commandPath: string[],\n): Promise<ExampleExecutionResult> {\n // Parse command string into argv\n const exampleArgs = parseExampleCmd(example.cmd);\n\n // Build full argv: command path + example args\n const argv = [...commandPath, ...exampleArgs];\n\n // Use unified log collector (don't passthrough to console)\n const collector = createLogCollector({ passthrough: false });\n collector.start();\n\n let success = true;\n try {\n // Import runCommand dynamically to avoid circular dependency\n const { runCommand } = await import(\"../core/runner.js\");\n const result = await runCommand(rootCommand, argv);\n success = result.success;\n\n // Also capture any errors from the result\n if (!result.success && result.error) {\n console.error(result.error.message);\n }\n } catch (error) {\n success = false;\n console.error(error instanceof Error ? error.message : String(error));\n } finally {\n collector.stop();\n }\n\n // Convert entries to stdout/stderr strings\n const logs = collector.getLogs();\n const stdout = logs.entries\n .filter((e) => e.stream === \"stdout\")\n .map((e) => e.message)\n .join(\"\\n\");\n const stderr = logs.entries\n .filter((e) => e.stream === \"stderr\")\n .map((e) => e.message)\n .join(\"\\n\");\n\n return {\n cmd: example.cmd,\n desc: example.desc,\n expectedOutput: example.output,\n stdout,\n stderr,\n success,\n };\n}\n\n/**\n * Parse example command string into argv array\n * Handles quoted strings (single and double quotes)\n *\n * @example\n * parseExampleCmd('World') // ['World']\n * parseExampleCmd('--name \"John Doe\"') // ['--name', 'John Doe']\n * parseExampleCmd(\"--greeting 'Hello World'\") // ['--greeting', 'Hello World']\n */\nfunction parseExampleCmd(cmd: string): string[] {\n const args: string[] = [];\n let current = \"\";\n let inQuote = false;\n let quoteChar = \"\";\n\n for (let i = 0; i < cmd.length; i++) {\n const char = cmd[i]!;\n\n if ((char === '\"' || char === \"'\") && !inQuote) {\n inQuote = true;\n quoteChar = char;\n } else if (char === quoteChar && inQuote) {\n inQuote = false;\n quoteChar = \"\";\n } else if (char === \" \" && !inQuote) {\n if (current) {\n args.push(current);\n current = \"\";\n }\n } else {\n current += char;\n }\n }\n\n if (current) {\n args.push(current);\n }\n\n return args;\n}\n","import { z } from \"zod\";\nimport { extractFields, type ResolvedFieldMeta } from \"../core/schema-extractor.js\";\nimport { negationRelationMarker, renderOptionsTableFromArray } from \"./default-renderers.js\";\n\n/**\n * Args shape type (Record of string keys to Zod schemas)\n * This matches the typical structure of `commonArgs`, `workspaceArgs`, etc.\n */\nexport type ArgsShape = Record<string, z.ZodType>;\n\n/**\n * Options for rendering args table\n */\nexport type ArgsTableOptions = {\n /** Columns to include in the table (default: all columns) */\n columns?: (\"option\" | \"alias\" | \"description\" | \"required\" | \"default\" | \"env\")[];\n};\n\n/**\n * Extract ResolvedFieldMeta array from ArgsShape\n *\n * This converts a raw args shape (like `commonArgs`) into the\n * ResolvedFieldMeta format used by politty's rendering functions.\n */\nfunction extractArgsFields(args: ArgsShape): ResolvedFieldMeta[] {\n // Wrap in z.object to use extractFields\n const schema = z.object(args);\n const extracted = extractFields(schema);\n return extracted.fields;\n}\n\n/**\n * Render args definition as a markdown options table\n *\n * This function takes raw args definitions (like `commonArgs`) and\n * renders them as a markdown table suitable for documentation.\n *\n * @example\n * import { renderArgsTable } from \"politty/docs\";\n * import { commonArgs, workspaceArgs } from \"./args\";\n *\n * const table = renderArgsTable({\n * ...commonArgs,\n * ...workspaceArgs,\n * });\n * // | Option | Alias | Description | Default |\n * // |--------|-------|-------------|---------|\n * // | `--env-file <ENV_FILE>` | `-e` | Path to environment file | - |\n * // ...\n *\n * @param args - Args shape (Record of string keys to Zod schemas with arg() metadata)\n * @param options - Rendering options\n * @returns Rendered markdown table string\n */\nexport function renderArgsTable(args: ArgsShape, options?: ArgsTableOptions): string {\n const fields = extractArgsFields(args);\n\n // Filter to non-positional args only (options)\n const optionFields = fields.filter((f) => !f.positional);\n\n if (optionFields.length === 0) {\n return \"\";\n }\n\n // Use existing renderOptionsTableFromArray for consistency\n // Note: column filtering is not yet supported by renderOptionsTableFromArray\n // If columns option is needed, we would need to implement custom rendering\n if (options?.columns) {\n return renderFilteredTable(optionFields, options.columns);\n }\n\n return renderOptionsTableFromArray(optionFields);\n}\n\n/**\n * Escape markdown special characters in table cells\n */\nfunction escapeTableCell(str: string): string {\n return str.replace(/\\|/g, \"\\\\|\").replace(/\\n/g, \" \");\n}\n\n/**\n * Format default value for display\n */\nfunction formatDefaultValue(value: unknown): string {\n if (value === undefined) {\n return \"-\";\n }\n return `\\`${JSON.stringify(value)}\\``;\n}\n\n/**\n * Render table with filtered columns\n */\nfunction renderFilteredTable(\n options: ResolvedFieldMeta[],\n columns: (\"option\" | \"alias\" | \"description\" | \"required\" | \"default\" | \"env\")[],\n): string {\n const lines: string[] = [];\n\n // Build header\n const headerCells: string[] = [];\n const separatorCells: string[] = [];\n\n for (const col of columns) {\n switch (col) {\n case \"option\":\n headerCells.push(\"Option\");\n separatorCells.push(\"------\");\n break;\n case \"alias\":\n headerCells.push(\"Alias\");\n separatorCells.push(\"-----\");\n break;\n case \"description\":\n headerCells.push(\"Description\");\n separatorCells.push(\"-----------\");\n break;\n case \"required\":\n headerCells.push(\"Required\");\n separatorCells.push(\"--------\");\n break;\n case \"default\":\n headerCells.push(\"Default\");\n separatorCells.push(\"-------\");\n break;\n case \"env\":\n headerCells.push(\"Env\");\n separatorCells.push(\"---\");\n break;\n }\n }\n\n lines.push(`| ${headerCells.join(\" | \")} |`);\n lines.push(`| ${separatorCells.join(\" | \")} |`);\n\n // Build rows\n for (const opt of options) {\n const cells: string[] = [];\n\n for (const col of columns) {\n switch (col) {\n case \"option\": {\n const placeholder = opt.placeholder ?? opt.cliName.toUpperCase().replace(/-/g, \"_\");\n let optionName: string;\n if (opt.type === \"boolean\") {\n optionName = `\\`--${opt.cliName}\\``;\n if (opt.negationDisplay && !opt.negationDescription) {\n optionName += ` / \\`--${opt.negationDisplay}\\``;\n }\n } else {\n optionName = `\\`--${opt.cliName} <${placeholder}>\\``;\n }\n cells.push(optionName);\n break;\n }\n case \"alias\":\n cells.push(\n opt.alias && opt.alias.length > 0\n ? opt.alias.map((a) => `\\`${a.length === 1 ? `-${a}` : `--${a}`}\\``).join(\", \")\n : \"-\",\n );\n break;\n case \"description\":\n cells.push(escapeTableCell(opt.description ?? \"\"));\n break;\n case \"required\":\n cells.push(opt.required ? \"Yes\" : \"No\");\n break;\n case \"default\":\n cells.push(formatDefaultValue(opt.defaultValue));\n break;\n case \"env\": {\n const envNames = opt.env\n ? Array.isArray(opt.env)\n ? opt.env.map((e) => `\\`${e}\\``).join(\", \")\n : `\\`${opt.env}\\``\n : \"-\";\n cells.push(envNames);\n break;\n }\n }\n }\n\n lines.push(`| ${cells.join(\" | \")} |`);\n\n // Append a separate row for the negation when description is provided\n if (opt.type === \"boolean\" && opt.negationDisplay && opt.negationDescription) {\n const negCells: string[] = [];\n for (const col of columns) {\n switch (col) {\n case \"option\":\n negCells.push(`\\`--${opt.negationDisplay}\\``);\n break;\n case \"description\":\n negCells.push(\n `${escapeTableCell(opt.negationDescription)} ${negationRelationMarker(opt)}`,\n );\n break;\n case \"required\":\n negCells.push(opt.required ? \"Yes\" : \"No\");\n break;\n case \"alias\":\n case \"default\":\n case \"env\":\n negCells.push(\"-\");\n break;\n }\n }\n lines.push(`| ${negCells.join(\" | \")} |`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n","import type { AnyCommand } from \"../types.js\";\nimport { collectAllCommands } from \"./doc-generator.js\";\nimport type { CommandIndexOptions, CommandInfo } from \"./types.js\";\n\n/**\n * Escape markdown special characters in table cells\n */\nfunction escapeTableCell(str: string): string {\n return str.replace(/\\|/g, \"\\\\|\").replace(/\\n/g, \" \");\n}\n\n/**\n * Generate anchor from command path\n */\nfunction generateAnchor(commandPath: string): string {\n return commandPath.replace(/\\s+/g, \"-\").toLowerCase();\n}\n\n/**\n * Configuration for a command category\n */\nexport type CommandCategory = {\n /** Category title (e.g., \"Application Commands\") */\n title: string;\n /** Category description */\n description: string;\n /** Command paths to include (parent commands will auto-expand to leaf commands) */\n commands: string[];\n /** Optional post-expansion allowlist, used when a caller has already applied ignores */\n allowedCommands?: string[];\n /** Path to documentation file for links (e.g., \"./cli/application.md\") */\n docPath: string;\n /**\n * When true, `commands` are used verbatim as index rows without expanding\n * parent commands to their leaf subcommands. Used for template-derived\n * categories where only explicitly rendered scopes have headings.\n */\n noExpand?: boolean;\n};\n\nexport type { CommandIndexOptions };\n\n/**\n * Check if a command is a leaf (has no subcommands)\n */\nfunction isLeafCommand(info: CommandInfo): boolean {\n return info.subCommands.length === 0;\n}\n\nfunction isSubcommandOf(childPath: string, parentPath: string): boolean {\n if (childPath === parentPath) return true;\n if (parentPath === \"\") return childPath !== \"\";\n return childPath.startsWith(parentPath + \" \");\n}\n\n/**\n * Expand commands to include their subcommands\n * If a command has subcommands, recursively find all commands under it\n *\n * @param commandPaths - Command paths to expand\n * @param allCommands - Map of all available commands\n * @param leafOnly - If true, only include leaf commands; if false, include all commands\n */\nfunction expandCommands(\n commandPaths: string[],\n allCommands: Map<string, CommandInfo>,\n leafOnly: boolean,\n): string[] {\n const result: string[] = [];\n\n for (const cmdPath of commandPaths) {\n const info = allCommands.get(cmdPath);\n if (!info) continue;\n\n if (isLeafCommand(info)) {\n // Already a leaf command\n result.push(cmdPath);\n } else {\n // Find all commands under this parent\n for (const [path, pathInfo] of allCommands) {\n // Check if this is a subcommand of the current command\n const isSubcommand =\n cmdPath === \"\" ? path.length > 0 : path.startsWith(cmdPath + \" \") || path === cmdPath;\n\n if (isSubcommand) {\n // Include if it's a leaf command, or if we're including all commands\n if (isLeafCommand(pathInfo) || !leafOnly) {\n result.push(path);\n }\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Render a single category section\n */\nfunction renderCategory(\n category: CommandCategory,\n allCommands: Map<string, CommandInfo>,\n headingLevel: number,\n leafOnly: boolean,\n): string {\n const h = \"#\".repeat(headingLevel);\n const lines: string[] = [];\n\n // Category title with link\n lines.push(`${h} [${category.title}](${category.docPath})`);\n lines.push(\"\");\n\n // Category description\n lines.push(category.description);\n lines.push(\"\");\n\n // Determine which commands to include. noExpand categories (template-derived) use\n // their command list verbatim so the index lists exactly the rendered scopes;\n // otherwise parent commands expand to leaf subcommands (leafOnly controls filtering).\n const commandPaths = category.noExpand\n ? category.commands\n : expandCommands(category.commands, allCommands, leafOnly);\n let visibleCommandPaths = commandPaths;\n const fallbackCommandPaths = new Set<string>();\n if (category.allowedCommands) {\n const allowed = new Set(category.allowedCommands);\n visibleCommandPaths = commandPaths.filter((cmdPath) => allowed.has(cmdPath));\n for (const configuredPath of category.commands) {\n if (\n allowed.has(configuredPath) &&\n !visibleCommandPaths.some((cmdPath) => isSubcommandOf(cmdPath, configuredPath))\n ) {\n visibleCommandPaths.push(configuredPath);\n fallbackCommandPaths.add(configuredPath);\n }\n }\n }\n\n // Build command table\n lines.push(\"| Command | Description |\");\n lines.push(\"|---------|-------------|\");\n\n for (const cmdPath of visibleCommandPaths) {\n const info = allCommands.get(cmdPath);\n if (!info) continue;\n\n // Skip non-leaf commands if leafOnly is true (not applied to noExpand categories,\n // whose scopes are explicit and must all be listed).\n if (\n !category.noExpand &&\n leafOnly &&\n !fallbackCommandPaths.has(cmdPath) &&\n !isLeafCommand(info)\n ) {\n continue;\n }\n\n const displayName = cmdPath || info.name;\n const anchor = generateAnchor(displayName);\n const desc = escapeTableCell(info.description ?? \"\");\n\n lines.push(`| [${displayName}](${category.docPath}#${anchor}) | ${desc} |`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Render command index from categories\n *\n * Generates a category-based index of commands with links to documentation.\n *\n * @example\n * const categories: CommandCategory[] = [\n * {\n * title: \"Application Commands\",\n * description: \"Commands for managing applications.\",\n * commands: [\"init\", \"generate\", \"apply\"],\n * docPath: \"./cli/application.md\",\n * },\n * ];\n *\n * const index = await renderCommandIndex(mainCommand, categories);\n * // ### [Application Commands](./cli/application.md)\n * //\n * // Commands for managing applications.\n * //\n * // | Command | Description |\n * // |---------|-------------|\n * // | [init](./cli/application.md#init) | Initialize a project |\n * // ...\n *\n * @param command - Root command to extract command information from\n * @param categories - Category definitions for grouping commands\n * @param options - Rendering options\n * @returns Rendered markdown string\n */\nexport async function renderCommandIndex(\n command: AnyCommand,\n categories: CommandCategory[],\n options?: CommandIndexOptions,\n): Promise<string> {\n const headingLevel = options?.headingLevel ?? 3;\n const leafOnly = options?.leafOnly ?? true;\n\n // Collect all commands\n const allCommands = await collectAllCommands(command);\n\n // Render each category\n const sections: string[] = [];\n for (const category of categories) {\n const section = renderCategory(category, allCommands, headingLevel, leafOnly);\n sections.push(section);\n }\n\n return sections.join(\"\\n\\n\");\n}\n","import * as path from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { z } from \"zod\";\nimport {\n extractFields,\n type ExtractedFields,\n type ResolvedFieldMeta,\n} from \"../core/schema-extractor.js\";\nimport type { AnyCommand, ArgsSchema } from \"../types.js\";\nimport { createCommandRenderer } from \"./default-renderers.js\";\nimport {\n compareWithExisting,\n deleteFile,\n formatDiff,\n readFile,\n writeFile,\n type DeleteFileFs,\n} from \"./doc-comparator.js\";\nimport { collectAllCommands } from \"./doc-generator.js\";\nimport { executeExamples } from \"./example-executor.js\";\nimport { renderArgsTable, type ArgsShape, type ArgsTableOptions } from \"./render-args.js\";\nimport { renderCommandIndex, type CommandCategory } from \"./render-index.js\";\nimport type {\n CommandIndexOptions,\n CommandInfo,\n ExampleConfig,\n FileConfig,\n FileMapping,\n FormatterFunction,\n GenerateDocConfig,\n GenerateDocResult,\n HeadingLevel,\n PathConfig,\n RenderFunction,\n RootDocConfig,\n} from \"./types.js\";\nimport {\n DOCTOR_ENV,\n globalOptionsEndMarker,\n globalOptionsStartMarker,\n indexEndMarker,\n indexStartMarker,\n rootFooterEndMarker,\n rootFooterStartMarker,\n rootHeaderEndMarker,\n rootHeaderStartMarker,\n SECTION_TYPES,\n sectionEndMarker,\n sectionStartMarker,\n UPDATE_GOLDEN_ENV,\n type SectionType,\n} from \"./types.js\";\n\n/**\n * Apply formatter to content if provided\n * Supports both sync and async formatters\n */\nasync function applyFormatter(\n content: string,\n formatter: FormatterFunction | undefined,\n): Promise<string> {\n if (!formatter) {\n return content;\n }\n const formatted = await formatter(content);\n // Preserve trailing newline behavior of input\n if (!content.endsWith(\"\\n\") && formatted.endsWith(\"\\n\")) {\n return formatted.slice(0, -1);\n }\n return formatted;\n}\n\nfunction isTruthyEnv(envKey: string): boolean {\n const value = process.env[envKey];\n return value === \"true\" || value === \"1\";\n}\n\nfunction extractYamlFrontMatter(content: string): string | null {\n const lines = content.split(/\\r?\\n/);\n if (lines[0] !== \"---\") {\n return null;\n }\n\n const frontMatterLines: string[] = [];\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i];\n if (line === \"---\" || line === \"...\") {\n return frontMatterLines.join(\"\\n\");\n }\n frontMatterLines.push(line ?? \"\");\n }\n\n return null;\n}\n\nfunction stripPolittyFrontMatterForOutput(content: string): string {\n const lineEnding = detectLineEnding(content);\n const lines = content.split(/\\r?\\n/);\n if (lines[0] !== \"---\") {\n return content;\n }\n\n let endIndex = -1;\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i];\n if (line === \"---\" || line === \"...\") {\n endIndex = i;\n break;\n }\n }\n if (endIndex === -1) {\n return content;\n }\n\n const frontMatterLines = lines.slice(1, endIndex);\n const keptFrontMatterLines: string[] = [];\n for (let i = 0; i < frontMatterLines.length; i++) {\n const line = frontMatterLines[i] ?? \"\";\n if (!/^politty\\s*:\\s*(.*)$/.test(line)) {\n keptFrontMatterLines.push(line);\n continue;\n }\n while (i + 1 < frontMatterLines.length) {\n const nextLine = frontMatterLines[i + 1] ?? \"\";\n if (nextLine.trim() !== \"\" && !nextLine.startsWith(\" \") && !nextLine.startsWith(\"\\t\")) {\n break;\n }\n i++;\n }\n }\n\n const bodyLines = lines.slice(endIndex + 1);\n const hasKeptFrontMatter = keptFrontMatterLines.some((line) => line.trim() !== \"\");\n if (!hasKeptFrontMatter) {\n return bodyLines.join(lineEnding).replace(new RegExp(`^${lineEnding}`), \"\");\n }\n\n return [\"---\", ...keptFrontMatterLines, lines[endIndex] ?? \"---\", ...bodyLines].join(lineEnding);\n}\n\nfunction stripYamlScalarQuotes(value: string): string {\n const trimmed = value.trim();\n if (\n trimmed.length >= 2 &&\n ((trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\")))\n ) {\n return trimmed.slice(1, -1);\n }\n return trimmed;\n}\n\nfunction normalizeTemplatePlaceholderKey(value: string): string | null {\n let normalized = stripYamlScalarQuotes(value);\n if (normalized === \"\") {\n return null;\n }\n\n const fullPlaceholder = normalized.match(/^\\{\\{politty:([^{}]*)\\}\\}$/);\n if (fullPlaceholder) {\n normalized = fullPlaceholder[1] ?? \"\";\n } else if (normalized.startsWith(\"politty:\")) {\n normalized = normalized.slice(\"politty:\".length);\n }\n\n return normalized === \"\" ? null : normalized;\n}\n\nfunction templatePlaceholderKey(placeholder: string): string {\n return placeholder.slice(2, -2).slice(\"politty:\".length);\n}\n\nfunction splitFrontMatterListValue(value: string): string[] {\n const trimmed = value.trim();\n if (!trimmed.startsWith(\"[\") || !trimmed.endsWith(\"]\")) {\n return [trimmed];\n }\n return trimmed\n .slice(1, -1)\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length > 0);\n}\n\nfunction addTemplatePlaceholderExclusion(exclusions: Set<string>, value: string): void {\n const normalized = normalizeTemplatePlaceholderKey(value);\n if (normalized !== null) {\n exclusions.add(normalized);\n }\n}\n\nfunction collectExcludedTemplatePlaceholders(templateContent: string): Set<string> {\n const exclusions = new Set<string>();\n const frontMatter = extractYamlFrontMatter(templateContent);\n if (frontMatter === null) {\n return exclusions;\n }\n\n let inPolittyBlock = false;\n let inExcludeList = false;\n let excludeIndent = 0;\n for (const line of frontMatter.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n const topLevelPolitty = line.match(/^politty\\s*:\\s*(.*)$/);\n if (topLevelPolitty) {\n const value = topLevelPolitty[1]?.trim() ?? \"\";\n inPolittyBlock = value === \"\";\n inExcludeList = false;\n continue;\n }\n\n if (!line.startsWith(\" \") && !line.startsWith(\"\\t\")) {\n inPolittyBlock = false;\n inExcludeList = false;\n continue;\n }\n\n if (!inPolittyBlock) {\n continue;\n }\n\n const excludeEntry = line.match(/^(\\s+)(?:exclude|excludes)\\s*:\\s*(.*)$/);\n if (excludeEntry) {\n const value = excludeEntry[2]?.trim() ?? \"\";\n if (value === \"\") {\n inExcludeList = true;\n excludeIndent = excludeEntry[1]?.length ?? 0;\n } else {\n inExcludeList = false;\n for (const item of splitFrontMatterListValue(value)) {\n addTemplatePlaceholderExclusion(exclusions, item);\n }\n }\n continue;\n }\n\n if (!inExcludeList) {\n continue;\n }\n\n const listItem = line.match(/^(\\s*)-\\s*(.+)$/);\n if (!listItem || (listItem[1]?.length ?? 0) <= excludeIndent) {\n inExcludeList = false;\n continue;\n }\n\n addTemplatePlaceholderExclusion(exclusions, listItem[2] ?? \"\");\n }\n\n return exclusions;\n}\n\ninterface TemplateIndexMetadata {\n title?: string;\n description?: string;\n}\n\nfunction collectTemplateIndexMetadata(templateContent: string): TemplateIndexMetadata {\n const frontMatter = extractYamlFrontMatter(templateContent);\n if (frontMatter === null) {\n return {};\n }\n\n let inPolittyBlock = false;\n let inIndexBlock = false;\n let indexIndent = 0;\n const metadata: TemplateIndexMetadata = {};\n\n for (const line of frontMatter.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n const topLevelPolitty = line.match(/^politty\\s*:\\s*(.*)$/);\n if (topLevelPolitty) {\n const value = topLevelPolitty[1]?.trim() ?? \"\";\n inPolittyBlock = value === \"\";\n inIndexBlock = false;\n continue;\n }\n\n if (!line.startsWith(\" \") && !line.startsWith(\"\\t\")) {\n inPolittyBlock = false;\n inIndexBlock = false;\n continue;\n }\n\n if (!inPolittyBlock) {\n continue;\n }\n\n const indexEntry = line.match(/^(\\s+)index\\s*:\\s*(.*)$/);\n if (indexEntry) {\n const value = indexEntry[2]?.trim() ?? \"\";\n inIndexBlock = value === \"\";\n indexIndent = indexEntry[1]?.length ?? 0;\n continue;\n }\n\n if (!inIndexBlock) {\n continue;\n }\n\n const indent = line.match(/^(\\s*)/)?.[1]?.length ?? 0;\n if (indent <= indexIndent) {\n inIndexBlock = false;\n continue;\n }\n\n const property = line.match(/^\\s+(title|description)\\s*:\\s*(.+)$/);\n if (!property) {\n continue;\n }\n\n const key = property[1];\n const value = stripYamlScalarQuotes(property[2] ?? \"\");\n if (key === \"title\") {\n metadata.title = value;\n } else if (key === \"description\") {\n metadata.description = value;\n }\n }\n\n return metadata;\n}\n\ninterface TemplateExclusions {\n rawKeys: Set<string>;\n commandScopes: Set<string>;\n commandSections: Map<string, Set<SectionType>>;\n globalOptions: boolean;\n index: boolean;\n}\n\nfunction createTemplateExclusions(rawKeys: Set<string>): TemplateExclusions {\n return {\n rawKeys,\n commandScopes: new Set(),\n commandSections: new Map(),\n globalOptions: false,\n index: false,\n };\n}\n\nfunction setFileMapEntry(\n fileMap: Record<string, string>,\n commandPath: string,\n filePath: string,\n): void {\n Object.defineProperty(fileMap, commandPath, {\n value: filePath,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n}\n\n/**\n * Normalize file mapping entry to FileConfig\n */\nfunction normalizeFileConfig(config: string[] | FileConfig): FileConfig & { commands: string[] } {\n if (Array.isArray(config)) {\n return { commands: config };\n }\n if (!(\"commands\" in config) || !Array.isArray(config.commands)) {\n throw new Error(\n 'Invalid file config: object form must include a \"commands\" array. Use [] to skip generation intentionally.',\n );\n }\n return config;\n}\n\n/**\n * Check if a command path is a subcommand of another\n */\nfunction isSubcommandOf(childPath: string, parentPath: string): boolean {\n if (parentPath === \"\") return true; // Root is parent of everything\n if (childPath === parentPath) return true;\n return childPath.startsWith(parentPath + \" \");\n}\n\n/**\n * Check if a pattern contains wildcards\n */\nfunction containsWildcard(pattern: string): boolean {\n return pattern.includes(\"*\");\n}\n\n/**\n * Check if a command path matches a wildcard pattern\n * - `*` matches any single command segment\n * - Pattern segments are space-separated\n *\n * @example\n * matchesWildcard(\"config get\", \"* *\") // true\n * matchesWildcard(\"config\", \"* *\") // false\n * matchesWildcard(\"config get\", \"config *\") // true\n * matchesWildcard(\"greet\", \"*\") // true\n */\nfunction matchesWildcard(path: string, pattern: string): boolean {\n const pathSegments = path === \"\" ? [] : path.split(\" \");\n const patternSegments = pattern === \"\" ? [] : pattern.split(\" \");\n\n if (pathSegments.length !== patternSegments.length) {\n return false;\n }\n\n for (let i = 0; i < patternSegments.length; i++) {\n const patternSeg = patternSegments[i]!;\n const pathSeg = pathSegments[i]!;\n\n if (patternSeg !== \"*\" && patternSeg !== pathSeg) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Expand a wildcard pattern to matching command paths\n */\nfunction expandWildcardPattern(pattern: string, allCommands: Map<string, CommandInfo>): string[] {\n const matches: string[] = [];\n\n for (const cmdPath of allCommands.keys()) {\n if (matchesWildcard(cmdPath, pattern)) {\n matches.push(cmdPath);\n }\n }\n\n return matches;\n}\n\n/**\n * Check if a path matches any ignore pattern (with wildcard support)\n * For wildcard patterns, also ignores subcommands of matched commands\n */\nfunction matchesIgnorePattern(path: string, ignorePattern: string): boolean {\n if (containsWildcard(ignorePattern)) {\n // Check if path matches the wildcard pattern exactly\n if (matchesWildcard(path, ignorePattern)) {\n return true;\n }\n // Check if path is a subcommand of any command matching the pattern\n // e.g., \"config get\" is a subcommand of \"config\" which matches \"*\"\n const pathSegments = path === \"\" ? [] : path.split(\" \");\n const patternSegments = ignorePattern === \"\" ? [] : ignorePattern.split(\" \");\n\n // If path is deeper than pattern, check if prefix matches\n if (pathSegments.length > patternSegments.length) {\n const prefixPath = pathSegments.slice(0, patternSegments.length).join(\" \");\n return matchesWildcard(prefixPath, ignorePattern);\n }\n return false;\n }\n // For non-wildcards, use original subcommand logic\n return isSubcommandOf(path, ignorePattern);\n}\n\n/**\n * Expand command paths to include all subcommands (with wildcard support)\n */\nfunction expandCommandPaths(\n commandPaths: string[],\n allCommands: Map<string, CommandInfo>,\n): string[] {\n const expanded = new Set<string>();\n\n // Resolve wildcards to concrete command paths\n const resolved = commandPaths.flatMap((cmdPath) =>\n containsWildcard(cmdPath) ? expandWildcardPattern(cmdPath, allCommands) : [cmdPath],\n );\n\n // Add each resolved command and its subcommands\n for (const cmdPath of resolved) {\n for (const existingPath of allCommands.keys()) {\n if (isSubcommandOf(existingPath, cmdPath)) {\n expanded.add(existingPath);\n }\n }\n }\n\n return Array.from(expanded);\n}\n\n/**\n * Filter out ignored commands (with wildcard support)\n */\nfunction filterIgnoredCommands(commandPaths: string[], ignores: string[]): string[] {\n return commandPaths.filter((path) => {\n return !ignores.some((ignorePattern) => matchesIgnorePattern(path, ignorePattern));\n });\n}\n\n/**\n * Resolve wildcards to direct matches without subcommand expansion.\n * Returns the \"top-level\" commands for use in CommandCategory.commands,\n * where expandCommands in render-index handles subcommand expansion.\n */\nfunction resolveTopLevelCommands(\n specifiedCommands: string[],\n allCommands: Map<string, CommandInfo>,\n): string[] {\n const result: string[] = [];\n for (const cmdPath of specifiedCommands) {\n if (containsWildcard(cmdPath)) {\n result.push(...expandWildcardPattern(cmdPath, allCommands));\n } else if (allCommands.has(cmdPath)) {\n result.push(cmdPath);\n }\n }\n return result;\n}\n\n/**\n * Resolve file command configuration to concrete command paths.\n * This applies wildcard/subcommand expansion and ignore filtering.\n */\nfunction resolveConfiguredCommandPaths(\n fileConfigRaw: string[] | FileConfig,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): {\n fileConfig: FileConfig & { commands: string[] };\n specifiedCommands: string[];\n commandPaths: string[];\n topLevelCommands: string[];\n} {\n const fileConfig = normalizeFileConfig(fileConfigRaw);\n const specifiedCommands = fileConfig.commands;\n const expandedCommands = fileConfig.noExpand\n ? specifiedCommands.filter((p) => allCommands.has(p))\n : expandCommandPaths(specifiedCommands, allCommands);\n const commandPaths = filterIgnoredCommands(expandedCommands, ignores);\n const topLevelCommands = filterIgnoredCommands(\n resolveTopLevelCommands(specifiedCommands, allCommands),\n ignores,\n );\n\n return {\n fileConfig,\n specifiedCommands,\n commandPaths,\n topLevelCommands,\n };\n}\n\n/**\n * Validate that there are no conflicts between files and ignores (with wildcard support)\n */\nfunction validateNoConflicts(\n filesCommands: string[],\n ignores: string[],\n allCommands: Map<string, CommandInfo>,\n): void {\n const conflicts: string[] = [];\n\n for (const filePattern of filesCommands) {\n // Expand file pattern if it's a wildcard\n const filePaths = containsWildcard(filePattern)\n ? expandWildcardPattern(filePattern, allCommands)\n : [filePattern];\n\n for (const filePath of filePaths) {\n for (const ignorePattern of ignores) {\n if (containsWildcard(ignorePattern)) {\n // For wildcard ignores, check if file path matches the pattern\n if (matchesWildcard(filePath, ignorePattern)) {\n conflicts.push(`\"${filePath}\" is both in files and ignored by \"${ignorePattern}\"`);\n }\n } else {\n // For non-wildcard ignores, use original logic\n if (filePath === ignorePattern || isSubcommandOf(filePath, ignorePattern)) {\n conflicts.push(`\"${filePath}\" is both in files and ignored by \"${ignorePattern}\"`);\n }\n }\n }\n }\n }\n\n if (conflicts.length > 0) {\n throw new Error(`Conflict between files and ignores:\\n - ${conflicts.join(\"\\n - \")}`);\n }\n}\n\n/**\n * Validate that all ignored paths exist in the command tree (with wildcard support)\n */\nfunction validateIgnoresExist(ignores: string[], allCommands: Map<string, CommandInfo>): void {\n const nonExistent: string[] = [];\n\n for (const ignorePattern of ignores) {\n if (containsWildcard(ignorePattern)) {\n // For wildcard patterns, check if at least one command matches\n const matches = expandWildcardPattern(ignorePattern, allCommands);\n if (matches.length === 0) {\n nonExistent.push(`\"${ignorePattern}\"`);\n }\n } else {\n // For non-wildcard paths, check exact existence\n if (!allCommands.has(ignorePattern)) {\n nonExistent.push(`\"${ignorePattern}\"`);\n }\n }\n }\n\n if (nonExistent.length > 0) {\n throw new Error(`Ignored command paths do not exist: ${nonExistent.join(\", \")}`);\n }\n}\n\n/**\n * Sort command paths in depth-first order while preserving the specified command order\n * Parent commands are immediately followed by their subcommands\n */\nfunction sortDepthFirst(commandPaths: string[], specifiedOrder: string[]): string[] {\n // Build a set of all paths for quick lookup\n const pathSet = new Set(commandPaths);\n\n // Find top-level commands (those that match specified order or have no parent in the set)\n const topLevelPaths = specifiedOrder.filter((cmd) => pathSet.has(cmd));\n\n // Also include any commands not in specifiedOrder (for safety)\n for (const path of commandPaths) {\n const depth = path === \"\" ? 0 : path.split(\" \").length;\n if (depth === 1 && !topLevelPaths.includes(path)) {\n topLevelPaths.push(path);\n }\n }\n\n const result: string[] = [];\n const visited = new Set<string>();\n\n function addWithChildren(cmdPath: string): void {\n if (visited.has(cmdPath) || !pathSet.has(cmdPath)) return;\n visited.add(cmdPath);\n result.push(cmdPath);\n\n // Find and add direct children in alphabetical order\n const children = commandPaths\n .filter((p) => {\n if (p === cmdPath || visited.has(p)) return false;\n // Check if p is a direct child of cmdPath\n if (cmdPath === \"\") {\n return p.split(\" \").length === 1;\n }\n return p.startsWith(cmdPath + \" \") && p.split(\" \").length === cmdPath.split(\" \").length + 1;\n })\n .sort((a, b) => a.localeCompare(b));\n\n for (const child of children) {\n addWithChildren(child);\n }\n }\n\n // Start with top-level commands in specified order\n for (const topLevel of topLevelPaths) {\n addWithChildren(topLevel);\n }\n\n // Add any remaining paths (shouldn't happen normally)\n for (const path of commandPaths) {\n if (!visited.has(path)) {\n result.push(path);\n }\n }\n\n return result;\n}\n\n/**\n * Generate file header from FileConfig\n */\ntype FileHeaderConfig = Pick<FileConfig, \"title\" | \"description\"> & {\n headingLevel?: HeadingLevel;\n};\n\nfunction generateFileHeader(fileConfig: FileHeaderConfig): string | null {\n if (!fileConfig.title && !fileConfig.description) {\n return null;\n }\n\n const parts: string[] = [];\n if (fileConfig.title) {\n const heading = \"#\".repeat(fileConfig.headingLevel ?? 1);\n parts.push(`${heading} ${fileConfig.title}`);\n }\n if (fileConfig.description) {\n parts.push(\"\");\n parts.push(fileConfig.description);\n }\n parts.push(\"\");\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Extract a leading file header (title and optional description paragraph)\n */\nfunction extractFileHeader(content: string): string | null {\n if (!/^#{1,6} /.test(content)) {\n return null;\n }\n\n const titleEnd = content.indexOf(\"\\n\");\n if (titleEnd === -1) {\n return content;\n }\n\n let cursor = titleEnd + 1;\n\n // Skip an optional blank line between the title and description paragraph.\n if (content[cursor] === \"\\n\") {\n cursor += 1;\n }\n\n // Consume description paragraph lines until we hit a blank line, heading, or marker.\n while (cursor < content.length) {\n const lineEnd = content.indexOf(\"\\n\", cursor);\n const line = lineEnd === -1 ? content.slice(cursor) : content.slice(cursor, lineEnd);\n\n if (line.length === 0 || /^#{1,6}\\s/.test(line) || line.startsWith(\"<!-- politty:\")) {\n break;\n }\n\n cursor = lineEnd === -1 ? content.length : lineEnd + 1;\n }\n\n return content.slice(0, cursor);\n}\n\n/**\n * Validate and optionally update configured file header\n */\nfunction processFileHeader(\n existingContent: string,\n fileConfig: FileHeaderConfig,\n updateMode: boolean,\n): {\n content: string;\n diff?: string;\n hasError: boolean;\n wasUpdated: boolean;\n} {\n const generatedHeader = generateFileHeader(fileConfig);\n if (!generatedHeader) {\n return { content: existingContent, hasError: false, wasUpdated: false };\n }\n\n if (existingContent.startsWith(generatedHeader)) {\n return { content: existingContent, hasError: false, wasUpdated: false };\n }\n\n const existingHeader = extractFileHeader(existingContent) ?? \"\";\n\n if (!updateMode) {\n return {\n content: existingContent,\n diff: formatDiff(existingHeader, generatedHeader),\n hasError: true,\n wasUpdated: false,\n };\n }\n\n const contentWithoutHeader = existingHeader\n ? existingContent.slice(existingHeader.length)\n : existingContent;\n const normalizedBody = contentWithoutHeader.replace(/^\\n+/, \"\");\n\n return {\n content: `${generatedHeader}${normalizedBody}`,\n hasError: false,\n wasUpdated: true,\n };\n}\n\nfunction formatCommandPath(commandPath: string): string {\n return commandPath === \"\" ? \"<root>\" : commandPath;\n}\n\n/**\n * Extract a section marker's content from document content.\n * Returns the content between start and end markers (including markers).\n */\nfunction extractSectionMarker(content: string, type: SectionType, scope: string): string | null {\n const start = sectionStartMarker(type, scope);\n const end = sectionEndMarker(type, scope);\n return extractMarkerSection(content, start, end);\n}\n\n/**\n * Replace a section marker's content in document content.\n * Returns updated content, or null if marker not found.\n */\nfunction replaceSectionMarker(\n content: string,\n type: SectionType,\n scope: string,\n newContent: string,\n): string | null {\n const start = sectionStartMarker(type, scope);\n const end = sectionEndMarker(type, scope);\n return replaceMarkerSection(content, start, end, newContent);\n}\n\n/**\n * Insert a new section marker into existing content at the correct position\n * relative to other section markers for the same command, based on SECTION_TYPES order.\n * Preserves any existing content between adjacent markers by wrapping it with the new markers\n * instead of replacing it with generated content.\n * @throws If no adjacent marker is found (unreachable when at least one marker exists for the command)\n */\nfunction insertSectionMarkerAtOrder(\n content: string,\n type: SectionType,\n scope: string,\n generatedSection: string,\n): string {\n const typeIndex = SECTION_TYPES.indexOf(type);\n const startMarker = sectionStartMarker(type, scope);\n const endMarker = sectionEndMarker(type, scope);\n\n // Find the boundary: end of preceding marker and start of following marker\n let prevBoundary: number | null = null;\n for (let i = typeIndex - 1; i >= 0; i--) {\n const prevType = SECTION_TYPES[i]!;\n const prevEnd = sectionEndMarker(prevType, scope);\n const prevEndIdx = content.indexOf(prevEnd);\n if (prevEndIdx !== -1) {\n prevBoundary = prevEndIdx + prevEnd.length;\n break;\n }\n }\n\n let nextBoundary: number | null = null;\n for (let i = typeIndex + 1; i < SECTION_TYPES.length; i++) {\n const nextType = SECTION_TYPES[i]!;\n const nextStart = sectionStartMarker(nextType, scope);\n const nextStartIdx = content.indexOf(nextStart);\n if (nextStartIdx !== -1) {\n nextBoundary = nextStartIdx;\n break;\n }\n }\n\n if (prevBoundary != null && nextBoundary != null) {\n // Both boundaries found: wrap the existing content between them with markers\n // to preserve user customizations\n const between = content.slice(prevBoundary, nextBoundary);\n const innerContent = between.replace(/^\\n+/, \"\\n\").replace(/\\n+$/, \"\\n\");\n const wrapped = startMarker + innerContent + endMarker;\n return content.slice(0, prevBoundary) + \"\\n\\n\" + wrapped + \"\\n\\n\" + content.slice(nextBoundary);\n }\n\n // Only one boundary found: cannot safely determine the current command's content range\n // (wrapping could capture other commands). Insert generated content instead.\n if (prevBoundary != null) {\n let afterPos = prevBoundary;\n while (afterPos < content.length && content[afterPos] === \"\\n\") {\n afterPos++;\n }\n return (\n content.slice(0, prevBoundary) +\n \"\\n\\n\" +\n generatedSection +\n (afterPos < content.length ? \"\\n\\n\" : \"\\n\") +\n content.slice(afterPos)\n );\n }\n\n if (nextBoundary != null) {\n let beforePos = nextBoundary;\n while (beforePos > 0 && content[beforePos - 1] === \"\\n\") {\n beforePos--;\n }\n const prefix = beforePos === 0 ? \"\" : \"\\n\\n\";\n return (\n content.slice(0, beforePos) + prefix + generatedSection + \"\\n\\n\" + content.slice(nextBoundary)\n );\n }\n\n throw new Error(\n `No insertion point found for section \"${type}\" (scope=\"${scope}\"). This should be unreachable when at least one marker exists for the command.`,\n );\n}\n\n/**\n * Collect all section types that have markers for a given command path.\n */\nfunction collectSectionMarkers(content: string, commandPath: string): SectionType[] {\n const found: SectionType[] = [];\n for (const type of SECTION_TYPES) {\n if (extractSectionMarker(content, type, commandPath) !== null) {\n found.push(type);\n }\n }\n return found;\n}\n\n/**\n * Collect all command paths that have any section markers in the content.\n */\nfunction collectSectionMarkerPaths(content: string): string[] {\n // Match any section marker: <!-- politty:command:<scope>:<type>:start -->\n const sectionTypes = SECTION_TYPES.join(\"|\");\n const markerPattern = new RegExp(\n `<!--\\\\s*politty:command:(.*?):(?:${sectionTypes}):start\\\\s*-->`,\n \"g\",\n );\n const paths = new Set<string>();\n\n for (const match of content.matchAll(markerPattern)) {\n paths.add(match[1] ?? \"\");\n }\n\n return Array.from(paths);\n}\n\n/**\n * Insert command section markers at the correct position based on specified order.\n * Uses the heading marker of adjacent commands as reference points.\n */\nfunction insertCommandSections(\n content: string,\n commandPath: string,\n newSection: string,\n specifiedOrder: string[],\n): string {\n const targetIndex = specifiedOrder.indexOf(commandPath);\n if (targetIndex === -1) {\n return content.trimEnd() + \"\\n\\n\" + newSection + \"\\n\";\n }\n\n // Find the next command's heading marker in the content\n for (let i = targetIndex + 1; i < specifiedOrder.length; i++) {\n const nextCmd = specifiedOrder[i];\n if (nextCmd === undefined) continue;\n const nextMarker = sectionStartMarker(\"heading\", nextCmd);\n const nextIndex = content.indexOf(nextMarker);\n if (nextIndex !== -1) {\n let insertPos = nextIndex;\n while (insertPos > 0 && content[insertPos - 1] === \"\\n\") {\n insertPos--;\n }\n if (insertPos < nextIndex) {\n insertPos++;\n }\n return content.slice(0, insertPos) + newSection + \"\\n\" + content.slice(nextIndex);\n }\n }\n\n // Find the previous command's last marker in the content\n for (let i = targetIndex - 1; i >= 0; i--) {\n const prevCmd = specifiedOrder[i];\n if (prevCmd === undefined) continue;\n // Find the last section marker for the previous command\n const prevMarkers = collectSectionMarkers(content, prevCmd);\n if (prevMarkers.length > 0) {\n const lastType = prevMarkers[prevMarkers.length - 1]!;\n const prevEndMarker = sectionEndMarker(lastType, prevCmd);\n const prevEndIndex = content.indexOf(prevEndMarker);\n if (prevEndIndex !== -1) {\n const insertPos = prevEndIndex + prevEndMarker.length;\n return content.slice(0, insertPos) + \"\\n\" + newSection + content.slice(insertPos);\n }\n }\n }\n\n return content.trimEnd() + \"\\n\" + newSection + \"\\n\";\n}\n\n/**\n * Remove all section markers for a command from content.\n * Returns the content with all markers for the command removed and excess blank lines cleaned up.\n */\nfunction removeCommandSections(content: string, commandPath: string): string {\n const markers = collectSectionMarkers(content, commandPath);\n for (const type of markers) {\n const start = sectionStartMarker(type, commandPath);\n const end = sectionEndMarker(type, commandPath);\n let startIndex = content.indexOf(start);\n while (startIndex !== -1) {\n const endIndex = content.indexOf(end, startIndex);\n if (endIndex === -1) {\n break;\n }\n content = content.slice(0, startIndex) + content.slice(endIndex + end.length);\n startIndex = content.indexOf(start, startIndex);\n }\n }\n // Clean up excess blank lines (3+ consecutive newlines -> 2)\n content = content.replace(/\\n{3,}/g, \"\\n\\n\");\n return content;\n}\n\n/**\n * Strip politty marker lines from content, then collapse the blank-line gaps the removed markers\n * leave behind (outside fenced code blocks only, so intentional blank lines inside generated\n * example/code blocks are preserved) and trim leading/trailing blank lines.\n */\nfunction stripPolittyMarkers(content: string): string {\n const lines = content.split(\"\\n\");\n const stripped = lines.filter((line) => !/^<!-- politty:.*-->$/.test(line.trim()));\n let result = collapseBlankLinesOutsideCodeFences(stripped.join(\"\\n\"));\n result = result.replace(/^\\n+/, \"\").replace(/\\n+$/, \"\");\n return result;\n}\n\n/**\n * Collapse runs of 3+ newlines to 2, but only outside fenced code blocks so that intentional\n * blank lines inside handwritten code samples are preserved. Fences are lines whose trimmed\n * content starts with ``` or ~~~.\n */\nfunction collapseBlankLinesOutsideCodeFences(content: string): string {\n const lines = content.split(\"\\n\");\n const out: string[] = [];\n let inFence = false;\n let blankRun = 0;\n for (const line of lines) {\n const trimmed = line.trim();\n const isFence = trimmed.startsWith(\"```\") || trimmed.startsWith(\"~~~\");\n if (isFence) {\n inFence = !inFence;\n blankRun = 0;\n out.push(line);\n continue;\n }\n if (!inFence && line.trim() === \"\") {\n blankRun++;\n // Keep at most one blank line between content outside fences.\n if (blankRun >= 2) {\n continue;\n }\n } else if (!inFence) {\n blankRun = 0;\n }\n out.push(line);\n }\n return out.join(\"\\n\");\n}\n\nfunction detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n return content.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n}\n\nfunction countLineBreaks(value: string): number {\n return (value.match(/\\n/g) ?? []).length;\n}\n\n/**\n * Type guard for SectionType values parsed from template placeholders.\n */\nfunction isSectionType(value: string): value is SectionType {\n return SECTION_TYPES.some((type) => type === value);\n}\n\n/**\n * Clamp a numeric heading level to the valid HeadingLevel range (1–6).\n * Uses a switch to return a literal union member, avoiding `as` assertions.\n */\nfunction clampHeadingLevel(level: number): HeadingLevel {\n const clamped = Math.min(6, Math.max(1, Math.trunc(level)));\n switch (clamped) {\n case 1:\n return 1;\n case 2:\n return 2;\n case 3:\n return 3;\n case 4:\n return 4;\n case 5:\n return 5;\n default:\n return 6;\n }\n}\n\n/**\n * Parsed representation of a {{politty:...}} placeholder.\n * Discriminated union; `type` variants are required for unions per project style.\n */\ntype ParsedPlaceholder =\n | { kind: \"command\"; scope: string; type: SectionType | undefined }\n | { kind: \"global-options\" }\n | { kind: \"index\" }\n | { kind: \"invalid\"; reason: string };\n\n/**\n * Per-output metadata collected while validating a template.\n */\ninterface TemplateMeta {\n /** All command scopes referenced by any command placeholder (used for compatibility validation). */\n referencedScopes: string[];\n /**\n * Scopes that produce a command heading in this output, i.e. full-section placeholders\n * (`{{politty:command}}` / `{{politty:command:<scope>}}` without a type). Typed placeholders\n * like `{{politty:command:greet:usage}}` do not emit a `#greet` heading, so they are excluded.\n * Used to build cross-output links and index rows that only point at real anchors.\n */\n headingScopes: string[];\n /**\n * The command scopes at which this output roots a heading: full-tree placeholder scopes\n * (`{{politty:command}}` → `\"\"`, `{{politty:command:<scope>}}` → `<scope>`) and typed\n * `heading` placeholders (`{{politty:command:<scope>:heading}}` → `<scope>`). Used to resolve\n * cross-output links by SPECIFICITY: a scope links to the output whose nearest (longest)\n * ancestor root renders it, so a dedicated per-command page wins over a full-tree page\n * regardless of registration order.\n */\n commandTreeRoots: string[];\n /** Whether this output emits a `#global-options` anchor via `{{politty:global-options}}`. */\n emitsGlobalOptions: boolean;\n /** Whether this output renders an index from configured outputs via `{{politty:index}}`. */\n emitsIndex: boolean;\n /** Optional title for this output when included in `{{politty:index}}`. */\n indexTitle?: string;\n /** Optional description for this output when included in `{{politty:index}}`. */\n indexDescription?: string;\n}\n\nfunction resolveTemplateCommandScope(\n tokens: string[],\n allCommands: ReadonlyMap<string, CommandInfo> | undefined,\n): string | null {\n if (tokens.length === 0) {\n return allCommands === undefined || allCommands.has(\"\") ? \"\" : null;\n }\n\n const exactScope = tokens.join(\":\");\n if (allCommands?.has(exactScope)) {\n return exactScope;\n }\n\n const colonSeparatedScope = tokens.join(\" \");\n if (allCommands?.has(colonSeparatedScope)) {\n return colonSeparatedScope;\n }\n\n return allCommands === undefined ? colonSeparatedScope : null;\n}\n\nfunction templateScopeFallback(tokens: string[]): string {\n return tokens.join(\" \");\n}\n\n/**\n * Parse a single {{politty:...}} placeholder string into a discriminated structure.\n * The `placeholder` argument should be the full `{{politty:...}}` text.\n *\n * Uses String.match / String.replace internally (not .exec) to avoid lastIndex\n * state issues from the shared TEMPLATE_PLACEHOLDER_REGEX constant.\n */\nfunction parsePlaceholder(\n placeholder: string,\n allCommands?: ReadonlyMap<string, CommandInfo>,\n): ParsedPlaceholder {\n const inner = placeholder.slice(2, -2); // strip {{ and }}\n const tokens = inner.split(\":\");\n // tokens[0] === \"politty\"\n const directive = tokens[1];\n\n if (directive === \"command\") {\n // tokens after \"politty\"/\"command\" form the scope, with an OPTIONAL trailing section type.\n // The public template API separates subcommands with \":\" (e.g. config:get). Exact command\n // names that themselves contain \":\" still win when present, preserving files-mode parity.\n const rest = tokens.slice(2);\n // {{politty:command:}} — trailing colon with empty scope and no type is ambiguous with the\n // intentional root form {{politty:command}}; treat it as invalid. The typed-root form\n // {{politty:command::usage}} (scope=\"\", type=\"usage\") stays valid.\n if (rest.length === 1 && rest[0] === \"\") {\n return {\n kind: \"invalid\",\n reason: `Trailing colon in \"${placeholder}\"; use {{politty:command}} for the root command.`,\n };\n }\n\n const fullScope = resolveTemplateCommandScope(rest, allCommands);\n if (fullScope !== null) {\n return { kind: \"command\", scope: fullScope, type: undefined };\n }\n\n if (rest.length >= 2) {\n const last = rest[rest.length - 1];\n const scopeTokens = rest.slice(0, -1);\n const sectionScope = resolveTemplateCommandScope(scopeTokens, allCommands);\n if (last !== undefined && isSectionType(last)) {\n return {\n kind: \"command\",\n scope: sectionScope ?? templateScopeFallback(scopeTokens),\n type: last,\n };\n }\n if (last !== undefined && sectionScope !== null) {\n return {\n kind: \"invalid\",\n reason: `Unknown section type \"${last}\" for command scope \"${formatCommandPath(sectionScope)}\". Valid section types: ${SECTION_TYPES.join(\", \")}`,\n };\n }\n }\n return { kind: \"command\", scope: templateScopeFallback(rest), type: undefined };\n }\n\n if (directive === \"global-options\") {\n if (tokens.length !== 2) {\n return {\n kind: \"invalid\",\n reason: `Malformed placeholder \"${placeholder}\". Expected {{politty:global-options}}.`,\n };\n }\n return { kind: \"global-options\" };\n }\n\n if (directive === \"index\") {\n if (tokens.length !== 2) {\n return {\n kind: \"invalid\",\n reason: `Malformed placeholder \"${placeholder}\". Expected {{politty:index}}.`,\n };\n }\n return { kind: \"index\" };\n }\n\n return {\n kind: \"invalid\",\n reason: `Unknown politty directive \"${directive ?? \"\"}\" in \"${placeholder}\". Valid directives: command, global-options, index`,\n };\n}\n\nfunction buildTemplateExclusions(\n rawKeys: Set<string>,\n allCommands: ReadonlyMap<string, CommandInfo>,\n): TemplateExclusions {\n const exclusions = createTemplateExclusions(rawKeys);\n for (const key of rawKeys) {\n const parsed = parsePlaceholder(`{{politty:${key}}}`, allCommands);\n if (parsed.kind === \"command\") {\n if (parsed.type === undefined) {\n exclusions.commandScopes.add(parsed.scope);\n } else {\n let sections = exclusions.commandSections.get(parsed.scope);\n if (!sections) {\n sections = new Set();\n exclusions.commandSections.set(parsed.scope, sections);\n }\n sections.add(parsed.type);\n }\n } else if (parsed.kind === \"global-options\") {\n exclusions.globalOptions = true;\n } else if (parsed.kind === \"index\") {\n exclusions.index = true;\n }\n }\n return exclusions;\n}\n\nfunction isCommandScopeExcluded(\n commandPath: string,\n excludedCommandScopes: ReadonlySet<string>,\n): boolean {\n for (const excludedScope of excludedCommandScopes) {\n if (isSubcommandOf(commandPath, excludedScope)) {\n return true;\n }\n }\n return false;\n}\n\nfunction isCommandSectionExcluded(\n commandPath: string,\n sectionType: SectionType,\n exclusions: TemplateExclusions,\n): boolean {\n if (isCommandScopeExcluded(commandPath, exclusions.commandScopes)) {\n return true;\n }\n return exclusions.commandSections.get(commandPath)?.has(sectionType) ?? false;\n}\n\nfunction getTemplateCommandTreePaths(\n commandPath: string,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n exclusions: TemplateExclusions,\n): string[] {\n const expandedPaths = expandCommandPaths([commandPath], allCommands);\n const visiblePaths = filterIgnoredCommands(expandedPaths, ignores).filter(\n (path) => !isCommandScopeExcluded(path, exclusions.commandScopes),\n );\n return sortDepthFirst(visiblePaths, [commandPath]);\n}\n\nfunction shouldSkipTemplatePlaceholder(\n placeholder: string,\n parsed: ParsedPlaceholder,\n exclusions: TemplateExclusions,\n): boolean {\n if (exclusions.rawKeys.has(templatePlaceholderKey(placeholder))) {\n return true;\n }\n\n if (parsed.kind === \"command\") {\n if (isCommandScopeExcluded(parsed.scope, exclusions.commandScopes)) {\n return true;\n }\n return (\n parsed.type !== undefined &&\n (exclusions.commandSections.get(parsed.scope)?.has(parsed.type) ?? false)\n );\n }\n\n if (parsed.kind === \"global-options\") {\n return exclusions.globalOptions;\n }\n\n if (parsed.kind === \"index\") {\n return exclusions.index;\n }\n\n return false;\n}\n\nfunction isRawCommandPlaceholderUnderExcludedScope(\n key: string,\n exclusions: TemplateExclusions,\n): boolean {\n if (!key.startsWith(\"command:\")) {\n return false;\n }\n const tokens = key.slice(\"command:\".length).split(\":\");\n for (const excludedScope of exclusions.commandScopes) {\n if (excludedScope === \"\") {\n return true;\n }\n const spaceTokens = excludedScope.split(\" \");\n if (tokens.slice(0, spaceTokens.length).join(\" \") === excludedScope) {\n return true;\n }\n const colonTokens = excludedScope.split(\":\");\n if (tokens.slice(0, colonTokens.length).join(\":\") === excludedScope) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Regex matching {{politty:...}} placeholders.\n * NOTE: only use with String.match / String.replace, never with .exec in a loop,\n * because the /g flag makes the regex stateful via lastIndex.\n */\nconst TEMPLATE_PLACEHOLDER_REGEX = /\\{\\{politty:[^{}]*\\}\\}/g;\n\nfunction validateTemplatePlaceholderSyntax(templateContent: string, templatePath: string): void {\n const validPlaceholderStarts = new Set<number>();\n for (const match of templateContent.matchAll(TEMPLATE_PLACEHOLDER_REGEX)) {\n const start = match.index;\n const end = start + match[0].length;\n if (templateContent[start - 1] === \"{\" || templateContent[end] === \"}\") {\n const snippet = templateContent\n .slice(Math.max(0, start - 1), Math.min(templateContent.length, end + 1))\n .split(\"\\n\")[0];\n throw new Error(\n `Malformed politty placeholder in template \"${templatePath}\": \"${snippet}\". Expected {{politty:...}}.`,\n );\n }\n validPlaceholderStarts.add(start);\n }\n let searchIndex = 0;\n while (true) {\n const placeholderStart = templateContent.indexOf(\"{{politty:\", searchIndex);\n if (placeholderStart === -1) {\n return;\n }\n if (!validPlaceholderStarts.has(placeholderStart)) {\n const snippet = templateContent.slice(placeholderStart, placeholderStart + 80).split(\"\\n\")[0];\n throw new Error(\n `Malformed politty placeholder in template \"${templatePath}\": \"${snippet}\". Expected {{politty:...}}.`,\n );\n }\n searchIndex = placeholderStart + \"{{politty:\".length;\n }\n}\n\nfunction getUnknownSectionTypeError(\n scope: string,\n allCommands: Map<string, CommandInfo>,\n): string | null {\n const separatorIndex = scope.lastIndexOf(\":\");\n if (separatorIndex === -1) {\n return null;\n }\n\n const commandScope = scope.slice(0, separatorIndex);\n const sectionType = scope.slice(separatorIndex + 1);\n if (sectionType === \"\" || !allCommands.has(commandScope)) {\n return null;\n }\n\n return `Unknown section type \"${sectionType}\" for command scope \"${formatCommandPath(commandScope)}\". Valid section types: ${SECTION_TYPES.join(\", \")}`;\n}\n\n/**\n * Extract a marker section from content\n * Returns the content between start and end markers (including markers)\n */\nfunction extractMarkerSection(\n content: string,\n startMarker: string,\n endMarker: string,\n): string | null {\n const startIndex = content.indexOf(startMarker);\n if (startIndex === -1) {\n return null;\n }\n\n const endIndex = content.indexOf(endMarker, startIndex);\n if (endIndex === -1) {\n return null;\n }\n\n return content.slice(startIndex, endIndex + endMarker.length);\n}\n\n/**\n * Replace a marker section in content\n * Returns the updated content with the new section\n */\nfunction replaceMarkerSection(\n content: string,\n startMarker: string,\n endMarker: string,\n newSection: string,\n): string | null {\n const startIndex = content.indexOf(startMarker);\n if (startIndex === -1) {\n return null;\n }\n\n const endIndex = content.indexOf(endMarker, startIndex);\n if (endIndex === -1) {\n return null;\n }\n\n return content.slice(0, startIndex) + newSection + content.slice(endIndex + endMarker.length);\n}\n\n/**\n * Check if config is the { args, options? } shape (not shorthand ArgsShape)\n *\n * Distinguishes between:\n * - { args: ArgsShape, options?: ArgsTableOptions } → returns true\n * - ArgsShape (e.g., { verbose: ZodType, args: ZodType }) → returns false\n *\n * The key insight is that in the { args, options? } shape, config.args is an ArgsShape\n * (Record of ZodTypes), while in shorthand, config itself is the ArgsShape and config.args\n * would be a single ZodType if user has an option named \"args\".\n */\nfunction isGlobalOptionsConfigWithOptions(\n config: NonNullable<RootDocConfig[\"globalOptions\"]>,\n): config is {\n args: ArgsShape;\n options?: ArgsTableOptions;\n} {\n if (typeof config !== \"object\" || config === null || !(\"args\" in config)) {\n return false;\n }\n // If config.args is a ZodType, this is shorthand with an option named \"args\"\n // If config.args is an object (ArgsShape), this is the { args, options? } shape\n return !(config.args instanceof z.ZodType);\n}\n\n/**\n * Collect option fields that are actually rendered by global options markers.\n * Positional args are not rendered in args tables, so they must not be excluded.\n */\nfunction collectRenderableGlobalOptionFields(argsShape: ArgsShape): ResolvedFieldMeta[] {\n const extracted = extractFields(z.object(argsShape));\n return extracted.fields.filter((field) => !field.positional);\n}\n\n/**\n * Compare option definitions for global-options compatibility.\n */\nfunction areGlobalOptionsEquivalent(a: ResolvedFieldMeta, b: ResolvedFieldMeta): boolean {\n const { schema: _aSchema, ...aRest } = a;\n const { schema: _bSchema, ...bRest } = b;\n return isDeepStrictEqual(aRest, bRest);\n}\n\n/**\n * Normalize rootDoc.globalOptions to { args, options? } form.\n */\nfunction normalizeGlobalOptions(\n config: RootDocConfig[\"globalOptions\"],\n): { args: ArgsShape; options?: ArgsTableOptions } | undefined {\n if (!config) return undefined;\n return isGlobalOptionsConfigWithOptions(config) ? config : { args: config };\n}\n\n/**\n * Derive an ArgsShape from a globalArgs Zod schema, retaining only non-positional option fields.\n * Returns undefined when globalArgs is undefined or contains no option fields.\n * Used to build globalOptionDefinitions from globalArgs when rootDoc is not available.\n */\nfunction deriveGlobalArgsShape(globalArgs: ArgsSchema | undefined): ArgsShape | undefined {\n if (!globalArgs) return undefined;\n const optionFields = extractFields(globalArgs).fields.filter((f) => !f.positional);\n if (optionFields.length === 0) return undefined;\n return Object.fromEntries(optionFields.map((f) => [f.name, f.schema]));\n}\n\n/**\n * Collect global option definitions from rootDoc.\n * Global options are intentionally applied to all generated command sections.\n */\nfunction collectGlobalOptionDefinitions(\n rootDoc: RootDocConfig | undefined,\n): Map<string, ResolvedFieldMeta> {\n const globalOptions = new Map<string, ResolvedFieldMeta>();\n if (!rootDoc?.globalOptions) return globalOptions;\n\n const normalized = normalizeGlobalOptions(rootDoc.globalOptions);\n if (!normalized) return globalOptions;\n\n for (const field of collectRenderableGlobalOptionFields(normalized.args)) {\n globalOptions.set(field.name, field);\n }\n\n return globalOptions;\n}\n\n/**\n * Derive CommandCategory[] from files mapping.\n * Category title/description come from the first command in each file entry.\n */\nfunction deriveIndexFromFiles(\n files: FileMapping,\n rootDocPath: string,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): CommandCategory[] {\n const categories: CommandCategory[] = [];\n for (const [filePath, fileConfigRaw] of Object.entries(files)) {\n const { commandPaths, topLevelCommands } = resolveConfiguredCommandPaths(\n fileConfigRaw,\n allCommands,\n ignores,\n );\n if (commandPaths.length === 0) continue;\n\n const docPath = \"./\" + path.relative(path.dirname(rootDocPath), filePath).replace(/\\\\/g, \"/\");\n const firstCmdPath = commandPaths[0];\n const cmdInfo = firstCmdPath !== undefined ? allCommands.get(firstCmdPath) : undefined;\n const fileConfig = Array.isArray(fileConfigRaw) ? undefined : fileConfigRaw;\n categories.push({\n title: fileConfig?.title ?? cmdInfo?.name ?? path.basename(filePath, path.extname(filePath)),\n description: fileConfig?.description ?? cmdInfo?.description ?? \"\",\n commands: topLevelCommands,\n allowedCommands: commandPaths,\n docPath,\n });\n }\n return categories;\n}\n\n/**\n * Build index categories for the {{politty:index}} placeholder from other template outputs.\n * Each category lists exactly the heading-producing scopes of that output (noExpand), so the\n * index never links to commands that template mode did not render.\n */\nfunction deriveIndexFromTemplateOutputs(\n templateMeta: ReadonlyMap<string, TemplateMeta>,\n currentOutputPath: string,\n indexFilePath: string,\n allCommands: Map<string, CommandInfo>,\n): CommandCategory[] {\n const normalizedCurrent = normalizeDocPathForComparison(currentOutputPath);\n const categories: CommandCategory[] = [];\n for (const [outputPath, meta] of templateMeta.entries()) {\n if (normalizeDocPathForComparison(outputPath) === normalizedCurrent) continue;\n const scopes = meta.headingScopes;\n if (scopes.length === 0) continue;\n\n const docPath =\n \"./\" + path.relative(path.dirname(indexFilePath), outputPath).replace(/\\\\/g, \"/\");\n const firstScope = scopes[0];\n const cmdInfo = firstScope !== undefined ? allCommands.get(firstScope) : undefined;\n categories.push({\n title:\n meta.indexTitle ?? cmdInfo?.name ?? path.basename(outputPath, path.extname(outputPath)),\n description: meta.indexDescription ?? cmdInfo?.description ?? \"\",\n commands: scopes,\n docPath,\n noExpand: true,\n });\n }\n return categories;\n}\n\n/**\n * Collect command paths that are actually documented in configured files.\n */\nfunction collectDocumentedCommandPaths(\n files: FileMapping,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): Set<string> {\n const documentedCommandPaths = new Set<string>();\n\n for (const fileConfigRaw of Object.values(files)) {\n const { commandPaths } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);\n for (const commandPath of commandPaths) {\n documentedCommandPaths.add(commandPath);\n }\n }\n\n return documentedCommandPaths;\n}\n\n/**\n * Collect command paths that are targeted in configured files.\n */\nfunction collectTargetDocumentedCommandPaths(\n targetCommands: string[],\n files: FileMapping,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): Set<string> {\n const documentedTargetCommandPaths = new Set<string>();\n\n for (const filePath of Object.keys(files)) {\n const targetCommandsInFile = findTargetCommandsInFile(\n targetCommands,\n filePath,\n files,\n allCommands,\n ignores,\n );\n\n for (const commandPath of targetCommandsInFile) {\n documentedTargetCommandPaths.add(commandPath);\n }\n }\n\n return documentedTargetCommandPaths;\n}\n\nfunction commandPathMatchesTarget(commandPath: string, targetCommands: string[]): boolean {\n return targetCommands.some((targetCommand) => isSubcommandOf(commandPath, targetCommand));\n}\n\nfunction templateMetaReferencesCommandTarget(\n meta: TemplateMeta,\n targetCommands: string[],\n): boolean {\n return meta.referencedScopes.some((scope) => commandPathMatchesTarget(scope, targetCommands));\n}\n\nfunction templateMetaShouldProcessForTarget(meta: TemplateMeta, targetCommands: string[]): boolean {\n return (\n meta.emitsIndex ||\n meta.emitsGlobalOptions ||\n templateMetaReferencesCommandTarget(meta, targetCommands)\n );\n}\n\n/**\n * Validate that excluded command options match globalOptions definitions.\n */\nfunction validateGlobalOptionCompatibility(\n documentedCommandPaths: Iterable<string>,\n allCommands: Map<string, CommandInfo>,\n globalOptions: Map<string, ResolvedFieldMeta>,\n): void {\n if (globalOptions.size === 0) {\n return;\n }\n\n const conflicts: string[] = [];\n\n for (const commandPath of documentedCommandPaths) {\n const info = allCommands.get(commandPath);\n if (!info) {\n continue;\n }\n\n for (const option of info.options) {\n const globalOption = globalOptions.get(option.name);\n if (!globalOption) {\n continue;\n }\n\n if (!areGlobalOptionsEquivalent(globalOption, option)) {\n conflicts.push(\n `Command \"${formatCommandPath(commandPath)}\" option \"--${option.cliName}\" does not match globalOptions definition for \"${option.name}\".`,\n );\n }\n }\n }\n\n if (conflicts.length > 0) {\n throw new Error(`Invalid globalOptions configuration:\\n - ${conflicts.join(\"\\n - \")}`);\n }\n}\n\n/**\n * Build global options content (anchor + args table) without markers\n */\nfunction buildGlobalOptionsContent(config: {\n args: ArgsShape;\n options?: ArgsTableOptions;\n}): string {\n const anchor = '<a id=\"global-options\"></a>';\n const table = renderArgsTable(config.args, config.options);\n\n return [anchor, table].join(\"\\n\");\n}\n\n/**\n * Generate global options section content with markers\n */\nfunction generateGlobalOptionsSection(config: {\n args: ArgsShape;\n options?: ArgsTableOptions;\n}): string {\n return [\n globalOptionsStartMarker(),\n buildGlobalOptionsContent(config),\n globalOptionsEndMarker(),\n ].join(\"\\n\");\n}\n\n/**\n * Generate index section content with markers\n */\nasync function generateIndexSection(\n categories: CommandCategory[],\n command: AnyCommand,\n scope: string,\n options?: CommandIndexOptions,\n): Promise<string> {\n const startMarker = indexStartMarker(scope);\n const endMarker = indexEndMarker(scope);\n\n const indexContent = await renderCommandIndex(command, categories, options);\n\n return [startMarker, indexContent, endMarker].join(\"\\n\");\n}\n\n/**\n * Normalize a doc file path for equivalence checks.\n */\nfunction normalizeDocPathForComparison(filePath: string): string {\n return path.resolve(filePath);\n}\n\n/**\n * Process global options marker in file content\n * Returns result with updated content and any diffs\n */\nasync function processGlobalOptionsMarker(\n existingContent: string,\n globalOptionsConfig: { args: ArgsShape; options?: ArgsTableOptions },\n updateMode: boolean,\n formatter: FormatterFunction | undefined,\n autoInsertIfMissing?: boolean,\n): Promise<{\n content: string;\n diffs: string[];\n hasError: boolean;\n wasUpdated: boolean;\n}> {\n let content = existingContent;\n const diffs: string[] = [];\n let hasError = false;\n let wasUpdated = false;\n\n const startMarker = globalOptionsStartMarker();\n const endMarker = globalOptionsEndMarker();\n\n // Generate new section\n const rawSection = generateGlobalOptionsSection(globalOptionsConfig);\n const generatedSection = await applyFormatter(rawSection, formatter);\n\n // Extract existing section\n const existingSection = extractMarkerSection(content, startMarker, endMarker);\n\n if (!existingSection) {\n if (updateMode && autoInsertIfMissing) {\n // Auto-insert markers with generated content (generatedSection already includes markers)\n content = content.trimEnd() + \"\\n\\n\" + generatedSection + \"\\n\";\n wasUpdated = true;\n return { content, diffs, hasError, wasUpdated };\n }\n hasError = true;\n diffs.push(\n `Global options marker not found in file. Expected markers:\\n${startMarker}\\n...\\n${endMarker}`,\n );\n return { content, diffs, hasError, wasUpdated };\n }\n\n // Compare sections\n if (existingSection !== generatedSection) {\n if (updateMode) {\n const updated = replaceMarkerSection(content, startMarker, endMarker, generatedSection);\n if (updated) {\n content = updated;\n wasUpdated = true;\n } else {\n hasError = true;\n diffs.push(\"Failed to replace global options section\");\n }\n } else {\n hasError = true;\n diffs.push(formatDiff(existingSection, generatedSection));\n }\n }\n\n return { content, diffs, hasError, wasUpdated };\n}\n\n/**\n * Process a static content marker (root-header or root-footer).\n * Inserts/updates the marker section with the given content.\n */\nasync function processStaticMarker(\n existingContent: string,\n markerLabel: string,\n startMarker: string,\n endMarker: string,\n rawContent: string,\n updateMode: boolean,\n formatter: FormatterFunction | undefined,\n autoInsertIfMissing: boolean,\n): Promise<{\n content: string;\n diffs: string[];\n hasError: boolean;\n wasUpdated: boolean;\n}> {\n let content = existingContent;\n const diffs: string[] = [];\n let hasError = false;\n let wasUpdated = false;\n\n const generatedInner = await applyFormatter(rawContent, formatter);\n const generatedSection = [startMarker, generatedInner, endMarker].join(\"\\n\");\n\n const existingSection = extractMarkerSection(content, startMarker, endMarker);\n\n if (!existingSection) {\n if (updateMode && autoInsertIfMissing) {\n content = content.trimEnd() + \"\\n\\n\" + generatedSection + \"\\n\";\n wasUpdated = true;\n return { content, diffs, hasError, wasUpdated };\n }\n hasError = true;\n diffs.push(\n `${markerLabel} marker not found in file. Expected markers:\\n${startMarker}\\n...\\n${endMarker}`,\n );\n return { content, diffs, hasError, wasUpdated };\n }\n\n if (existingSection !== generatedSection) {\n if (updateMode) {\n const updated = replaceMarkerSection(content, startMarker, endMarker, generatedSection);\n if (updated) {\n content = updated;\n wasUpdated = true;\n } else {\n hasError = true;\n diffs.push(`Failed to replace ${markerLabel} section`);\n }\n } else {\n hasError = true;\n diffs.push(formatDiff(existingSection, generatedSection));\n }\n }\n\n return { content, diffs, hasError, wasUpdated };\n}\n\n/**\n * Process index marker in file content\n * Returns result with updated content and any diffs.\n * If the marker is not present in the file, the section is silently skipped.\n */\nasync function processIndexMarker(\n existingContent: string,\n categories: CommandCategory[],\n command: AnyCommand,\n scope: string,\n updateMode: boolean,\n formatter: FormatterFunction | undefined,\n indexOptions?: CommandIndexOptions,\n): Promise<{\n content: string;\n diffs: string[];\n hasError: boolean;\n wasUpdated: boolean;\n}> {\n let content = existingContent;\n const diffs: string[] = [];\n let hasError = false;\n let wasUpdated = false;\n\n const startMarker = indexStartMarker(scope);\n const endMarker = indexEndMarker(scope);\n\n const hasStartMarker = content.includes(startMarker);\n const hasEndMarker = content.includes(endMarker);\n\n // Skip silently only when marker is completely absent\n if (!hasStartMarker && !hasEndMarker) {\n return { content, diffs, hasError, wasUpdated };\n }\n\n if (!hasStartMarker || !hasEndMarker) {\n hasError = true;\n diffs.push(\"Index marker section is malformed: both start and end markers are required.\");\n return { content, diffs, hasError, wasUpdated };\n }\n\n // Extract existing section. If extraction fails despite both markers existing,\n // marker placement/order is malformed.\n const existingSection = extractMarkerSection(content, startMarker, endMarker);\n if (!existingSection) {\n hasError = true;\n diffs.push(\"Index marker section is malformed: start marker must appear before end marker.\");\n return { content, diffs, hasError, wasUpdated };\n }\n\n // Generate new section\n const rawSection = await generateIndexSection(categories, command, scope, indexOptions);\n const generatedSection = await applyFormatter(rawSection, formatter);\n\n // Compare sections\n if (existingSection !== generatedSection) {\n if (updateMode) {\n const updated = replaceMarkerSection(content, startMarker, endMarker, generatedSection);\n if (updated) {\n content = updated;\n wasUpdated = true;\n } else {\n hasError = true;\n diffs.push(\"Failed to replace index section\");\n }\n } else {\n hasError = true;\n diffs.push(formatDiff(existingSection, generatedSection));\n }\n }\n\n return { content, diffs, hasError, wasUpdated };\n}\n\n/**\n * Find which file contains a specific command\n */\nfunction findFileForCommand(\n commandPath: string,\n files: FileMapping,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): string | null {\n for (const [filePath, fileConfigRaw] of Object.entries(files)) {\n const { commandPaths } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);\n\n if (commandPaths.includes(commandPath)) {\n return filePath;\n }\n }\n return null;\n}\n\n/**\n * Find which target commands are contained in a file\n * Also expands each target command to include subcommands that are NOT explicitly in specifiedCommands\n */\nfunction findTargetCommandsInFile(\n targetCommands: string[],\n filePath: string,\n files: FileMapping,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): string[] {\n const fileConfigRaw = files[filePath];\n if (!fileConfigRaw) return [];\n\n const { specifiedCommands, commandPaths } = resolveConfiguredCommandPaths(\n fileConfigRaw,\n allCommands,\n ignores,\n );\n\n // Expand targetCommands to include their subcommands,\n // but exclude subcommands that are explicitly in specifiedCommands\n const expandedTargets = new Set<string>();\n for (const targetCmd of targetCommands) {\n if (!commandPaths.includes(targetCmd)) continue;\n\n // Add the target command itself\n expandedTargets.add(targetCmd);\n\n // Add subcommands that are NOT explicitly specified\n for (const cmdPath of commandPaths) {\n if (isSubcommandOf(cmdPath, targetCmd) && !specifiedCommands.includes(cmdPath)) {\n expandedTargets.add(cmdPath);\n }\n }\n }\n\n return Array.from(expandedTargets);\n}\n\n/**\n * Generate a single command section (already contains section markers from renderer)\n */\nfunction generateCommandSection(\n cmdPath: string,\n allCommands: Map<string, CommandInfo>,\n render: RenderFunction,\n filePath?: string,\n fileMap?: Record<string, string>,\n rootDocPath?: string,\n hasGlobalOptions?: boolean,\n ignores: readonly string[] = [],\n excludeOptionNames?: ReadonlySet<string>,\n templateExclusions?: TemplateExclusions,\n): string | null {\n const info = allCommands.get(cmdPath);\n if (!info) return null;\n if (\n templateExclusions &&\n isCommandScopeExcluded(info.commandPath, templateExclusions.commandScopes)\n ) {\n return null;\n }\n\n // Add file context to CommandInfo for cross-file link generation\n const enriched: CommandInfo = { ...info, filePath, fileMap, rootDocPath };\n if (ignores.length > 0 || (templateExclusions && templateExclusions.commandScopes.size > 0)) {\n enriched.subCommands = info.subCommands.filter((sub) => {\n const subCommandPath = sub.fullPath.join(\" \");\n if (ignores.some((pattern) => matchesIgnorePattern(subCommandPath, pattern))) {\n return false;\n }\n return !(\n templateExclusions &&\n isCommandScopeExcluded(subCommandPath, templateExclusions.commandScopes)\n );\n });\n }\n if (hasGlobalOptions !== undefined) {\n enriched.hasGlobalOptions = hasGlobalOptions;\n }\n // Non-destructively exclude options (e.g. per-template global options) without mutating\n // the shared CommandInfo in allCommands. The default renderer also reads grouped option\n // tables from `extracted` (union/discriminated-union schemas), so filter those too, otherwise\n // an excluded global option would still appear there and duplicate {{politty:global-options}}.\n if (excludeOptionNames && excludeOptionNames.size > 0) {\n enriched.options = info.options.filter((opt) => !excludeOptionNames.has(opt.name));\n if (info.extracted) {\n enriched.extracted = filterExtractedFields(info.extracted, excludeOptionNames);\n }\n }\n let rendered = render(enriched);\n if (templateExclusions) {\n for (const [scope, sectionTypes] of templateExclusions.commandSections) {\n if (scope !== info.commandPath) {\n continue;\n }\n for (const sectionType of sectionTypes) {\n const section = extractSectionMarker(rendered, sectionType, scope);\n if (section !== null) {\n rendered = rendered.replace(section, \"\");\n }\n }\n rendered = collapseBlankLinesOutsideCodeFences(rendered);\n }\n }\n return rendered;\n}\n\nfunction generateCommandTreeMarkdown(\n cmdPath: string,\n allCommands: Map<string, CommandInfo>,\n render: RenderFunction,\n ignores: string[],\n filePath: string | undefined,\n fileMap: Record<string, string> | undefined,\n rootDocPath: string | undefined,\n hasGlobalOptions: boolean | undefined,\n excludeOptionNames: ReadonlySet<string> | undefined,\n templateExclusions: TemplateExclusions,\n): string | null {\n const commandPaths = getTemplateCommandTreePaths(\n cmdPath,\n allCommands,\n ignores,\n templateExclusions,\n );\n const sections: string[] = [];\n\n for (const commandPath of commandPaths) {\n const section = generateCommandSection(\n commandPath,\n allCommands,\n render,\n filePath,\n fileMap,\n rootDocPath,\n hasGlobalOptions,\n ignores,\n excludeOptionNames,\n templateExclusions,\n );\n if (section !== null) {\n sections.push(section);\n }\n }\n\n return sections.length === 0 ? null : sections.join(\"\\n\");\n}\n\n/**\n * Return a copy of ExtractedFields with the named options removed from every field collection\n * (top-level fields, union options, and discriminated-union variants). Used to exclude global\n * options from grouped option tables rendered directly from `extracted`.\n */\nfunction filterExtractedFields(\n extracted: ExtractedFields,\n excludeOptionNames: ReadonlySet<string>,\n): ExtractedFields {\n const result: ExtractedFields = {\n ...extracted,\n fields: extracted.fields.filter((f) => !excludeOptionNames.has(f.name)),\n };\n if (extracted.unionOptions) {\n result.unionOptions = extracted.unionOptions.map((opt) =>\n filterExtractedFields(opt, excludeOptionNames),\n );\n }\n if (extracted.variants) {\n result.variants = extracted.variants.map((variant) => ({\n ...variant,\n fields: variant.fields.filter((f) => !excludeOptionNames.has(f.name)),\n }));\n }\n return result;\n}\n\n/**\n * Generate markdown for a file containing multiple commands\n * Each command section is wrapped with markers for partial validation\n */\nfunction generateFileMarkdown(\n commandPaths: string[],\n allCommands: Map<string, CommandInfo>,\n render: RenderFunction,\n filePath?: string,\n fileMap?: Record<string, string>,\n specifiedOrder?: string[],\n fileConfig?: FileConfig,\n rootDocPath?: string,\n hasGlobalOptions?: boolean,\n ignores: string[] = [],\n): string {\n const sections: string[] = [];\n\n // Add file header if title or description is provided\n const header = fileConfig ? generateFileHeader(fileConfig) : null;\n if (header) {\n sections.push(header);\n }\n\n // Sort commands depth-first while preserving specified order\n const sortedPaths = sortDepthFirst(commandPaths, specifiedOrder ?? []);\n\n for (const cmdPath of sortedPaths) {\n const section = generateCommandSection(\n cmdPath,\n allCommands,\n render,\n filePath,\n fileMap,\n rootDocPath,\n hasGlobalOptions,\n ignores,\n );\n if (section) {\n sections.push(section);\n }\n }\n\n return `${sections.join(\"\\n\")}\\n`;\n}\n\n/**\n * Build a map of command path to file path\n */\nfunction buildFileMap(\n files: FileMapping,\n allCommands: Map<string, CommandInfo>,\n ignores: string[],\n): Record<string, string> {\n const fileMap: Record<string, string> = {};\n\n for (const [filePath, fileConfigRaw] of Object.entries(files)) {\n const { commandPaths } = resolveConfiguredCommandPaths(fileConfigRaw, allCommands, ignores);\n\n for (const cmdPath of commandPaths) {\n setFileMapEntry(fileMap, cmdPath, filePath);\n }\n }\n\n return fileMap;\n}\n\n/**\n * Execute examples for commands based on configuration\n */\nasync function executeConfiguredExamples(\n allCommands: Map<string, CommandInfo>,\n examplesConfig: ExampleConfig,\n rootCommand: AnyCommand,\n): Promise<void> {\n for (const [cmdPath, cmdConfig] of Object.entries(examplesConfig)) {\n const commandInfo = allCommands.get(cmdPath);\n if (!commandInfo?.examples?.length) {\n continue;\n }\n\n // Normalize config: true means no mock setup\n const config = cmdConfig === true ? {} : cmdConfig;\n\n // Parse command path into array\n const commandPath = cmdPath ? cmdPath.split(\" \") : [];\n\n // Execute examples and store results\n const results = await executeExamples(commandInfo.examples, config, rootCommand, commandPath);\n\n // Update CommandInfo with execution results\n commandInfo.exampleResults = results;\n }\n}\n\n/**\n * Convert PathConfig to FileMapping with explicit command paths.\n * Uses noExpand to prevent subcommand expansion since paths are pre-resolved.\n */\nfunction pathToFiles(\n pathConfig: PathConfig,\n allCommands: Map<string, CommandInfo>,\n): { files: FileMapping; rootDocPath: string } {\n if (typeof pathConfig === \"string\") {\n // All commands in one file\n return {\n files: { [pathConfig]: Array.from(allCommands.keys()) },\n rootDocPath: pathConfig,\n };\n }\n\n const { root, commands = {} } = pathConfig;\n const files: FileMapping = {};\n\n // Collect commands explicitly assigned to other files.\n // Sort by specificity (most specific first) so that e.g. 'config get' -> 'get.md'\n // takes priority over 'config' -> 'config.md' for that descendant.\n const assignedToOtherFiles = new Set<string>();\n const sortedEntries = Object.entries(commands).sort(\n ([a], [b]) => b.split(\" \").length - a.split(\" \").length,\n );\n\n for (const [cmdPath, filePath] of sortedEntries) {\n if (!files[filePath]) {\n files[filePath] = { commands: [], noExpand: true };\n }\n const fc = files[filePath] as FileConfig;\n // Add the command and all its descendants, skipping already-assigned commands\n for (const existingPath of allCommands.keys()) {\n if (\n (existingPath === cmdPath || existingPath.startsWith(cmdPath + \" \")) &&\n !assignedToOtherFiles.has(existingPath)\n ) {\n fc.commands.push(existingPath);\n assignedToOtherFiles.add(existingPath);\n }\n }\n }\n\n // Remaining commands go to root file\n const rootCommands = Array.from(allCommands.keys()).filter((p) => !assignedToOtherFiles.has(p));\n files[root] = { commands: rootCommands, noExpand: true };\n\n return { files, rootDocPath: root };\n}\n\n/**\n * Generate documentation from command definition\n */\nexport async function generateDoc(config: GenerateDocConfig): Promise<GenerateDocResult> {\n const {\n command,\n ignores = [],\n format = {},\n formatter,\n examples: examplesConfig,\n targetCommands,\n globalArgs,\n customizable = false,\n } = config;\n\n // Collect all commands early (needed for PathConfig conversion)\n const allCommands = await collectAllCommands(command);\n\n // Resolve files from PathConfig or direct FileMapping\n let files: FileMapping;\n let usingPathConfig = false;\n let resolvedRootDocPath: string | undefined;\n if (config.path !== undefined) {\n if (config.files !== undefined) {\n throw new Error('Cannot specify both \"path\" and \"files\". Use one or the other.');\n }\n const converted = pathToFiles(config.path, allCommands);\n files = converted.files;\n resolvedRootDocPath = converted.rootDocPath;\n usingPathConfig = true;\n } else if (config.files !== undefined) {\n files = config.files;\n } else if (config.templates !== undefined) {\n files = {};\n } else {\n throw new Error('Either \"path\", \"files\", or \"templates\" must be specified.');\n }\n\n // Auto-derive rootDoc from PathConfig or globalArgs\n let rootDoc = config.rootDoc;\n if (!rootDoc && usingPathConfig && (globalArgs || config.rootInfo)) {\n rootDoc = { path: resolvedRootDocPath! };\n }\n\n // Auto-derive rootDoc.globalOptions from globalArgs schema if provided\n if (globalArgs && rootDoc && !rootDoc.globalOptions) {\n const optionFields = extractFields(globalArgs).fields.filter((f) => !f.positional);\n if (optionFields.length > 0) {\n const globalShape: ArgsShape = Object.fromEntries(\n optionFields.map((f) => [f.name, f.schema]),\n );\n rootDoc = { ...rootDoc, globalOptions: globalShape };\n }\n }\n const updateMode = isTruthyEnv(UPDATE_GOLDEN_ENV);\n const doctorMode = isTruthyEnv(DOCTOR_ENV);\n let hasDoctorIssues = false;\n\n // Validate rootDoc.path does not overlap with files keys (only for explicit files mode)\n if (rootDoc && !usingPathConfig) {\n const normalizedRootDocPath = normalizeDocPathForComparison(rootDoc.path);\n const hasOverlap = Object.keys(files).some(\n (filePath) => normalizeDocPathForComparison(filePath) === normalizedRootDocPath,\n );\n if (hasOverlap) {\n throw new Error(`rootDoc.path \"${rootDoc.path}\" must not also appear as a key in files.`);\n }\n }\n\n // Execute examples for all commands specified in examplesConfig\n if (examplesConfig) {\n await executeConfiguredExamples(allCommands, examplesConfig, command);\n }\n\n const hasTargetCommands = targetCommands !== undefined && targetCommands.length > 0;\n\n // Collect global option definitions and the initial set of documented command paths (files only).\n // Template scopes will be added after template validation below, before the single\n // validateGlobalOptionCompatibility call and before the mutation that strips global options.\n const globalOptionDefinitions = collectGlobalOptionDefinitions(rootDoc);\n\n // Global option definitions used to exclude options from command tables WITHIN template\n // outputs that emit a #global-options anchor. Sourced from rootDoc.globalOptions or globalArgs.\n // Unlike globalOptionDefinitions (which drives the destructive global strip for files/rootDoc),\n // these are applied per-output during template generation so plain files outputs are unaffected.\n const templateGlobalOptionFields = new Map<string, ResolvedFieldMeta>();\n if (config.templates) {\n if (globalOptionDefinitions.size > 0) {\n for (const [name, field] of globalOptionDefinitions) {\n templateGlobalOptionFields.set(name, field);\n }\n } else {\n const shape = deriveGlobalArgsShape(globalArgs);\n if (shape) {\n for (const field of collectRenderableGlobalOptionFields(shape)) {\n templateGlobalOptionFields.set(field.name, field);\n }\n }\n }\n }\n\n const documentedCommandPaths = hasTargetCommands\n ? collectTargetDocumentedCommandPaths(targetCommands, files, allCommands, ignores)\n : collectDocumentedCommandPaths(files, allCommands, ignores);\n\n // Collect all explicitly specified commands from files\n const allFilesCommands: string[] = [];\n for (const fileConfigRaw of Object.values(files)) {\n const fileConfig = normalizeFileConfig(fileConfigRaw);\n allFilesCommands.push(...fileConfig.commands);\n }\n\n // Validate ignores refer to existing commands\n validateIgnoresExist(ignores, allCommands);\n\n // Validate no conflicts between files and ignores\n validateNoConflicts(allFilesCommands, ignores, allCommands);\n\n // Build file map for cross-file links\n const fileMap = buildFileMap(files, allCommands, ignores);\n const templateContents = new Map<string, string | null>();\n const templateExclusions = new Map<string, TemplateExclusions>();\n if (config.templates) {\n for (const [outputPath, templatePath] of Object.entries(config.templates)) {\n const templateContent = readFile(templatePath);\n templateContents.set(outputPath, templateContent);\n if (templateContent !== null) {\n templateExclusions.set(\n outputPath,\n buildTemplateExclusions(\n collectExcludedTemplatePlaceholders(templateContent),\n allCommands,\n ),\n );\n }\n }\n }\n const templateEntries = Object.entries(config.templates ?? {});\n\n // === Template scope collection (validation pass) ===\n // Parse all templates early — before the files loop — so that template-referenced command scopes\n // can be included in validateGlobalOptionCompatibility and the global-option strip that follow.\n // This ensures a command referenced ONLY via a template is validated against its original\n // (pre-strip) options, closing the vacuous-validation window.\n const templateMeta = new Map<string, TemplateMeta>(); // outputPath -> metadata\n const templateValidationErrors = new Map<string, string[]>();\n\n if (templateEntries.length > 0) {\n // Upfront validation: path collisions\n const normalizedRootDocPath = rootDoc ? normalizeDocPathForComparison(rootDoc.path) : null;\n const normalizedFileKeys = new Set(Object.keys(files).map(normalizeDocPathForComparison));\n const normalizedTemplateOutputs = new Set<string>();\n\n // Pre-collect all template output paths so source-vs-output checks can see\n // outputs declared later in the same loop iteration.\n const allNormalizedTemplateOutputs = new Set(\n templateEntries.map(([outputPath]) => normalizeDocPathForComparison(outputPath)),\n );\n\n for (const [outputPath, templatePath] of templateEntries) {\n const normalizedOutput = normalizeDocPathForComparison(outputPath);\n const normalizedSource = normalizeDocPathForComparison(templatePath);\n\n if (normalizedFileKeys.has(normalizedOutput)) {\n throw new Error(\n `Template output path \"${outputPath}\" conflicts with an existing files key.`,\n );\n }\n if (normalizedRootDocPath && normalizedOutput === normalizedRootDocPath) {\n throw new Error(\n `Template output path \"${outputPath}\" conflicts with rootDoc.path \"${rootDoc!.path}\".`,\n );\n }\n if (normalizedTemplateOutputs.has(normalizedOutput)) {\n throw new Error(`Duplicate template output path: \"${outputPath}\".`);\n }\n normalizedTemplateOutputs.add(normalizedOutput);\n\n if (normalizedSource === normalizedOutput) {\n throw new Error(\n `Template output path \"${outputPath}\" must not be the same as its source template path.`,\n );\n }\n\n // Check template SOURCE path against output sets to prevent read-after-write corruption.\n if (normalizedFileKeys.has(normalizedSource)) {\n throw new Error(\n `Template source path \"${templatePath}\" conflicts with a files output key.`,\n );\n }\n if (normalizedRootDocPath && normalizedSource === normalizedRootDocPath) {\n throw new Error(\n `Template source path \"${templatePath}\" conflicts with rootDoc.path \"${rootDoc!.path}\".`,\n );\n }\n if (allNormalizedTemplateOutputs.has(normalizedSource)) {\n throw new Error(\n `Template source path \"${templatePath}\" conflicts with a template output path.`,\n );\n }\n }\n\n // Parse templates to collect referencedScopes\n const availableCommandPaths = Array.from(allCommands.keys()).join(\", \");\n\n for (const [outputPath, templatePath] of templateEntries) {\n const templateContent = templateContents.get(outputPath) ?? null;\n const validationErrors: string[] = [];\n if (templateContent === null) {\n // Will be handled in generation loop\n templateMeta.set(outputPath, {\n referencedScopes: [],\n headingScopes: [],\n commandTreeRoots: [],\n emitsGlobalOptions: false,\n emitsIndex: false,\n });\n templateValidationErrors.set(outputPath, validationErrors);\n continue;\n }\n try {\n validateTemplatePlaceholderSyntax(templateContent, templatePath);\n } catch (error) {\n validationErrors.push(error instanceof Error ? error.message : String(error));\n }\n\n const placeholders = Array.from(\n new Set(templateContent.match(TEMPLATE_PLACEHOLDER_REGEX) ?? []),\n );\n const scopes = new Set<string>();\n const headingScopes = new Set<string>();\n const commandTreeRoots = new Set<string>();\n let emitsGlobalOptions = false;\n let emitsIndex = false;\n const exclusions = templateExclusions.get(outputPath) ?? createTemplateExclusions(new Set());\n const indexMetadata = collectTemplateIndexMetadata(templateContent);\n\n for (const placeholder of placeholders) {\n const placeholderKey = templatePlaceholderKey(placeholder);\n if (\n exclusions.rawKeys.has(placeholderKey) ||\n isRawCommandPlaceholderUnderExcludedScope(placeholderKey, exclusions)\n ) {\n continue;\n }\n\n const parsed = parsePlaceholder(placeholder, allCommands);\n if (shouldSkipTemplatePlaceholder(placeholder, parsed, exclusions)) {\n continue;\n }\n\n if (parsed.kind === \"invalid\") {\n validationErrors.push(`${parsed.reason} (in template \"${templatePath}\")`);\n continue;\n }\n\n if (parsed.kind === \"command\") {\n const { scope, type } = parsed;\n\n if (!allCommands.has(scope)) {\n const sectionTypeError = getUnknownSectionTypeError(scope, allCommands);\n if (sectionTypeError) {\n validationErrors.push(`${sectionTypeError} (in template \"${templatePath}\")`);\n continue;\n }\n validationErrors.push(\n `Unknown command scope \"${scope}\" in template \"${templatePath}\". Available: ${availableCommandPaths}`,\n );\n continue;\n }\n // Validate scope not in ignores\n if (ignores.some((pattern) => matchesIgnorePattern(scope, pattern))) {\n validationErrors.push(\n `Command scope \"${scope}\" in template \"${templatePath}\" conflicts with ignores configuration.`,\n );\n continue;\n }\n if (type === undefined) {\n const commandTreePaths = getTemplateCommandTreePaths(\n scope,\n allCommands,\n ignores,\n exclusions,\n );\n // The placeholder scope is the root of this rendered tree (used for link specificity).\n if (!isCommandSectionExcluded(scope, \"heading\", exclusions)) {\n commandTreeRoots.add(scope);\n }\n for (const commandTreePath of commandTreePaths) {\n scopes.add(commandTreePath);\n if (!isCommandSectionExcluded(commandTreePath, \"heading\", exclusions)) {\n headingScopes.add(commandTreePath);\n }\n }\n } else {\n // Section type is already constrained to a valid SectionType by parsePlaceholder.\n scopes.add(scope);\n // A scope produces a #anchor heading only via the explicit \"heading\" section.\n // Other typed placeholders (usage, options, …) emit no heading, so they must not\n // feed cross-output links or index rows.\n if (type === \"heading\" && !isCommandSectionExcluded(scope, \"heading\", exclusions)) {\n headingScopes.add(scope);\n // A typed heading renders exactly this scope's heading: it is its own (maximally\n // specific) root for link resolution.\n commandTreeRoots.add(scope);\n }\n }\n } else if (parsed.kind === \"global-options\") {\n emitsGlobalOptions = true;\n } else if (parsed.kind === \"index\") {\n emitsIndex = true;\n }\n }\n\n // Check if global-options is used but not configured\n if (emitsGlobalOptions) {\n const hasGlobalOptionsConfig =\n !!rootDoc?.globalOptions || deriveGlobalArgsShape(globalArgs) !== undefined;\n if (!hasGlobalOptionsConfig) {\n validationErrors.push(\n `Template \"${templatePath}\" uses {{politty:global-options}} but no global options are configured (neither rootDoc.globalOptions nor globalArgs with non-positional options).`,\n );\n }\n }\n\n templateMeta.set(outputPath, {\n referencedScopes: Array.from(scopes),\n headingScopes: Array.from(headingScopes),\n commandTreeRoots: Array.from(commandTreeRoots),\n emitsGlobalOptions,\n emitsIndex,\n ...(indexMetadata.title !== undefined ? { indexTitle: indexMetadata.title } : {}),\n ...(indexMetadata.description !== undefined\n ? { indexDescription: indexMetadata.description }\n : {}),\n });\n templateValidationErrors.set(outputPath, validationErrors);\n }\n\n // Extend documentedCommandPaths with template scopes so the single\n // validateGlobalOptionCompatibility call below covers template-only commands too.\n for (const meta of templateMeta.values()) {\n if (hasTargetCommands && !templateMetaShouldProcessForTarget(meta, targetCommands)) {\n continue;\n }\n for (const scope of meta.referencedScopes) {\n documentedCommandPaths.add(scope);\n }\n }\n }\n\n if (hasTargetCommands) {\n for (const targetCommand of targetCommands) {\n const targetFilePath = findFileForCommand(targetCommand, files, allCommands, ignores);\n const targetTemplatePath = Array.from(templateMeta.values()).some((meta) =>\n templateMetaReferencesCommandTarget(meta, [targetCommand]),\n );\n if (!targetFilePath && !targetTemplatePath) {\n throw new Error(\n `Target command \"${targetCommand}\" not found in any file or template configuration`,\n );\n }\n }\n }\n\n const activeTemplateMeta =\n hasTargetCommands && config.templates\n ? new Map(\n Array.from(templateMeta.entries()).filter(([, meta]) =>\n templateMetaShouldProcessForTarget(meta, targetCommands),\n ),\n )\n : templateMeta;\n\n for (const [outputPath, validationErrors] of templateValidationErrors.entries()) {\n if (validationErrors.length > 0 && activeTemplateMeta.has(outputPath)) {\n throw new Error(validationErrors.join(\"\\n\"));\n }\n }\n\n const templateGlobalOptionsProviderPaths = Array.from(templateMeta.entries())\n .filter(([, meta]) => meta.emitsGlobalOptions)\n .map(([outputPath]) => outputPath);\n const templateGlobalOptionsProviderPath =\n templateGlobalOptionsProviderPaths.length === 1\n ? templateGlobalOptionsProviderPaths[0]\n : undefined;\n\n // Validate global option compatibility across ALL documented commands (files + template scopes),\n // then strip global options from command option tables. Both steps must happen before the files\n // loop and the template generation loop so that generated sections use the stripped options.\n validateGlobalOptionCompatibility(documentedCommandPaths, allCommands, globalOptionDefinitions);\n // When global options come only from globalArgs (no rootDoc), the destructive strip below does\n // not run, so validate them separately — but ONLY for scopes in templates that actually emit a\n // reachable global-options anchor (where options will be excluded). With a single template\n // provider, every template output can link to that provider.\n if (globalOptionDefinitions.size === 0 && templateGlobalOptionFields.size > 0) {\n const emittingTemplateScopes = new Set<string>();\n for (const meta of activeTemplateMeta.values()) {\n if (!meta.emitsGlobalOptions && templateGlobalOptionsProviderPath === undefined) {\n continue;\n }\n for (const scope of meta.referencedScopes) {\n emittingTemplateScopes.add(scope);\n }\n }\n validateGlobalOptionCompatibility(\n emittingTemplateScopes,\n allCommands,\n templateGlobalOptionFields,\n );\n }\n if (globalOptionDefinitions.size > 0) {\n for (const info of allCommands.values()) {\n info.options = info.options.filter((opt) => !globalOptionDefinitions.has(opt.name));\n if (info.extracted) {\n info.extracted = filterExtractedFields(\n info.extracted,\n new Set(globalOptionDefinitions.keys()),\n );\n }\n }\n }\n\n // Link map covering both files outputs and template-output headings, so a command rendered in\n // one place can link to its heading rendered in another (in either direction). Only scopes that\n // actually produce a heading in a template output are added. A files output (already in fileMap)\n // takes precedence over template outputs; among template outputs, the most SPECIFIC renderer of\n // a scope wins (see below), giving a stable, order-independent link target.\n const templateFileMap: Record<string, string> = {};\n for (const [scope, outputPath] of Object.entries(fileMap)) {\n setFileMapEntry(templateFileMap, scope, outputPath);\n }\n // Resolve each template-rendered scope to the output that renders it most specifically: the\n // output whose nearest (longest) command-tree root is an ancestor-or-equal of the scope wins.\n // This makes a dedicated per-command page (`{{politty:command:module}}`) own `module` and its\n // descendants over a full-tree page (`{{politty:command}}`), independent of registration order.\n // Files outputs (already in fileMap) always take precedence; ties fall back to first registration.\n const scopeRootLength = (root: string): number => (root === \"\" ? 0 : root.split(\" \").length);\n const templateOwners = new Map<string, { outputPath: string; rootLen: number }>();\n for (const [templateOutputPath, meta] of templateMeta.entries()) {\n for (const scope of meta.headingScopes) {\n if (Object.prototype.hasOwnProperty.call(fileMap, scope)) {\n continue;\n }\n let bestRootLen = -1;\n for (const root of meta.commandTreeRoots) {\n if (isSubcommandOf(scope, root)) {\n bestRootLen = Math.max(bestRootLen, scopeRootLength(root));\n }\n }\n if (bestRootLen < 0) {\n continue;\n }\n const existing = templateOwners.get(scope);\n if (!existing || bestRootLen > existing.rootLen) {\n templateOwners.set(scope, { outputPath: templateOutputPath, rootLen: bestRootLen });\n }\n }\n }\n for (const [scope, { outputPath }] of templateOwners) {\n setFileMapEntry(templateFileMap, scope, outputPath);\n }\n\n const results: GenerateDocResult[\"files\"] = [];\n let hasError = false;\n\n // Process each file\n for (const [filePath, fileConfigRaw] of Object.entries(files)) {\n const { fileConfig, specifiedCommands, commandPaths } = resolveConfiguredCommandPaths(\n fileConfigRaw,\n allCommands,\n ignores,\n );\n\n if (specifiedCommands.length === 0) {\n continue;\n }\n\n // Skip files where no commands resolved\n if (commandPaths.length === 0) {\n continue;\n }\n\n // In target mode, skip non-target files entirely\n const fileTargetCommands = hasTargetCommands\n ? findTargetCommandsInFile(targetCommands, filePath, files, allCommands, ignores)\n : [];\n if (hasTargetCommands && fileTargetCommands.length === 0) {\n continue;\n }\n\n let fileStatus: \"match\" | \"created\" | \"updated\" | \"diff\" = \"match\";\n const diffs: string[] = [];\n\n // Calculate minimum depth in this file for relative heading level\n const minDepth = Math.min(...commandPaths.map((p) => allCommands.get(p)?.depth ?? 1));\n\n // Adjust headingLevel so that minimum depth command gets the configured headingLevel\n const adjustedHeadingLevel = Math.max(\n 1,\n (format?.headingLevel ?? 1) - (minDepth - 1),\n ) as HeadingLevel;\n\n // In PathConfig mode, the rootDoc file has extra content (header, global-options)\n // managed by rootDoc processing and always uses markers to inject generated sections\n // into handwritten content.\n const isRootDocFile =\n usingPathConfig &&\n rootDoc &&\n normalizeDocPathForComparison(filePath) === normalizeDocPathForComparison(rootDoc.path);\n // `path` mode injects generated sections into hand-authored files, so every file in a\n // path config uses markers. Plain `files` output is fully generated unless the caller opts\n // into hand-customizable output via `customizable: true`. (isRootDocFile implies\n // usingPathConfig, so it is already covered here.)\n const fileUsesMarkers = usingPathConfig || customizable;\n\n // Create file-specific renderer with adjusted headingLevel (if no custom renderer)\n const fileRenderer = createCommandRenderer({\n ...format,\n headingLevel: adjustedHeadingLevel,\n markerless: !fileUsesMarkers,\n });\n\n // Use custom renderer if provided, otherwise use file-specific renderer\n const render = fileConfig.render ?? fileRenderer;\n\n // Marker-based in-place comparison/update is only possible when the file carries markers:\n // the rootDoc host file, or a `customizable` files output with partial (targetCommands)\n // updates. Fully generated files are always compared/regenerated as a whole.\n const useMarkerBasedComparison =\n Boolean(isRootDocFile) || (hasTargetCommands && fileUsesMarkers);\n\n // Handle partial validation when targetCommands are specified\n // or when the file is the rootDoc in PathConfig mode\n if (useMarkerBasedComparison) {\n // Read existing content once for all target commands in this file\n let existingContent = readFile(filePath);\n // Pre-compute sorted order once per file for insertCommandSections\n const sortedCommandPaths = sortDepthFirst(commandPaths, specifiedCommands);\n const effectiveTargetCommands = hasTargetCommands ? fileTargetCommands : commandPaths;\n\n for (const targetCommand of effectiveTargetCommands) {\n // Generate only the target command's section\n const rawSection = generateCommandSection(\n targetCommand,\n allCommands,\n render,\n filePath,\n templateFileMap,\n rootDoc?.path,\n globalOptionDefinitions.size > 0,\n ignores,\n );\n\n if (!rawSection) {\n throw new Error(`Target command \"${targetCommand}\" not found in commands`);\n }\n\n // Apply formatter to the section\n const generatedSection = await applyFormatter(rawSection, formatter);\n\n if (!existingContent) {\n // File doesn't exist yet, create it with the section only\n if (updateMode) {\n // For root command, include file header if configured\n const isRootCommand = targetCommand === \"\";\n const header = isRootCommand && fileConfig ? generateFileHeader(fileConfig) : null;\n const fullContent = header ? `${header}\\n${generatedSection}` : generatedSection;\n writeFile(filePath, fullContent);\n existingContent = fullContent;\n fileStatus = \"created\";\n } else {\n hasError = true;\n fileStatus = \"diff\";\n diffs.push(\n `File does not exist. Target command \"${targetCommand}\" section cannot be validated.`,\n );\n }\n continue;\n }\n\n // Check which section markers exist for this command in the existing content\n const existingMarkers = collectSectionMarkers(existingContent, targetCommand);\n\n if (existingMarkers.length === 0) {\n // No markers found — insert full template\n if (updateMode) {\n existingContent = insertCommandSections(\n existingContent,\n targetCommand,\n generatedSection,\n sortedCommandPaths,\n );\n writeFile(filePath, existingContent);\n if (fileStatus !== \"created\") {\n fileStatus = \"updated\";\n }\n } else {\n hasError = true;\n fileStatus = \"diff\";\n diffs.push(\n `Existing file does not contain section markers for command \"${targetCommand}\"`,\n );\n }\n continue;\n }\n\n // Validate/update only existing section markers\n for (const sectionType of existingMarkers) {\n const existingSection = extractSectionMarker(existingContent, sectionType, targetCommand);\n const generatedSectionPart = extractSectionMarker(\n generatedSection,\n sectionType,\n targetCommand,\n );\n\n if (!existingSection) {\n continue;\n }\n\n // Stale section: exists in document but not in generated output — replace with empty markers\n if (!generatedSectionPart) {\n const emptyMarker =\n sectionStartMarker(sectionType, targetCommand) +\n \"\\n\" +\n sectionEndMarker(sectionType, targetCommand);\n if (existingSection !== emptyMarker) {\n if (updateMode) {\n const updated = replaceSectionMarker(\n existingContent,\n sectionType,\n targetCommand,\n emptyMarker,\n );\n if (!updated) {\n throw new Error(\n `Failed to replace stale ${sectionType} section for command \"${targetCommand}\"`,\n );\n }\n existingContent = updated.replace(/\\n{3,}/g, \"\\n\\n\");\n writeFile(filePath, existingContent);\n if (fileStatus !== \"created\") {\n fileStatus = \"updated\";\n }\n } else {\n hasError = true;\n fileStatus = \"diff\";\n diffs.push(formatDiff(existingSection, emptyMarker));\n }\n }\n continue;\n }\n\n if (existingSection !== generatedSectionPart) {\n if (updateMode) {\n const updated = replaceSectionMarker(\n existingContent,\n sectionType,\n targetCommand,\n generatedSectionPart,\n );\n if (updated) {\n existingContent = updated;\n writeFile(filePath, existingContent);\n if (fileStatus !== \"created\") {\n fileStatus = \"updated\";\n }\n } else {\n throw new Error(\n `Failed to replace ${sectionType} section for command \"${targetCommand}\"`,\n );\n }\n } else {\n hasError = true;\n fileStatus = \"diff\";\n diffs.push(formatDiff(existingSection, generatedSectionPart));\n }\n }\n }\n\n // Detect section markers present in the generated output but missing from the existing\n // file. Doctor mode inserts them (update) or reports them as errors (check). When the\n // output is `customizable` but doctor mode is off, surface a non-fatal warning instead:\n // newly added sections stay visible without re-inserting markers the user may have\n // deliberately removed to opt that section out.\n if (doctorMode || customizable) {\n const generatedMarkers = collectSectionMarkers(generatedSection, targetCommand);\n const existingMarkerSet = new Set(existingMarkers);\n\n for (const sectionType of generatedMarkers) {\n if (existingMarkerSet.has(sectionType)) {\n continue;\n }\n\n const generatedSectionPart = extractSectionMarker(\n generatedSection,\n sectionType,\n targetCommand,\n );\n if (!generatedSectionPart) {\n continue;\n }\n\n if (doctorMode && updateMode) {\n existingContent = insertSectionMarkerAtOrder(\n existingContent,\n sectionType,\n targetCommand,\n generatedSectionPart,\n );\n writeFile(filePath, existingContent);\n if (fileStatus !== \"created\") {\n fileStatus = \"updated\";\n }\n } else if (doctorMode) {\n hasError = true;\n hasDoctorIssues = true;\n fileStatus = \"diff\";\n diffs.push(\n `[doctor] Missing section marker \"${sectionType}\" for command \"${formatCommandPath(targetCommand)}\". Run with ${DOCTOR_ENV}=true ${UPDATE_GOLDEN_ENV}=true to insert.\\n${generatedSectionPart}`,\n );\n } else {\n // customizable, doctor off: non-fatal nudge, no insertion.\n console.warn(\n `[politty] Missing \"${sectionType}\" section for command \"${formatCommandPath(targetCommand)}\" in ${filePath}. Run with ${DOCTOR_ENV}=true ${UPDATE_GOLDEN_ENV}=true to insert it, or leave it removed to opt that section out.`,\n );\n }\n }\n }\n }\n\n // Remove orphaned section markers for commands no longer in this file\n if (existingContent) {\n const existingMarkerPaths = collectSectionMarkerPaths(existingContent);\n const commandPathSet = new Set(commandPaths);\n\n if (updateMode) {\n let removedAny = false;\n for (const markerPath of existingMarkerPaths) {\n if (!commandPathSet.has(markerPath)) {\n existingContent = removeCommandSections(existingContent, markerPath);\n removedAny = true;\n }\n }\n if (removedAny) {\n writeFile(filePath, existingContent);\n if (fileStatus !== \"created\") {\n fileStatus = \"updated\";\n }\n }\n } else {\n for (const markerPath of existingMarkerPaths) {\n if (!commandPathSet.has(markerPath)) {\n hasError = true;\n fileStatus = \"diff\";\n diffs.push(\n `Found orphaned section markers for deleted command \"${formatCommandPath(markerPath)}\"`,\n );\n }\n }\n }\n }\n } else {\n // Generate markdown with file context (pass specifiedCommands as order hint).\n // Use templateFileMap so a files output can link to a heading rendered in a template\n // output; with no templates it is identical to fileMap.\n const rawMarkdown = generateFileMarkdown(\n commandPaths,\n allCommands,\n render,\n filePath,\n templateFileMap,\n specifiedCommands,\n fileConfig,\n rootDoc?.path,\n globalOptionDefinitions.size > 0,\n ignores,\n );\n\n // Apply formatter if provided\n const generatedMarkdown = await applyFormatter(rawMarkdown, formatter);\n // Full file comparison (original behavior)\n const comparison = compareWithExisting(generatedMarkdown, filePath);\n\n if (comparison.match) {\n // fileStatus stays \"match\"\n } else if (updateMode) {\n writeFile(filePath, generatedMarkdown);\n fileStatus = comparison.fileExists ? \"updated\" : \"created\";\n } else {\n hasError = true;\n fileStatus = \"diff\";\n if (comparison.diff) {\n diffs.push(comparison.diff);\n }\n }\n }\n\n // Determine final status based on diffs\n if (diffs.length > 0) {\n fileStatus = \"diff\";\n }\n\n results.push({\n path: filePath,\n status: fileStatus,\n diff: diffs.length > 0 ? diffs.join(\"\\n\\n\") : undefined,\n });\n }\n\n // === Template generation ===\n // Global options shape used by {{politty:global-options}} placeholders\n let normalizedTemplateGlobalOptions: { args: ArgsShape; options?: ArgsTableOptions } | undefined;\n if (rootDoc?.globalOptions) {\n normalizedTemplateGlobalOptions = normalizeGlobalOptions(rootDoc.globalOptions);\n } else {\n const shape = deriveGlobalArgsShape(globalArgs);\n if (shape) {\n normalizedTemplateGlobalOptions = { args: shape };\n }\n }\n\n // Now process each template\n for (const [outputPath, templatePath] of templateEntries) {\n if (!activeTemplateMeta.has(outputPath)) {\n continue;\n }\n\n const templateContent = templateContents.get(outputPath) ?? null;\n if (templateContent === null) {\n hasError = true;\n results.push({\n path: outputPath,\n status: \"diff\",\n diff: `Template file not found: ${templatePath}`,\n });\n continue;\n }\n\n const meta = templateMeta.get(outputPath);\n const templateLineEnding = detectLineEnding(templateContent);\n const outputTemplateContent = stripPolittyFrontMatterForOutput(templateContent);\n\n // Compute heading level adjustment from the scopes that actually render a heading. Typed-only\n // placeholders (which emit no heading) must not skew the depth, matching files-mode behaviour\n // where the shallowest rendered command maps to the configured heading level.\n const headingDepths = (meta?.headingScopes ?? []).map((s) => allCommands.get(s)?.depth ?? 1);\n const minDepth = headingDepths.length > 0 ? Math.min(...headingDepths) : 1;\n const adjustedHeadingLevel = clampHeadingLevel((format?.headingLevel ?? 1) - (minDepth - 1));\n const templateRenderer = createCommandRenderer({\n ...format,\n headingLevel: adjustedHeadingLevel,\n });\n\n // Global options affect command sections in this output ONLY when this output emits a\n // reachable #global-options anchor, another template output provides one, or a rootDoc\n // provides one. Otherwise, leave command option tables intact and emit no global-options link.\n const outputEmitsGlobalOptions = meta?.emitsGlobalOptions ?? false;\n const globalOptionsReachable =\n (rootDoc !== undefined && globalOptionDefinitions.size > 0) ||\n outputEmitsGlobalOptions ||\n templateGlobalOptionsProviderPath !== undefined;\n const excludeOptionNames =\n globalOptionsReachable && templateGlobalOptionFields.size > 0\n ? new Set(templateGlobalOptionFields.keys())\n : undefined;\n const sectionHasGlobalOptions = excludeOptionNames !== undefined;\n // Prefer this output's own #global-options anchor when it emits one, then fall back to rootDoc\n // or the single template output that provides global options.\n const effectiveRootDocPath = outputEmitsGlobalOptions\n ? outputPath\n : (rootDoc?.path ?? templateGlobalOptionsProviderPath);\n\n // Parse placeholders and compute replacements (reuse TEMPLATE_PLACEHOLDER_REGEX via .match)\n const placeholders = Array.from(\n new Set(outputTemplateContent.match(TEMPLATE_PLACEHOLDER_REGEX) ?? []),\n );\n const replacements = new Map<string, string>();\n const exclusions = templateExclusions.get(outputPath) ?? createTemplateExclusions(new Set());\n\n for (const placeholder of placeholders) {\n const placeholderKey = templatePlaceholderKey(placeholder);\n if (\n exclusions.rawKeys.has(placeholderKey) ||\n isRawCommandPlaceholderUnderExcludedScope(placeholderKey, exclusions)\n ) {\n replacements.set(placeholder, \"\");\n continue;\n }\n\n const parsed = parsePlaceholder(placeholder, allCommands);\n if (shouldSkipTemplatePlaceholder(placeholder, parsed, exclusions)) {\n replacements.set(placeholder, \"\");\n continue;\n }\n\n if (parsed.kind === \"invalid\") {\n // Should have been caught in the validation pass; guard defensively.\n throw new Error(\n `Internal error: unresolved placeholder \"${placeholder}\" in template \"${templatePath}\": ${parsed.reason}`,\n );\n }\n\n if (parsed.kind === \"command\") {\n const { scope, type } = parsed;\n\n if (type === undefined) {\n const rawSection = generateCommandTreeMarkdown(\n scope,\n allCommands,\n templateRenderer,\n ignores,\n outputPath,\n templateFileMap,\n effectiveRootDocPath,\n sectionHasGlobalOptions,\n excludeOptionNames,\n exclusions,\n );\n if (rawSection === null) {\n replacements.set(placeholder, \"\");\n continue;\n }\n replacements.set(placeholder, stripPolittyMarkers(rawSection));\n } else {\n const rawSection = generateCommandSection(\n scope,\n allCommands,\n templateRenderer,\n outputPath,\n templateFileMap,\n effectiveRootDocPath,\n sectionHasGlobalOptions,\n ignores,\n excludeOptionNames,\n exclusions,\n );\n if (rawSection === null) {\n replacements.set(placeholder, \"\");\n continue;\n }\n // Single section type\n const extracted = extractSectionMarker(rawSection, type, scope);\n replacements.set(placeholder, extracted === null ? \"\" : stripPolittyMarkers(extracted));\n }\n } else if (parsed.kind === \"global-options\") {\n if (normalizedTemplateGlobalOptions) {\n replacements.set(placeholder, buildGlobalOptionsContent(normalizedTemplateGlobalOptions));\n } else {\n replacements.set(placeholder, \"\");\n }\n } else if (parsed.kind === \"index\") {\n // files-based categories keep their normal leaf-only expansion; template-output\n // categories list exactly their rendered heading scopes (noExpand) so the index never\n // links to commands template mode did not render.\n const categories = [\n ...deriveIndexFromFiles(files, outputPath, allCommands, ignores),\n ...deriveIndexFromTemplateOutputs(templateMeta, outputPath, outputPath, allCommands),\n ];\n const indexContent = await renderCommandIndex(command, categories, rootDoc?.index);\n replacements.set(placeholder, indexContent);\n }\n }\n\n // Substitute placeholders. Handwritten spacing is preserved verbatim; the ONLY whitespace we\n // touch is the gap an EMPTY own-line placeholder would otherwise leave. For such a placeholder\n // we consume the newlines immediately around it and re-emit a single break that matches the\n // larger of the two surrounding runs (so a blank-line paragraph gap stays a blank line, and a\n // tight single-newline gap stays a single newline — adjacent lines never concatenate).\n let generated = outputTemplateContent.replace(\n /((?:\\r?\\n)*)([ \\t]*)(\\{\\{politty:[^{}]*\\}\\})([ \\t]*)((?:\\r?\\n)*)/g,\n (\n match,\n leadNl: string,\n leadWs: string,\n placeholder: string,\n trailWs: string,\n trailNl: string,\n offset: number,\n fullString: string,\n ) => {\n const replacement = replacements.get(placeholder);\n if (replacement === undefined) {\n throw new Error(\n `Internal error: unresolved placeholder \"${placeholder}\" in template \"${templatePath}\".`,\n );\n }\n const startsLine = leadNl !== \"\" || offset === 0 || fullString[offset - 1] === \"\\n\";\n const endsLine = trailNl !== \"\" || offset + match.length === fullString.length;\n const isOwnLine = startsLine && endsLine;\n if (replacement === \"\" && isOwnLine) {\n // Re-emit one break: the wider of the two surrounding newline runs, capped at a blank\n // line. Empty when the placeholder sat at the very start/end so output does not gain a\n // leading or trailing blank line.\n if (leadNl === \"\" || trailNl === \"\") {\n return \"\";\n }\n const leadBreaks = countLineBreaks(leadNl);\n const trailBreaks = countLineBreaks(trailNl);\n const widest = Math.max(leadBreaks, trailBreaks);\n const lineEnding =\n leadBreaks >= trailBreaks ? detectLineEnding(leadNl) : detectLineEnding(trailNl);\n return widest >= 2 ? lineEnding + lineEnding : widest === 1 ? lineEnding : \"\";\n }\n // Otherwise restore the exact surrounding whitespace and substitute the content.\n return `${leadNl}${leadWs}${replacement}${trailWs}${trailNl}`;\n },\n );\n\n // Ensure exactly one trailing newline.\n generated = `${generated.trimEnd()}${templateLineEnding}`;\n\n // Apply formatter\n generated = await applyFormatter(generated, formatter);\n\n // Compare and update\n const comparison = compareWithExisting(generated, outputPath);\n let templateStatus: \"match\" | \"created\" | \"updated\" | \"diff\" = \"match\";\n let templateDiff: string | undefined;\n\n if (comparison.match) {\n // stays \"match\"\n } else if (updateMode) {\n writeFile(outputPath, generated);\n templateStatus = comparison.fileExists ? \"updated\" : \"created\";\n } else {\n hasError = true;\n templateStatus = \"diff\";\n if (comparison.diff) {\n templateDiff = comparison.diff;\n }\n }\n\n results.push({\n path: outputPath,\n status: templateStatus,\n diff: templateDiff,\n });\n }\n\n // === Root document processing ===\n if (rootDoc) {\n const rootDocFilePath = rootDoc.path;\n let rootDocStatus: \"match\" | \"created\" | \"updated\" | \"diff\" = \"match\";\n const rootDocDiffs: string[] = [];\n\n const existingContent = readFile(rootDocFilePath);\n if (existingContent === null) {\n hasError = true;\n rootDocStatus = \"diff\";\n rootDocDiffs.push(\"File does not exist. Cannot validate rootDoc markers.\");\n } else {\n let content = existingContent;\n let markerUpdated = false;\n\n // Validate/update rootDoc file header derived from command.name/description\n // rootInfo overrides command defaults\n const rootInfo = config.rootInfo;\n const rootDocFileConfig: FileHeaderConfig = {\n title: rootInfo?.title ?? command.name,\n };\n if (rootDoc.headingLevel !== undefined) {\n rootDocFileConfig.headingLevel = rootDoc.headingLevel;\n }\n const rootDescription = rootInfo?.description ?? command.description;\n if (rootDescription !== undefined) {\n rootDocFileConfig.description = rootDescription;\n }\n const headerResult = processFileHeader(content, rootDocFileConfig, updateMode);\n content = headerResult.content;\n if (headerResult.diff) {\n rootDocDiffs.push(headerResult.diff);\n }\n if (headerResult.hasError) {\n hasError = true;\n }\n if (headerResult.wasUpdated) {\n markerUpdated = true;\n }\n\n // Process rootInfo.header marker (after title/description)\n if (rootInfo?.header) {\n const headerMarkerResult = await processStaticMarker(\n content,\n \"Root header\",\n rootHeaderStartMarker(),\n rootHeaderEndMarker(),\n rootInfo.header,\n updateMode,\n formatter,\n usingPathConfig,\n );\n content = headerMarkerResult.content;\n rootDocDiffs.push(...headerMarkerResult.diffs);\n if (headerMarkerResult.hasError) {\n hasError = true;\n }\n if (headerMarkerResult.wasUpdated) {\n markerUpdated = true;\n }\n }\n\n // Detect and clean up unexpected section markers in rootDoc\n // In PathConfig mode, section markers are expected (rootDoc overlaps with files)\n if (!usingPathConfig) {\n const unexpectedSectionPaths = collectSectionMarkerPaths(content);\n if (unexpectedSectionPaths.length > 0) {\n if (updateMode) {\n for (const commandPath of unexpectedSectionPaths) {\n content = removeCommandSections(content, commandPath);\n }\n markerUpdated = true;\n } else {\n hasError = true;\n rootDocDiffs.push(\n `Found unexpected section markers in rootDoc: ${unexpectedSectionPaths\n .map((commandPath) => `\"${formatCommandPath(commandPath)}\"`)\n .join(\", \")}.`,\n );\n }\n }\n }\n\n // Process global options marker\n const normalizedGlobalOptions = normalizeGlobalOptions(rootDoc.globalOptions);\n if (normalizedGlobalOptions) {\n const globalOptionsResult = await processGlobalOptionsMarker(\n content,\n normalizedGlobalOptions,\n updateMode,\n formatter,\n usingPathConfig,\n );\n content = globalOptionsResult.content;\n rootDocDiffs.push(...globalOptionsResult.diffs);\n if (globalOptionsResult.hasError) {\n hasError = true;\n }\n if (globalOptionsResult.wasUpdated) {\n markerUpdated = true;\n }\n }\n\n // Process index marker (auto-derived from files)\n const derivedCategories = deriveIndexFromFiles(files, rootDocFilePath, allCommands, ignores);\n // Forward slashes keep the marker stable when docs are regenerated on a different OS.\n const indexScope = path.relative(process.cwd(), rootDocFilePath).replace(/\\\\/g, \"/\");\n const indexResult = await processIndexMarker(\n content,\n derivedCategories,\n command,\n indexScope,\n updateMode,\n formatter,\n rootDoc.index,\n );\n content = indexResult.content;\n rootDocDiffs.push(...indexResult.diffs);\n if (indexResult.hasError) {\n hasError = true;\n }\n if (indexResult.wasUpdated) {\n markerUpdated = true;\n }\n\n // Process rootInfo.footer marker (at end of document)\n if (rootInfo?.footer) {\n const footerMarkerResult = await processStaticMarker(\n content,\n \"Root footer\",\n rootFooterStartMarker(),\n rootFooterEndMarker(),\n rootInfo.footer,\n updateMode,\n formatter,\n usingPathConfig,\n );\n content = footerMarkerResult.content;\n rootDocDiffs.push(...footerMarkerResult.diffs);\n if (footerMarkerResult.hasError) {\n hasError = true;\n }\n if (footerMarkerResult.wasUpdated) {\n markerUpdated = true;\n }\n }\n\n // Write updated content if markers were modified\n if (updateMode && markerUpdated) {\n writeFile(rootDocFilePath, content);\n if (rootDocStatus === \"match\") {\n rootDocStatus = \"updated\";\n }\n }\n }\n\n // Determine final status based on diffs\n if (rootDocDiffs.length > 0) {\n rootDocStatus = \"diff\";\n }\n\n results.push({\n path: rootDocFilePath,\n status: rootDocStatus,\n diff: rootDocDiffs.length > 0 ? rootDocDiffs.join(\"\\n\\n\") : undefined,\n });\n }\n\n const errorHint = hasDoctorIssues\n ? `Run with ${DOCTOR_ENV}=true ${UPDATE_GOLDEN_ENV}=true to fix missing markers.`\n : `Run with ${UPDATE_GOLDEN_ENV}=true to update.`;\n\n return {\n success: !hasError,\n files: results,\n error: hasError ? `Documentation is out of date. ${errorHint}` : undefined,\n };\n}\n\n/**\n * Assert that documentation matches golden files\n * Throws an error if there are differences and update mode is not enabled\n */\nexport async function assertDocMatch(config: GenerateDocConfig): Promise<void> {\n const result = await generateDoc(config);\n\n if (!result.success) {\n const diffMessages = result.files\n .filter((f) => f.status === \"diff\")\n .map((f) => {\n let msg = `File: ${f.path}\\n`;\n if (f.diff) {\n msg += f.diff;\n }\n return msg;\n })\n .join(\"\\n\\n\");\n\n throw new Error(\n `Documentation does not match golden files.\\n\\n${diffMessages}\\n\\n` +\n (result.error ?? `Run with ${UPDATE_GOLDEN_ENV}=true to update the documentation.`),\n );\n }\n}\n\n/**\n * Initialize documentation files by deleting them\n * Only deletes when update mode is enabled (POLITTY_DOCS_UPDATE=true)\n * Use this in beforeAll to ensure skipped tests don't leave stale sections\n * @param config - Config containing files to initialize, or a single file path\n * @param fileSystem - Optional fs implementation (useful when fs is mocked)\n */\nexport function initDocFile(\n config: Pick<GenerateDocConfig, \"files\" | \"templates\" | \"rootDoc\"> | string,\n fileSystem?: DeleteFileFs,\n): void {\n if (!isTruthyEnv(UPDATE_GOLDEN_ENV)) {\n return;\n }\n\n if (typeof config === \"string\") {\n deleteFile(config, fileSystem);\n } else {\n // Never delete a path that is used as a template source. A misconfigured entry whose files\n // output or template output equals some template source (e.g. { [p]: p }) must be left intact\n // so generateDoc can reject it instead of this initializer destroying the source first.\n // Computed up front so it guards BOTH the files loop and the templates loop.\n const protectedPaths = new Set(\n Object.values(config.templates ?? {}).map(normalizeDocPathForComparison),\n );\n if (config.rootDoc) {\n protectedPaths.add(normalizeDocPathForComparison(config.rootDoc.path));\n }\n const isProtectedPath = (p: string): boolean =>\n protectedPaths.has(normalizeDocPathForComparison(p));\n\n // rootDoc is NOT deleted because generateDoc expects it to exist with markers.\n // Only generated files (which are fully regenerated) are deleted.\n if (config.files) {\n for (const filePath of Object.keys(config.files)) {\n if (isProtectedPath(filePath)) {\n continue;\n }\n deleteFile(filePath, fileSystem);\n }\n }\n if (config.templates) {\n for (const outputPath of Object.keys(config.templates)) {\n if (isProtectedPath(outputPath)) {\n continue;\n }\n deleteFile(outputPath, fileSystem);\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAocA,MAAa,oBAAoB;;;;;;AAOjC,MAAa,aAAa;;;;AAK1B,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAWA,MAAa,wBAAwB;;;;AAKrC,SAAgB,mBAAmB,MAAmB,OAAuB;CAC3E,OAAO,QAAQ,sBAAsB,GAAG,MAAM,GAAG,KAAK;AACxD;;;;AAKA,SAAgB,iBAAiB,MAAmB,OAAuB;CACzE,OAAO,QAAQ,sBAAsB,GAAG,MAAM,GAAG,KAAK;AACxD;;;;;AAMA,MAAa,+BAA+B;;;;AAK5C,SAAgB,2BAAmC;CACjD,OAAO,QAAQ,6BAA6B;AAC9C;;;;AAKA,SAAgB,yBAAiC;CAC/C,OAAO,QAAQ,6BAA6B;AAC9C;;;;AAKA,MAAa,4BAA4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