zod-matter is a tiny wrapper for gray-matter and Zod to parse and validate front matter with static type inference.
gray-matter is a great package to parse front matter but provides no validation or type safety. This package exposes an API adding a schema
parameter to validate front matter data using Zod. This can be particularly useful to parse & validate front matter for user generated Markdown or MDX files for example.
Install zod-matter
and its peer dependencies with your favorite package manager, e.g.:
pnpm add zod-matter zod gray-matter
Extracts and parses front matter according to the given Zod schema.
import { parse } from 'zod-matter'
import { z } from 'zod'
const { data } = parse('---\nauthor: HiDeoo\n---\n# Hello world!', z.object({ author: z.string() }))
// ^? { author: string }
input
: The string, buffer or object with acontent
property to parse.schema
: The Zod schema to use to parse the front matter.options
: Optionally, the gray-matter options to use.
A file object with the same properties of a gray-matter file object but with a data
property of the type inferred from the given Zod schema.
If the front matter data is invalid, a ZodError
will be thrown.
Extracts and parses front matter from a file according to the given Zod schema.
import { read } from 'zod-matter'
import { z } from 'zod'
const { data } = read('./data/post.md', z.object({ author: z.string(), date: z.date() }))
// ^? { author: string; date: Date }
path
: The path to the file to read and parse.schema
: The Zod schema to use to parse the front matter.options
: Optionally, the gray-matter options to use.
A file object with the same properties of a gray-matter file object but with a data
property of the type inferred from the given Zod schema.
If the front matter data is invalid, a ZodError
will be thrown.
Stringify an object to YAML or a specified language, and append it to the given string.
import { stringify } from 'zod-matter'
import { z } from 'zod'
const content = stringify('# Hello world!', { author: 'HiDeoo' })
// ^? ---
// author: HiDeoo
// ---
// # Hello world!
This function is re-exported for convenience from gray-matter with the same signature.
Checks if the given string contains a front matter.
import { test } from 'zod-matter'
import { z } from 'zod'
const containsFrontMatter = test('---\nauthor: HiDeoo\n---\n# Hello world!')
// ^? true
This function is re-exported for convenience from gray-matter with the same signature.
Licensed under the MIT License, Copyright © HiDeoo.
See LICENSE for more information.