"use strict"; const fs = require("fs"); const path = require("path"); const matter = require("gray-matter"); const markdown = require("../modules/markdown.js"); const { indentForTemplate, postIndentLevel } = require("../responders.js"); const grayMatterOptions = { lang: "toml", delims: "+++" }; function* lowercaseKeys(iterator) { for (let [k, v] of iterator) { yield [String(k).toLowerCase(), v]; } } function canonicaliseMetadata(meta) { if (meta.data) { meta.data = new Map(lowercaseKeys(Object.entries(meta.data))); } else { meta.data = new Map(); } return meta; } function getTitle(file) { return path.basename(file.path, path.extname(file.path)); } function get(getURL, filename) { const fileMatter = matter.read(filename, grayMatterOptions); fileMatter.basename = getTitle(fileMatter); delete fileMatter.orig; fileMatter.body = indentForTemplate( markdown(fileMatter.content), postIndentLevel ); fileMatter.url = getURL(fileMatter.basename); return canonicaliseMetadata(fileMatter); } function getFolder(folder, getURL) { return new Map( fs .readdirSync(folder) .map(f => path.resolve(folder, f)) .map(get.bind(this, getURL)) .map(f => [getTitle(f), f]) ); } function taxonomise(taxonomies, posts) { const taxons = new Map(Object.keys(taxonomies).map(t => [t, new Map()])); for (let [, post] of posts) { for (let [singularName, pluralName] of Object.entries(taxonomies)) { if (post.data.has(pluralName)) { for (let term of post.data.get(pluralName)) { const current = taxons.get(singularName).get(term); taxons .get(singularName) .set(term, current ? current.concat(post) : [post]); } } } } return taxons; } module.exports = function(config, getURL) { const posts = getFolder(config.folder, getURL); const taxonomies = taxonomise(config.taxonomies, posts); return { posts, taxonomies, get }; };