import * as plugins from './smartmarkdown.plugins.js'; export type TFrontmatterData = Record; type TYamlNode = plugins.RootContent & { type: 'yaml'; value: string; }; const isYamlNode = (nodeArg: plugins.RootContent): nodeArg is TYamlNode => { return nodeArg.type === 'yaml' && 'value' in nodeArg && typeof nodeArg.value === 'string'; }; export class MdParsedResult { public static async createFromMarkdownString(mdStringArg: string): Promise { const mdParsedResult = new MdParsedResult(); await mdParsedResult.updateFromMarkdownString(mdStringArg); return mdParsedResult; } public originalString = ''; public title = ''; public html = ''; public frontmatterData: TFrontmatterData = {}; public async updateFromMarkdownString(mdStringArg: string): Promise { this.originalString = mdStringArg; let yamlString: string | undefined; const result = await plugins.unified() .use(plugins.remarkParse) .use(plugins.remarkGfm) .use(plugins.remarkFrontmatter, ['yaml', 'toml']) .use(plugins.remarkStringify) .use(plugins.remarkHtml) .use((): plugins.Transformer => (tree) => { const yamlChild = tree.children.find(isYamlNode); if (yamlChild) { yamlString = yamlChild.value; } }) .process(mdStringArg); this.html = result.toString(); if (yamlString) { this.frontmatterData = await plugins.smartyaml.yamlStringToObject(yamlString); } else { this.frontmatterData = {}; } } }