-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloadMDX.ts
79 lines (64 loc) · 2.16 KB
/
loadMDX.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import fs from 'fs';
import matter from 'gray-matter';
import { bundleMDX } from 'mdx-bundler';
import path from 'path';
import rehypeAutolink from 'rehype-autolink-headings';
import rehypeSlug from 'rehype-slug';
import remarkGfm from 'remark-gfm';
import remarkPrism from 'remark-prism';
import glob from 'tiny-glob';
import remarkHighlightSyntax from './hightlight';
import { autoLinkHeadingsOptions } from './rehypeAutolinkPlugin';
export const RootPath = process.cwd();
export const PostPath = path.join(RootPath, 'posts');
export const ExercisesPath = path.join(RootPath, 'exercises');
export async function loadMDX(source: string) {
const bundle = await bundleMDX({
source,
xdmOptions: (options) => {
options.remarkPlugins = [
...(options?.remarkPlugins ?? []),
remarkGfm,
remarkPrism,
remarkHighlightSyntax
];
options.rehypePlugins = [
...(options?.rehypePlugins ?? []),
rehypeSlug,
[rehypeAutolink, autoLinkHeadingsOptions]
];
return options;
}
});
return bundle;
}
/**
* Get meta data of all posts
*/
export const getAllDocsMeta = async (dir: string) => {
const allDocsMeta = await glob(`${dir}/**/*.mdx`);
return allDocsMeta
.map((postPath): PostMeta => {
const post = fs.readFileSync(path.join(RootPath, postPath), 'utf-8');
const slug = path.basename(postPath).replace('.mdx', '');
const meta = matter(post).data;
return { ...meta, slug } as PostMeta;
})
.filter((meta) => meta.published)
.sort((a, b) => Number(new Date(b.date)) - Number(new Date(a.date)));
};
const TWEET_RE = /<StaticTweet\sid="[0-9]+"\s\/>/g;
/**
* Get a single post content by slug
*/
export const getDocs = async (slug: string, dir: string) => {
const source = fs.readFileSync(path.join(dir, `${slug}.mdx`), 'utf-8');
const { code, frontmatter, matter } = await loadMDX(source);
const tweetMatch = matter.content.match(TWEET_RE);
const tweetIDs = tweetMatch?.map((mdxTweet) => {
const id = mdxTweet.match(/[0-9]+/g)![0];
return id;
});
const meta = { ...frontmatter, slug } as PostMeta;
return { meta, code, tweetIDs: tweetIDs ?? [] };
};