-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
parse.js
50 lines (42 loc) · 1.22 KB
/
parse.js
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
"use strict";
const frontMatterRegex = new RegExp(
"^(?<startDelimiter>-{3}|\\+{3})" +
// trailing spaces after delimiters are allowed
"(?<language>[^\\n]*)" +
"\\n(?:|(?<value>.*?)\\n)" +
// In some markdown processors such as pandoc,
// "..." can be used as the end delimiter for YAML front-matter.
// Adding `\.{3}` make the regex matches `+++\n...`, but we'll exclude it later
"(?<endDelimiter>\\k<startDelimiter>|\\.{3})" +
"[^\\S\\n]*(?:\\n|$)",
"s"
);
function parse(text) {
const match = text.match(frontMatterRegex);
if (!match) {
return { content: text };
}
const { startDelimiter, language, value = "", endDelimiter } = match.groups;
let lang = language.trim() || "yaml";
if (startDelimiter === "+++") {
lang = "toml";
}
// Only allow yaml to parse with a different end delimiter
if (lang !== "yaml" && startDelimiter !== endDelimiter) {
return { content: text };
}
const [raw] = match;
const frontMatter = {
type: "front-matter",
lang,
value,
startDelimiter,
endDelimiter,
raw: raw.replace(/\n$/, ""),
};
return {
frontMatter,
content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length),
};
}
module.exports = parse;