Repository navigation
Expand file tree
/
Copy pathparse.js
More file actions
78 lines (61 loc) · 1.69 KB
/
Copy pathparse.js
File metadata and controls
78 lines (61 loc) · 1.69 KB
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
const DELIMITER_LENGTH = 3;
function getFrontMatter(text) {
const startDelimiter = text.slice(0, DELIMITER_LENGTH);
if (startDelimiter !== "---" && startDelimiter !== "+++") {
return;
}
const firstLineBreakIndex = text.indexOf("\n", DELIMITER_LENGTH);
if (firstLineBreakIndex === -1) {
return;
}
const explicitLanguage = text
.slice(DELIMITER_LENGTH, firstLineBreakIndex)
.trim();
let endDelimiterIndex = text.indexOf(
`\n${startDelimiter}`,
firstLineBreakIndex,
);
let language = explicitLanguage;
if (!language) {
language = startDelimiter === "+++" ? "toml" : "yaml";
}
if (
endDelimiterIndex === -1 &&
startDelimiter === "---" &&
language === "yaml"
) {
// In some markdown processors such as pandoc,
// "..." can be used as the end delimiter for YAML front-matter.
endDelimiterIndex = text.indexOf("\n...", firstLineBreakIndex);
}
if (endDelimiterIndex === -1) {
return;
}
const frontMatterEndIndex = endDelimiterIndex + 1 + DELIMITER_LENGTH;
const nextCharacter = text.charAt(frontMatterEndIndex + 1);
if (!/\s?/u.test(nextCharacter)) {
return;
}
const raw = text.slice(0, frontMatterEndIndex);
return {
type: "front-matter",
language,
explicitLanguage,
value: text.slice(firstLineBreakIndex + 1, endDelimiterIndex),
startDelimiter,
endDelimiter: raw.slice(-DELIMITER_LENGTH),
raw,
};
}
function parse(text) {
const frontMatter = getFrontMatter(text);
if (!frontMatter) {
return { content: text };
}
const { raw } = frontMatter;
return {
frontMatter,
content: raw.replaceAll(/[^\n]/gu, " ") + text.slice(raw.length),
};
}
export default parse;