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

0% Statements 0/36
0% Branches 0/19
0% Functions 0/6
0% Lines 0/35

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 67 68 69 70 71 72 73 74 75 76                                                                                                                                                       
/**
 * YAML Format Provider
 *
 * Handles parsing and serialization of YAML frontmatter in content files.
 */
import jsYaml from 'js-yaml';
export class YamlFormatProvider {
    defaultExt() {
        return 'yaml';
    }
    matchContentFirstLine(line) {
        return line.startsWith('---');
    }
    parse(str) {
        return jsYaml.load(str);
    }
    dump(obj) {
        return jsYaml.dump(obj);
    }
    dumpContent(obj) {
        let content = '';
        if (obj.mainContent) {
            content = obj.mainContent;
            delete obj.mainContent;
        }
        if (obj &&
            Object.keys(obj).length === 0 &&
            Object.getPrototypeOf(obj) === Object.prototype) {
            return `${content}`;
        }
        else {
            const header = this.dump(obj);
            // TODO WHY??? This causes https://github.com/quiqr/quiqr-desktop/issues/421
            // header = header.split(/\r?\n/).filter(line => line.trim() !== "").join("\n");
            return `---
${header}---
 
${content}`;
        }
    }
    parseFromMdFileString(str) {
        const data = str;
        const reg = /^[-]{3} *(\r?\n|\r|^)/gm;
        let yamlEnd = -1;
        let hasFrontMatter = true;
        for (let i = 0; i < 2; i++) {
            const execResult = reg.exec(data);
            if (execResult === null)
                break;
            if (i === 1)
                yamlEnd = execResult.index;
        }
        let yamlStr, md;
        if (yamlEnd === -1) {
            yamlStr = '';
            md = data;
        }
        else {
            yamlStr = data.substr(3, yamlEnd - 3);
            md = data.substr(yamlEnd + 3);
        }
        let parsedData = this.parse(yamlStr);
        if (parsedData === undefined) {
            parsedData = {};
            hasFrontMatter = false;
        }
        if (hasFrontMatter && /\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;
    }
}