npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

hierarchy-mdast

v1.0.7

Published

[![npm version](https://badge.fury.io/js/hierarchy-mdast.svg)](https://www.npmjs.com/package/hierarchy-mdast)

Readme

hierarchy-mdast

npm version

一个专门用于将扁平的 Markdown AST (MDAST) 转换为层次化树状结构的工具。本工具不是标准的 remark plugin,而是对已解析的 MDAST 进行后处理的工具。

✨ 特性

  • 🚀 层次化解析 - 根据标题层级自动构建树状结构
  • 🎯 位置查询 - 根据文档位置快速定位所属标题层级
  • 🔄 结构转换 - 支持层次化 ↔ 扁平化双向转换
  • 📝 完整支持 - 支持 frontmatter、GitHub Flavored Markdown 等
  • 🛠️ TypeScript - 完整的类型定义

📦 安装

npm install hierarchy-mdast

pnpm add hierarchy-mdast

💡 主要用法

本工具的核心API是 toHierarchy(),它接受一个从 remark 解析得到的扁平 MDAST 对象,并将其转换为层次化结构:

import { toHierarchy } from 'hierarchy-mdast';

const flatMdast = remark.parse(markdown);  // 先用 remark 解析
const hierarchyAst = toHierarchy(flatMdast);  // 后处理为层次化结构

🚀 快速开始

import { toHierarchy, getBelowHeading, unHierarchy, getRemark } from 'hierarchy-mdast';
import { remark } from 'remark';

// 首先用 remark 解析 Markdown 为 MDAST
const remarkProcessor = await getRemark();
const markdown = `
# 主标题

这是文档简介。

## 二级标题

二级标题下的内容。

### 三级标题

三级标题下的内容。
`;

const flatMdast = remarkProcessor.parse(markdown);

// 然后用 toHierarchy 转换为层次化结构
const hierarchyAst = toHierarchy(flatMdast);
console.log(hierarchyAst);

📚 API 文档

toHierarchy(mdast: any): any

将扁平的 MDAST 转换为层次化结构。这是主要API函数。

参数:

  • mdast (any): 从 remark 解析得到的扁平 MDAST 对象

返回值:

  • any: 层次化的 mdast 对象

parse(markdown: string): Promise<any> (已弃用)

将 Markdown 字符串解析为层次化的 AST 结构。

⚠️ 已弃用: 请使用 toHierarchy 配合 remark 解析代替。

参数:

  • markdown (string): 要解析的 Markdown 内容

返回值:

  • Promise: 层次化的 mdast 对象

注意: 输出的 AST 不是标准的 MDAST 格式。与原生 MDAST 不同,此库扩展了 heading 节点的 children 字段语义。在原生 MDAST 中,heading 的 children 只包含标题文本内容(如 text 节点),不支持嵌套的 MDAST 结构;而在此库中,heading 的 children 被扩展为可以包含该标题下所有子内容的完整 AST 节点,包括嵌套的标题、段落、列表等。

类型示例

{
  "type": "root",
  "children": [
    {
      "type": "heading",
      "depth": 1,
      "children": [
        {
          "type": "text",
          "value": "使用指南",
          "position": {
            "start": {
              "line": 12,
              "column": 3,
              "offset": 365
            },
            "end": {
              "line": 12,
              "column": 7,
              "offset": 369
            }
          }
        }
      ],
      "position": {
        "start": {
          "line": 12,
          "column": 1,
          "offset": 363
        },
        "end": {
          "line": 12,
          "column": 7,
          "offset": 369
        }
      },
      "content": "..." //新增字段
	}
  ]
}

getBelowHeading(mdastHierarchy: any, offset: number): Promise<string[]>

根据文档中的字符偏移位置,找到该位置所属的标题层级路径。

参数:

  • mdastHierarchy (any): 层次化的 mdast 对象
  • offset (number): 字符偏移位置

返回值:

  • Promise<string[]>: 从根到当前位置的所有标题字符串数组

toHierarchy(mdast: any): any

将扁平的 mdast 转换为层次化结构。

参数:

  • mdast (any): 扁平的 mdast 对象

返回值:

  • any: 层次化的 mdast 对象

unHierarchy(mdast: any): any

将层次化的 mdast 转换回扁平结构。

参数:

  • mdast (any): 层次化的 mdast 对象

返回值:

  • any: 扁平的 mdast 对象

💡 使用示例

基本层次化解析

import { toHierarchy, unHierarchy, getRemark } from 'hierarchy-mdast';

const markdown = `
# 项目介绍

这是项目的基本介绍。

## 功能特性

### 核心功能

核心功能说明。

### 扩展功能

扩展功能说明。

## 使用指南

安装和使用说明。
`;

const remarkProcessor = await getRemark();
const flatMdast = remarkProcessor.parse(markdown);

// 转换为层次化结构
const hierarchyAst = toHierarchy(flatMdast);

// 查看层次化结构
console.log(JSON.stringify(hierarchyAst, null, 2));

// 转换回扁平 Markdown
const flatAst = unHierarchy(hierarchyAst);
const outputMarkdown = remarkProcessor.stringify(flatAst);

位置查询

import { toHierarchy, getBelowHeading, getRemark } from 'hierarchy-mdast';

const markdown = `
# 主标题

一些内容。

## 二级标题

更多内容。

### 三级标题

具体内容。
`;

const remarkProcessor = await getRemark();
const flatMdast = remarkProcessor.parse(markdown);
const hierarchyAst = toHierarchy(flatMdast);

// 查询位置 50 处的标题路径
const headingPath = await getBelowHeading(hierarchyAst, 50);
console.log(headingPath); // ['# 主标题', '## 二级标题']

文档处理工作流

import { toHierarchy, unHierarchy, getRemark } from 'hierarchy-mdast';

async function processDocument(markdown: string) {
  const remarkProcessor = await getRemark();

  // 1. 解析为扁平 MDAST
  const flatMdast = remarkProcessor.parse(markdown);

  // 2. 转换为层次化结构
  const hierarchyAst = toHierarchy(flatMdast);

  // 3. 在层次化结构上进行处理
  // ... 你的业务逻辑 ...

  // 4. 转换回扁平结构
  const flatAst = unHierarchy(hierarchyAst);

  // 5. 输出 Markdown
  return remarkProcessor.stringify(flatAst);
}

🧪 测试

运行测试套件:

# 运行简单测试
npm run test:simple

# 运行原有测试
npm run test

🔧 开发

# 安装依赖
npm install

# 开发模式
npm run dev

# 构建
npm run build

# 发布
npm run pub

📋 依赖

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📄 许可证

MIT License

👤 作者

qql2