2023-12-02 13:48:26 +00:00
|
|
|
import DOMPurify from 'isomorphic-dompurify';
|
2021-11-27 14:13:00 +00:00
|
|
|
import { marked } from 'marked';
|
2022-09-25 17:04:47 +00:00
|
|
|
import { parse as YAMLParse } from 'yaml';
|
2021-10-19 16:54:01 +00:00
|
|
|
|
|
|
|
const tokens = ['---', '---'];
|
|
|
|
const regexHeader = new RegExp('^' + tokens[0] + '([\\s|\\S]*?)' + tokens[1]);
|
2021-11-27 14:13:00 +00:00
|
|
|
const regexContent = new RegExp('^ *?\\' + tokens[0] + '[^]*?' + tokens[1] + '*');
|
2021-10-19 16:54:01 +00:00
|
|
|
|
|
|
|
export function getHeader<T = any>(data: string): T {
|
|
|
|
const header = getRawHeader(data);
|
2022-09-25 17:04:47 +00:00
|
|
|
return YAMLParse(header) as T;
|
2021-10-19 16:54:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function getRawHeader(data: string): string {
|
|
|
|
const header = regexHeader.exec(data);
|
|
|
|
if (!header) {
|
2022-09-25 17:04:47 +00:00
|
|
|
throw new Error("Can't get the header");
|
2021-10-19 16:54:01 +00:00
|
|
|
}
|
|
|
|
return header[1];
|
|
|
|
}
|
|
|
|
|
2022-09-25 17:04:47 +00:00
|
|
|
export function getContent(data: string): string {
|
2021-10-19 16:54:01 +00:00
|
|
|
const content = data.replace(regexContent, '').replace(/<!--(.*?)-->/gm, '');
|
|
|
|
if (!content) {
|
|
|
|
throw new Error("Can't get the content");
|
|
|
|
}
|
2023-12-02 13:48:26 +00:00
|
|
|
return DOMPurify.sanitize(marked(content) as string);
|
2021-10-19 16:54:01 +00:00
|
|
|
}
|