zod2md

repository·main·Indexed 40 days ago

https://github.com/matejchalk/zod2md

A tool to automatically generate Markdown documentation from Zod schemas. It provides a CLI and a programmatic API to maintain up-to-date API references for data models. Supports Zod v3 and v4, including a specific helper pattern for documenting Zod v4 function schemas. Version 0.3.6.

Tokens
3.6K
Snippets
18
Records
23
Agent score
99%

What's inside zod2md

  1. How to document Zod v4 function schemas

    main

    In Zod v4, z.function is a function factory rather than a Zod schema. To ensure zod2md can find and document the input/output schemas of a function, you must use a workaround that attaches the factory to the schema's metadata using the $ZodFunction key.

    Use the following helper pattern to wrap your function factories:

    import { z } from 'zod/v4';
    import type { $ZodFunction } from 'zod/v4/core';
    
    export function convertZodFunctionToSchema<T extends $ZodFunction>(factory: T) {
      return z
        .custom()
        .transform((arg, ctx) => {
          if (typeof arg !== 'function') {
            ctx.addIssue('Must be a function');
            return z.NEVER;
          }
          return factory.implement(arg as Parameters<T['implement']>[0]);
        })
        .meta({
          $ZodFunction: factory, // 👈 This metadata enables zod2md to find input/output schemas
        });
    }
    
    // Usage
    export const predicateSchema = convertZodFunctionToSchema(
      z.function({ input: [z.string(), z.number()], output: z.boolean() }),
    );
  2. Install and run zod2md via CLI

    main

    To generate Markdown documentation from your Zod schemas using the command line, first install the package as a dev dependency. You can then run the CLI using npx.

    Required arguments:

    • --entry: Path to the file(s) exporting your Zod schemas.
    • --title: The heading text for the generated Markdown document.
    • --output: The destination path for the generated Markdown file.

    Note: You can provide multiple entry points by repeating the --entry flag.

    npm install --save-dev zod2md
    
    npx zod2md --entry src/schemas.ts --title "Models reference" --output docs/models.md
  3. Configure zod2md using a configuration file

    main

    Instead of passing all arguments via the CLI, you can create a zod2md.config.ts (or .mjs, .js) file. This is useful for complex setups or keeping your commands clean.

    When using a configuration file, CLI arguments take precedence over the values defined in the file.

    import type { Config } from 'zod2md';
    
    const config: Config = {
      entry: 'src/schemas.ts',
      title: 'Models reference',
      output: 'docs/models.md',
    };
    
    export default config;
  4. Resolve configuration for the CLI

    main

    When running zod2md via the CLI, the configuration is resolved using a specific hierarchy. The tool first looks for a configuration file specified via the --config flag. If no config flag is provided, it attempts to find a default configuration file in the project. If no configuration file is found, the tool requires that all mandatory arguments (--entry, --output, and --title) are provided directly via CLI flags.

    If a configuration file is present, the CLI arguments are merged into the configuration object, with CLI arguments taking precedence over values defined in the config file.

    // Note: This logic is internal to the CLI execution flow. 
    // If no config file is found, the following flags are mandatory:
    // --entry
    // --output
    // --title
  5. Use zod2md programmatically

    main

    You can import the core zod2md function to generate a Markdown string directly within your own TypeScript/JavaScript code. This is useful for custom build scripts or integration into existing workflows.

    Returns a Promise<string> containing the generated Markdown.

    import { zod2md } from 'zod2md';
    
    const markdown = await zod2md({
      entry: 'src/schemas.ts',
      title: 'Models reference',
    });
  6. Configure FormatterOptions

    main

    When using zod2md programmatically, you can provide a FormatterOptions object to customize the output.

    • title: A required string that serves as the title for the generated documentation.
    • transformName: An optional NameTransformFn used to modify how schema names are displayed in the markdown output.
    const options: FormatterOptions = {
      title: 'My API Documentation',
      transformName: (name, path, schema) => {
        // Custom logic to transform the name
        return name?.toUpperCase() ?? 'UNKNOWN';
      }
    };
  7. Reference: CLI arguments for zod2md

    main

    The following options are available when running the zod2md CLI:

    OptionTypeRequiredDescription
    -e, --entrystring[]yesEntry point(s), i.e. paths to modules with Zod schema exports
    -t, --titlestringyesHeading text for Markdown document
    -o, --outputstringyesOutput file path where Markdown document will be generated
    --tsconfigstringnoPath to tsconfig.json to be used when importing entry point(s)
    -f, --format'esm' | 'cjs'noModule type to assume when importing entry point(s)
    -c, --configstringnoPath to configuration file (default is zod2md.config.{ts,mjs,js})
    -h, --helpbooleannoDisplay CLI help and exit
  8. Reference: Configuration file properties

    main

    The Config object used in zod2md.config.ts supports the following properties:

    PropertyTypeRequiredDescription
    entrystring | string[]yesEntry point(s), i.e. paths to modules with Zod schema exports
    tsconfigstringnoPath to tsconfig.json to be used when importing entry point(s)
    format'esm' | 'cjs'noModule type to assume when importing entry point(s)
    titlestringyesHeading text for Markdown document
    transformName(name: string | undefined, path: string, schema: z4.$ZodType | z3.ZodTypeAny) => stringnoCustom function for converting exported schema to a display title

    Note on transformName: By default, zod2md uses the title from Zod v4 metadata. If unavailable, it uses the variable name, stripping the Schema-suffix and converting it to PascalCase (e.g., userSchema becomes User). For default exports, the file path is used.

  9. Use the zod2md() function to convert Zod schemas to Markdown

    main

    The zod2md function is the primary entrypoint for converting Zod schemas into a Markdown string. It handles both loading the schemas and formatting them based on the provided Options. It is an asynchronous function that returns a Promise<string> containing the generated Markdown.

    import { zod2md } from 'zod2md';
    
    const markdown = await zod2md({
      // ... options
    });
  10. Run the zod2md CLI via runCLI

    main

    The runCLI function serves as the entrypoint for executing the zod2md command-line interface. It is responsible for parsing command-line arguments and initiating the conversion process.

    import { runCLI } from './src/cli/index';
    
    runCLI(process.argv);
  11. Load Zod schemas with loadZodSchemas

    main

    Use the loadZodSchemas function to load and process Zod schemas from a specified directory or file. This is the primary entrypoint for using zod2md programmatically.

    import { loadZodSchemas } from 'zod2md/loader';
    
    // Usage example (requires LoaderOptions configuration)
    const schemas = await loadZodSchemas(options);
  12. Use formatSchemasAsMarkdown() for direct Markdown generation

    main

    If you have already loaded your Zod schemas and want to skip the loading phase, you can use formatSchemasAsMarkdown directly. This function takes an array of loaded schemas and an Options object, returning a Promise<string> of the formatted Markdown.

    import { formatSchemasAsMarkdown } from 'zod2md';
    
    // schemas would be the result of loadZodSchemas()
    const markdown = await formatSchemasAsMarkdown(schemas, options);