Skip to content

ipikuka/unist-plugin-log-tree

Repository files navigation

A robust Next.js newsletter Next.js Weekly is sponsoring me 💖 NextjsWeekly banner

If you find unist-plugin-log-tree useful in your projects, consider supporting my work.
Your sponsorship means a lot 💖

My sponsors are going to be featured here and on my sponsor wall.

A warm thanks 🙌 to @ErfanEbrahimnia, @recepkyk, and @LSeaburg for the support!

Thank you for supporting open source! 🙌

unist-plugin-log-tree

npm version npm downloads publish to npm code-coverage type-coverage typescript license

This package is a unified (remark) plugin to log and optionally filter unist syntax trees for debugging purposes. It is debugging plugin for the unified ecosystem that logs unist syntax trees without transforming.

unified is a project that transforms content with abstract syntax trees (ASTs) using the new parser micromark. remark adds support for markdown to unified. mdast is the Markdown Abstract Syntax Tree (AST) which is a specification for representing markdown in a syntax tree. rehype is a tool that transforms HTML with plugins. hast stands for HTML Abstract Syntax Tree (HAST) that rehype uses. recma adds support for producing a javascript code by transforming esast which stands for Ecma Script Abstract Syntax Tree (AST) that is used in production of compiled source for the MDX.

This plugin is a universal syntax tree (unist) plugin for mdast, hast, estree, and other unist-based trees. It does not transform the tree; it only inspects and logs it for debugging.

unist-plugin-log-tree

A debugging plugin for the unified ecosystem that logs unist syntax trees without transforming them.

When should I use this?

unist-plugin-log-tree is useful when you want to inspect, debug, or snapshot syntax trees during a unified processing pipeline.

It works with any unist-compatible tree:

  • mdast (remark)
  • hast (rehype)
  • estree / recma
  • any custom unist-based AST

This plugin:

  • ✅ Logs the syntax tree to the console
  • ✅ Optionally filters nodes using test
  • ✅ Preserves parent chains when filtering
  • ✅ Optionally preserves full subtrees
  • ✅ Can hide position data
  • ❌ Does not transform or mutate the original tree

It is purely a debugging utility.

Installation

This package is ESM only.

In Node.js (version 16+), install with npm:

npm install unist-plugin-log-tree

or

yarn add unist-plugin-log-tree

Usage

⚠️ Important: Factory Pattern Usage

This plugin follows a factory pattern.

Unlike typical unified plugins that are used like this:

.use(plugin, options)

this plugin must be used like this:

.use(plugin(options))

Why?

The plugin is implemented as a factory so that it can be used multiple times in a single unified pipeline — for example, to log different stages (mdast, hast, etc.) independently.

Because of this structure, it returns a configured plugin instance immediately, which is why .use(plugin(options)) is required.

Basic usage (log full tree)

import { read } from "to-vfile";
import { unified } from "unified";
import remarkParse from "remark-parse";
import logTree from "unist-plugin-log-tree";

const file = await unified()
  .use(remarkParse)
  .use(logTree()) // ← factory call
  .process(await read("example.md"));

Running this will print the full mdast to the console.

With filtering

You can pass a test option (powered by unist-util-is) to log only specific nodes.

.use(logTree({ test: "heading" }))

This will:

  • Keep only heading nodes
  • Preserve their parent chain
  • Remove unrelated branches

With label

.use(logTree({ label: "Remark AST" }))

Console output:

[unist-log-tree] Remark AST
{ ...tree }

In a full pipeline (remark → rehype)

import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import rehypeStringify from "rehype-stringify";
import logTree from "unist-plugin-log-tree";

await unified()
  .use(remarkParse)
  .use(logTree({ label: "MDAST" }))
  .use(remarkRehype)
  .use(logTree({ label: "HAST" }))
  .use(rehypeStringify)
  .process("# Hello");

This logs both the mdast and hast trees.

Options

All options are optional.

type UnistLogTreeOptions = {
  test?: Test;
  preserveSubtree?: boolean;
  excludeKeys?: string[];
  depth?: number | null;
  indentation?: number;
  label?: string;
  enabled?: boolean;
};

test

Type: Test (from unist-util-is)
Default: undefined

Filters the tree. Only matching nodes and their parent chain are kept.

Examples:

test: "heading"
test: ["heading", "paragraph"]
test: (node) => node.type === "link"

If test is undefined or null, the full tree is logged.

preserveSubtree

Type: boolean
Default: true

Controls behavior when a node matches test.

  • true → Keep the matched node and entire subtree.
  • false → Recursively filter its children as well.

Example:

.use(logTree({
  test: "heading",
  preserveSubtree: false
}))
.use(logTree({
  test: { type: "CallExpression" }
  preserveSubtree: true
}))

excludeKeys

Type: string[]
Default: [] empty array

An array of property names to be recursively removed from the AST nodes before logging. This is useful for reducing noise by hiding metadata like position, loc, or range. Use this to filter out unwanted node data during logging.

.use(logTree({ excludeKeys: ["position"] }))

Strips position from the AST output. Output of the tree will not contain position data.

depth

Type: number | null
Default: null

Passed to console.dir as the depth option.

.use(logTree({ depth: 4 }))

indentation

Type: number
Default: 2

Controls JSON indentation size before printing.

label

Type: string
Default: undefined

Adds a label before the logged tree.

.use(logTree({ label: "Rehype AST" }))

enabled

Type: boolean
Default: true

Allows turning the logger off without removing it from the pipeline.

.use(logTree({ enabled: false }))

Useful in CI or production builds.

Filtering Behavior

When test is provided:

  • Matching nodes are kept.
  • Parent nodes are preserved if any descendant matches.
  • Non-matching branches are removed.
  • The original AST is never mutated.

The plugin internally clones the tree before pruning.

Syntax Tree

This plugin does not transform the syntax tree. It:

  • Clones the tree (when filtering)
  • Optionally prunes branches
  • Logs the result
  • Leaves the original AST untouched

Types

This package is fully typed with TypeScript. The options type is exported as:

UnistLogTreeOptions

Compatibility

This plugin works with unified version 6+, and any unist-compatible trees in a plugin chain of remark, rehype, recma.

Security

This plugin does not generate HTML, execute user code, or manipulate output content. It only logs syntax trees to the console. There are no XSS or runtime security concerns.

My Plugins

I like to contribute the Unified / Remark / MDX ecosystem, so I recommend you to have a look my plugins.

My Remark Plugins

My Rehype Plugins

  • rehype-pre-language – Rehype plugin to add language information as a property to pre element
  • rehype-highlight-code-lines – Rehype plugin to add line numbers to code blocks and allow highlighting of desired code lines
  • rehype-code-meta – Rehype plugin to copy code.data.meta to code.properties.metastring
  • rehype-image-toolkit – Rehype plugin to enhance Markdown image syntax ![]() and Markdown/MDX media elements (<img>, <audio>, <video>) by auto-linking bracketed or parenthesized image URLs, wrapping them in <figure> with optional captions, unwrapping images/videos/audio from paragraph, parsing directives in title for styling and adding attributes, and dynamically converting images into <video> or <audio> elements based on file extension.

My Recma Plugins

  • recma-mdx-escape-missing-components – Recma plugin to set the default value () => null for the Components in MDX in case of missing or not provided so as not to throw an error
  • recma-mdx-change-props – Recma plugin to change the props parameter into the _props in the function _createMdxContent(props) {/* */} in the compiled source in order to be able to use {props.foo} like expressions. It is useful for the next-mdx-remote or next-mdx-remote-client users in nextjs applications.
  • recma-mdx-change-imports – Recma plugin to convert import declarations for assets and media with relative links into variable declarations with string URLs, enabling direct asset URL resolution in compiled MDX.
  • recma-mdx-import-media – Recma plugin to turn media relative paths into import declarations for both markdown and html syntax in MDX.
  • recma-mdx-import-react – Recma plugin to ensure getting React instance from the arguments and to make the runtime props {React, jsx, jsxs, jsxDev, Fragment} is available in the dynamically imported components in the compiled source of MDX.
  • recma-mdx-html-override – Recma plugin to allow selected raw HTML elements to be overridden via MDX components.
  • recma-mdx-interpolate – Recma plugin to enable interpolation of identifiers wrapped in curly braces within the alt, src, href, and title attributes of markdown link and image syntax in MDX.

My Unist Utils and Plugins

I also build low-level utilities and plugins for the Unist ecosystem that can be used across Remark, Rehype, Recma, and other syntax trees.

License

MIT License © ipikuka

About

A debugging plugin for the unified ecosystem that logs unist syntax trees without transforming.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors