Skip to content

fix: treat a string passed to stringify as opaque content#190

Open
spokodev wants to merge 1 commit into
jonschlinkert:masterfrom
spokodev:fix-stringify-string-content
Open

fix: treat a string passed to stringify as opaque content#190
spokodev wants to merge 1 commit into
jonschlinkert:masterfrom
spokodev:fix-stringify-string-content

Conversation

@spokodev

Copy link
Copy Markdown

Problem

matter.stringify(file, data) documents the string form of file as "The content string to append to stringified front-matter" (and "appending that to the given string"). But when file is a string it runs matter(file), which parses the string as a document. If the body itself begins with the front-matter delimiter, that leading block is pulled out of the body and merged into the front matter — corrupting both content and data:

const matter = require('gray-matter');

const body = '---\nnot: real\n---\nHello world'; // intended as opaque content
const out  = matter.stringify(body, { title: 'Home' });
const back = matter(out);

back.data;    // { not: 'real', title: 'Home' }   <- body key leaked into front matter
back.content; // 'Hello world\n'                  <- '---\nnot: real\n---' lost from the body

A plain string (no leading delimiter) round-trips fine, so this is the documented happy path silently losing data, not misuse.

Fix

Wrap the string as { content: file, data: {} } instead of re-parsing it, so the body is appended verbatim under the new front matter. The empty data keeps stringify's existing no-data behaviour (a plain string with no data is returned unchanged). Object inputs and plain strings are unaffected.

Test

Added an assertion that a content string starting with a delimiter is appended (not parsed) and round-trips with clean data. It fails before the change and passes after; the full suite is green (76 passing).

`matter.stringify(file, data)` documents the string form of `file` as
"the content string to append to stringified front-matter". But for a
string it ran `matter(file)`, which parses the string as a document. When
the body itself begins with the front-matter delimiter, that leading
block is extracted out of the body and merged into the front matter, so
both the content and the data come back wrong:

  matter.stringify('---\nnot: real\n---\nHello world', { title: 'Home' })
  // body's "not: real" leaks into data, and "---\nnot: real\n---" is
  // stripped from the content on the next parse

Wrap the string as `{ content: file, data: {} }` instead of re-parsing it,
so the body is appended verbatim. Plain strings and object inputs are
unaffected.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant