Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

read-frontmatter.js 2.2 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...