|
| 1 | +const matter = require('gray-matter') |
| 2 | +const revalidator = require('revalidator') |
| 3 | +const { difference, intersection } = require('lodash') |
| 4 | + |
| 5 | +function readFrontmatter (markdown, opts = { validateKeyNames: false, validateKeyOrder: false }) { |
| 6 | + const schema = opts.schema || { properties: {} } |
| 7 | + const filepath = opts.filepath || null |
| 8 | + |
| 9 | + let content, data |
| 10 | + let errors = [] |
| 11 | + |
| 12 | + try { |
| 13 | + ({ content, data } = matter(markdown)) |
| 14 | + } catch (e) { |
| 15 | + const defaultReason = 'invalid frontmatter entry' |
| 16 | + |
| 17 | + const reason = e.reason |
| 18 | + // make this common error message a little easier to understand |
| 19 | + ? e.reason.startsWith('can not read a block mapping entry;') ? defaultReason : e.reason |
| 20 | + : defaultReason |
| 21 | + |
| 22 | + const error = { |
| 23 | + reason, |
| 24 | + message: 'YML parsing error!' |
| 25 | + } |
| 26 | + |
| 27 | + if (filepath) error.filepath = filepath |
| 28 | + errors.push(error) |
| 29 | + return { errors } |
| 30 | + } |
| 31 | + |
| 32 | + const allowedKeys = Object.keys(schema.properties) |
| 33 | + const existingKeys = Object.keys(data) |
| 34 | + const expectedKeys = intersection(allowedKeys, existingKeys) |
| 35 | + |
| 36 | + ;({ errors } = revalidator.validate(data, schema)) |
| 37 | + |
| 38 | + // add filepath property to each error object |
| 39 | + if (errors.length && filepath) { |
| 40 | + errors = errors.map(error => Object.assign(error, { filepath })) |
| 41 | + } |
| 42 | + |
| 43 | + // validate key names |
| 44 | + if (opts.validateKeyNames) { |
| 45 | + const invalidKeys = difference(existingKeys, allowedKeys) |
| 46 | + invalidKeys.forEach(key => { |
| 47 | + const error = { |
| 48 | + property: key, |
| 49 | + message: `not allowed. Allowed properties are: ${allowedKeys.join(', ')}` |
| 50 | + } |
| 51 | + if (filepath) error.filepath = filepath |
| 52 | + errors.push(error) |
| 53 | + }) |
| 54 | + } |
| 55 | + |
| 56 | + // validate key order |
| 57 | + if (opts.validateKeyOrder && existingKeys.join('') !== expectedKeys.join('')) { |
| 58 | + const error = { |
| 59 | + property: 'keys', |
| 60 | + message: `keys must be in order. Current: ${existingKeys.join(',')}; Expected: ${expectedKeys.join(',')}` |
| 61 | + } |
| 62 | + if (filepath) error.filepath = filepath |
| 63 | + errors.push(error) |
| 64 | + } |
| 65 | + |
| 66 | + return { content, data, errors } |
| 67 | +} |
| 68 | + |
| 69 | +// Expose gray-matter's underlying stringify method for joining a parsed |
| 70 | +// frontmatter object and a markdown string back into a unified string |
| 71 | +// |
| 72 | +// stringify('some string', {some: 'frontmatter'}) |
| 73 | +readFrontmatter.stringify = matter.stringify |
| 74 | + |
| 75 | +module.exports = readFrontmatter |
0 commit comments