Skip to content

Markdown AST

These runtime helpers provide a friendly wrapper around the remark, mdast, unified ecosystem to parse and manipulate Markdown documents.

Terminal window
npm i -D @genaiscript/plugin-mdast

If you are using the plugin in a Node.JS environment, without a .genai... entry file, you will need to initialize the runtime before using the plugin:

import { initialize } from "@genaiscript/runtime";
await initialize();
  • load the parsers
import { mdast } from "@genaiscript/plugin-mdast";
const { parse, visit, stringify } = await mdast();
  • parsing to mdast tree
const root = parse("# Hello World");
const updated = visit(root, `code`, (node) => {
...node
});
  • serializing the tree back to Markdown
const markdown = await stringify(updated);
  • chunk the tree into sections
const { parse, chunk } = await mdast();
const root = parse(
"# Section 1\n\nContent 1\n\n## Subsection 1.1\n\nContent 1.1\n\n# Section 2\n\nContent 2",
);
const sections = chunk(root);
console.log(sections);

In order to get type completion, you will need to install the @types/mdast package as a development dependency.

You can use inspect to pretty print a MDAST tree.

const { parse, inspect } = await mdast();
const root = parse("# Hello World");
console.log(inspect(root));

If you plan to process MDX documents, you should configure the plugin to use the mdx parser:

const { parse } = await mdast({ mdx: true });