forked from lobehub/lobe-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
38 lines (32 loc) · 1.06 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { readFileSync, writeFileSync } from 'node:fs';
import remarkGfm from 'remark-gfm';
import remarkParse from 'remark-parse';
import { unified } from 'unified';
import { visit } from 'unist-util-visit';
import { SPLIT } from './const';
export const updateDocs = (path: string, content: string) => {
const md = readFileSync(path, 'utf8');
const mds = md.split(SPLIT);
mds[1] = [' ', content, ' '].join('\n\n');
const result = mds.join(SPLIT);
writeFileSync(path, result, 'utf8');
};
export const convertMarkdownToMdast = async (md: string) => {
// @ts-ignore
return unified().use(remarkParse).use(remarkGfm).parse(md.trim());
};
export const getTitle = async (path: string) => {
const md = readFileSync(path, 'utf8');
const mdast: any = await convertMarkdownToMdast(md);
let title = '';
visit(mdast, 'heading', (node) => {
if (node.depth !== 1) return;
visit(node, 'text', (heading) => {
title += heading.value;
});
});
return title;
};
export const genMdLink = (title: string, url: string) => {
return `[${title}](${url})`;
};