Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support serializing all VFile-compatible values #311

Merged
merged 2 commits into from
Nov 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .jest/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import React from 'react'
import { MDXRemote, MDXRemoteProps } from '../src/index'
import { serialize } from '../src/serialize'
import { SerializeOptions } from '../src/types'
import { VFileCompatible } from 'vfile'

export async function renderStatic(
mdx: string,
mdx: VFileCompatible,
{
components,
scope,
Expand Down
11 changes: 11 additions & 0 deletions __tests__/serialize.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as React from 'react'
import ReactDOMServer from 'react-dom/server'
import { paragraphCustomAlerts } from '@hashicorp/remark-plugins'
import * as MDX from '@mdx-js/react'
import { VFile } from 'vfile'

import { MDXRemote } from '../src/index'
import { serialize } from '../src/serialize'
Expand Down Expand Up @@ -163,4 +164,14 @@ hello: world
`)
}
})

test('supports VFile', async () => {
const result = await renderStatic(new VFile('foo **bar**'))
expect(result).toMatchInlineSnapshot(`"<p>foo <strong>bar</strong></p>"`)
})

test('supports Buffer', async () => {
const result = await renderStatic(Buffer.from('foo **bar**'))
expect(result).toMatchInlineSnapshot(`"<p>foo <strong>bar</strong></p>"`)
})
})
7 changes: 3 additions & 4 deletions src/serialize.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { compile, CompileOptions } from '@mdx-js/mdx'
import { VFile } from 'vfile'
import { VFile, VFileCompatible } from 'vfile'
import { matter } from 'vfile-matter'

import { createFormattedMDXError } from './format-mdx-error'
Expand Down Expand Up @@ -32,15 +32,14 @@ function getCompileOptions(
* Parses and compiles the provided MDX string. Returns a result which can be passed into <MDXRemote /> to be rendered.
*/
export async function serialize(
/** Raw MDX contents as a string. */
source: string,
source: VFileCompatible,
{
scope = {},
mdxOptions = {},
parseFrontmatter = false,
}: SerializeOptions = {}
): Promise<MDXRemoteSerializeResult> {
const vfile = new VFile({ value: source })
const vfile = new VFile(source)

// makes frontmatter available via vfile.data.matter
if (parseFrontmatter) {
Expand Down