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

@cmtx/core

v0.4.1

Published

Core markdown document processing library - image extraction/manipulation and metadata handling

Downloads

545

Readme


title: "@cmtx/core" category: guide lang: zh-Hans skip_doc_render: true

@cmtx/core

npm version License

Markdown 纯文本处理核心库 - 图片解析、替换、尺寸调整、元数据操作。

文件系统操作(批量读写、删除)由 @cmtx/asset 处理(FileService、DeleteService)。本包专注于纯文本处理,但部分函数(如 extractMetadata)直接操作文件。

完整 API 文档:pnpm run docs(生成于 docs/api/

1. 安装

pnpm add @cmtx/core

2. 功能模块

2.1. 图片解析与格式化

import { parseImages, parseImagesMdSingleline, parseImagesHtmlSingleline,
         formatMarkdownImage, formatHtmlImage } from "@cmtx/core";

const images = parseImages(markdown); // 解析 Markdown + HTML 图片
const mdImg = formatMarkdownImage({ src: "../assets/examples/img.png", alt: "desc", title: "标题" });
const htmlImg = formatHtmlImage({ src: "../assets/examples/img.png", alt: "desc", width: "100", height: "100" });

2.2. 图片筛选

import { filterImages } from "@cmtx/core";

const allImages   = filterImages(markdown);
const localImages = filterImages(markdown, { mode: "sourceType", value: "local" });
const webImages   = filterImages(markdown, { mode: "hostname", value: "example.com" });
const pngImages   = filterImages(markdown, { mode: "regex", value: /\.png$/i });

2.3. 图片替换

import { updateImageRefs } from "@cmtx/core";

const result = updateImageRefs(markdown, [
  { field: "src", pattern: /\.png$/, newSrc: (m) => m.replace(/\.png$/, ".webp"),
    newAlt: "updated", newTitle: "new title" },
]);

2.4. 图片尺寸调整

import { setImageDimensions, toHtmlImage } from "@cmtx/core";

const img     = setImageDimensions('<img src="../assets/examples/test.png" width="300">', { width: '500' });  // width="500"
const html    = toHtmlImage("![alt](img.png)");               // <img src="img.png" alt="alt">
const htmlW   = toHtmlImage("![alt](img.png)", { width: '800' });  // <img src="..." width="800">

2.5. 元数据处理

import { extractFrontmatter, extractSectionHeadings,
         extractFrontmatterField, METADATA_REGEX,
         convertHeadingToFrontmatter, upsertFrontmatterFields,
         removeFrontmatter, deleteFrontmatterFields,
         parseFrontmatter, parseYamlFrontmatter, generateFrontmatterYaml } from "@cmtx/core";

const meta     = extractMetadata("./doc.md", { headingLevel: 1 });
const headings = extractSectionHeadings(markdown, { minLevel: 2, maxLevel: 4 });
const title    = extractTitleFromMarkdown(markdown); // Frontmatter.title > H1 > undefined
const tag      = extractFrontmatterField(markdown, "tags"); // 提取指定字段

const { hasFrontmatter, data } = parseFrontmatter(markdown); // 解析 frontmatter 边界
const parsed    = parseYamlFrontmatter(data);

METADATA_REGEX.test("---\ntitle: Hello\n---");        // true (frontmatter 边界匹配)

const wf = convertHeadingToFrontmatter(markdown, { format: "yaml", headingLevel: 1 });
const uf = upsertFrontmatterFields(markdown, { title: "New", tags: ["tech"] }, { createIfMissing: true });

2.6. 章节编号

import { addSectionNumbers, removeSectionNumbers } from "@cmtx/core";

const numbered = addSectionNumbers(markdown);   // 添加编号 (## 1. 标题)
const cleaned  = removeSectionNumbers(markdown); // 移除编号

2.7. 多正则操作

import { findAllMatches, replaceWithMultipleRegex } from "@cmtx/core";

const matches = findAllMatches(markdown, [
  { name: "images", pattern: /!\[([^\]]*)\]\(([^)]+)\)/g },
  { name: "links",  pattern: /\[([^\]]+)\]\(([^)]+)\)/g },
]);

const result = replaceWithMultipleRegex(markdown, [
  { pattern: /old/g, replacement: "new" },
  { pattern: /http:\/\//g, replacement: "https://" },
]);

2.8. 工具函数

import { isLocalImage, isLocalImageWithAbsPath, isLocalImageWithRelativePath,
         isWebImage, isWebSource, isLocalAbsolutePath, isPathInside,
         isValidUrl, normalizePath, replaceAltVariables, parseUrlSafe,
         CoreError, ErrorCode } from "@cmtx/core";

isLocalImage("../assets/examples/img.png");                            // true (相对路径或绝对路径)
isLocalImageWithAbsPath("/abs/img.png");              // true (仅绝对路径)
isLocalImageWithRelativePath("../assets/examples/img.png");            // true (仅相对路径)
isWebImage("https://example.com/img.png");            // true
isWebSource("http://cdn.example.com/img.png");        // true
isPathInside("/root", "/root/docs");                  // true
normalizePath("path\\to\\file");                      // path/to/file
parseUrlSafe("https://example.com/path?q=a#h");        // URL 安全解析(不抛异常)
replaceAltVariables("Page {{n}}", { n: "3" });        // Page 3

// 统一错误类型与错误码
throw new CoreError(ErrorCode.INVALID_INPUT, "Invalid image URL");

2.9. 日志与监控

import { getLogger, initLogger, dummyLogger, consoleLogger } from "@cmtx/core";

initLogger({ level: "info" });
const logger = getLogger("core");
logger.info("done");

3. 与其他包的关系

@cmtx/template  --调用-->  @cmtx/core (纯文本处理)
@cmtx/asset     --调用-->  @cmtx/core (纯文本处理)
@cmtx/rule-engine   --调用-->  @cmtx/core (纯文本处理)
  • @cmtx/core:纯文本处理(解析、替换、格式化、元数据)
  • @cmtx/asset/file:文件系统读写(filterImagesFromFile、replaceImagesInFile)
  • @cmtx/asset/delete:文件级删除(DeleteService)

4. 开发

pnpm build      # 构建
pnpm test       # 测试
pnpm test parser    # 特定模块测试
pnpm test filter
pnpm test replace
pnpm test metadata
pnpm test utils
pnpm lint       # 代码检查
pnpm run docs   # 生成 API 文档