All files / backend/dist/utils/format-providers toml-format-provider.js

0% Statements 0/32
0% Branches 0/12
0% Functions 0/6
0% Lines 0/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                   
/**
 * TOML Format Provider
 *
 * Handles parsing and serialization of TOML frontmatter in content files.
 */
import tomlify from 'tomlify-j0.4';
import toml from 'toml';
export class TomlFormatProvider {
    defaultExt() {
        return 'toml';
    }
    matchContentFirstLine(line) {
        return line.startsWith('+++');
    }
    parse(str) {
        return toml.parse(str);
    }
    dump(obj) {
        return tomlify.toToml(obj, { space: 2 });
    }
    dumpContent(obj) {
        let content = '';
        if (obj.mainContent) {
            content = obj.mainContent;
            delete obj.mainContent;
        }
        const header = this.dump(obj);
        return `+++
${header}+++
 
${content}`;
    }
    parseFromMdFileString(str) {
        const data = str;
        const reg = /^[+]{3} *(\r?\n|\r|^)/gm;
        let tomlEnd = -1;
        for (let i = 0; i < 2; i++) {
            const execResult = reg.exec(data);
            if (execResult === null)
                break;
            if (i === 1)
                tomlEnd = execResult.index;
        }
        let tomlStr, md;
        if (tomlEnd === -1) {
            tomlStr = '';
            md = data;
        }
        else {
            tomlStr = data.substr(3, tomlEnd - 3);
            md = data.substr(tomlEnd + 3);
        }
        const parsedData = this.parse(tomlStr);
        if (parsedData === undefined) {
            return {};
        }
        if (/\S/.test(md)) {
            // if have non whitespaces
            // remove the two first line breaks
            md = md.replace(/(\r?\n|\r)/, '').replace(/(\r?\n|\r)/, '');
            parsedData.mainContent = md;
        }
        return parsedData;
    }
}