'use strict';
const fs = require('fs');
const sections = require('section-matter');
const defaults = require('./lib/defaults');
const stringify = require('./lib/stringify');
const excerpt = require('./lib/excerpt');
const engines = require('./lib/engines');
const toFile = require('./lib/to-file');
const parse = require('./lib/parse');
const utils = require('./lib/utils');
function matter(input, options) {
if (input === '') {
return { data: {}, content: input, excerpt: '', orig: input };
}
let file = toFile(input);
const cached = matter.cache[file.content];
if (!options) {
if (cached) {
file = Object.assign({}, cached);
file.orig = cached.orig;
return file;
}
matter.cache[file.content] = file;
}
return parseMatter(file, options);
}
function parseMatter(file, options) {
const opts = defaults(options);
const open = opts.delimiters[0];
const close = '\n' + opts.delimiters[1];
let str = file.content;
if (opts.language) {
file.language = opts.language;
}
const openLen = open.length;
if (!utils.startsWith(str, open, openLen)) {
excerpt(file, opts);
return file;
}
if (str.charAt(openLen) === open.slice(-1)) {
return file;
}
str = str.slice(openLen);
const len = str.length;
const language = matter.language(str, opts);
if (language.name) {
file.language = language.name;
str = str.slice(language.raw.length);
}
let closeIndex = str.indexOf(close);
if (closeIndex === -1) {
closeIndex = len;
}
file.matter = str.slice(0, closeIndex);
const block = file.matter.replace(/^\s*#[^\n]+/gm, '').trim();
if (block === '') {
file.isEmpty = true;
file.empty = file.content;
file.data = {};
} else {
file.data = parse(file.language, file.matter, opts);
}
if (closeIndex === len) {
file.content = '';
} else {
file.content = str.slice(closeIndex + close.length);
if (file.content[0] === '\r') {
file.content = file.content.slice(1);
}
if (file.content[0] === '\n') {
file.content = file.content.slice(1);
}
}
excerpt(file, opts);
if (opts.sections === true || typeof opts.section === 'function') {
sections(file, opts.section);
}
return file;
}
matter.engines = engines;
matter.stringify = function(file, data, options) {
if (typeof file === 'string') file = matter(file, options);
return stringify(file, data, options);
};
matter.read = function(filepath, options) {
const str = fs.readFileSync(filepath, 'utf8');
const file = matter(str, options);
file.path = filepath;
return file;
};
matter.test = function(str, options) {
return utils.startsWith(str, defaults(options).delimiters[0]);
};
matter.language = function(str, options) {
const opts = defaults(options);
const open = opts.delimiters[0];
if (matter.test(str)) {
str = str.slice(open.length);
}
const language = str.slice(0, str.search(/\r?\n/));
return {
raw: language,
name: language ? language.trim() : ''
};
};
matter.cache = {};
matter.clearCache = function() {
matter.cache = {};
};
module.exports = matter;