Plugin API

Type-safe API for creating Comark plugins with pre and post lifecycle hooks.

The comark package exports defineComarkPlugin, a typed factory wrapper for building plugins that extend the parser.

defineComarkPlugin(factory)

Wraps a plugin factory function to provide type safety for both options and the returned plugin.

Parameters:

  • factory: A function (options?: O) => ComarkPlugin where O is an optional options type. When the plugin is instantiated, options receives the values passed by the caller. See ComarkPlugin for the full shape of the returned object.

Type parameters:

ParameterDefaultDescription
OptionsunknownShape of the options the factory accepts.
TMeta{}Keys this plugin contributes to tree.meta. Surfaces on the parse result and constrains writes inside post.
TFrontmatter{}Keys this plugin contributes to tree.frontmatter. This is experimental and may change in future versions.

Returns: A typed plugin factory (options?: O) => ComarkPlugin<TMeta, TFrontmatter>

Example:

import { defineComarkPlugin } from 'comark'

export default defineComarkPlugin(() => ({
  name: 'my-plugin',
  pre(state) {},
  post(state) {},
}))

With typed options:

import { defineComarkPlugin } from 'comark'

interface MyOptions {
  prefix?: string
}

export default defineComarkPlugin((options: MyOptions = {}) => ({
  name: 'my-plugin',
  post(state) {
    // options.prefix is typed
  },
}))

Typed contributions

Plugins that write to tree.meta can declare what they contribute via the second and third type parameters of defineComarkPlugin. Two things follow from that declaration:

  1. Inside post(state), state.tree.meta and state.tree.frontmatter are typed as the declared shape, so writes are checked against it.
  2. At the parseMarkdown call site, Comark intersects the contribution into tree.meta and tree.frontmatter, so result.meta.toc reads back as the declared type instead of any.

Declaring a contribution

import { defineComarkPlugin } from 'comark'

interface TocTree {
  title: string
  depth: number
  links: { id: string; text: string }[]
}

export default defineComarkPlugin<{}, { toc: TocTree }>(() => ({
  name: 'toc',
  post(state) {
    state.tree.meta.toc = { title: 'Contents', depth: 2, links: [] }

    // @ts-expect-error wrong value type for the declared key
    state.tree.meta.toc = 123

    // @ts-expect-error `summary` was not declared in the contribution
    state.tree.meta.summary = []
  },
}))

A plugin that contributes more than one key lists them all in the same object literal:

defineComarkPlugin<TitleDescriptionOptions, { title?: string; description?: string }>(() => ({
  name: 'title-description',
  post(state) {
    state.tree.meta.title = 'Hello'
    state.tree.meta.description = undefined
  },
}))

Inference at the parseMarkdown call site

parseMarkdown and createMarkdownParser infer the plugins tuple and intersect each plugin's contribution into the result type without an explicit generic argument:

import { parseMarkdown } from 'comark'
import toc from 'comark/plugins/toc'
import summary from 'comark/plugins/summary'

const tree = await parseMarkdown(content, { plugins: [toc(), summary()] })

tree.meta.toc       // Toc
tree.meta.summary   // Node[]
tree.meta.something // unknown: undeclared keys are typed as unknown

Backward compatibility for untyped plugins

Plugins that omit the meta and frontmatter type parameters keep untyped Record<string, any> maps, allowing writes to any key. At the parseMarkdown call site, meta also stays Record<string, any> when no plugin declares a contribution (or when plugins is typed as a widened ComarkPlugin[] variable rather than an inline array).

// Untyped plugin: meta stays Record<string, any>
defineComarkPlugin(() => ({
  name: 'wordcount',
  post(state) {
    state.tree.meta.wordCount = 42 // allowed when no contribution is declared
  },
}))

Lifecycle

Plugins hook into two phases of the parsing pipeline:

Markdown string
    │
    ▼
┌──────────┐
│   pre()  │  ← Modify raw Markdown before parsing
└──────────┘
    │
    ▼
  Parse & Build MarkdownDocument
    │
    ▼
┌──────────┐
│  post()  │  ← Transform the AST after parsing
└──────────┘
    │
    ▼
  MarkdownDocument

pre(state)

Called before Markdown is tokenized. Use it to transform the raw Markdown string.

import { defineComarkPlugin } from 'comark'

export default defineComarkPlugin(() => ({
  name: 'strip-comments',
  pre(state) {
    state.markdown = state.markdown.replace(/<!--[\s\S]*?-->/g, '')
  },
}))

ComarkParsePreState:

FieldTypeDescription
markdownstringThe raw Markdown; modify it to change parser input
optionsParserOptionsThe parser configuration

post(state)

Called after the AST is built. Use it to traverse nodes or populate meta with extracted data.

import { defineComarkPlugin } from 'comark'
import { visit } from 'comark/utils'

export default defineComarkPlugin(() => ({
  name: 'word-count',
  post(state) {
    let count = 0
    visit(state.tree,
      (node) => typeof node === 'string',
      (node) => { count += (node as string).split(/\s+/).filter(Boolean).length }
    )
    state.tree.meta.wordCount = count
  },
}))

ComarkParsePostState<TMeta, TFrontmatter>:

FieldTypeDescription
markdownstringThe original Markdown input
treeMarkdownDocument<TMeta, TFrontmatter>The parsed document; modify it to transform output. tree.meta and tree.frontmatter are typed against the plugin's declared contribution.
optionsParserOptionsThe parser configuration
tokensunknown[]The raw markdown-it tokens
To traverse and transform tree nodes, see the AST API page for the visit() utility.

ComarkPlugin<TMeta, TFrontmatter>

PropertyTypeDescription
namestringA unique identifier for the plugin
markdownItPluginsMarkdownItPlugin[]markdown-it plugins to register on the parser. See Markdown-it plugins
pre(state: ComarkParsePreState) => Promise<void> | voidHook called before parsing
post(state: ComarkParsePostState<TMeta, TFrontmatter>) => Promise<void> | voidHook called after the AST is built. state.tree.meta and state.tree.frontmatter are typed as the declared contribution. See Typed contributions
autoClose{ bracketMath?: boolean }Auto-close flags for syntax this plugin adds. Flags from all plugins are merged and applied when the parser's autoClose is true; a custom autoClose function ignores them

Usage

Pass plugins to parseMarkdown() or the <Markdown> component:

import { parseMarkdown } from 'comark'
import myPlugin from './my-plugin'

const tree = await parseMarkdown(content, {
  plugins: [myPlugin()]
})
© 2026 Vercel, Inc.